/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */
const FLAG_USE_REQUIRE_JS=1,FLAG_USE_IMPORTMAP=2,FLAG_USE_TOP_WINDOW=16,deniedProperties=["__proto__","prototype","constructor"],allowedJavaScriptItemTypes=["assign","invoke","instance"];let useShim=!1;const moduleImporter=e=>useShim?window.importShim(e):import(e).catch((()=>(useShim=!0,moduleImporter(e))));export function loadModule(e){if(!e.name)throw new Error("JavaScript module name is required");if(2==(2&e.flags)){if(16&e.flags){const t=new CustomEvent("typo3:import-javascript-module",{detail:{specifier:e.name,importPromise:null}});return top.document.dispatchEvent(t),t.detail.importPromise||Promise.reject(new Error("Top-level import failed"))}return moduleImporter(e.name)}if(1==(1&e.flags))return new Promise(((t,r)=>{(16==(16&e.flags)?top.window:window).require([e.name],(e=>t(e)),(e=>r(e)))}));throw new Error("Unknown JavaScript module type")}export function resolveSubjectRef(e,t){const r=t.exportName;return"string"==typeof r?e[r]:1==(1&t.flags)?e:e.default}export function executeJavaScriptModuleInstruction(e){if(!e.name)throw new Error("JavaScript module name is required");if(!e.items)return loadModule(e);const t=e.items.filter((e=>allowedJavaScriptItemTypes.includes(e.type))).map((t=>"assign"===t.type?r=>{mergeRecursive(resolveSubjectRef(r,e),t.assignments)}:"invoke"===t.type?r=>{const o=resolveSubjectRef(r,e);return"method"in t&&t.method?o[t.method].apply(o,t.args):o(...t.args)}:"instance"===t.type?r=>{const o=[null].concat(t.args),n=resolveSubjectRef(r,e);return new(n.bind.apply(n,o))}:e=>{}));return loadModule(e).then((e=>t.map((t=>t.call(null,e)))))}function isObjectInstance(e){return e instanceof Object&&!(e instanceof Array)}function mergeRecursive(e,t){Object.keys(t).forEach((r=>{if(-1!==deniedProperties.indexOf(r))throw new Error("Property "+r+" is not allowed");isObjectInstance(t[r])&&void 0!==e[r]?mergeRecursive(e[r],t[r]):Object.assign(e,{[r]:t[r]})}))}export class JavaScriptItemProcessor{constructor(){this.invokableNames=["globalAssignment","javaScriptModuleInstruction"]}processItems(e){e.forEach((e=>this.invoke(e.type,e.payload)))}invoke(e,t){if(!this.invokableNames.includes(e)||"function"!=typeof this[e])throw new Error('Unknown handler name "'+e+'"');this[e].call(this,t)}globalAssignment(e){mergeRecursive(window,e)}javaScriptModuleInstruction(e){executeJavaScriptModuleInstruction(e)}}