appscms-tools-theme 3.2.0 → 3.2.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,1868 +1,2691 @@
1
1
  /* Partytown 0.7.5 - MIT builder.io */
2
- (self => {
3
- const WinIdKey = Symbol();
4
- const InstanceIdKey = Symbol();
5
- const InstanceDataKey = Symbol();
6
- const NamespaceKey = Symbol();
7
- const ApplyPathKey = Symbol();
8
- const InstanceStateKey = Symbol();
9
- const HookContinue = Symbol();
10
- const HookPrevent = Symbol();
11
- const webWorkerInstances = new Map;
12
- const webWorkerRefsByRefId = {};
13
- const webWorkerRefIdsByRef = new WeakMap;
14
- const postMessages = [];
15
- const webWorkerCtx = {};
16
- const webWorkerlocalStorage = new Map;
17
- const webWorkerSessionStorage = new Map;
18
- const environments = {};
19
- const cachedDimensions = new Map;
20
- const cachedStructure = new Map;
21
- const commaSplit = str => str.split(",");
22
- const partytownLibUrl = url => {
23
- url = webWorkerCtx.$libPath$ + url;
24
- if (new URL(url).origin != location.origin) {
25
- throw "Invalid " + url;
26
- }
27
- return url;
28
- };
29
- const getterDimensionPropNames = commaSplit("clientWidth,clientHeight,clientTop,clientLeft,innerWidth,innerHeight,offsetWidth,offsetHeight,offsetTop,offsetLeft,outerWidth,outerHeight,pageXOffset,pageYOffset,scrollWidth,scrollHeight,scrollTop,scrollLeft");
30
- const elementStructurePropNames = commaSplit("childElementCount,children,firstElementChild,lastElementChild,nextElementSibling,previousElementSibling");
31
- const structureChangingMethodNames = commaSplit("insertBefore,remove,removeChild,replaceChild");
32
- const dimensionChangingSetterNames = commaSplit("className,width,height,hidden,innerHTML,innerText,textContent");
33
- const dimensionChangingMethodNames = commaSplit("setAttribute,setAttributeNS,setProperty");
34
- const eventTargetMethods = commaSplit("addEventListener,dispatchEvent,removeEventListener");
35
- const nonBlockingMethods = eventTargetMethods.concat(dimensionChangingMethodNames, commaSplit("add,observe,remove,unobserve"));
36
- const IS_TAG_REG = /^[A-Z_]([A-Z0-9-]*[A-Z0-9])?$/;
37
- const noop = () => {};
38
- const len = obj => obj.length;
39
- const getConstructorName = obj => {
40
- var _a, _b, _c;
41
- try {
42
- const constructorName = null === (_a = null == obj ? void 0 : obj.constructor) || void 0 === _a ? void 0 : _a.name;
43
- if (constructorName) {
44
- return constructorName;
45
- }
46
- } catch (e) {}
47
- try {
48
- const zoneJsConstructorName = null === (_c = null === (_b = null == obj ? void 0 : obj.__zone_symbol__originalInstance) || void 0 === _b ? void 0 : _b.constructor) || void 0 === _c ? void 0 : _c.name;
49
- if (zoneJsConstructorName) {
50
- return zoneJsConstructorName;
51
- }
52
- } catch (e) {}
53
- return "";
54
- };
55
- const EMPTY_ARRAY = [];
56
- const randomId = () => Math.round(Math.random() * Number.MAX_SAFE_INTEGER).toString(36);
57
- const SCRIPT_TYPE = "text/partytown";
58
- const defineProperty = (obj, memberName, descriptor) => Object.defineProperty(obj, memberName, {
59
- ...descriptor,
60
- configurable: true
2
+ ((self) => {
3
+ const WinIdKey = Symbol();
4
+ const InstanceIdKey = Symbol();
5
+ const InstanceDataKey = Symbol();
6
+ const NamespaceKey = Symbol();
7
+ const ApplyPathKey = Symbol();
8
+ const InstanceStateKey = Symbol();
9
+ const HookContinue = Symbol();
10
+ const HookPrevent = Symbol();
11
+ const webWorkerInstances = new Map();
12
+ const webWorkerRefsByRefId = {};
13
+ const webWorkerRefIdsByRef = new WeakMap();
14
+ const postMessages = [];
15
+ const webWorkerCtx = {};
16
+ const webWorkerlocalStorage = new Map();
17
+ const webWorkerSessionStorage = new Map();
18
+ const environments = {};
19
+ const cachedDimensions = new Map();
20
+ const cachedStructure = new Map();
21
+ const commaSplit = (str) => str.split(",");
22
+ const partytownLibUrl = (url) => {
23
+ url = webWorkerCtx.$libPath$ + url;
24
+ if (new URL(url).origin != location.origin) {
25
+ throw "Invalid " + url;
26
+ }
27
+ return url;
28
+ };
29
+ const getterDimensionPropNames = commaSplit(
30
+ "clientWidth,clientHeight,clientTop,clientLeft,innerWidth,innerHeight,offsetWidth,offsetHeight,offsetTop,offsetLeft,outerWidth,outerHeight,pageXOffset,pageYOffset,scrollWidth,scrollHeight,scrollTop,scrollLeft"
31
+ );
32
+ const elementStructurePropNames = commaSplit(
33
+ "childElementCount,children,firstElementChild,lastElementChild,nextElementSibling,previousElementSibling"
34
+ );
35
+ const structureChangingMethodNames = commaSplit(
36
+ "insertBefore,remove,removeChild,replaceChild"
37
+ );
38
+ const dimensionChangingSetterNames = commaSplit(
39
+ "className,width,height,hidden,innerHTML,innerText,textContent"
40
+ );
41
+ const dimensionChangingMethodNames = commaSplit(
42
+ "setAttribute,setAttributeNS,setProperty"
43
+ );
44
+ const eventTargetMethods = commaSplit(
45
+ "addEventListener,dispatchEvent,removeEventListener"
46
+ );
47
+ const nonBlockingMethods = eventTargetMethods.concat(
48
+ dimensionChangingMethodNames,
49
+ commaSplit("add,observe,remove,unobserve")
50
+ );
51
+ const IS_TAG_REG = /^[A-Z_]([A-Z0-9-]*[A-Z0-9])?$/;
52
+ const noop = () => {};
53
+ const len = (obj) => obj.length;
54
+ const getConstructorName = (obj) => {
55
+ var _a, _b, _c;
56
+ try {
57
+ const constructorName =
58
+ null === (_a = null == obj ? void 0 : obj.constructor) || void 0 === _a
59
+ ? void 0
60
+ : _a.name;
61
+ if (constructorName) {
62
+ return constructorName;
63
+ }
64
+ } catch (e) {}
65
+ try {
66
+ const zoneJsConstructorName =
67
+ null ===
68
+ (_c =
69
+ null ===
70
+ (_b =
71
+ null == obj ? void 0 : obj.__zone_symbol__originalInstance) ||
72
+ void 0 === _b
73
+ ? void 0
74
+ : _b.constructor) || void 0 === _c
75
+ ? void 0
76
+ : _c.name;
77
+ if (zoneJsConstructorName) {
78
+ return zoneJsConstructorName;
79
+ }
80
+ } catch (e) {}
81
+ return "";
82
+ };
83
+ const EMPTY_ARRAY = [];
84
+ const randomId = () =>
85
+ Math.round(Math.random() * Number.MAX_SAFE_INTEGER).toString(36);
86
+ const SCRIPT_TYPE = "text/partytown";
87
+ const defineProperty = (obj, memberName, descriptor) =>
88
+ Object.defineProperty(obj, memberName, {
89
+ ...descriptor,
90
+ configurable: true,
61
91
  });
62
- const defineConstructorName = (Cstr, value) => defineProperty(Cstr, "name", {
63
- value: value
92
+ const defineConstructorName = (Cstr, value) =>
93
+ defineProperty(Cstr, "name", {
94
+ value: value,
64
95
  });
65
- const definePrototypeProperty = (Cstr, memberName, descriptor) => defineProperty(Cstr.prototype, memberName, descriptor);
66
- const definePrototypePropertyDescriptor = (Cstr, propertyDescriptorMap) => Object.defineProperties(Cstr.prototype, propertyDescriptorMap);
67
- const definePrototypeValue = (Cstr, memberName, value) => definePrototypeProperty(Cstr, memberName, {
68
- value: value,
69
- writable: true
96
+ const definePrototypeProperty = (Cstr, memberName, descriptor) =>
97
+ defineProperty(Cstr.prototype, memberName, descriptor);
98
+ const definePrototypePropertyDescriptor = (Cstr, propertyDescriptorMap) =>
99
+ Object.defineProperties(Cstr.prototype, propertyDescriptorMap);
100
+ const definePrototypeValue = (Cstr, memberName, value) =>
101
+ definePrototypeProperty(Cstr, memberName, {
102
+ value: value,
103
+ writable: true,
70
104
  });
71
- const hasInstanceStateValue = (instance, stateKey) => stateKey in instance[InstanceStateKey];
72
- const getInstanceStateValue = (instance, stateKey) => instance[InstanceStateKey][stateKey];
73
- const setInstanceStateValue = (instance, stateKey, stateValue) => instance[InstanceStateKey][stateKey] = stateValue;
74
- const setWorkerRef = (ref, refId) => {
75
- if (!(refId = webWorkerRefIdsByRef.get(ref))) {
76
- webWorkerRefIdsByRef.set(ref, refId = randomId());
77
- webWorkerRefsByRefId[refId] = ref;
78
- }
79
- return refId;
80
- };
81
- const getOrCreateNodeInstance = (winId, instanceId, nodeName, namespace, instance) => {
82
- instance = webWorkerInstances.get(instanceId);
83
- if (!instance && nodeName && environments[winId]) {
84
- instance = environments[winId].$createNode$(nodeName, instanceId, namespace);
85
- webWorkerInstances.set(instanceId, instance);
86
- }
87
- return instance;
88
- };
89
- const definePrototypeNodeType = (Cstr, nodeType) => definePrototypeValue(Cstr, "nodeType", nodeType);
90
- const cachedTreeProps = (Cstr, treeProps) => treeProps.map((propName => definePrototypeProperty(Cstr, propName, {
105
+ const hasInstanceStateValue = (instance, stateKey) =>
106
+ stateKey in instance[InstanceStateKey];
107
+ const getInstanceStateValue = (instance, stateKey) =>
108
+ instance[InstanceStateKey][stateKey];
109
+ const setInstanceStateValue = (instance, stateKey, stateValue) =>
110
+ (instance[InstanceStateKey][stateKey] = stateValue);
111
+ const setWorkerRef = (ref, refId) => {
112
+ if (!(refId = webWorkerRefIdsByRef.get(ref))) {
113
+ webWorkerRefIdsByRef.set(ref, (refId = randomId()));
114
+ webWorkerRefsByRefId[refId] = ref;
115
+ }
116
+ return refId;
117
+ };
118
+ const getOrCreateNodeInstance = (
119
+ winId,
120
+ instanceId,
121
+ nodeName,
122
+ namespace,
123
+ instance
124
+ ) => {
125
+ instance = webWorkerInstances.get(instanceId);
126
+ if (!instance && nodeName && environments[winId]) {
127
+ instance = environments[winId].$createNode$(
128
+ nodeName,
129
+ instanceId,
130
+ namespace
131
+ );
132
+ webWorkerInstances.set(instanceId, instance);
133
+ }
134
+ return instance;
135
+ };
136
+ const definePrototypeNodeType = (Cstr, nodeType) =>
137
+ definePrototypeValue(Cstr, "nodeType", nodeType);
138
+ const cachedTreeProps = (Cstr, treeProps) =>
139
+ treeProps.map((propName) =>
140
+ definePrototypeProperty(Cstr, propName, {
91
141
  get() {
92
- let cacheKey = getInstanceCacheKey(this, propName);
93
- let result = cachedStructure.get(cacheKey);
94
- if (!result) {
95
- result = getter(this, [ propName ]);
96
- cachedStructure.set(cacheKey, result);
97
- }
98
- return result;
99
- }
100
- })));
101
- const getInstanceCacheKey = (instance, memberName, args) => [ instance[WinIdKey], instance[InstanceIdKey], memberName, ...(args || EMPTY_ARRAY).map((arg => String(arg && arg[WinIdKey] ? arg[InstanceIdKey] : arg))) ].join(".");
102
- const cachedProps = (Cstr, propNames) => commaSplit(propNames).map((propName => definePrototypeProperty(Cstr, propName, {
142
+ let cacheKey = getInstanceCacheKey(this, propName);
143
+ let result = cachedStructure.get(cacheKey);
144
+ if (!result) {
145
+ result = getter(this, [propName]);
146
+ cachedStructure.set(cacheKey, result);
147
+ }
148
+ return result;
149
+ },
150
+ })
151
+ );
152
+ const getInstanceCacheKey = (instance, memberName, args) =>
153
+ [
154
+ instance[WinIdKey],
155
+ instance[InstanceIdKey],
156
+ memberName,
157
+ ...(args || EMPTY_ARRAY).map((arg) =>
158
+ String(arg && arg[WinIdKey] ? arg[InstanceIdKey] : arg)
159
+ ),
160
+ ].join(".");
161
+ const cachedProps = (Cstr, propNames) =>
162
+ commaSplit(propNames).map((propName) =>
163
+ definePrototypeProperty(Cstr, propName, {
103
164
  get() {
104
- hasInstanceStateValue(this, propName) || setInstanceStateValue(this, propName, getter(this, [ propName ]));
105
- return getInstanceStateValue(this, propName);
165
+ hasInstanceStateValue(this, propName) ||
166
+ setInstanceStateValue(this, propName, getter(this, [propName]));
167
+ return getInstanceStateValue(this, propName);
106
168
  },
107
169
  set(val) {
108
- getInstanceStateValue(this, propName) !== val && setter(this, [ propName ], val);
109
- setInstanceStateValue(this, propName, val);
110
- }
111
- })));
112
- const cachedDimensionProps = Cstr => getterDimensionPropNames.map((propName => definePrototypeProperty(Cstr, propName, {
170
+ getInstanceStateValue(this, propName) !== val &&
171
+ setter(this, [propName], val);
172
+ setInstanceStateValue(this, propName, val);
173
+ },
174
+ })
175
+ );
176
+ const cachedDimensionProps = (Cstr) =>
177
+ getterDimensionPropNames.map((propName) =>
178
+ definePrototypeProperty(Cstr, propName, {
113
179
  get() {
114
- const dimension = cachedDimensions.get(getInstanceCacheKey(this, propName));
115
- if ("number" == typeof dimension) {
116
- return dimension;
117
- }
118
- const groupedDimensions = getter(this, [ propName ], getterDimensionPropNames);
119
- if (groupedDimensions && "object" == typeof groupedDimensions) {
120
- Object.entries(groupedDimensions).map((([dimensionPropName, value]) => cachedDimensions.set(getInstanceCacheKey(this, dimensionPropName), value)));
121
- return groupedDimensions[propName];
122
- }
123
- return groupedDimensions;
124
- }
125
- })));
126
- const cachedDimensionMethods = (Cstr, dimensionMethodNames) => dimensionMethodNames.map((methodName => {
127
- Cstr.prototype[methodName] = function(...args) {
128
- let cacheKey = getInstanceCacheKey(this, methodName, args);
129
- let dimensions = cachedDimensions.get(cacheKey);
130
- if (!dimensions) {
131
- dimensions = callMethod(this, [ methodName ], args);
132
- cachedDimensions.set(cacheKey, dimensions);
133
- }
134
- return dimensions;
135
- };
136
- }));
137
- const serializeForMain = ($winId$, $instanceId$, value, added, type) => void 0 !== value && (type = typeof value) ? "string" === type || "boolean" === type || "number" === type || null == value ? [ 0, value ] : "function" === type ? [ 4, {
138
- $winId$: $winId$,
139
- $instanceId$: $instanceId$,
140
- $refId$: setWorkerRef(value)
141
- } ] : (added = added || new Set) && Array.isArray(value) ? added.has(value) ? [ 1, [] ] : added.add(value) && [ 1, value.map((v => serializeForMain($winId$, $instanceId$, v, added))) ] : "object" === type ? value[InstanceIdKey] ? [ 3, [ value[WinIdKey], value[InstanceIdKey] ] ] : value instanceof Event ? [ 5, serializeObjectForMain($winId$, $instanceId$, value, false, added) ] : supportsTrustedHTML && value instanceof TrustedHTML ? [ 0, value.toString() ] : value instanceof ArrayBuffer ? [ 8, value ] : ArrayBuffer.isView(value) ? [ 9, value.buffer, getConstructorName(value) ] : [ 2, serializeObjectForMain($winId$, $instanceId$, value, true, added) ] : void 0 : value;
142
- const supportsTrustedHTML = "undefined" != typeof TrustedHTML;
143
- const serializeObjectForMain = (winId, instanceId, obj, includeFunctions, added, serializedObj, propName, propValue) => {
144
- serializedObj = {};
145
- if (!added.has(obj)) {
146
- added.add(obj);
147
- for (propName in obj) {
148
- propValue = obj[propName];
149
- (includeFunctions || "function" != typeof propValue) && (serializedObj[propName] = serializeForMain(winId, instanceId, propValue, added));
150
- }
151
- }
152
- return serializedObj;
153
- };
154
- const serializeInstanceForMain = (instance, value) => instance ? serializeForMain(instance[WinIdKey], instance[InstanceIdKey], value) : [ 0, value ];
155
- const deserializeFromMain = (winId, instanceId, applyPath, serializedValueTransfer, serializedType, serializedValue, obj, key) => {
156
- if (serializedValueTransfer) {
157
- serializedType = serializedValueTransfer[0];
158
- serializedValue = serializedValueTransfer[1];
159
- if (0 === serializedType || 11 === serializedType || 12 === serializedType) {
160
- return serializedValue;
161
- }
162
- if (4 === serializedType) {
163
- return deserializeRefFromMain(applyPath, serializedValue);
164
- }
165
- if (6 === serializedType) {
166
- return winId && applyPath.length > 0 ? (...args) => callMethod(environments[winId].$window$, applyPath, args, 1) : noop;
167
- }
168
- if (3 === serializedType) {
169
- return getOrCreateSerializedInstance(serializedValue);
170
- }
171
- if (7 === serializedType) {
172
- return new NodeList(serializedValue.map(getOrCreateSerializedInstance));
173
- }
174
- if (10 === serializedType) {
175
- return new Attr(serializedValue);
176
- }
177
- if (1 === serializedType) {
178
- return serializedValue.map((v => deserializeFromMain(winId, instanceId, applyPath, v)));
179
- }
180
- if (14 === serializedType) {
181
- return new CustomError(serializedValue);
182
- }
183
- obj = {};
184
- for (key in serializedValue) {
185
- obj[key] = deserializeFromMain(winId, instanceId, [ ...applyPath, key ], serializedValue[key]);
186
- }
187
- if (13 === serializedType) {
188
- return new environments[winId].$window$.CSSStyleDeclaration(winId, instanceId, applyPath, obj);
189
- }
190
- if (5 === serializedType) {
191
- if ("message" === obj.type && obj.origin) {
192
- let postMessageKey = JSON.stringify(obj.data);
193
- let postMessageData = postMessages.find((pm => pm.$data$ === postMessageKey));
194
- let env;
195
- if (postMessageData) {
196
- env = environments[postMessageData.$winId$];
197
- if (env) {
198
- obj.source = env.$window$;
199
- obj.origin = env.$location$.origin;
200
- }
201
- }
202
- }
203
- return new Proxy(new Event(obj.type, obj), {
204
- get: (target, propName) => propName in obj ? obj[propName] : "function" == typeof target[String(propName)] ? noop : target[String(propName)]
205
- });
206
- }
207
- if (2 === serializedType) {
208
- return obj;
209
- }
210
- }
211
- };
212
- const getOrCreateSerializedInstance = ([winId, instanceId, nodeName]) => instanceId === winId && environments[winId] ? environments[winId].$window$ : getOrCreateNodeInstance(winId, instanceId, nodeName);
213
- const deserializeRefFromMain = (applyPath, {$winId$: $winId$, $instanceId$: $instanceId$, $nodeName$: $nodeName$, $refId$: $refId$}) => {
214
- webWorkerRefsByRefId[$refId$] || webWorkerRefIdsByRef.set(webWorkerRefsByRefId[$refId$] = function(...args) {
215
- const instance = getOrCreateNodeInstance($winId$, $instanceId$, $nodeName$);
216
- return callMethod(instance, applyPath, args);
217
- }, $refId$);
218
- return webWorkerRefsByRefId[$refId$];
219
- };
220
- class CustomError extends Error {
221
- constructor(errorObject) {
222
- super(errorObject.message);
223
- this.name = errorObject.name;
224
- this.message = errorObject.message;
225
- this.stack = errorObject.stack;
180
+ const dimension = cachedDimensions.get(
181
+ getInstanceCacheKey(this, propName)
182
+ );
183
+ if ("number" == typeof dimension) {
184
+ return dimension;
185
+ }
186
+ const groupedDimensions = getter(
187
+ this,
188
+ [propName],
189
+ getterDimensionPropNames
190
+ );
191
+ if (groupedDimensions && "object" == typeof groupedDimensions) {
192
+ Object.entries(groupedDimensions).map(
193
+ ([dimensionPropName, value]) =>
194
+ cachedDimensions.set(
195
+ getInstanceCacheKey(this, dimensionPropName),
196
+ value
197
+ )
198
+ );
199
+ return groupedDimensions[propName];
200
+ }
201
+ return groupedDimensions;
202
+ },
203
+ })
204
+ );
205
+ const cachedDimensionMethods = (Cstr, dimensionMethodNames) =>
206
+ dimensionMethodNames.map((methodName) => {
207
+ Cstr.prototype[methodName] = function (...args) {
208
+ let cacheKey = getInstanceCacheKey(this, methodName, args);
209
+ let dimensions = cachedDimensions.get(cacheKey);
210
+ if (!dimensions) {
211
+ dimensions = callMethod(this, [methodName], args);
212
+ cachedDimensions.set(cacheKey, dimensions);
226
213
  }
214
+ return dimensions;
215
+ };
216
+ });
217
+ const serializeForMain = ($winId$, $instanceId$, value, added, type) =>
218
+ void 0 !== value && (type = typeof value)
219
+ ? "string" === type ||
220
+ "boolean" === type ||
221
+ "number" === type ||
222
+ null == value
223
+ ? [0, value]
224
+ : "function" === type
225
+ ? [
226
+ 4,
227
+ {
228
+ $winId$: $winId$,
229
+ $instanceId$: $instanceId$,
230
+ $refId$: setWorkerRef(value),
231
+ },
232
+ ]
233
+ : (added = added || new Set()) && Array.isArray(value)
234
+ ? added.has(value)
235
+ ? [1, []]
236
+ : added.add(value) && [
237
+ 1,
238
+ value.map((v) =>
239
+ serializeForMain($winId$, $instanceId$, v, added)
240
+ ),
241
+ ]
242
+ : "object" === type
243
+ ? value[InstanceIdKey]
244
+ ? [3, [value[WinIdKey], value[InstanceIdKey]]]
245
+ : value instanceof Event
246
+ ? [
247
+ 5,
248
+ serializeObjectForMain(
249
+ $winId$,
250
+ $instanceId$,
251
+ value,
252
+ false,
253
+ added
254
+ ),
255
+ ]
256
+ : supportsTrustedHTML && value instanceof TrustedHTML
257
+ ? [0, value.toString()]
258
+ : value instanceof ArrayBuffer
259
+ ? [8, value]
260
+ : ArrayBuffer.isView(value)
261
+ ? [9, value.buffer, getConstructorName(value)]
262
+ : [
263
+ 2,
264
+ serializeObjectForMain($winId$, $instanceId$, value, true, added),
265
+ ]
266
+ : void 0
267
+ : value;
268
+ const supportsTrustedHTML = "undefined" != typeof TrustedHTML;
269
+ const serializeObjectForMain = (
270
+ winId,
271
+ instanceId,
272
+ obj,
273
+ includeFunctions,
274
+ added,
275
+ serializedObj,
276
+ propName,
277
+ propValue
278
+ ) => {
279
+ serializedObj = {};
280
+ if (!added.has(obj)) {
281
+ added.add(obj);
282
+ for (propName in obj) {
283
+ propValue = obj[propName];
284
+ (includeFunctions || "function" != typeof propValue) &&
285
+ (serializedObj[propName] = serializeForMain(
286
+ winId,
287
+ instanceId,
288
+ propValue,
289
+ added
290
+ ));
291
+ }
227
292
  }
228
- class NodeList {
229
- constructor(nodes) {
230
- (this._ = nodes).map(((node, index) => this[index] = node));
231
- }
232
- entries() {
233
- return this._.entries();
234
- }
235
- forEach(cb, thisArg) {
236
- this._.map(cb, thisArg);
237
- }
238
- item(index) {
239
- return this[index];
240
- }
241
- keys() {
242
- return this._.keys();
243
- }
244
- get length() {
245
- return len(this._);
246
- }
247
- values() {
248
- return this._.values();
249
- }
250
- [Symbol.iterator]() {
251
- return this._[Symbol.iterator]();
293
+ return serializedObj;
294
+ };
295
+ const serializeInstanceForMain = (instance, value) =>
296
+ instance
297
+ ? serializeForMain(instance[WinIdKey], instance[InstanceIdKey], value)
298
+ : [0, value];
299
+ const deserializeFromMain = (
300
+ winId,
301
+ instanceId,
302
+ applyPath,
303
+ serializedValueTransfer,
304
+ serializedType,
305
+ serializedValue,
306
+ obj,
307
+ key
308
+ ) => {
309
+ if (serializedValueTransfer) {
310
+ serializedType = serializedValueTransfer[0];
311
+ serializedValue = serializedValueTransfer[1];
312
+ if (
313
+ 0 === serializedType ||
314
+ 11 === serializedType ||
315
+ 12 === serializedType
316
+ ) {
317
+ return serializedValue;
318
+ }
319
+ if (4 === serializedType) {
320
+ return deserializeRefFromMain(applyPath, serializedValue);
321
+ }
322
+ if (6 === serializedType) {
323
+ return winId && applyPath.length > 0
324
+ ? (...args) =>
325
+ callMethod(environments[winId].$window$, applyPath, args, 1)
326
+ : noop;
327
+ }
328
+ if (3 === serializedType) {
329
+ return getOrCreateSerializedInstance(serializedValue);
330
+ }
331
+ if (7 === serializedType) {
332
+ return new NodeList(serializedValue.map(getOrCreateSerializedInstance));
333
+ }
334
+ if (10 === serializedType) {
335
+ return new Attr(serializedValue);
336
+ }
337
+ if (1 === serializedType) {
338
+ return serializedValue.map((v) =>
339
+ deserializeFromMain(winId, instanceId, applyPath, v)
340
+ );
341
+ }
342
+ if (14 === serializedType) {
343
+ return new CustomError(serializedValue);
344
+ }
345
+ obj = {};
346
+ for (key in serializedValue) {
347
+ obj[key] = deserializeFromMain(
348
+ winId,
349
+ instanceId,
350
+ [...applyPath, key],
351
+ serializedValue[key]
352
+ );
353
+ }
354
+ if (13 === serializedType) {
355
+ return new environments[winId].$window$.CSSStyleDeclaration(
356
+ winId,
357
+ instanceId,
358
+ applyPath,
359
+ obj
360
+ );
361
+ }
362
+ if (5 === serializedType) {
363
+ if ("message" === obj.type && obj.origin) {
364
+ let postMessageKey = JSON.stringify(obj.data);
365
+ let postMessageData = postMessages.find(
366
+ (pm) => pm.$data$ === postMessageKey
367
+ );
368
+ let env;
369
+ if (postMessageData) {
370
+ env = environments[postMessageData.$winId$];
371
+ if (env) {
372
+ obj.source = env.$window$;
373
+ obj.origin = env.$location$.origin;
374
+ }
375
+ }
252
376
  }
377
+ return new Proxy(new Event(obj.type, obj), {
378
+ get: (target, propName) =>
379
+ propName in obj
380
+ ? obj[propName]
381
+ : "function" == typeof target[String(propName)]
382
+ ? noop
383
+ : target[String(propName)],
384
+ });
385
+ }
386
+ if (2 === serializedType) {
387
+ return obj;
388
+ }
389
+ }
390
+ };
391
+ const getOrCreateSerializedInstance = ([winId, instanceId, nodeName]) =>
392
+ instanceId === winId && environments[winId]
393
+ ? environments[winId].$window$
394
+ : getOrCreateNodeInstance(winId, instanceId, nodeName);
395
+ const deserializeRefFromMain = (
396
+ applyPath,
397
+ {
398
+ $winId$: $winId$,
399
+ $instanceId$: $instanceId$,
400
+ $nodeName$: $nodeName$,
401
+ $refId$: $refId$,
402
+ }
403
+ ) => {
404
+ webWorkerRefsByRefId[$refId$] ||
405
+ webWorkerRefIdsByRef.set(
406
+ (webWorkerRefsByRefId[$refId$] = function (...args) {
407
+ const instance = getOrCreateNodeInstance(
408
+ $winId$,
409
+ $instanceId$,
410
+ $nodeName$
411
+ );
412
+ return callMethod(instance, applyPath, args);
413
+ }),
414
+ $refId$
415
+ );
416
+ return webWorkerRefsByRefId[$refId$];
417
+ };
418
+ class CustomError extends Error {
419
+ constructor(errorObject) {
420
+ super(errorObject.message);
421
+ this.name = errorObject.name;
422
+ this.message = errorObject.message;
423
+ this.stack = errorObject.stack;
424
+ }
425
+ }
426
+ class NodeList {
427
+ constructor(nodes) {
428
+ (this._ = nodes).map((node, index) => (this[index] = node));
429
+ }
430
+ entries() {
431
+ return this._.entries();
432
+ }
433
+ forEach(cb, thisArg) {
434
+ this._.map(cb, thisArg);
435
+ }
436
+ item(index) {
437
+ return this[index];
438
+ }
439
+ keys() {
440
+ return this._.keys();
441
+ }
442
+ get length() {
443
+ return len(this._);
444
+ }
445
+ values() {
446
+ return this._.values();
253
447
  }
254
- const Attr = class {
255
- constructor(serializedAttr) {
256
- this.name = serializedAttr[0];
257
- this.value = serializedAttr[1];
448
+ [Symbol.iterator]() {
449
+ return this._[Symbol.iterator]();
450
+ }
451
+ }
452
+ const Attr = class {
453
+ constructor(serializedAttr) {
454
+ this.name = serializedAttr[0];
455
+ this.value = serializedAttr[1];
456
+ }
457
+ get nodeName() {
458
+ return this.name;
459
+ }
460
+ get nodeType() {
461
+ return 2;
462
+ }
463
+ };
464
+ const warnCrossOrgin = (apiType, apiName, env) =>
465
+ console.warn(
466
+ `Partytown unable to ${apiType} cross-origin ${apiName}: ` +
467
+ env.$location$
468
+ );
469
+ const logWorker = (msg, winId) => {
470
+ try {
471
+ const config = webWorkerCtx.$config$;
472
+ if (config.logStackTraces) {
473
+ const frames = new Error().stack.split("\n");
474
+ const i = frames.findIndex((f) => f.includes("logWorker"));
475
+ msg += "\n" + frames.slice(i + 1).join("\n");
476
+ }
477
+ let prefix;
478
+ let color;
479
+ if (winId) {
480
+ prefix = `Worker (${normalizedWinId(winId)}) 🎉`;
481
+ color = winColor(winId);
482
+ } else {
483
+ prefix = self.name;
484
+ color = "#9844bf";
485
+ }
486
+ if (webWorkerCtx.lastLog !== msg) {
487
+ webWorkerCtx.lastLog = msg;
488
+ console.debug.apply(console, [
489
+ `%c${prefix}`,
490
+ `background: ${color}; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;`,
491
+ msg,
492
+ ]);
493
+ }
494
+ } catch (e) {}
495
+ };
496
+ const winIds = [];
497
+ const normalizedWinId = (winId) => {
498
+ winIds.includes(winId) || winIds.push(winId);
499
+ return winIds.indexOf(winId) + 1;
500
+ };
501
+ const winColor = (winId) => {
502
+ const colors = ["#00309e", "#ea3655", "#eea727"];
503
+ const index = normalizedWinId(winId) - 1;
504
+ return colors[index] || colors[colors.length - 1];
505
+ };
506
+ const getTargetProp = (target, applyPath) => {
507
+ let n = "";
508
+ if (target) {
509
+ const cstrName = getConstructorName(target);
510
+ if ("Window" === cstrName) {
511
+ n = "";
512
+ } else if ("string" == typeof target[InstanceDataKey]) {
513
+ let nodeName = target[InstanceDataKey];
514
+ n =
515
+ "#text" === nodeName
516
+ ? "textNode."
517
+ : "#comment" === nodeName
518
+ ? "commentNode."
519
+ : "#document" === nodeName
520
+ ? "document."
521
+ : "html" === nodeName
522
+ ? "doctype."
523
+ : nodeName.toLowerCase() + ".";
524
+ } else {
525
+ n =
526
+ "nodeType" in target && 2 === target.nodeType
527
+ ? "attributes."
528
+ : "CanvasRenderingContext2D" === cstrName
529
+ ? "context2D."
530
+ : "CanvasRenderingContextWebGL" === cstrName
531
+ ? "contextWebGL."
532
+ : "CSSStyleDeclaration" === cstrName
533
+ ? "style."
534
+ : "MutationObserver" === cstrName
535
+ ? "mutationObserver."
536
+ : "NamedNodeMap" === cstrName
537
+ ? "namedNodeMap."
538
+ : "ResizeObserver" === cstrName
539
+ ? "resizeObserver."
540
+ : cstrName.substring(0, 1).toLowerCase() +
541
+ cstrName.substring(1) +
542
+ ".";
543
+ }
544
+ target[ApplyPathKey] &&
545
+ target[ApplyPathKey].length &&
546
+ (n += [...target[ApplyPathKey]].join(".") + ".");
547
+ }
548
+ if (applyPath.length > 1) {
549
+ const first = applyPath.slice(0, applyPath.length - 1);
550
+ const last = applyPath[applyPath.length - 1];
551
+ if (!isNaN(last)) {
552
+ return n + `${first.join(".")}[${last}]`;
553
+ }
554
+ }
555
+ return n + applyPath.join(".");
556
+ };
557
+ const getLogValue = (applyPath, v) => {
558
+ const type = typeof v;
559
+ if (void 0 === v) {
560
+ return "undefined";
561
+ }
562
+ if ("boolean" === type || "number" === type || null == v) {
563
+ return JSON.stringify(v);
564
+ }
565
+ if ("string" === type) {
566
+ return applyPath.includes("cookie")
567
+ ? JSON.stringify(v.slice(0, 10) + "...")
568
+ : JSON.stringify(v.length > 50 ? v.slice(0, 40) + "..." : v);
569
+ }
570
+ if (Array.isArray(v)) {
571
+ return `[${v.map(getLogValue).join(", ")}]`;
572
+ }
573
+ if ("object" === type) {
574
+ const instanceId = v[InstanceIdKey];
575
+ const cstrName = getConstructorName(v);
576
+ if ("string" == typeof instanceId) {
577
+ if ("Window" === cstrName) {
578
+ return "window";
258
579
  }
259
- get nodeName() {
260
- return this.name;
580
+ if ("string" == typeof v[InstanceDataKey]) {
581
+ if (1 === v.nodeType) {
582
+ return `<${v[InstanceDataKey].toLowerCase()}>`;
583
+ }
584
+ if (10 === v.nodeType) {
585
+ return `<!DOCTYPE ${v[InstanceDataKey]}>`;
586
+ }
587
+ if (v.nodeType <= 11) {
588
+ return v[InstanceDataKey];
589
+ }
261
590
  }
262
- get nodeType() {
263
- return 2;
591
+ return "¯\\_()_/¯ instance obj";
592
+ }
593
+ return v[Symbol.iterator]
594
+ ? `[${Array.from(v)
595
+ .map((i) => getLogValue(applyPath, i))
596
+ .join(", ")}]`
597
+ : "value" in v
598
+ ? "string" == typeof v.value
599
+ ? `"${v.value}"`
600
+ : objToString(v.value)
601
+ : objToString(v);
602
+ }
603
+ return ((v) => "object" == typeof v && v && v.then)(v)
604
+ ? "Promise"
605
+ : "function" === type
606
+ ? `ƒ() ${v.name || ""}`.trim()
607
+ : `¯\\_(ツ)_/¯ ${String(v)}`.trim();
608
+ };
609
+ const objToString = (obj) => {
610
+ const s = [];
611
+ for (let key in obj) {
612
+ const value = obj[key];
613
+ const type = typeof value;
614
+ "string" === type
615
+ ? s.push(`${key}: "${value}"`)
616
+ : "function" === type
617
+ ? s.push(`${key}: ƒ`)
618
+ : Array.isArray(type)
619
+ ? s.push(`${key}: [..]`)
620
+ : "object" === type && value
621
+ ? s.push(`${key}: {..}`)
622
+ : s.push(`${key}: ${String(value)}`);
623
+ }
624
+ let str = s.join(", ");
625
+ str.length > 200 && (str = str.substring(0, 200) + "..");
626
+ return `{ ${str} }`;
627
+ };
628
+ const logDimensionCacheClearStyle = (target, propName) => {
629
+ (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logSetters) &&
630
+ logWorker(
631
+ `Dimension cache cleared from style.${propName} setter`,
632
+ target[WinIdKey]
633
+ );
634
+ };
635
+ const logDimensionCacheClearMethod = (target, methodName) => {
636
+ (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) &&
637
+ logWorker(
638
+ `Dimension cache cleared from method call ${methodName}()`,
639
+ target[WinIdKey]
640
+ );
641
+ };
642
+ const taskQueue = [];
643
+ const queue = (
644
+ instance,
645
+ $applyPath$,
646
+ callType,
647
+ $assignInstanceId$,
648
+ $groupedGetters$,
649
+ buffer
650
+ ) => {
651
+ if (instance[ApplyPathKey]) {
652
+ taskQueue.push({
653
+ $winId$: instance[WinIdKey],
654
+ $instanceId$: instance[InstanceIdKey],
655
+ $applyPath$: [...instance[ApplyPathKey], ...$applyPath$],
656
+ $assignInstanceId$: $assignInstanceId$,
657
+ $groupedGetters$: $groupedGetters$,
658
+ });
659
+ taskQueue[len(taskQueue) - 1].$debug$ = ((
660
+ target,
661
+ applyPath,
662
+ callType
663
+ ) => {
664
+ let m = getTargetProp(target, applyPath);
665
+ 1 === callType
666
+ ? (m += " (blocking)")
667
+ : 2 === callType
668
+ ? (m += " (non-blocking)")
669
+ : 3 === callType && (m += " (non-blocking, no-side-effect)");
670
+ return m.trim();
671
+ })(instance, $applyPath$, callType);
672
+ buffer &&
673
+ 3 !== callType &&
674
+ console.error("buffer must be sent NonBlockingNoSideEffect");
675
+ if (3 === callType) {
676
+ webWorkerCtx.$postMessage$(
677
+ [
678
+ 12,
679
+ {
680
+ $msgId$: randomId(),
681
+ $tasks$: [...taskQueue],
682
+ },
683
+ ],
684
+ buffer
685
+ ? [buffer instanceof ArrayBuffer ? buffer : buffer.buffer]
686
+ : void 0
687
+ );
688
+ taskQueue.length = 0;
689
+ } else if (1 === callType) {
690
+ return sendToMain(true);
691
+ }
692
+ webWorkerCtx.$asyncMsgTimer$ = setTimeout(sendToMain, 20);
693
+ }
694
+ };
695
+ const sendToMain = (isBlocking) => {
696
+ clearTimeout(webWorkerCtx.$asyncMsgTimer$);
697
+ if (len(taskQueue)) {
698
+ webWorkerCtx.$config$.logMainAccess &&
699
+ logWorker(`Main access, tasks sent: ${taskQueue.length}`);
700
+ const endTask = taskQueue[len(taskQueue) - 1];
701
+ const accessReq = {
702
+ $msgId$: randomId(),
703
+ $tasks$: [...taskQueue],
704
+ };
705
+ taskQueue.length = 0;
706
+ if (isBlocking) {
707
+ const accessRsp = ((webWorkerCtx, accessReq) => {
708
+ const xhr = new XMLHttpRequest();
709
+ xhr.open("POST", partytownLibUrl("proxytown"), false);
710
+ xhr.send(JSON.stringify(accessReq));
711
+ return JSON.parse(xhr.responseText);
712
+ })(0, accessReq);
713
+ const isPromise = accessRsp.$isPromise$;
714
+ const rtnValue = deserializeFromMain(
715
+ endTask.$winId$,
716
+ endTask.$instanceId$,
717
+ endTask.$applyPath$,
718
+ accessRsp.$rtnValue$
719
+ );
720
+ if (accessRsp.$error$) {
721
+ if (isPromise) {
722
+ return Promise.reject(accessRsp.$error$);
723
+ }
724
+ throw new Error(accessRsp.$error$);
264
725
  }
265
- };
266
- const warnCrossOrgin = (apiType, apiName, env) => console.warn(`Partytown unable to ${apiType} cross-origin ${apiName}: ` + env.$location$);
267
- const logWorker = (msg, winId) => {
726
+ return isPromise ? Promise.resolve(rtnValue) : rtnValue;
727
+ }
728
+ webWorkerCtx.$postMessage$([12, accessReq]);
729
+ }
730
+ };
731
+ const getter = (instance, applyPath, groupedGetters, rtnValue) => {
732
+ if (webWorkerCtx.$config$.get) {
733
+ rtnValue = webWorkerCtx.$config$.get(
734
+ createHookOptions(instance, applyPath)
735
+ );
736
+ if (rtnValue !== HookContinue) {
737
+ return rtnValue;
738
+ }
739
+ }
740
+ rtnValue = queue(instance, applyPath, 1, void 0, groupedGetters);
741
+ ((
742
+ target,
743
+ applyPath,
744
+ rtnValue,
745
+ restrictedToWorker = false,
746
+ groupedGetters = false
747
+ ) => {
748
+ if (webWorkerCtx.$config$.logGetters) {
268
749
  try {
269
- const config = webWorkerCtx.$config$;
270
- if (config.logStackTraces) {
271
- const frames = (new Error).stack.split("\n");
272
- const i = frames.findIndex((f => f.includes("logWorker")));
273
- msg += "\n" + frames.slice(i + 1).join("\n");
274
- }
275
- let prefix;
276
- let color;
277
- if (winId) {
278
- prefix = `Worker (${normalizedWinId(winId)}) 🎉`;
279
- color = winColor(winId);
280
- } else {
281
- prefix = self.name;
282
- color = "#9844bf";
283
- }
284
- if (webWorkerCtx.lastLog !== msg) {
285
- webWorkerCtx.lastLog = msg;
286
- console.debug.apply(console, [ `%c${prefix}`, `background: ${color}; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;`, msg ]);
287
- }
750
+ const msg = `Get ${getTargetProp(
751
+ target,
752
+ applyPath
753
+ )}, returned: ${getLogValue(applyPath, rtnValue)}${
754
+ restrictedToWorker ? " (restricted to worker)" : ""
755
+ }${groupedGetters ? " (grouped getter)" : ""}`;
756
+ msg.includes("Symbol(") || logWorker(msg, target[WinIdKey]);
288
757
  } catch (e) {}
758
+ }
759
+ })(instance, applyPath, rtnValue, false, !!groupedGetters);
760
+ return rtnValue;
761
+ };
762
+ const setter = (instance, applyPath, value, hookSetterValue) => {
763
+ if (webWorkerCtx.$config$.set) {
764
+ hookSetterValue = webWorkerCtx.$config$.set({
765
+ value: value,
766
+ prevent: HookPrevent,
767
+ ...createHookOptions(instance, applyPath),
768
+ });
769
+ if (hookSetterValue === HookPrevent) {
770
+ return;
771
+ }
772
+ hookSetterValue !== HookContinue && (value = hookSetterValue);
773
+ }
774
+ if (dimensionChangingSetterNames.some((s) => applyPath.includes(s))) {
775
+ cachedDimensions.clear();
776
+ ((target, propName) => {
777
+ (webWorkerCtx.$config$.logGetters ||
778
+ webWorkerCtx.$config$.logSetters) &&
779
+ logWorker(
780
+ `Dimension cache cleared from setter "${propName}"`,
781
+ target[WinIdKey]
782
+ );
783
+ })(instance, applyPath[applyPath.length - 1]);
784
+ }
785
+ applyPath = [...applyPath, serializeInstanceForMain(instance, value), 0];
786
+ ((target, applyPath, value, restrictedToWorker = false) => {
787
+ if (webWorkerCtx.$config$.logSetters) {
788
+ try {
789
+ applyPath = applyPath.slice(0, applyPath.length - 2);
790
+ logWorker(
791
+ `Set ${getTargetProp(target, applyPath)}, value: ${getLogValue(
792
+ applyPath,
793
+ value
794
+ )}${restrictedToWorker ? " (restricted to worker)" : ""}`,
795
+ target[WinIdKey]
796
+ );
797
+ } catch (e) {}
798
+ }
799
+ })(instance, applyPath, value);
800
+ queue(instance, applyPath, 2);
801
+ };
802
+ const callMethod = (
803
+ instance,
804
+ applyPath,
805
+ args,
806
+ callType,
807
+ assignInstanceId,
808
+ buffer,
809
+ rtnValue,
810
+ methodName
811
+ ) => {
812
+ if (webWorkerCtx.$config$.apply) {
813
+ rtnValue = webWorkerCtx.$config$.apply({
814
+ args: args,
815
+ ...createHookOptions(instance, applyPath),
816
+ });
817
+ if (rtnValue !== HookContinue) {
818
+ return rtnValue;
819
+ }
820
+ }
821
+ methodName = applyPath[len(applyPath) - 1];
822
+ applyPath = [...applyPath, serializeInstanceForMain(instance, args)];
823
+ callType = callType || (nonBlockingMethods.includes(methodName) ? 2 : 1);
824
+ if (
825
+ "setAttribute" === methodName &&
826
+ hasInstanceStateValue(instance, args[0])
827
+ ) {
828
+ setInstanceStateValue(instance, args[0], args[1]);
829
+ } else if (structureChangingMethodNames.includes(methodName)) {
830
+ cachedDimensions.clear();
831
+ cachedStructure.clear();
832
+ ((target, methodName) => {
833
+ (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) &&
834
+ logWorker(
835
+ `Dimension and DOM structure cache cleared from method call ${methodName}()`,
836
+ target[WinIdKey]
837
+ );
838
+ })(instance, methodName);
839
+ } else if (dimensionChangingMethodNames.includes(methodName)) {
840
+ callType = 2;
841
+ cachedDimensions.clear();
842
+ logDimensionCacheClearMethod(instance, methodName);
843
+ }
844
+ rtnValue = queue(
845
+ instance,
846
+ applyPath,
847
+ callType,
848
+ assignInstanceId,
849
+ void 0,
850
+ buffer
851
+ );
852
+ ((target, applyPath, args, rtnValue) => {
853
+ if (webWorkerCtx.$config$.logCalls) {
854
+ try {
855
+ applyPath = applyPath.slice(0, applyPath.length - 1);
856
+ logWorker(
857
+ `Call ${getTargetProp(target, applyPath)}(${args
858
+ .map((v) => getLogValue(applyPath, v))
859
+ .join(", ")}), returned: ${getLogValue(applyPath, rtnValue)}`,
860
+ target[WinIdKey]
861
+ );
862
+ } catch (e) {}
863
+ }
864
+ })(instance, applyPath, args, rtnValue);
865
+ return rtnValue;
866
+ };
867
+ const constructGlobal = (instance, cstrName, args) => {
868
+ ((target, cstrName, args) => {
869
+ if (webWorkerCtx.$config$.logCalls) {
870
+ try {
871
+ logWorker(
872
+ `Construct new ${cstrName}(${args
873
+ .map((v) => getLogValue([], v))
874
+ .join(", ")})`,
875
+ target[WinIdKey]
876
+ );
877
+ } catch (e) {}
878
+ }
879
+ })(instance, cstrName, args);
880
+ queue(instance, [1, cstrName, serializeInstanceForMain(instance, args)], 1);
881
+ };
882
+ const createHookOptions = (instance, applyPath) => ({
883
+ name: applyPath.join("."),
884
+ continue: HookContinue,
885
+ nodeName: instance[InstanceDataKey],
886
+ constructor: getConstructorName(instance),
887
+ instance: instance,
888
+ window: environments[instance[WinIdKey]].$window$,
889
+ });
890
+ const addStorageApi = (win, storageName, storages, isSameOrigin, env) => {
891
+ let getItems = (items) => {
892
+ items = storages.get(win.origin);
893
+ items || storages.set(win.origin, (items = []));
894
+ return items;
289
895
  };
290
- const winIds = [];
291
- const normalizedWinId = winId => {
292
- winIds.includes(winId) || winIds.push(winId);
293
- return winIds.indexOf(winId) + 1;
294
- };
295
- const winColor = winId => {
296
- const colors = [ "#00309e", "#ea3655", "#eea727" ];
297
- const index = normalizedWinId(winId) - 1;
298
- return colors[index] || colors[colors.length - 1];
896
+ let getIndexByKey = (key) =>
897
+ getItems().findIndex((i) => i[STORAGE_KEY] === key);
898
+ let index;
899
+ let item;
900
+ let storage = {
901
+ getItem(key) {
902
+ index = getIndexByKey(key);
903
+ return index > -1 ? getItems()[index][STORAGE_VALUE] : null;
904
+ },
905
+ setItem(key, value) {
906
+ index = getIndexByKey(key);
907
+ index > -1
908
+ ? (getItems()[index][STORAGE_VALUE] = value)
909
+ : getItems().push([key, value]);
910
+ isSameOrigin
911
+ ? callMethod(win, [storageName, "setItem"], [key, value], 2)
912
+ : warnCrossOrgin("set", storageName, env);
913
+ },
914
+ removeItem(key) {
915
+ index = getIndexByKey(key);
916
+ index > -1 && getItems().splice(index, 1);
917
+ isSameOrigin
918
+ ? callMethod(win, [storageName, "removeItem"], [key], 2)
919
+ : warnCrossOrgin("remove", storageName, env);
920
+ },
921
+ key(index) {
922
+ item = getItems()[index];
923
+ return item ? item[STORAGE_KEY] : null;
924
+ },
925
+ clear() {
926
+ getItems().length = 0;
927
+ isSameOrigin
928
+ ? callMethod(win, [storageName, "clear"], EMPTY_ARRAY, 2)
929
+ : warnCrossOrgin("clear", storageName, env);
930
+ },
931
+ get length() {
932
+ return getItems().length;
933
+ },
299
934
  };
300
- const getTargetProp = (target, applyPath) => {
301
- let n = "";
302
- if (target) {
303
- const cstrName = getConstructorName(target);
304
- if ("Window" === cstrName) {
305
- n = "";
306
- } else if ("string" == typeof target[InstanceDataKey]) {
307
- let nodeName = target[InstanceDataKey];
308
- n = "#text" === nodeName ? "textNode." : "#comment" === nodeName ? "commentNode." : "#document" === nodeName ? "document." : "html" === nodeName ? "doctype." : nodeName.toLowerCase() + ".";
309
- } else {
310
- n = "nodeType" in target && 2 === target.nodeType ? "attributes." : "CanvasRenderingContext2D" === cstrName ? "context2D." : "CanvasRenderingContextWebGL" === cstrName ? "contextWebGL." : "CSSStyleDeclaration" === cstrName ? "style." : "MutationObserver" === cstrName ? "mutationObserver." : "NamedNodeMap" === cstrName ? "namedNodeMap." : "ResizeObserver" === cstrName ? "resizeObserver." : cstrName.substring(0, 1).toLowerCase() + cstrName.substring(1) + ".";
311
- }
312
- target[ApplyPathKey] && target[ApplyPathKey].length && (n += [ ...target[ApplyPathKey] ].join(".") + ".");
313
- }
314
- if (applyPath.length > 1) {
315
- const first = applyPath.slice(0, applyPath.length - 1);
316
- const last = applyPath[applyPath.length - 1];
317
- if (!isNaN(last)) {
318
- return n + `${first.join(".")}[${last}]`;
319
- }
935
+ win[storageName] = new Proxy(storage, {
936
+ get: (target, key) =>
937
+ Reflect.has(target, key)
938
+ ? Reflect.get(target, key)
939
+ : target.getItem(key),
940
+ set(target, key, value) {
941
+ target.setItem(key, value);
942
+ return true;
943
+ },
944
+ has: (target, key) =>
945
+ !!Reflect.has(target, key) ||
946
+ ("string" == typeof key && null !== target.getItem(key)),
947
+ deleteProperty(target, key) {
948
+ target.removeItem(key);
949
+ return true;
950
+ },
951
+ });
952
+ };
953
+ const STORAGE_KEY = 0;
954
+ const STORAGE_VALUE = 1;
955
+ const createCSSStyleDeclarationCstr = (win, WorkerBase, cstrName) => {
956
+ win[cstrName] = defineConstructorName(
957
+ class extends WorkerBase {
958
+ constructor(winId, instanceId, applyPath, styles) {
959
+ super(winId, instanceId, applyPath, styles || {});
960
+ return new Proxy(this, {
961
+ get(target, propName) {
962
+ if (target[propName]) {
963
+ return target[propName];
964
+ }
965
+ target[propName] ||
966
+ "string" != typeof propName ||
967
+ target[InstanceDataKey][propName] ||
968
+ (target[InstanceDataKey][propName] = getter(target, [
969
+ propName,
970
+ ]));
971
+ return target[InstanceDataKey][propName];
972
+ },
973
+ set(target, propName, propValue) {
974
+ target[InstanceDataKey][propName] = propValue;
975
+ setter(target, [propName], propValue);
976
+ logDimensionCacheClearStyle(target, propName);
977
+ cachedDimensions.clear();
978
+ return true;
979
+ },
980
+ });
320
981
  }
321
- return n + applyPath.join(".");
322
- };
323
- const getLogValue = (applyPath, v) => {
324
- const type = typeof v;
325
- if (void 0 === v) {
326
- return "undefined";
982
+ setProperty(...args) {
983
+ this[InstanceDataKey][args[0]] = args[1];
984
+ callMethod(this, ["setProperty"], args, 2);
985
+ logDimensionCacheClearStyle(this, args[0]);
986
+ cachedDimensions.clear();
327
987
  }
328
- if ("boolean" === type || "number" === type || null == v) {
329
- return JSON.stringify(v);
988
+ getPropertyValue(propName) {
989
+ return this[propName];
330
990
  }
331
- if ("string" === type) {
332
- return applyPath.includes("cookie") ? JSON.stringify(v.slice(0, 10) + "...") : JSON.stringify(v.length > 50 ? v.slice(0, 40) + "..." : v);
991
+ removeProperty(propName) {
992
+ let value = this[InstanceDataKey][propName];
993
+ callMethod(this, ["removeProperty"], [propName], 2);
994
+ logDimensionCacheClearStyle(this, propName);
995
+ cachedDimensions.clear();
996
+ this[InstanceDataKey][propName] = void 0;
997
+ return value;
333
998
  }
334
- if (Array.isArray(v)) {
335
- return `[${v.map(getLogValue).join(", ")}]`;
999
+ },
1000
+ cstrName
1001
+ );
1002
+ };
1003
+ const createCSSStyleSheetConstructor = (win, cssStyleSheetCstrName) => {
1004
+ win[cssStyleSheetCstrName] = defineConstructorName(
1005
+ class {
1006
+ constructor(ownerNode) {
1007
+ this.ownerNode = ownerNode;
336
1008
  }
337
- if ("object" === type) {
338
- const instanceId = v[InstanceIdKey];
339
- const cstrName = getConstructorName(v);
340
- if ("string" == typeof instanceId) {
341
- if ("Window" === cstrName) {
342
- return "window";
343
- }
344
- if ("string" == typeof v[InstanceDataKey]) {
345
- if (1 === v.nodeType) {
346
- return `<${v[InstanceDataKey].toLowerCase()}>`;
347
- }
348
- if (10 === v.nodeType) {
349
- return `<!DOCTYPE ${v[InstanceDataKey]}>`;
350
- }
351
- if (v.nodeType <= 11) {
352
- return v[InstanceDataKey];
353
- }
354
- }
355
- return "¯\\_(ツ)_/¯ instance obj";
356
- }
357
- return v[Symbol.iterator] ? `[${Array.from(v).map((i => getLogValue(applyPath, i))).join(", ")}]` : "value" in v ? "string" == typeof v.value ? `"${v.value}"` : objToString(v.value) : objToString(v);
1009
+ get cssRules() {
1010
+ const ownerNode = this.ownerNode;
1011
+ return new Proxy(
1012
+ {},
1013
+ {
1014
+ get(target, propKey) {
1015
+ const propName = String(propKey);
1016
+ return "item" === propName
1017
+ ? (index) => getCssRule(ownerNode, index)
1018
+ : "length" === propName
1019
+ ? getCssRules(ownerNode).length
1020
+ : isNaN(propName)
1021
+ ? target[propKey]
1022
+ : getCssRule(ownerNode, propName);
1023
+ },
1024
+ }
1025
+ );
358
1026
  }
359
- return (v => "object" == typeof v && v && v.then)(v) ? "Promise" : "function" === type ? `ƒ() ${v.name || ""}`.trim() : `¯\\_(ツ)_/¯ ${String(v)}`.trim();
360
- };
361
- const objToString = obj => {
362
- const s = [];
363
- for (let key in obj) {
364
- const value = obj[key];
365
- const type = typeof value;
366
- "string" === type ? s.push(`${key}: "${value}"`) : "function" === type ? s.push(`${key}: ƒ`) : Array.isArray(type) ? s.push(`${key}: [..]`) : "object" === type && value ? s.push(`${key}: {..}`) : s.push(`${key}: ${String(value)}`);
1027
+ insertRule(ruleText, index) {
1028
+ const cssRules = getCssRules(this.ownerNode);
1029
+ index = void 0 === index ? 0 : index;
1030
+ if (index >= 0 && index <= cssRules.length) {
1031
+ callMethod(
1032
+ this.ownerNode,
1033
+ ["sheet", "insertRule"],
1034
+ [ruleText, index],
1035
+ 2
1036
+ );
1037
+ cssRules.splice(index, 0, 0);
1038
+ }
1039
+ logDimensionCacheClearMethod(this.ownerNode, "insertRule");
1040
+ cachedDimensions.clear();
1041
+ return index;
367
1042
  }
368
- let str = s.join(", ");
369
- str.length > 200 && (str = str.substring(0, 200) + "..");
370
- return `{ ${str} }`;
371
- };
372
- const logDimensionCacheClearStyle = (target, propName) => {
373
- (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logSetters) && logWorker(`Dimension cache cleared from style.${propName} setter`, target[WinIdKey]);
374
- };
375
- const logDimensionCacheClearMethod = (target, methodName) => {
376
- (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) && logWorker(`Dimension cache cleared from method call ${methodName}()`, target[WinIdKey]);
377
- };
378
- const taskQueue = [];
379
- const queue = (instance, $applyPath$, callType, $assignInstanceId$, $groupedGetters$, buffer) => {
380
- if (instance[ApplyPathKey]) {
381
- taskQueue.push({
382
- $winId$: instance[WinIdKey],
383
- $instanceId$: instance[InstanceIdKey],
384
- $applyPath$: [ ...instance[ApplyPathKey], ...$applyPath$ ],
385
- $assignInstanceId$: $assignInstanceId$,
386
- $groupedGetters$: $groupedGetters$
387
- });
388
- taskQueue[len(taskQueue) - 1].$debug$ = ((target, applyPath, callType) => {
389
- let m = getTargetProp(target, applyPath);
390
- 1 === callType ? m += " (blocking)" : 2 === callType ? m += " (non-blocking)" : 3 === callType && (m += " (non-blocking, no-side-effect)");
391
- return m.trim();
392
- })(instance, $applyPath$, callType);
393
- buffer && 3 !== callType && console.error("buffer must be sent NonBlockingNoSideEffect");
394
- if (3 === callType) {
395
- webWorkerCtx.$postMessage$([ 12, {
396
- $msgId$: randomId(),
397
- $tasks$: [ ...taskQueue ]
398
- } ], buffer ? [ buffer instanceof ArrayBuffer ? buffer : buffer.buffer ] : void 0);
399
- taskQueue.length = 0;
400
- } else if (1 === callType) {
401
- return sendToMain(true);
402
- }
403
- webWorkerCtx.$asyncMsgTimer$ = setTimeout(sendToMain, 20);
1043
+ deleteRule(index) {
1044
+ callMethod(this.ownerNode, ["sheet", "deleteRule"], [index], 2);
1045
+ getCssRules(this.ownerNode).splice(index, 1);
1046
+ logDimensionCacheClearMethod(this.ownerNode, "deleteRule");
1047
+ cachedDimensions.clear();
404
1048
  }
405
- };
406
- const sendToMain = isBlocking => {
407
- clearTimeout(webWorkerCtx.$asyncMsgTimer$);
408
- if (len(taskQueue)) {
409
- webWorkerCtx.$config$.logMainAccess && logWorker(`Main access, tasks sent: ${taskQueue.length}`);
410
- const endTask = taskQueue[len(taskQueue) - 1];
411
- const accessReq = {
412
- $msgId$: randomId(),
413
- $tasks$: [ ...taskQueue ]
414
- };
415
- taskQueue.length = 0;
416
- if (isBlocking) {
417
- const accessRsp = ((webWorkerCtx, accessReq) => {
418
- const xhr = new XMLHttpRequest;
419
- xhr.open("POST", partytownLibUrl("proxytown"), false);
420
- xhr.send(JSON.stringify(accessReq));
421
- return JSON.parse(xhr.responseText);
422
- })(0, accessReq);
423
- const isPromise = accessRsp.$isPromise$;
424
- const rtnValue = deserializeFromMain(endTask.$winId$, endTask.$instanceId$, endTask.$applyPath$, accessRsp.$rtnValue$);
425
- if (accessRsp.$error$) {
426
- if (isPromise) {
427
- return Promise.reject(accessRsp.$error$);
428
- }
429
- throw new Error(accessRsp.$error$);
430
- }
431
- return isPromise ? Promise.resolve(rtnValue) : rtnValue;
432
- }
433
- webWorkerCtx.$postMessage$([ 12, accessReq ]);
1049
+ get type() {
1050
+ return "text/css";
434
1051
  }
1052
+ },
1053
+ cssStyleSheetCstrName
1054
+ );
1055
+ const HTMLStyleDescriptorMap = {
1056
+ sheet: {
1057
+ get() {
1058
+ return new win[cssStyleSheetCstrName](this);
1059
+ },
1060
+ },
435
1061
  };
436
- const getter = (instance, applyPath, groupedGetters, rtnValue) => {
437
- if (webWorkerCtx.$config$.get) {
438
- rtnValue = webWorkerCtx.$config$.get(createHookOptions(instance, applyPath));
439
- if (rtnValue !== HookContinue) {
440
- return rtnValue;
441
- }
442
- }
443
- rtnValue = queue(instance, applyPath, 1, void 0, groupedGetters);
444
- ((target, applyPath, rtnValue, restrictedToWorker = false, groupedGetters = false) => {
445
- if (webWorkerCtx.$config$.logGetters) {
446
- try {
447
- const msg = `Get ${getTargetProp(target, applyPath)}, returned: ${getLogValue(applyPath, rtnValue)}${restrictedToWorker ? " (restricted to worker)" : ""}${groupedGetters ? " (grouped getter)" : ""}`;
448
- msg.includes("Symbol(") || logWorker(msg, target[WinIdKey]);
449
- } catch (e) {}
450
- }
451
- })(instance, applyPath, rtnValue, false, !!groupedGetters);
452
- return rtnValue;
1062
+ definePrototypePropertyDescriptor(
1063
+ win.HTMLStyleElement,
1064
+ HTMLStyleDescriptorMap
1065
+ );
1066
+ };
1067
+ const getCssRules = (ownerNode, cssRules) => {
1068
+ cssRules = getInstanceStateValue(ownerNode, 2);
1069
+ if (!cssRules) {
1070
+ cssRules = getter(ownerNode, ["sheet", "cssRules"]);
1071
+ setInstanceStateValue(ownerNode, 2, cssRules);
1072
+ }
1073
+ return cssRules;
1074
+ };
1075
+ const getCssRule = (ownerNode, index, cssRules) => {
1076
+ cssRules = getCssRules(ownerNode);
1077
+ 0 === cssRules[index] &&
1078
+ (cssRules[index] = getter(ownerNode, [
1079
+ "sheet",
1080
+ "cssRules",
1081
+ parseInt(index, 10),
1082
+ ]));
1083
+ return cssRules[index];
1084
+ };
1085
+ const runScriptContent = (
1086
+ env,
1087
+ instanceId,
1088
+ scriptContent,
1089
+ winId,
1090
+ errorMsg
1091
+ ) => {
1092
+ try {
1093
+ webWorkerCtx.$config$.logScriptExecution &&
1094
+ logWorker(
1095
+ `Execute script: ${scriptContent
1096
+ .substring(0, 100)
1097
+ .split("\n")
1098
+ .map((l) => l.trim())
1099
+ .join(" ")
1100
+ .trim()
1101
+ .substring(0, 60)}...`,
1102
+ winId
1103
+ );
1104
+ env.$currentScriptId$ = instanceId;
1105
+ run(env, scriptContent);
1106
+ } catch (contentError) {
1107
+ console.error(scriptContent, contentError);
1108
+ errorMsg = String(contentError.stack || contentError);
1109
+ }
1110
+ env.$currentScriptId$ = "";
1111
+ return errorMsg;
1112
+ };
1113
+ const run = (env, scriptContent, scriptUrl) => {
1114
+ env.$runWindowLoadEvent$ = 1;
1115
+ scriptContent =
1116
+ `with(this){${scriptContent
1117
+ .replace(/\bthis\b/g, "(thi$(this)?window:this)")
1118
+ .replace(/\/\/# so/g, "//Xso")}\n;function thi$(t){return t===this}};${(
1119
+ webWorkerCtx.$config$.globalFns || []
1120
+ )
1121
+ .filter((globalFnName) => /[a-zA-Z_$][0-9a-zA-Z_$]*/.test(globalFnName))
1122
+ .map((g) => `(typeof ${g}=='function'&&(this.${g}=${g}))`)
1123
+ .join(";")};` + (scriptUrl ? "\n//# sourceURL=" + scriptUrl : "");
1124
+ env.$isSameOrigin$ ||
1125
+ (scriptContent = scriptContent.replace(
1126
+ /.postMessage\(/g,
1127
+ `.postMessage('${env.$winId$}',`
1128
+ ));
1129
+ new Function(scriptContent).call(env.$window$);
1130
+ env.$runWindowLoadEvent$ = 0;
1131
+ };
1132
+ const runStateLoadHandlers = (instance, type, handlers) => {
1133
+ handlers = getInstanceStateValue(instance, type);
1134
+ handlers &&
1135
+ setTimeout(() =>
1136
+ handlers.map((cb) =>
1137
+ cb({
1138
+ type: type,
1139
+ })
1140
+ )
1141
+ );
1142
+ };
1143
+ const resolveToUrl = (
1144
+ env,
1145
+ url,
1146
+ type,
1147
+ baseLocation,
1148
+ resolvedUrl,
1149
+ configResolvedUrl
1150
+ ) => {
1151
+ baseLocation = env.$location$;
1152
+ while (!baseLocation.host) {
1153
+ env = environments[env.$parentWinId$];
1154
+ baseLocation = env.$location$;
1155
+ if (env.$winId$ === env.$parentWinId$) {
1156
+ break;
1157
+ }
1158
+ }
1159
+ resolvedUrl = new URL(url || "", baseLocation);
1160
+ if (type && webWorkerCtx.$config$.resolveUrl) {
1161
+ configResolvedUrl = webWorkerCtx.$config$.resolveUrl(
1162
+ resolvedUrl,
1163
+ baseLocation,
1164
+ type
1165
+ );
1166
+ if (configResolvedUrl) {
1167
+ return configResolvedUrl;
1168
+ }
1169
+ }
1170
+ return resolvedUrl;
1171
+ };
1172
+ const resolveUrl = (env, url, type) => resolveToUrl(env, url, type) + "";
1173
+ const getPartytownScript = () =>
1174
+ `<script src="${partytownLibUrl("partytown.js?v=0.7.5")}"><\/script>`;
1175
+ const createImageConstructor = (env) =>
1176
+ class HTMLImageElement {
1177
+ constructor() {
1178
+ this.s = "";
1179
+ this.l = [];
1180
+ this.e = [];
1181
+ this.style = {};
1182
+ }
1183
+ get src() {
1184
+ return this.s;
1185
+ }
1186
+ set src(src) {
1187
+ webWorkerCtx.$config$.logImageRequests &&
1188
+ logWorker(
1189
+ `Image() request: ${resolveUrl(env, src, "image")}`,
1190
+ env.$winId$
1191
+ );
1192
+ this.s = src;
1193
+ fetch(resolveUrl(env, src, "image"), {
1194
+ mode: "no-cors",
1195
+ credentials: "include",
1196
+ keepalive: true,
1197
+ }).then(
1198
+ (rsp) => {
1199
+ rsp.ok || 0 === rsp.status
1200
+ ? this.l.map((cb) =>
1201
+ cb({
1202
+ type: "load",
1203
+ })
1204
+ )
1205
+ : this.e.map((cb) =>
1206
+ cb({
1207
+ type: "error",
1208
+ })
1209
+ );
1210
+ },
1211
+ () =>
1212
+ this.e.forEach((cb) =>
1213
+ cb({
1214
+ type: "error",
1215
+ })
1216
+ )
1217
+ );
1218
+ }
1219
+ addEventListener(eventName, cb) {
1220
+ "load" === eventName && this.l.push(cb);
1221
+ "error" === eventName && this.e.push(cb);
1222
+ }
1223
+ get onload() {
1224
+ return this.l[0];
1225
+ }
1226
+ set onload(cb) {
1227
+ this.l = [cb];
1228
+ }
1229
+ get onerror() {
1230
+ return this.e[0];
1231
+ }
1232
+ set onerror(cb) {
1233
+ this.e = [cb];
1234
+ }
453
1235
  };
454
- const setter = (instance, applyPath, value, hookSetterValue) => {
455
- if (webWorkerCtx.$config$.set) {
456
- hookSetterValue = webWorkerCtx.$config$.set({
457
- value: value,
458
- prevent: HookPrevent,
459
- ...createHookOptions(instance, applyPath)
460
- });
461
- if (hookSetterValue === HookPrevent) {
462
- return;
463
- }
464
- hookSetterValue !== HookContinue && (value = hookSetterValue);
465
- }
466
- if (dimensionChangingSetterNames.some((s => applyPath.includes(s)))) {
467
- cachedDimensions.clear();
468
- ((target, propName) => {
469
- (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logSetters) && logWorker(`Dimension cache cleared from setter "${propName}"`, target[WinIdKey]);
470
- })(instance, applyPath[applyPath.length - 1]);
471
- }
472
- applyPath = [ ...applyPath, serializeInstanceForMain(instance, value), 0 ];
473
- ((target, applyPath, value, restrictedToWorker = false) => {
474
- if (webWorkerCtx.$config$.logSetters) {
475
- try {
476
- applyPath = applyPath.slice(0, applyPath.length - 2);
477
- logWorker(`Set ${getTargetProp(target, applyPath)}, value: ${getLogValue(applyPath, value)}${restrictedToWorker ? " (restricted to worker)" : ""}`, target[WinIdKey]);
478
- } catch (e) {}
479
- }
480
- })(instance, applyPath, value);
481
- queue(instance, applyPath, 2);
1236
+ const HTMLSrcElementDescriptorMap = {
1237
+ addEventListener: {
1238
+ value(...args) {
1239
+ const eventName = args[0];
1240
+ const callbacks = getInstanceStateValue(this, eventName) || [];
1241
+ callbacks.push(args[1]);
1242
+ setInstanceStateValue(this, eventName, callbacks);
1243
+ },
1244
+ },
1245
+ async: {
1246
+ get: noop,
1247
+ set: noop,
1248
+ },
1249
+ defer: {
1250
+ get: noop,
1251
+ set: noop,
1252
+ },
1253
+ onload: {
1254
+ get() {
1255
+ let callbacks = getInstanceStateValue(this, "load");
1256
+ return (callbacks && callbacks[0]) || null;
1257
+ },
1258
+ set(cb) {
1259
+ setInstanceStateValue(this, "load", cb ? [cb] : null);
1260
+ },
1261
+ },
1262
+ onerror: {
1263
+ get() {
1264
+ let callbacks = getInstanceStateValue(this, "error");
1265
+ return (callbacks && callbacks[0]) || null;
1266
+ },
1267
+ set(cb) {
1268
+ setInstanceStateValue(this, "error", cb ? [cb] : null);
1269
+ },
1270
+ },
1271
+ getAttribute: {
1272
+ value(attrName) {
1273
+ return "src" === attrName
1274
+ ? this.src
1275
+ : callMethod(this, ["getAttribute"], [attrName]);
1276
+ },
1277
+ },
1278
+ setAttribute: {
1279
+ value(attrName, attrValue) {
1280
+ scriptAttrPropNames.includes(attrName)
1281
+ ? (this[attrName] = attrValue)
1282
+ : callMethod(this, ["setAttribute"], [attrName, attrValue]);
1283
+ },
1284
+ },
1285
+ };
1286
+ const scriptAttrPropNames = commaSplit("src,type");
1287
+ const patchHTMLScriptElement = (WorkerHTMLScriptElement, env) => {
1288
+ const HTMLScriptDescriptorMap = {
1289
+ innerHTML: innerHTMLDescriptor,
1290
+ innerText: innerHTMLDescriptor,
1291
+ src: {
1292
+ get() {
1293
+ return getInstanceStateValue(this, 4) || "";
1294
+ },
1295
+ set(url) {
1296
+ const orgUrl = resolveUrl(env, url, null);
1297
+ const config = webWorkerCtx.$config$;
1298
+ url = resolveUrl(env, url, "script");
1299
+ setInstanceStateValue(this, 4, url);
1300
+ setter(this, ["src"], url);
1301
+ orgUrl !== url && setter(this, ["dataset", "ptsrc"], orgUrl);
1302
+ if (this.type && config.loadScriptsOnMainThread) {
1303
+ const shouldExecuteScriptViaMainThread =
1304
+ config.loadScriptsOnMainThread.some(
1305
+ (scriptUrl) => scriptUrl === url
1306
+ );
1307
+ shouldExecuteScriptViaMainThread &&
1308
+ setter(this, ["type"], "text/javascript");
1309
+ }
1310
+ },
1311
+ },
1312
+ textContent: innerHTMLDescriptor,
1313
+ type: {
1314
+ get() {
1315
+ return getter(this, ["type"]);
1316
+ },
1317
+ set(type) {
1318
+ if (!isScriptJsType(type)) {
1319
+ setInstanceStateValue(this, 5, type);
1320
+ setter(this, ["type"], type);
1321
+ }
1322
+ },
1323
+ },
1324
+ ...HTMLSrcElementDescriptorMap,
482
1325
  };
483
- const callMethod = (instance, applyPath, args, callType, assignInstanceId, buffer, rtnValue, methodName) => {
484
- if (webWorkerCtx.$config$.apply) {
485
- rtnValue = webWorkerCtx.$config$.apply({
486
- args: args,
487
- ...createHookOptions(instance, applyPath)
488
- });
489
- if (rtnValue !== HookContinue) {
490
- return rtnValue;
491
- }
492
- }
493
- methodName = applyPath[len(applyPath) - 1];
494
- applyPath = [ ...applyPath, serializeInstanceForMain(instance, args) ];
495
- callType = callType || (nonBlockingMethods.includes(methodName) ? 2 : 1);
496
- if ("setAttribute" === methodName && hasInstanceStateValue(instance, args[0])) {
497
- setInstanceStateValue(instance, args[0], args[1]);
498
- } else if (structureChangingMethodNames.includes(methodName)) {
499
- cachedDimensions.clear();
500
- cachedStructure.clear();
501
- ((target, methodName) => {
502
- (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) && logWorker(`Dimension and DOM structure cache cleared from method call ${methodName}()`, target[WinIdKey]);
503
- })(instance, methodName);
504
- } else if (dimensionChangingMethodNames.includes(methodName)) {
505
- callType = 2;
506
- cachedDimensions.clear();
507
- logDimensionCacheClearMethod(instance, methodName);
1326
+ definePrototypePropertyDescriptor(
1327
+ WorkerHTMLScriptElement,
1328
+ HTMLScriptDescriptorMap
1329
+ );
1330
+ };
1331
+ const innerHTMLDescriptor = {
1332
+ get() {
1333
+ const type = getter(this, ["type"]);
1334
+ return isScriptJsType(type)
1335
+ ? getInstanceStateValue(this, 3) || ""
1336
+ : getter(this, ["innerHTML"]);
1337
+ },
1338
+ set(scriptContent) {
1339
+ setInstanceStateValue(this, 3, scriptContent);
1340
+ },
1341
+ };
1342
+ const isScriptJsType = (scriptType) =>
1343
+ !scriptType || "text/javascript" === scriptType;
1344
+ const createNodeCstr = (win, env, WorkerBase) => {
1345
+ const config = webWorkerCtx.$config$;
1346
+ const WorkerNode = defineConstructorName(
1347
+ class extends WorkerBase {
1348
+ appendChild(node) {
1349
+ return this.insertBefore(node, null);
508
1350
  }
509
- rtnValue = queue(instance, applyPath, callType, assignInstanceId, void 0, buffer);
510
- ((target, applyPath, args, rtnValue) => {
511
- if (webWorkerCtx.$config$.logCalls) {
512
- try {
513
- applyPath = applyPath.slice(0, applyPath.length - 1);
514
- logWorker(`Call ${getTargetProp(target, applyPath)}(${args.map((v => getLogValue(applyPath, v))).join(", ")}), returned: ${getLogValue(applyPath, rtnValue)}`, target[WinIdKey]);
515
- } catch (e) {}
516
- }
517
- })(instance, applyPath, args, rtnValue);
518
- return rtnValue;
519
- };
520
- const constructGlobal = (instance, cstrName, args) => {
521
- ((target, cstrName, args) => {
522
- if (webWorkerCtx.$config$.logCalls) {
523
- try {
524
- logWorker(`Construct new ${cstrName}(${args.map((v => getLogValue([], v))).join(", ")})`, target[WinIdKey]);
525
- } catch (e) {}
526
- }
527
- })(instance, cstrName, args);
528
- queue(instance, [ 1, cstrName, serializeInstanceForMain(instance, args) ], 1);
529
- };
530
- const createHookOptions = (instance, applyPath) => ({
531
- name: applyPath.join("."),
532
- continue: HookContinue,
533
- nodeName: instance[InstanceDataKey],
534
- constructor: getConstructorName(instance),
535
- instance: instance,
536
- window: environments[instance[WinIdKey]].$window$
537
- });
538
- const addStorageApi = (win, storageName, storages, isSameOrigin, env) => {
539
- let getItems = items => {
540
- items = storages.get(win.origin);
541
- items || storages.set(win.origin, items = []);
542
- return items;
543
- };
544
- let getIndexByKey = key => getItems().findIndex((i => i[STORAGE_KEY] === key));
545
- let index;
546
- let item;
547
- let storage = {
548
- getItem(key) {
549
- index = getIndexByKey(key);
550
- return index > -1 ? getItems()[index][STORAGE_VALUE] : null;
551
- },
552
- setItem(key, value) {
553
- index = getIndexByKey(key);
554
- index > -1 ? getItems()[index][STORAGE_VALUE] = value : getItems().push([ key, value ]);
555
- isSameOrigin ? callMethod(win, [ storageName, "setItem" ], [ key, value ], 2) : warnCrossOrgin("set", storageName, env);
556
- },
557
- removeItem(key) {
558
- index = getIndexByKey(key);
559
- index > -1 && getItems().splice(index, 1);
560
- isSameOrigin ? callMethod(win, [ storageName, "removeItem" ], [ key ], 2) : warnCrossOrgin("remove", storageName, env);
561
- },
562
- key(index) {
563
- item = getItems()[index];
564
- return item ? item[STORAGE_KEY] : null;
565
- },
566
- clear() {
567
- getItems().length = 0;
568
- isSameOrigin ? callMethod(win, [ storageName, "clear" ], EMPTY_ARRAY, 2) : warnCrossOrgin("clear", storageName, env);
569
- },
570
- get length() {
571
- return getItems().length;
572
- }
573
- };
574
- win[storageName] = new Proxy(storage, {
575
- get: (target, key) => Reflect.has(target, key) ? Reflect.get(target, key) : target.getItem(key),
576
- set(target, key, value) {
577
- target.setItem(key, value);
578
- return true;
579
- },
580
- has: (target, key) => !!Reflect.has(target, key) || "string" == typeof key && null !== target.getItem(key),
581
- deleteProperty(target, key) {
582
- target.removeItem(key);
583
- return true;
584
- }
585
- });
586
- };
587
- const STORAGE_KEY = 0;
588
- const STORAGE_VALUE = 1;
589
- const createCSSStyleDeclarationCstr = (win, WorkerBase, cstrName) => {
590
- win[cstrName] = defineConstructorName(class extends WorkerBase {
591
- constructor(winId, instanceId, applyPath, styles) {
592
- super(winId, instanceId, applyPath, styles || {});
593
- return new Proxy(this, {
594
- get(target, propName) {
595
- if (target[propName]) {
596
- return target[propName];
597
- }
598
- target[propName] || "string" != typeof propName || target[InstanceDataKey][propName] || (target[InstanceDataKey][propName] = getter(target, [ propName ]));
599
- return target[InstanceDataKey][propName];
600
- },
601
- set(target, propName, propValue) {
602
- target[InstanceDataKey][propName] = propValue;
603
- setter(target, [ propName ], propValue);
604
- logDimensionCacheClearStyle(target, propName);
605
- cachedDimensions.clear();
606
- return true;
607
- }
608
- });
609
- }
610
- setProperty(...args) {
611
- this[InstanceDataKey][args[0]] = args[1];
612
- callMethod(this, [ "setProperty" ], args, 2);
613
- logDimensionCacheClearStyle(this, args[0]);
614
- cachedDimensions.clear();
615
- }
616
- getPropertyValue(propName) {
617
- return this[propName];
618
- }
619
- removeProperty(propName) {
620
- let value = this[InstanceDataKey][propName];
621
- callMethod(this, [ "removeProperty" ], [ propName ], 2);
622
- logDimensionCacheClearStyle(this, propName);
623
- cachedDimensions.clear();
624
- this[InstanceDataKey][propName] = void 0;
625
- return value;
626
- }
627
- }, cstrName);
628
- };
629
- const createCSSStyleSheetConstructor = (win, cssStyleSheetCstrName) => {
630
- win[cssStyleSheetCstrName] = defineConstructorName(class {
631
- constructor(ownerNode) {
632
- this.ownerNode = ownerNode;
633
- }
634
- get cssRules() {
635
- const ownerNode = this.ownerNode;
636
- return new Proxy({}, {
637
- get(target, propKey) {
638
- const propName = String(propKey);
639
- return "item" === propName ? index => getCssRule(ownerNode, index) : "length" === propName ? getCssRules(ownerNode).length : isNaN(propName) ? target[propKey] : getCssRule(ownerNode, propName);
640
- }
641
- });
642
- }
643
- insertRule(ruleText, index) {
644
- const cssRules = getCssRules(this.ownerNode);
645
- index = void 0 === index ? 0 : index;
646
- if (index >= 0 && index <= cssRules.length) {
647
- callMethod(this.ownerNode, [ "sheet", "insertRule" ], [ ruleText, index ], 2);
648
- cssRules.splice(index, 0, 0);
1351
+ get href() {}
1352
+ set href(_) {}
1353
+ insertBefore(newNode, referenceNode) {
1354
+ var _a, _b;
1355
+ const winId = (newNode[WinIdKey] = this[WinIdKey]);
1356
+ const instanceId = newNode[InstanceIdKey];
1357
+ const nodeName = newNode[InstanceDataKey];
1358
+ const isScript = "SCRIPT" === nodeName;
1359
+ const isIFrame = "INPUT" === nodeName;
1360
+ if (isScript) {
1361
+ const scriptContent = getInstanceStateValue(newNode, 3);
1362
+ const scriptType = getInstanceStateValue(newNode, 5);
1363
+ if (scriptContent) {
1364
+ if (isScriptJsType(scriptType)) {
1365
+ const scriptId = newNode.id;
1366
+ const loadOnMainThread =
1367
+ scriptId &&
1368
+ (null ===
1369
+ (_b =
1370
+ null === (_a = config.loadScriptsOnMainThread) ||
1371
+ void 0 === _a
1372
+ ? void 0
1373
+ : _a.includes) || void 0 === _b
1374
+ ? void 0
1375
+ : _b.call(_a, scriptId));
1376
+ if (loadOnMainThread) {
1377
+ setter(newNode, ["type"], "text/javascript");
1378
+ } else {
1379
+ const errorMsg = runScriptContent(
1380
+ env,
1381
+ instanceId,
1382
+ scriptContent,
1383
+ winId,
1384
+ ""
1385
+ );
1386
+ const datasetType = errorMsg ? "pterror" : "ptid";
1387
+ const datasetValue = errorMsg || instanceId;
1388
+ setter(newNode, ["type"], "text/partytown-x");
1389
+ setter(newNode, ["dataset", datasetType], datasetValue);
649
1390
  }
650
- logDimensionCacheClearMethod(this.ownerNode, "insertRule");
651
- cachedDimensions.clear();
652
- return index;
653
- }
654
- deleteRule(index) {
655
- callMethod(this.ownerNode, [ "sheet", "deleteRule" ], [ index ], 2);
656
- getCssRules(this.ownerNode).splice(index, 1);
657
- logDimensionCacheClearMethod(this.ownerNode, "deleteRule");
658
- cachedDimensions.clear();
659
- }
660
- get type() {
661
- return "text/css";
662
- }
663
- }, cssStyleSheetCstrName);
664
- const HTMLStyleDescriptorMap = {
665
- sheet: {
666
- get() {
667
- return new win[cssStyleSheetCstrName](this);
1391
+ }
1392
+ setter(newNode, ["innerHTML"], scriptContent);
1393
+ }
1394
+ }
1395
+ callMethod(this, ["insertBefore"], [newNode, referenceNode], 2);
1396
+ if (isIFrame) {
1397
+ const src = getInstanceStateValue(newNode, 0);
1398
+ if (src && src.startsWith("javascript:")) {
1399
+ const scriptContent = src.split("javascript:")[1];
1400
+ runScriptContent(env, instanceId, scriptContent, winId, "");
1401
+ }
1402
+ ((winId, iframe) => {
1403
+ let i = 0;
1404
+ let type;
1405
+ let handlers;
1406
+ let callback = () => {
1407
+ if (
1408
+ environments[winId] &&
1409
+ environments[winId].$isInitialized$ &&
1410
+ !environments[winId].$isLoading$
1411
+ ) {
1412
+ type = getInstanceStateValue(iframe, 1) ? "error" : "load";
1413
+ handlers = getInstanceStateValue(iframe, type);
1414
+ handlers &&
1415
+ handlers.map((handler) =>
1416
+ handler({
1417
+ type: type,
1418
+ })
1419
+ );
1420
+ } else if (i++ > 2e3) {
1421
+ handlers = getInstanceStateValue(iframe, "error");
1422
+ handlers &&
1423
+ handlers.map((handler) =>
1424
+ handler({
1425
+ type: "error",
1426
+ })
1427
+ );
1428
+ } else {
1429
+ setTimeout(callback, 9);
668
1430
  }
669
- }
670
- };
671
- definePrototypePropertyDescriptor(win.HTMLStyleElement, HTMLStyleDescriptorMap);
672
- };
673
- const getCssRules = (ownerNode, cssRules) => {
674
- cssRules = getInstanceStateValue(ownerNode, 2);
675
- if (!cssRules) {
676
- cssRules = getter(ownerNode, [ "sheet", "cssRules" ]);
677
- setInstanceStateValue(ownerNode, 2, cssRules);
678
- }
679
- return cssRules;
680
- };
681
- const getCssRule = (ownerNode, index, cssRules) => {
682
- cssRules = getCssRules(ownerNode);
683
- 0 === cssRules[index] && (cssRules[index] = getter(ownerNode, [ "sheet", "cssRules", parseInt(index, 10) ]));
684
- return cssRules[index];
685
- };
686
- const runScriptContent = (env, instanceId, scriptContent, winId, errorMsg) => {
687
- try {
688
- webWorkerCtx.$config$.logScriptExecution && logWorker(`Execute script: ${scriptContent.substring(0, 100).split("\n").map((l => l.trim())).join(" ").trim().substring(0, 60)}...`, winId);
689
- env.$currentScriptId$ = instanceId;
690
- run(env, scriptContent);
691
- } catch (contentError) {
692
- console.error(scriptContent, contentError);
693
- errorMsg = String(contentError.stack || contentError);
694
- }
695
- env.$currentScriptId$ = "";
696
- return errorMsg;
697
- };
698
- const run = (env, scriptContent, scriptUrl) => {
699
- env.$runWindowLoadEvent$ = 1;
700
- scriptContent = `with(this){${scriptContent.replace(/\bthis\b/g, "(thi$(this)?window:this)").replace(/\/\/# so/g, "//Xso")}\n;function thi$(t){return t===this}};${(webWorkerCtx.$config$.globalFns || []).filter((globalFnName => /[a-zA-Z_$][0-9a-zA-Z_$]*/.test(globalFnName))).map((g => `(typeof ${g}=='function'&&(this.${g}=${g}))`)).join(";")};` + (scriptUrl ? "\n//# sourceURL=" + scriptUrl : "");
701
- env.$isSameOrigin$ || (scriptContent = scriptContent.replace(/.postMessage\(/g, `.postMessage('${env.$winId$}',`));
702
- new Function(scriptContent).call(env.$window$);
703
- env.$runWindowLoadEvent$ = 0;
704
- };
705
- const runStateLoadHandlers = (instance, type, handlers) => {
706
- handlers = getInstanceStateValue(instance, type);
707
- handlers && setTimeout((() => handlers.map((cb => cb({
708
- type: type
709
- })))));
710
- };
711
- const resolveToUrl = (env, url, type, baseLocation, resolvedUrl, configResolvedUrl) => {
712
- baseLocation = env.$location$;
713
- while (!baseLocation.host) {
714
- env = environments[env.$parentWinId$];
715
- baseLocation = env.$location$;
716
- if (env.$winId$ === env.$parentWinId$) {
717
- break;
718
- }
719
- }
720
- resolvedUrl = new URL(url || "", baseLocation);
721
- if (type && webWorkerCtx.$config$.resolveUrl) {
722
- configResolvedUrl = webWorkerCtx.$config$.resolveUrl(resolvedUrl, baseLocation, type);
723
- if (configResolvedUrl) {
724
- return configResolvedUrl;
725
- }
726
- }
727
- return resolvedUrl;
728
- };
729
- const resolveUrl = (env, url, type) => resolveToUrl(env, url, type) + "";
730
- const getPartytownScript = () => `<script src="${partytownLibUrl("partytown.js?v=0.7.5")}"><\/script>`;
731
- const createImageConstructor = env => class HTMLImageElement {
732
- constructor() {
733
- this.s = "";
734
- this.l = [];
735
- this.e = [];
736
- this.style = {};
737
- }
738
- get src() {
739
- return this.s;
740
- }
741
- set src(src) {
742
- webWorkerCtx.$config$.logImageRequests && logWorker(`Image() request: ${resolveUrl(env, src, "image")}`, env.$winId$);
743
- this.s = src;
744
- fetch(resolveUrl(env, src, "image"), {
745
- mode: "no-cors",
746
- credentials: "include",
747
- keepalive: true
748
- }).then((rsp => {
749
- rsp.ok || 0 === rsp.status ? this.l.map((cb => cb({
750
- type: "load"
751
- }))) : this.e.map((cb => cb({
752
- type: "error"
753
- })));
754
- }), (() => this.e.forEach((cb => cb({
755
- type: "error"
756
- })))));
757
- }
758
- addEventListener(eventName, cb) {
759
- "load" === eventName && this.l.push(cb);
760
- "error" === eventName && this.e.push(cb);
1431
+ };
1432
+ callback();
1433
+ })(instanceId, newNode);
1434
+ }
1435
+ if (isScript) {
1436
+ sendToMain(true);
1437
+ webWorkerCtx.$postMessage$([7, winId]);
1438
+ }
1439
+ return newNode;
761
1440
  }
762
- get onload() {
763
- return this.l[0];
764
- }
765
- set onload(cb) {
766
- this.l = [ cb ];
1441
+ get nodeName() {
1442
+ return "#s" === this[InstanceDataKey]
1443
+ ? "#document-fragment"
1444
+ : this[InstanceDataKey];
767
1445
  }
768
- get onerror() {
769
- return this.e[0];
1446
+ get nodeType() {
1447
+ return 3;
770
1448
  }
771
- set onerror(cb) {
772
- this.e = [ cb ];
1449
+ get ownerDocument() {
1450
+ return env.$document$;
773
1451
  }
774
- };
775
- const HTMLSrcElementDescriptorMap = {
776
- addEventListener: {
777
- value(...args) {
778
- const eventName = args[0];
779
- const callbacks = getInstanceStateValue(this, eventName) || [];
780
- callbacks.push(args[1]);
781
- setInstanceStateValue(this, eventName, callbacks);
782
- }
1452
+ },
1453
+ "Node"
1454
+ );
1455
+ cachedTreeProps(
1456
+ WorkerNode,
1457
+ commaSplit(
1458
+ "childNodes,firstChild,isConnected,lastChild,nextSibling,parentElement,parentNode,previousSibling"
1459
+ )
1460
+ );
1461
+ win.Node = WorkerNode;
1462
+ };
1463
+ const htmlMedia = commaSplit("AUDIO,CANVAS,VIDEO");
1464
+ const windowMediaConstructors = commaSplit("Audio,MediaSource");
1465
+ const patchDocument = (WorkerDocument, env, isDocumentImplementation) => {
1466
+ const DocumentDescriptorMap = {
1467
+ body: {
1468
+ get: () => env.$body$,
1469
+ },
1470
+ cookie: {
1471
+ get() {
1472
+ if (env.$isSameOrigin$) {
1473
+ return getter(this, ["cookie"]);
1474
+ }
1475
+ warnCrossOrgin("get", "cookie", env);
1476
+ return "";
783
1477
  },
784
- async: {
785
- get: noop,
786
- set: noop
1478
+ set(value) {
1479
+ if (env.$isSameOrigin$) {
1480
+ setter(this, ["cookie"], value);
1481
+ } else {
1482
+ warnCrossOrgin("set", "cookie", env);
1483
+ }
787
1484
  },
788
- defer: {
789
- get: noop,
790
- set: noop
1485
+ },
1486
+ createElement: {
1487
+ value(tagName) {
1488
+ tagName = tagName.toUpperCase();
1489
+ if (!IS_TAG_REG.test(tagName)) {
1490
+ throw tagName + " not valid";
1491
+ }
1492
+ const isIframe = "IFRAME" === tagName;
1493
+ const winId = this[WinIdKey];
1494
+ const instanceId = (isIframe ? "f_" : "") + randomId();
1495
+ callMethod(this, ["createElement"], [tagName], 2, instanceId);
1496
+ const elm = getOrCreateNodeInstance(winId, instanceId, tagName);
1497
+ if (isIframe) {
1498
+ const env = createEnvironment(
1499
+ {
1500
+ $winId$: instanceId,
1501
+ $parentWinId$: winId,
1502
+ $url$: "about:blank",
1503
+ },
1504
+ true
1505
+ );
1506
+ env.$window$.fetch = fetch;
1507
+ setter(elm, ["srcdoc"], getPartytownScript());
1508
+ } else if ("SCRIPT" === tagName) {
1509
+ const scriptType = getInstanceStateValue(elm, 5);
1510
+ isScriptJsType(scriptType) &&
1511
+ setter(elm, ["type"], "text/partytown");
1512
+ }
1513
+ return elm;
791
1514
  },
792
- onload: {
793
- get() {
794
- let callbacks = getInstanceStateValue(this, "load");
795
- return callbacks && callbacks[0] || null;
796
- },
797
- set(cb) {
798
- setInstanceStateValue(this, "load", cb ? [ cb ] : null);
799
- }
1515
+ },
1516
+ createElementNS: {
1517
+ value(namespace, tagName) {
1518
+ const instanceId = randomId();
1519
+ const nsElm = getOrCreateNodeInstance(
1520
+ this[WinIdKey],
1521
+ instanceId,
1522
+ tagName,
1523
+ namespace
1524
+ );
1525
+ callMethod(
1526
+ this,
1527
+ ["createElementNS"],
1528
+ [namespace, tagName],
1529
+ 2,
1530
+ instanceId
1531
+ );
1532
+ return nsElm;
800
1533
  },
801
- onerror: {
802
- get() {
803
- let callbacks = getInstanceStateValue(this, "error");
804
- return callbacks && callbacks[0] || null;
805
- },
806
- set(cb) {
807
- setInstanceStateValue(this, "error", cb ? [ cb ] : null);
808
- }
1534
+ },
1535
+ createTextNode: {
1536
+ value(text) {
1537
+ const winId = this[WinIdKey];
1538
+ const instanceId = randomId();
1539
+ const textNode = getOrCreateNodeInstance(winId, instanceId, "#text");
1540
+ callMethod(this, ["createTextNode"], [text], 2, instanceId);
1541
+ return textNode;
809
1542
  },
810
- getAttribute: {
811
- value(attrName) {
812
- return "src" === attrName ? this.src : callMethod(this, [ "getAttribute" ], [ attrName ]);
813
- }
1543
+ },
1544
+ createEvent: {
1545
+ value: (type) => new Event(type),
1546
+ },
1547
+ currentScript: {
1548
+ get() {
1549
+ return env.$currentScriptId$
1550
+ ? getOrCreateNodeInstance(
1551
+ this[WinIdKey],
1552
+ env.$currentScriptId$,
1553
+ "SCRIPT"
1554
+ )
1555
+ : null;
814
1556
  },
815
- setAttribute: {
816
- value(attrName, attrValue) {
817
- scriptAttrPropNames.includes(attrName) ? this[attrName] = attrValue : callMethod(this, [ "setAttribute" ], [ attrName, attrValue ]);
818
- }
819
- }
820
- };
821
- const scriptAttrPropNames = commaSplit("src,type");
822
- const patchHTMLScriptElement = (WorkerHTMLScriptElement, env) => {
823
- const HTMLScriptDescriptorMap = {
824
- innerHTML: innerHTMLDescriptor,
825
- innerText: innerHTMLDescriptor,
826
- src: {
827
- get() {
828
- return getInstanceStateValue(this, 4) || "";
829
- },
830
- set(url) {
831
- const orgUrl = resolveUrl(env, url, null);
832
- const config = webWorkerCtx.$config$;
833
- url = resolveUrl(env, url, "script");
834
- setInstanceStateValue(this, 4, url);
835
- setter(this, [ "src" ], url);
836
- orgUrl !== url && setter(this, [ "dataset", "ptsrc" ], orgUrl);
837
- if (this.type && config.loadScriptsOnMainThread) {
838
- const shouldExecuteScriptViaMainThread = config.loadScriptsOnMainThread.some((scriptUrl => scriptUrl === url));
839
- shouldExecuteScriptViaMainThread && setter(this, [ "type" ], "text/javascript");
840
- }
1557
+ },
1558
+ defaultView: {
1559
+ get: () => (isDocumentImplementation ? null : env.$window$),
1560
+ },
1561
+ documentElement: {
1562
+ get: () => env.$documentElement$,
1563
+ },
1564
+ getElementsByTagName: {
1565
+ value(tagName) {
1566
+ tagName = tagName.toUpperCase();
1567
+ return "BODY" === tagName
1568
+ ? [env.$body$]
1569
+ : "HEAD" === tagName
1570
+ ? [env.$head$]
1571
+ : callMethod(this, ["getElementsByTagName"], [tagName]);
1572
+ },
1573
+ },
1574
+ head: {
1575
+ get: () => env.$head$,
1576
+ },
1577
+ images: {
1578
+ get() {
1579
+ return getter(this, ["images"]);
1580
+ },
1581
+ },
1582
+ implementation: {
1583
+ get() {
1584
+ return {
1585
+ hasFeature: () => true,
1586
+ createHTMLDocument: (title) => {
1587
+ const $winId$ = randomId();
1588
+ callMethod(
1589
+ this,
1590
+ ["implementation", "createHTMLDocument"],
1591
+ [title],
1592
+ 1,
1593
+ {
1594
+ $winId$: $winId$,
841
1595
  }
842
- },
843
- textContent: innerHTMLDescriptor,
844
- type: {
845
- get() {
846
- return getter(this, [ "type" ]);
1596
+ );
1597
+ const docEnv = createEnvironment(
1598
+ {
1599
+ $winId$: $winId$,
1600
+ $parentWinId$: $winId$,
1601
+ $url$: env.$location$ + "",
1602
+ $visibilityState$: "hidden",
847
1603
  },
848
- set(type) {
849
- if (!isScriptJsType(type)) {
850
- setInstanceStateValue(this, 5, type);
851
- setter(this, [ "type" ], type);
852
- }
853
- }
1604
+ true,
1605
+ true
1606
+ );
1607
+ return docEnv.$document$;
854
1608
  },
855
- ...HTMLSrcElementDescriptorMap
856
- };
857
- definePrototypePropertyDescriptor(WorkerHTMLScriptElement, HTMLScriptDescriptorMap);
1609
+ };
1610
+ },
1611
+ },
1612
+ location: {
1613
+ get: () => env.$location$,
1614
+ set(url) {
1615
+ env.$location$.href = url + "";
1616
+ },
1617
+ },
1618
+ nodeType: {
1619
+ value: 9,
1620
+ },
1621
+ parentNode: {
1622
+ value: null,
1623
+ },
1624
+ parentElement: {
1625
+ value: null,
1626
+ },
1627
+ readyState: {
1628
+ value: "complete",
1629
+ },
1630
+ visibilityState: {
1631
+ get: () => env.$visibilityState$ || "visible",
1632
+ },
858
1633
  };
859
- const innerHTMLDescriptor = {
1634
+ definePrototypePropertyDescriptor(WorkerDocument, DocumentDescriptorMap);
1635
+ cachedProps(WorkerDocument, "compatMode,referrer,forms");
1636
+ };
1637
+ const patchDocumentElementChild = (WokerDocumentElementChild, env) => {
1638
+ const DocumentElementChildDescriptorMap = {
1639
+ parentElement: {
860
1640
  get() {
861
- const type = getter(this, [ "type" ]);
862
- return isScriptJsType(type) ? getInstanceStateValue(this, 3) || "" : getter(this, [ "innerHTML" ]);
1641
+ return this.parentNode;
863
1642
  },
864
- set(scriptContent) {
865
- setInstanceStateValue(this, 3, scriptContent);
866
- }
1643
+ },
1644
+ parentNode: {
1645
+ get: () => env.$documentElement$,
1646
+ },
867
1647
  };
868
- const isScriptJsType = scriptType => !scriptType || "text/javascript" === scriptType;
869
- const createNodeCstr = (win, env, WorkerBase) => {
870
- const config = webWorkerCtx.$config$;
871
- const WorkerNode = defineConstructorName(class extends WorkerBase {
872
- appendChild(node) {
873
- return this.insertBefore(node, null);
874
- }
875
- get href() {}
876
- set href(_) {}
877
- insertBefore(newNode, referenceNode) {
878
- var _a, _b;
879
- const winId = newNode[WinIdKey] = this[WinIdKey];
880
- const instanceId = newNode[InstanceIdKey];
881
- const nodeName = newNode[InstanceDataKey];
882
- const isScript = "SCRIPT" === nodeName;
883
- const isIFrame = "IFRAME" === nodeName;
884
- if (isScript) {
885
- const scriptContent = getInstanceStateValue(newNode, 3);
886
- const scriptType = getInstanceStateValue(newNode, 5);
887
- if (scriptContent) {
888
- if (isScriptJsType(scriptType)) {
889
- const scriptId = newNode.id;
890
- const loadOnMainThread = scriptId && (null === (_b = null === (_a = config.loadScriptsOnMainThread) || void 0 === _a ? void 0 : _a.includes) || void 0 === _b ? void 0 : _b.call(_a, scriptId));
891
- if (loadOnMainThread) {
892
- setter(newNode, [ "type" ], "text/javascript");
893
- } else {
894
- const errorMsg = runScriptContent(env, instanceId, scriptContent, winId, "");
895
- const datasetType = errorMsg ? "pterror" : "ptid";
896
- const datasetValue = errorMsg || instanceId;
897
- setter(newNode, [ "type" ], "text/partytown-x");
898
- setter(newNode, [ "dataset", datasetType ], datasetValue);
899
- }
900
- }
901
- setter(newNode, [ "innerHTML" ], scriptContent);
902
- }
903
- }
904
- callMethod(this, [ "insertBefore" ], [ newNode, referenceNode ], 2);
905
- if (isIFrame) {
906
- const src = getInstanceStateValue(newNode, 0);
907
- if (src && src.startsWith("javascript:")) {
908
- const scriptContent = src.split("javascript:")[1];
909
- runScriptContent(env, instanceId, scriptContent, winId, "");
910
- }
911
- ((winId, iframe) => {
912
- let i = 0;
913
- let type;
914
- let handlers;
915
- let callback = () => {
916
- if (environments[winId] && environments[winId].$isInitialized$ && !environments[winId].$isLoading$) {
917
- type = getInstanceStateValue(iframe, 1) ? "error" : "load";
918
- handlers = getInstanceStateValue(iframe, type);
919
- handlers && handlers.map((handler => handler({
920
- type: type
921
- })));
922
- } else if (i++ > 2e3) {
923
- handlers = getInstanceStateValue(iframe, "error");
924
- handlers && handlers.map((handler => handler({
925
- type: "error"
926
- })));
927
- } else {
928
- setTimeout(callback, 9);
929
- }
930
- };
931
- callback();
932
- })(instanceId, newNode);
933
- }
934
- if (isScript) {
935
- sendToMain(true);
936
- webWorkerCtx.$postMessage$([ 7, winId ]);
937
- }
938
- return newNode;
939
- }
940
- get nodeName() {
941
- return "#s" === this[InstanceDataKey] ? "#document-fragment" : this[InstanceDataKey];
942
- }
943
- get nodeType() {
944
- return 3;
945
- }
946
- get ownerDocument() {
947
- return env.$document$;
948
- }
949
- }, "Node");
950
- cachedTreeProps(WorkerNode, commaSplit("childNodes,firstChild,isConnected,lastChild,nextSibling,parentElement,parentNode,previousSibling"));
951
- win.Node = WorkerNode;
1648
+ definePrototypePropertyDescriptor(
1649
+ WokerDocumentElementChild,
1650
+ DocumentElementChildDescriptorMap
1651
+ );
1652
+ };
1653
+ const patchElement = (WorkerElement, WorkerHTMLElement) => {
1654
+ const ElementDescriptorMap = {
1655
+ localName: {
1656
+ get() {
1657
+ return this[InstanceDataKey].toLowerCase();
1658
+ },
1659
+ },
1660
+ namespaceURI: {
1661
+ get() {
1662
+ return this[NamespaceKey] || "http://www.w3.org/1999/xhtml";
1663
+ },
1664
+ },
1665
+ nodeType: {
1666
+ value: 1,
1667
+ },
1668
+ tagName: {
1669
+ get() {
1670
+ return this[InstanceDataKey];
1671
+ },
1672
+ },
952
1673
  };
953
- const htmlMedia = commaSplit("AUDIO,CANVAS,VIDEO");
954
- const windowMediaConstructors = commaSplit("Audio,MediaSource");
955
- const patchDocument = (WorkerDocument, env, isDocumentImplementation) => {
956
- const DocumentDescriptorMap = {
957
- body: {
958
- get: () => env.$body$
959
- },
960
- cookie: {
961
- get() {
962
- if (env.$isSameOrigin$) {
963
- return getter(this, [ "cookie" ]);
964
- }
965
- warnCrossOrgin("get", "cookie", env);
966
- return "";
967
- },
968
- set(value) {
969
- if (env.$isSameOrigin$) {
970
- setter(this, [ "cookie" ], value);
971
- } else {
972
- warnCrossOrgin("set", "cookie", env);
973
- }
974
- }
975
- },
976
- createElement: {
977
- value(tagName) {
978
- tagName = tagName.toUpperCase();
979
- if (!IS_TAG_REG.test(tagName)) {
980
- throw tagName + " not valid";
981
- }
982
- const isIframe = "IFRAME" === tagName;
983
- const winId = this[WinIdKey];
984
- const instanceId = (isIframe ? "f_" : "") + randomId();
985
- callMethod(this, [ "createElement" ], [ tagName ], 2, instanceId);
986
- const elm = getOrCreateNodeInstance(winId, instanceId, tagName);
987
- if (isIframe) {
988
- const env = createEnvironment({
989
- $winId$: instanceId,
990
- $parentWinId$: winId,
991
- $url$: "about:blank"
992
- }, true);
993
- env.$window$.fetch = fetch;
994
- setter(elm, [ "srcdoc" ], getPartytownScript());
995
- } else if ("SCRIPT" === tagName) {
996
- const scriptType = getInstanceStateValue(elm, 5);
997
- isScriptJsType(scriptType) && setter(elm, [ "type" ], "text/partytown");
998
- }
999
- return elm;
1000
- }
1001
- },
1002
- createElementNS: {
1003
- value(namespace, tagName) {
1004
- const instanceId = randomId();
1005
- const nsElm = getOrCreateNodeInstance(this[WinIdKey], instanceId, tagName, namespace);
1006
- callMethod(this, [ "createElementNS" ], [ namespace, tagName ], 2, instanceId);
1007
- return nsElm;
1008
- }
1009
- },
1010
- createTextNode: {
1011
- value(text) {
1012
- const winId = this[WinIdKey];
1013
- const instanceId = randomId();
1014
- const textNode = getOrCreateNodeInstance(winId, instanceId, "#text");
1015
- callMethod(this, [ "createTextNode" ], [ text ], 2, instanceId);
1016
- return textNode;
1017
- }
1018
- },
1019
- createEvent: {
1020
- value: type => new Event(type)
1021
- },
1022
- currentScript: {
1023
- get() {
1024
- return env.$currentScriptId$ ? getOrCreateNodeInstance(this[WinIdKey], env.$currentScriptId$, "SCRIPT") : null;
1025
- }
1026
- },
1027
- defaultView: {
1028
- get: () => isDocumentImplementation ? null : env.$window$
1029
- },
1030
- documentElement: {
1031
- get: () => env.$documentElement$
1032
- },
1033
- getElementsByTagName: {
1034
- value(tagName) {
1035
- tagName = tagName.toUpperCase();
1036
- return "BODY" === tagName ? [ env.$body$ ] : "HEAD" === tagName ? [ env.$head$ ] : callMethod(this, [ "getElementsByTagName" ], [ tagName ]);
1037
- }
1038
- },
1039
- head: {
1040
- get: () => env.$head$
1041
- },
1042
- images: {
1043
- get() {
1044
- return getter(this, [ "images" ]);
1674
+ definePrototypePropertyDescriptor(WorkerElement, ElementDescriptorMap);
1675
+ cachedTreeProps(WorkerElement, elementStructurePropNames);
1676
+ cachedProps(WorkerElement, "id");
1677
+ cachedDimensionProps(WorkerHTMLElement);
1678
+ cachedDimensionMethods(
1679
+ WorkerHTMLElement,
1680
+ commaSplit("getClientRects,getBoundingClientRect")
1681
+ );
1682
+ };
1683
+ const patchHTMLAnchorElement = (WorkerHTMLAnchorElement, env) => {
1684
+ const HTMLAnchorDescriptorMap = {};
1685
+ commaSplit(
1686
+ "hash,host,hostname,href,origin,pathname,port,protocol,search"
1687
+ ).map((anchorProp) => {
1688
+ HTMLAnchorDescriptorMap[anchorProp] = {
1689
+ get() {
1690
+ let value = getInstanceStateValue(this, 4);
1691
+ let href;
1692
+ if ("string" != typeof value) {
1693
+ href = getter(this, ["href"]);
1694
+ setInstanceStateValue(this, 4, href);
1695
+ value = new URL(href)[anchorProp];
1696
+ }
1697
+ return resolveToUrl(env, value, null)[anchorProp];
1698
+ },
1699
+ set(value) {
1700
+ let url;
1701
+ if ("href" === anchorProp) {
1702
+ if (
1703
+ ((url) => {
1704
+ try {
1705
+ new URL(url);
1706
+ return true;
1707
+ } catch (_) {
1708
+ return false;
1045
1709
  }
1046
- },
1047
- implementation: {
1048
- get() {
1049
- return {
1050
- hasFeature: () => true,
1051
- createHTMLDocument: title => {
1052
- const $winId$ = randomId();
1053
- callMethod(this, [ "implementation", "createHTMLDocument" ], [ title ], 1, {
1054
- $winId$: $winId$
1055
- });
1056
- const docEnv = createEnvironment({
1057
- $winId$: $winId$,
1058
- $parentWinId$: $winId$,
1059
- $url$: env.$location$ + "",
1060
- $visibilityState$: "hidden"
1061
- }, true, true);
1062
- return docEnv.$document$;
1710
+ })(value)
1711
+ ) {
1712
+ url = new URL(value);
1713
+ } else {
1714
+ const baseHref = env.$location$.href;
1715
+ url = resolveToUrl(env, baseHref, null);
1716
+ url.href = new URL(value + "", url.href);
1717
+ }
1718
+ } else {
1719
+ url = resolveToUrl(env, this.href, null);
1720
+ url[anchorProp] = value;
1721
+ }
1722
+ setInstanceStateValue(this, 4, url.href);
1723
+ setter(this, ["href"], url.href);
1724
+ },
1725
+ };
1726
+ });
1727
+ definePrototypePropertyDescriptor(
1728
+ WorkerHTMLAnchorElement,
1729
+ HTMLAnchorDescriptorMap
1730
+ );
1731
+ };
1732
+ const patchHTMLIFrameElement = (WorkerHTMLIFrameElement, env) => {
1733
+ const HTMLIFrameDescriptorMap = {
1734
+ contentDocument: {
1735
+ get() {
1736
+ return getIframeEnv(this).$document$;
1737
+ },
1738
+ },
1739
+ contentWindow: {
1740
+ get() {
1741
+ return getIframeEnv(this).$window$;
1742
+ },
1743
+ },
1744
+ src: {
1745
+ get() {
1746
+ let src = getInstanceStateValue(this, 0);
1747
+ if (src && src.startsWith("javascript:")) {
1748
+ return src;
1749
+ }
1750
+ src = getIframeEnv(this).$location$.href;
1751
+ return src.startsWith("about:") ? "" : src;
1752
+ },
1753
+ set(src) {
1754
+ if (src) {
1755
+ if (src.startsWith("javascript:")) {
1756
+ setInstanceStateValue(this, 0, src);
1757
+ } else if (!src.startsWith("about:")) {
1758
+ let xhr = new XMLHttpRequest();
1759
+ let xhrStatus;
1760
+ let env = getIframeEnv(this);
1761
+ env.$location$.href = src = resolveUrl(env, src, "input");
1762
+ env.$isLoading$ = 1;
1763
+ setInstanceStateValue(this, 1, void 0);
1764
+ xhr.open("GET", src, false);
1765
+ xhr.send();
1766
+ xhrStatus = xhr.status;
1767
+ if (xhrStatus > 199 && xhrStatus < 300) {
1768
+ setter(
1769
+ this,
1770
+ ["srcdoc"],
1771
+ `<base href="${src}">` +
1772
+ (function (text) {
1773
+ return text.replace(SCRIPT_TAG_REGEXP, (_, attrs) => {
1774
+ const parts = [];
1775
+ let hasType = false;
1776
+ let match;
1777
+ while ((match = ATTR_REGEXP.exec(attrs))) {
1778
+ let [keyValue] = match;
1779
+ if (keyValue.startsWith("type=")) {
1780
+ hasType = true;
1781
+ keyValue = keyValue.replace(
1782
+ /(application|text)\/javascript/,
1783
+ SCRIPT_TYPE
1784
+ );
1785
+ }
1786
+ parts.push(keyValue);
1063
1787
  }
1064
- };
1065
- }
1066
- },
1067
- location: {
1068
- get: () => env.$location$,
1069
- set(url) {
1070
- env.$location$.href = url + "";
1071
- }
1072
- },
1073
- nodeType: {
1074
- value: 9
1075
- },
1076
- parentNode: {
1077
- value: null
1078
- },
1079
- parentElement: {
1080
- value: null
1081
- },
1082
- readyState: {
1083
- value: "complete"
1084
- },
1085
- visibilityState: {
1086
- get: () => env.$visibilityState$ || "visible"
1087
- }
1088
- };
1089
- definePrototypePropertyDescriptor(WorkerDocument, DocumentDescriptorMap);
1090
- cachedProps(WorkerDocument, "compatMode,referrer,forms");
1091
- };
1092
- const patchDocumentElementChild = (WokerDocumentElementChild, env) => {
1093
- const DocumentElementChildDescriptorMap = {
1094
- parentElement: {
1095
- get() {
1096
- return this.parentNode;
1097
- }
1098
- },
1099
- parentNode: {
1100
- get: () => env.$documentElement$
1101
- }
1102
- };
1103
- definePrototypePropertyDescriptor(WokerDocumentElementChild, DocumentElementChildDescriptorMap);
1788
+ hasType || parts.push('type="text/partytown"');
1789
+ return `<script ${parts.join(" ")}>`;
1790
+ });
1791
+ })(xhr.responseText) +
1792
+ getPartytownScript()
1793
+ );
1794
+ sendToMain(true);
1795
+ webWorkerCtx.$postMessage$([7, env.$winId$]);
1796
+ } else {
1797
+ setInstanceStateValue(this, 1, xhrStatus);
1798
+ env.$isLoading$ = 0;
1799
+ }
1800
+ }
1801
+ }
1802
+ },
1803
+ },
1804
+ ...HTMLSrcElementDescriptorMap,
1104
1805
  };
1105
- const patchElement = (WorkerElement, WorkerHTMLElement) => {
1106
- const ElementDescriptorMap = {
1107
- localName: {
1108
- get() {
1109
- return this[InstanceDataKey].toLowerCase();
1110
- }
1111
- },
1112
- namespaceURI: {
1113
- get() {
1114
- return this[NamespaceKey] || "http://www.w3.org/1999/xhtml";
1115
- }
1116
- },
1117
- nodeType: {
1118
- value: 1
1119
- },
1120
- tagName: {
1121
- get() {
1122
- return this[InstanceDataKey];
1123
- }
1124
- }
1125
- };
1126
- definePrototypePropertyDescriptor(WorkerElement, ElementDescriptorMap);
1127
- cachedTreeProps(WorkerElement, elementStructurePropNames);
1128
- cachedProps(WorkerElement, "id");
1129
- cachedDimensionProps(WorkerHTMLElement);
1130
- cachedDimensionMethods(WorkerHTMLElement, commaSplit("getClientRects,getBoundingClientRect"));
1806
+ definePrototypePropertyDescriptor(
1807
+ WorkerHTMLIFrameElement,
1808
+ HTMLIFrameDescriptorMap
1809
+ );
1810
+ };
1811
+ const ATTR_REGEXP_STR =
1812
+ "((?:\\w|-)+(?:=(?:(?:\\w|-)+|'[^']*'|\"[^\"]*\")?)?)";
1813
+ const SCRIPT_TAG_REGEXP = new RegExp(
1814
+ `<script\\s*((${ATTR_REGEXP_STR}\\s*)*)>`,
1815
+ "mg"
1816
+ );
1817
+ const ATTR_REGEXP = new RegExp(ATTR_REGEXP_STR, "mg");
1818
+ const getIframeEnv = (iframe) => {
1819
+ const $winId$ = iframe[InstanceIdKey];
1820
+ environments[$winId$] ||
1821
+ createEnvironment(
1822
+ {
1823
+ $winId$: $winId$,
1824
+ $parentWinId$: iframe[WinIdKey],
1825
+ $url$: getter(iframe, ["src"]) || "about:blank",
1826
+ },
1827
+ true
1828
+ );
1829
+ return environments[$winId$];
1830
+ };
1831
+ const patchSvgElement = (WorkerSVGGraphicsElement) => {
1832
+ const getMatrix = (elm, methodName) => {
1833
+ const {
1834
+ a: a,
1835
+ b: b,
1836
+ c: c,
1837
+ d: d,
1838
+ e: e,
1839
+ f: f,
1840
+ } = callMethod(elm, [methodName], EMPTY_ARRAY);
1841
+ return new DOMMatrixReadOnly([a, b, c, d, e, f]);
1131
1842
  };
1132
- const patchHTMLAnchorElement = (WorkerHTMLAnchorElement, env) => {
1133
- const HTMLAnchorDescriptorMap = {};
1134
- commaSplit("hash,host,hostname,href,origin,pathname,port,protocol,search").map((anchorProp => {
1135
- HTMLAnchorDescriptorMap[anchorProp] = {
1136
- get() {
1137
- let value = getInstanceStateValue(this, 4);
1138
- let href;
1139
- if ("string" != typeof value) {
1140
- href = getter(this, [ "href" ]);
1141
- setInstanceStateValue(this, 4, href);
1142
- value = new URL(href)[anchorProp];
1143
- }
1144
- return resolveToUrl(env, value, null)[anchorProp];
1145
- },
1146
- set(value) {
1147
- let url;
1148
- if ("href" === anchorProp) {
1149
- if ((url => {
1150
- try {
1151
- new URL(url);
1152
- return true;
1153
- } catch (_) {
1154
- return false;
1155
- }
1156
- })(value)) {
1157
- url = new URL(value);
1158
- } else {
1159
- const baseHref = env.$location$.href;
1160
- url = resolveToUrl(env, baseHref, null);
1161
- url.href = new URL(value + "", url.href);
1162
- }
1163
- } else {
1164
- url = resolveToUrl(env, this.href, null);
1165
- url[anchorProp] = value;
1166
- }
1167
- setInstanceStateValue(this, 4, url.href);
1168
- setter(this, [ "href" ], url.href);
1169
- }
1170
- };
1171
- }));
1172
- definePrototypePropertyDescriptor(WorkerHTMLAnchorElement, HTMLAnchorDescriptorMap);
1843
+ const SVGGraphicsElementDescriptorMap = {
1844
+ ...WorkerSVGGraphicsElement,
1845
+ getCTM: {
1846
+ value: function () {
1847
+ return getMatrix(this, "getCTM");
1848
+ },
1849
+ },
1850
+ getScreenCTM: {
1851
+ value: function () {
1852
+ return getMatrix(this, "getScreenCTM");
1853
+ },
1854
+ },
1173
1855
  };
1174
- const patchHTMLIFrameElement = (WorkerHTMLIFrameElement, env) => {
1175
- const HTMLIFrameDescriptorMap = {
1176
- contentDocument: {
1177
- get() {
1178
- return getIframeEnv(this).$document$;
1179
- }
1180
- },
1181
- contentWindow: {
1182
- get() {
1183
- return getIframeEnv(this).$window$;
1184
- }
1856
+ definePrototypePropertyDescriptor(
1857
+ WorkerSVGGraphicsElement,
1858
+ SVGGraphicsElementDescriptorMap
1859
+ );
1860
+ };
1861
+ const createNamedNodeMapCstr = (win, WorkerBase) => {
1862
+ win.NamedNodeMap = defineConstructorName(
1863
+ class NamedNodeMap extends WorkerBase {
1864
+ constructor(winId, instanceId, applyPath) {
1865
+ super(winId, instanceId, applyPath);
1866
+ return new Proxy(this, {
1867
+ get(target, propName) {
1868
+ const handler = NAMED_NODE_MAP_HANDLERS[propName];
1869
+ return handler
1870
+ ? handler.bind(target, [propName])
1871
+ : getter(target, [propName]);
1185
1872
  },
1186
- src: {
1187
- get() {
1188
- let src = getInstanceStateValue(this, 0);
1189
- if (src && src.startsWith("javascript:")) {
1190
- return src;
1191
- }
1192
- src = getIframeEnv(this).$location$.href;
1193
- return src.startsWith("about:") ? "" : src;
1194
- },
1195
- set(src) {
1196
- if (src) {
1197
- if (src.startsWith("javascript:")) {
1198
- setInstanceStateValue(this, 0, src);
1199
- } else if (!src.startsWith("about:")) {
1200
- let xhr = new XMLHttpRequest;
1201
- let xhrStatus;
1202
- let env = getIframeEnv(this);
1203
- env.$location$.href = src = resolveUrl(env, src, "iframe");
1204
- env.$isLoading$ = 1;
1205
- setInstanceStateValue(this, 1, void 0);
1206
- xhr.open("GET", src, false);
1207
- xhr.send();
1208
- xhrStatus = xhr.status;
1209
- if (xhrStatus > 199 && xhrStatus < 300) {
1210
- setter(this, [ "srcdoc" ], `<base href="${src}">` + function(text) {
1211
- return text.replace(SCRIPT_TAG_REGEXP, ((_, attrs) => {
1212
- const parts = [];
1213
- let hasType = false;
1214
- let match;
1215
- while (match = ATTR_REGEXP.exec(attrs)) {
1216
- let [keyValue] = match;
1217
- if (keyValue.startsWith("type=")) {
1218
- hasType = true;
1219
- keyValue = keyValue.replace(/(application|text)\/javascript/, SCRIPT_TYPE);
1220
- }
1221
- parts.push(keyValue);
1222
- }
1223
- hasType || parts.push('type="text/partytown"');
1224
- return `<script ${parts.join(" ")}>`;
1225
- }));
1226
- }(xhr.responseText) + getPartytownScript());
1227
- sendToMain(true);
1228
- webWorkerCtx.$postMessage$([ 7, env.$winId$ ]);
1229
- } else {
1230
- setInstanceStateValue(this, 1, xhrStatus);
1231
- env.$isLoading$ = 0;
1232
- }
1233
- }
1234
- }
1235
- }
1873
+ set(target, propName, propValue) {
1874
+ const handler = NAMED_NODE_MAP_HANDLERS[propName];
1875
+ if (handler) {
1876
+ throw new Error(
1877
+ "Can't set read-only property: " + String(propName)
1878
+ );
1879
+ }
1880
+ setter(target, [propName], propValue);
1881
+ return true;
1236
1882
  },
1237
- ...HTMLSrcElementDescriptorMap
1238
- };
1239
- definePrototypePropertyDescriptor(WorkerHTMLIFrameElement, HTMLIFrameDescriptorMap);
1883
+ });
1884
+ }
1885
+ },
1886
+ "NamedNodeMap"
1887
+ );
1888
+ };
1889
+ function method(applyPath, ...args) {
1890
+ return callMethod(this, applyPath, args, 1);
1891
+ }
1892
+ const NAMED_NODE_MAP_HANDLERS = {
1893
+ getNamedItem: method,
1894
+ getNamedItemNS: method,
1895
+ item: method,
1896
+ removeNamedItem: method,
1897
+ removeNamedItemNS: method,
1898
+ setNamedItem: method,
1899
+ setNamedItemNS: method,
1900
+ };
1901
+ const createWindow = (
1902
+ $winId$,
1903
+ $parentWinId$,
1904
+ url,
1905
+ $visibilityState$,
1906
+ isIframeWindow,
1907
+ isDocumentImplementation
1908
+ ) => {
1909
+ let cstrInstanceId;
1910
+ let cstrNodeName;
1911
+ let cstrNamespace;
1912
+ const WorkerBase = class {
1913
+ constructor(winId, instanceId, applyPath, instanceData, namespace) {
1914
+ this[WinIdKey] = winId || $winId$;
1915
+ this[InstanceIdKey] = instanceId || cstrInstanceId || randomId();
1916
+ this[ApplyPathKey] = applyPath || [];
1917
+ this[InstanceDataKey] = instanceData || cstrNodeName;
1918
+ this[NamespaceKey] = namespace || cstrNamespace;
1919
+ this[InstanceStateKey] = {};
1920
+ cstrInstanceId = cstrNodeName = cstrNamespace = void 0;
1921
+ }
1240
1922
  };
1241
- const ATTR_REGEXP_STR = "((?:\\w|-)+(?:=(?:(?:\\w|-)+|'[^']*'|\"[^\"]*\")?)?)";
1242
- const SCRIPT_TAG_REGEXP = new RegExp(`<script\\s*((${ATTR_REGEXP_STR}\\s*)*)>`, "mg");
1243
- const ATTR_REGEXP = new RegExp(ATTR_REGEXP_STR, "mg");
1244
- const getIframeEnv = iframe => {
1245
- const $winId$ = iframe[InstanceIdKey];
1246
- environments[$winId$] || createEnvironment({
1247
- $winId$: $winId$,
1248
- $parentWinId$: iframe[WinIdKey],
1249
- $url$: getter(iframe, [ "src" ]) || "about:blank"
1250
- }, true);
1251
- return environments[$winId$];
1923
+ const WorkerLocation = defineConstructorName(
1924
+ class extends URL {
1925
+ assign() {
1926
+ logWorker("location.assign(), noop");
1927
+ }
1928
+ reload() {
1929
+ logWorker("location.reload(), noop");
1930
+ }
1931
+ replace() {
1932
+ logWorker("location.replace(), noop");
1933
+ }
1934
+ },
1935
+ "Location"
1936
+ );
1937
+ const $location$ = new WorkerLocation(url);
1938
+ const $isSameOrigin$ =
1939
+ $location$.origin === webWorkerCtx.$origin$ ||
1940
+ "about:blank" === $location$.origin;
1941
+ const $isTopWindow$ = $parentWinId$ === $winId$;
1942
+ const env = {};
1943
+ const getChildEnvs = () => {
1944
+ let childEnv = [];
1945
+ let envWinId;
1946
+ let otherEnv;
1947
+ for (envWinId in environments) {
1948
+ otherEnv = environments[envWinId];
1949
+ otherEnv.$parentWinId$ !== $winId$ ||
1950
+ otherEnv.$isTopWindow$ ||
1951
+ childEnv.push(otherEnv);
1952
+ }
1953
+ return childEnv;
1252
1954
  };
1253
- const patchSvgElement = WorkerSVGGraphicsElement => {
1254
- const getMatrix = (elm, methodName) => {
1255
- const {a: a, b: b, c: c, d: d, e: e, f: f} = callMethod(elm, [ methodName ], EMPTY_ARRAY);
1256
- return new DOMMatrixReadOnly([ a, b, c, d, e, f ]);
1257
- };
1258
- const SVGGraphicsElementDescriptorMap = {
1259
- ...WorkerSVGGraphicsElement,
1260
- getCTM: {
1261
- value: function() {
1262
- return getMatrix(this, "getCTM");
1955
+ const WorkerWindow = defineConstructorName(
1956
+ class extends WorkerBase {
1957
+ constructor() {
1958
+ super($winId$, $winId$);
1959
+ let win = this;
1960
+ let value;
1961
+ let historyState;
1962
+ let hasInitializedMedia = 0;
1963
+ let initWindowMedia = () => {
1964
+ if (!hasInitializedMedia) {
1965
+ (() => {
1966
+ if (!webWorkerCtx.$initWindowMedia$) {
1967
+ self.$bridgeToMedia$ = [
1968
+ getter,
1969
+ setter,
1970
+ callMethod,
1971
+ constructGlobal,
1972
+ definePrototypePropertyDescriptor,
1973
+ randomId,
1974
+ WinIdKey,
1975
+ InstanceIdKey,
1976
+ ApplyPathKey,
1977
+ ];
1978
+ webWorkerCtx.$importScripts$(
1979
+ partytownLibUrl("partytown-media.js?v=0.7.5")
1980
+ );
1981
+ webWorkerCtx.$initWindowMedia$ = self.$bridgeFromMedia$;
1982
+ delete self.$bridgeFromMedia$;
1263
1983
  }
1264
- },
1265
- getScreenCTM: {
1266
- value: function() {
1267
- return getMatrix(this, "getScreenCTM");
1984
+ return webWorkerCtx.$initWindowMedia$;
1985
+ })()(
1986
+ WorkerBase,
1987
+ WorkerEventTargetProxy,
1988
+ env,
1989
+ win,
1990
+ windowMediaConstructors
1991
+ );
1992
+ hasInitializedMedia = 1;
1993
+ }
1994
+ };
1995
+ let nodeCstrs = {};
1996
+ let $createNode$ = (nodeName, instanceId, namespace) => {
1997
+ htmlMedia.includes(nodeName) && initWindowMedia();
1998
+ const NodeCstr = nodeCstrs[nodeName]
1999
+ ? nodeCstrs[nodeName]
2000
+ : nodeName.includes("-")
2001
+ ? nodeCstrs.UNKNOWN
2002
+ : nodeCstrs.I;
2003
+ cstrInstanceId = instanceId;
2004
+ cstrNodeName = nodeName;
2005
+ cstrNamespace = namespace;
2006
+ return new NodeCstr();
2007
+ };
2008
+ win.Window = WorkerWindow;
2009
+ win.name = name + `${normalizedWinId($winId$)} (${$winId$})`;
2010
+ createNodeCstr(win, env, WorkerBase);
2011
+ ((win) => {
2012
+ win.NodeList = defineConstructorName(NodeList, "NodeList");
2013
+ })(win);
2014
+ createNamedNodeMapCstr(win, WorkerBase);
2015
+ createCSSStyleDeclarationCstr(win, WorkerBase, "CSSStyleDeclaration");
2016
+ ((win, WorkerBase, cstrName) => {
2017
+ win[cstrName] = defineConstructorName(
2018
+ class extends WorkerBase {
2019
+ now() {
2020
+ return performance.now();
1268
2021
  }
1269
- }
1270
- };
1271
- definePrototypePropertyDescriptor(WorkerSVGGraphicsElement, SVGGraphicsElementDescriptorMap);
1272
- };
1273
- const createNamedNodeMapCstr = (win, WorkerBase) => {
1274
- win.NamedNodeMap = defineConstructorName(class NamedNodeMap extends WorkerBase {
1275
- constructor(winId, instanceId, applyPath) {
1276
- super(winId, instanceId, applyPath);
1277
- return new Proxy(this, {
1278
- get(target, propName) {
1279
- const handler = NAMED_NODE_MAP_HANDLERS[propName];
1280
- return handler ? handler.bind(target, [ propName ]) : getter(target, [ propName ]);
1281
- },
1282
- set(target, propName, propValue) {
1283
- const handler = NAMED_NODE_MAP_HANDLERS[propName];
1284
- if (handler) {
1285
- throw new Error("Can't set read-only property: " + String(propName));
1286
- }
1287
- setter(target, [ propName ], propValue);
1288
- return true;
1289
- }
1290
- });
1291
- }
1292
- }, "NamedNodeMap");
1293
- };
1294
- function method(applyPath, ...args) {
1295
- return callMethod(this, applyPath, args, 1);
1296
- }
1297
- const NAMED_NODE_MAP_HANDLERS = {
1298
- getNamedItem: method,
1299
- getNamedItemNS: method,
1300
- item: method,
1301
- removeNamedItem: method,
1302
- removeNamedItemNS: method,
1303
- setNamedItem: method,
1304
- setNamedItemNS: method
1305
- };
1306
- const createWindow = ($winId$, $parentWinId$, url, $visibilityState$, isIframeWindow, isDocumentImplementation) => {
1307
- let cstrInstanceId;
1308
- let cstrNodeName;
1309
- let cstrNamespace;
1310
- const WorkerBase = class {
1311
- constructor(winId, instanceId, applyPath, instanceData, namespace) {
1312
- this[WinIdKey] = winId || $winId$;
1313
- this[InstanceIdKey] = instanceId || cstrInstanceId || randomId();
1314
- this[ApplyPathKey] = applyPath || [];
1315
- this[InstanceDataKey] = instanceData || cstrNodeName;
1316
- this[NamespaceKey] = namespace || cstrNamespace;
1317
- this[InstanceStateKey] = {};
1318
- cstrInstanceId = cstrNodeName = cstrNamespace = void 0;
1319
- }
1320
- };
1321
- const WorkerLocation = defineConstructorName(class extends URL {
1322
- assign() {
1323
- logWorker("location.assign(), noop");
1324
- }
1325
- reload() {
1326
- logWorker("location.reload(), noop");
1327
- }
1328
- replace() {
1329
- logWorker("location.replace(), noop");
1330
- }
1331
- }, "Location");
1332
- const $location$ = new WorkerLocation(url);
1333
- const $isSameOrigin$ = $location$.origin === webWorkerCtx.$origin$ || "about:blank" === $location$.origin;
1334
- const $isTopWindow$ = $parentWinId$ === $winId$;
1335
- const env = {};
1336
- const getChildEnvs = () => {
1337
- let childEnv = [];
1338
- let envWinId;
1339
- let otherEnv;
1340
- for (envWinId in environments) {
1341
- otherEnv = environments[envWinId];
1342
- otherEnv.$parentWinId$ !== $winId$ || otherEnv.$isTopWindow$ || childEnv.push(otherEnv);
1343
- }
1344
- return childEnv;
1345
- };
1346
- const WorkerWindow = defineConstructorName(class extends WorkerBase {
1347
- constructor() {
1348
- super($winId$, $winId$);
1349
- let win = this;
1350
- let value;
1351
- let historyState;
1352
- let hasInitializedMedia = 0;
1353
- let initWindowMedia = () => {
1354
- if (!hasInitializedMedia) {
1355
- (() => {
1356
- if (!webWorkerCtx.$initWindowMedia$) {
1357
- self.$bridgeToMedia$ = [ getter, setter, callMethod, constructGlobal, definePrototypePropertyDescriptor, randomId, WinIdKey, InstanceIdKey, ApplyPathKey ];
1358
- webWorkerCtx.$importScripts$(partytownLibUrl("partytown-media.js?v=0.7.5"));
1359
- webWorkerCtx.$initWindowMedia$ = self.$bridgeFromMedia$;
1360
- delete self.$bridgeFromMedia$;
1361
- }
1362
- return webWorkerCtx.$initWindowMedia$;
1363
- })()(WorkerBase, WorkerEventTargetProxy, env, win, windowMediaConstructors);
1364
- hasInitializedMedia = 1;
2022
+ },
2023
+ cstrName
2024
+ );
2025
+ })(win, WorkerBase, "Performance");
2026
+ ((win, nodeCstrs) => {
2027
+ const registry = new Map();
2028
+ win.customElements = {
2029
+ define(tagName, Cstr, opts) {
2030
+ registry.set(tagName, Cstr);
2031
+ nodeCstrs[tagName.toUpperCase()] = Cstr;
2032
+ const ceData = [Cstr.name, Cstr.observedAttributes];
2033
+ callMethod(
2034
+ win,
2035
+ ["customElements", "define"],
2036
+ [tagName, ceData, opts]
2037
+ );
2038
+ },
2039
+ get: (tagName) =>
2040
+ registry.get(tagName) ||
2041
+ callMethod(win, ["customElements", "get"], [tagName]),
2042
+ whenDefined: (tagName) =>
2043
+ registry.has(tagName)
2044
+ ? Promise.resolve()
2045
+ : callMethod(
2046
+ win,
2047
+ ["customElements", "whenDefined"],
2048
+ [tagName]
2049
+ ),
2050
+ upgrade: (elm) =>
2051
+ callMethod(win, ["customElements", "upgrade"], [elm]),
2052
+ };
2053
+ })(win, nodeCstrs);
2054
+ webWorkerCtx.$interfaces$.map(
2055
+ ([cstrName, superCstrName, members, interfaceType, nodeName]) => {
2056
+ const SuperCstr = TrapConstructors[cstrName]
2057
+ ? WorkerTrapProxy
2058
+ : "EventTarget" === superCstrName
2059
+ ? WorkerEventTargetProxy
2060
+ : "Object" === superCstrName
2061
+ ? WorkerBase
2062
+ : win[superCstrName];
2063
+ const Cstr = (win[cstrName] = defineConstructorName(
2064
+ 12 === interfaceType
2065
+ ? class extends WorkerBase {
2066
+ constructor(...args) {
2067
+ super();
2068
+ constructGlobal(this, cstrName, args);
2069
+ }
1365
2070
  }
1366
- };
1367
- let nodeCstrs = {};
1368
- let $createNode$ = (nodeName, instanceId, namespace) => {
1369
- htmlMedia.includes(nodeName) && initWindowMedia();
1370
- const NodeCstr = nodeCstrs[nodeName] ? nodeCstrs[nodeName] : nodeName.includes("-") ? nodeCstrs.UNKNOWN : nodeCstrs.I;
1371
- cstrInstanceId = instanceId;
1372
- cstrNodeName = nodeName;
1373
- cstrNamespace = namespace;
1374
- return new NodeCstr;
1375
- };
1376
- win.Window = WorkerWindow;
1377
- win.name = name + `${normalizedWinId($winId$)} (${$winId$})`;
1378
- createNodeCstr(win, env, WorkerBase);
1379
- (win => {
1380
- win.NodeList = defineConstructorName(NodeList, "NodeList");
1381
- })(win);
1382
- createNamedNodeMapCstr(win, WorkerBase);
1383
- createCSSStyleDeclarationCstr(win, WorkerBase, "CSSStyleDeclaration");
1384
- ((win, WorkerBase, cstrName) => {
1385
- win[cstrName] = defineConstructorName(class extends WorkerBase {
1386
- now() {
1387
- return performance.now();
1388
- }
1389
- }, cstrName);
1390
- })(win, WorkerBase, "Performance");
1391
- ((win, nodeCstrs) => {
1392
- const registry = new Map;
1393
- win.customElements = {
1394
- define(tagName, Cstr, opts) {
1395
- registry.set(tagName, Cstr);
1396
- nodeCstrs[tagName.toUpperCase()] = Cstr;
1397
- const ceData = [ Cstr.name, Cstr.observedAttributes ];
1398
- callMethod(win, [ "customElements", "define" ], [ tagName, ceData, opts ]);
2071
+ : win[cstrName] || class extends SuperCstr {},
2072
+ cstrName
2073
+ ));
2074
+ nodeName && (nodeCstrs[nodeName] = Cstr);
2075
+ members.map(([memberName, memberType, staticValue]) => {
2076
+ memberName in Cstr.prototype ||
2077
+ memberName in SuperCstr.prototype ||
2078
+ ("string" == typeof memberType
2079
+ ? definePrototypeProperty(Cstr, memberName, {
2080
+ get() {
2081
+ if (!hasInstanceStateValue(this, memberName)) {
2082
+ const instanceId = this[InstanceIdKey];
2083
+ const applyPath = [
2084
+ ...this[ApplyPathKey],
2085
+ memberName,
2086
+ ];
2087
+ const PropCstr = win[memberType];
2088
+ PropCstr &&
2089
+ setInstanceStateValue(
2090
+ this,
2091
+ memberName,
2092
+ new PropCstr($winId$, instanceId, applyPath)
2093
+ );
2094
+ }
2095
+ return getInstanceStateValue(this, memberName);
1399
2096
  },
1400
- get: tagName => registry.get(tagName) || callMethod(win, [ "customElements", "get" ], [ tagName ]),
1401
- whenDefined: tagName => registry.has(tagName) ? Promise.resolve() : callMethod(win, [ "customElements", "whenDefined" ], [ tagName ]),
1402
- upgrade: elm => callMethod(win, [ "customElements", "upgrade" ], [ elm ])
1403
- };
1404
- })(win, nodeCstrs);
1405
- webWorkerCtx.$interfaces$.map((([cstrName, superCstrName, members, interfaceType, nodeName]) => {
1406
- const SuperCstr = TrapConstructors[cstrName] ? WorkerTrapProxy : "EventTarget" === superCstrName ? WorkerEventTargetProxy : "Object" === superCstrName ? WorkerBase : win[superCstrName];
1407
- const Cstr = win[cstrName] = defineConstructorName(12 === interfaceType ? class extends WorkerBase {
1408
- constructor(...args) {
1409
- super();
1410
- constructGlobal(this, cstrName, args);
2097
+ set(value) {
2098
+ setInstanceStateValue(this, memberName, value);
2099
+ },
2100
+ })
2101
+ : 5 === memberType
2102
+ ? definePrototypeValue(
2103
+ Cstr,
2104
+ memberName,
2105
+ function (...args) {
2106
+ return callMethod(this, [memberName], args);
1411
2107
  }
1412
- } : win[cstrName] || class extends SuperCstr {}, cstrName);
1413
- nodeName && (nodeCstrs[nodeName] = Cstr);
1414
- members.map((([memberName, memberType, staticValue]) => {
1415
- memberName in Cstr.prototype || memberName in SuperCstr.prototype || ("string" == typeof memberType ? definePrototypeProperty(Cstr, memberName, {
2108
+ )
2109
+ : memberType > 0 &&
2110
+ (void 0 !== staticValue
2111
+ ? definePrototypeValue(Cstr, memberName, staticValue)
2112
+ : definePrototypeProperty(Cstr, memberName, {
1416
2113
  get() {
1417
- if (!hasInstanceStateValue(this, memberName)) {
1418
- const instanceId = this[InstanceIdKey];
1419
- const applyPath = [ ...this[ApplyPathKey], memberName ];
1420
- const PropCstr = win[memberType];
1421
- PropCstr && setInstanceStateValue(this, memberName, new PropCstr($winId$, instanceId, applyPath));
1422
- }
1423
- return getInstanceStateValue(this, memberName);
2114
+ return getter(this, [memberName]);
1424
2115
  },
1425
2116
  set(value) {
1426
- setInstanceStateValue(this, memberName, value);
1427
- }
1428
- }) : 5 === memberType ? definePrototypeValue(Cstr, memberName, (function(...args) {
1429
- return callMethod(this, [ memberName ], args);
1430
- })) : memberType > 0 && (void 0 !== staticValue ? definePrototypeValue(Cstr, memberName, staticValue) : definePrototypeProperty(Cstr, memberName, {
1431
- get() {
1432
- return getter(this, [ memberName ]);
2117
+ return setter(this, [memberName], value);
1433
2118
  },
1434
- set(value) {
1435
- return setter(this, [ memberName ], value);
1436
- }
1437
- })));
1438
- }));
1439
- }));
1440
- commaSplit("atob,btoa,crypto,indexedDB,setTimeout,setInterval,clearTimeout,clearInterval").map((globalName => {
1441
- delete WorkerWindow.prototype[globalName];
1442
- if (!(globalName in win)) {
1443
- value = self[globalName];
1444
- null != value && (win[globalName] = "function" != typeof value || value.toString().startsWith("class") ? value : value.bind(self));
1445
- }
1446
- }));
1447
- Object.getOwnPropertyNames(self).map((globalName => {
1448
- globalName in win || (win[globalName] = self[globalName]);
1449
- }));
1450
- windowMediaConstructors.map((cstrName => defineProperty(win, cstrName, {
1451
- get() {
1452
- initWindowMedia();
1453
- return win[cstrName];
1454
- }
1455
- })));
1456
- "trustedTypes" in self && (win.trustedTypes = self.trustedTypes);
1457
- patchElement(win.Element, win.HTMLElement);
1458
- patchDocument(win.Document, env, isDocumentImplementation);
1459
- (WorkerDocumentFragment => {
1460
- definePrototypeNodeType(WorkerDocumentFragment, 11);
1461
- cachedTreeProps(WorkerDocumentFragment, elementStructurePropNames);
1462
- })(win.DocumentFragment);
1463
- patchHTMLAnchorElement(win.HTMLAnchorElement, env);
1464
- (WorkerHTMLFormElement => {
1465
- definePrototypePropertyDescriptor(WorkerHTMLFormElement, {});
1466
- cachedProps(WorkerHTMLFormElement, "elements");
1467
- })(win.HTMLFormElement);
1468
- patchHTMLIFrameElement(win.HTMLIFrameElement);
1469
- patchHTMLScriptElement(win.HTMLScriptElement, env);
1470
- patchSvgElement(win.SVGGraphicsElement);
1471
- patchDocumentElementChild(win.HTMLHeadElement, env);
1472
- patchDocumentElementChild(win.HTMLBodyElement, env);
1473
- ((WorkerHTMLHtmlElement, env) => {
1474
- const DocumentElementDescriptorMap = {
1475
- parentElement: {
1476
- value: null
1477
- },
1478
- parentNode: {
1479
- get: () => env.$document$
1480
- }
1481
- };
1482
- definePrototypePropertyDescriptor(WorkerHTMLHtmlElement, DocumentElementDescriptorMap);
1483
- })(win.HTMLHtmlElement, env);
1484
- createCSSStyleSheetConstructor(win, "CSSStyleSheet");
1485
- definePrototypeNodeType(win.Comment, 8);
1486
- definePrototypeNodeType(win.DocumentType, 10);
1487
- Object.assign(env, {
1488
- $winId$: $winId$,
1489
- $parentWinId$: $parentWinId$,
1490
- $window$: new Proxy(win, {
1491
- get: (win, propName) => {
1492
- var _a;
1493
- if ("string" != typeof propName || isNaN(propName)) {
1494
- return (null === (_a = webWorkerCtx.$config$.mainWindowAccessors) || void 0 === _a ? void 0 : _a.includes(propName)) ? getter(this, [ propName ]) : win[propName];
1495
- }
1496
- {
1497
- let frame = getChildEnvs()[propName];
1498
- return frame ? frame.$window$ : void 0;
1499
- }
1500
- },
1501
- has: () => true
1502
- }),
1503
- $document$: $createNode$("#document", $winId$ + ".d"),
1504
- $documentElement$: $createNode$("HTML", $winId$ + ".e"),
1505
- $head$: $createNode$("HEAD", $winId$ + ".h"),
1506
- $body$: $createNode$("BODY", $winId$ + ".b"),
1507
- $location$: $location$,
1508
- $visibilityState$: $visibilityState$,
1509
- $isSameOrigin$: $isSameOrigin$,
1510
- $isTopWindow$: $isTopWindow$,
1511
- $createNode$: $createNode$
1512
- });
1513
- win.requestAnimationFrame = cb => setTimeout((() => cb(performance.now())), 9);
1514
- win.cancelAnimationFrame = id => clearTimeout(id);
1515
- win.requestIdleCallback = (cb, start) => {
1516
- start = Date.now();
1517
- return setTimeout((() => cb({
1518
- didTimeout: false,
1519
- timeRemaining: () => Math.max(0, 50 - (Date.now() - start))
1520
- })), 1);
1521
- };
1522
- win.cancelIdleCallback = id => clearTimeout(id);
1523
- addStorageApi(win, "localStorage", webWorkerlocalStorage, $isSameOrigin$, env);
1524
- addStorageApi(win, "sessionStorage", webWorkerSessionStorage, $isSameOrigin$, env);
1525
- $isSameOrigin$ || (win.indexeddb = void 0);
1526
- if (isIframeWindow) {
1527
- historyState = {};
1528
- win.history = {
1529
- pushState(stateObj) {
1530
- historyState = stateObj;
1531
- },
1532
- replaceState(stateObj) {
1533
- historyState = stateObj;
1534
- },
1535
- get state() {
1536
- return historyState;
1537
- },
1538
- length: 0
1539
- };
1540
- win.indexeddb = void 0;
1541
- } else {
1542
- const originalPushState = win.history.pushState.bind(win.history);
1543
- const originalReplaceState = win.history.replaceState.bind(win.history);
1544
- win.history.pushState = (stateObj, _, newUrl) => {
1545
- false !== env.$propagateHistoryChange$ && originalPushState(stateObj, _, newUrl);
1546
- };
1547
- win.history.replaceState = (stateObj, _, newUrl) => {
1548
- false !== env.$propagateHistoryChange$ && originalReplaceState(stateObj, _, newUrl);
1549
- };
2119
+ })));
2120
+ });
2121
+ }
2122
+ );
2123
+ commaSplit(
2124
+ "atob,btoa,crypto,indexedDB,setTimeout,setInterval,clearTimeout,clearInterval"
2125
+ ).map((globalName) => {
2126
+ delete WorkerWindow.prototype[globalName];
2127
+ if (!(globalName in win)) {
2128
+ value = self[globalName];
2129
+ null != value &&
2130
+ (win[globalName] =
2131
+ "function" != typeof value ||
2132
+ value.toString().startsWith("class")
2133
+ ? value
2134
+ : value.bind(self));
2135
+ }
2136
+ });
2137
+ Object.getOwnPropertyNames(self).map((globalName) => {
2138
+ globalName in win || (win[globalName] = self[globalName]);
2139
+ });
2140
+ windowMediaConstructors.map((cstrName) =>
2141
+ defineProperty(win, cstrName, {
2142
+ get() {
2143
+ initWindowMedia();
2144
+ return win[cstrName];
2145
+ },
2146
+ })
2147
+ );
2148
+ "trustedTypes" in self && (win.trustedTypes = self.trustedTypes);
2149
+ patchElement(win.Element, win.HTMLElement);
2150
+ patchDocument(win.Document, env, isDocumentImplementation);
2151
+ ((WorkerDocumentFragment) => {
2152
+ definePrototypeNodeType(WorkerDocumentFragment, 11);
2153
+ cachedTreeProps(WorkerDocumentFragment, elementStructurePropNames);
2154
+ })(win.DocumentFragment);
2155
+ patchHTMLAnchorElement(win.HTMLAnchorElement, env);
2156
+ ((WorkerHTMLFormElement) => {
2157
+ definePrototypePropertyDescriptor(WorkerHTMLFormElement, {});
2158
+ cachedProps(WorkerHTMLFormElement, "elements");
2159
+ })(win.HTMLFormElement);
2160
+ patchHTMLIFrameElement(win.HTMLIFrameElement);
2161
+ patchHTMLScriptElement(win.HTMLScriptElement, env);
2162
+ patchSvgElement(win.SVGGraphicsElement);
2163
+ patchDocumentElementChild(win.HTMLHeadElement, env);
2164
+ patchDocumentElementChild(win.HTMLBodyElement, env);
2165
+ ((WorkerHTMLHtmlElement, env) => {
2166
+ const DocumentElementDescriptorMap = {
2167
+ parentElement: {
2168
+ value: null,
2169
+ },
2170
+ parentNode: {
2171
+ get: () => env.$document$,
2172
+ },
2173
+ };
2174
+ definePrototypePropertyDescriptor(
2175
+ WorkerHTMLHtmlElement,
2176
+ DocumentElementDescriptorMap
2177
+ );
2178
+ })(win.HTMLHtmlElement, env);
2179
+ createCSSStyleSheetConstructor(win, "CSSStyleSheet");
2180
+ definePrototypeNodeType(win.Comment, 8);
2181
+ definePrototypeNodeType(win.DocumentType, 10);
2182
+ Object.assign(env, {
2183
+ $winId$: $winId$,
2184
+ $parentWinId$: $parentWinId$,
2185
+ $window$: new Proxy(win, {
2186
+ get: (win, propName) => {
2187
+ var _a;
2188
+ if ("string" != typeof propName || isNaN(propName)) {
2189
+ return (
2190
+ null === (_a = webWorkerCtx.$config$.mainWindowAccessors) ||
2191
+ void 0 === _a
2192
+ ? void 0
2193
+ : _a.includes(propName)
2194
+ )
2195
+ ? getter(this, [propName])
2196
+ : win[propName];
1550
2197
  }
1551
- win.Worker = void 0;
1552
- }
1553
- addEventListener(...args) {
1554
- "load" === args[0] ? env.$runWindowLoadEvent$ && setTimeout((() => args[1]({
1555
- type: "load"
1556
- }))) : callMethod(this, [ "addEventListener" ], args, 2);
1557
- }
1558
- get body() {
1559
- return env.$body$;
1560
- }
1561
- get document() {
1562
- return env.$document$;
1563
- }
1564
- get documentElement() {
1565
- return env.$documentElement$;
1566
- }
1567
- fetch(input, init) {
1568
- input = "string" == typeof input || input instanceof URL ? String(input) : input.url;
1569
- return fetch(resolveUrl(env, input, "fetch"), init);
1570
- }
1571
- get frames() {
1572
- return env.$window$;
1573
- }
1574
- get frameElement() {
1575
- return $isTopWindow$ ? null : getOrCreateNodeInstance($parentWinId$, $winId$, "IFRAME");
1576
- }
1577
- get globalThis() {
1578
- return env.$window$;
1579
- }
1580
- get head() {
1581
- return env.$head$;
1582
- }
1583
- get length() {
1584
- return getChildEnvs().length;
1585
- }
1586
- get location() {
1587
- return $location$;
1588
- }
1589
- set location(loc) {
1590
- $location$.href = loc + "";
1591
- }
1592
- get Image() {
1593
- return createImageConstructor(env);
1594
- }
1595
- get navigator() {
1596
- return (env => {
1597
- let key;
1598
- let nav = {
1599
- sendBeacon: (url, body) => {
1600
- if (webWorkerCtx.$config$.logSendBeaconRequests) {
1601
- try {
1602
- logWorker(`sendBeacon: ${resolveUrl(env, url, null)}${body ? ", data: " + JSON.stringify(body) : ""}`);
1603
- } catch (e) {
1604
- console.error(e);
1605
- }
1606
- }
1607
- try {
1608
- fetch(resolveUrl(env, url, null), {
1609
- method: "POST",
1610
- body: body,
1611
- mode: "no-cors",
1612
- keepalive: true
1613
- });
1614
- return true;
1615
- } catch (e) {
1616
- console.error(e);
1617
- return false;
1618
- }
1619
- }
1620
- };
1621
- for (key in navigator) {
1622
- nav[key] = navigator[key];
1623
- }
1624
- return nav;
1625
- })(env);
1626
- }
1627
- get origin() {
1628
- return $location$.origin;
1629
- }
1630
- set origin(_) {}
1631
- get parent() {
1632
- for (let envWinId in environments) {
1633
- if (environments[envWinId].$winId$ === $parentWinId$) {
1634
- return environments[envWinId].$window$;
1635
- }
2198
+ {
2199
+ let frame = getChildEnvs()[propName];
2200
+ return frame ? frame.$window$ : void 0;
1636
2201
  }
1637
- return env.$window$;
1638
- }
1639
- postMessage(...args) {
1640
- if (environments[args[0]]) {
1641
- len(postMessages) > 50 && postMessages.splice(0, 5);
1642
- postMessages.push({
1643
- $winId$: args[0],
1644
- $data$: JSON.stringify(args[1])
1645
- });
1646
- args = args.slice(1);
2202
+ },
2203
+ has: () => true,
2204
+ }),
2205
+ $document$: $createNode$("#document", $winId$ + ".d"),
2206
+ $documentElement$: $createNode$("HTML", $winId$ + ".e"),
2207
+ $head$: $createNode$("HEAD", $winId$ + ".h"),
2208
+ $body$: $createNode$("BODY", $winId$ + ".b"),
2209
+ $location$: $location$,
2210
+ $visibilityState$: $visibilityState$,
2211
+ $isSameOrigin$: $isSameOrigin$,
2212
+ $isTopWindow$: $isTopWindow$,
2213
+ $createNode$: $createNode$,
2214
+ });
2215
+ win.requestAnimationFrame = (cb) =>
2216
+ setTimeout(() => cb(performance.now()), 9);
2217
+ win.cancelAnimationFrame = (id) => clearTimeout(id);
2218
+ win.requestIdleCallback = (cb, start) => {
2219
+ start = Date.now();
2220
+ return setTimeout(
2221
+ () =>
2222
+ cb({
2223
+ didTimeout: false,
2224
+ timeRemaining: () => Math.max(0, 50 - (Date.now() - start)),
2225
+ }),
2226
+ 1
2227
+ );
2228
+ };
2229
+ win.cancelIdleCallback = (id) => clearTimeout(id);
2230
+ addStorageApi(
2231
+ win,
2232
+ "localStorage",
2233
+ webWorkerlocalStorage,
2234
+ $isSameOrigin$,
2235
+ env
2236
+ );
2237
+ addStorageApi(
2238
+ win,
2239
+ "sessionStorage",
2240
+ webWorkerSessionStorage,
2241
+ $isSameOrigin$,
2242
+ env
2243
+ );
2244
+ $isSameOrigin$ || (win.indexeddb = void 0);
2245
+ if (isIframeWindow) {
2246
+ historyState = {};
2247
+ win.history = {
2248
+ pushState(stateObj) {
2249
+ historyState = stateObj;
2250
+ },
2251
+ replaceState(stateObj) {
2252
+ historyState = stateObj;
2253
+ },
2254
+ get state() {
2255
+ return historyState;
2256
+ },
2257
+ length: 0,
2258
+ };
2259
+ win.indexeddb = void 0;
2260
+ } else {
2261
+ const originalPushState = win.history.pushState.bind(win.history);
2262
+ const originalReplaceState = win.history.replaceState.bind(
2263
+ win.history
2264
+ );
2265
+ win.history.pushState = (stateObj, _, newUrl) => {
2266
+ false !== env.$propagateHistoryChange$ &&
2267
+ originalPushState(stateObj, _, newUrl);
2268
+ };
2269
+ win.history.replaceState = (stateObj, _, newUrl) => {
2270
+ false !== env.$propagateHistoryChange$ &&
2271
+ originalReplaceState(stateObj, _, newUrl);
2272
+ };
2273
+ }
2274
+ win.Worker = void 0;
2275
+ }
2276
+ addEventListener(...args) {
2277
+ "load" === args[0]
2278
+ ? env.$runWindowLoadEvent$ &&
2279
+ setTimeout(() =>
2280
+ args[1]({
2281
+ type: "load",
2282
+ })
2283
+ )
2284
+ : callMethod(this, ["addEventListener"], args, 2);
2285
+ }
2286
+ get body() {
2287
+ return env.$body$;
2288
+ }
2289
+ get document() {
2290
+ return env.$document$;
2291
+ }
2292
+ get documentElement() {
2293
+ return env.$documentElement$;
2294
+ }
2295
+ fetch(input, init) {
2296
+ input =
2297
+ "string" == typeof input || input instanceof URL
2298
+ ? String(input)
2299
+ : input.url;
2300
+ return fetch(resolveUrl(env, input, "fetch"), init);
2301
+ }
2302
+ get frames() {
2303
+ return env.$window$;
2304
+ }
2305
+ get frameElement() {
2306
+ return $isTopWindow$
2307
+ ? null
2308
+ : getOrCreateNodeInstance($parentWinId$, $winId$, "INPUT");
2309
+ }
2310
+ get globalThis() {
2311
+ return env.$window$;
2312
+ }
2313
+ get head() {
2314
+ return env.$head$;
2315
+ }
2316
+ get length() {
2317
+ return getChildEnvs().length;
2318
+ }
2319
+ get location() {
2320
+ return $location$;
2321
+ }
2322
+ set location(loc) {
2323
+ $location$.href = loc + "";
2324
+ }
2325
+ get Image() {
2326
+ return createImageConstructor(env);
2327
+ }
2328
+ get navigator() {
2329
+ return ((env) => {
2330
+ let key;
2331
+ let nav = {
2332
+ sendBeacon: (url, body) => {
2333
+ if (webWorkerCtx.$config$.logSendBeaconRequests) {
2334
+ try {
2335
+ logWorker(
2336
+ `sendBeacon: ${resolveUrl(env, url, null)}${
2337
+ body ? ", data: " + JSON.stringify(body) : ""
2338
+ }`
2339
+ );
2340
+ } catch (e) {
2341
+ console.error(e);
2342
+ }
1647
2343
  }
1648
- callMethod(this, [ "postMessage" ], args, 3);
1649
- }
1650
- get self() {
1651
- return env.$window$;
1652
- }
1653
- get top() {
1654
- for (let envWinId in environments) {
1655
- if (environments[envWinId].$isTopWindow$) {
1656
- return environments[envWinId].$window$;
1657
- }
2344
+ try {
2345
+ fetch(resolveUrl(env, url, null), {
2346
+ method: "POST",
2347
+ body: body,
2348
+ mode: "no-cors",
2349
+ keepalive: true,
2350
+ });
2351
+ return true;
2352
+ } catch (e) {
2353
+ console.error(e);
2354
+ return false;
1658
2355
  }
1659
- return env.$window$;
1660
- }
1661
- get window() {
1662
- return env.$window$;
1663
- }
1664
- get XMLHttpRequest() {
1665
- const Xhr = XMLHttpRequest;
1666
- const str = String(Xhr);
1667
- const ExtendedXhr = defineConstructorName(class extends Xhr {
1668
- open(...args) {
1669
- args[1] = resolveUrl(env, args[1], "xhr");
1670
- super.open(...args);
1671
- }
1672
- set withCredentials(_) {}
1673
- toString() {
1674
- return str;
1675
- }
1676
- }, getConstructorName(Xhr));
1677
- ExtendedXhr.prototype.constructor.toString = () => str;
1678
- return ExtendedXhr;
1679
- }
1680
- }, "Window");
1681
- const WorkerTrapProxy = class extends WorkerBase {
1682
- constructor(winId, instanceId, applyPath, nodeName) {
1683
- super(winId, instanceId, applyPath, nodeName);
1684
- return new Proxy(this, {
1685
- get: (instance, propName) => getter(instance, [ propName ]),
1686
- set(instance, propName, propValue) {
1687
- setter(instance, [ propName ], propValue);
1688
- return true;
1689
- }
1690
- });
2356
+ },
2357
+ };
2358
+ for (key in navigator) {
2359
+ nav[key] = navigator[key];
1691
2360
  }
1692
- };
1693
- const WorkerEventTargetProxy = class extends WorkerBase {};
1694
- eventTargetMethods.map((methodName => WorkerEventTargetProxy.prototype[methodName] = function(...args) {
1695
- return callMethod(this, [ methodName ], args, 2);
1696
- }));
1697
- cachedProps(WorkerWindow, "devicePixelRatio");
1698
- cachedDimensionProps(WorkerWindow);
1699
- cachedDimensionMethods(WorkerWindow, [ "getComputedStyle" ]);
1700
- new WorkerWindow;
1701
- return env;
1702
- };
1703
- const TrapConstructors = {
1704
- DOMStringMap: 1,
1705
- NamedNodeMap: 1
1706
- };
1707
- const createEnvironment = ({$winId$: $winId$, $parentWinId$: $parentWinId$, $url$: $url$, $visibilityState$: $visibilityState$}, isIframeWindow, isDocumentImplementation) => {
1708
- if (!environments[$winId$]) {
1709
- environments[$winId$] = createWindow($winId$, $parentWinId$, $url$, $visibilityState$, isIframeWindow, isDocumentImplementation);
1710
- {
1711
- const winType = $winId$ === $parentWinId$ ? "top" : "iframe";
1712
- logWorker(`Created ${winType} window ${normalizedWinId($winId$)} environment`, $winId$);
2361
+ return nav;
2362
+ })(env);
2363
+ }
2364
+ get origin() {
2365
+ return $location$.origin;
2366
+ }
2367
+ set origin(_) {}
2368
+ get parent() {
2369
+ for (let envWinId in environments) {
2370
+ if (environments[envWinId].$winId$ === $parentWinId$) {
2371
+ return environments[envWinId].$window$;
2372
+ }
2373
+ }
2374
+ return env.$window$;
2375
+ }
2376
+ postMessage(...args) {
2377
+ if (environments[args[0]]) {
2378
+ len(postMessages) > 50 && postMessages.splice(0, 5);
2379
+ postMessages.push({
2380
+ $winId$: args[0],
2381
+ $data$: JSON.stringify(args[1]),
2382
+ });
2383
+ args = args.slice(1);
2384
+ }
2385
+ callMethod(this, ["postMessage"], args, 3);
2386
+ }
2387
+ get self() {
2388
+ return env.$window$;
2389
+ }
2390
+ get top() {
2391
+ for (let envWinId in environments) {
2392
+ if (environments[envWinId].$isTopWindow$) {
2393
+ return environments[envWinId].$window$;
1713
2394
  }
2395
+ }
2396
+ return env.$window$;
2397
+ }
2398
+ get window() {
2399
+ return env.$window$;
2400
+ }
2401
+ get XMLHttpRequest() {
2402
+ const Xhr = XMLHttpRequest;
2403
+ const str = String(Xhr);
2404
+ const ExtendedXhr = defineConstructorName(
2405
+ class extends Xhr {
2406
+ open(...args) {
2407
+ args[1] = resolveUrl(env, args[1], "xhr");
2408
+ super.open(...args);
2409
+ }
2410
+ set withCredentials(_) {}
2411
+ toString() {
2412
+ return str;
2413
+ }
2414
+ },
2415
+ getConstructorName(Xhr)
2416
+ );
2417
+ ExtendedXhr.prototype.constructor.toString = () => str;
2418
+ return ExtendedXhr;
1714
2419
  }
1715
- webWorkerCtx.$postMessage$([ 7, $winId$ ]);
1716
- return environments[$winId$];
2420
+ },
2421
+ "Window"
2422
+ );
2423
+ const WorkerTrapProxy = class extends WorkerBase {
2424
+ constructor(winId, instanceId, applyPath, nodeName) {
2425
+ super(winId, instanceId, applyPath, nodeName);
2426
+ return new Proxy(this, {
2427
+ get: (instance, propName) => getter(instance, [propName]),
2428
+ set(instance, propName, propValue) {
2429
+ setter(instance, [propName], propValue);
2430
+ return true;
2431
+ },
2432
+ });
2433
+ }
1717
2434
  };
1718
- const queuedEvents = [];
1719
- const receiveMessageFromSandboxToWorker = ev => {
1720
- const msg = ev.data;
1721
- const msgType = msg[0];
1722
- const msgValue = msg[1];
1723
- if (webWorkerCtx.$isInitialized$) {
1724
- if (7 === msgType) {
1725
- (async initScript => {
1726
- let winId = initScript.$winId$;
1727
- let instanceId = initScript.$instanceId$;
1728
- let instance = getOrCreateNodeInstance(winId, instanceId, "SCRIPT");
1729
- let scriptContent = initScript.$content$;
1730
- let scriptSrc = initScript.$url$;
1731
- let scriptOrgSrc = initScript.$orgUrl$;
1732
- let errorMsg = "";
1733
- let env = environments[winId];
1734
- let rsp;
1735
- let javascriptContentTypes = [ "text/jscript", "text/javascript", "text/x-javascript", "application/javascript", "application/x-javascript", "text/ecmascript", "text/x-ecmascript", "application/ecmascript" ];
1736
- if (scriptSrc) {
1737
- try {
1738
- scriptSrc = resolveToUrl(env, scriptSrc, "script") + "";
1739
- setInstanceStateValue(instance, 4, scriptSrc);
1740
- webWorkerCtx.$config$.logScriptExecution && logWorker(`Execute script src: ${scriptOrgSrc}`, winId);
1741
- rsp = await fetch(scriptSrc);
1742
- if (rsp.ok) {
1743
- let responseContentType = rsp.headers.get("content-type");
1744
- let shouldExecute = javascriptContentTypes.some((ct => {
1745
- var _a, _b, _c;
1746
- return null === (_c = null === (_a = null == responseContentType ? void 0 : responseContentType.toLowerCase) || void 0 === _a ? void 0 : (_b = _a.call(responseContentType)).includes) || void 0 === _c ? void 0 : _c.call(_b, ct);
1747
- }));
1748
- if (shouldExecute) {
1749
- scriptContent = await rsp.text();
1750
- env.$currentScriptId$ = instanceId;
1751
- run(env, scriptContent, scriptOrgSrc || scriptSrc);
1752
- }
1753
- runStateLoadHandlers(instance, "load");
1754
- } else {
1755
- errorMsg = rsp.statusText;
1756
- runStateLoadHandlers(instance, "error");
1757
- }
1758
- } catch (urlError) {
1759
- console.error(urlError);
1760
- errorMsg = String(urlError.stack || urlError);
1761
- runStateLoadHandlers(instance, "error");
1762
- }
1763
- } else {
1764
- scriptContent && (errorMsg = runScriptContent(env, instanceId, scriptContent, winId, errorMsg));
1765
- }
1766
- env.$currentScriptId$ = "";
1767
- webWorkerCtx.$postMessage$([ 6, winId, instanceId, errorMsg ]);
1768
- })(msgValue);
1769
- } else if (9 === msgType) {
1770
- (({$winId$: $winId$, $instanceId$: $instanceId$, $refId$: $refId$, $thisArg$: $thisArg$, $args$: $args$}) => {
1771
- if (webWorkerRefsByRefId[$refId$]) {
1772
- try {
1773
- webWorkerRefsByRefId[$refId$].apply(deserializeFromMain($winId$, $instanceId$, [], $thisArg$), deserializeFromMain($winId$, $instanceId$, [], $args$));
1774
- } catch (e) {
1775
- console.error(e);
1776
- }
1777
- }
1778
- })(msgValue);
1779
- } else if (10 === msgType) {
1780
- (({$winId$: $winId$, $forward$: $forward$, $args$: $args$}) => {
1781
- try {
1782
- let target = environments[$winId$].$window$;
1783
- let i = 0;
1784
- let l = len($forward$);
1785
- for (;i < l; i++) {
1786
- i + 1 < l ? target = target[$forward$[i]] : target[$forward$[i]].apply(target, deserializeFromMain(null, $winId$, [], $args$));
1787
- }
1788
- } catch (e) {
1789
- console.error(e);
1790
- }
1791
- })(msgValue);
1792
- } else if (5 === msgType) {
1793
- createEnvironment(msgValue);
1794
- } else if (8 === msgType) {
1795
- if (1 !== environments[msgValue].$isInitialized$) {
1796
- const winId = msgValue;
1797
- const env = environments[winId];
1798
- const winType = env.$winId$ === env.$parentWinId$ ? "top" : "iframe";
1799
- logWorker(`Initialized ${winType} window ${normalizedWinId(winId)} environment 🎉`, winId);
2435
+ const WorkerEventTargetProxy = class extends WorkerBase {};
2436
+ eventTargetMethods.map(
2437
+ (methodName) =>
2438
+ (WorkerEventTargetProxy.prototype[methodName] = function (...args) {
2439
+ return callMethod(this, [methodName], args, 2);
2440
+ })
2441
+ );
2442
+ cachedProps(WorkerWindow, "devicePixelRatio");
2443
+ cachedDimensionProps(WorkerWindow);
2444
+ cachedDimensionMethods(WorkerWindow, ["getComputedStyle"]);
2445
+ new WorkerWindow();
2446
+ return env;
2447
+ };
2448
+ const TrapConstructors = {
2449
+ DOMStringMap: 1,
2450
+ NamedNodeMap: 1,
2451
+ };
2452
+ const createEnvironment = (
2453
+ {
2454
+ $winId$: $winId$,
2455
+ $parentWinId$: $parentWinId$,
2456
+ $url$: $url$,
2457
+ $visibilityState$: $visibilityState$,
2458
+ },
2459
+ isIframeWindow,
2460
+ isDocumentImplementation
2461
+ ) => {
2462
+ if (!environments[$winId$]) {
2463
+ environments[$winId$] = createWindow(
2464
+ $winId$,
2465
+ $parentWinId$,
2466
+ $url$,
2467
+ $visibilityState$,
2468
+ isIframeWindow,
2469
+ isDocumentImplementation
2470
+ );
2471
+ {
2472
+ const winType = $winId$ === $parentWinId$ ? "top" : "input";
2473
+ logWorker(
2474
+ `Created ${winType} window ${normalizedWinId($winId$)} environment`,
2475
+ $winId$
2476
+ );
2477
+ }
2478
+ }
2479
+ webWorkerCtx.$postMessage$([7, $winId$]);
2480
+ return environments[$winId$];
2481
+ };
2482
+ const queuedEvents = [];
2483
+ const receiveMessageFromSandboxToWorker = (ev) => {
2484
+ const msg = ev.data;
2485
+ const msgType = msg[0];
2486
+ const msgValue = msg[1];
2487
+ if (webWorkerCtx.$isInitialized$) {
2488
+ if (7 === msgType) {
2489
+ (async (initScript) => {
2490
+ let winId = initScript.$winId$;
2491
+ let instanceId = initScript.$instanceId$;
2492
+ let instance = getOrCreateNodeInstance(winId, instanceId, "SCRIPT");
2493
+ let scriptContent = initScript.$content$;
2494
+ let scriptSrc = initScript.$url$;
2495
+ let scriptOrgSrc = initScript.$orgUrl$;
2496
+ let errorMsg = "";
2497
+ let env = environments[winId];
2498
+ let rsp;
2499
+ let javascriptContentTypes = [
2500
+ "text/jscript",
2501
+ "text/javascript",
2502
+ "text/x-javascript",
2503
+ "application/javascript",
2504
+ "application/x-javascript",
2505
+ "text/ecmascript",
2506
+ "text/x-ecmascript",
2507
+ "application/ecmascript",
2508
+ ];
2509
+ if (scriptSrc) {
2510
+ try {
2511
+ scriptSrc = resolveToUrl(env, scriptSrc, "script") + "";
2512
+ setInstanceStateValue(instance, 4, scriptSrc);
2513
+ webWorkerCtx.$config$.logScriptExecution &&
2514
+ logWorker(`Execute script src: ${scriptOrgSrc}`, winId);
2515
+ rsp = await fetch(scriptSrc);
2516
+ if (rsp.ok) {
2517
+ let responseContentType = rsp.headers.get("content-type");
2518
+ let shouldExecute = javascriptContentTypes.some((ct) => {
2519
+ var _a, _b, _c;
2520
+ return null ===
2521
+ (_c =
2522
+ null ===
2523
+ (_a =
2524
+ null == responseContentType
2525
+ ? void 0
2526
+ : responseContentType.toLowerCase) || void 0 === _a
2527
+ ? void 0
2528
+ : (_b = _a.call(responseContentType)).includes) ||
2529
+ void 0 === _c
2530
+ ? void 0
2531
+ : _c.call(_b, ct);
2532
+ });
2533
+ if (shouldExecute) {
2534
+ scriptContent = await rsp.text();
2535
+ env.$currentScriptId$ = instanceId;
2536
+ run(env, scriptContent, scriptOrgSrc || scriptSrc);
1800
2537
  }
1801
- environments[msgValue].$isInitialized$ = 1;
1802
- environments[msgValue].$isLoading$ = 0;
1803
- } else if (14 === msgType) {
1804
- environments[msgValue].$visibilityState$ = msg[2];
1805
- } else if (13 === msgType) {
1806
- const $winId$ = msgValue.$winId$;
1807
- const env = environments[$winId$];
1808
- env.$location$.href = msgValue.url;
1809
- !function($winId$, env, data) {
1810
- const history = env.$window$.history;
1811
- switch (data.type) {
1812
- case 0:
1813
- env.$propagateHistoryChange$ = false;
1814
- try {
1815
- history.pushState(data.state, "", data.newUrl);
1816
- } catch (e) {}
1817
- env.$propagateHistoryChange$ = true;
1818
- break;
1819
-
1820
- case 1:
1821
- env.$propagateHistoryChange$ = false;
1822
- try {
1823
- history.replaceState(data.state, "", data.newUrl);
1824
- } catch (e) {}
1825
- env.$propagateHistoryChange$ = true;
1826
- }
1827
- }(msgValue.$winId$, env, msgValue);
1828
- } else {
1829
- 15 === msgType && ((_type, winId, instanceId, callbackName, args) => {
1830
- const elm = getOrCreateNodeInstance(winId, instanceId);
1831
- elm && "function" == typeof elm[callbackName] && elm[callbackName].apply(elm, args);
1832
- })(...msg);
1833
- }
1834
- } else if (1 === msgType) {
1835
- (initWebWorkerData => {
1836
- const config = webWorkerCtx.$config$ = JSON.parse(initWebWorkerData.$config$);
1837
- const locOrigin = initWebWorkerData.$origin$;
1838
- webWorkerCtx.$importScripts$ = importScripts.bind(self);
1839
- webWorkerCtx.$interfaces$ = initWebWorkerData.$interfaces$;
1840
- webWorkerCtx.$libPath$ = initWebWorkerData.$libPath$;
1841
- webWorkerCtx.$origin$ = locOrigin;
1842
- webWorkerCtx.$postMessage$ = postMessage.bind(self);
1843
- webWorkerCtx.$sharedDataBuffer$ = initWebWorkerData.$sharedDataBuffer$;
1844
- webWorkerlocalStorage.set(locOrigin, initWebWorkerData.$localStorage$);
1845
- webWorkerSessionStorage.set(locOrigin, initWebWorkerData.$sessionStorage$);
1846
- self.importScripts = void 0;
1847
- delete self.postMessage;
1848
- delete self.WorkerGlobalScope;
1849
- commaSplit("resolveUrl,get,set,apply").map((configName => {
1850
- config[configName] && (config[configName] = new Function("return " + config[configName])());
1851
- }));
1852
- })(msgValue);
1853
- webWorkerCtx.$postMessage$([ 2 ]);
1854
- } else if (3 === msgType) {
1855
- webWorkerCtx.$interfaces$ = [ ...webWorkerCtx.$interfaces$, ...msgValue ];
1856
- webWorkerCtx.$isInitialized$ = 1;
1857
- logWorker("Initialized web worker");
1858
- webWorkerCtx.$postMessage$([ 4 ]);
1859
- queuedEvents.length && logWorker(`Queued ready messages: ${queuedEvents.length}`);
1860
- [ ...queuedEvents ].map(receiveMessageFromSandboxToWorker);
1861
- queuedEvents.length = 0;
1862
- } else {
1863
- queuedEvents.push(ev);
2538
+ runStateLoadHandlers(instance, "load");
2539
+ } else {
2540
+ errorMsg = rsp.statusText;
2541
+ runStateLoadHandlers(instance, "error");
2542
+ }
2543
+ } catch (urlError) {
2544
+ console.error(urlError);
2545
+ errorMsg = String(urlError.stack || urlError);
2546
+ runStateLoadHandlers(instance, "error");
2547
+ }
2548
+ } else {
2549
+ scriptContent &&
2550
+ (errorMsg = runScriptContent(
2551
+ env,
2552
+ instanceId,
2553
+ scriptContent,
2554
+ winId,
2555
+ errorMsg
2556
+ ));
2557
+ }
2558
+ env.$currentScriptId$ = "";
2559
+ webWorkerCtx.$postMessage$([6, winId, instanceId, errorMsg]);
2560
+ })(msgValue);
2561
+ } else if (9 === msgType) {
2562
+ (({
2563
+ $winId$: $winId$,
2564
+ $instanceId$: $instanceId$,
2565
+ $refId$: $refId$,
2566
+ $thisArg$: $thisArg$,
2567
+ $args$: $args$,
2568
+ }) => {
2569
+ if (webWorkerRefsByRefId[$refId$]) {
2570
+ try {
2571
+ webWorkerRefsByRefId[$refId$].apply(
2572
+ deserializeFromMain($winId$, $instanceId$, [], $thisArg$),
2573
+ deserializeFromMain($winId$, $instanceId$, [], $args$)
2574
+ );
2575
+ } catch (e) {
2576
+ console.error(e);
2577
+ }
2578
+ }
2579
+ })(msgValue);
2580
+ } else if (10 === msgType) {
2581
+ (({ $winId$: $winId$, $forward$: $forward$, $args$: $args$ }) => {
2582
+ try {
2583
+ let target = environments[$winId$].$window$;
2584
+ let i = 0;
2585
+ let l = len($forward$);
2586
+ for (; i < l; i++) {
2587
+ i + 1 < l
2588
+ ? (target = target[$forward$[i]])
2589
+ : target[$forward$[i]].apply(
2590
+ target,
2591
+ deserializeFromMain(null, $winId$, [], $args$)
2592
+ );
2593
+ }
2594
+ } catch (e) {
2595
+ console.error(e);
2596
+ }
2597
+ })(msgValue);
2598
+ } else if (5 === msgType) {
2599
+ createEnvironment(msgValue);
2600
+ } else if (8 === msgType) {
2601
+ if (1 !== environments[msgValue].$isInitialized$) {
2602
+ const winId = msgValue;
2603
+ const env = environments[winId];
2604
+ const winType = env.$winId$ === env.$parentWinId$ ? "top" : "iframe";
2605
+ logWorker(
2606
+ `Initialized ${winType} window ${normalizedWinId(
2607
+ winId
2608
+ )} environment 🎉`,
2609
+ winId
2610
+ );
1864
2611
  }
1865
- };
1866
- self.onmessage = receiveMessageFromSandboxToWorker;
1867
- postMessage([ 0 ]);
2612
+ environments[msgValue].$isInitialized$ = 1;
2613
+ environments[msgValue].$isLoading$ = 0;
2614
+ } else if (14 === msgType) {
2615
+ environments[msgValue].$visibilityState$ = msg[2];
2616
+ } else if (13 === msgType) {
2617
+ const $winId$ = msgValue.$winId$;
2618
+ const env = environments[$winId$];
2619
+ env.$location$.href = msgValue.url;
2620
+ !(function ($winId$, env, data) {
2621
+ const history = env.$window$.history;
2622
+ switch (data.type) {
2623
+ case 0:
2624
+ env.$propagateHistoryChange$ = false;
2625
+ try {
2626
+ history.pushState(data.state, "", data.newUrl);
2627
+ } catch (e) {}
2628
+ env.$propagateHistoryChange$ = true;
2629
+ break;
2630
+
2631
+ case 1:
2632
+ env.$propagateHistoryChange$ = false;
2633
+ try {
2634
+ history.replaceState(data.state, "", data.newUrl);
2635
+ } catch (e) {}
2636
+ env.$propagateHistoryChange$ = true;
2637
+ }
2638
+ })(msgValue.$winId$, env, msgValue);
2639
+ } else {
2640
+ 15 === msgType &&
2641
+ ((_type, winId, instanceId, callbackName, args) => {
2642
+ const elm = getOrCreateNodeInstance(winId, instanceId);
2643
+ elm &&
2644
+ "function" == typeof elm[callbackName] &&
2645
+ elm[callbackName].apply(elm, args);
2646
+ })(...msg);
2647
+ }
2648
+ } else if (1 === msgType) {
2649
+ ((initWebWorkerData) => {
2650
+ const config = (webWorkerCtx.$config$ = JSON.parse(
2651
+ initWebWorkerData.$config$
2652
+ ));
2653
+ const locOrigin = initWebWorkerData.$origin$;
2654
+ webWorkerCtx.$importScripts$ = importScripts.bind(self);
2655
+ webWorkerCtx.$interfaces$ = initWebWorkerData.$interfaces$;
2656
+ webWorkerCtx.$libPath$ = initWebWorkerData.$libPath$;
2657
+ webWorkerCtx.$origin$ = locOrigin;
2658
+ webWorkerCtx.$postMessage$ = postMessage.bind(self);
2659
+ webWorkerCtx.$sharedDataBuffer$ = initWebWorkerData.$sharedDataBuffer$;
2660
+ webWorkerlocalStorage.set(locOrigin, initWebWorkerData.$localStorage$);
2661
+ webWorkerSessionStorage.set(
2662
+ locOrigin,
2663
+ initWebWorkerData.$sessionStorage$
2664
+ );
2665
+ self.importScripts = void 0;
2666
+ delete self.postMessage;
2667
+ delete self.WorkerGlobalScope;
2668
+ commaSplit("resolveUrl,get,set,apply").map((configName) => {
2669
+ config[configName] &&
2670
+ (config[configName] = new Function(
2671
+ "return " + config[configName]
2672
+ )());
2673
+ });
2674
+ })(msgValue);
2675
+ webWorkerCtx.$postMessage$([2]);
2676
+ } else if (3 === msgType) {
2677
+ webWorkerCtx.$interfaces$ = [...webWorkerCtx.$interfaces$, ...msgValue];
2678
+ webWorkerCtx.$isInitialized$ = 1;
2679
+ logWorker("Initialized web worker");
2680
+ webWorkerCtx.$postMessage$([4]);
2681
+ queuedEvents.length &&
2682
+ logWorker(`Queued ready messages: ${queuedEvents.length}`);
2683
+ [...queuedEvents].map(receiveMessageFromSandboxToWorker);
2684
+ queuedEvents.length = 0;
2685
+ } else {
2686
+ queuedEvents.push(ev);
2687
+ }
2688
+ };
2689
+ self.onmessage = receiveMessageFromSandboxToWorker;
2690
+ postMessage([0]);
1868
2691
  })(self);