1 |
|
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 environments = {};
|
17 | const cachedDimensions = new Map;
|
18 | const cachedStructure = new Map;
|
19 | const commaSplit = str => str.split(",");
|
20 | const partytownLibUrl = url => {
|
21 | url = webWorkerCtx.$libPath$ + url;
|
22 | if (new URL(url).origin != location.origin) {
|
23 | throw "Invalid " + url;
|
24 | }
|
25 | return url;
|
26 | };
|
27 | const getterDimensionPropNames = commaSplit("clientWidth,clientHeight,clientTop,clientLeft,innerWidth,innerHeight,offsetWidth,offsetHeight,offsetTop,offsetLeft,outerWidth,outerHeight,pageXOffset,pageYOffset,scrollWidth,scrollHeight,scrollTop,scrollLeft");
|
28 | const elementStructurePropNames = commaSplit("childElementCount,children,firstElementChild,lastElementChild,nextElementSibling,previousElementSibling");
|
29 | const structureChangingMethodNames = commaSplit("insertBefore,remove,removeChild,replaceChild");
|
30 | const dimensionChangingSetterNames = commaSplit("className,width,height,hidden,innerHTML,innerText,textContent,text");
|
31 | const dimensionChangingMethodNames = commaSplit("setAttribute,setAttributeNS,setProperty");
|
32 | const eventTargetMethods = commaSplit("addEventListener,dispatchEvent,removeEventListener");
|
33 | const nonBlockingMethods = eventTargetMethods.concat(dimensionChangingMethodNames, commaSplit("add,observe,remove,unobserve"));
|
34 | const IS_TAG_REG = /^[A-Z_]([A-Z0-9-]*[A-Z0-9])?$/;
|
35 | const noop = () => {};
|
36 | const len = obj => obj.length;
|
37 | const getConstructorName = obj => {
|
38 | var _a, _b, _c;
|
39 | try {
|
40 | const constructorName = null === (_a = null == obj ? void 0 : obj.constructor) || void 0 === _a ? void 0 : _a.name;
|
41 | if (constructorName) {
|
42 | return constructorName;
|
43 | }
|
44 | } catch (e) {}
|
45 | try {
|
46 | 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;
|
47 | if (zoneJsConstructorName) {
|
48 | return zoneJsConstructorName;
|
49 | }
|
50 | } catch (e) {}
|
51 | return "";
|
52 | };
|
53 | const EMPTY_ARRAY = [];
|
54 | const randomId = () => Math.round(Math.random() * Number.MAX_SAFE_INTEGER).toString(36);
|
55 | const SCRIPT_TYPE = "text/partytown";
|
56 | const defineProperty = (obj, memberName, descriptor) => Object.defineProperty(obj, memberName, {
|
57 | ...descriptor,
|
58 | configurable: true
|
59 | });
|
60 | const defineConstructorName = (Cstr, value) => defineProperty(Cstr, "name", {
|
61 | value: value
|
62 | });
|
63 | const definePrototypeProperty = (Cstr, memberName, descriptor) => defineProperty(Cstr.prototype, memberName, descriptor);
|
64 | const definePrototypePropertyDescriptor = (Cstr, propertyDescriptorMap) => Object.defineProperties(Cstr.prototype, propertyDescriptorMap);
|
65 | const definePrototypeValue = (Cstr, memberName, value) => definePrototypeProperty(Cstr, memberName, {
|
66 | value: value,
|
67 | writable: true
|
68 | });
|
69 | Object.freeze((obj => {
|
70 | const properties = new Set;
|
71 | let currentObj = obj;
|
72 | do {
|
73 | Object.getOwnPropertyNames(currentObj).forEach((item => {
|
74 | "function" == typeof currentObj[item] && properties.add(item);
|
75 | }));
|
76 | } while ((currentObj = Object.getPrototypeOf(currentObj)) !== Object.prototype);
|
77 | return Array.from(properties);
|
78 | })([]));
|
79 | function testIfMustLoadScriptOnMainThread(config, value) {
|
80 | var _a, _b;
|
81 | return null !== (_b = null === (_a = config.loadScriptsOnMainThread) || void 0 === _a ? void 0 : _a.map((([type, value]) => new RegExp("string" === type ? function(input) {
|
82 | return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
83 | }(value) : value))).some((regexp => regexp.test(value)))) && void 0 !== _b && _b;
|
84 | }
|
85 | const hasInstanceStateValue = (instance, stateKey) => stateKey in instance[InstanceStateKey];
|
86 | const getInstanceStateValue = (instance, stateKey) => instance[InstanceStateKey][stateKey];
|
87 | const setInstanceStateValue = (instance, stateKey, stateValue) => instance[InstanceStateKey][stateKey] = stateValue;
|
88 | const setWorkerRef = (ref, refId) => {
|
89 | if (!(refId = webWorkerRefIdsByRef.get(ref))) {
|
90 | webWorkerRefIdsByRef.set(ref, refId = randomId());
|
91 | webWorkerRefsByRefId[refId] = ref;
|
92 | }
|
93 | return refId;
|
94 | };
|
95 | const getOrCreateNodeInstance = (winId, instanceId, nodeName, namespace, instance, prevInstanceId) => {
|
96 | instance = webWorkerInstances.get(instanceId);
|
97 | if (!instance && nodeName && environments[winId]) {
|
98 | const prevInstance = webWorkerInstances.get(prevInstanceId || "");
|
99 | instance = environments[winId].$createNode$(nodeName, instanceId, namespace, prevInstance);
|
100 | webWorkerInstances.set(instanceId, instance);
|
101 | }
|
102 | return instance;
|
103 | };
|
104 | const definePrototypeNodeType = (Cstr, nodeType) => definePrototypeValue(Cstr, "nodeType", nodeType);
|
105 | const cachedTreeProps = (Cstr, treeProps) => treeProps.map((propName => definePrototypeProperty(Cstr, propName, {
|
106 | get() {
|
107 | let cacheKey = getInstanceCacheKey(this, propName);
|
108 | let result = cachedStructure.get(cacheKey);
|
109 | if (!result) {
|
110 | result = getter(this, [ propName ]);
|
111 | cachedStructure.set(cacheKey, result);
|
112 | }
|
113 | return result;
|
114 | }
|
115 | })));
|
116 | const getInstanceCacheKey = (instance, memberName, args) => [ instance[WinIdKey], instance[InstanceIdKey], memberName, ...(args || EMPTY_ARRAY).map((arg => String(arg && arg[WinIdKey] ? arg[InstanceIdKey] : arg))) ].join(".");
|
117 | const cachedProps = (Cstr, propNames) => commaSplit(propNames).map((propName => definePrototypeProperty(Cstr, propName, {
|
118 | get() {
|
119 | hasInstanceStateValue(this, propName) || setInstanceStateValue(this, propName, getter(this, [ propName ]));
|
120 | return getInstanceStateValue(this, propName);
|
121 | },
|
122 | set(val) {
|
123 | getInstanceStateValue(this, propName) !== val && setter(this, [ propName ], val);
|
124 | setInstanceStateValue(this, propName, val);
|
125 | }
|
126 | })));
|
127 | const cachedDimensionProps = Cstr => getterDimensionPropNames.map((propName => definePrototypeProperty(Cstr, propName, {
|
128 | get() {
|
129 | const dimension = cachedDimensions.get(getInstanceCacheKey(this, propName));
|
130 | if ("number" == typeof dimension) {
|
131 | return dimension;
|
132 | }
|
133 | const groupedDimensions = getter(this, [ propName ], getterDimensionPropNames);
|
134 | if (groupedDimensions && "object" == typeof groupedDimensions) {
|
135 | Object.entries(groupedDimensions).map((([dimensionPropName, value]) => cachedDimensions.set(getInstanceCacheKey(this, dimensionPropName), value)));
|
136 | return groupedDimensions[propName];
|
137 | }
|
138 | return groupedDimensions;
|
139 | }
|
140 | })));
|
141 | const cachedDimensionMethods = (Cstr, dimensionMethodNames) => dimensionMethodNames.map((methodName => {
|
142 | Cstr.prototype[methodName] = function(...args) {
|
143 | let cacheKey = getInstanceCacheKey(this, methodName, args);
|
144 | let dimensions = cachedDimensions.get(cacheKey);
|
145 | if (!dimensions) {
|
146 | dimensions = callMethod(this, [ methodName ], args);
|
147 | cachedDimensions.set(cacheKey, dimensions);
|
148 | }
|
149 | return dimensions;
|
150 | };
|
151 | }));
|
152 | 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, {
|
153 | $winId$: $winId$,
|
154 | $instanceId$: $instanceId$,
|
155 | $refId$: setWorkerRef(value)
|
156 | } ] : (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;
|
157 | const supportsTrustedHTML = "undefined" != typeof TrustedHTML;
|
158 | const serializeObjectForMain = (winId, instanceId, obj, includeFunctions, added, serializedObj, propName, propValue) => {
|
159 | serializedObj = {};
|
160 | if (!added.has(obj)) {
|
161 | added.add(obj);
|
162 | for (propName in obj) {
|
163 | propValue = obj[propName];
|
164 | (includeFunctions || "function" != typeof propValue) && (serializedObj[propName] = serializeForMain(winId, instanceId, propValue, added));
|
165 | }
|
166 | }
|
167 | return serializedObj;
|
168 | };
|
169 | const serializeInstanceForMain = (instance, value) => instance ? serializeForMain(instance[WinIdKey], instance[InstanceIdKey], value) : [ 0, value ];
|
170 | const deserializeFromMain = (winId, instanceId, applyPath, serializedValueTransfer, serializedType, serializedValue, obj, key) => {
|
171 | if (serializedValueTransfer) {
|
172 | serializedType = serializedValueTransfer[0];
|
173 | serializedValue = serializedValueTransfer[1];
|
174 | if (0 === serializedType || 11 === serializedType || 12 === serializedType) {
|
175 | return serializedValue;
|
176 | }
|
177 | if (4 === serializedType) {
|
178 | return deserializeRefFromMain(applyPath, serializedValue);
|
179 | }
|
180 | if (6 === serializedType) {
|
181 | return winId && applyPath.length > 0 ? (...args) => callMethod(environments[winId].$window$, applyPath, args, 1) : noop;
|
182 | }
|
183 | if (3 === serializedType) {
|
184 | return getOrCreateSerializedInstance(serializedValue);
|
185 | }
|
186 | if (7 === serializedType) {
|
187 | return new NodeList(serializedValue.map(getOrCreateSerializedInstance));
|
188 | }
|
189 | if (10 === serializedType) {
|
190 | return new Attr(serializedValue);
|
191 | }
|
192 | if (1 === serializedType) {
|
193 | return serializedValue.map((v => deserializeFromMain(winId, instanceId, applyPath, v)));
|
194 | }
|
195 | if (14 === serializedType) {
|
196 | return new CustomError(serializedValue);
|
197 | }
|
198 | obj = {};
|
199 | for (key in serializedValue) {
|
200 | obj[key] = deserializeFromMain(winId, instanceId, [ ...applyPath, key ], serializedValue[key]);
|
201 | }
|
202 | if (13 === serializedType) {
|
203 | return new environments[winId].$window$.CSSStyleDeclaration(winId, instanceId, applyPath, obj);
|
204 | }
|
205 | if (5 === serializedType) {
|
206 | if ("message" === obj.type && obj.origin) {
|
207 | let postMessageKey = JSON.stringify(obj.data);
|
208 | let postMessageData = postMessages.find((pm => pm.$data$ === postMessageKey));
|
209 | let env;
|
210 | if (postMessageData) {
|
211 | env = environments[postMessageData.$winId$];
|
212 | if (env) {
|
213 | obj.source = env.$window$;
|
214 | obj.origin = env.$location$.origin;
|
215 | }
|
216 | }
|
217 | }
|
218 | return new Proxy(new Event(obj.type, obj), {
|
219 | get: (target, propName) => propName in obj ? obj[propName] : "function" == typeof target[String(propName)] ? noop : target[String(propName)]
|
220 | });
|
221 | }
|
222 | if (2 === serializedType) {
|
223 | return obj;
|
224 | }
|
225 | }
|
226 | };
|
227 | const getOrCreateSerializedInstance = ([winId, instanceId, nodeName, prevInstanceId]) => instanceId === winId && environments[winId] ? environments[winId].$window$ : getOrCreateNodeInstance(winId, instanceId, nodeName, void 0, void 0, prevInstanceId);
|
228 | const deserializeRefFromMain = (applyPath, {$winId$: $winId$, $instanceId$: $instanceId$, $nodeName$: $nodeName$, $refId$: $refId$}) => {
|
229 | webWorkerRefsByRefId[$refId$] || webWorkerRefIdsByRef.set(webWorkerRefsByRefId[$refId$] = function(...args) {
|
230 | const instance = getOrCreateNodeInstance($winId$, $instanceId$, $nodeName$);
|
231 | return callMethod(instance, applyPath, args);
|
232 | }, $refId$);
|
233 | return webWorkerRefsByRefId[$refId$];
|
234 | };
|
235 | class CustomError extends Error {
|
236 | constructor(errorObject) {
|
237 | super(errorObject.message);
|
238 | this.name = errorObject.name;
|
239 | this.message = errorObject.message;
|
240 | this.stack = errorObject.stack;
|
241 | }
|
242 | }
|
243 | class NodeList {
|
244 | constructor(nodes) {
|
245 | (this._ = nodes).map(((node, index) => this[index] = node));
|
246 | }
|
247 | entries() {
|
248 | return this._.entries();
|
249 | }
|
250 | forEach(cb, thisArg) {
|
251 | this._.map(cb, thisArg);
|
252 | }
|
253 | item(index) {
|
254 | return this[index];
|
255 | }
|
256 | keys() {
|
257 | return this._.keys();
|
258 | }
|
259 | get length() {
|
260 | return len(this._);
|
261 | }
|
262 | values() {
|
263 | return this._.values();
|
264 | }
|
265 | [Symbol.iterator]() {
|
266 | return this._[Symbol.iterator]();
|
267 | }
|
268 | }
|
269 | const Attr = class {
|
270 | constructor(serializedAttr) {
|
271 | this.name = serializedAttr[0];
|
272 | this.value = serializedAttr[1];
|
273 | }
|
274 | get nodeName() {
|
275 | return this.name;
|
276 | }
|
277 | get nodeType() {
|
278 | return 2;
|
279 | }
|
280 | };
|
281 | const warnCrossOrigin = (apiType, apiName, env) => console.warn(`Partytown unable to ${apiType} cross-origin ${apiName}: ` + env.$location$);
|
282 | const logWorker = (msg, winId) => {
|
283 | try {
|
284 | const config = webWorkerCtx.$config$;
|
285 | if (config.logStackTraces) {
|
286 | const frames = (new Error).stack.split("\n");
|
287 | const i = frames.findIndex((f => f.includes("logWorker")));
|
288 | msg += "\n" + frames.slice(i + 1).join("\n");
|
289 | }
|
290 | let prefix;
|
291 | let color;
|
292 | if (winId) {
|
293 | prefix = `Worker (${normalizedWinId(winId)}) 🎉`;
|
294 | color = winColor(winId);
|
295 | } else {
|
296 | prefix = self.name;
|
297 | color = "#9844bf";
|
298 | }
|
299 | if (webWorkerCtx.lastLog !== msg) {
|
300 | webWorkerCtx.lastLog = msg;
|
301 | console.debug.apply(console, [ `%c${prefix}`, `background: ${color}; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;`, msg ]);
|
302 | }
|
303 | } catch (e) {}
|
304 | };
|
305 | const winIds = [];
|
306 | const normalizedWinId = winId => {
|
307 | winIds.includes(winId) || winIds.push(winId);
|
308 | return winIds.indexOf(winId) + 1;
|
309 | };
|
310 | const winColor = winId => {
|
311 | const colors = [ "#00309e", "#ea3655", "#eea727" ];
|
312 | const index = normalizedWinId(winId) - 1;
|
313 | return colors[index] || colors[colors.length - 1];
|
314 | };
|
315 | const getTargetProp = (target, applyPath) => {
|
316 | let n = "";
|
317 | if (target) {
|
318 | const cstrName = getConstructorName(target);
|
319 | if ("Window" === cstrName) {
|
320 | n = "";
|
321 | } else if ("string" == typeof target[InstanceDataKey]) {
|
322 | let nodeName = target[InstanceDataKey];
|
323 | n = "#text" === nodeName ? "textNode." : "#comment" === nodeName ? "commentNode." : "#document" === nodeName ? "document." : "html" === nodeName ? "doctype." : nodeName.toLowerCase() + ".";
|
324 | } else {
|
325 | 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) + ".";
|
326 | }
|
327 | target[ApplyPathKey] && target[ApplyPathKey].length && (n += [ ...target[ApplyPathKey] ].join(".") + ".");
|
328 | }
|
329 | if (applyPath.length > 1) {
|
330 | const first = applyPath.slice(0, applyPath.length - 1);
|
331 | const last = applyPath[applyPath.length - 1];
|
332 | if (!isNaN(last)) {
|
333 | return n + `${first.join(".")}[${last}]`;
|
334 | }
|
335 | }
|
336 | return n + applyPath.join(".");
|
337 | };
|
338 | const getLogValue = (applyPath, v) => {
|
339 | const type = typeof v;
|
340 | if (void 0 === v) {
|
341 | return "undefined";
|
342 | }
|
343 | if ("boolean" === type || "number" === type || null == v) {
|
344 | return JSON.stringify(v);
|
345 | }
|
346 | if ("string" === type) {
|
347 | return applyPath.includes("cookie") ? JSON.stringify(v.slice(0, 10) + "...") : JSON.stringify(v.length > 50 ? v.slice(0, 40) + "..." : v);
|
348 | }
|
349 | if (Array.isArray(v)) {
|
350 | return `[${v.map(getLogValue).join(", ")}]`;
|
351 | }
|
352 | if ("object" === type) {
|
353 | const instanceId = v[InstanceIdKey];
|
354 | const cstrName = getConstructorName(v);
|
355 | if ("string" == typeof instanceId) {
|
356 | if ("Window" === cstrName) {
|
357 | return "window";
|
358 | }
|
359 | if ("string" == typeof v[InstanceDataKey]) {
|
360 | if (1 === v.nodeType) {
|
361 | return `<${v[InstanceDataKey].toLowerCase()}>`;
|
362 | }
|
363 | if (10 === v.nodeType) {
|
364 | return `<!DOCTYPE ${v[InstanceDataKey]}>`;
|
365 | }
|
366 | if (v.nodeType <= 11) {
|
367 | return v[InstanceDataKey];
|
368 | }
|
369 | }
|
370 | return "¯\\_(ツ)_/¯ instance obj";
|
371 | }
|
372 | 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);
|
373 | }
|
374 | return (v => "object" == typeof v && v && v.then)(v) ? "Promise" : "function" === type ? `ƒ() ${v.name || ""}`.trim() : `¯\\_(ツ)_/¯ ${String(v)}`.trim();
|
375 | };
|
376 | const objToString = obj => {
|
377 | const s = [];
|
378 | for (let key in obj) {
|
379 | const value = obj[key];
|
380 | const type = typeof value;
|
381 | "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)}`);
|
382 | }
|
383 | let str = s.join(", ");
|
384 | str.length > 200 && (str = str.substring(0, 200) + "..");
|
385 | return `{ ${str} }`;
|
386 | };
|
387 | const logDimensionCacheClearStyle = (target, propName) => {
|
388 | (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logSetters) && logWorker(`Dimension cache cleared from style.${propName} setter`, target[WinIdKey]);
|
389 | };
|
390 | const logDimensionCacheClearMethod = (target, methodName) => {
|
391 | (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) && logWorker(`Dimension cache cleared from method call ${methodName}()`, target[WinIdKey]);
|
392 | };
|
393 | const taskQueue = [];
|
394 | const queue = (instance, $applyPath$, callType, $assignInstanceId$, $groupedGetters$, buffer) => {
|
395 | if (instance[ApplyPathKey]) {
|
396 | taskQueue.push({
|
397 | $winId$: instance[WinIdKey],
|
398 | $instanceId$: instance[InstanceIdKey],
|
399 | $applyPath$: [ ...instance[ApplyPathKey], ...$applyPath$ ],
|
400 | $assignInstanceId$: $assignInstanceId$,
|
401 | $groupedGetters$: $groupedGetters$
|
402 | });
|
403 | taskQueue[len(taskQueue) - 1].$debug$ = ((target, applyPath, callType) => {
|
404 | let m = getTargetProp(target, applyPath);
|
405 | 1 === callType ? m += " (blocking)" : 2 === callType ? m += " (non-blocking)" : 3 === callType && (m += " (non-blocking, no-side-effect)");
|
406 | return m.trim();
|
407 | })(instance, $applyPath$, callType);
|
408 | buffer && 3 !== callType && console.error("buffer must be sent NonBlockingNoSideEffect");
|
409 | if (3 === callType) {
|
410 | webWorkerCtx.$postMessage$([ 12, {
|
411 | $msgId$: randomId(),
|
412 | $tasks$: [ ...taskQueue ]
|
413 | } ], buffer ? [ buffer instanceof ArrayBuffer ? buffer : buffer.buffer ] : void 0);
|
414 | taskQueue.length = 0;
|
415 | } else if (1 === callType) {
|
416 | return sendToMain(true);
|
417 | }
|
418 | webWorkerCtx.$asyncMsgTimer$ = setTimeout(sendToMain, 20);
|
419 | }
|
420 | };
|
421 | const sendToMain = isBlocking => {
|
422 | clearTimeout(webWorkerCtx.$asyncMsgTimer$);
|
423 | if (len(taskQueue)) {
|
424 | webWorkerCtx.$config$.logMainAccess && logWorker(`Main access, tasks sent: ${taskQueue.length}`);
|
425 | const endTask = taskQueue[len(taskQueue) - 1];
|
426 | const accessReq = {
|
427 | $msgId$: `${randomId()}.${webWorkerCtx.$tabId$}`,
|
428 | $tasks$: [ ...taskQueue ]
|
429 | };
|
430 | taskQueue.length = 0;
|
431 | if (isBlocking) {
|
432 | const accessRsp = ((webWorkerCtx, accessReq) => {
|
433 | const xhr = new XMLHttpRequest;
|
434 | xhr.open("POST", partytownLibUrl("proxytown"), false);
|
435 | xhr.send(JSON.stringify(accessReq));
|
436 | return JSON.parse(xhr.responseText);
|
437 | })(0, accessReq);
|
438 | const isPromise = accessRsp.$isPromise$;
|
439 | const rtnValue = deserializeFromMain(endTask.$winId$, endTask.$instanceId$, endTask.$applyPath$, accessRsp.$rtnValue$);
|
440 | if (accessRsp.$error$) {
|
441 | if (isPromise) {
|
442 | return Promise.reject(accessRsp.$error$);
|
443 | }
|
444 | throw new Error(accessRsp.$error$);
|
445 | }
|
446 | return isPromise ? Promise.resolve(rtnValue) : rtnValue;
|
447 | }
|
448 | webWorkerCtx.$postMessage$([ 12, accessReq ]);
|
449 | }
|
450 | };
|
451 | const getter = (instance, applyPath, groupedGetters, rtnValue) => {
|
452 | if (webWorkerCtx.$config$.get) {
|
453 | rtnValue = webWorkerCtx.$config$.get(createHookOptions(instance, applyPath));
|
454 | if (rtnValue !== HookContinue) {
|
455 | return rtnValue;
|
456 | }
|
457 | }
|
458 | rtnValue = queue(instance, applyPath, 1, void 0, groupedGetters);
|
459 | ((target, applyPath, rtnValue, restrictedToWorker = false, groupedGetters = false) => {
|
460 | if (webWorkerCtx.$config$.logGetters) {
|
461 | try {
|
462 | const msg = `Get ${getTargetProp(target, applyPath)}, returned: ${getLogValue(applyPath, rtnValue)}${restrictedToWorker ? " (restricted to worker)" : ""}${groupedGetters ? " (grouped getter)" : ""}`;
|
463 | msg.includes("Symbol(") || logWorker(msg, target[WinIdKey]);
|
464 | } catch (e) {}
|
465 | }
|
466 | })(instance, applyPath, rtnValue, false, !!groupedGetters);
|
467 | return rtnValue;
|
468 | };
|
469 | const setter = (instance, applyPath, value, hookSetterValue) => {
|
470 | if (webWorkerCtx.$config$.set) {
|
471 | hookSetterValue = webWorkerCtx.$config$.set({
|
472 | value: value,
|
473 | prevent: HookPrevent,
|
474 | ...createHookOptions(instance, applyPath)
|
475 | });
|
476 | if (hookSetterValue === HookPrevent) {
|
477 | return;
|
478 | }
|
479 | hookSetterValue !== HookContinue && (value = hookSetterValue);
|
480 | }
|
481 | if (dimensionChangingSetterNames.some((s => applyPath.includes(s)))) {
|
482 | cachedDimensions.clear();
|
483 | ((target, propName) => {
|
484 | (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logSetters) && logWorker(`Dimension cache cleared from setter "${propName}"`, target[WinIdKey]);
|
485 | })(instance, applyPath[applyPath.length - 1]);
|
486 | }
|
487 | applyPath = [ ...applyPath, serializeInstanceForMain(instance, value), 0 ];
|
488 | ((target, applyPath, value, restrictedToWorker = false) => {
|
489 | if (webWorkerCtx.$config$.logSetters) {
|
490 | try {
|
491 | applyPath = applyPath.slice(0, applyPath.length - 2);
|
492 | logWorker(`Set ${getTargetProp(target, applyPath)}, value: ${getLogValue(applyPath, value)}${restrictedToWorker ? " (restricted to worker)" : ""}`, target[WinIdKey]);
|
493 | } catch (e) {}
|
494 | }
|
495 | })(instance, applyPath, value);
|
496 | queue(instance, applyPath, 2);
|
497 | };
|
498 | const callMethod = (instance, applyPath, args, callType, assignInstanceId, buffer, rtnValue, methodName) => {
|
499 | if (webWorkerCtx.$config$.apply) {
|
500 | rtnValue = webWorkerCtx.$config$.apply({
|
501 | args: args,
|
502 | ...createHookOptions(instance, applyPath)
|
503 | });
|
504 | if (rtnValue !== HookContinue) {
|
505 | return rtnValue;
|
506 | }
|
507 | }
|
508 | methodName = applyPath[len(applyPath) - 1];
|
509 | applyPath = [ ...applyPath, serializeInstanceForMain(instance, args) ];
|
510 | callType = callType || (nonBlockingMethods.includes(methodName) ? 2 : 1);
|
511 | if ("setAttribute" === methodName && hasInstanceStateValue(instance, args[0])) {
|
512 | setInstanceStateValue(instance, args[0], args[1]);
|
513 | } else if (structureChangingMethodNames.includes(methodName)) {
|
514 | cachedDimensions.clear();
|
515 | cachedStructure.clear();
|
516 | ((target, methodName) => {
|
517 | (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) && logWorker(`Dimension and DOM structure cache cleared from method call ${methodName}()`, target[WinIdKey]);
|
518 | })(instance, methodName);
|
519 | } else if (dimensionChangingMethodNames.includes(methodName)) {
|
520 | callType = 2;
|
521 | cachedDimensions.clear();
|
522 | logDimensionCacheClearMethod(instance, methodName);
|
523 | }
|
524 | rtnValue = queue(instance, applyPath, callType, assignInstanceId, void 0, buffer);
|
525 | ((target, applyPath, args, rtnValue) => {
|
526 | if (webWorkerCtx.$config$.logCalls) {
|
527 | try {
|
528 | applyPath = applyPath.slice(0, applyPath.length - 1);
|
529 | logWorker(`Call ${getTargetProp(target, applyPath)}(${args.map((v => getLogValue(applyPath, v))).join(", ")}), returned: ${getLogValue(applyPath, rtnValue)}`, target[WinIdKey]);
|
530 | } catch (e) {}
|
531 | }
|
532 | })(instance, applyPath, args, rtnValue);
|
533 | return rtnValue;
|
534 | };
|
535 | const constructGlobal = (instance, cstrName, args) => {
|
536 | ((target, cstrName, args) => {
|
537 | if (webWorkerCtx.$config$.logCalls) {
|
538 | try {
|
539 | logWorker(`Construct new ${cstrName}(${args.map((v => getLogValue([], v))).join(", ")})`, target[WinIdKey]);
|
540 | } catch (e) {}
|
541 | }
|
542 | })(instance, cstrName, args);
|
543 | queue(instance, [ 1, cstrName, serializeInstanceForMain(instance, args) ], 1);
|
544 | };
|
545 | const createHookOptions = (instance, applyPath) => ({
|
546 | name: applyPath.join("."),
|
547 | continue: HookContinue,
|
548 | nodeName: instance[InstanceDataKey],
|
549 | constructor: getConstructorName(instance),
|
550 | instance: instance,
|
551 | window: environments[instance[WinIdKey]].$window$
|
552 | });
|
553 | const addStorageApi = (win, storageName, isSameOrigin, env) => {
|
554 | let storage = {
|
555 | getItem(key) {
|
556 | if (isSameOrigin) {
|
557 | return callMethod(win, [ storageName, "getItem" ], [ key ], 1);
|
558 | }
|
559 | warnCrossOrigin("get", storageName, env);
|
560 | },
|
561 | setItem(key, value) {
|
562 | isSameOrigin ? callMethod(win, [ storageName, "setItem" ], [ key, value ], 1) : warnCrossOrigin("set", storageName, env);
|
563 | },
|
564 | removeItem(key) {
|
565 | isSameOrigin ? callMethod(win, [ storageName, "removeItem" ], [ key ], 1) : warnCrossOrigin("remove", storageName, env);
|
566 | },
|
567 | key(index) {
|
568 | if (isSameOrigin) {
|
569 | return callMethod(win, [ storageName, "key" ], [ index ], 1);
|
570 | }
|
571 | warnCrossOrigin("key", storageName, env);
|
572 | },
|
573 | clear() {
|
574 | isSameOrigin ? callMethod(win, [ storageName, "clear" ], EMPTY_ARRAY, 1) : warnCrossOrigin("clear", storageName, env);
|
575 | },
|
576 | get length() {
|
577 | if (isSameOrigin) {
|
578 | return getter(win, [ storageName, "length" ]);
|
579 | }
|
580 | warnCrossOrigin("length", storageName, env);
|
581 | }
|
582 | };
|
583 | win[storageName] = new Proxy(storage, {
|
584 | get: (target, key) => Reflect.has(target, key) ? Reflect.get(target, key) : target.getItem(key),
|
585 | set(target, key, value) {
|
586 | target.setItem(key, value);
|
587 | return true;
|
588 | },
|
589 | has: (target, key) => !!Reflect.has(target, key) || "string" == typeof key && null !== target.getItem(key),
|
590 | deleteProperty(target, key) {
|
591 | target.removeItem(key);
|
592 | return true;
|
593 | }
|
594 | });
|
595 | };
|
596 | const createCSSStyleDeclarationCstr = (win, WorkerBase, cstrName) => {
|
597 | win[cstrName] = defineConstructorName(class extends WorkerBase {
|
598 | constructor(winId, instanceId, applyPath, styles) {
|
599 | super(winId, instanceId, applyPath, styles || {});
|
600 | return new Proxy(this, {
|
601 | get(target, propName) {
|
602 | if (target[propName]) {
|
603 | return target[propName];
|
604 | }
|
605 | target[propName] || "string" != typeof propName || target[InstanceDataKey][propName] || (target[InstanceDataKey][propName] = getter(target, [ propName ]));
|
606 | return target[InstanceDataKey][propName];
|
607 | },
|
608 | set(target, propName, propValue) {
|
609 | target[InstanceDataKey][propName] = propValue;
|
610 | setter(target, [ propName ], propValue);
|
611 | logDimensionCacheClearStyle(target, propName);
|
612 | cachedDimensions.clear();
|
613 | return true;
|
614 | }
|
615 | });
|
616 | }
|
617 | setProperty(...args) {
|
618 | this[InstanceDataKey][args[0]] = args[1];
|
619 | callMethod(this, [ "setProperty" ], args, 2);
|
620 | logDimensionCacheClearStyle(this, args[0]);
|
621 | cachedDimensions.clear();
|
622 | }
|
623 | getPropertyValue(propName) {
|
624 | return this[propName];
|
625 | }
|
626 | removeProperty(propName) {
|
627 | let value = this[InstanceDataKey][propName];
|
628 | callMethod(this, [ "removeProperty" ], [ propName ], 2);
|
629 | logDimensionCacheClearStyle(this, propName);
|
630 | cachedDimensions.clear();
|
631 | this[InstanceDataKey][propName] = void 0;
|
632 | return value;
|
633 | }
|
634 | }, cstrName);
|
635 | };
|
636 | const createCSSStyleSheetConstructor = (win, cssStyleSheetCstrName) => {
|
637 | win[cssStyleSheetCstrName] = defineConstructorName(class {
|
638 | constructor(ownerNode) {
|
639 | this.ownerNode = ownerNode;
|
640 | }
|
641 | get cssRules() {
|
642 | const ownerNode = this.ownerNode;
|
643 | return new Proxy({}, {
|
644 | get(target, propKey) {
|
645 | const propName = String(propKey);
|
646 | return "item" === propName ? index => getCssRule(ownerNode, index) : "length" === propName ? getCssRules(ownerNode).length : isNaN(propName) ? target[propKey] : getCssRule(ownerNode, propName);
|
647 | }
|
648 | });
|
649 | }
|
650 | insertRule(ruleText, index) {
|
651 | const cssRules = getCssRules(this.ownerNode);
|
652 | index = void 0 === index ? 0 : index;
|
653 | if (index >= 0 && index <= cssRules.length) {
|
654 | callMethod(this.ownerNode, [ "sheet", "insertRule" ], [ ruleText, index ], 2);
|
655 | cssRules.splice(index, 0, 0);
|
656 | }
|
657 | logDimensionCacheClearMethod(this.ownerNode, "insertRule");
|
658 | cachedDimensions.clear();
|
659 | return index;
|
660 | }
|
661 | deleteRule(index) {
|
662 | callMethod(this.ownerNode, [ "sheet", "deleteRule" ], [ index ], 2);
|
663 | getCssRules(this.ownerNode).splice(index, 1);
|
664 | logDimensionCacheClearMethod(this.ownerNode, "deleteRule");
|
665 | cachedDimensions.clear();
|
666 | }
|
667 | get type() {
|
668 | return "text/css";
|
669 | }
|
670 | }, cssStyleSheetCstrName);
|
671 | const HTMLStyleDescriptorMap = {
|
672 | sheet: {
|
673 | get() {
|
674 | return new win[cssStyleSheetCstrName](this);
|
675 | }
|
676 | }
|
677 | };
|
678 | definePrototypePropertyDescriptor(win.HTMLStyleElement, HTMLStyleDescriptorMap);
|
679 | };
|
680 | const getCssRules = (ownerNode, cssRules) => {
|
681 | cssRules = getInstanceStateValue(ownerNode, 2);
|
682 | if (!cssRules) {
|
683 | cssRules = getter(ownerNode, [ "sheet", "cssRules" ]);
|
684 | setInstanceStateValue(ownerNode, 2, cssRules);
|
685 | }
|
686 | return cssRules;
|
687 | };
|
688 | const getCssRule = (ownerNode, index, cssRules) => {
|
689 | cssRules = getCssRules(ownerNode);
|
690 | 0 === cssRules[index] && (cssRules[index] = getter(ownerNode, [ "sheet", "cssRules", parseInt(index, 10) ]));
|
691 | return cssRules[index];
|
692 | };
|
693 | const runScriptContent = (env, instanceId, scriptContent, winId, errorMsg) => {
|
694 | try {
|
695 | webWorkerCtx.$config$.logScriptExecution && logWorker(`Execute script: ${scriptContent.substring(0, 100).split("\n").map((l => l.trim())).join(" ").trim().substring(0, 60)}...`, winId);
|
696 | env.$currentScriptId$ = instanceId;
|
697 | run(env, scriptContent);
|
698 | } catch (contentError) {
|
699 | console.error(scriptContent, contentError);
|
700 | errorMsg = String(contentError.stack || contentError);
|
701 | }
|
702 | env.$currentScriptId$ = "";
|
703 | return errorMsg;
|
704 | };
|
705 | const run = (env, scriptContent, scriptUrl) => {
|
706 | env.$runWindowLoadEvent$ = 1;
|
707 | let sourceWithReplacedThis = ((scriptContent, newThis) => scriptContent.replace(/([a-zA-Z0-9_$\.\'\"\`])?(\.\.\.)?this(?![a-zA-Z0-9_$:])/g, ((match, p1, p2) => {
|
708 | const prefix = (p1 || "") + (p2 || "");
|
709 | return null != p1 ? prefix + "this" : prefix + newThis;
|
710 | })))(scriptContent, "(thi$(this)?window:this)");
|
711 | scriptContent = `with(this){${sourceWithReplacedThis.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 : "");
|
712 | env.$isSameOrigin$ || (scriptContent = scriptContent.replace(/.postMessage\(/g, `.postMessage('${env.$winId$}',`));
|
713 | new Function(scriptContent).call(env.$window$);
|
714 | env.$runWindowLoadEvent$ = 0;
|
715 | };
|
716 | const runStateLoadHandlers = (instance, type, handlers) => {
|
717 | handlers = getInstanceStateValue(instance, type);
|
718 | handlers && setTimeout((() => handlers.map((cb => cb({
|
719 | type: type
|
720 | })))));
|
721 | };
|
722 | const resolveBaseLocation = (env, baseLocation) => {
|
723 | baseLocation = env.$location$;
|
724 | while (!baseLocation.host) {
|
725 | env = environments[env.$parentWinId$];
|
726 | baseLocation = env.$location$;
|
727 | if (env.$winId$ === env.$parentWinId$) {
|
728 | break;
|
729 | }
|
730 | }
|
731 | return baseLocation;
|
732 | };
|
733 | const resolveToUrl = (env, url, type, baseLocation, resolvedUrl, configResolvedUrl) => {
|
734 | baseLocation = resolveBaseLocation(env, baseLocation);
|
735 | resolvedUrl = new URL(url || "", baseLocation);
|
736 | if (type && webWorkerCtx.$config$.resolveUrl) {
|
737 | configResolvedUrl = webWorkerCtx.$config$.resolveUrl(resolvedUrl, baseLocation, type);
|
738 | if (configResolvedUrl) {
|
739 | return configResolvedUrl;
|
740 | }
|
741 | }
|
742 | return resolvedUrl;
|
743 | };
|
744 | const resolveUrl = (env, url, type) => resolveToUrl(env, url, type) + "";
|
745 | const resolveSendBeaconRequestParameters = (env, url) => {
|
746 | const baseLocation = resolveBaseLocation(env);
|
747 | const resolvedUrl = new URL(url || "", baseLocation);
|
748 | if (webWorkerCtx.$config$.resolveSendBeaconRequestParameters) {
|
749 | const configResolvedParams = webWorkerCtx.$config$.resolveSendBeaconRequestParameters(resolvedUrl, baseLocation);
|
750 | if (configResolvedParams) {
|
751 | return configResolvedParams;
|
752 | }
|
753 | }
|
754 | return {};
|
755 | };
|
756 | const getPartytownScript = () => `<script src="${partytownLibUrl("partytown.js?v=0.10.1")}"><\/script>`;
|
757 | const createImageConstructor = env => class HTMLImageElement {
|
758 | constructor() {
|
759 | this.s = "";
|
760 | this.l = [];
|
761 | this.e = [];
|
762 | this.style = {};
|
763 | }
|
764 | get src() {
|
765 | return this.s;
|
766 | }
|
767 | set src(src) {
|
768 | webWorkerCtx.$config$.logImageRequests && logWorker(`Image() request: ${resolveUrl(env, src, "image")}`, env.$winId$);
|
769 | this.s = src;
|
770 | fetch(resolveUrl(env, src, "image"), {
|
771 | mode: "no-cors",
|
772 | credentials: "include",
|
773 | keepalive: true
|
774 | }).then((rsp => {
|
775 | rsp.ok || 0 === rsp.status ? this.l.map((cb => cb({
|
776 | type: "load"
|
777 | }))) : this.e.map((cb => cb({
|
778 | type: "error"
|
779 | })));
|
780 | }), (() => this.e.forEach((cb => cb({
|
781 | type: "error"
|
782 | })))));
|
783 | }
|
784 | addEventListener(eventName, cb) {
|
785 | "load" === eventName && this.l.push(cb);
|
786 | "error" === eventName && this.e.push(cb);
|
787 | }
|
788 | removeEventListener(eventName, cb) {
|
789 | "load" === eventName && (this.l = this.l.filter((fn => fn !== cb)));
|
790 | "error" === eventName && (this.e = this.e.filter((fn => fn !== cb)));
|
791 | }
|
792 | get onload() {
|
793 | return this.l[0];
|
794 | }
|
795 | set onload(cb) {
|
796 | this.l = [ cb ];
|
797 | }
|
798 | get onerror() {
|
799 | return this.e[0];
|
800 | }
|
801 | set onerror(cb) {
|
802 | this.e = [ cb ];
|
803 | }
|
804 | };
|
805 | const HTMLSrcElementDescriptorMap = {
|
806 | addEventListener: {
|
807 | value(...args) {
|
808 | const eventName = args[0];
|
809 | const callbacks = getInstanceStateValue(this, eventName) || [];
|
810 | callbacks.push(args[1]);
|
811 | setInstanceStateValue(this, eventName, callbacks);
|
812 | }
|
813 | },
|
814 | async: {
|
815 | get: noop,
|
816 | set: noop
|
817 | },
|
818 | defer: {
|
819 | get: noop,
|
820 | set: noop
|
821 | },
|
822 | onload: {
|
823 | get() {
|
824 | let callbacks = getInstanceStateValue(this, "load");
|
825 | return callbacks && callbacks[0] || null;
|
826 | },
|
827 | set(cb) {
|
828 | setInstanceStateValue(this, "load", cb ? [ cb ] : null);
|
829 | }
|
830 | },
|
831 | onerror: {
|
832 | get() {
|
833 | let callbacks = getInstanceStateValue(this, "error");
|
834 | return callbacks && callbacks[0] || null;
|
835 | },
|
836 | set(cb) {
|
837 | setInstanceStateValue(this, "error", cb ? [ cb ] : null);
|
838 | }
|
839 | },
|
840 | getAttribute: {
|
841 | value(attrName) {
|
842 | return "src" === attrName ? this.src : callMethod(this, [ "getAttribute" ], [ attrName ]);
|
843 | }
|
844 | },
|
845 | setAttribute: {
|
846 | value(attrName, attrValue) {
|
847 | scriptAttrPropNames.includes(attrName) ? this[attrName] = attrValue : callMethod(this, [ "setAttribute" ], [ attrName, attrValue ]);
|
848 | }
|
849 | }
|
850 | };
|
851 | const scriptAttrPropNames = commaSplit("src,type");
|
852 | const patchHTMLScriptElement = (WorkerHTMLScriptElement, env) => {
|
853 | const HTMLScriptDescriptorMap = {
|
854 | innerHTML: innerHTMLDescriptor,
|
855 | innerText: innerHTMLDescriptor,
|
856 | src: {
|
857 | get() {
|
858 | return getInstanceStateValue(this, 4) || "";
|
859 | },
|
860 | set(url) {
|
861 | const orgUrl = resolveUrl(env, url, null);
|
862 | const config = webWorkerCtx.$config$;
|
863 | url = resolveUrl(env, url, "script");
|
864 | setInstanceStateValue(this, 4, url);
|
865 | setter(this, [ "src" ], url);
|
866 | orgUrl !== url && setter(this, [ "dataset", "ptsrc" ], orgUrl);
|
867 | if (this.type) {
|
868 | const shouldExecuteScriptViaMainThread = testIfMustLoadScriptOnMainThread(config, url);
|
869 | shouldExecuteScriptViaMainThread && setter(this, [ "type" ], "text/javascript");
|
870 | }
|
871 | }
|
872 | },
|
873 | text: innerHTMLDescriptor,
|
874 | textContent: innerHTMLDescriptor,
|
875 | type: {
|
876 | get() {
|
877 | return getter(this, [ "type" ]);
|
878 | },
|
879 | set(type) {
|
880 | if (!isScriptJsType(type)) {
|
881 | setInstanceStateValue(this, 5, type);
|
882 | setter(this, [ "type" ], type);
|
883 | }
|
884 | }
|
885 | },
|
886 | ...HTMLSrcElementDescriptorMap
|
887 | };
|
888 | definePrototypePropertyDescriptor(WorkerHTMLScriptElement, HTMLScriptDescriptorMap);
|
889 | };
|
890 | const innerHTMLDescriptor = {
|
891 | get() {
|
892 | const type = getter(this, [ "type" ]);
|
893 | if (isScriptJsType(type)) {
|
894 | const scriptContent = getInstanceStateValue(this, 3);
|
895 | if (scriptContent) {
|
896 | return scriptContent;
|
897 | }
|
898 | }
|
899 | return getter(this, [ "innerHTML" ]) || "";
|
900 | },
|
901 | set(scriptContent) {
|
902 | setInstanceStateValue(this, 3, scriptContent);
|
903 | }
|
904 | };
|
905 | const isScriptJsType = scriptType => !scriptType || "text/javascript" === scriptType;
|
906 | const createNodeCstr = (win, env, WorkerBase) => {
|
907 | const config = webWorkerCtx.$config$;
|
908 | const WorkerNode = defineConstructorName(class extends WorkerBase {
|
909 | appendChild(node) {
|
910 | return this.insertBefore(node, null);
|
911 | }
|
912 | get href() {}
|
913 | set href(_) {}
|
914 | insertBefore(newNode, referenceNode) {
|
915 | const winId = newNode[WinIdKey] = this[WinIdKey];
|
916 | const instanceId = newNode[InstanceIdKey];
|
917 | const nodeName = newNode[InstanceDataKey];
|
918 | const isScript = "SCRIPT" === nodeName;
|
919 | const isIFrame = "IFRAME" === nodeName;
|
920 | if (isScript) {
|
921 | const scriptContent = getInstanceStateValue(newNode, 3);
|
922 | const scriptType = getInstanceStateValue(newNode, 5);
|
923 | if (scriptContent) {
|
924 | if (isScriptJsType(scriptType)) {
|
925 | const scriptId = newNode.id;
|
926 | const loadOnMainThread = scriptId && testIfMustLoadScriptOnMainThread(config, scriptId);
|
927 | if (loadOnMainThread) {
|
928 | setter(newNode, [ "type" ], "text/javascript");
|
929 | } else {
|
930 | const errorMsg = runScriptContent(env, instanceId, scriptContent, winId, "");
|
931 | const datasetType = errorMsg ? "pterror" : "ptid";
|
932 | const datasetValue = errorMsg || instanceId;
|
933 | setter(newNode, [ "type" ], "text/partytown-x");
|
934 | setter(newNode, [ "dataset", datasetType ], datasetValue);
|
935 | }
|
936 | }
|
937 | setter(newNode, [ "innerHTML" ], scriptContent);
|
938 | }
|
939 | }
|
940 | callMethod(this, [ "insertBefore" ], [ newNode, referenceNode ], 2);
|
941 | if (isIFrame) {
|
942 | const src = getInstanceStateValue(newNode, 0);
|
943 | if (src && src.startsWith("javascript:")) {
|
944 | const scriptContent = src.split("javascript:")[1];
|
945 | runScriptContent(env, instanceId, scriptContent, winId, "");
|
946 | }
|
947 | ((winId, iframe) => {
|
948 | let i = 0;
|
949 | let type;
|
950 | let handlers;
|
951 | let callback = () => {
|
952 | if (environments[winId] && environments[winId].$isInitialized$ && !environments[winId].$isLoading$) {
|
953 | type = getInstanceStateValue(iframe, 1) ? "error" : "load";
|
954 | handlers = getInstanceStateValue(iframe, type);
|
955 | handlers && handlers.map((handler => handler({
|
956 | type: type
|
957 | })));
|
958 | } else if (i++ > 2e3) {
|
959 | handlers = getInstanceStateValue(iframe, "error");
|
960 | handlers && handlers.map((handler => handler({
|
961 | type: "error"
|
962 | })));
|
963 | } else {
|
964 | setTimeout(callback, 9);
|
965 | }
|
966 | };
|
967 | callback();
|
968 | })(instanceId, newNode);
|
969 | }
|
970 | if (isScript) {
|
971 | sendToMain(true);
|
972 | webWorkerCtx.$postMessage$([ 7, winId ]);
|
973 | }
|
974 | return newNode;
|
975 | }
|
976 | get nodeName() {
|
977 | return "#s" === this[InstanceDataKey] ? "#document-fragment" : this[InstanceDataKey];
|
978 | }
|
979 | get nodeType() {
|
980 | return 3;
|
981 | }
|
982 | get ownerDocument() {
|
983 | return env.$document$;
|
984 | }
|
985 | }, "Node");
|
986 | cachedTreeProps(WorkerNode, commaSplit("childNodes,firstChild,isConnected,lastChild,nextSibling,parentElement,parentNode,previousSibling"));
|
987 | win.Node = WorkerNode;
|
988 | };
|
989 | const htmlMedia = commaSplit("AUDIO,CANVAS,VIDEO");
|
990 | const windowMediaConstructors = commaSplit("Audio,MediaSource");
|
991 | const patchDocument = (WorkerDocument, env, isDocumentImplementation) => {
|
992 | const DocumentDescriptorMap = {
|
993 | body: {
|
994 | get: () => env.$body$
|
995 | },
|
996 | cookie: {
|
997 | get() {
|
998 | if (env.$isSameOrigin$) {
|
999 | return getter(this, [ "cookie" ]);
|
1000 | }
|
1001 | warnCrossOrigin("get", "cookie", env);
|
1002 | return "";
|
1003 | },
|
1004 | set(value) {
|
1005 | if (env.$isSameOrigin$) {
|
1006 | setter(this, [ "cookie" ], value);
|
1007 | } else {
|
1008 | warnCrossOrigin("set", "cookie", env);
|
1009 | }
|
1010 | }
|
1011 | },
|
1012 | createElement: {
|
1013 | value(tagName) {
|
1014 | tagName = tagName.toUpperCase();
|
1015 | if (!IS_TAG_REG.test(tagName)) {
|
1016 | throw tagName + " not valid";
|
1017 | }
|
1018 | const isIframe = "IFRAME" === tagName;
|
1019 | const winId = this[WinIdKey];
|
1020 | const instanceId = (isIframe ? "f_" : "") + randomId();
|
1021 | callMethod(this, [ "createElement" ], [ tagName ], 2, instanceId);
|
1022 | const elm = getOrCreateNodeInstance(winId, instanceId, tagName);
|
1023 | if (isIframe) {
|
1024 | const env = createEnvironment({
|
1025 | $winId$: instanceId,
|
1026 | $parentWinId$: winId,
|
1027 | $url$: "about:blank"
|
1028 | }, true);
|
1029 | env.$window$.fetch = fetch;
|
1030 | setter(elm, [ "srcdoc" ], getPartytownScript());
|
1031 | } else if ("SCRIPT" === tagName) {
|
1032 | const scriptType = getInstanceStateValue(elm, 5);
|
1033 | isScriptJsType(scriptType) && setter(elm, [ "type" ], "text/partytown");
|
1034 | }
|
1035 | return elm;
|
1036 | }
|
1037 | },
|
1038 | createElementNS: {
|
1039 | value(namespace, tagName) {
|
1040 | const instanceId = randomId();
|
1041 | const nsElm = getOrCreateNodeInstance(this[WinIdKey], instanceId, tagName, namespace);
|
1042 | callMethod(this, [ "createElementNS" ], [ namespace, tagName ], 2, instanceId);
|
1043 | return nsElm;
|
1044 | }
|
1045 | },
|
1046 | createTextNode: {
|
1047 | value(text) {
|
1048 | const winId = this[WinIdKey];
|
1049 | const instanceId = randomId();
|
1050 | const textNode = getOrCreateNodeInstance(winId, instanceId, "#text");
|
1051 | callMethod(this, [ "createTextNode" ], [ text ], 2, instanceId);
|
1052 | return textNode;
|
1053 | }
|
1054 | },
|
1055 | createEvent: {
|
1056 | value: type => new Event(type)
|
1057 | },
|
1058 | currentScript: {
|
1059 | get() {
|
1060 | return env.$currentScriptId$ ? getOrCreateNodeInstance(this[WinIdKey], env.$currentScriptId$, "SCRIPT") : null;
|
1061 | }
|
1062 | },
|
1063 | defaultView: {
|
1064 | get: () => isDocumentImplementation ? null : env.$window$
|
1065 | },
|
1066 | documentElement: {
|
1067 | get: () => env.$documentElement$
|
1068 | },
|
1069 | getElementsByTagName: {
|
1070 | value(tagName) {
|
1071 | tagName = tagName.toUpperCase();
|
1072 | return "BODY" === tagName ? [ env.$body$ ] : "HEAD" === tagName ? [ env.$head$ ] : callMethod(this, [ "getElementsByTagName" ], [ tagName ]);
|
1073 | }
|
1074 | },
|
1075 | head: {
|
1076 | get: () => env.$head$
|
1077 | },
|
1078 | images: {
|
1079 | get() {
|
1080 | return getter(this, [ "images" ]);
|
1081 | }
|
1082 | },
|
1083 | scripts: {
|
1084 | get() {
|
1085 | return getter(this, [ "scripts" ]);
|
1086 | }
|
1087 | },
|
1088 | implementation: {
|
1089 | get() {
|
1090 | return {
|
1091 | hasFeature: () => true,
|
1092 | createHTMLDocument: title => {
|
1093 | const $winId$ = randomId();
|
1094 | callMethod(this, [ "implementation", "createHTMLDocument" ], [ title ], 1, {
|
1095 | $winId$: $winId$
|
1096 | });
|
1097 | const docEnv = createEnvironment({
|
1098 | $winId$: $winId$,
|
1099 | $parentWinId$: $winId$,
|
1100 | $url$: env.$location$ + "",
|
1101 | $visibilityState$: "hidden"
|
1102 | }, true, true);
|
1103 | return docEnv.$document$;
|
1104 | }
|
1105 | };
|
1106 | }
|
1107 | },
|
1108 | location: {
|
1109 | get: () => env.$location$,
|
1110 | set(url) {
|
1111 | env.$location$.href = url + "";
|
1112 | }
|
1113 | },
|
1114 | nodeType: {
|
1115 | value: 9
|
1116 | },
|
1117 | parentNode: {
|
1118 | value: null
|
1119 | },
|
1120 | parentElement: {
|
1121 | value: null
|
1122 | },
|
1123 | readyState: {
|
1124 | value: "complete"
|
1125 | },
|
1126 | visibilityState: {
|
1127 | get: () => env.$visibilityState$ || "visible"
|
1128 | }
|
1129 | };
|
1130 | definePrototypePropertyDescriptor(WorkerDocument, DocumentDescriptorMap);
|
1131 | cachedProps(WorkerDocument, "compatMode,referrer,forms");
|
1132 | };
|
1133 | const patchDocumentElementChild = (WokerDocumentElementChild, env) => {
|
1134 | const DocumentElementChildDescriptorMap = {
|
1135 | parentElement: {
|
1136 | get() {
|
1137 | return this.parentNode;
|
1138 | }
|
1139 | },
|
1140 | parentNode: {
|
1141 | get: () => env.$documentElement$
|
1142 | }
|
1143 | };
|
1144 | definePrototypePropertyDescriptor(WokerDocumentElementChild, DocumentElementChildDescriptorMap);
|
1145 | };
|
1146 | const patchElement = (WorkerElement, WorkerHTMLElement) => {
|
1147 | const ElementDescriptorMap = {
|
1148 | localName: {
|
1149 | get() {
|
1150 | return this[InstanceDataKey].toLowerCase();
|
1151 | }
|
1152 | },
|
1153 | namespaceURI: {
|
1154 | get() {
|
1155 | return this[NamespaceKey] || "http://www.w3.org/1999/xhtml";
|
1156 | }
|
1157 | },
|
1158 | nodeType: {
|
1159 | value: 1
|
1160 | },
|
1161 | tagName: {
|
1162 | get() {
|
1163 | return this[InstanceDataKey];
|
1164 | }
|
1165 | }
|
1166 | };
|
1167 | definePrototypePropertyDescriptor(WorkerElement, ElementDescriptorMap);
|
1168 | cachedTreeProps(WorkerElement, elementStructurePropNames);
|
1169 | cachedProps(WorkerElement, "id");
|
1170 | cachedDimensionProps(WorkerHTMLElement);
|
1171 | cachedDimensionMethods(WorkerHTMLElement, commaSplit("getClientRects,getBoundingClientRect"));
|
1172 | };
|
1173 | const patchHTMLAnchorElement = (WorkerHTMLAnchorElement, env) => {
|
1174 | const HTMLAnchorDescriptorMap = {};
|
1175 | commaSplit("hash,host,hostname,href,origin,pathname,port,protocol,search").map((anchorProp => {
|
1176 | HTMLAnchorDescriptorMap[anchorProp] = {
|
1177 | get() {
|
1178 | let value = getInstanceStateValue(this, 4);
|
1179 | let href;
|
1180 | if ("string" != typeof value) {
|
1181 | href = getter(this, [ "href" ]);
|
1182 | if ("" === href) {
|
1183 | return "protocol" === anchorProp ? ":" : "";
|
1184 | }
|
1185 | setInstanceStateValue(this, 4, href);
|
1186 | value = new URL(href)[anchorProp];
|
1187 | }
|
1188 | return resolveToUrl(env, value, null)[anchorProp];
|
1189 | },
|
1190 | set(value) {
|
1191 | let url;
|
1192 | if ("href" === anchorProp) {
|
1193 | if ((url => {
|
1194 | try {
|
1195 | new URL(url);
|
1196 | return true;
|
1197 | } catch (_) {
|
1198 | return false;
|
1199 | }
|
1200 | })(value)) {
|
1201 | url = new URL(value);
|
1202 | } else {
|
1203 | const baseHref = env.$location$.href;
|
1204 | url = resolveToUrl(env, baseHref, null);
|
1205 | url.href = new URL(value + "", url.href);
|
1206 | }
|
1207 | } else {
|
1208 | url = resolveToUrl(env, this.href, null);
|
1209 | url[anchorProp] = value;
|
1210 | }
|
1211 | setInstanceStateValue(this, 4, url.href);
|
1212 | setter(this, [ "href" ], url.href);
|
1213 | }
|
1214 | };
|
1215 | }));
|
1216 | definePrototypePropertyDescriptor(WorkerHTMLAnchorElement, HTMLAnchorDescriptorMap);
|
1217 | };
|
1218 | const patchHTMLIFrameElement = (WorkerHTMLIFrameElement, env) => {
|
1219 | const HTMLIFrameDescriptorMap = {
|
1220 | contentDocument: {
|
1221 | get() {
|
1222 | return getIframeEnv(this).$document$;
|
1223 | }
|
1224 | },
|
1225 | contentWindow: {
|
1226 | get() {
|
1227 | return getIframeEnv(this).$window$;
|
1228 | }
|
1229 | },
|
1230 | src: {
|
1231 | get() {
|
1232 | let src = getInstanceStateValue(this, 0);
|
1233 | if (src && src.startsWith("javascript:")) {
|
1234 | return src;
|
1235 | }
|
1236 | src = getIframeEnv(this).$location$.href;
|
1237 | return src.startsWith("about:") ? "" : src;
|
1238 | },
|
1239 | set(src) {
|
1240 | if (src) {
|
1241 | if (src.startsWith("javascript:")) {
|
1242 | setInstanceStateValue(this, 0, src);
|
1243 | } else if (!src.startsWith("about:")) {
|
1244 | let xhr = new XMLHttpRequest;
|
1245 | let xhrStatus;
|
1246 | let env = getIframeEnv(this);
|
1247 | env.$location$.href = src = resolveUrl(env, src, "iframe");
|
1248 | env.$isLoading$ = 1;
|
1249 | setInstanceStateValue(this, 1, void 0);
|
1250 | xhr.open("GET", src, false);
|
1251 | xhr.send();
|
1252 | xhrStatus = xhr.status;
|
1253 | if (xhrStatus > 199 && xhrStatus < 300) {
|
1254 | setter(this, [ "srcdoc" ], `<base href="${src}">` + function(text) {
|
1255 | return text.replace(SCRIPT_TAG_REGEXP, ((_, attrs) => {
|
1256 | const parts = [];
|
1257 | let hasType = false;
|
1258 | let match;
|
1259 | while (match = ATTR_REGEXP.exec(attrs)) {
|
1260 | let [keyValue] = match;
|
1261 | if (keyValue.startsWith("type=")) {
|
1262 | hasType = true;
|
1263 | keyValue = keyValue.replace(/(application|text)\/javascript/, SCRIPT_TYPE);
|
1264 | }
|
1265 | parts.push(keyValue);
|
1266 | }
|
1267 | hasType || parts.push('type="text/partytown"');
|
1268 | return `<script ${parts.join(" ")}>`;
|
1269 | }));
|
1270 | }(xhr.responseText) + getPartytownScript());
|
1271 | sendToMain(true);
|
1272 | webWorkerCtx.$postMessage$([ 7, env.$winId$ ]);
|
1273 | } else {
|
1274 | setInstanceStateValue(this, 1, xhrStatus);
|
1275 | env.$isLoading$ = 0;
|
1276 | }
|
1277 | }
|
1278 | }
|
1279 | }
|
1280 | },
|
1281 | ...HTMLSrcElementDescriptorMap
|
1282 | };
|
1283 | definePrototypePropertyDescriptor(WorkerHTMLIFrameElement, HTMLIFrameDescriptorMap);
|
1284 | };
|
1285 | const ATTR_REGEXP_STR = "((?:\\w|-)+(?:=(?:(?:\\w|-)+|'[^']*'|\"[^\"]*\")?)?)";
|
1286 | const SCRIPT_TAG_REGEXP = new RegExp(`<script\\s*((${ATTR_REGEXP_STR}\\s*)*)>`, "mg");
|
1287 | const ATTR_REGEXP = new RegExp(ATTR_REGEXP_STR, "mg");
|
1288 | const getIframeEnv = iframe => {
|
1289 | const $winId$ = iframe[InstanceIdKey];
|
1290 | environments[$winId$] || createEnvironment({
|
1291 | $winId$: $winId$,
|
1292 | $parentWinId$: iframe[WinIdKey],
|
1293 | $url$: getter(iframe, [ "src" ]) || "about:blank"
|
1294 | }, true);
|
1295 | return environments[$winId$];
|
1296 | };
|
1297 | const patchSvgElement = WorkerSVGGraphicsElement => {
|
1298 | const getMatrix = (elm, methodName) => {
|
1299 | const {a: a, b: b, c: c, d: d, e: e, f: f} = callMethod(elm, [ methodName ], EMPTY_ARRAY);
|
1300 | return new DOMMatrixReadOnly([ a, b, c, d, e, f ]);
|
1301 | };
|
1302 | const SVGGraphicsElementDescriptorMap = {
|
1303 | ...WorkerSVGGraphicsElement,
|
1304 | getCTM: {
|
1305 | value: function() {
|
1306 | return getMatrix(this, "getCTM");
|
1307 | }
|
1308 | },
|
1309 | getScreenCTM: {
|
1310 | value: function() {
|
1311 | return getMatrix(this, "getScreenCTM");
|
1312 | }
|
1313 | }
|
1314 | };
|
1315 | definePrototypePropertyDescriptor(WorkerSVGGraphicsElement, SVGGraphicsElementDescriptorMap);
|
1316 | };
|
1317 | const createNamedNodeMapCstr = (win, WorkerBase) => {
|
1318 | win.NamedNodeMap = defineConstructorName(class NamedNodeMap extends WorkerBase {
|
1319 | constructor(winId, instanceId, applyPath) {
|
1320 | super(winId, instanceId, applyPath);
|
1321 | return new Proxy(this, {
|
1322 | get(target, propName) {
|
1323 | const handler = NAMED_NODE_MAP_HANDLERS[propName];
|
1324 | return handler ? handler.bind(target, [ propName ]) : getter(target, [ propName ]);
|
1325 | },
|
1326 | set(target, propName, propValue) {
|
1327 | const handler = NAMED_NODE_MAP_HANDLERS[propName];
|
1328 | if (handler) {
|
1329 | throw new Error("Can't set read-only property: " + String(propName));
|
1330 | }
|
1331 | setter(target, [ propName ], propValue);
|
1332 | return true;
|
1333 | }
|
1334 | });
|
1335 | }
|
1336 | }, "NamedNodeMap");
|
1337 | };
|
1338 | function method(applyPath, ...args) {
|
1339 | return callMethod(this, applyPath, args, 1);
|
1340 | }
|
1341 | const NAMED_NODE_MAP_HANDLERS = {
|
1342 | getNamedItem: method,
|
1343 | getNamedItemNS: method,
|
1344 | item: method,
|
1345 | removeNamedItem: method,
|
1346 | removeNamedItemNS: method,
|
1347 | setNamedItem: method,
|
1348 | setNamedItemNS: method
|
1349 | };
|
1350 | const createWindow = ($winId$, $parentWinId$, url, $visibilityState$, isIframeWindow, isDocumentImplementation) => {
|
1351 | let cstrInstanceId;
|
1352 | let cstrNodeName;
|
1353 | let cstrNamespace;
|
1354 | let cstrPrevInstance;
|
1355 | const WorkerBase = class {
|
1356 | constructor(winId, instanceId, applyPath, instanceData, namespace) {
|
1357 | this[WinIdKey] = winId || $winId$;
|
1358 | this[InstanceIdKey] = instanceId || cstrInstanceId || randomId();
|
1359 | this[ApplyPathKey] = applyPath || [];
|
1360 | this[InstanceDataKey] = instanceData || cstrNodeName;
|
1361 | this[NamespaceKey] = namespace || cstrNamespace;
|
1362 | this[InstanceStateKey] = cstrPrevInstance && cstrPrevInstance[InstanceStateKey] || {};
|
1363 | cstrInstanceId = cstrNodeName = cstrNamespace = void 0;
|
1364 | }
|
1365 | };
|
1366 | const WorkerLocation = defineConstructorName(class extends URL {
|
1367 | assign() {
|
1368 | logWorker("location.assign(), noop");
|
1369 | }
|
1370 | reload() {
|
1371 | logWorker("location.reload(), noop");
|
1372 | }
|
1373 | replace() {
|
1374 | logWorker("location.replace(), noop");
|
1375 | }
|
1376 | }, "Location");
|
1377 | const $location$ = new WorkerLocation(url);
|
1378 | const $isSameOrigin$ = $location$.origin === webWorkerCtx.$origin$ || "about:blank" === $location$.origin;
|
1379 | const $isTopWindow$ = $parentWinId$ === $winId$;
|
1380 | const env = {};
|
1381 | const getChildEnvs = () => {
|
1382 | let childEnv = [];
|
1383 | let envWinId;
|
1384 | let otherEnv;
|
1385 | for (envWinId in environments) {
|
1386 | otherEnv = environments[envWinId];
|
1387 | otherEnv.$parentWinId$ !== $winId$ || otherEnv.$isTopWindow$ || childEnv.push(otherEnv);
|
1388 | }
|
1389 | return childEnv;
|
1390 | };
|
1391 | const WorkerWindow = defineConstructorName(class extends WorkerBase {
|
1392 | constructor() {
|
1393 | super($winId$, $winId$);
|
1394 | this.addEventListener = (...args) => {
|
1395 | "load" === args[0] ? env.$runWindowLoadEvent$ && setTimeout((() => args[1]({
|
1396 | type: "load"
|
1397 | }))) : callMethod(this, [ "addEventListener" ], args, 2);
|
1398 | };
|
1399 | let win = this;
|
1400 | let value;
|
1401 | let historyState;
|
1402 | let hasInitializedMedia = 0;
|
1403 | let initWindowMedia = () => {
|
1404 | if (!hasInitializedMedia) {
|
1405 | (() => {
|
1406 | if (!webWorkerCtx.$initWindowMedia$) {
|
1407 | self.$bridgeToMedia$ = [ getter, setter, callMethod, constructGlobal, definePrototypePropertyDescriptor, randomId, WinIdKey, InstanceIdKey, ApplyPathKey ];
|
1408 | webWorkerCtx.$importScripts$(partytownLibUrl("partytown-media.js?v=0.10.1"));
|
1409 | webWorkerCtx.$initWindowMedia$ = self.$bridgeFromMedia$;
|
1410 | delete self.$bridgeFromMedia$;
|
1411 | }
|
1412 | return webWorkerCtx.$initWindowMedia$;
|
1413 | })()(WorkerBase, WorkerEventTargetProxy, env, win, windowMediaConstructors);
|
1414 | hasInitializedMedia = 1;
|
1415 | }
|
1416 | };
|
1417 | let nodeCstrs = {};
|
1418 | let $createNode$ = (nodeName, instanceId, namespace, prevInstance) => {
|
1419 | htmlMedia.includes(nodeName) && initWindowMedia();
|
1420 | const NodeCstr = nodeCstrs[nodeName] ? nodeCstrs[nodeName] : nodeName.includes("-") ? nodeCstrs.UNKNOWN : nodeCstrs.I;
|
1421 | cstrInstanceId = instanceId;
|
1422 | cstrNodeName = nodeName;
|
1423 | cstrNamespace = namespace;
|
1424 | cstrPrevInstance = prevInstance;
|
1425 | return new NodeCstr;
|
1426 | };
|
1427 | win.Window = WorkerWindow;
|
1428 | win.name = name + `${normalizedWinId($winId$)} (${$winId$})`;
|
1429 | createNodeCstr(win, env, WorkerBase);
|
1430 | (win => {
|
1431 | win.NodeList = defineConstructorName(NodeList, "NodeList");
|
1432 | })(win);
|
1433 | createNamedNodeMapCstr(win, WorkerBase);
|
1434 | createCSSStyleDeclarationCstr(win, WorkerBase, "CSSStyleDeclaration");
|
1435 | ((win, WorkerBase, cstrName) => {
|
1436 | win[cstrName] = defineConstructorName(class extends WorkerBase {
|
1437 | now() {
|
1438 | return performance.now();
|
1439 | }
|
1440 | }, cstrName);
|
1441 | })(win, WorkerBase, "Performance");
|
1442 | ((win, nodeCstrs) => {
|
1443 | const registry = new Map;
|
1444 | win.customElements = {
|
1445 | define(tagName, Cstr, opts) {
|
1446 | registry.set(tagName, Cstr);
|
1447 | nodeCstrs[tagName.toUpperCase()] = Cstr;
|
1448 | const ceData = [ Cstr.name, Cstr.observedAttributes ];
|
1449 | callMethod(win, [ "customElements", "define" ], [ tagName, ceData, opts ]);
|
1450 | },
|
1451 | get: tagName => registry.get(tagName) || callMethod(win, [ "customElements", "get" ], [ tagName ]),
|
1452 | whenDefined: tagName => registry.has(tagName) ? Promise.resolve() : callMethod(win, [ "customElements", "whenDefined" ], [ tagName ]),
|
1453 | upgrade: elm => callMethod(win, [ "customElements", "upgrade" ], [ elm ])
|
1454 | };
|
1455 | })(win, nodeCstrs);
|
1456 | webWorkerCtx.$interfaces$.map((([cstrName, superCstrName, members, interfaceType, nodeName]) => {
|
1457 | const SuperCstr = TrapConstructors[cstrName] ? WorkerTrapProxy : "EventTarget" === superCstrName ? WorkerEventTargetProxy : "Object" === superCstrName ? WorkerBase : win[superCstrName];
|
1458 | const Cstr = win[cstrName] = defineConstructorName(12 === interfaceType ? class extends WorkerBase {
|
1459 | constructor(...args) {
|
1460 | super();
|
1461 | constructGlobal(this, cstrName, args);
|
1462 | }
|
1463 | } : win[cstrName] || class extends SuperCstr {}, cstrName);
|
1464 | nodeName && (nodeCstrs[nodeName] = Cstr);
|
1465 | members.map((([memberName, memberType, staticValue]) => {
|
1466 | memberName in Cstr.prototype || memberName in SuperCstr.prototype || ("string" == typeof memberType ? definePrototypeProperty(Cstr, memberName, {
|
1467 | get() {
|
1468 | if (!hasInstanceStateValue(this, memberName)) {
|
1469 | const instanceId = this[InstanceIdKey];
|
1470 | const applyPath = [ ...this[ApplyPathKey], memberName ];
|
1471 | const PropCstr = win[memberType];
|
1472 | PropCstr && setInstanceStateValue(this, memberName, new PropCstr($winId$, instanceId, applyPath));
|
1473 | }
|
1474 | return getInstanceStateValue(this, memberName);
|
1475 | },
|
1476 | set(value) {
|
1477 | setInstanceStateValue(this, memberName, value);
|
1478 | }
|
1479 | }) : 5 === memberType ? definePrototypeValue(Cstr, memberName, (function(...args) {
|
1480 | return callMethod(this, [ memberName ], args);
|
1481 | })) : memberType > 0 && (void 0 !== staticValue ? definePrototypeValue(Cstr, memberName, staticValue) : definePrototypeProperty(Cstr, memberName, {
|
1482 | get() {
|
1483 | return getter(this, [ memberName ]);
|
1484 | },
|
1485 | set(value) {
|
1486 | return setter(this, [ memberName ], value);
|
1487 | }
|
1488 | })));
|
1489 | }));
|
1490 | }));
|
1491 | commaSplit("atob,btoa,crypto,indexedDB,setTimeout,setInterval,clearTimeout,clearInterval").map((globalName => {
|
1492 | delete WorkerWindow.prototype[globalName];
|
1493 | if (!(globalName in win)) {
|
1494 | value = self[globalName];
|
1495 | null != value && (win[globalName] = "function" != typeof value || value.toString().startsWith("class") ? value : value.bind(self));
|
1496 | }
|
1497 | }));
|
1498 | Object.getOwnPropertyNames(self).map((globalName => {
|
1499 | globalName in win || (win[globalName] = self[globalName]);
|
1500 | }));
|
1501 | windowMediaConstructors.map((cstrName => defineProperty(win, cstrName, {
|
1502 | get() {
|
1503 | initWindowMedia();
|
1504 | return win[cstrName];
|
1505 | }
|
1506 | })));
|
1507 | "trustedTypes" in self && (win.trustedTypes = self.trustedTypes);
|
1508 | patchElement(win.Element, win.HTMLElement);
|
1509 | patchDocument(win.Document, env, isDocumentImplementation);
|
1510 | (WorkerDocumentFragment => {
|
1511 | definePrototypeNodeType(WorkerDocumentFragment, 11);
|
1512 | cachedTreeProps(WorkerDocumentFragment, elementStructurePropNames);
|
1513 | })(win.DocumentFragment);
|
1514 | patchHTMLAnchorElement(win.HTMLAnchorElement, env);
|
1515 | (WorkerHTMLFormElement => {
|
1516 | definePrototypePropertyDescriptor(WorkerHTMLFormElement, {});
|
1517 | cachedProps(WorkerHTMLFormElement, "elements");
|
1518 | })(win.HTMLFormElement);
|
1519 | patchHTMLIFrameElement(win.HTMLIFrameElement);
|
1520 | patchHTMLScriptElement(win.HTMLScriptElement, env);
|
1521 | patchSvgElement(win.SVGGraphicsElement);
|
1522 | patchDocumentElementChild(win.HTMLHeadElement, env);
|
1523 | patchDocumentElementChild(win.HTMLBodyElement, env);
|
1524 | ((WorkerHTMLHtmlElement, env) => {
|
1525 | const DocumentElementDescriptorMap = {
|
1526 | parentElement: {
|
1527 | value: null
|
1528 | },
|
1529 | parentNode: {
|
1530 | get: () => env.$document$
|
1531 | }
|
1532 | };
|
1533 | definePrototypePropertyDescriptor(WorkerHTMLHtmlElement, DocumentElementDescriptorMap);
|
1534 | })(win.HTMLHtmlElement, env);
|
1535 | createCSSStyleSheetConstructor(win, "CSSStyleSheet");
|
1536 | definePrototypeNodeType(win.Comment, 8);
|
1537 | definePrototypeNodeType(win.DocumentType, 10);
|
1538 | Object.assign(env, {
|
1539 | $winId$: $winId$,
|
1540 | $parentWinId$: $parentWinId$,
|
1541 | $window$: new Proxy(win, {
|
1542 | get: (win, propName) => {
|
1543 | var _a;
|
1544 | if ("string" != typeof propName || isNaN(propName)) {
|
1545 | return (null === (_a = webWorkerCtx.$config$.mainWindowAccessors) || void 0 === _a ? void 0 : _a.includes(propName)) ? getter(this, [ propName ]) : win[propName];
|
1546 | }
|
1547 | {
|
1548 | let frame = getChildEnvs()[propName];
|
1549 | return frame ? frame.$window$ : void 0;
|
1550 | }
|
1551 | },
|
1552 | has: () => true
|
1553 | }),
|
1554 | $document$: $createNode$("#document", $winId$ + ".d"),
|
1555 | $documentElement$: $createNode$("HTML", $winId$ + ".e"),
|
1556 | $head$: $createNode$("HEAD", $winId$ + ".h"),
|
1557 | $body$: $createNode$("BODY", $winId$ + ".b"),
|
1558 | $location$: $location$,
|
1559 | $visibilityState$: $visibilityState$,
|
1560 | $isSameOrigin$: $isSameOrigin$,
|
1561 | $isTopWindow$: $isTopWindow$,
|
1562 | $createNode$: $createNode$
|
1563 | });
|
1564 | win.requestAnimationFrame = cb => setTimeout((() => cb(performance.now())), 9);
|
1565 | win.cancelAnimationFrame = id => clearTimeout(id);
|
1566 | win.requestIdleCallback = (cb, start) => {
|
1567 | start = Date.now();
|
1568 | return setTimeout((() => cb({
|
1569 | didTimeout: false,
|
1570 | timeRemaining: () => Math.max(0, 50 - (Date.now() - start))
|
1571 | })), 1);
|
1572 | };
|
1573 | win.cancelIdleCallback = id => clearTimeout(id);
|
1574 | addStorageApi(win, "localStorage", $isSameOrigin$, env);
|
1575 | addStorageApi(win, "sessionStorage", $isSameOrigin$, env);
|
1576 | $isSameOrigin$ || (win.indexeddb = void 0);
|
1577 | if (isIframeWindow) {
|
1578 | historyState = {};
|
1579 | win.history = {
|
1580 | pushState(stateObj) {
|
1581 | historyState = stateObj;
|
1582 | },
|
1583 | replaceState(stateObj) {
|
1584 | historyState = stateObj;
|
1585 | },
|
1586 | get state() {
|
1587 | return historyState;
|
1588 | },
|
1589 | length: 0
|
1590 | };
|
1591 | win.indexeddb = void 0;
|
1592 | } else {
|
1593 | const originalPushState = win.history.pushState.bind(win.history);
|
1594 | const originalReplaceState = win.history.replaceState.bind(win.history);
|
1595 | win.history.pushState = (stateObj, _, newUrl) => {
|
1596 | false !== env.$propagateHistoryChange$ && originalPushState(stateObj, _, newUrl);
|
1597 | };
|
1598 | win.history.replaceState = (stateObj, _, newUrl) => {
|
1599 | false !== env.$propagateHistoryChange$ && originalReplaceState(stateObj, _, newUrl);
|
1600 | };
|
1601 | }
|
1602 | win.Worker = void 0;
|
1603 | }
|
1604 | get body() {
|
1605 | return env.$body$;
|
1606 | }
|
1607 | get document() {
|
1608 | return env.$document$;
|
1609 | }
|
1610 | get documentElement() {
|
1611 | return env.$documentElement$;
|
1612 | }
|
1613 | fetch(input, init) {
|
1614 | input = "string" == typeof input || input instanceof URL ? String(input) : input.url;
|
1615 | return fetch(resolveUrl(env, input, "fetch"), init);
|
1616 | }
|
1617 | get frames() {
|
1618 | return env.$window$;
|
1619 | }
|
1620 | get frameElement() {
|
1621 | return $isTopWindow$ ? null : getOrCreateNodeInstance($parentWinId$, $winId$, "IFRAME");
|
1622 | }
|
1623 | get globalThis() {
|
1624 | return env.$window$;
|
1625 | }
|
1626 | get head() {
|
1627 | return env.$head$;
|
1628 | }
|
1629 | get length() {
|
1630 | return getChildEnvs().length;
|
1631 | }
|
1632 | get location() {
|
1633 | return $location$;
|
1634 | }
|
1635 | set location(loc) {
|
1636 | $location$.href = loc + "";
|
1637 | }
|
1638 | get Image() {
|
1639 | return createImageConstructor(env);
|
1640 | }
|
1641 | get navigator() {
|
1642 | return (env => {
|
1643 | const nav = {
|
1644 | sendBeacon: (url, body) => {
|
1645 | if (webWorkerCtx.$config$.logSendBeaconRequests) {
|
1646 | try {
|
1647 | logWorker(`sendBeacon: ${resolveUrl(env, url, null)}${body ? ", data: " + JSON.stringify(body) : ""}, resolvedParams: ${JSON.stringify(resolveSendBeaconRequestParameters(env, url))}`);
|
1648 | } catch (e) {
|
1649 | console.error(e);
|
1650 | }
|
1651 | }
|
1652 | try {
|
1653 | fetch(resolveUrl(env, url, null), {
|
1654 | method: "POST",
|
1655 | body: body,
|
1656 | mode: "no-cors",
|
1657 | keepalive: true,
|
1658 | ...resolveSendBeaconRequestParameters(env, url)
|
1659 | });
|
1660 | return true;
|
1661 | } catch (e) {
|
1662 | console.error(e);
|
1663 | return false;
|
1664 | }
|
1665 | }
|
1666 | };
|
1667 | for (let key in navigator) {
|
1668 | nav[key] = navigator[key];
|
1669 | }
|
1670 | return new Proxy(nav, {
|
1671 | set(_, propName, propValue) {
|
1672 | navigator[propName] = propValue;
|
1673 | return true;
|
1674 | },
|
1675 | get(target, prop) {
|
1676 | if (Object.prototype.hasOwnProperty.call(target, prop)) {
|
1677 | return target[prop];
|
1678 | }
|
1679 | const value = getter(env.$window$, [ "navigator", prop ]);
|
1680 | return value;
|
1681 | }
|
1682 | });
|
1683 | })(env);
|
1684 | }
|
1685 | get origin() {
|
1686 | return $location$.origin;
|
1687 | }
|
1688 | set origin(_) {}
|
1689 | get parent() {
|
1690 | for (let envWinId in environments) {
|
1691 | if (environments[envWinId].$winId$ === $parentWinId$) {
|
1692 | return environments[envWinId].$window$;
|
1693 | }
|
1694 | }
|
1695 | return env.$window$;
|
1696 | }
|
1697 | postMessage(...args) {
|
1698 | if (environments[args[0]]) {
|
1699 | len(postMessages) > 50 && postMessages.splice(0, 5);
|
1700 | postMessages.push({
|
1701 | $winId$: args[0],
|
1702 | $data$: JSON.stringify(args[1])
|
1703 | });
|
1704 | args = args.slice(1);
|
1705 | }
|
1706 | callMethod(this, [ "postMessage" ], args, 3);
|
1707 | }
|
1708 | get self() {
|
1709 | return env.$window$;
|
1710 | }
|
1711 | get top() {
|
1712 | for (let envWinId in environments) {
|
1713 | if (environments[envWinId].$isTopWindow$) {
|
1714 | return environments[envWinId].$window$;
|
1715 | }
|
1716 | }
|
1717 | return env.$window$;
|
1718 | }
|
1719 | get window() {
|
1720 | return env.$window$;
|
1721 | }
|
1722 | get XMLHttpRequest() {
|
1723 | const Xhr = XMLHttpRequest;
|
1724 | const str = String(Xhr);
|
1725 | const ExtendedXhr = defineConstructorName(class extends Xhr {
|
1726 | open(...args) {
|
1727 | args[1] = resolveUrl(env, args[1], "xhr");
|
1728 | super.open(...args);
|
1729 | }
|
1730 | set withCredentials(_) {
|
1731 | webWorkerCtx.$config$.allowXhrCredentials && (super.withCredentials = _);
|
1732 | }
|
1733 | toString() {
|
1734 | return str;
|
1735 | }
|
1736 | }, getConstructorName(Xhr));
|
1737 | ExtendedXhr.prototype.constructor.toString = () => str;
|
1738 | return ExtendedXhr;
|
1739 | }
|
1740 | }, "Window");
|
1741 | const WorkerTrapProxy = class extends WorkerBase {
|
1742 | constructor(winId, instanceId, applyPath, nodeName) {
|
1743 | super(winId, instanceId, applyPath, nodeName);
|
1744 | return new Proxy(this, {
|
1745 | get: (instance, propName) => getter(instance, [ propName ]),
|
1746 | set(instance, propName, propValue) {
|
1747 | setter(instance, [ propName ], propValue);
|
1748 | return true;
|
1749 | }
|
1750 | });
|
1751 | }
|
1752 | };
|
1753 | const WorkerEventTargetProxy = class extends WorkerBase {};
|
1754 | eventTargetMethods.map((methodName => WorkerEventTargetProxy.prototype[methodName] = function(...args) {
|
1755 | return callMethod(this, [ methodName ], args, 2);
|
1756 | }));
|
1757 | cachedProps(WorkerWindow, "devicePixelRatio");
|
1758 | cachedDimensionProps(WorkerWindow);
|
1759 | cachedDimensionMethods(WorkerWindow, [ "getComputedStyle" ]);
|
1760 | new WorkerWindow;
|
1761 | return env;
|
1762 | };
|
1763 | const TrapConstructors = {
|
1764 | DOMStringMap: 1,
|
1765 | NamedNodeMap: 1
|
1766 | };
|
1767 | const createEnvironment = ({$winId$: $winId$, $parentWinId$: $parentWinId$, $url$: $url$, $visibilityState$: $visibilityState$}, isIframeWindow, isDocumentImplementation) => {
|
1768 | if (!environments[$winId$]) {
|
1769 | environments[$winId$] = createWindow($winId$, $parentWinId$, $url$, $visibilityState$, isIframeWindow, isDocumentImplementation);
|
1770 | {
|
1771 | const winType = $winId$ === $parentWinId$ ? "top" : "iframe";
|
1772 | logWorker(`Created ${winType} window ${normalizedWinId($winId$)} environment`, $winId$);
|
1773 | }
|
1774 | }
|
1775 | webWorkerCtx.$postMessage$([ 7, $winId$ ]);
|
1776 | return environments[$winId$];
|
1777 | };
|
1778 | const queuedEvents = [];
|
1779 | const receiveMessageFromSandboxToWorker = ev => {
|
1780 | const msg = ev.data;
|
1781 | const msgType = msg[0];
|
1782 | const msgValue = msg[1];
|
1783 | if (webWorkerCtx.$isInitialized$) {
|
1784 | if (7 === msgType) {
|
1785 | (async initScript => {
|
1786 | let winId = initScript.$winId$;
|
1787 | let instanceId = initScript.$instanceId$;
|
1788 | let instance = getOrCreateNodeInstance(winId, instanceId, "SCRIPT");
|
1789 | let scriptContent = initScript.$content$;
|
1790 | let scriptSrc = initScript.$url$;
|
1791 | let scriptOrgSrc = initScript.$orgUrl$;
|
1792 | let errorMsg = "";
|
1793 | let env = environments[winId];
|
1794 | let rsp;
|
1795 | let javascriptContentTypes = [ "text/jscript", "text/javascript", "text/x-javascript", "application/javascript", "application/x-javascript", "text/ecmascript", "text/x-ecmascript", "application/ecmascript" ];
|
1796 | if (scriptSrc) {
|
1797 | try {
|
1798 | scriptSrc = resolveToUrl(env, scriptSrc, "script") + "";
|
1799 | setInstanceStateValue(instance, 4, scriptSrc);
|
1800 | webWorkerCtx.$config$.logScriptExecution && logWorker(`Execute script src: ${scriptOrgSrc}`, winId);
|
1801 | rsp = await fetch(scriptSrc);
|
1802 | if (rsp.ok) {
|
1803 | let responseContentType = rsp.headers.get("content-type");
|
1804 | let shouldExecute = javascriptContentTypes.some((ct => {
|
1805 | var _a, _b, _c;
|
1806 | 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);
|
1807 | }));
|
1808 | if (shouldExecute) {
|
1809 | scriptContent = await rsp.text();
|
1810 | env.$currentScriptId$ = instanceId;
|
1811 | run(env, scriptContent, scriptOrgSrc || scriptSrc);
|
1812 | }
|
1813 | runStateLoadHandlers(instance, "load");
|
1814 | } else {
|
1815 | errorMsg = rsp.statusText;
|
1816 | runStateLoadHandlers(instance, "error");
|
1817 | }
|
1818 | } catch (urlError) {
|
1819 | console.error(urlError);
|
1820 | errorMsg = String(urlError.stack || urlError);
|
1821 | runStateLoadHandlers(instance, "error");
|
1822 | }
|
1823 | } else {
|
1824 | scriptContent && (errorMsg = runScriptContent(env, instanceId, scriptContent, winId, errorMsg));
|
1825 | }
|
1826 | env.$currentScriptId$ = "";
|
1827 | webWorkerCtx.$postMessage$([ 6, winId, instanceId, errorMsg ]);
|
1828 | })(msgValue);
|
1829 | } else if (9 === msgType) {
|
1830 | (({$winId$: $winId$, $instanceId$: $instanceId$, $refId$: $refId$, $thisArg$: $thisArg$, $args$: $args$}) => {
|
1831 | if (webWorkerRefsByRefId[$refId$]) {
|
1832 | try {
|
1833 | webWorkerRefsByRefId[$refId$].apply(deserializeFromMain($winId$, $instanceId$, [], $thisArg$), deserializeFromMain($winId$, $instanceId$, [], $args$));
|
1834 | } catch (e) {
|
1835 | console.error(e);
|
1836 | }
|
1837 | }
|
1838 | })(msgValue);
|
1839 | } else if (10 === msgType) {
|
1840 | (({$winId$: $winId$, $forward$: $forward$, $args$: $args$}) => {
|
1841 | try {
|
1842 | let target = environments[$winId$].$window$;
|
1843 | let i = 0;
|
1844 | let l = len($forward$);
|
1845 | for (;i < l; i++) {
|
1846 | i + 1 < l ? target = target[$forward$[i]] : target[$forward$[i]].apply(target, deserializeFromMain(null, $winId$, [], $args$));
|
1847 | }
|
1848 | } catch (e) {
|
1849 | console.error(e);
|
1850 | }
|
1851 | })(msgValue);
|
1852 | } else if (5 === msgType) {
|
1853 | createEnvironment(msgValue);
|
1854 | } else if (8 === msgType) {
|
1855 | if (1 !== environments[msgValue].$isInitialized$) {
|
1856 | const winId = msgValue;
|
1857 | const env = environments[winId];
|
1858 | const winType = env.$winId$ === env.$parentWinId$ ? "top" : "iframe";
|
1859 | logWorker(`Initialized ${winType} window ${normalizedWinId(winId)} environment 🎉`, winId);
|
1860 | }
|
1861 | environments[msgValue].$isInitialized$ = 1;
|
1862 | environments[msgValue].$isLoading$ = 0;
|
1863 | } else if (14 === msgType) {
|
1864 | environments[msgValue].$visibilityState$ = msg[2];
|
1865 | } else if (13 === msgType) {
|
1866 | const $winId$ = msgValue.$winId$;
|
1867 | const env = environments[$winId$];
|
1868 | env.$location$.href = msgValue.url;
|
1869 | !function($winId$, env, data) {
|
1870 | const history = env.$window$.history;
|
1871 | switch (data.type) {
|
1872 | case 0:
|
1873 | env.$propagateHistoryChange$ = false;
|
1874 | try {
|
1875 | history.pushState(data.state, "", data.newUrl);
|
1876 | } catch (e) {}
|
1877 | env.$propagateHistoryChange$ = true;
|
1878 | break;
|
1879 |
|
1880 | case 1:
|
1881 | env.$propagateHistoryChange$ = false;
|
1882 | try {
|
1883 | history.replaceState(data.state, "", data.newUrl);
|
1884 | } catch (e) {}
|
1885 | env.$propagateHistoryChange$ = true;
|
1886 | }
|
1887 | }(msgValue.$winId$, env, msgValue);
|
1888 | } else {
|
1889 | 15 === msgType && ((_type, winId, instanceId, callbackName, args) => {
|
1890 | const elm = getOrCreateNodeInstance(winId, instanceId);
|
1891 | elm && "function" == typeof elm[callbackName] && elm[callbackName].apply(elm, args);
|
1892 | })(...msg);
|
1893 | }
|
1894 | } else if (1 === msgType) {
|
1895 | (initWebWorkerData => {
|
1896 | const config = webWorkerCtx.$config$ = JSON.parse(initWebWorkerData.$config$);
|
1897 | const locOrigin = initWebWorkerData.$origin$;
|
1898 | webWorkerCtx.$importScripts$ = importScripts.bind(self);
|
1899 | webWorkerCtx.$interfaces$ = initWebWorkerData.$interfaces$;
|
1900 | webWorkerCtx.$libPath$ = initWebWorkerData.$libPath$;
|
1901 | webWorkerCtx.$origin$ = locOrigin;
|
1902 | webWorkerCtx.$postMessage$ = postMessage.bind(self);
|
1903 | webWorkerCtx.$sharedDataBuffer$ = initWebWorkerData.$sharedDataBuffer$;
|
1904 | webWorkerCtx.$tabId$ = initWebWorkerData.$tabId$;
|
1905 | self.importScripts = void 0;
|
1906 | delete self.postMessage;
|
1907 | delete self.WorkerGlobalScope;
|
1908 | commaSplit("resolveUrl,resolveSendBeaconRequestParameters,get,set,apply").map((configName => {
|
1909 | config[configName] && (config[configName] = new Function("return " + config[configName])());
|
1910 | }));
|
1911 | })(msgValue);
|
1912 | webWorkerCtx.$postMessage$([ 2 ]);
|
1913 | } else if (3 === msgType) {
|
1914 | webWorkerCtx.$interfaces$ = [ ...webWorkerCtx.$interfaces$, ...msgValue ];
|
1915 | webWorkerCtx.$isInitialized$ = 1;
|
1916 | logWorker("Initialized web worker");
|
1917 | webWorkerCtx.$postMessage$([ 4 ]);
|
1918 | queuedEvents.length && logWorker(`Queued ready messages: ${queuedEvents.length}`);
|
1919 | [ ...queuedEvents ].map(receiveMessageFromSandboxToWorker);
|
1920 | queuedEvents.length = 0;
|
1921 | } else {
|
1922 | queuedEvents.push(ev);
|
1923 | }
|
1924 | };
|
1925 | self.onmessage = receiveMessageFromSandboxToWorker;
|
1926 | postMessage([ 0 ]);
|
1927 | })(self);
|