thebe-core
Version:
Typescript based core functionality for Thebe
57 lines • 2.58 kB
JavaScript
/**
* Inspired by https://github.com/jupyterlab/jupyterlab-plugin-playground/blob/main/src/requirejs.ts
*/
import { __awaiter } from "tslib";
const REQUIREJS_CDN_URL = 'https://cdn.jsdelivr.net/npm/';
const REQUIREJS_URL = 'https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js';
function fetchAndLoadInFrame(baseUrl) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof document === 'undefined')
throw new Error('Cannot load requirejs outside of the browser');
const res = yield fetch(REQUIREJS_URL);
if (!res.ok) {
throw new Error(`Could not fetch requirejs ${res.status} ${res.statusText}`);
}
const requireJsSource = yield res.text();
return new Promise((resolve, reject) => {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.onload = () => {
const contentWindow = iframe.contentWindow;
if (!contentWindow)
return reject('Cannot load in isolated: no contentWindow, origin error?');
contentWindow.window.eval(requireJsSource);
const requirejs = {
require: contentWindow.window.require,
define: contentWindow.window.define,
};
if (!requirejs.require || !requirejs.define)
return reject('Require.js loading did not result in `require` and `define` objects attachment to window');
requirejs.require.config({ baseUrl });
resolve(requirejs);
iframe.onload = null;
};
document.body.appendChild(iframe);
});
});
}
export class RequireJsLoader {
constructor(baseUrl) {
this.baseUrl = baseUrl !== null && baseUrl !== void 0 ? baseUrl : REQUIREJS_CDN_URL;
this.requested = false;
this.resolveFn = () => ({});
this.ready = new Promise((resolve) => (this.resolveFn = resolve));
}
load(postLoadFn) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.requested) {
this.requested = true;
this.requirejs = yield fetchAndLoadInFrame(this.baseUrl);
yield (postLoadFn === null || postLoadFn === void 0 ? void 0 : postLoadFn(this.requirejs.require, this.requirejs.define));
this.resolveFn(this.requirejs);
}
return this.ready;
});
}
}
//# sourceMappingURL=requireJsLoader.js.map