chromium-bidi 0.5.19 → 0.5.21

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.
Files changed (63) hide show
  1. package/.browser +1 -1
  2. package/README.md +3 -3
  3. package/lib/THIRD_PARTY_NOTICES +1 -1
  4. package/lib/cjs/bidiMapper/CommandProcessor.js +1 -1
  5. package/lib/cjs/bidiMapper/CommandProcessor.js.map +1 -1
  6. package/lib/cjs/bidiMapper/modules/cdp/CdpTarget.d.ts +1 -1
  7. package/lib/cjs/bidiMapper/modules/cdp/CdpTarget.js +32 -3
  8. package/lib/cjs/bidiMapper/modules/cdp/CdpTarget.js.map +1 -1
  9. package/lib/cjs/bidiMapper/modules/cdp/CdpTargetManager.js +14 -2
  10. package/lib/cjs/bidiMapper/modules/cdp/CdpTargetManager.js.map +1 -1
  11. package/lib/cjs/bidiMapper/modules/context/BrowsingContextImpl.d.ts +1 -1
  12. package/lib/cjs/bidiMapper/modules/context/BrowsingContextImpl.js +65 -27
  13. package/lib/cjs/bidiMapper/modules/context/BrowsingContextImpl.js.map +1 -1
  14. package/lib/cjs/bidiMapper/modules/context/BrowsingContextProcessor.d.ts +2 -1
  15. package/lib/cjs/bidiMapper/modules/context/BrowsingContextProcessor.js +20 -1
  16. package/lib/cjs/bidiMapper/modules/context/BrowsingContextProcessor.js.map +1 -1
  17. package/lib/cjs/bidiMapper/modules/input/ActionDispatcher.js +26 -9
  18. package/lib/cjs/bidiMapper/modules/input/ActionDispatcher.js.map +1 -1
  19. package/lib/cjs/bidiMapper/modules/input/InputProcessor.js +16 -10
  20. package/lib/cjs/bidiMapper/modules/input/InputProcessor.js.map +1 -1
  21. package/lib/cjs/bidiMapper/modules/input/InputSource.d.ts +5 -5
  22. package/lib/cjs/bidiMapper/modules/input/keyUtils.d.ts +12 -0
  23. package/lib/cjs/bidiMapper/modules/input/keyUtils.js +23 -1
  24. package/lib/cjs/bidiMapper/modules/input/keyUtils.js.map +1 -1
  25. package/lib/cjs/bidiMapper/modules/log/LogManager.js.map +1 -1
  26. package/lib/cjs/bidiMapper/modules/network/NetworkProcessor.d.ts +6 -0
  27. package/lib/cjs/bidiMapper/modules/network/NetworkProcessor.js +78 -20
  28. package/lib/cjs/bidiMapper/modules/network/NetworkProcessor.js.map +1 -1
  29. package/lib/cjs/bidiMapper/modules/network/NetworkRequest.d.ts +1 -1
  30. package/lib/cjs/bidiMapper/modules/network/NetworkRequest.js +34 -9
  31. package/lib/cjs/bidiMapper/modules/network/NetworkRequest.js.map +1 -1
  32. package/lib/cjs/bidiMapper/modules/network/NetworkStorage.js.map +1 -1
  33. package/lib/cjs/bidiMapper/modules/network/NetworkUtils.d.ts +3 -1
  34. package/lib/cjs/bidiMapper/modules/network/NetworkUtils.js +21 -4
  35. package/lib/cjs/bidiMapper/modules/network/NetworkUtils.js.map +1 -1
  36. package/lib/cjs/bidiMapper/modules/session/EventManager.d.ts +8 -0
  37. package/lib/cjs/bidiMapper/modules/session/EventManager.js +21 -1
  38. package/lib/cjs/bidiMapper/modules/session/EventManager.js.map +1 -1
  39. package/lib/cjs/bidiMapper/modules/session/SubscriptionManager.d.ts +13 -2
  40. package/lib/cjs/bidiMapper/modules/session/SubscriptionManager.js +35 -12
  41. package/lib/cjs/bidiMapper/modules/session/SubscriptionManager.js.map +1 -1
  42. package/lib/cjs/bidiMapper/modules/storage/StorageProcessor.js +2 -2
  43. package/lib/cjs/bidiMapper/modules/storage/StorageProcessor.js.map +1 -1
  44. package/lib/cjs/bidiServer/MapperCdpConnection.js +13 -3
  45. package/lib/cjs/bidiServer/MapperCdpConnection.js.map +1 -1
  46. package/lib/cjs/bidiTab/bidiTab.d.ts +1 -0
  47. package/lib/cjs/bidiTab/bidiTab.js.map +1 -1
  48. package/lib/cjs/bidiTab/mapperTabPage.js +2 -0
  49. package/lib/cjs/bidiTab/mapperTabPage.js.map +1 -1
  50. package/lib/cjs/protocol-parser/generated/webdriver-bidi.d.ts +10996 -32218
  51. package/lib/cjs/protocol-parser/protocol-parser.d.ts +9 -9
  52. package/lib/cjs/utils/Deferred.d.ts +1 -0
  53. package/lib/cjs/utils/Deferred.js +8 -0
  54. package/lib/cjs/utils/Deferred.js.map +1 -1
  55. package/lib/cjs/utils/DistinctValues.d.ts +14 -0
  56. package/lib/cjs/utils/DistinctValues.js +59 -0
  57. package/lib/cjs/utils/DistinctValues.js.map +1 -0
  58. package/lib/cjs/utils/GraphemeTools.d.ts +9 -0
  59. package/lib/cjs/utils/GraphemeTools.js +39 -0
  60. package/lib/cjs/utils/GraphemeTools.js.map +1 -0
  61. package/lib/iife/mapperTab.js +787 -194
  62. package/lib/iife/mapperTab.js.map +1 -1
  63. package/package.json +23 -23
@@ -169,9 +169,9 @@ var mapperTab = (function () {
169
169
  */
170
170
  Object.defineProperty(ProcessingQueue$1, "__esModule", { value: true });
171
171
  ProcessingQueue$1.ProcessingQueue = void 0;
172
- const log_js_1$d = log$1;
172
+ const log_js_1$e = log$1;
173
173
  class ProcessingQueue {
174
- static LOGGER_PREFIX = `${log_js_1$d.LogType.debug}:queue`;
174
+ static LOGGER_PREFIX = `${log_js_1$e.LogType.debug}:queue`;
175
175
  #logger;
176
176
  #processor;
177
177
  #queue = [];
@@ -201,13 +201,13 @@ var mapperTab = (function () {
201
201
  await entryPromise
202
202
  .then((entry) => {
203
203
  if (entry.kind === 'error') {
204
- this.#logger?.(log_js_1$d.LogType.debugError, 'Event threw before sending:', entry.error.message, entry.error.stack);
204
+ this.#logger?.(log_js_1$e.LogType.debugError, 'Event threw before sending:', entry.error.message, entry.error.stack);
205
205
  return;
206
206
  }
207
207
  return this.#processor(entry.value);
208
208
  })
209
209
  .catch((error) => {
210
- this.#logger?.(log_js_1$d.LogType.debugError, 'Event was not processed:', error?.message);
210
+ this.#logger?.(log_js_1$e.LogType.debugError, 'Event was not processed:', error?.message);
211
211
  });
212
212
  }
213
213
  this.#isProcessing = false;
@@ -887,9 +887,12 @@ var mapperTab = (function () {
887
887
  class BrowsingContextProcessor {
888
888
  #browserCdpClient;
889
889
  #browsingContextStorage;
890
- constructor(browserCdpClient, browsingContextStorage) {
890
+ #eventManager;
891
+ constructor(browserCdpClient, browsingContextStorage, eventManager) {
891
892
  this.#browserCdpClient = browserCdpClient;
892
893
  this.#browsingContextStorage = browsingContextStorage;
894
+ this.#eventManager = eventManager;
895
+ this.#eventManager.addSubscribeHook(protocol_js_1$l.ChromiumBidi.BrowsingContext.EventNames.ContextCreated, this.#onContextCreatedSubscribeHook.bind(this));
893
896
  }
894
897
  getTree(params) {
895
898
  const resultContexts = params.root === undefined
@@ -935,6 +938,7 @@ var mapperTab = (function () {
935
938
  url: 'about:blank',
936
939
  newWindow,
937
940
  browserContextId: userContext === 'default' ? undefined : userContext,
941
+ background: params.background === true,
938
942
  });
939
943
  }
940
944
  catch (err) {
@@ -1054,6 +1058,21 @@ var mapperTab = (function () {
1054
1058
  const context = this.#browsingContextStorage.getContext(params.context);
1055
1059
  return await context.locateNodes(params);
1056
1060
  }
1061
+ #onContextCreatedSubscribeHook(contextId) {
1062
+ const context = this.#browsingContextStorage.getContext(contextId);
1063
+ const contextsToReport = [
1064
+ context,
1065
+ ...this.#browsingContextStorage.getContext(contextId).allChildren,
1066
+ ];
1067
+ contextsToReport.forEach((context) => {
1068
+ this.#eventManager.registerEvent({
1069
+ type: 'event',
1070
+ method: protocol_js_1$l.ChromiumBidi.BrowsingContext.EventNames.ContextCreated,
1071
+ params: context.serializeToBidiValue(),
1072
+ }, context.id);
1073
+ });
1074
+ return Promise.resolve();
1075
+ }
1057
1076
  }
1058
1077
  BrowsingContextProcessor$1.BrowsingContextProcessor = BrowsingContextProcessor;
1059
1078
 
@@ -1088,6 +1107,46 @@ var mapperTab = (function () {
1088
1107
 
1089
1108
  var ActionDispatcher$1 = {};
1090
1109
 
1110
+ var GraphemeTools = {};
1111
+
1112
+ /*
1113
+ * Copyright 2024 Google LLC.
1114
+ * Copyright (c) Microsoft Corporation.
1115
+ *
1116
+ * Licensed under the Apache License, Version 2.0 (the "License");
1117
+ * you may not use this file except in compliance with the License.
1118
+ * You may obtain a copy of the License at
1119
+ *
1120
+ * http://www.apache.org/licenses/LICENSE-2.0
1121
+ *
1122
+ * Unless required by applicable law or agreed to in writing, software
1123
+ * distributed under the License is distributed on an "AS IS" BASIS,
1124
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1125
+ * See the License for the specific language governing permissions and
1126
+ * limitations under the License.
1127
+ */
1128
+ Object.defineProperty(GraphemeTools, "__esModule", { value: true });
1129
+ GraphemeTools.isSingleGrapheme = GraphemeTools.isSingleComplexGrapheme = void 0;
1130
+ /**
1131
+ * Check if the given string is a single complex grapheme. A complex grapheme is one that
1132
+ * is made up of multiple characters.
1133
+ */
1134
+ function isSingleComplexGrapheme(value) {
1135
+ return isSingleGrapheme(value) && value.length > 1;
1136
+ }
1137
+ GraphemeTools.isSingleComplexGrapheme = isSingleComplexGrapheme;
1138
+ /**
1139
+ * Check if the given string is a single grapheme.
1140
+ */
1141
+ function isSingleGrapheme(value) {
1142
+ // Theoretically there can be some strings considered a grapheme in some locales, like
1143
+ // slovak "ch" digraph. Use english locale for consistency.
1144
+ // https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
1145
+ const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });
1146
+ return [...segmenter.segment(value)].length === 1;
1147
+ }
1148
+ GraphemeTools.isSingleGrapheme = isSingleGrapheme;
1149
+
1091
1150
  var InputSource = {};
1092
1151
 
1093
1152
  /**
@@ -1257,6 +1316,10 @@ var mapperTab = (function () {
1257
1316
  */
1258
1317
  Object.defineProperty(keyUtils, "__esModule", { value: true });
1259
1318
  keyUtils.getKeyLocation = keyUtils.getKeyCode = keyUtils.getNormalizedKey = void 0;
1319
+ /**
1320
+ * Returns the normalized key value for a given key according to the table:
1321
+ * https://w3c.github.io/webdriver/#dfn-normalized-key-value
1322
+ */
1260
1323
  function getNormalizedKey(value) {
1261
1324
  switch (value) {
1262
1325
  case '\uE000':
@@ -1271,8 +1334,9 @@ var mapperTab = (function () {
1271
1334
  return 'Tab';
1272
1335
  case '\uE005':
1273
1336
  return 'Clear';
1337
+ // Specification declares the '\uE006' to be `Return`, but it is not supported by
1338
+ // Chrome, so fall back to `Enter`, which aligns with WPT.
1274
1339
  case '\uE006':
1275
- return 'Return';
1276
1340
  case '\uE007':
1277
1341
  return 'Enter';
1278
1342
  case '\uE008':
@@ -1404,6 +1468,10 @@ var mapperTab = (function () {
1404
1468
  }
1405
1469
  }
1406
1470
  keyUtils.getNormalizedKey = getNormalizedKey;
1471
+ /**
1472
+ * Returns the key code for a given key according to the table:
1473
+ * https://w3c.github.io/webdriver/#dfn-shifted-character
1474
+ */
1407
1475
  function getKeyCode(key) {
1408
1476
  switch (key) {
1409
1477
  case '`':
@@ -1456,6 +1524,10 @@ var mapperTab = (function () {
1456
1524
  case '=':
1457
1525
  case '+':
1458
1526
  return 'Equal';
1527
+ // The spec declares the '<' to be `IntlBackslash` as well, but it is already covered
1528
+ // in the `Comma` above.
1529
+ case '>':
1530
+ return 'IntlBackslash';
1459
1531
  case 'a':
1460
1532
  case 'A':
1461
1533
  return 'KeyA';
@@ -1558,6 +1630,8 @@ var mapperTab = (function () {
1558
1630
  return 'ControlRight';
1559
1631
  case '\uE006':
1560
1632
  return 'Enter';
1633
+ case '\uE00B':
1634
+ return 'Pause';
1561
1635
  case '\uE03D':
1562
1636
  return 'MetaLeft';
1563
1637
  case '\uE053':
@@ -1619,6 +1693,8 @@ var mapperTab = (function () {
1619
1693
  return 'F11';
1620
1694
  case '\uE03C':
1621
1695
  return 'F12';
1696
+ case '\uE019':
1697
+ return 'NumpadEqual';
1622
1698
  case '\uE01A':
1623
1699
  case '\uE05C':
1624
1700
  return 'Numpad0';
@@ -1668,6 +1744,10 @@ var mapperTab = (function () {
1668
1744
  }
1669
1745
  }
1670
1746
  keyUtils.getKeyCode = getKeyCode;
1747
+ /**
1748
+ * Returns the location of the key according to the table:
1749
+ * https://w3c.github.io/webdriver/#dfn-key-location
1750
+ */
1671
1751
  function getKeyLocation(key) {
1672
1752
  switch (key) {
1673
1753
  case '\uE007':
@@ -1676,6 +1756,7 @@ var mapperTab = (function () {
1676
1756
  case '\uE00A':
1677
1757
  case '\uE03D':
1678
1758
  return 1;
1759
+ case '\uE019':
1679
1760
  case '\uE01A':
1680
1761
  case '\uE01B':
1681
1762
  case '\uE01C':
@@ -2009,6 +2090,7 @@ var mapperTab = (function () {
2009
2090
  ActionDispatcher$1.ActionDispatcher = void 0;
2010
2091
  const protocol_js_1$k = protocol;
2011
2092
  const assert_js_1$6 = assert$1;
2093
+ const GraphemeTools_1 = GraphemeTools;
2012
2094
  const InputSource_js_1$1 = InputSource;
2013
2095
  const keyUtils_js_1 = keyUtils;
2014
2096
  const USKeyboardLayout_js_1 = USKeyboardLayout;
@@ -2375,10 +2457,13 @@ var mapperTab = (function () {
2375
2457
  } while (!last);
2376
2458
  }
2377
2459
  async #dispatchKeyDownAction(source, action) {
2378
- if ([...action.value].length > 1) {
2379
- throw new protocol_js_1$k.InvalidArgumentException(`Invalid key value: ${action.value}`);
2380
- }
2381
2460
  const rawKey = action.value;
2461
+ if (!(0, GraphemeTools_1.isSingleGrapheme)(rawKey)) {
2462
+ // https://w3c.github.io/webdriver/#dfn-process-a-key-action
2463
+ // WebDriver spec allows a grapheme to be used.
2464
+ throw new protocol_js_1$k.InvalidArgumentException(`Invalid key value: ${rawKey}`);
2465
+ }
2466
+ const isGrapheme = (0, GraphemeTools_1.isSingleComplexGrapheme)(rawKey);
2382
2467
  const key = (0, keyUtils_js_1.getNormalizedKey)(rawKey);
2383
2468
  const repeat = source.pressed.has(key);
2384
2469
  const code = (0, keyUtils_js_1.getKeyCode)(rawKey);
@@ -2402,7 +2487,7 @@ var mapperTab = (function () {
2402
2487
  // --- Platform-specific code begins here ---
2403
2488
  // The spread is a little hack so JS gives us an array of unicode characters
2404
2489
  // to measure.
2405
- const unmodifiedText = getKeyEventUnmodifiedText(key, source);
2490
+ const unmodifiedText = getKeyEventUnmodifiedText(key, source, isGrapheme);
2406
2491
  const text = getKeyEventText(code ?? '', source) ?? unmodifiedText;
2407
2492
  let command;
2408
2493
  // The following commands need to be declared because Chromium doesn't
@@ -2455,10 +2540,13 @@ var mapperTab = (function () {
2455
2540
  // --- Platform-specific code ends here ---
2456
2541
  }
2457
2542
  #dispatchKeyUpAction(source, action) {
2458
- if ([...action.value].length > 1) {
2459
- throw new protocol_js_1$k.InvalidArgumentException(`Invalid key value: ${action.value}`);
2460
- }
2461
2543
  const rawKey = action.value;
2544
+ if (!(0, GraphemeTools_1.isSingleGrapheme)(rawKey)) {
2545
+ // https://w3c.github.io/webdriver/#dfn-process-a-key-action
2546
+ // WebDriver spec allows a grapheme to be used.
2547
+ throw new protocol_js_1$k.InvalidArgumentException(`Invalid key value: ${rawKey}`);
2548
+ }
2549
+ const isGrapheme = (0, GraphemeTools_1.isSingleComplexGrapheme)(rawKey);
2462
2550
  const key = (0, keyUtils_js_1.getNormalizedKey)(rawKey);
2463
2551
  if (!source.pressed.has(key)) {
2464
2552
  return;
@@ -2484,7 +2572,7 @@ var mapperTab = (function () {
2484
2572
  // --- Platform-specific code begins here ---
2485
2573
  // The spread is a little hack so JS gives us an array of unicode characters
2486
2574
  // to measure.
2487
- const unmodifiedText = getKeyEventUnmodifiedText(key, source);
2575
+ const unmodifiedText = getKeyEventUnmodifiedText(key, source, isGrapheme);
2488
2576
  const text = getKeyEventText(code ?? '', source) ?? unmodifiedText;
2489
2577
  return this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchKeyEvent', {
2490
2578
  type: 'keyUp',
@@ -2502,10 +2590,20 @@ var mapperTab = (function () {
2502
2590
  }
2503
2591
  }
2504
2592
  ActionDispatcher$1.ActionDispatcher = ActionDispatcher;
2505
- const getKeyEventUnmodifiedText = (key, source) => {
2593
+ /**
2594
+ * Translates a non-grapheme key to either an `undefined` for a special keys, or a single
2595
+ * character modified by shift if needed.
2596
+ */
2597
+ const getKeyEventUnmodifiedText = (key, source, isGrapheme) => {
2598
+ if (isGrapheme) {
2599
+ // Graphemes should be presented as text in the CDP command.
2600
+ return key;
2601
+ }
2506
2602
  if (key === 'Enter') {
2507
2603
  return '\r';
2508
2604
  }
2605
+ // If key is not a single character, it is a normalized key value, and should be
2606
+ // presented as key, not text in the CDP command.
2509
2607
  return [...key].length === 1
2510
2608
  ? source.shift
2511
2609
  ? key.toLocaleUpperCase('en-US')
@@ -2920,36 +3018,42 @@ var mapperTab = (function () {
2920
3018
  try {
2921
3019
  result = await realm.callFunction(String(function getFiles(fileListLength) {
2922
3020
  if (!(this instanceof HTMLInputElement)) {
2923
- return 0 /* ErrorCode.Object */;
3021
+ if (this instanceof Element) {
3022
+ return 1 /* ErrorCode.Element */;
3023
+ }
3024
+ return 0 /* ErrorCode.Node */;
2924
3025
  }
2925
3026
  if (this.type !== 'file') {
2926
- return 1 /* ErrorCode.Type */;
3027
+ return 2 /* ErrorCode.Type */;
2927
3028
  }
2928
3029
  if (this.disabled) {
2929
- return 2 /* ErrorCode.Disabled */;
3030
+ return 3 /* ErrorCode.Disabled */;
2930
3031
  }
2931
3032
  if (fileListLength > 1 && !this.multiple) {
2932
- return 3 /* ErrorCode.Multiple */;
3033
+ return 4 /* ErrorCode.Multiple */;
2933
3034
  }
2934
3035
  return;
2935
3036
  }), false, params.element, [{ type: 'number', value: params.files.length }]);
2936
3037
  }
2937
3038
  catch {
2938
- throw new protocol_js_1$i.NoSuchElementException(`Could not find element ${params.element.sharedId}`);
3039
+ throw new protocol_js_1$i.NoSuchNodeException(`Could not find element ${params.element.sharedId}`);
2939
3040
  }
2940
3041
  (0, assert_js_1$4.assert)(result.type === 'success');
2941
3042
  if (result.result.type === 'number') {
2942
3043
  switch (result.result.value) {
2943
- case 0 /* ErrorCode.Object */: {
3044
+ case 0 /* ErrorCode.Node */: {
2944
3045
  throw new protocol_js_1$i.NoSuchElementException(`Could not find element ${params.element.sharedId}`);
2945
3046
  }
2946
- case 1 /* ErrorCode.Type */: {
2947
- throw new protocol_js_1$i.UnableToSetFileInputException(`Element ${params.element.sharedId} is not a file input`);
3047
+ case 1 /* ErrorCode.Element */: {
3048
+ throw new protocol_js_1$i.UnableToSetFileInputException(`Element ${params.element.sharedId} is not a input`);
3049
+ }
3050
+ case 2 /* ErrorCode.Type */: {
3051
+ throw new protocol_js_1$i.UnableToSetFileInputException(`Input element ${params.element.sharedId} is not a file type`);
2948
3052
  }
2949
- case 2 /* ErrorCode.Disabled */: {
3053
+ case 3 /* ErrorCode.Disabled */: {
2950
3054
  throw new protocol_js_1$i.UnableToSetFileInputException(`Input element ${params.element.sharedId} is disabled`);
2951
3055
  }
2952
- case 3 /* ErrorCode.Multiple */: {
3056
+ case 4 /* ErrorCode.Multiple */: {
2953
3057
  throw new protocol_js_1$i.UnableToSetFileInputException(`Cannot set multiple files on a non-multiple input element`);
2954
3058
  }
2955
3059
  }
@@ -3096,7 +3200,7 @@ var mapperTab = (function () {
3096
3200
 
3097
3201
  var UrlPattern = {};
3098
3202
 
3099
- var M=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Oe=(e,t)=>{for(var r in t)M(e,r,{get:t[r],enumerable:!0});},ke=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Re(t))!Ee.call(e,a)&&a!==r&&M(e,a,{get:()=>t[a],enumerable:!(n=Pe(t,a))||n.enumerable});return e};var Te=e=>ke(M({},"__esModule",{value:!0}),e);var Ne={};Oe(Ne,{URLPattern:()=>Y});var urlpattern=Te(Ne);var R=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,r,n,a,c,l){this.type=t,this.name=r,this.prefix=n,this.value=a,this.suffix=c,this.modifier=l;}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},Ae=/[$_\p{ID_Start}]/u,ye=/[$_\u200C\u200D\p{ID_Continue}]/u,v=".*";function we(e,t){return (t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function D(e,t=!1){let r=[],n=0;for(;n<e.length;){let a=e[n],c=function(l){if(!t)throw new TypeError(l);r.push({type:"INVALID_CHAR",index:n,value:e[n++]});};if(a==="*"){r.push({type:"ASTERISK",index:n,value:e[n++]});continue}if(a==="+"||a==="?"){r.push({type:"OTHER_MODIFIER",index:n,value:e[n++]});continue}if(a==="\\"){r.push({type:"ESCAPED_CHAR",index:n++,value:e[n++]});continue}if(a==="{"){r.push({type:"OPEN",index:n,value:e[n++]});continue}if(a==="}"){r.push({type:"CLOSE",index:n,value:e[n++]});continue}if(a===":"){let l="",s=n+1;for(;s<e.length;){let i=e.substr(s,1);if(s===n+1&&Ae.test(i)||s!==n+1&&ye.test(i)){l+=e[s++];continue}break}if(!l){c(`Missing parameter name at ${n}`);continue}r.push({type:"NAME",index:n,value:l}),n=s;continue}if(a==="("){let l=1,s="",i=n+1,o=!1;if(e[i]==="?"){c(`Pattern cannot start with "?" at ${i}`);continue}for(;i<e.length;){if(!we(e[i],!1)){c(`Invalid character '${e[i]}' at ${i}.`),o=!0;break}if(e[i]==="\\"){s+=e[i++]+e[i++];continue}if(e[i]===")"){if(l--,l===0){i++;break}}else if(e[i]==="("&&(l++,e[i+1]!=="?")){c(`Capturing groups are not allowed at ${i}`),o=!0;break}s+=e[i++];}if(o)continue;if(l){c(`Unbalanced pattern at ${n}`);continue}if(!s){c(`Missing pattern at ${n}`);continue}r.push({type:"REGEX",index:n,value:s}),n=i;continue}r.push({type:"CHAR",index:n,value:e[n++]});}return r.push({type:"END",index:n,value:""}),r}function F(e,t={}){let r=D(e);t.delimiter??="/#?",t.prefixes??="./";let n=`[^${S(t.delimiter)}]+?`,a=[],c=0,l=0,i=new Set,o=h=>{if(l<r.length&&r[l].type===h)return r[l++].value},f=()=>o("OTHER_MODIFIER")??o("ASTERISK"),d=h=>{let u=o(h);if(u!==void 0)return u;let{type:p,index:A}=r[l];throw new TypeError(`Unexpected ${p} at ${A}, expected ${h}`)},T=()=>{let h="",u;for(;u=o("CHAR")??o("ESCAPED_CHAR");)h+=u;return h},xe=h=>h,L=t.encodePart||xe,I="",U=h=>{I+=h;},$=()=>{I.length&&(a.push(new R(3,"","",L(I),"",3)),I="");},X=(h,u,p,A,Z)=>{let g=3;switch(Z){case"?":g=1;break;case"*":g=0;break;case"+":g=2;break}if(!u&&!p&&g===3){U(h);return}if($(),!u&&!p){if(!h)return;a.push(new R(3,"","",L(h),"",g));return}let m;p?p==="*"?m=v:m=p:m=n;let O=2;m===n?(O=1,m=""):m===v&&(O=0,m="");let P;if(u?P=u:p&&(P=c++),i.has(P))throw new TypeError(`Duplicate name '${P}'.`);i.add(P),a.push(new R(O,P,L(h),m,L(A),g));};for(;l<r.length;){let h=o("CHAR"),u=o("NAME"),p=o("REGEX");if(!u&&!p&&(p=o("ASTERISK")),u||p){let g=h??"";t.prefixes.indexOf(g)===-1&&(U(g),g=""),$();let m=f();X(g,u,p,"",m);continue}let A=h??o("ESCAPED_CHAR");if(A){U(A);continue}if(o("OPEN")){let g=T(),m=o("NAME"),O=o("REGEX");!m&&!O&&(O=o("ASTERISK"));let P=T();d("CLOSE");let be=f();X(g,m,O,P,be);continue}$(),d("END");}return a}function S(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function B(e){return e&&e.ignoreCase?"ui":"u"}function q(e,t,r){return W(F(e,r),t,r)}function k(e){switch(e){case 0:return "*";case 1:return "?";case 2:return "+";case 3:return ""}}function W(e,t,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let n=r.start?"^":"";for(let s of e){if(s.type===3){s.modifier===3?n+=S(s.value):n+=`(?:${S(s.value)})${k(s.modifier)}`;continue}t&&t.push(s.name);let i=`[^${S(r.delimiter)}]+?`,o=s.value;if(s.type===1?o=i:s.type===0&&(o=v),!s.prefix.length&&!s.suffix.length){s.modifier===3||s.modifier===1?n+=`(${o})${k(s.modifier)}`:n+=`((?:${o})${k(s.modifier)})`;continue}if(s.modifier===3||s.modifier===1){n+=`(?:${S(s.prefix)}(${o})${S(s.suffix)})`,n+=k(s.modifier);continue}n+=`(?:${S(s.prefix)}`,n+=`((?:${o})(?:`,n+=S(s.suffix),n+=S(s.prefix),n+=`(?:${o}))*)${S(s.suffix)})`,s.modifier===0&&(n+="?");}let a=`[${S(r.endsWith)}]|$`,c=`[${S(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${c}?`),r.endsWith.length?n+=`(?=${a})`:n+="$",new RegExp(n,B(r));r.strict||(n+=`(?:${c}(?=${a}))?`);let l=!1;if(e.length){let s=e[e.length-1];s.type===3&&s.modifier===3&&(l=r.delimiter.indexOf(s)>-1);}return l||(n+=`(?=${c}|${a})`),new RegExp(n,B(r))}var x={delimiter:"",prefixes:"",sensitive:!0,strict:!0},J={delimiter:".",prefixes:"",sensitive:!0,strict:!0},Q={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function ee(e,t){return e.length?e[0]==="/"?!0:!t||e.length<2?!1:(e[0]=="\\"||e[0]=="{")&&e[1]=="/":!1}function te(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function Ce(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function _(e){return !e||e.length<2?!1:e[0]==="["||(e[0]==="\\"||e[0]==="{")&&e[1]==="["}var re=["ftp","file","http","https","ws","wss"];function N(e){if(!e)return !0;for(let t of re)if(e.test(t))return !0;return !1}function ne(e,t){if(e=te(e,"#"),t||e==="")return e;let r=new URL("https://example.com");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):""}function se(e,t){if(e=te(e,"?"),t||e==="")return e;let r=new URL("https://example.com");return r.search=e,r.search?r.search.substring(1,r.search.length):""}function ie(e,t){return t||e===""?e:_(e)?K(e):j(e)}function ae(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.password=e,r.password}function oe(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.username=e,r.username}function ce(e,t,r){if(r||e==="")return e;if(t&&!re.includes(t))return new URL(`${t}:${e}`).pathname;let n=e[0]=="/";return e=new URL(n?e:"/-"+e,"https://example.com").pathname,n||(e=e.substring(2,e.length)),e}function le(e,t,r){return z(t)===e&&(e=""),r||e===""?e:G(e)}function fe(e,t){return e=Ce(e,":"),t||e===""?e:y(e)}function z(e){switch(e){case"ws":case"http":return "80";case"wws":case"https":return "443";case"ftp":return "21";default:return ""}}function y(e){if(e==="")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}function he(e){if(e==="")return e;let t=new URL("https://example.com");return t.username=e,t.username}function ue(e){if(e==="")return e;let t=new URL("https://example.com");return t.password=e,t.password}function j(e){if(e==="")return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL("https://example.com");return t.hostname=e,t.hostname}function K(e){if(e==="")return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function G(e){if(e===""||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}function de(e){if(e==="")return e;let t=new URL("https://example.com");return t.pathname=e[0]!=="/"?"/-"+e:e,e[0]!=="/"?t.pathname.substring(2,t.pathname.length):t.pathname}function pe(e){return e===""?e:new URL(`data:${e}`).pathname}function ge(e){if(e==="")return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function me(e){if(e==="")return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var H=class{#i;#n=[];#t={};#e=0;#s=1;#l=0;#o=0;#d=0;#p=0;#g=!1;constructor(t){this.#i=t;}get result(){return this.#t}parse(){for(this.#n=D(this.#i,!0);this.#e<this.#n.length;this.#e+=this.#s){if(this.#s=1,this.#n[this.#e].type==="END"){if(this.#o===0){this.#b(),this.#f()?this.#r(9,1):this.#h()?this.#r(8,1):this.#r(7,0);continue}else if(this.#o===2){this.#u(5);continue}this.#r(10,0);break}if(this.#d>0)if(this.#A())this.#d-=1;else continue;if(this.#T()){this.#d+=1;continue}switch(this.#o){case 0:this.#P()&&this.#u(1);break;case 1:if(this.#P()){this.#C();let t=7,r=1;this.#E()?(t=2,r=3):this.#g&&(t=2),this.#r(t,r);}break;case 2:this.#S()?this.#u(3):(this.#x()||this.#h()||this.#f())&&this.#u(5);break;case 3:this.#O()?this.#r(4,1):this.#S()&&this.#r(5,1);break;case 4:this.#S()&&this.#r(5,1);break;case 5:this.#y()?this.#p+=1:this.#w()&&(this.#p-=1),this.#k()&&!this.#p?this.#r(6,1):this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 6:this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 8:this.#f()&&this.#r(9,1);break;}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port="");}#r(t,r){switch(this.#o){case 0:break;case 1:this.#t.protocol=this.#c();break;case 2:break;case 3:this.#t.username=this.#c();break;case 4:this.#t.password=this.#c();break;case 5:this.#t.hostname=this.#c();break;case 6:this.#t.port=this.#c();break;case 7:this.#t.pathname=this.#c();break;case 8:this.#t.search=this.#c();break;case 9:this.#t.hash=this.#c();break;}this.#o!==0&&t!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(t)&&(this.#t.hostname??=""),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(t)&&(this.#t.pathname??=this.#g?"/":""),[1,2,3,4,5,6,7].includes(this.#o)&&t===9&&(this.#t.search??="")),this.#R(t,r);}#R(t,r){this.#o=t,this.#l=this.#e+r,this.#e+=r,this.#s=0;}#b(){this.#e=this.#l,this.#s=0;}#u(t){this.#b(),this.#o=t;}#m(t){return t<0&&(t=this.#n.length-t),t<this.#n.length?this.#n[t]:this.#n[this.#n.length-1]}#a(t,r){let n=this.#m(t);return n.value===r&&(n.type==="CHAR"||n.type==="ESCAPED_CHAR"||n.type==="INVALID_CHAR")}#P(){return this.#a(this.#e,":")}#E(){return this.#a(this.#e+1,"/")&&this.#a(this.#e+2,"/")}#S(){return this.#a(this.#e,"@")}#O(){return this.#a(this.#e,":")}#k(){return this.#a(this.#e,":")}#x(){return this.#a(this.#e,"/")}#h(){if(this.#a(this.#e,"?"))return !0;if(this.#n[this.#e].value!=="?")return !1;let t=this.#m(this.#e-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#f(){return this.#a(this.#e,"#")}#T(){return this.#n[this.#e].type=="OPEN"}#A(){return this.#n[this.#e].type=="CLOSE"}#y(){return this.#a(this.#e,"[")}#w(){return this.#a(this.#e,"]")}#c(){let t=this.#n[this.#e],r=this.#m(this.#l).index;return this.#i.substring(r,t.index)}#C(){let t={};Object.assign(t,x),t.encodePart=y;let r=q(this.#c(),void 0,t);this.#g=N(r);}};var V=["protocol","username","password","hostname","port","pathname","search","hash"],E="*";function Se(e,t){if(typeof e!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(e,t);return {protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}function b(e,t){return t?C(e):e}function w(e,t,r){let n;if(typeof t.baseURL=="string")try{n=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=b(n.protocol.substring(0,n.protocol.length-1),r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=b(n.username,r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=b(n.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=b(n.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=b(n.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=b(n.pathname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=b(n.search.substring(1,n.search.length),r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=b(n.hash.substring(1,n.hash.length),r));}catch{throw new TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol=="string"&&(e.protocol=fe(t.protocol,r)),typeof t.username=="string"&&(e.username=oe(t.username,r)),typeof t.password=="string"&&(e.password=ae(t.password,r)),typeof t.hostname=="string"&&(e.hostname=ie(t.hostname,r)),typeof t.port=="string"&&(e.port=le(t.port,e.protocol,r)),typeof t.pathname=="string"){if(e.pathname=t.pathname,n&&!ee(e.pathname,r)){let a=n.pathname.lastIndexOf("/");a>=0&&(e.pathname=b(n.pathname.substring(0,a+1),r)+e.pathname);}e.pathname=ce(e.pathname,e.protocol,r);}return typeof t.search=="string"&&(e.search=se(t.search,r)),typeof t.hash=="string"&&(e.hash=ne(t.hash,r)),e}function C(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function Le(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function Ie(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let r=".*",n=`[^${Le(t.delimiter)}]+?`,a=/[$_\u200C\u200D\p{ID_Continue}]/u,c="";for(let l=0;l<e.length;++l){let s=e[l];if(s.type===3){if(s.modifier===3){c+=C(s.value);continue}c+=`{${C(s.value)}}${k(s.modifier)}`;continue}let i=s.hasCustomName(),o=!!s.suffix.length||!!s.prefix.length&&(s.prefix.length!==1||!t.prefixes.includes(s.prefix)),f=l>0?e[l-1]:null,d=l<e.length-1?e[l+1]:null;if(!o&&i&&s.type===1&&s.modifier===3&&d&&!d.prefix.length&&!d.suffix.length)if(d.type===3){let T=d.value.length>0?d.value[0]:"";o=a.test(T);}else o=!d.hasCustomName();if(!o&&!s.prefix.length&&f&&f.type===3){let T=f.value[f.value.length-1];o=t.prefixes.includes(T);}o&&(c+="{"),c+=C(s.prefix),i&&(c+=`:${s.name}`),s.type===2?c+=`(${s.value})`:s.type===1?i||(c+=`(${n})`):s.type===0&&(!i&&(!f||f.type===3||f.modifier!==3||o||s.prefix!=="")?c+="*":c+=`(${r})`),s.type===1&&i&&s.suffix.length&&a.test(s.suffix[0])&&(c+="\\"),c+=C(s.suffix),o&&(c+="}"),s.modifier!==3&&(c+=k(s.modifier));}return c}var Y=class{#i;#n={};#t={};#e={};#s={};#l=!1;constructor(t={},r,n){try{let a;if(typeof r=="string"?a=r:n=r,typeof t=="string"){let i=new H(t);if(i.parse(),t=i.result,a===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=a;}else {if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(a)throw new TypeError("parameter 1 is not of type 'string'.")}typeof n>"u"&&(n={ignoreCase:!1});let c={ignoreCase:n.ignoreCase===!0},l={pathname:E,protocol:E,username:E,password:E,hostname:E,port:E,search:E,hash:E};this.#i=w(l,t,!0),z(this.#i.protocol)===this.#i.port&&(this.#i.port="");let s;for(s of V){if(!(s in this.#i))continue;let i={},o=this.#i[s];switch(this.#t[s]=[],s){case"protocol":Object.assign(i,x),i.encodePart=y;break;case"username":Object.assign(i,x),i.encodePart=he;break;case"password":Object.assign(i,x),i.encodePart=ue;break;case"hostname":Object.assign(i,J),_(o)?i.encodePart=K:i.encodePart=j;break;case"port":Object.assign(i,x),i.encodePart=G;break;case"pathname":N(this.#n.protocol)?(Object.assign(i,Q,c),i.encodePart=de):(Object.assign(i,x,c),i.encodePart=pe);break;case"search":Object.assign(i,x,c),i.encodePart=ge;break;case"hash":Object.assign(i,x,c),i.encodePart=me;break}try{this.#s[s]=F(o,i),this.#n[s]=W(this.#s[s],this.#t[s],i),this.#e[s]=Ie(this.#s[s],i),this.#l=this.#l||this.#s[s].some(f=>f.type===2);}catch{throw new TypeError(`invalid ${s} pattern '${this.#i[s]}'.`)}}}catch(a){throw new TypeError(`Failed to construct 'URLPattern': ${a.message}`)}}test(t={},r){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&r)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return !1;try{typeof t=="object"?n=w(n,t,!1):n=w(n,Se(t,r),!1);}catch{return !1}let a;for(a of V)if(!this.#n[a].exec(n[a]))return !1;return !0}exec(t={},r){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&r)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?n=w(n,t,!1):n=w(n,Se(t,r),!1);}catch{return null}let a={};r?a.inputs=[t,r]:a.inputs=[t];let c;for(c of V){let l=this.#n[c].exec(n[c]);if(!l)return null;let s={};for(let[i,o]of this.#t[c].entries())if(typeof o=="string"||typeof o=="number"){let f=l[i+1];s[o]=f;}a[c]={input:n[c]??"",groups:s};}return a}static compareComponent(t,r,n){let a=(i,o)=>{for(let f of ["type","modifier","prefix","value","suffix"]){if(i[f]<o[f])return -1;if(i[f]===o[f])continue;return 1}return 0},c=new R(3,"","","","",3),l=new R(0,"","","","",3),s=(i,o)=>{let f=0;for(;f<Math.min(i.length,o.length);++f){let d=a(i[f],o[f]);if(d)return d}return i.length===o.length?0:a(i[f]??c,o[f]??c)};return !r.#e[t]&&!n.#e[t]?0:r.#e[t]&&!n.#e[t]?s(r.#s[t],[l]):!r.#e[t]&&n.#e[t]?s([l],n.#s[t]):s(r.#s[t],n.#s[t])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#l}};
3203
+ var M=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Oe=(e,t)=>{for(var r in t)M(e,r,{get:t[r],enumerable:!0});},ke=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Re(t))!Ee.call(e,a)&&a!==r&&M(e,a,{get:()=>t[a],enumerable:!(n=Pe(t,a))||n.enumerable});return e};var Te=e=>ke(M({},"__esModule",{value:!0}),e);var Ne={};Oe(Ne,{URLPattern:()=>Y});var urlpattern=Te(Ne);var R=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,r,n,a,c,l){this.type=t,this.name=r,this.prefix=n,this.value=a,this.suffix=c,this.modifier=l;}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},Ae=/[$_\p{ID_Start}]/u,ye=/[$_\u200C\u200D\p{ID_Continue}]/u,v=".*";function we(e,t){return (/^[\x00-\x7F]*$/).test(e)}function D(e,t=!1){let r=[],n=0;for(;n<e.length;){let a=e[n],c=function(l){if(!t)throw new TypeError(l);r.push({type:"INVALID_CHAR",index:n,value:e[n++]});};if(a==="*"){r.push({type:"ASTERISK",index:n,value:e[n++]});continue}if(a==="+"||a==="?"){r.push({type:"OTHER_MODIFIER",index:n,value:e[n++]});continue}if(a==="\\"){r.push({type:"ESCAPED_CHAR",index:n++,value:e[n++]});continue}if(a==="{"){r.push({type:"OPEN",index:n,value:e[n++]});continue}if(a==="}"){r.push({type:"CLOSE",index:n,value:e[n++]});continue}if(a===":"){let l="",s=n+1;for(;s<e.length;){let i=e.substr(s,1);if(s===n+1&&Ae.test(i)||s!==n+1&&ye.test(i)){l+=e[s++];continue}break}if(!l){c(`Missing parameter name at ${n}`);continue}r.push({type:"NAME",index:n,value:l}),n=s;continue}if(a==="("){let l=1,s="",i=n+1,o=!1;if(e[i]==="?"){c(`Pattern cannot start with "?" at ${i}`);continue}for(;i<e.length;){if(!we(e[i])){c(`Invalid character '${e[i]}' at ${i}.`),o=!0;break}if(e[i]==="\\"){s+=e[i++]+e[i++];continue}if(e[i]===")"){if(l--,l===0){i++;break}}else if(e[i]==="("&&(l++,e[i+1]!=="?")){c(`Capturing groups are not allowed at ${i}`),o=!0;break}s+=e[i++];}if(o)continue;if(l){c(`Unbalanced pattern at ${n}`);continue}if(!s){c(`Missing pattern at ${n}`);continue}r.push({type:"REGEX",index:n,value:s}),n=i;continue}r.push({type:"CHAR",index:n,value:e[n++]});}return r.push({type:"END",index:n,value:""}),r}function F(e,t={}){let r=D(e);t.delimiter??="/#?",t.prefixes??="./";let n=`[^${S(t.delimiter)}]+?`,a=[],c=0,l=0,i=new Set,o=h=>{if(l<r.length&&r[l].type===h)return r[l++].value},f=()=>o("OTHER_MODIFIER")??o("ASTERISK"),d=h=>{let u=o(h);if(u!==void 0)return u;let{type:p,index:A}=r[l];throw new TypeError(`Unexpected ${p} at ${A}, expected ${h}`)},T=()=>{let h="",u;for(;u=o("CHAR")??o("ESCAPED_CHAR");)h+=u;return h},xe=h=>h,L=t.encodePart||xe,I="",U=h=>{I+=h;},$=()=>{I.length&&(a.push(new R(3,"","",L(I),"",3)),I="");},X=(h,u,p,A,Z)=>{let g=3;switch(Z){case"?":g=1;break;case"*":g=0;break;case"+":g=2;break}if(!u&&!p&&g===3){U(h);return}if($(),!u&&!p){if(!h)return;a.push(new R(3,"","",L(h),"",g));return}let m;p?p==="*"?m=v:m=p:m=n;let O=2;m===n?(O=1,m=""):m===v&&(O=0,m="");let P;if(u?P=u:p&&(P=c++),i.has(P))throw new TypeError(`Duplicate name '${P}'.`);i.add(P),a.push(new R(O,P,L(h),m,L(A),g));};for(;l<r.length;){let h=o("CHAR"),u=o("NAME"),p=o("REGEX");if(!u&&!p&&(p=o("ASTERISK")),u||p){let g=h??"";t.prefixes.indexOf(g)===-1&&(U(g),g=""),$();let m=f();X(g,u,p,"",m);continue}let A=h??o("ESCAPED_CHAR");if(A){U(A);continue}if(o("OPEN")){let g=T(),m=o("NAME"),O=o("REGEX");!m&&!O&&(O=o("ASTERISK"));let P=T();d("CLOSE");let be=f();X(g,m,O,P,be);continue}$(),d("END");}return a}function S(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function B(e){return e&&e.ignoreCase?"ui":"u"}function q(e,t,r){return W(F(e,r),t,r)}function k(e){switch(e){case 0:return "*";case 1:return "?";case 2:return "+";case 3:return ""}}function W(e,t,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let n=r.start?"^":"";for(let s of e){if(s.type===3){s.modifier===3?n+=S(s.value):n+=`(?:${S(s.value)})${k(s.modifier)}`;continue}t&&t.push(s.name);let i=`[^${S(r.delimiter)}]+?`,o=s.value;if(s.type===1?o=i:s.type===0&&(o=v),!s.prefix.length&&!s.suffix.length){s.modifier===3||s.modifier===1?n+=`(${o})${k(s.modifier)}`:n+=`((?:${o})${k(s.modifier)})`;continue}if(s.modifier===3||s.modifier===1){n+=`(?:${S(s.prefix)}(${o})${S(s.suffix)})`,n+=k(s.modifier);continue}n+=`(?:${S(s.prefix)}`,n+=`((?:${o})(?:`,n+=S(s.suffix),n+=S(s.prefix),n+=`(?:${o}))*)${S(s.suffix)})`,s.modifier===0&&(n+="?");}let a=`[${S(r.endsWith)}]|$`,c=`[${S(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${c}?`),r.endsWith.length?n+=`(?=${a})`:n+="$",new RegExp(n,B(r));r.strict||(n+=`(?:${c}(?=${a}))?`);let l=!1;if(e.length){let s=e[e.length-1];s.type===3&&s.modifier===3&&(l=r.delimiter.indexOf(s)>-1);}return l||(n+=`(?=${c}|${a})`),new RegExp(n,B(r))}var x={delimiter:"",prefixes:"",sensitive:!0,strict:!0},J={delimiter:".",prefixes:"",sensitive:!0,strict:!0},Q={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function ee(e,t){return e.length?e[0]==="/"?!0:!t||e.length<2?!1:(e[0]=="\\"||e[0]=="{")&&e[1]=="/":!1}function te(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function Ce(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function _(e){return !e||e.length<2?!1:e[0]==="["||(e[0]==="\\"||e[0]==="{")&&e[1]==="["}var re=["ftp","file","http","https","ws","wss"];function N(e){if(!e)return !0;for(let t of re)if(e.test(t))return !0;return !1}function ne(e,t){if(e=te(e,"#"),t||e==="")return e;let r=new URL("https://example.com");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):""}function se(e,t){if(e=te(e,"?"),t||e==="")return e;let r=new URL("https://example.com");return r.search=e,r.search?r.search.substring(1,r.search.length):""}function ie(e,t){return t||e===""?e:_(e)?K(e):j(e)}function ae(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.password=e,r.password}function oe(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.username=e,r.username}function ce(e,t,r){if(r||e==="")return e;if(t&&!re.includes(t))return new URL(`${t}:${e}`).pathname;let n=e[0]=="/";return e=new URL(n?e:"/-"+e,"https://example.com").pathname,n||(e=e.substring(2,e.length)),e}function le(e,t,r){return z(t)===e&&(e=""),r||e===""?e:G(e)}function fe(e,t){return e=Ce(e,":"),t||e===""?e:y(e)}function z(e){switch(e){case"ws":case"http":return "80";case"wws":case"https":return "443";case"ftp":return "21";default:return ""}}function y(e){if(e==="")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}function he(e){if(e==="")return e;let t=new URL("https://example.com");return t.username=e,t.username}function ue(e){if(e==="")return e;let t=new URL("https://example.com");return t.password=e,t.password}function j(e){if(e==="")return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL("https://example.com");return t.hostname=e,t.hostname}function K(e){if(e==="")return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function G(e){if(e===""||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}function de(e){if(e==="")return e;let t=new URL("https://example.com");return t.pathname=e[0]!=="/"?"/-"+e:e,e[0]!=="/"?t.pathname.substring(2,t.pathname.length):t.pathname}function pe(e){return e===""?e:new URL(`data:${e}`).pathname}function ge(e){if(e==="")return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function me(e){if(e==="")return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var H=class{#i;#n=[];#t={};#e=0;#s=1;#l=0;#o=0;#d=0;#p=0;#g=!1;constructor(t){this.#i=t;}get result(){return this.#t}parse(){for(this.#n=D(this.#i,!0);this.#e<this.#n.length;this.#e+=this.#s){if(this.#s=1,this.#n[this.#e].type==="END"){if(this.#o===0){this.#b(),this.#f()?this.#r(9,1):this.#h()?this.#r(8,1):this.#r(7,0);continue}else if(this.#o===2){this.#u(5);continue}this.#r(10,0);break}if(this.#d>0)if(this.#A())this.#d-=1;else continue;if(this.#T()){this.#d+=1;continue}switch(this.#o){case 0:this.#P()&&this.#u(1);break;case 1:if(this.#P()){this.#C();let t=7,r=1;this.#E()?(t=2,r=3):this.#g&&(t=2),this.#r(t,r);}break;case 2:this.#S()?this.#u(3):(this.#x()||this.#h()||this.#f())&&this.#u(5);break;case 3:this.#O()?this.#r(4,1):this.#S()&&this.#r(5,1);break;case 4:this.#S()&&this.#r(5,1);break;case 5:this.#y()?this.#p+=1:this.#w()&&(this.#p-=1),this.#k()&&!this.#p?this.#r(6,1):this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 6:this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 8:this.#f()&&this.#r(9,1);break;}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port="");}#r(t,r){switch(this.#o){case 0:break;case 1:this.#t.protocol=this.#c();break;case 2:break;case 3:this.#t.username=this.#c();break;case 4:this.#t.password=this.#c();break;case 5:this.#t.hostname=this.#c();break;case 6:this.#t.port=this.#c();break;case 7:this.#t.pathname=this.#c();break;case 8:this.#t.search=this.#c();break;case 9:this.#t.hash=this.#c();break;}this.#o!==0&&t!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(t)&&(this.#t.hostname??=""),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(t)&&(this.#t.pathname??=this.#g?"/":""),[1,2,3,4,5,6,7].includes(this.#o)&&t===9&&(this.#t.search??="")),this.#R(t,r);}#R(t,r){this.#o=t,this.#l=this.#e+r,this.#e+=r,this.#s=0;}#b(){this.#e=this.#l,this.#s=0;}#u(t){this.#b(),this.#o=t;}#m(t){return t<0&&(t=this.#n.length-t),t<this.#n.length?this.#n[t]:this.#n[this.#n.length-1]}#a(t,r){let n=this.#m(t);return n.value===r&&(n.type==="CHAR"||n.type==="ESCAPED_CHAR"||n.type==="INVALID_CHAR")}#P(){return this.#a(this.#e,":")}#E(){return this.#a(this.#e+1,"/")&&this.#a(this.#e+2,"/")}#S(){return this.#a(this.#e,"@")}#O(){return this.#a(this.#e,":")}#k(){return this.#a(this.#e,":")}#x(){return this.#a(this.#e,"/")}#h(){if(this.#a(this.#e,"?"))return !0;if(this.#n[this.#e].value!=="?")return !1;let t=this.#m(this.#e-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#f(){return this.#a(this.#e,"#")}#T(){return this.#n[this.#e].type=="OPEN"}#A(){return this.#n[this.#e].type=="CLOSE"}#y(){return this.#a(this.#e,"[")}#w(){return this.#a(this.#e,"]")}#c(){let t=this.#n[this.#e],r=this.#m(this.#l).index;return this.#i.substring(r,t.index)}#C(){let t={};Object.assign(t,x),t.encodePart=y;let r=q(this.#c(),void 0,t);this.#g=N(r);}};var V=["protocol","username","password","hostname","port","pathname","search","hash"],E="*";function Se(e,t){if(typeof e!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(e,t);return {protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}function b(e,t){return t?C(e):e}function w(e,t,r){let n;if(typeof t.baseURL=="string")try{n=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=b(n.protocol.substring(0,n.protocol.length-1),r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=b(n.username,r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=b(n.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=b(n.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=b(n.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=b(n.pathname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=b(n.search.substring(1,n.search.length),r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=b(n.hash.substring(1,n.hash.length),r));}catch{throw new TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol=="string"&&(e.protocol=fe(t.protocol,r)),typeof t.username=="string"&&(e.username=oe(t.username,r)),typeof t.password=="string"&&(e.password=ae(t.password,r)),typeof t.hostname=="string"&&(e.hostname=ie(t.hostname,r)),typeof t.port=="string"&&(e.port=le(t.port,e.protocol,r)),typeof t.pathname=="string"){if(e.pathname=t.pathname,n&&!ee(e.pathname,r)){let a=n.pathname.lastIndexOf("/");a>=0&&(e.pathname=b(n.pathname.substring(0,a+1),r)+e.pathname);}e.pathname=ce(e.pathname,e.protocol,r);}return typeof t.search=="string"&&(e.search=se(t.search,r)),typeof t.hash=="string"&&(e.hash=ne(t.hash,r)),e}function C(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function Le(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function Ie(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let r=".*",n=`[^${Le(t.delimiter)}]+?`,a=/[$_\u200C\u200D\p{ID_Continue}]/u,c="";for(let l=0;l<e.length;++l){let s=e[l];if(s.type===3){if(s.modifier===3){c+=C(s.value);continue}c+=`{${C(s.value)}}${k(s.modifier)}`;continue}let i=s.hasCustomName(),o=!!s.suffix.length||!!s.prefix.length&&(s.prefix.length!==1||!t.prefixes.includes(s.prefix)),f=l>0?e[l-1]:null,d=l<e.length-1?e[l+1]:null;if(!o&&i&&s.type===1&&s.modifier===3&&d&&!d.prefix.length&&!d.suffix.length)if(d.type===3){let T=d.value.length>0?d.value[0]:"";o=a.test(T);}else o=!d.hasCustomName();if(!o&&!s.prefix.length&&f&&f.type===3){let T=f.value[f.value.length-1];o=t.prefixes.includes(T);}o&&(c+="{"),c+=C(s.prefix),i&&(c+=`:${s.name}`),s.type===2?c+=`(${s.value})`:s.type===1?i||(c+=`(${n})`):s.type===0&&(!i&&(!f||f.type===3||f.modifier!==3||o||s.prefix!=="")?c+="*":c+=`(${r})`),s.type===1&&i&&s.suffix.length&&a.test(s.suffix[0])&&(c+="\\"),c+=C(s.suffix),o&&(c+="}"),s.modifier!==3&&(c+=k(s.modifier));}return c}var Y=class{#i;#n={};#t={};#e={};#s={};#l=!1;constructor(t={},r,n){try{let a;if(typeof r=="string"?a=r:n=r,typeof t=="string"){let i=new H(t);if(i.parse(),t=i.result,a===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=a;}else {if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(a)throw new TypeError("parameter 1 is not of type 'string'.")}typeof n>"u"&&(n={ignoreCase:!1});let c={ignoreCase:n.ignoreCase===!0},l={pathname:E,protocol:E,username:E,password:E,hostname:E,port:E,search:E,hash:E};this.#i=w(l,t,!0),z(this.#i.protocol)===this.#i.port&&(this.#i.port="");let s;for(s of V){if(!(s in this.#i))continue;let i={},o=this.#i[s];switch(this.#t[s]=[],s){case"protocol":Object.assign(i,x),i.encodePart=y;break;case"username":Object.assign(i,x),i.encodePart=he;break;case"password":Object.assign(i,x),i.encodePart=ue;break;case"hostname":Object.assign(i,J),_(o)?i.encodePart=K:i.encodePart=j;break;case"port":Object.assign(i,x),i.encodePart=G;break;case"pathname":N(this.#n.protocol)?(Object.assign(i,Q,c),i.encodePart=de):(Object.assign(i,x,c),i.encodePart=pe);break;case"search":Object.assign(i,x,c),i.encodePart=ge;break;case"hash":Object.assign(i,x,c),i.encodePart=me;break}try{this.#s[s]=F(o,i),this.#n[s]=W(this.#s[s],this.#t[s],i),this.#e[s]=Ie(this.#s[s],i),this.#l=this.#l||this.#s[s].some(f=>f.type===2);}catch{throw new TypeError(`invalid ${s} pattern '${this.#i[s]}'.`)}}}catch(a){throw new TypeError(`Failed to construct 'URLPattern': ${a.message}`)}}test(t={},r){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&r)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return !1;try{typeof t=="object"?n=w(n,t,!1):n=w(n,Se(t,r),!1);}catch{return !1}let a;for(a of V)if(!this.#n[a].exec(n[a]))return !1;return !0}exec(t={},r){let n={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&r)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?n=w(n,t,!1):n=w(n,Se(t,r),!1);}catch{return null}let a={};r?a.inputs=[t,r]:a.inputs=[t];let c;for(c of V){let l=this.#n[c].exec(n[c]);if(!l)return null;let s={};for(let[i,o]of this.#t[c].entries())if(typeof o=="string"||typeof o=="number"){let f=l[i+1];s[o]=f;}a[c]={input:n[c]??"",groups:s};}return a}static compareComponent(t,r,n){let a=(i,o)=>{for(let f of ["type","modifier","prefix","value","suffix"]){if(i[f]<o[f])return -1;if(i[f]===o[f])continue;return 1}return 0},c=new R(3,"","","","",3),l=new R(0,"","","","",3),s=(i,o)=>{let f=0;for(;f<Math.min(i.length,o.length);++f){let d=a(i[f],o[f]);if(d)return d}return i.length===o.length?0:a(i[f]??c,o[f]??c)};return !r.#e[t]&&!n.#e[t]?0:r.#e[t]&&!n.#e[t]?s(r.#s[t],[l]):!r.#e[t]&&n.#e[t]?s([l],n.#s[t]):s(r.#s[t],n.#s[t])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#l}};
3100
3204
 
3101
3205
  const { URLPattern: URLPattern$2 } = urlpattern;
3102
3206
 
@@ -3151,7 +3255,7 @@ var mapperTab = (function () {
3151
3255
  *
3152
3256
  */
3153
3257
  Object.defineProperty(NetworkUtils, "__esModule", { value: true });
3154
- NetworkUtils.matchUrlPattern = NetworkUtils.isSpecialScheme = NetworkUtils.sameSiteBiDiToCdp = NetworkUtils.bidiToCdpCookie = NetworkUtils.deserializeByteValue = NetworkUtils.cdpToBiDiCookie = NetworkUtils.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction = NetworkUtils.cdpFetchHeadersFromBidiNetworkHeaders = NetworkUtils.bidiNetworkHeadersFromCdpFetchHeaders = NetworkUtils.cdpNetworkHeadersFromBidiNetworkHeaders = NetworkUtils.bidiNetworkHeadersFromCdpNetworkHeaders = NetworkUtils.computeHeadersSize = void 0;
3258
+ NetworkUtils.matchUrlPattern = NetworkUtils.isSpecialScheme = NetworkUtils.sameSiteBiDiToCdp = NetworkUtils.bidiToCdpCookie = NetworkUtils.deserializeByteValue = NetworkUtils.cdpToBiDiCookie = NetworkUtils.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction = NetworkUtils.cdpFetchHeadersFromBidiNetworkHeaders = NetworkUtils.bidiNetworkHeadersFromCdpFetchHeaders = NetworkUtils.cdpNetworkHeadersFromBidiNetworkHeaders = NetworkUtils.bidiNetworkHeadersFromCdpNetworkHeadersEntries = NetworkUtils.bidiNetworkHeadersFromCdpNetworkHeaders = NetworkUtils.computeHeadersSize = void 0;
3155
3259
  const ErrorResponse_js_1 = ErrorResponse;
3156
3260
  const Base64_js_1 = Base64;
3157
3261
  const UrlPattern_js_1 = UrlPattern;
@@ -3162,7 +3266,7 @@ var mapperTab = (function () {
3162
3266
  return new TextEncoder().encode(requestHeaders).length;
3163
3267
  }
3164
3268
  NetworkUtils.computeHeadersSize = computeHeadersSize;
3165
- /** Converts from CDP Network domain headers to Bidi network headers. */
3269
+ /** Converts from CDP Network domain headers to BiDi network headers. */
3166
3270
  function bidiNetworkHeadersFromCdpNetworkHeaders(headers) {
3167
3271
  if (!headers) {
3168
3272
  return [];
@@ -3176,6 +3280,20 @@ var mapperTab = (function () {
3176
3280
  }));
3177
3281
  }
3178
3282
  NetworkUtils.bidiNetworkHeadersFromCdpNetworkHeaders = bidiNetworkHeadersFromCdpNetworkHeaders;
3283
+ /** Converts from CDP Fetch domain headers to BiDi network headers. */
3284
+ function bidiNetworkHeadersFromCdpNetworkHeadersEntries(headers) {
3285
+ if (!headers) {
3286
+ return [];
3287
+ }
3288
+ return headers.map(({ name, value }) => ({
3289
+ name,
3290
+ value: {
3291
+ type: 'string',
3292
+ value,
3293
+ },
3294
+ }));
3295
+ }
3296
+ NetworkUtils.bidiNetworkHeadersFromCdpNetworkHeadersEntries = bidiNetworkHeadersFromCdpNetworkHeadersEntries;
3179
3297
  /** Converts from Bidi network headers to CDP Network domain headers. */
3180
3298
  function cdpNetworkHeadersFromBidiNetworkHeaders(headers) {
3181
3299
  if (headers === undefined) {
@@ -3285,9 +3403,12 @@ var mapperTab = (function () {
3285
3403
  path: params.cookie.path ?? '/',
3286
3404
  secure: params.cookie.secure ?? false,
3287
3405
  httpOnly: params.cookie.httpOnly ?? false,
3288
- // CDP's `partitionKey` is the BiDi's `partition.sourceOrigin`.
3289
3406
  ...(partitionKey.sourceOrigin !== undefined && {
3290
- partitionKey: partitionKey.sourceOrigin,
3407
+ partitionKey: {
3408
+ hasCrossSiteAncestor: false,
3409
+ // CDP's `partitionKey.topLevelSite` is the BiDi's `partition.sourceOrigin`.
3410
+ topLevelSite: partitionKey.sourceOrigin,
3411
+ },
3291
3412
  }),
3292
3413
  ...(params.cookie.expiry !== undefined && {
3293
3414
  expires: params.cookie.expiry,
@@ -3405,22 +3526,38 @@ var mapperTab = (function () {
3405
3526
  if (params.url !== undefined) {
3406
3527
  NetworkProcessor.parseUrlString(params.url);
3407
3528
  }
3529
+ if (params.method !== undefined) {
3530
+ if (!NetworkProcessor.isMethodValid(params.method)) {
3531
+ throw new protocol_js_1$h.InvalidArgumentException(`Method '${method}' is invalid.`);
3532
+ }
3533
+ }
3534
+ if (params.headers) {
3535
+ NetworkProcessor.validateHeaders(params.headers);
3536
+ }
3408
3537
  const request = this.#getBlockedRequestOrFail(networkId, [
3409
3538
  "beforeRequestSent" /* Network.InterceptPhase.BeforeRequestSent */,
3410
3539
  ]);
3411
3540
  const headers = (0, NetworkUtils_js_1$3.cdpFetchHeadersFromBidiNetworkHeaders)(commandHeaders);
3412
3541
  // TODO: Set / expand.
3413
3542
  // ; Step 9. cookies
3414
- await request.continueRequest({
3415
- url,
3416
- method,
3417
- headers,
3418
- postData: getCdpBodyFromBiDiBytesValue(body),
3419
- });
3543
+ try {
3544
+ await request.continueRequest({
3545
+ url,
3546
+ method,
3547
+ headers,
3548
+ postData: getCdpBodyFromBiDiBytesValue(body),
3549
+ });
3550
+ }
3551
+ catch (error) {
3552
+ throw NetworkProcessor.wrapInterceptionError(error);
3553
+ }
3420
3554
  return {};
3421
3555
  }
3422
3556
  async continueResponse(params) {
3423
3557
  const { request: networkId, statusCode, reasonPhrase, headers } = params;
3558
+ if (params.headers) {
3559
+ NetworkProcessor.validateHeaders(params.headers);
3560
+ }
3424
3561
  const responseHeaders = (0, NetworkUtils_js_1$3.cdpFetchHeadersFromBidiNetworkHeaders)(headers);
3425
3562
  const request = this.#getBlockedRequestOrFail(networkId, [
3426
3563
  "authRequired" /* Network.InterceptPhase.AuthRequired */,
@@ -3449,11 +3586,16 @@ var mapperTab = (function () {
3449
3586
  if (request.interceptPhase === "responseStarted" /* Network.InterceptPhase.ResponseStarted */) {
3450
3587
  // TODO: Set / expand.
3451
3588
  // ; Step 10. cookies
3452
- await request.continueResponse({
3453
- responseCode: statusCode,
3454
- responsePhrase: reasonPhrase,
3455
- responseHeaders,
3456
- });
3589
+ try {
3590
+ await request.continueResponse({
3591
+ responseCode: statusCode,
3592
+ responsePhrase: reasonPhrase,
3593
+ responseHeaders,
3594
+ });
3595
+ }
3596
+ catch (error) {
3597
+ throw NetworkProcessor.wrapInterceptionError(error);
3598
+ }
3457
3599
  }
3458
3600
  return {};
3459
3601
  }
@@ -3490,12 +3632,14 @@ var mapperTab = (function () {
3490
3632
  }
3491
3633
  async provideResponse(params) {
3492
3634
  const { statusCode, reasonPhrase: responsePhrase, headers, body, request: networkId, } = params;
3635
+ if (params.headers) {
3636
+ NetworkProcessor.validateHeaders(params.headers);
3637
+ }
3493
3638
  // TODO: Step 6
3494
3639
  // https://w3c.github.io/webdriver-bidi/#command-network-continueResponse
3495
3640
  const responseHeaders = (0, NetworkUtils_js_1$3.cdpFetchHeadersFromBidiNetworkHeaders)(headers);
3496
3641
  // TODO: Set / expand.
3497
3642
  // ; Step 10. cookies
3498
- // ; Step 11. credentials
3499
3643
  const request = this.#getBlockedRequestOrFail(networkId, [
3500
3644
  "beforeRequestSent" /* Network.InterceptPhase.BeforeRequestSent */,
3501
3645
  "responseStarted" /* Network.InterceptPhase.ResponseStarted */,
@@ -3511,19 +3655,24 @@ var mapperTab = (function () {
3511
3655
  });
3512
3656
  return {};
3513
3657
  }
3514
- // If we con't modify the response
3515
- // Just continue the request
3658
+ // If we don't modify the response
3659
+ // just continue the request
3516
3660
  if (!body && !headers) {
3517
3661
  await request.continueRequest();
3518
3662
  return {};
3519
3663
  }
3520
3664
  const responseCode = statusCode ?? request.statusCode ?? 200;
3521
- await request.provideResponse({
3522
- responseCode,
3523
- responsePhrase,
3524
- responseHeaders,
3525
- body: getCdpBodyFromBiDiBytesValue(body),
3526
- });
3665
+ try {
3666
+ await request.provideResponse({
3667
+ responseCode,
3668
+ responsePhrase,
3669
+ responseHeaders,
3670
+ body: getCdpBodyFromBiDiBytesValue(body),
3671
+ });
3672
+ }
3673
+ catch (error) {
3674
+ throw NetworkProcessor.wrapInterceptionError(error);
3675
+ }
3527
3676
  return {};
3528
3677
  }
3529
3678
  async removeIntercept(params) {
@@ -3550,6 +3699,29 @@ var mapperTab = (function () {
3550
3699
  }
3551
3700
  return request;
3552
3701
  }
3702
+ /**
3703
+ * Validate https://fetch.spec.whatwg.org/#header-value
3704
+ */
3705
+ static validateHeaders(headers) {
3706
+ for (const header of headers) {
3707
+ let headerValue;
3708
+ if (header.value.type === 'string') {
3709
+ headerValue = header.value.value;
3710
+ }
3711
+ else {
3712
+ headerValue = atob(header.value.value);
3713
+ }
3714
+ if (headerValue !== headerValue.trim() ||
3715
+ headerValue.includes('\n') ||
3716
+ headerValue.includes('\0')) {
3717
+ throw new protocol_js_1$h.InvalidArgumentException(`Header value '${headerValue}' is not acceptable value`);
3718
+ }
3719
+ }
3720
+ }
3721
+ static isMethodValid(method) {
3722
+ // https://httpwg.org/specs/rfc9110.html#method.overview
3723
+ return /^[!#$%&'*+\-.^_`|~a-zA-Z\d]+$/.test(method);
3724
+ }
3553
3725
  /**
3554
3726
  * Attempts to parse the given url.
3555
3727
  * Throws an InvalidArgumentException if the url is invalid.
@@ -3639,6 +3811,13 @@ var mapperTab = (function () {
3639
3811
  }
3640
3812
  });
3641
3813
  }
3814
+ static wrapInterceptionError(error) {
3815
+ // https://source.chromium.org/chromium/chromium/src/+/main:content/browser/devtools/protocol/fetch_handler.cc;l=169
3816
+ if (error?.message.includes('Invalid header')) {
3817
+ return new protocol_js_1$h.InvalidArgumentException('Invalid header');
3818
+ }
3819
+ return error;
3820
+ }
3642
3821
  }
3643
3822
  NetworkProcessor$1.NetworkProcessor = NetworkProcessor;
3644
3823
  /**
@@ -3819,7 +3998,7 @@ var mapperTab = (function () {
3819
3998
  Object.defineProperty(ChannelProxy$1, "__esModule", { value: true });
3820
3999
  ChannelProxy$1.ChannelProxy = void 0;
3821
4000
  const protocol_js_1$f = protocol;
3822
- const log_js_1$c = log$1;
4001
+ const log_js_1$d = log$1;
3823
4002
  const uuid_js_1$3 = uuid;
3824
4003
  /**
3825
4004
  * Used to send messages from realm to BiDi user.
@@ -3849,7 +4028,7 @@ var mapperTab = (function () {
3849
4028
  void this.#startListener(realm, channelHandle, eventManager);
3850
4029
  }
3851
4030
  catch (error) {
3852
- this.#logger?.(log_js_1$c.LogType.debugError, error);
4031
+ this.#logger?.(log_js_1$d.LogType.debugError, error);
3853
4032
  }
3854
4033
  }
3855
4034
  /**
@@ -3956,7 +4135,7 @@ var mapperTab = (function () {
3956
4135
  catch (error) {
3957
4136
  // If an error is thrown, then the channel is permanently broken, so we
3958
4137
  // exit the loop.
3959
- this.#logger?.(log_js_1$c.LogType.debugError, error);
4138
+ this.#logger?.(log_js_1$d.LogType.debugError, error);
3960
4139
  break;
3961
4140
  }
3962
4141
  }
@@ -4315,7 +4494,7 @@ var mapperTab = (function () {
4315
4494
  StorageProcessor$1.StorageProcessor = void 0;
4316
4495
  const protocol_js_1$d = protocol;
4317
4496
  const assert_js_1$3 = assert$1;
4318
- const log_js_1$b = log$1;
4497
+ const log_js_1$c = log$1;
4319
4498
  const NetworkProcessor_js_1$1 = NetworkProcessor$1;
4320
4499
  const NetworkUtils_js_1$2 = NetworkUtils;
4321
4500
  /**
@@ -4351,7 +4530,7 @@ var mapperTab = (function () {
4351
4530
  // `sourceOrigin` partition key, only cookies with the requested source origin
4352
4531
  // are returned.
4353
4532
  (c) => partitionKey.sourceOrigin === undefined ||
4354
- c.partitionKey === partitionKey.sourceOrigin)
4533
+ c.partitionKey?.topLevelSite === partitionKey.sourceOrigin)
4355
4534
  .filter((cdpCookie) => {
4356
4535
  const bidiCookie = (0, NetworkUtils_js_1$2.cdpToBiDiCookie)(cdpCookie);
4357
4536
  return this.#matchCookie(bidiCookie, params.filter);
@@ -4390,7 +4569,7 @@ var mapperTab = (function () {
4390
4569
  // `sourceOrigin` partition key, only cookies with the requested source origin
4391
4570
  // are returned.
4392
4571
  (c) => partitionKey.sourceOrigin === undefined ||
4393
- c.partitionKey === partitionKey.sourceOrigin)
4572
+ c.partitionKey?.topLevelSite === partitionKey.sourceOrigin)
4394
4573
  .map((c) => (0, NetworkUtils_js_1$2.cdpToBiDiCookie)(c))
4395
4574
  .filter((c) => this.#matchCookie(c, params.filter));
4396
4575
  return {
@@ -4412,7 +4591,7 @@ var mapperTab = (function () {
4412
4591
  // If the user context is not found, special error is thrown.
4413
4592
  throw new protocol_js_1$d.NoSuchUserContextException(err.message);
4414
4593
  }
4415
- this.#logger?.(log_js_1$b.LogType.debugError, err);
4594
+ this.#logger?.(log_js_1$c.LogType.debugError, err);
4416
4595
  throw new protocol_js_1$d.UnableToSetCookieException(err.toString());
4417
4596
  }
4418
4597
  return {
@@ -4463,7 +4642,7 @@ var mapperTab = (function () {
4463
4642
  }
4464
4643
  }
4465
4644
  if (unsupportedPartitionKeys.size > 0) {
4466
- this.#logger?.(log_js_1$b.LogType.debugInfo, `Unsupported partition keys: ${JSON.stringify(Object.fromEntries(unsupportedPartitionKeys))}`);
4645
+ this.#logger?.(log_js_1$c.LogType.debugInfo, `Unsupported partition keys: ${JSON.stringify(Object.fromEntries(unsupportedPartitionKeys))}`);
4467
4646
  }
4468
4647
  // Set `userContext` to `default` if not provided, as it's required in Chromium.
4469
4648
  const userContext = descriptor.userContext ?? 'default';
@@ -4578,7 +4757,7 @@ var mapperTab = (function () {
4578
4757
  CommandProcessor$1.CommandProcessor = void 0;
4579
4758
  const protocol_js_1$c = protocol;
4580
4759
  const EventEmitter_js_1$3 = EventEmitter$1;
4581
- const log_js_1$a = log$1;
4760
+ const log_js_1$b = log$1;
4582
4761
  const BidiNoOpParser_js_1 = BidiNoOpParser$1;
4583
4762
  const BrowserProcessor_js_1 = BrowserProcessor$1;
4584
4763
  const CdpProcessor_js_1 = CdpProcessor$1;
@@ -4610,7 +4789,7 @@ var mapperTab = (function () {
4610
4789
  this.#logger = logger;
4611
4790
  // keep-sorted start block=yes
4612
4791
  this.#browserProcessor = new BrowserProcessor_js_1.BrowserProcessor(browserCdpClient);
4613
- this.#browsingContextProcessor = new BrowsingContextProcessor_js_1.BrowsingContextProcessor(browserCdpClient, browsingContextStorage);
4792
+ this.#browsingContextProcessor = new BrowsingContextProcessor_js_1.BrowsingContextProcessor(browserCdpClient, browsingContextStorage, eventManager);
4614
4793
  this.#cdpProcessor = new CdpProcessor_js_1.CdpProcessor(browsingContextStorage, realmStorage, cdpConnection, browserCdpClient);
4615
4794
  this.#inputProcessor = new InputProcessor_js_1.InputProcessor(browsingContextStorage, realmStorage);
4616
4795
  this.#networkProcessor = new NetworkProcessor_js_1.NetworkProcessor(browsingContextStorage, networkStorage);
@@ -4779,7 +4958,7 @@ var mapperTab = (function () {
4779
4958
  }
4780
4959
  else {
4781
4960
  const error = e;
4782
- this.#logger?.(log_js_1$a.LogType.bidi, error);
4961
+ this.#logger?.(log_js_1$b.LogType.bidi, error);
4783
4962
  this.emit("response" /* CommandProcessorEvents.Response */, {
4784
4963
  message: OutgoingMessage_js_1$1.OutgoingMessage.createResolved(new protocol_js_1$c.UnknownErrorException(error.message, error.stack).toErrorResponse(command.id), command.channel),
4785
4964
  event: command.method,
@@ -4817,11 +4996,18 @@ var mapperTab = (function () {
4817
4996
  class Deferred {
4818
4997
  #isFinished = false;
4819
4998
  #promise;
4999
+ #result;
4820
5000
  #resolve;
4821
5001
  #reject;
4822
5002
  get isFinished() {
4823
5003
  return this.#isFinished;
4824
5004
  }
5005
+ get result() {
5006
+ if (!this.#isFinished) {
5007
+ throw new Error('Deferred is not finished yet');
5008
+ }
5009
+ return this.#result;
5010
+ }
4825
5011
  constructor() {
4826
5012
  this.#promise = new Promise((resolve, reject) => {
4827
5013
  this.#resolve = resolve;
@@ -4840,6 +5026,7 @@ var mapperTab = (function () {
4840
5026
  return this.#promise.catch(onRejected);
4841
5027
  }
4842
5028
  resolve(value) {
5029
+ this.#result = value;
4843
5030
  if (!this.#isFinished) {
4844
5031
  this.#isFinished = true;
4845
5032
  this.#resolve(value);
@@ -4891,7 +5078,7 @@ var mapperTab = (function () {
4891
5078
  Object.defineProperty(Realm$1, "__esModule", { value: true });
4892
5079
  Realm$1.Realm = void 0;
4893
5080
  const protocol_js_1$b = protocol;
4894
- const log_js_1$9 = log$1;
5081
+ const log_js_1$a = log$1;
4895
5082
  const uuid_js_1$1 = uuid;
4896
5083
  const ChannelProxy_js_1 = ChannelProxy$1;
4897
5084
  class Realm {
@@ -4925,7 +5112,7 @@ var mapperTab = (function () {
4925
5112
  }
4926
5113
  else {
4927
5114
  // No need to await for the object to be released.
4928
- void this.#releaseObject(objectId).catch((error) => this.#logger?.(log_js_1$9.LogType.debugError, error));
5115
+ void this.#releaseObject(objectId).catch((error) => this.#logger?.(log_js_1$a.LogType.debugError, error));
4929
5116
  }
4930
5117
  }
4931
5118
  return bidiValue;
@@ -5593,11 +5780,11 @@ var mapperTab = (function () {
5593
5780
  const protocol_js_1$9 = protocol;
5594
5781
  const assert_js_1$2 = assert$1;
5595
5782
  const Deferred_js_1$2 = Deferred$1;
5596
- const log_js_1$8 = log$1;
5783
+ const log_js_1$9 = log$1;
5597
5784
  const unitConversions_js_1 = unitConversions;
5598
5785
  const WindowRealm_js_1$1 = WindowRealm$1;
5599
5786
  class BrowsingContextImpl {
5600
- static LOGGER_PREFIX = `${log_js_1$8.LogType.debug}:browsingContext`;
5787
+ static LOGGER_PREFIX = `${log_js_1$9.LogType.debug}:browsingContext`;
5601
5788
  /** The ID of this browsing context. */
5602
5789
  #id;
5603
5790
  userContext;
@@ -5616,16 +5803,17 @@ var mapperTab = (function () {
5616
5803
  #navigation = {
5617
5804
  withinDocument: new Deferred_js_1$2.Deferred(),
5618
5805
  };
5619
- #url = 'about:blank';
5806
+ #url;
5620
5807
  #eventManager;
5621
5808
  #realmStorage;
5622
5809
  #loaderId;
5623
5810
  #cdpTarget;
5624
- #maybeDefaultRealm;
5811
+ // The deferred will be resolved when the default realm is created.
5812
+ #defaultRealmDeferred = new Deferred_js_1$2.Deferred();
5625
5813
  #logger;
5626
5814
  // Keeps track of the previously set viewport.
5627
5815
  #previousViewport = { width: 0, height: 0 };
5628
- constructor(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, logger) {
5816
+ constructor(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, url, logger) {
5629
5817
  this.#cdpTarget = cdpTarget;
5630
5818
  this.#id = id;
5631
5819
  this.#parentId = parentId;
@@ -5634,9 +5822,10 @@ var mapperTab = (function () {
5634
5822
  this.#browsingContextStorage = browsingContextStorage;
5635
5823
  this.#realmStorage = realmStorage;
5636
5824
  this.#logger = logger;
5825
+ this.#url = url;
5637
5826
  }
5638
- static create(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, logger) {
5639
- const context = new BrowsingContextImpl(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, logger);
5827
+ static create(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, url, logger) {
5828
+ const context = new BrowsingContextImpl(id, parentId, userContext, cdpTarget, eventManager, browsingContextStorage, realmStorage, url, logger);
5640
5829
  context.#initListeners();
5641
5830
  browsingContextStorage.addContext(context);
5642
5831
  if (!context.isTopLevelContext()) {
@@ -5727,10 +5916,6 @@ var mapperTab = (function () {
5727
5916
  #deleteAllChildren() {
5728
5917
  this.directChildren.map((child) => child.dispose());
5729
5918
  }
5730
- get #defaultRealm() {
5731
- (0, assert_js_1$2.assert)(this.#maybeDefaultRealm, `No default realm for browsing context ${this.#id}`);
5732
- return this.#maybeDefaultRealm;
5733
- }
5734
5919
  get cdpTarget() {
5735
5920
  return this.#cdpTarget;
5736
5921
  }
@@ -5752,7 +5937,8 @@ var mapperTab = (function () {
5752
5937
  }
5753
5938
  async getOrCreateSandbox(sandbox) {
5754
5939
  if (sandbox === undefined || sandbox === '') {
5755
- return this.#defaultRealm;
5940
+ // Default realm is not guaranteed to be created at this point, so return a deferred.
5941
+ return await this.#defaultRealmDeferred;
5756
5942
  }
5757
5943
  let maybeSandboxes = this.#realmStorage.findRealms({
5758
5944
  browsingContextId: this.id,
@@ -5900,7 +6086,13 @@ var mapperTab = (function () {
5900
6086
  sandbox = name;
5901
6087
  // Sandbox should have the same origin as the context itself, but in CDP
5902
6088
  // it has an empty one.
5903
- origin = this.#defaultRealm.origin;
6089
+ if (!this.#defaultRealmDeferred.isFinished) {
6090
+ this.#logger?.(log_js_1$9.LogType.debugError, 'Unexpectedly, isolated realm created before the default one');
6091
+ }
6092
+ origin = this.#defaultRealmDeferred.isFinished
6093
+ ? this.#defaultRealmDeferred.result.origin
6094
+ : // This fallback is not expected to be ever reached.
6095
+ '';
5904
6096
  break;
5905
6097
  case 'default':
5906
6098
  origin = serializeOrigin(params.context.origin);
@@ -5910,7 +6102,7 @@ var mapperTab = (function () {
5910
6102
  }
5911
6103
  const realm = new WindowRealm_js_1$1.WindowRealm(this.id, this.#browsingContextStorage, this.#cdpTarget.cdpClient, this.#eventManager, id, this.#logger, origin, uniqueId, this.#realmStorage, sandbox);
5912
6104
  if (auxData.isDefault) {
5913
- this.#maybeDefaultRealm = realm;
6105
+ this.#defaultRealmDeferred.resolve(realm);
5914
6106
  // Initialize ChannelProxy listeners for all the channels of all the
5915
6107
  // preload scripts related to this BrowsingContext.
5916
6108
  // TODO: extend for not default realms by the sandbox name.
@@ -5920,12 +6112,21 @@ var mapperTab = (function () {
5920
6112
  }
5921
6113
  });
5922
6114
  this.#cdpTarget.cdpClient.on('Runtime.executionContextDestroyed', (params) => {
6115
+ if (this.#defaultRealmDeferred.isFinished &&
6116
+ this.#defaultRealmDeferred.result.executionContextId ===
6117
+ params.executionContextId) {
6118
+ this.#defaultRealmDeferred = new Deferred_js_1$2.Deferred();
6119
+ }
5923
6120
  this.#realmStorage.deleteRealms({
5924
6121
  cdpSessionId: this.#cdpTarget.cdpSessionId,
5925
6122
  executionContextId: params.executionContextId,
5926
6123
  });
5927
6124
  });
5928
6125
  this.#cdpTarget.cdpClient.on('Runtime.executionContextsCleared', () => {
6126
+ if (!this.#defaultRealmDeferred.isFinished) {
6127
+ this.#defaultRealmDeferred.reject(new protocol_js_1$9.UnknownErrorException('execution contexts cleared'));
6128
+ }
6129
+ this.#defaultRealmDeferred = new Deferred_js_1$2.Deferred();
5929
6130
  this.#realmStorage.deleteRealms({
5930
6131
  cdpSessionId: this.#cdpTarget.cdpSessionId,
5931
6132
  });
@@ -5950,8 +6151,9 @@ var mapperTab = (function () {
5950
6151
  context: this.id,
5951
6152
  type: params.type,
5952
6153
  message: params.message,
5953
- // Don't set the value if empty string
5954
- defaultValue: params.defaultPrompt || undefined,
6154
+ ...(params.type === 'prompt'
6155
+ ? { defaultValue: params.defaultPrompt }
6156
+ : {}),
5955
6157
  },
5956
6158
  }, this.id);
5957
6159
  });
@@ -6160,9 +6362,18 @@ var mapperTab = (function () {
6160
6362
  (0, assert_js_1$2.assert)(originResult.type === 'success');
6161
6363
  const origin = deserializeDOMRect(originResult.result);
6162
6364
  (0, assert_js_1$2.assert)(origin);
6163
- const rect = params.clip
6164
- ? getIntersectionRect(await this.#parseRect(params.clip), origin)
6165
- : origin;
6365
+ let rect = origin;
6366
+ if (params.clip) {
6367
+ const clip = params.clip;
6368
+ if (params.origin === 'viewport' && clip.type === 'box') {
6369
+ // For viewport origin, the clip is relative to the viewport, while the CDP
6370
+ // screenshot is relative to the document. So correction for the viewport position
6371
+ // is required.
6372
+ clip.x += origin.x;
6373
+ clip.y += origin.y;
6374
+ }
6375
+ rect = getIntersectionRect(await this.#parseRect(clip), origin);
6376
+ }
6166
6377
  if (rect.width === 0 || rect.height === 0) {
6167
6378
  throw new protocol_js_1$9.UnableToCaptureScreenException(`Unable to capture screenshot with zero dimensions: width=${rect.width}, height=${rect.height}`);
6168
6379
  }
@@ -6315,7 +6526,7 @@ var mapperTab = (function () {
6315
6526
  }
6316
6527
  async locateNodes(params) {
6317
6528
  // TODO: create a dedicated sandbox instead of `#defaultRealm`.
6318
- return await this.#locateNodesByLocator(this.#defaultRealm, params.locator, params.startNodes ?? [], params.maxNodeCount, params.serializationOptions);
6529
+ return await this.#locateNodesByLocator(await this.#defaultRealmDeferred, params.locator, params.startNodes ?? [], params.maxNodeCount, params.serializationOptions);
6319
6530
  }
6320
6531
  async #getLocatorDelegate(realm, locator, maxNodeCount, startNodes) {
6321
6532
  switch (locator.type) {
@@ -6323,8 +6534,10 @@ var mapperTab = (function () {
6323
6534
  return {
6324
6535
  functionDeclaration: String((cssSelector, maxNodeCount, ...startNodes) => {
6325
6536
  const locateNodesUsingCss = (element) => {
6326
- if (!(element instanceof HTMLElement)) {
6327
- throw new Error('startNodes in css selector should be HTMLElement');
6537
+ if (!(element instanceof HTMLElement ||
6538
+ element instanceof Document ||
6539
+ element instanceof DocumentFragment)) {
6540
+ throw new Error('startNodes in css selector should be HTMLElement, Document or DocumentFragment');
6328
6541
  }
6329
6542
  return [...element.querySelectorAll(cssSelector)];
6330
6543
  };
@@ -6390,8 +6603,21 @@ var mapperTab = (function () {
6390
6603
  const searchText = ignoreCase
6391
6604
  ? innerTextSelector.toUpperCase()
6392
6605
  : innerTextSelector;
6393
- const locateNodesUsingInnerText = (element, currentMaxDepth) => {
6606
+ const locateNodesUsingInnerText = (node, currentMaxDepth) => {
6394
6607
  const returnedNodes = [];
6608
+ if (node instanceof DocumentFragment ||
6609
+ node instanceof Document) {
6610
+ const children = [...node.children];
6611
+ children.forEach((child) =>
6612
+ // `currentMaxDepth` is not decremented intentionally according to
6613
+ // https://github.com/w3c/webdriver-bidi/pull/713.
6614
+ returnedNodes.push(...locateNodesUsingInnerText(child, currentMaxDepth)));
6615
+ return returnedNodes;
6616
+ }
6617
+ if (!(node instanceof HTMLElement)) {
6618
+ return [];
6619
+ }
6620
+ const element = node;
6395
6621
  const nodeInnerText = ignoreCase
6396
6622
  ? element.innerText?.toUpperCase()
6397
6623
  : element.innerText;
@@ -6418,7 +6644,7 @@ var mapperTab = (function () {
6418
6644
  else {
6419
6645
  const childNodeMatches =
6420
6646
  // Don't search deeper if `maxDepth` is reached.
6421
- currentMaxDepth === 0
6647
+ currentMaxDepth <= 0
6422
6648
  ? []
6423
6649
  : childNodes
6424
6650
  .map((child) => locateNodesUsingInnerText(child, currentMaxDepth - 1))
@@ -6436,9 +6662,8 @@ var mapperTab = (function () {
6436
6662
  // TODO: stop search early if `maxNodeCount` is reached.
6437
6663
  return returnedNodes;
6438
6664
  };
6439
- // TODO: add maxDepth.
6440
6665
  // TODO: stop search early if `maxNodeCount` is reached.
6441
- startNodes = startNodes.length > 0 ? startNodes : [document.body];
6666
+ startNodes = startNodes.length > 0 ? startNodes : [document];
6442
6667
  const returnedNodes = startNodes
6443
6668
  .map((startNode) =>
6444
6669
  // TODO: stop search early if `maxNodeCount` is reached.
@@ -6470,7 +6695,7 @@ var mapperTab = (function () {
6470
6695
  }
6471
6696
  // The next two commands cause a11y caches for the target to be
6472
6697
  // preserved. We probably do not need to disable them if the
6473
- // client is using a11y features but we could by calling
6698
+ // client is using a11y features, but we could by calling
6474
6699
  // Accessibility.disable.
6475
6700
  await Promise.all([
6476
6701
  this.#cdpTarget.cdpClient.sendCommand('Accessibility.enable'),
@@ -6570,8 +6795,8 @@ var mapperTab = (function () {
6570
6795
  }
6571
6796
  // Heuristic to detect if the `startNode` is not an `HTMLElement` in css selector.
6572
6797
  if (locatorResult.exceptionDetails.text ===
6573
- 'Error: startNodes in css selector should be HTMLElement') {
6574
- throw new protocol_js_1$9.InvalidArgumentException(`startNodes in css selector should be HTMLElement`);
6798
+ 'Error: startNodes in css selector should be HTMLElement, Document or DocumentFragment') {
6799
+ throw new protocol_js_1$9.InvalidArgumentException('startNodes in css selector should be HTMLElement, Document or DocumentFragment');
6575
6800
  }
6576
6801
  throw new protocol_js_1$9.UnknownErrorException(`Unexpected error in selector script: ${locatorResult.exceptionDetails.text}`);
6577
6802
  }
@@ -6946,7 +7171,7 @@ var mapperTab = (function () {
6946
7171
  Object.defineProperty(LogManager$1, "__esModule", { value: true });
6947
7172
  LogManager$1.LogManager = void 0;
6948
7173
  const protocol_js_1$8 = protocol;
6949
- const log_js_1$7 = log$1;
7174
+ const log_js_1$8 = log$1;
6950
7175
  const logHelper_js_1 = logHelper;
6951
7176
  /** Converts CDP StackTrace object to BiDi StackTrace object. */
6952
7177
  function getBidiStackTrace(cdpStackTrace) {
@@ -6998,7 +7223,7 @@ var mapperTab = (function () {
6998
7223
  });
6999
7224
  if (realm === undefined) {
7000
7225
  // Ignore exceptions not attached to any realm.
7001
- this.#logger?.(log_js_1$7.LogType.cdp, params);
7226
+ this.#logger?.(log_js_1$8.LogType.cdp, params);
7002
7227
  return;
7003
7228
  }
7004
7229
  const argsPromise = realm === undefined
@@ -7037,7 +7262,7 @@ var mapperTab = (function () {
7037
7262
  });
7038
7263
  if (realm === undefined) {
7039
7264
  // Ignore exceptions not attached to any realm.
7040
- this.#logger?.(log_js_1$7.LogType.cdp, params);
7265
+ this.#logger?.(log_js_1$8.LogType.cdp, params);
7041
7266
  return;
7042
7267
  }
7043
7268
  for (const browsingContext of realm.associatedBrowsingContexts) {
@@ -7078,17 +7303,21 @@ var mapperTab = (function () {
7078
7303
  CdpTarget$1.CdpTarget = void 0;
7079
7304
  const chromium_bidi_js_1 = chromiumBidi;
7080
7305
  const Deferred_js_1$1 = Deferred$1;
7306
+ const log_js_1$7 = log$1;
7307
+ const BrowsingContextImpl_js_1$1 = BrowsingContextImpl$1;
7081
7308
  const LogManager_js_1 = LogManager$1;
7082
7309
  class CdpTarget {
7083
7310
  #id;
7084
7311
  #cdpClient;
7085
7312
  #browserCdpClient;
7313
+ #realmStorage;
7086
7314
  #eventManager;
7087
7315
  #preloadScriptStorage;
7088
7316
  #browsingContextStorage;
7089
7317
  #networkStorage;
7090
7318
  #unblocked = new Deferred_js_1$1.Deferred();
7091
7319
  #acceptInsecureCerts;
7320
+ #logger;
7092
7321
  #networkDomainEnabled = false;
7093
7322
  #fetchDomainStages = {
7094
7323
  request: false,
@@ -7096,7 +7325,7 @@ var mapperTab = (function () {
7096
7325
  auth: false,
7097
7326
  };
7098
7327
  static create(targetId, cdpClient, browserCdpClient, realmStorage, eventManager, preloadScriptStorage, browsingContextStorage, networkStorage, acceptInsecureCerts, logger) {
7099
- const cdpTarget = new CdpTarget(targetId, cdpClient, browserCdpClient, eventManager, preloadScriptStorage, browsingContextStorage, networkStorage, acceptInsecureCerts);
7328
+ const cdpTarget = new CdpTarget(targetId, cdpClient, browserCdpClient, eventManager, realmStorage, preloadScriptStorage, browsingContextStorage, networkStorage, acceptInsecureCerts, logger);
7100
7329
  LogManager_js_1.LogManager.create(cdpTarget, realmStorage, eventManager, logger);
7101
7330
  cdpTarget.#setEventListeners();
7102
7331
  // No need to await.
@@ -7104,15 +7333,17 @@ var mapperTab = (function () {
7104
7333
  void cdpTarget.#unblock();
7105
7334
  return cdpTarget;
7106
7335
  }
7107
- constructor(targetId, cdpClient, browserCdpClient, eventManager, preloadScriptStorage, browsingContextStorage, networkStorage, acceptInsecureCerts) {
7336
+ constructor(targetId, cdpClient, browserCdpClient, eventManager, realmStorage, preloadScriptStorage, browsingContextStorage, networkStorage, acceptInsecureCerts, logger) {
7108
7337
  this.#id = targetId;
7109
7338
  this.#cdpClient = cdpClient;
7110
7339
  this.#browserCdpClient = browserCdpClient;
7111
7340
  this.#eventManager = eventManager;
7341
+ this.#realmStorage = realmStorage;
7112
7342
  this.#preloadScriptStorage = preloadScriptStorage;
7113
7343
  this.#networkStorage = networkStorage;
7114
7344
  this.#browsingContextStorage = browsingContextStorage;
7115
7345
  this.#acceptInsecureCerts = acceptInsecureCerts;
7346
+ this.#logger = logger;
7116
7347
  }
7117
7348
  /** Returns a deferred that resolves when the target is unblocked. */
7118
7349
  get unblocked() {
@@ -7138,8 +7369,19 @@ var mapperTab = (function () {
7138
7369
  async #unblock() {
7139
7370
  try {
7140
7371
  await Promise.all([
7141
- this.#cdpClient.sendCommand('Runtime.enable'),
7142
7372
  this.#cdpClient.sendCommand('Page.enable'),
7373
+ // There can be some existing frames in the target, if reconnecting to an
7374
+ // existing browser instance, e.g. via Puppeteer. Need to restore the browsing
7375
+ // contexts for the frames to correctly handle further events, like
7376
+ // `Runtime.executionContextCreated`.
7377
+ // It's important to schedule this task together with enabling domains commands to
7378
+ // prepare the tree before the events (e.g. Runtime.executionContextCreated) start
7379
+ // coming.
7380
+ // https://github.com/GoogleChromeLabs/chromium-bidi/issues/2282
7381
+ this.#cdpClient
7382
+ .sendCommand('Page.getFrameTree')
7383
+ .then((frameTree) => this.#restoreFrameTreeState(frameTree.frameTree)),
7384
+ this.#cdpClient.sendCommand('Runtime.enable'),
7143
7385
  this.#cdpClient.sendCommand('Page.setLifecycleEventsEnabled', {
7144
7386
  enabled: true,
7145
7387
  }),
@@ -7158,6 +7400,7 @@ var mapperTab = (function () {
7158
7400
  ]);
7159
7401
  }
7160
7402
  catch (error) {
7403
+ this.#logger?.(log_js_1$7.LogType.debugError, 'Failed to unblock target', error);
7161
7404
  // The target might have been closed before the initialization finished.
7162
7405
  if (!this.#cdpClient.isCloseError(error)) {
7163
7406
  this.#unblocked.resolve({
@@ -7172,6 +7415,17 @@ var mapperTab = (function () {
7172
7415
  value: undefined,
7173
7416
  });
7174
7417
  }
7418
+ #restoreFrameTreeState(frameTree) {
7419
+ const frame = frameTree.frame;
7420
+ if (this.#browsingContextStorage.findContext(frame.id) === undefined &&
7421
+ frame.parentId !== undefined) {
7422
+ // Can restore only not yet known nested frames. The top-level frame is created
7423
+ // when the target is attached.
7424
+ const parentBrowsingContext = this.#browsingContextStorage.getContext(frame.parentId);
7425
+ BrowsingContextImpl_js_1$1.BrowsingContextImpl.create(frame.id, frame.parentId, parentBrowsingContext.userContext, parentBrowsingContext.cdpTarget, this.#eventManager, this.#browsingContextStorage, this.#realmStorage, frame.url, this.#logger);
7426
+ }
7427
+ frameTree.childFrames?.map((frameTree) => this.#restoreFrameTreeState(frameTree));
7428
+ }
7175
7429
  async toggleFetchIfNeeded() {
7176
7430
  const stages = this.#networkStorage.getInterceptionStages(this.topLevelId);
7177
7431
  if (
@@ -7330,7 +7584,10 @@ var mapperTab = (function () {
7330
7584
  #handleFrameAttachedEvent(params) {
7331
7585
  const parentBrowsingContext = this.#browsingContextStorage.findContext(params.parentFrameId);
7332
7586
  if (parentBrowsingContext !== undefined) {
7333
- BrowsingContextImpl_js_1.BrowsingContextImpl.create(params.frameId, params.parentFrameId, parentBrowsingContext.userContext, parentBrowsingContext.cdpTarget, this.#eventManager, this.#browsingContextStorage, this.#realmStorage, this.#logger);
7587
+ BrowsingContextImpl_js_1.BrowsingContextImpl.create(params.frameId, params.parentFrameId, parentBrowsingContext.userContext, parentBrowsingContext.cdpTarget, this.#eventManager, this.#browsingContextStorage, this.#realmStorage,
7588
+ // At this point, we don't know the URL of the frame yet, so it will be updated
7589
+ // later.
7590
+ 'about:blank', this.#logger);
7334
7591
  }
7335
7592
  }
7336
7593
  #handleFrameDetachedEvent(params) {
@@ -7361,7 +7618,16 @@ var mapperTab = (function () {
7361
7618
  ? targetInfo.browserContextId
7362
7619
  : 'default';
7363
7620
  // New context.
7364
- BrowsingContextImpl_js_1.BrowsingContextImpl.create(targetInfo.targetId, null, userContext, cdpTarget, this.#eventManager, this.#browsingContextStorage, this.#realmStorage, this.#logger);
7621
+ BrowsingContextImpl_js_1.BrowsingContextImpl.create(targetInfo.targetId, null, userContext, cdpTarget, this.#eventManager, this.#browsingContextStorage, this.#realmStorage,
7622
+ // Hack: when a new target created, CDP emits targetInfoChanged with an empty
7623
+ // url, and navigates it to about:blank later. When the event is emitted for
7624
+ // an existing target (reconnect), the url is already known, and navigation
7625
+ // events will not be emitted anymore. Replacing empty url with `about:blank`
7626
+ // allows to handle both cases in the same way.
7627
+ // "7.3.2.1 Creating browsing contexts".
7628
+ // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-browsing-contexts
7629
+ // TODO: check who to deal with non-null creator and its `creatorOrigin`.
7630
+ targetInfo.url === '' ? 'about:blank' : targetInfo.url, this.#logger);
7365
7631
  }
7366
7632
  return;
7367
7633
  }
@@ -7635,6 +7901,7 @@ var mapperTab = (function () {
7635
7901
  '';
7636
7902
  const url = this.#response.info?.url ??
7637
7903
  this.#response.paused?.request.url ??
7904
+ this.#request.overrides?.url ??
7638
7905
  this.#request.auth?.request.url ??
7639
7906
  this.#request.info?.request.url ??
7640
7907
  this.#request.paused?.request.url ??
@@ -7642,7 +7909,8 @@ var mapperTab = (function () {
7642
7909
  return `${url}${fragment}`;
7643
7910
  }
7644
7911
  get method() {
7645
- return (this.#request.info?.request.method ??
7912
+ return (this.#request.overrides?.method ??
7913
+ this.#request.info?.request.method ??
7646
7914
  this.#request.paused?.request.method ??
7647
7915
  this.#request.auth?.request.method ??
7648
7916
  this.#response.paused?.request.method ??
@@ -7837,15 +8105,21 @@ var mapperTab = (function () {
7837
8105
  });
7838
8106
  }
7839
8107
  /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-continueRequest */
7840
- async continueRequest({ url, method, headers, postData, } = {}) {
8108
+ async continueRequest(overrides = {}) {
7841
8109
  (0, assert_js_1.assert)(this.#fetchId, 'Network Interception not set-up.');
7842
8110
  await this.cdpClient.sendCommand('Fetch.continueRequest', {
7843
8111
  requestId: this.#fetchId,
7844
- url,
7845
- method,
7846
- headers,
7847
- postData,
8112
+ url: overrides.url,
8113
+ method: overrides.method,
8114
+ headers: overrides.headers,
8115
+ postData: overrides.postData,
7848
8116
  });
8117
+ // TODO: Store postData's size only
8118
+ this.#request.overrides = {
8119
+ url: overrides.url,
8120
+ method: overrides.method,
8121
+ headers: overrides.headers,
8122
+ };
7849
8123
  this.#interceptPhase = undefined;
7850
8124
  }
7851
8125
  /** @see https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#method-continueResponse */
@@ -7945,8 +8219,14 @@ var mapperTab = (function () {
7945
8219
  if (this.#response.info?.fromDiskCache) {
7946
8220
  this.#response.extraInfo = undefined;
7947
8221
  }
7948
- // TODO: get headers from Fetch.requestPaused
7949
- const headers = (0, NetworkUtils_js_1$1.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#response.info?.headers);
8222
+ const headers = [
8223
+ ...(0, NetworkUtils_js_1$1.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#response.info?.headers),
8224
+ ...(0, NetworkUtils_js_1$1.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#response.extraInfo?.headers),
8225
+ // TODO: Verify how to dedupe these
8226
+ // ...bidiNetworkHeadersFromCdpNetworkHeadersEntries(
8227
+ // this.#response.paused?.responseHeaders
8228
+ // ),
8229
+ ];
7950
8230
  // TODO: get headers from Fetch.requestPaused
7951
8231
  const authChallenges = this.#authChallenges(this.#response.info?.headers ?? {});
7952
8232
  return {
@@ -7987,7 +8267,18 @@ var mapperTab = (function () {
7987
8267
  const cookies = this.#request.extraInfo
7988
8268
  ? NetworkRequest.#getCookies(this.#request.extraInfo.associatedCookies)
7989
8269
  : [];
7990
- const headers = (0, NetworkUtils_js_1$1.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#request.info?.request.headers);
8270
+ let headers = [];
8271
+ if (this.#request.overrides?.headers) {
8272
+ headers = [
8273
+ ...(0, NetworkUtils_js_1$1.bidiNetworkHeadersFromCdpNetworkHeadersEntries)(this.#request.overrides?.headers),
8274
+ ];
8275
+ }
8276
+ else {
8277
+ headers = [
8278
+ ...(0, NetworkUtils_js_1$1.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#request.info?.request.headers),
8279
+ ...(0, NetworkUtils_js_1$1.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#request.extraInfo?.headers),
8280
+ ];
8281
+ }
7991
8282
  return {
7992
8283
  request: this.#id,
7993
8284
  url: this.url,
@@ -8516,6 +8807,66 @@ var mapperTab = (function () {
8516
8807
  }
8517
8808
  DefaultMap$1.DefaultMap = DefaultMap;
8518
8809
 
8810
+ var DistinctValues = {};
8811
+
8812
+ /*
8813
+ * Copyright 2024 Google LLC.
8814
+ * Copyright (c) Microsoft Corporation.
8815
+ *
8816
+ * Licensed under the Apache License, Version 2.0 (the "License");
8817
+ * you may not use this file except in compliance with the License.
8818
+ * You may obtain a copy of the License at
8819
+ *
8820
+ * http://www.apache.org/licenses/LICENSE-2.0
8821
+ *
8822
+ * Unless required by applicable law or agreed to in writing, software
8823
+ * distributed under the License is distributed on an "AS IS" BASIS,
8824
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8825
+ * See the License for the specific language governing permissions and
8826
+ * limitations under the License.
8827
+ */
8828
+ Object.defineProperty(DistinctValues, "__esModule", { value: true });
8829
+ DistinctValues.deterministicJSONStringify = DistinctValues.distinctValues = void 0;
8830
+ /**
8831
+ * Returns an array of distinct values. Order is not guaranteed.
8832
+ * @param values - The values to filter. Should be JSON-serializable.
8833
+ * @return - An array of distinct values.
8834
+ */
8835
+ function distinctValues(values) {
8836
+ const map = new Map();
8837
+ for (const value of values) {
8838
+ map.set(deterministicJSONStringify(value), value);
8839
+ }
8840
+ return Array.from(map.values());
8841
+ }
8842
+ DistinctValues.distinctValues = distinctValues;
8843
+ /**
8844
+ * Returns a stringified version of the object with keys sorted. This is required to
8845
+ * ensure that the stringified version of an object is deterministic independent of the
8846
+ * order of keys.
8847
+ * @param obj
8848
+ * @return {string}
8849
+ */
8850
+ function deterministicJSONStringify(obj) {
8851
+ return JSON.stringify(normalizeObject(obj));
8852
+ }
8853
+ DistinctValues.deterministicJSONStringify = deterministicJSONStringify;
8854
+ function normalizeObject(obj) {
8855
+ if (obj === undefined ||
8856
+ obj === null ||
8857
+ Array.isArray(obj) ||
8858
+ typeof obj !== 'object') {
8859
+ return obj;
8860
+ }
8861
+ // Copy the original object key and values to a new object in sorted order.
8862
+ const newObj = {};
8863
+ for (const key of Object.keys(obj).sort()) {
8864
+ const value = obj[key];
8865
+ newObj[key] = normalizeObject(value); // Recursively sort nested objects
8866
+ }
8867
+ return newObj;
8868
+ }
8869
+
8519
8870
  var IdWrapper$1 = {};
8520
8871
 
8521
8872
  /**
@@ -8742,23 +9093,37 @@ var mapperTab = (function () {
8742
9093
  }
8743
9094
  return false;
8744
9095
  }
9096
+ /**
9097
+ * Subscribes to event in the given context and channel.
9098
+ * @param {EventNames} event
9099
+ * @param {BrowsingContext.BrowsingContext | null} contextId
9100
+ * @param {BidiPlusChannel} channel
9101
+ * @return {SubscriptionItem[]} List of
9102
+ * subscriptions. If the event is a whole module, it will return all the specific
9103
+ * events. If the contextId is null, it will return all the top-level contexts which were
9104
+ * not subscribed before the command.
9105
+ */
8745
9106
  subscribe(event, contextId, channel) {
8746
9107
  // All the subscriptions are handled on the top-level contexts.
8747
9108
  contextId = this.#browsingContextStorage.findTopLevelContextId(contextId);
8748
9109
  // Check if subscribed event is a whole module
8749
9110
  switch (event) {
8750
9111
  case protocol_js_1$2.ChromiumBidi.BiDiModule.BrowsingContext:
8751
- Object.values(protocol_js_1$2.ChromiumBidi.BrowsingContext.EventNames).map((specificEvent) => this.subscribe(specificEvent, contextId, channel));
8752
- return;
9112
+ return Object.values(protocol_js_1$2.ChromiumBidi.BrowsingContext.EventNames)
9113
+ .map((specificEvent) => this.subscribe(specificEvent, contextId, channel))
9114
+ .flat();
8753
9115
  case protocol_js_1$2.ChromiumBidi.BiDiModule.Log:
8754
- Object.values(protocol_js_1$2.ChromiumBidi.Log.EventNames).map((specificEvent) => this.subscribe(specificEvent, contextId, channel));
8755
- return;
9116
+ return Object.values(protocol_js_1$2.ChromiumBidi.Log.EventNames)
9117
+ .map((specificEvent) => this.subscribe(specificEvent, contextId, channel))
9118
+ .flat();
8756
9119
  case protocol_js_1$2.ChromiumBidi.BiDiModule.Network:
8757
- Object.values(protocol_js_1$2.ChromiumBidi.Network.EventNames).map((specificEvent) => this.subscribe(specificEvent, contextId, channel));
8758
- return;
9120
+ return Object.values(protocol_js_1$2.ChromiumBidi.Network.EventNames)
9121
+ .map((specificEvent) => this.subscribe(specificEvent, contextId, channel))
9122
+ .flat();
8759
9123
  case protocol_js_1$2.ChromiumBidi.BiDiModule.Script:
8760
- Object.values(protocol_js_1$2.ChromiumBidi.Script.EventNames).map((specificEvent) => this.subscribe(specificEvent, contextId, channel));
8761
- return;
9124
+ return Object.values(protocol_js_1$2.ChromiumBidi.Script.EventNames)
9125
+ .map((specificEvent) => this.subscribe(specificEvent, contextId, channel))
9126
+ .flat();
8762
9127
  // Intentionally left empty.
8763
9128
  }
8764
9129
  if (!this.#channelToContextToEventMap.has(channel)) {
@@ -8769,11 +9134,20 @@ var mapperTab = (function () {
8769
9134
  contextToEventMap.set(contextId, new Map());
8770
9135
  }
8771
9136
  const eventMap = contextToEventMap.get(contextId);
8772
- // Do not re-subscribe to events to keep the priority.
8773
- if (eventMap.has(event)) {
8774
- return;
9137
+ const affectedContextIds = (contextId === null
9138
+ ? this.#browsingContextStorage.getTopLevelContexts().map((c) => c.id)
9139
+ : [contextId])
9140
+ // There can be contexts that are already subscribed to the event. Do not include
9141
+ // them to the output.
9142
+ .filter((contextId) => !this.isSubscribedTo(event, contextId));
9143
+ if (!eventMap.has(event)) {
9144
+ // Add subscription only if it's not already subscribed.
9145
+ eventMap.set(event, this.#subscriptionPriority++);
8775
9146
  }
8776
- eventMap.set(event, this.#subscriptionPriority++);
9147
+ return affectedContextIds.map((contextId) => ({
9148
+ event,
9149
+ contextId,
9150
+ }));
8777
9151
  }
8778
9152
  /**
8779
9153
  * Unsubscribes atomically from all events in the given contexts and channel.
@@ -8848,6 +9222,7 @@ var mapperTab = (function () {
8848
9222
  const protocol_js_1$1 = protocol;
8849
9223
  const Buffer_js_1 = Buffer$2;
8850
9224
  const DefaultMap_js_1 = DefaultMap$1;
9225
+ const DistinctValues_js_1 = DistinctValues;
8851
9226
  const EventEmitter_js_1$2 = EventEmitter$1;
8852
9227
  const IdWrapper_js_1 = IdWrapper$1;
8853
9228
  const OutgoingMessage_js_1 = OutgoingMessage$1;
@@ -8895,10 +9270,15 @@ var mapperTab = (function () {
8895
9270
  #lastMessageSent = new Map();
8896
9271
  #subscriptionManager;
8897
9272
  #browsingContextStorage;
9273
+ /**
9274
+ * Map of event name to hooks to be called when client is subscribed to the event.
9275
+ */
9276
+ #subscribeHooks;
8898
9277
  constructor(browsingContextStorage) {
8899
9278
  super();
8900
9279
  this.#browsingContextStorage = browsingContextStorage;
8901
9280
  this.#subscriptionManager = new SubscriptionManager_js_1.SubscriptionManager(browsingContextStorage);
9281
+ this.#subscribeHooks = new DefaultMap_js_1.DefaultMap(() => []);
8902
9282
  }
8903
9283
  get subscriptionManager() {
8904
9284
  return this.#subscriptionManager;
@@ -8909,6 +9289,9 @@ var mapperTab = (function () {
8909
9289
  static #getMapKey(eventName, browsingContext, channel) {
8910
9290
  return JSON.stringify({ eventName, browsingContext, channel });
8911
9291
  }
9292
+ addSubscribeHook(event, hook) {
9293
+ this.#subscribeHooks.get(event).push(hook);
9294
+ }
8912
9295
  registerEvent(event, contextId) {
8913
9296
  this.registerPromiseEvent(Promise.resolve({
8914
9297
  kind: 'success',
@@ -8939,9 +9322,13 @@ var mapperTab = (function () {
8939
9322
  this.#browsingContextStorage.getContext(contextId);
8940
9323
  }
8941
9324
  }
9325
+ // List of the subscription items that were actually added. Each contains a specific
9326
+ // event and context. No domain event (like "network") or global context subscription
9327
+ // (like null) are included.
9328
+ const addedSubscriptionItems = [];
8942
9329
  for (const eventName of eventNames) {
8943
9330
  for (const contextId of contextIds) {
8944
- this.#subscriptionManager.subscribe(eventName, contextId, channel);
9331
+ addedSubscriptionItems.push(...this.#subscriptionManager.subscribe(eventName, contextId, channel));
8945
9332
  for (const eventWrapper of this.#getBufferedEvents(eventName, contextId, channel)) {
8946
9333
  // The order of the events is important.
8947
9334
  this.emit("event" /* EventManagerEvents.Event */, {
@@ -8952,6 +9339,13 @@ var mapperTab = (function () {
8952
9339
  }
8953
9340
  }
8954
9341
  }
9342
+ // Iterate over all new subscription items and call hooks if any. There can be
9343
+ // duplicates, e.g. when subscribing to the whole domain and some specific event in
9344
+ // the same time ("network", "network.responseCompleted"). `distinctValues` guarantees
9345
+ // that hooks are called only once per pair event + context.
9346
+ (0, DistinctValues_js_1.distinctValues)(addedSubscriptionItems).forEach(({ contextId, event }) => {
9347
+ this.#subscribeHooks.get(event).forEach((hook) => hook(contextId));
9348
+ });
8955
9349
  await this.toggleModulesIfNeeded();
8956
9350
  }
8957
9351
  async unsubscribe(eventNames, contextIds, channel) {
@@ -9602,6 +9996,11 @@ var mapperTab = (function () {
9602
9996
  processError(this);
9603
9997
  return fieldErrors;
9604
9998
  }
9999
+ static assert(value) {
10000
+ if (!(value instanceof ZodError)) {
10001
+ throw new Error(`Not a ZodError: ${value}`);
10002
+ }
10003
+ }
9605
10004
  toString() {
9606
10005
  return this.message;
9607
10006
  }
@@ -9798,6 +10197,13 @@ var mapperTab = (function () {
9798
10197
  ...issueData,
9799
10198
  path: fullPath,
9800
10199
  };
10200
+ if (issueData.message !== undefined) {
10201
+ return {
10202
+ ...issueData,
10203
+ path: fullPath,
10204
+ message: issueData.message,
10205
+ };
10206
+ }
9801
10207
  let errorMessage = "";
9802
10208
  const maps = errorMaps
9803
10209
  .filter((m) => !!m)
@@ -9809,12 +10215,13 @@ var mapperTab = (function () {
9809
10215
  return {
9810
10216
  ...issueData,
9811
10217
  path: fullPath,
9812
- message: issueData.message || errorMessage,
10218
+ message: errorMessage,
9813
10219
  };
9814
10220
  };
9815
10221
  exports.makeIssue = makeIssue;
9816
10222
  exports.EMPTY_PATH = [];
9817
10223
  function addIssueToContext(ctx, issueData) {
10224
+ const overrideMap = (0, errors_1.getErrorMap)();
9818
10225
  const issue = (0, exports.makeIssue)({
9819
10226
  issueData: issueData,
9820
10227
  data: ctx.data,
@@ -9822,8 +10229,8 @@ var mapperTab = (function () {
9822
10229
  errorMaps: [
9823
10230
  ctx.common.contextualErrorMap,
9824
10231
  ctx.schemaErrorMap,
9825
- (0, errors_1.getErrorMap)(),
9826
- en_1.default, // then global default map
10232
+ overrideMap,
10233
+ overrideMap === en_1.default ? undefined : en_1.default, // then global default map
9827
10234
  ].filter((x) => !!x),
9828
10235
  });
9829
10236
  ctx.common.issues.push(issue);
@@ -9855,9 +10262,11 @@ var mapperTab = (function () {
9855
10262
  static async mergeObjectAsync(status, pairs) {
9856
10263
  const syncPairs = [];
9857
10264
  for (const pair of pairs) {
10265
+ const key = await pair.key;
10266
+ const value = await pair.value;
9858
10267
  syncPairs.push({
9859
- key: await pair.key,
9860
- value: await pair.value,
10268
+ key,
10269
+ value,
9861
10270
  });
9862
10271
  }
9863
10272
  return ParseStatus.mergeObjectSync(status, syncPairs);
@@ -9918,9 +10327,21 @@ var mapperTab = (function () {
9918
10327
  } (errorUtil));
9919
10328
 
9920
10329
  (function (exports) {
10330
+ var __classPrivateFieldGet = (commonjsGlobal && commonjsGlobal.__classPrivateFieldGet) || function (receiver, state, kind, f) {
10331
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10332
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10333
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
10334
+ };
10335
+ var __classPrivateFieldSet = (commonjsGlobal && commonjsGlobal.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
10336
+ if (kind === "m") throw new TypeError("Private method is not writable");
10337
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
10338
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
10339
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
10340
+ };
10341
+ var _ZodEnum_cache, _ZodNativeEnum_cache;
9921
10342
  Object.defineProperty(exports, "__esModule", { value: true });
9922
- exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0;
9923
- exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = exports.discriminatedUnion = void 0;
10343
+ exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.datetimeRegex = exports.ZodType = void 0;
10344
+ exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = exports.discriminatedUnion = exports.date = void 0;
9924
10345
  const errors_1 = errors;
9925
10346
  const errorUtil_1 = errorUtil;
9926
10347
  const parseUtil_1 = parseUtil;
@@ -9976,12 +10397,17 @@ var mapperTab = (function () {
9976
10397
  if (errorMap)
9977
10398
  return { errorMap: errorMap, description };
9978
10399
  const customMap = (iss, ctx) => {
9979
- if (iss.code !== "invalid_type")
9980
- return { message: ctx.defaultError };
10400
+ var _a, _b;
10401
+ const { message } = params;
10402
+ if (iss.code === "invalid_enum_value") {
10403
+ return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
10404
+ }
9981
10405
  if (typeof ctx.data === "undefined") {
9982
- return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
10406
+ return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
9983
10407
  }
9984
- return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
10408
+ if (iss.code !== "invalid_type")
10409
+ return { message: ctx.defaultError };
10410
+ return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
9985
10411
  };
9986
10412
  return { errorMap: customMap, description };
9987
10413
  }
@@ -10242,11 +10668,13 @@ var mapperTab = (function () {
10242
10668
  exports.Schema = ZodType;
10243
10669
  exports.ZodSchema = ZodType;
10244
10670
  const cuidRegex = /^c[^\s-]{8,}$/i;
10245
- const cuid2Regex = /^[a-z][a-z0-9]*$/;
10671
+ const cuid2Regex = /^[0-9a-z]+$/;
10246
10672
  const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
10247
10673
  // const uuidRegex =
10248
10674
  // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
10249
10675
  const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
10676
+ const nanoidRegex = /^[a-z0-9_-]{21}$/i;
10677
+ const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
10250
10678
  // from https://stackoverflow.com/a/46181/1550155
10251
10679
  // old version: too slow, didn't support unicode
10252
10680
  // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
@@ -10259,41 +10687,49 @@ var mapperTab = (function () {
10259
10687
  // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
10260
10688
  // const emailRegex =
10261
10689
  // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
10262
- const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
10690
+ const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
10263
10691
  // const emailRegex =
10264
10692
  // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
10265
10693
  // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
10266
10694
  const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
10267
10695
  let emojiRegex;
10268
- const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
10696
+ // faster, simpler, safer
10697
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
10269
10698
  const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
10270
- // Adapted from https://stackoverflow.com/a/3143231
10271
- const datetimeRegex = (args) => {
10699
+ // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
10700
+ const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
10701
+ // simple
10702
+ // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
10703
+ // no leap year validation
10704
+ // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
10705
+ // with leap year validation
10706
+ const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
10707
+ const dateRegex = new RegExp(`^${dateRegexSource}$`);
10708
+ function timeRegexSource(args) {
10709
+ // let regex = `\\d{2}:\\d{2}:\\d{2}`;
10710
+ let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
10272
10711
  if (args.precision) {
10273
- if (args.offset) {
10274
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
10275
- }
10276
- else {
10277
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
10278
- }
10279
- }
10280
- else if (args.precision === 0) {
10281
- if (args.offset) {
10282
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
10283
- }
10284
- else {
10285
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
10286
- }
10712
+ regex = `${regex}\\.\\d{${args.precision}}`;
10287
10713
  }
10288
- else {
10289
- if (args.offset) {
10290
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
10291
- }
10292
- else {
10293
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
10294
- }
10714
+ else if (args.precision == null) {
10715
+ regex = `${regex}(\\.\\d+)?`;
10295
10716
  }
10296
- };
10717
+ return regex;
10718
+ }
10719
+ function timeRegex(args) {
10720
+ return new RegExp(`^${timeRegexSource(args)}$`);
10721
+ }
10722
+ // Adapted from https://stackoverflow.com/a/3143231
10723
+ function datetimeRegex(args) {
10724
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
10725
+ const opts = [];
10726
+ opts.push(args.local ? `Z?` : `Z`);
10727
+ if (args.offset)
10728
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
10729
+ regex = `${regex}(${opts.join("|")})`;
10730
+ return new RegExp(`^${regex}$`);
10731
+ }
10732
+ exports.datetimeRegex = datetimeRegex;
10297
10733
  function isValidIP(ip, version) {
10298
10734
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
10299
10735
  return true;
@@ -10315,9 +10751,7 @@ var mapperTab = (function () {
10315
10751
  code: ZodError_1.ZodIssueCode.invalid_type,
10316
10752
  expected: util_1.ZodParsedType.string,
10317
10753
  received: ctx.parsedType,
10318
- }
10319
- //
10320
- );
10754
+ });
10321
10755
  return parseUtil_1.INVALID;
10322
10756
  }
10323
10757
  const status = new parseUtil_1.ParseStatus();
@@ -10415,6 +10849,17 @@ var mapperTab = (function () {
10415
10849
  status.dirty();
10416
10850
  }
10417
10851
  }
10852
+ else if (check.kind === "nanoid") {
10853
+ if (!nanoidRegex.test(input.data)) {
10854
+ ctx = this._getOrReturnCtx(input, ctx);
10855
+ (0, parseUtil_1.addIssueToContext)(ctx, {
10856
+ validation: "nanoid",
10857
+ code: ZodError_1.ZodIssueCode.invalid_string,
10858
+ message: check.message,
10859
+ });
10860
+ status.dirty();
10861
+ }
10862
+ }
10418
10863
  else if (check.kind === "cuid") {
10419
10864
  if (!cuidRegex.test(input.data)) {
10420
10865
  ctx = this._getOrReturnCtx(input, ctx);
@@ -10529,6 +10974,41 @@ var mapperTab = (function () {
10529
10974
  status.dirty();
10530
10975
  }
10531
10976
  }
10977
+ else if (check.kind === "date") {
10978
+ const regex = dateRegex;
10979
+ if (!regex.test(input.data)) {
10980
+ ctx = this._getOrReturnCtx(input, ctx);
10981
+ (0, parseUtil_1.addIssueToContext)(ctx, {
10982
+ code: ZodError_1.ZodIssueCode.invalid_string,
10983
+ validation: "date",
10984
+ message: check.message,
10985
+ });
10986
+ status.dirty();
10987
+ }
10988
+ }
10989
+ else if (check.kind === "time") {
10990
+ const regex = timeRegex(check);
10991
+ if (!regex.test(input.data)) {
10992
+ ctx = this._getOrReturnCtx(input, ctx);
10993
+ (0, parseUtil_1.addIssueToContext)(ctx, {
10994
+ code: ZodError_1.ZodIssueCode.invalid_string,
10995
+ validation: "time",
10996
+ message: check.message,
10997
+ });
10998
+ status.dirty();
10999
+ }
11000
+ }
11001
+ else if (check.kind === "duration") {
11002
+ if (!durationRegex.test(input.data)) {
11003
+ ctx = this._getOrReturnCtx(input, ctx);
11004
+ (0, parseUtil_1.addIssueToContext)(ctx, {
11005
+ validation: "duration",
11006
+ code: ZodError_1.ZodIssueCode.invalid_string,
11007
+ message: check.message,
11008
+ });
11009
+ status.dirty();
11010
+ }
11011
+ }
10532
11012
  else if (check.kind === "ip") {
10533
11013
  if (!isValidIP(input.data, check.version)) {
10534
11014
  ctx = this._getOrReturnCtx(input, ctx);
@@ -10540,6 +11020,17 @@ var mapperTab = (function () {
10540
11020
  status.dirty();
10541
11021
  }
10542
11022
  }
11023
+ else if (check.kind === "base64") {
11024
+ if (!base64Regex.test(input.data)) {
11025
+ ctx = this._getOrReturnCtx(input, ctx);
11026
+ (0, parseUtil_1.addIssueToContext)(ctx, {
11027
+ validation: "base64",
11028
+ code: ZodError_1.ZodIssueCode.invalid_string,
11029
+ message: check.message,
11030
+ });
11031
+ status.dirty();
11032
+ }
11033
+ }
10543
11034
  else {
10544
11035
  util_1.util.assertNever(check);
10545
11036
  }
@@ -10571,6 +11062,9 @@ var mapperTab = (function () {
10571
11062
  uuid(message) {
10572
11063
  return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) });
10573
11064
  }
11065
+ nanoid(message) {
11066
+ return this._addCheck({ kind: "nanoid", ...errorUtil_1.errorUtil.errToObj(message) });
11067
+ }
10574
11068
  cuid(message) {
10575
11069
  return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) });
10576
11070
  }
@@ -10580,16 +11074,20 @@ var mapperTab = (function () {
10580
11074
  ulid(message) {
10581
11075
  return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) });
10582
11076
  }
11077
+ base64(message) {
11078
+ return this._addCheck({ kind: "base64", ...errorUtil_1.errorUtil.errToObj(message) });
11079
+ }
10583
11080
  ip(options) {
10584
11081
  return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) });
10585
11082
  }
10586
11083
  datetime(options) {
10587
- var _a;
11084
+ var _a, _b;
10588
11085
  if (typeof options === "string") {
10589
11086
  return this._addCheck({
10590
11087
  kind: "datetime",
10591
11088
  precision: null,
10592
11089
  offset: false,
11090
+ local: false,
10593
11091
  message: options,
10594
11092
  });
10595
11093
  }
@@ -10597,9 +11095,30 @@ var mapperTab = (function () {
10597
11095
  kind: "datetime",
10598
11096
  precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
10599
11097
  offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
11098
+ local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
11099
+ ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
11100
+ });
11101
+ }
11102
+ date(message) {
11103
+ return this._addCheck({ kind: "date", message });
11104
+ }
11105
+ time(options) {
11106
+ if (typeof options === "string") {
11107
+ return this._addCheck({
11108
+ kind: "time",
11109
+ precision: null,
11110
+ message: options,
11111
+ });
11112
+ }
11113
+ return this._addCheck({
11114
+ kind: "time",
11115
+ precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
10600
11116
  ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
10601
11117
  });
10602
11118
  }
11119
+ duration(message) {
11120
+ return this._addCheck({ kind: "duration", ...errorUtil_1.errorUtil.errToObj(message) });
11121
+ }
10603
11122
  regex(regex, message) {
10604
11123
  return this._addCheck({
10605
11124
  kind: "regex",
@@ -10678,6 +11197,15 @@ var mapperTab = (function () {
10678
11197
  get isDatetime() {
10679
11198
  return !!this._def.checks.find((ch) => ch.kind === "datetime");
10680
11199
  }
11200
+ get isDate() {
11201
+ return !!this._def.checks.find((ch) => ch.kind === "date");
11202
+ }
11203
+ get isTime() {
11204
+ return !!this._def.checks.find((ch) => ch.kind === "time");
11205
+ }
11206
+ get isDuration() {
11207
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
11208
+ }
10681
11209
  get isEmail() {
10682
11210
  return !!this._def.checks.find((ch) => ch.kind === "email");
10683
11211
  }
@@ -10690,6 +11218,9 @@ var mapperTab = (function () {
10690
11218
  get isUUID() {
10691
11219
  return !!this._def.checks.find((ch) => ch.kind === "uuid");
10692
11220
  }
11221
+ get isNANOID() {
11222
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
11223
+ }
10693
11224
  get isCUID() {
10694
11225
  return !!this._def.checks.find((ch) => ch.kind === "cuid");
10695
11226
  }
@@ -10702,6 +11233,9 @@ var mapperTab = (function () {
10702
11233
  get isIP() {
10703
11234
  return !!this._def.checks.find((ch) => ch.kind === "ip");
10704
11235
  }
11236
+ get isBase64() {
11237
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
11238
+ }
10705
11239
  get minLength() {
10706
11240
  let min = null;
10707
11241
  for (const ch of this._def.checks) {
@@ -11702,9 +12236,10 @@ var mapperTab = (function () {
11702
12236
  const syncPairs = [];
11703
12237
  for (const pair of pairs) {
11704
12238
  const key = await pair.key;
12239
+ const value = await pair.value;
11705
12240
  syncPairs.push({
11706
12241
  key,
11707
- value: await pair.value,
12242
+ value,
11708
12243
  alwaysSet: pair.alwaysSet,
11709
12244
  });
11710
12245
  }
@@ -12080,7 +12615,7 @@ var mapperTab = (function () {
12080
12615
  }
12081
12616
  else if (type instanceof ZodNativeEnum) {
12082
12617
  // eslint-disable-next-line ban/ban
12083
- return Object.keys(type.enum);
12618
+ return util_1.util.objectValues(type.enum);
12084
12619
  }
12085
12620
  else if (type instanceof ZodDefault) {
12086
12621
  return getDiscriminator(type._def.innerType);
@@ -12091,8 +12626,23 @@ var mapperTab = (function () {
12091
12626
  else if (type instanceof ZodNull) {
12092
12627
  return [null];
12093
12628
  }
12629
+ else if (type instanceof ZodOptional) {
12630
+ return [undefined, ...getDiscriminator(type.unwrap())];
12631
+ }
12632
+ else if (type instanceof ZodNullable) {
12633
+ return [null, ...getDiscriminator(type.unwrap())];
12634
+ }
12635
+ else if (type instanceof ZodBranded) {
12636
+ return getDiscriminator(type.unwrap());
12637
+ }
12638
+ else if (type instanceof ZodReadonly) {
12639
+ return getDiscriminator(type.unwrap());
12640
+ }
12641
+ else if (type instanceof ZodCatch) {
12642
+ return getDiscriminator(type._def.innerType);
12643
+ }
12094
12644
  else {
12095
- return null;
12645
+ return [];
12096
12646
  }
12097
12647
  };
12098
12648
  class ZodDiscriminatedUnion extends ZodType {
@@ -12155,7 +12705,7 @@ var mapperTab = (function () {
12155
12705
  // try {
12156
12706
  for (const type of options) {
12157
12707
  const discriminatorValues = getDiscriminator(type.shape[discriminator]);
12158
- if (!discriminatorValues) {
12708
+ if (!discriminatorValues.length) {
12159
12709
  throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
12160
12710
  }
12161
12711
  for (const value of discriminatorValues) {
@@ -12371,6 +12921,7 @@ var mapperTab = (function () {
12371
12921
  pairs.push({
12372
12922
  key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
12373
12923
  value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
12924
+ alwaysSet: key in ctx.data,
12374
12925
  });
12375
12926
  }
12376
12927
  if (ctx.common.async) {
@@ -12736,6 +13287,10 @@ var mapperTab = (function () {
12736
13287
  });
12737
13288
  }
12738
13289
  class ZodEnum extends ZodType {
13290
+ constructor() {
13291
+ super(...arguments);
13292
+ _ZodEnum_cache.set(this, void 0);
13293
+ }
12739
13294
  _parse(input) {
12740
13295
  if (typeof input.data !== "string") {
12741
13296
  const ctx = this._getOrReturnCtx(input);
@@ -12747,7 +13302,10 @@ var mapperTab = (function () {
12747
13302
  });
12748
13303
  return parseUtil_1.INVALID;
12749
13304
  }
12750
- if (this._def.values.indexOf(input.data) === -1) {
13305
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
13306
+ __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
13307
+ }
13308
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
12751
13309
  const ctx = this._getOrReturnCtx(input);
12752
13310
  const expectedValues = this._def.values;
12753
13311
  (0, parseUtil_1.addIssueToContext)(ctx, {
@@ -12783,16 +13341,27 @@ var mapperTab = (function () {
12783
13341
  }
12784
13342
  return enumValues;
12785
13343
  }
12786
- extract(values) {
12787
- return ZodEnum.create(values);
13344
+ extract(values, newDef = this._def) {
13345
+ return ZodEnum.create(values, {
13346
+ ...this._def,
13347
+ ...newDef,
13348
+ });
12788
13349
  }
12789
- exclude(values) {
12790
- return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
13350
+ exclude(values, newDef = this._def) {
13351
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
13352
+ ...this._def,
13353
+ ...newDef,
13354
+ });
12791
13355
  }
12792
13356
  }
12793
13357
  exports.ZodEnum = ZodEnum;
13358
+ _ZodEnum_cache = new WeakMap();
12794
13359
  ZodEnum.create = createZodEnum;
12795
13360
  class ZodNativeEnum extends ZodType {
13361
+ constructor() {
13362
+ super(...arguments);
13363
+ _ZodNativeEnum_cache.set(this, void 0);
13364
+ }
12796
13365
  _parse(input) {
12797
13366
  const nativeEnumValues = util_1.util.getValidEnumValues(this._def.values);
12798
13367
  const ctx = this._getOrReturnCtx(input);
@@ -12806,7 +13375,10 @@ var mapperTab = (function () {
12806
13375
  });
12807
13376
  return parseUtil_1.INVALID;
12808
13377
  }
12809
- if (nativeEnumValues.indexOf(input.data) === -1) {
13378
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
13379
+ __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util_1.util.getValidEnumValues(this._def.values)), "f");
13380
+ }
13381
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
12810
13382
  const expectedValues = util_1.util.objectValues(nativeEnumValues);
12811
13383
  (0, parseUtil_1.addIssueToContext)(ctx, {
12812
13384
  received: ctx.data,
@@ -12822,6 +13394,7 @@ var mapperTab = (function () {
12822
13394
  }
12823
13395
  }
12824
13396
  exports.ZodNativeEnum = ZodNativeEnum;
13397
+ _ZodNativeEnum_cache = new WeakMap();
12825
13398
  ZodNativeEnum.create = (values, params) => {
12826
13399
  return new ZodNativeEnum({
12827
13400
  values: values,
@@ -12892,33 +13465,43 @@ var mapperTab = (function () {
12892
13465
  checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
12893
13466
  if (effect.type === "preprocess") {
12894
13467
  const processed = effect.transform(ctx.data, checkCtx);
12895
- if (ctx.common.issues.length) {
12896
- return {
12897
- status: "dirty",
12898
- value: ctx.data,
12899
- };
12900
- }
12901
13468
  if (ctx.common.async) {
12902
- return Promise.resolve(processed).then((processed) => {
12903
- return this._def.schema._parseAsync({
13469
+ return Promise.resolve(processed).then(async (processed) => {
13470
+ if (status.value === "aborted")
13471
+ return parseUtil_1.INVALID;
13472
+ const result = await this._def.schema._parseAsync({
12904
13473
  data: processed,
12905
13474
  path: ctx.path,
12906
13475
  parent: ctx,
12907
13476
  });
13477
+ if (result.status === "aborted")
13478
+ return parseUtil_1.INVALID;
13479
+ if (result.status === "dirty")
13480
+ return (0, parseUtil_1.DIRTY)(result.value);
13481
+ if (status.value === "dirty")
13482
+ return (0, parseUtil_1.DIRTY)(result.value);
13483
+ return result;
12908
13484
  });
12909
13485
  }
12910
13486
  else {
12911
- return this._def.schema._parseSync({
13487
+ if (status.value === "aborted")
13488
+ return parseUtil_1.INVALID;
13489
+ const result = this._def.schema._parseSync({
12912
13490
  data: processed,
12913
13491
  path: ctx.path,
12914
13492
  parent: ctx,
12915
13493
  });
13494
+ if (result.status === "aborted")
13495
+ return parseUtil_1.INVALID;
13496
+ if (result.status === "dirty")
13497
+ return (0, parseUtil_1.DIRTY)(result.value);
13498
+ if (status.value === "dirty")
13499
+ return (0, parseUtil_1.DIRTY)(result.value);
13500
+ return result;
12916
13501
  }
12917
13502
  }
12918
13503
  if (effect.type === "refinement") {
12919
- const executeRefinement = (acc
12920
- // effect: RefinementEffect<any>
12921
- ) => {
13504
+ const executeRefinement = (acc) => {
12922
13505
  const result = effect.refinement(acc, checkCtx);
12923
13506
  if (ctx.common.async) {
12924
13507
  return Promise.resolve(result);
@@ -13230,10 +13813,18 @@ var mapperTab = (function () {
13230
13813
  class ZodReadonly extends ZodType {
13231
13814
  _parse(input) {
13232
13815
  const result = this._def.innerType._parse(input);
13233
- if ((0, parseUtil_1.isValid)(result)) {
13234
- result.value = Object.freeze(result.value);
13235
- }
13236
- return result;
13816
+ const freeze = (data) => {
13817
+ if ((0, parseUtil_1.isValid)(data)) {
13818
+ data.value = Object.freeze(data.value);
13819
+ }
13820
+ return data;
13821
+ };
13822
+ return (0, parseUtil_1.isAsync)(result)
13823
+ ? result.then((data) => freeze(data))
13824
+ : freeze(result);
13825
+ }
13826
+ unwrap() {
13827
+ return this._def.innerType;
13237
13828
  }
13238
13829
  }
13239
13830
  exports.ZodReadonly = ZodReadonly;
@@ -13244,7 +13835,7 @@ var mapperTab = (function () {
13244
13835
  ...processCreateParams(params),
13245
13836
  });
13246
13837
  };
13247
- const custom = (check, params = {},
13838
+ function custom(check, params = {},
13248
13839
  /**
13249
13840
  * @deprecated
13250
13841
  *
@@ -13255,7 +13846,7 @@ var mapperTab = (function () {
13255
13846
  * ```
13256
13847
  *
13257
13848
  */
13258
- fatal) => {
13849
+ fatal) {
13259
13850
  if (check)
13260
13851
  return ZodAny.create().superRefine((data, ctx) => {
13261
13852
  var _a, _b;
@@ -13271,7 +13862,7 @@ var mapperTab = (function () {
13271
13862
  }
13272
13863
  });
13273
13864
  return ZodAny.create();
13274
- };
13865
+ }
13275
13866
  exports.custom = custom;
13276
13867
  exports.late = {
13277
13868
  object: ZodObject.lazycreate,
@@ -13319,7 +13910,7 @@ var mapperTab = (function () {
13319
13910
  // const instanceOfType = <T extends new (...args: any[]) => any>(
13320
13911
  cls, params = {
13321
13912
  message: `Input not instance of ${cls.name}`,
13322
- }) => (0, exports.custom)((data) => data instanceof cls, params);
13913
+ }) => custom((data) => data instanceof cls, params);
13323
13914
  exports.instanceof = instanceOfType;
13324
13915
  const stringType = ZodString.create;
13325
13916
  exports.string = stringType;
@@ -16149,6 +16740,8 @@ var mapperTab = (function () {
16149
16740
  return;
16150
16741
  }
16151
16742
  globalThis.document.documentElement.innerHTML = mapperPageSource;
16743
+ // Show a confirmation dialog when the user tries to leave the Mapper tab.
16744
+ globalThis.window.onbeforeunload = () => 'Closing or reloading this tab will stop the BiDi process. Are you sure you want to leave?';
16152
16745
  }
16153
16746
  mapperTabPage.generatePage = generatePage;
16154
16747
  function stringify(message) {