"use strict";
(self["webpackChunkggblab"] = self["webpackChunkggblab"] || []).push([["lib_index_js"],{

/***/ "./lib/comm/kernel_comm.js"
/*!*********************************!*\
  !*** ./lib/comm/kernel_comm.js ***!
  \*********************************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   initKernelCommHelpers: () => (/* binding */ initKernelCommHelpers)
/* harmony export */ });
// Kernel communication helpers used by the webview to send messages to the kernel.
function initKernelCommHelpers(resources, dbg) {
    // Default: enable fire-and-forget for kernel2 unless explicitly disabled.
    if (resources && typeof resources.kernel2FireAndForget === 'undefined') {
        resources.kernel2FireAndForget = true;
    }
    let sendChain = Promise.resolve();
    // (kernel-only mode) browser WebSocket fallback removed: sending is via kernel2
    // batching for action messages (add/remove/rename/clear and object_update)
    let actionBatchBuffer = [];
    let actionBatchTimer = null;
    const batchInterval = resources && resources.batchInterval ? resources.batchInterval : 30;
    const log = dbg || (() => { });
    async function performSend(msgToSend) {
        const wsUrl = resources && resources.wsUrl ? resources.wsUrl : undefined;
        const socketPath = resources && resources.socketPath ? resources.socketPath : undefined;
        if (resources && resources.kernel2 && typeof resources.kernel2.requestExecute === 'function') {
            try {
                try {
                    log && log('performSend: using kernel2.requestExecute', { kernel2: !!resources.kernel2, socketPath: socketPath || undefined, wsUrlPreview: wsUrl || undefined });
                }
                catch (e) {
                    // eslint-disable-next-line no-empty
                }
                let code;
                if (socketPath) {
                    code = `\nwith unix_connect(${JSON.stringify(socketPath)}) as ws:\n\tws.send(r"""${msgToSend}""")\n`;
                }
                else if (wsUrl) {
                    code = `\nwith connect(${JSON.stringify(wsUrl)}) as ws:\n\tws.send(r"""${msgToSend}""")\n`;
                }
                else {
                    // Neither socketPath nor wsUrl configured — fail fast rather than guessing
                    throw new Error('No socketPath or wsUrl configured in resources for performSend');
                }
                const exec = resources.kernel2.requestExecute({ code });
                // fire-and-forget mode avoids awaiting exec.done
                if (resources.kernel2FireAndForget) {
                    exec.done &&
                        exec.done.catch((err) => {
                            log('kernel2 async exec failed', err);
                        });
                }
                else {
                    await exec.done;
                }
            }
            catch (e) {
                log('performSend kernel2.requestExecute failed', e);
                throw e;
            }
        }
        else {
            log('performSend: kernel2.requestExecute not available');
            throw new Error('kernel2.requestExecute not available');
        }
        // small inter-send gap to avoid jamming
        await new Promise(resolve => setTimeout(resolve, 30));
    }
    const enqueueSend = (msgStr) => {
        const next = sendChain.then(() => performSend(msgStr));
        sendChain = next.catch(e => {
            log('callRemoteSocketSend chain error', e);
        });
        return next;
    };
    const flushActionBatch = () => {
        if (!actionBatchBuffer.length) {
            return;
        }
        const toSend = actionBatchBuffer.slice();
        actionBatchBuffer = [];
        if (actionBatchTimer) {
            clearTimeout(actionBatchTimer);
            actionBatchTimer = null;
        }
        const batchMsg = JSON.stringify({ type: 'bulk_actions', payload: toSend });
        enqueueSend(batchMsg).catch(() => { });
    };
    const scheduleActionBatchFlush = () => {
        if (actionBatchTimer) {
            return;
        }
        actionBatchTimer = setTimeout(() => {
            try {
                flushActionBatch();
            }
            catch (e) {
                log('flushActionBatch failed', e);
            }
        }, batchInterval);
    };
    async function callRemoteSocketSend(message) {
        var _a;
        try {
            // Debug: trace incoming messages to help diagnose why sends may be missing
            try {
                log && log('callRemoteSocketSend received', message);
            }
            catch (e) {
                // eslint-disable-next-line no-empty
            }
            try {
                const parsed = JSON.parse(message);
                // Treat object_update the same as UI action messages (add/remove/rename/clear)
                // and batch them into `bulk_actions` for kernel-side processing.
                if (parsed && (parsed.type === 'add' || parsed.type === 'remove' || parsed.type === 'rename' || parsed.type === 'clear' || parsed.type === 'object_update')) {
                    try {
                        const entry = { type: parsed.type, payload: parsed.payload, ts: (_a = parsed.ts) !== null && _a !== void 0 ? _a : Date.now() };
                        actionBatchBuffer.push(entry);
                        try {
                            log && log('Queued bulk action entry', entry, { actionBatchBufferLength: actionBatchBuffer.length });
                        }
                        catch (e) {
                            // eslint-disable-next-line no-empty
                        }
                        // For object_update we prefer immediate delivery rather than waiting
                        // for the action batch timer to fire, to reduce perceived latency.
                        if (parsed.type === 'object_update') {
                            try {
                                flushActionBatch();
                            }
                            catch (e) {
                                log('Immediate flushActionBatch failed', e);
                            }
                        }
                        else {
                            scheduleActionBatchFlush();
                        }
                        return;
                    }
                    catch (e) {
                        log('Batch queue failed', e);
                    }
                }
            }
            catch (e) {
                /* not JSON or other message */
            }
            await enqueueSend(message);
        }
        catch (err) {
            console.error('callRemoteSocketSend: error sending message', err);
            throw err;
        }
    }
    function attachCommCloseHandler(opts) {
        const { c, setClosed, commTarget, dbg: _dbg } = opts;
        try {
            c.onClose = (m) => {
                try {
                    setClosed(true);
                    const closedId = (m && m.content && m.content.comm_id) || (c === null || c === void 0 ? void 0 : c.comm_id) || (c === null || c === void 0 ? void 0 : c.commId) || null;
                    _dbg && _dbg('Kernel comm closed', { target: commTarget, commId: closedId, message: m });
                }
                catch (e) {
                    _dbg && _dbg('Kernel comm closed (no id available)', commTarget, m);
                }
            };
        }
        catch (e) {
            _dbg && _dbg('Unable to attach onClose to kernel comm', e);
        }
    }
    async function ensureKernelComm(opts) {
        var _a, _b, _c;
        const { kernelConn: kconn, commTarget: ct, handleIncomingCommMessage: h, attachCloseHandler: ach, dbg: _dbg } = opts;
        try {
            if (!kconn) {
                throw new Error('No kernelConn available to create comm');
            }
            resources.comm = kconn.createComm(ct);
            try {
                const maybeId = ((_a = resources.comm) === null || _a === void 0 ? void 0 : _a.comm_id) || ((_b = resources.comm) === null || _b === void 0 ? void 0 : _b.commId) || ((_c = resources.comm) === null || _c === void 0 ? void 0 : _c.id) || null;
                _dbg && _dbg('Recreated kernel comm', { target: ct, commObject: resources.comm, commId: maybeId });
            }
            catch (err) {
                _dbg && _dbg('Recreated kernel comm (unable to read id)', ct, resources.comm);
            }
            try {
                resources.comm.onMsg = h;
            }
            catch (err) {
                _dbg && _dbg('Failed to attach onMsg to recreated comm', err);
            }
            try {
                ach && ach(resources.comm);
            }
            catch (err) {
                _dbg && _dbg('Failed to attach close handler to recreated comm', err);
            }
            try {
                resources.comm.open && resources.comm.open('REOPEN from GGB').done;
            }
            catch (err) {
                _dbg && _dbg('Failed to open recreated comm', err);
            }
            return resources.comm;
        }
        catch (e) {
            _dbg && _dbg('ensureKernelComm failed', e);
            return null;
        }
    }
    function makeIncomingHandler(processCommandMessage) {
        let commClosed = false;
        const attachCommCloseHandlerLocal = (c) => attachCommCloseHandler({
            c,
            setClosed: (v) => {
                commClosed = v;
            },
            commTarget: resources.commTarget,
            dbg
        });
        return async function handler(msg) {
            var _a, _b;
            const _dbg = dbg || (() => { });
            _dbg('handleIncomingCommMessage:', msg);
            try {
                _dbg('Kernel comm onMsg received', { commTarget: resources.commTarget || '', msg });
                const command = JSON.parse(msg.content.data);
                _dbg('Parsed command:', command.type, command.payload);
                let rmsg = null;
                try {
                    rmsg = await processCommandMessage(command);
                }
                catch (e) {
                    _dbg('Error processing command', e);
                    rmsg = JSON.stringify({ type: 'error', id: (command === null || command === void 0 ? void 0 : command.id) || null, payload: { message: 'Processing failed' } });
                }
                try {
                    const cId = ((_a = resources.comm) === null || _a === void 0 ? void 0 : _a.comm_id) || ((_b = resources.comm) === null || _b === void 0 ? void 0 : _b.commId) || null;
                    _dbg('Sending via kernel comm', { commTarget: resources.commTarget, commId: cId, preview: (rmsg || '').slice(0, 200) });
                    if (!resources.comm || commClosed) {
                        try {
                            const created = await ensureKernelComm({
                                kernelConn: resources.kernelConn,
                                commTarget: resources.commTarget,
                                handleIncomingCommMessage: handler,
                                attachCloseHandler: attachCommCloseHandlerLocal,
                                dbg: _dbg
                            });
                            if (created) {
                                resources.comm = created;
                                commClosed = false;
                            }
                        }
                        catch (e) {
                            _dbg('ensureKernelComm failed before sending reply', e);
                        }
                    }
                    if (resources.comm) {
                        try {
                            resources.comm.send(rmsg);
                        }
                        catch (e) {
                            _dbg('Failed to send via kernel comm, will still attempt remote socket send', e, { rmsgPreview: (rmsg || '').slice(0, 200) });
                        }
                    }
                    else {
                        _dbg('No kernel comm available to send reply; will mirror via remote socket');
                    }
                }
                catch (e) {
                    _dbg('Failed to send via kernel comm, will still attempt remote socket send', e, { rmsgPreview: (rmsg || '').slice(0, 200) });
                }
                await callRemoteSocketSend(rmsg);
            }
            catch (e) {
                (dbg || (() => { }))('Error in handleIncomingCommMessage', e);
            }
        };
    }
    return { callRemoteSocketSend, ensureKernelComm, attachCommCloseHandler, makeIncomingHandler };
}


/***/ },

/***/ "./lib/components/jupyterlab.js"
/*!**************************************!*\
  !*** ./lib/components/jupyterlab.js ***!
  \**************************************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   isArrayOfArrays: () => (/* reexport safe */ _shared_geoGebraCommon__WEBPACK_IMPORTED_MODULE_3__.isArrayOfArrays),
/* harmony export */   setupKernelResources: () => (/* binding */ setupKernelResources)
/* harmony export */ });
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/services */ "webpack/sharing/consume/default/@jupyterlab/services");
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/coreutils */ "webpack/sharing/consume/default/@jupyterlab/coreutils");
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _comm__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../comm */ "./lib/comm/kernel_comm.js");
/* harmony import */ var _shared_geoGebraCommon__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../shared/geoGebraCommon */ "./lib/shared/geoGebraCommon.js");




// Note: import jupyter REST helpers dynamically where needed to keep
// browser/webview bundles small and avoid unused-import build errors.
// Re-export shared utility

/**
 * Initialize JupyterLab-specific kernel resources.
 * - starts a helper kernel (kernel2)
 * - creates a KernelConnection for the target kernel id
 * - initializes kernel_comm helpers and returns the send/handler factories
 * - registers widget comm passthrough when appropriate
 */
async function setupKernelResources(resources, props, dbg) {
    let _result = null;
    // If requested via props or PageConfig option, clear browser storage on startup.
    // This helps remove stale widget manager state that can conflict after refactors.
    const shouldClearFromProps = !!(props && (props.clearBrowserStorageOnStartup === true || props.clearBrowserStorageOnStartup === 'true'));
    const shouldClearFromPageConfig = (() => {
        try {
            const v = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__.PageConfig.getOption && _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__.PageConfig.getOption('ggblab.clearBrowserStorageOnStartup');
            return v === 'true';
        }
        catch (e) {
            return false;
        }
    })();
    const shouldClearFromGlobal = (() => {
        try {
            return !!(window.__ggblab_clearBrowserStorageOnStartup === true || window.__ggblab_clearBrowserStorageOnStartup === 'true');
        }
        catch (e) {
            return false;
        }
    })();
    let shouldClear = shouldClearFromProps || shouldClearFromPageConfig || shouldClearFromGlobal;
    // If running inside a VS Code webview (props.serverSettings present),
    // do not clear browser storage by default. Allow callers to opt-in by
    // passing `clearBrowserStorageInWebview: true` in props.
    try {
        const runningInWebview = !!(props && props.serverSettings);
        const allowClearInWebview = !!(props && (props.clearBrowserStorageInWebview === true || props.clearBrowserStorageInWebview === 'true'));
        if (runningInWebview && !allowClearInWebview) {
            try {
                console.debug('ggblab: running in VS Code webview — skipping browser storage clear by default');
            }
            catch (e) {
                // eslint-disable-next-line no-empty
            }
            shouldClear = false;
        }
    }
    catch (e) {
        /* ignore */
    }
    try {
        console.debug('ggblab: clearBrowserStorage flags', { shouldClearFromProps, shouldClearFromPageConfig, shouldClearFromGlobal, shouldClear });
    }
    catch (e) {
        // eslint-disable-next-line no-empty
    }
    async function clearBrowserStorage() {
        var _a;
        try {
            // Determine mode: selective (default) or full when explicitly requested
            const selective = !(props && props.clearBrowserStorageFull === true);
            const defaultPatterns = ['ggblab', 'widget', 'jupyterlab-workspace', 'jupyterlab', 'jupyter-widgets', '@jupyter-widgets'];
            const patterns = props && Array.isArray(props.clearBrowserStoragePatterns) && props.clearBrowserStoragePatterns.length ? props.clearBrowserStoragePatterns : defaultPatterns;
            const matches = (name) => {
                if (!name) {
                    return false;
                }
                try {
                    return patterns.some(p => name.toLowerCase().includes(String(p).toLowerCase()));
                }
                catch (e) {
                    return false;
                }
            };
            // localStorage: either clear all or only keys that match patterns
            const removedLocalKeys = [];
            try {
                if (!selective) {
                    try {
                        localStorage.clear();
                    }
                    catch (e) {
                        /* ignore */
                    }
                }
                else {
                    for (let i = localStorage.length - 1; i >= 0; i--) {
                        const k = localStorage.key(i);
                        if (k && matches(k)) {
                            try {
                                localStorage.removeItem(k);
                                removedLocalKeys.push(k);
                            }
                            catch (e) {
                                /* ignore */
                            }
                        }
                    }
                }
            }
            catch (e) {
                /* ignore */
            }
            // sessionStorage: selective removal
            const removedSessionKeys = [];
            try {
                if (!selective) {
                    try {
                        sessionStorage.clear();
                    }
                    catch (e) {
                        /* ignore */
                    }
                }
                else {
                    for (let i = sessionStorage.length - 1; i >= 0; i--) {
                        const k = sessionStorage.key(i);
                        if (k && matches(k)) {
                            try {
                                sessionStorage.removeItem(k);
                                removedSessionKeys.push(k);
                            }
                            catch (e) {
                                /* ignore */
                            }
                        }
                    }
                }
            }
            catch (e) {
                /* ignore */
            }
            // indexedDB: delete databases whose name matches patterns (where supported)
            const removedIndexedDB = [];
            try {
                if (indexedDB && typeof indexedDB.databases === 'function') {
                    const dbs = await indexedDB.databases();
                    for (const d of dbs) {
                        try {
                            const name = d && d.name ? d.name : null;
                            if (!name) {
                                continue;
                            }
                            if (!selective || matches(name)) {
                                try {
                                    indexedDB.deleteDatabase(name);
                                    removedIndexedDB.push(name);
                                }
                                catch (e) {
                                    /* ignore */
                                }
                            }
                        }
                        catch (e) {
                            /* ignore per-db */
                        }
                    }
                }
            }
            catch (e) {
                /* ignore */
            }
            // caches: delete caches whose key matches patterns
            const removedCaches = [];
            try {
                if (window.caches) {
                    const keys = await caches.keys();
                    for (const k of keys) {
                        try {
                            if (!selective || matches(k)) {
                                const ok = await caches.delete(k);
                                if (ok) {
                                    removedCaches.push(k);
                                }
                            }
                        }
                        catch (e) {
                            /* ignore per-cache */
                        }
                    }
                }
            }
            catch (e) {
                /* ignore */
            }
            // cookies: delete cookies whose name matches patterns (best-effort)
            const removedCookies = [];
            try {
                const cookies = document.cookie ? document.cookie.split(';') : [];
                for (const c of cookies) {
                    const name = (_a = c.split('=')[0]) === null || _a === void 0 ? void 0 : _a.trim();
                    if (!name) {
                        continue;
                    }
                    if (!selective || matches(name)) {
                        try {
                            document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
                            removedCookies.push(name);
                        }
                        catch (e) {
                            /* ignore */
                        }
                    }
                }
            }
            catch (e) {
                /* ignore */
            }
            try {
                console.info('ggblab: selective browser storage clear complete', {
                    removedLocalKeys,
                    removedSessionKeys,
                    removedIndexedDB,
                    removedCaches,
                    removedCookies
                });
            }
            catch (e) {
                /* ignore logging failure */
            }
        }
        catch (e) {
            try {
                console.warn('ggblab: clearBrowserStorage failed', e);
            }
            catch (ee) {
                // eslint-disable-next-line no-empty
            }
        }
    }
    if (shouldClear) {
        try {
            console.info('ggblab: clearBrowserStorageOnStartup active — clearing storages (selective mode default)');
        }
        catch (e) {
            // eslint-disable-next-line no-empty
        }
        clearBrowserStorage().catch(() => { });
    }
    // Determine server settings first. In a VS Code webview we expect
    // `props.serverSettings` to be provided; avoid calling JupyterLab APIs that
    // resolve against the current document origin (vscode-webview://...), which
    // results in 403/invalid requests. Use REST helper to list kernels when
    // explicit serverSettings are present.
    let kernels = [];
    let settings = null;
    if (props && props.serverSettings) {
        // Keep the raw settings for REST calls, but create a ServerConnection
        // settings object for @jupyterlab/services usage (it expects fields
        // like `cache` and other helpers produced by makeSettings).
        const restSettings = props.serverSettings;
        try {
            settings = _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.ServerConnection.makeSettings({
                baseUrl: restSettings.baseUrl || restSettings.base_url || '/',
                token: restSettings.token || '',
                appendToken: true
            });
        }
        catch (e) {
            dbg('Failed to create ServerConnection settings from props.serverSettings', e);
            settings = _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.ServerConnection.makeSettings({ baseUrl: restSettings.baseUrl || '/', appendToken: true });
        }
        dbg('Using serverSettings from props (webview mode)');
        // For security reasons, REST-based listing of kernels is disabled.
        // Avoid using `../shared/jupyterRest` and default to an empty list.
        dbg('Skipping REST-based kernel listing for webview/serverSettings (disabled)');
        kernels = [];
    }
    else {
        try {
            kernels = await _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelAPI.listRunning();
            dbg('Running kernels (via KernelAPI):', kernels);
            const baseUrl = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__.PageConfig.getBaseUrl();
            const token = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__.PageConfig.getToken();
            dbg(`Base URL: ${baseUrl}`);
            dbg(`Token: ${token}`);
            settings = _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.ServerConnection.makeSettings({
                baseUrl: baseUrl,
                token: token,
                appendToken: true
            });
        }
        catch (e) {
            dbg('KernelAPI.listRunning failed', e);
            kernels = [];
            const baseUrl = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__.PageConfig.getBaseUrl ? _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__.PageConfig.getBaseUrl() : '/';
            settings = _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.ServerConnection.makeSettings({ baseUrl, appendToken: true });
        }
    }
    resources.kernelManager = new _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelManager({ serverSettings: settings });
    resources.kernel2 = await resources.kernelManager.startNew({ name: 'python3' });
    dbg('Started new kernel:', resources.kernel2, resources.kernelId);
    try {
        await resources.kernel2.requestExecute({ code: 'from websockets.sync.client import unix_connect, connect' }).done;
        dbg('Imported unix_connect/connect in kernel2');
        // If a socketPath is available, perform a light probe to verify unix socket connectivity
        try {
            const probePath = resources.socketPath || (props && props.serverSettings && props.serverSettings.socketPath) || null;
            if (probePath) {
                const probeCode = `
try:
    with unix_connect("${probePath}") as ws:
        ws.send(r'''{"type":"probe","source":"kernel2"}''')
    print('ggblab:kernel2_probe:ok')
except Exception as _e:
    print('ggblab:kernel2_probe:error', repr(_e))
`;
                await resources.kernel2.requestExecute({ code: probeCode }).done;
                dbg('kernel2 unix_connect probe executed (sent probe)');
            }
            else {
                dbg('No socketPath available to probe from kernel2');
            }
        }
        catch (e) {
            dbg('kernel2 unix_connect probe failed', e);
        }
    }
    catch (e) {
        dbg('Failed to import unix_connect/connect in kernel2', e);
    }
    // Note: auxiliary kernel3 startup/registration removed — comm targets
    // are handled via the primary kernel or widget registration paths.
    // ws/socket values managed inside kernel_comm helpers
    // Initialize comm helpers from shared module
    const { callRemoteSocketSend, makeIncomingHandler } = (0,_comm__WEBPACK_IMPORTED_MODULE_2__.initKernelCommHelpers)(resources, dbg);
    dbg('Initialized kernel_comm helpers:', { callRemoteSocketSend, makeIncomingHandler });
    // Determine a target kernel id to connect to. `kernels` may be empty
    // (e.g., fresh server), and `resources.kernelId` may also be empty.
    // Prefer an explicit kernel id from props.serverSettings (or the
    // resources bag) if present. Otherwise fall back to the first running
    // kernel (if any).
    const explicitId = (props && props.serverSettings && props.serverSettings.kernelId) || resources.kernelId || null;
    const targetKernelId = explicitId || (Array.isArray(kernels) && kernels.length ? kernels[0] && (kernels[0].id || kernels[0]['kernel_id'] || kernels[0]['name']) : null);
    if (targetKernelId) {
        resources.kernelConn = new _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelConnection({
            model: { name: 'python3', id: targetKernelId },
            serverSettings: settings
        });
        dbg('Connected to kernel:', resources.kernelConn);
    }
    else {
        resources.kernelConn = null;
        dbg('No existing kernel id found to create KernelConnection; kernelConn set to null');
    }
    _result = { callRemoteSocketSend, makeIncomingHandler, kernelConn: resources.kernelConn, serverSettings: settings };
    // Widget comm passthrough registration is handled by the applet fallback
    // or by the optional widget-manager detection plugin. Keeping this module
    // focused on kernel/service initialization avoids duplicating registration
    // logic with `GeoGebraApplet.tsx`.
    return _result;
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (setupKernelResources);


/***/ },

/***/ "./lib/components/lumino.js"
/*!**********************************!*\
  !*** ./lib/components/lumino.js ***!
  \**********************************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   GeoGebraWidget: () => (/* binding */ GeoGebraWidget),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _widget__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./widget */ "./lib/components/widget.js");



/**
 * Lumino wrapper that renders the React `GeoGebraApplet` inside a widget.
 */
class GeoGebraWidget extends _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_0__.ReactWidget {
    constructor(props) {
        super();
        this.addClass('jp-ggblabWidget');
        this.props = props;
    }
    render() {
        var _a, _b, _c, _d, _e, _f;
        return (react__WEBPACK_IMPORTED_MODULE_1___default().createElement(_widget__WEBPACK_IMPORTED_MODULE_2__["default"], { kernelId: (_a = this.props) === null || _a === void 0 ? void 0 : _a.kernelId, commTarget: (_b = this.props) === null || _b === void 0 ? void 0 : _b.commTarget, wsPort: (_c = this.props) === null || _c === void 0 ? void 0 : _c.wsPort, socketPath: (_d = this.props) === null || _d === void 0 ? void 0 : _d.socketPath, appName: (_e = this.props) === null || _e === void 0 ? void 0 : _e.appName, widgetManager: (_f = this.props) === null || _f === void 0 ? void 0 : _f.widgetManager }));
    }
    onResize(msg) {
        // Let the React component handle resize via window resize events
        window.dispatchEvent(new Event('resize'));
        super.onResize(msg);
    }
    onCloseRequest(msg) {
        window.dispatchEvent(new Event('close'));
        super.onCloseRequest(msg);
    }
    dispose() {
        super.dispose();
    }
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (GeoGebraWidget);


/***/ },

/***/ "./lib/components/widget.js"
/*!**********************************!*\
  !*** ./lib/components/widget.js ***!
  \**********************************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./jupyterlab */ "./lib/components/jupyterlab.js");
/* harmony import */ var _widgets__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../widgets */ "./lib/widgets/widgetManager.js");
/* harmony import */ var _shared_createApplet__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../shared/createApplet */ "./lib/shared/createApplet.js");
/* harmony import */ var _shared_geoGebraCommon__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../shared/geoGebraCommon */ "./lib/shared/geoGebraCommon.js");
/* harmony import */ var _shared_appletOnLoadCommon__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../shared/appletOnLoadCommon */ "./lib/shared/appletOnLoadCommon.js");
// comm helper functions inlined from kernel_comm.ts to reduce indirection

//import MetaTags from 'react-meta-tags';





// Global typings are provided in src/declarations.d.ts; avoid duplicate declarations here.
// Debug logging helper controlled from the browser console.
// Enable message logging in the JS console by running:
//   window.ggblabDebugMessages = true
function dbg(...args) {
    if (window.ggblabDebugMessages) {
        // eslint-disable-next-line no-console
        console.log(...args);
    }
}
/**
 * React component for a GeoGebra.
 *
 * @returns The React component
 */
const GeoGebraApplet = (props) => {
    // const [kernels, setKernels] = React.useState<any[]>([]);
    const widgetRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);
    dbg('Component props: ', props.kernelId, props.commTarget, props.socketPath, props.wsPort);
    const elementId = 'ggb-element-' + ((props === null || props === void 0 ? void 0 : props.kernelId) || '').substring(0, 8);
    dbg('Element ID:', elementId);
    let applet = null;
    (0,react__WEBPACK_IMPORTED_MODULE_0__.useEffect)(() => {
        class Resources {
            constructor(kernelId, commTarget, socketPath, wsPort) {
                this.kernel2 = null;
                this.kernelManager = null;
                this.kernelConn = null;
                this.comm = null;
                this.widgetComm = null;
                this.appletApi = null;
                this.appletStyleObserver = null;
                this.unregisterWidgetCommTargets = null;
                this.injectCleanup = null;
                this.observer = null;
                this.resizeHandler = null;
                this.closeHandler = null;
                this.metaViewport = null;
                this.scriptTag = null;
                this._lastValues = {};
                this.kernelId = kernelId;
                this.commTarget = commTarget;
                this.socketPath = socketPath;
                this.wsPort = wsPort;
            }
            async dispose() {
                var _a, _b, _c, _d, _e, _f;
                try {
                    if (this.comm) {
                        try {
                            (_b = (_a = this.comm).close) === null || _b === void 0 ? void 0 : _b.call(_a);
                        }
                        catch (err) {
                            dbg('Error closing comm during cleanup', err);
                        }
                        this.comm = null;
                    }
                    if (this.kernel2) {
                        try {
                            await this.kernel2.shutdown();
                        }
                        catch (err) {
                            dbg('Error shutting down kernel2 during cleanup', err);
                        }
                        this.kernel2 = null;
                    }
                    this.widgetComm = null;
                    this.appletApi = null;
                    if (this.kernelManager) {
                        try {
                            await ((_d = (_c = this.kernelManager).shutdown) === null || _d === void 0 ? void 0 : _d.call(_c));
                        }
                        catch (err) {
                            dbg('Error shutting down kernelManager', err);
                        }
                        this.kernelManager = null;
                    }
                    if (this.observer) {
                        try {
                            this.observer.disconnect();
                        }
                        catch (err) {
                            dbg('Error disconnecting observer', err);
                        }
                        this.observer = null;
                    }
                    if (this.appletStyleObserver) {
                        try {
                            this.appletStyleObserver.disconnect();
                        }
                        catch (err) {
                            dbg('Error disconnecting appletStyleObserver', err);
                        }
                        this.appletStyleObserver = null;
                    }
                    if (this.resizeHandler) {
                        try {
                            window.removeEventListener('resize', this.resizeHandler);
                        }
                        catch (err) {
                            dbg('Error removing resize handler', err);
                        }
                        this.resizeHandler = null;
                    }
                    if (this.closeHandler) {
                        try {
                            window.removeEventListener('close', this.closeHandler);
                        }
                        catch (err) {
                            dbg('Error removing close handler', err);
                        }
                        this.closeHandler = null;
                    }
                    if (this.metaViewport && this.metaViewport.parentNode) {
                        this.metaViewport.parentNode.removeChild(this.metaViewport);
                        this.metaViewport = null;
                    }
                    if (this.scriptTag && this.scriptTag.parentNode) {
                        this.scriptTag.parentNode.removeChild(this.scriptTag);
                        this.scriptTag = null;
                    }
                    try {
                        (_e = this.unregisterWidgetCommTargets) === null || _e === void 0 ? void 0 : _e.call(this);
                        this.unregisterWidgetCommTargets = null;
                        try {
                            (_f = this.injectCleanup) === null || _f === void 0 ? void 0 : _f.call(this);
                        }
                        catch (err) {
                            dbg('Error during inject cleanup', err);
                        }
                        this.injectCleanup = null;
                    }
                    catch (err) {
                        dbg('Error unregistering widget comm targets', err);
                    }
                }
                catch (err) {
                    console.error('Error during resources.dispose():', err);
                }
            }
        }
        const resources = new Resources(props.kernelId || '', props.commTarget || '', props.socketPath || null, props.wsPort || 8888);
        dbg('useEffect: created Resources, about to run setup IIFE', { kernelId: props.kernelId, commTarget: props.commTarget }, []);
        (async () => {
            var _a, _b;
            dbg('IIFE: entered - calling setupKernelResources');
            const { callRemoteSocketSend, makeIncomingHandler } = await (0,_jupyterlab__WEBPACK_IMPORTED_MODULE_1__["default"])(resources, props, dbg);
            const processCommandMessage = (0,_shared_geoGebraCommon__WEBPACK_IMPORTED_MODULE_4__.createProcessCommandMessage)(resources, callRemoteSocketSend, _shared_geoGebraCommon__WEBPACK_IMPORTED_MODULE_4__.isArrayOfArrays, dbg);
            const handleIncomingCommMessage = makeIncomingHandler(processCommandMessage);
            try {
                if (props.widgetManager) {
                    dbg('widgetManager present; skipping raw jupyter.widget comm registration');
                }
                else {
                    const opts = { callRemoteSocketSend, kernel2: resources.kernel2, socketPath: resources.socketPath, wsUrl: `ws://localhost:${resources.wsPort}/`, getAppletApi: () => resources.appletApi, isArrayOfArrays: _shared_geoGebraCommon__WEBPACK_IMPORTED_MODULE_4__.isArrayOfArrays, dbg };
                    const unregisterFn = (0,_widgets__WEBPACK_IMPORTED_MODULE_2__.registerWidgetCommTargets)(resources.kernelConn, opts);
                    resources.unregisterWidgetCommTargets = unregisterFn;
                }
            }
            catch (e) {
                dbg('Widget comm target registration skipped or failed', e);
            }
            async function ggbOnLoad(api) {
                dbg('GeoGebra applet loaded:', api);
                try {
                    await (0,_shared_appletOnLoadCommon__WEBPACK_IMPORTED_MODULE_5__["default"])(api, resources, callRemoteSocketSend, handleIncomingCommMessage, dbg);
                }
                catch (e) {
                    dbg('setupAppletOnLoadCommon failed', e);
                }
                resources.resizeHandler = function () {
                    var _a;
                    try {
                        const wrapperDiv = document.getElementById(elementId);
                        const target = (_a = wrapperDiv === null || wrapperDiv === void 0 ? void 0 : wrapperDiv.parentElement) !== null && _a !== void 0 ? _a : wrapperDiv;
                        if (!target)
                            return;
                        const rect = target.getBoundingClientRect();
                        const width = Math.max(1, Math.floor(rect.width));
                        const height = Math.max(1, Math.floor(rect.height));
                        try {
                            api.recalculateEnvironments();
                        }
                        catch (e) {
                            dbg('recalculateEnvironments failed', e);
                        }
                        try {
                            api.setSize(width, height);
                        }
                        catch (e) {
                            dbg('setSize failed', e);
                        }
                    }
                    catch (e) {
                        dbg('resizeHandler error', e);
                    }
                };
                window.addEventListener('resize', resources.resizeHandler);
                resources.resizeHandler();
            }
            try {
                const wrapperDiv = (_a = widgetRef.current) !== null && _a !== void 0 ? _a : document.getElementById(elementId);
                const targetForSize = (_b = wrapperDiv === null || wrapperDiv === void 0 ? void 0 : wrapperDiv.parentElement) !== null && _b !== void 0 ? _b : wrapperDiv;
                let measuredWidth = 800;
                let measuredHeight = 600;
                try {
                    if (targetForSize) {
                        const rect = targetForSize.getBoundingClientRect();
                        measuredWidth = Math.max(1, Math.floor(rect.width));
                        measuredHeight = Math.max(1, Math.floor(rect.height));
                    }
                }
                catch (e) {
                    dbg('Failed to measure container for initial size, falling back to defaults', e);
                }
                const { appletPromise, scriptTag, metaViewport, cleanup } = (0,_shared_createApplet__WEBPACK_IMPORTED_MODULE_3__.injectGeoGebraApplet)({ elementId, appName: (props === null || props === void 0 ? void 0 : props.appName) || 'suite', width: measuredWidth, height: measuredHeight, scaleContainerClass: undefined, allowUpscale: true, appletOnLoad: ggbOnLoad, dbg });
                resources.scriptTag = scriptTag;
                resources.metaViewport = metaViewport;
                resources.injectCleanup = cleanup || null;
                appletPromise.then((a) => {
                    var _a, _b, _c;
                    applet = a;
                    try {
                        const api = a;
                        const wrapperDiv2 = (_a = widgetRef.current) !== null && _a !== void 0 ? _a : document.getElementById(elementId);
                        const target2 = (_b = wrapperDiv2 === null || wrapperDiv2 === void 0 ? void 0 : wrapperDiv2.parentElement) !== null && _b !== void 0 ? _b : wrapperDiv2;
                        let w = measuredWidth;
                        let h = measuredHeight;
                        try {
                            if (target2) {
                                const rect2 = target2.getBoundingClientRect();
                                w = Math.max(1, Math.floor(rect2.width));
                                h = Math.max(1, Math.floor(rect2.height));
                            }
                        }
                        catch (e) {
                            dbg('Failed to re-measure container for sizing', e);
                        }
                        try {
                            (_c = api.recalculateEnvironments) === null || _c === void 0 ? void 0 : _c.call(api);
                        }
                        catch (e) {
                            dbg('recalculateEnvironments failed', e);
                        }
                        try {
                            api.setSize(w, h);
                            dbg('Applied initial applet size', w, h);
                        }
                        catch (e) {
                            dbg('api.setSize failed', e);
                        }
                        try {
                            const appletNode = document.getElementById('ggbApplet-' + elementId);
                            if (appletNode) {
                                appletNode.style.width = '100%';
                                appletNode.style.height = '100%';
                                appletNode.style.maxWidth = '100%';
                                appletNode.style.transform = 'none';
                                appletNode.style.transformOrigin = '0 0';
                            }
                        }
                        catch (e) {
                            dbg('Failed to override applet DOM styles', e);
                        }
                        setTimeout(() => { try {
                            api.setSize(w, h);
                            dbg('Reapplied size (250ms)');
                        }
                        catch (e) {
                            dbg('reapply failed', e);
                        } }, 250);
                        setTimeout(() => { try {
                            api.setSize(w, h);
                            dbg('Reapplied size (1000ms)');
                        }
                        catch (e) {
                            dbg('reapply failed', e);
                        } }, 1000);
                        try {
                            const appletNode = document.getElementById('ggbApplet-' + elementId);
                            if (appletNode) {
                                const observer = new MutationObserver(mutations => { var _a; try {
                                    const rect3 = ((_a = appletNode.parentElement) !== null && _a !== void 0 ? _a : appletNode).getBoundingClientRect();
                                    const ww = Math.max(1, Math.floor(rect3.width));
                                    const hh = Math.max(1, Math.floor(rect3.height));
                                    try {
                                        api.setSize(ww, hh);
                                    }
                                    catch (e) { /* ignore */ }
                                    try {
                                        appletNode.style.transform = 'none';
                                        appletNode.style.width = '100%';
                                        appletNode.style.height = '100%';
                                    }
                                    catch (e) { /* ignore */ }
                                }
                                catch (e) {
                                    dbg('appletStyleObserver handler error', e);
                                } });
                                observer.observe(appletNode, { attributes: true, attributeFilter: ['style', 'class'], subtree: false });
                                resources.appletStyleObserver = observer;
                            }
                        }
                        catch (e) {
                            dbg('Failed to create appletStyleObserver', e);
                        }
                    }
                    catch (e) {
                        dbg('Error applying size to applet', e);
                    }
                }).catch((e) => dbg('Applet creation failed', e));
            }
            catch (e) {
                dbg('injectGeoGebraApplet failed', e);
            }
        })();
        return () => {
            var _a;
            if (resources.resizeHandler) {
                window.removeEventListener('resize', resources.resizeHandler);
                resources.resizeHandler = null;
            }
            if (resources.closeHandler) {
                window.removeEventListener('close', resources.closeHandler);
                resources.closeHandler = null;
            }
            if (resources.observer) {
                try {
                    resources.observer.disconnect();
                }
                catch (e) {
                    console.error(e);
                }
                resources.observer = null;
            }
            try {
                (_a = resources.unregisterWidgetCommTargets) === null || _a === void 0 ? void 0 : _a.call(resources);
                resources.unregisterWidgetCommTargets = null;
            }
            catch (e) {
                dbg('Error unregistering widget comm targets', e);
            }
            if (resources.metaViewport && resources.metaViewport.parentNode) {
                resources.metaViewport.parentNode.removeChild(resources.metaViewport);
                resources.metaViewport = null;
            }
            if (resources.scriptTag && resources.scriptTag.parentNode) {
                resources.scriptTag.parentNode.removeChild(resources.scriptTag);
                resources.scriptTag = null;
            }
            if (applet) {
                try {
                    dbg('Cleaning up GeoGebra applet.');
                    const winApplet = window.ggbApplet || applet;
                    try {
                        winApplet.remove();
                    }
                    catch (e) {
                        dbg('Error removing applet instance', e);
                    }
                }
                catch (e) {
                    dbg('Error while removing GeoGebra applet', e);
                }
                applet = null;
                delete window.ggbApplet;
            }
            (async () => { try {
                await resources.dispose();
            }
            catch (e) {
                console.error('Error during cleanup:', e);
            } })();
        };
    }, []);
    return react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { id: elementId, ref: widgetRef, style: { width: '100%', height: '100%' } });
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (GeoGebraApplet);


/***/ },

/***/ "./lib/index.js"
/*!**********************!*\
  !*** ./lib/index.js ***!
  \**********************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   createWidgetManagerLegacy: () => (/* binding */ createWidgetManagerLegacy),
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _jupyterlab_application__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/application */ "webpack/sharing/consume/default/@jupyterlab/application");
/* harmony import */ var _jupyterlab_application__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_application__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _jupyterlab_settingregistry__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @jupyterlab/settingregistry */ "webpack/sharing/consume/default/@jupyterlab/settingregistry");
/* harmony import */ var _jupyterlab_settingregistry__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_settingregistry__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _widget__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./widget */ "./lib/components/lumino.js");
/* harmony import */ var _widgets__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./widgets */ "./lib/widgets/widgetManager.js");
/* harmony import */ var _package_json__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../package.json */ "./package.json");
/* harmony import */ var _widgets__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./widgets */ "./lib/widgets/register_widget_manager_plugin.js");


// ILauncher removed: launcher integration is not used in this build

//import { DockLayout } from '@lumino/widgets';



/**
 * Legacy/compatibility note:
 * Historically the plugin created a `widgetManager` inline in this
 * module during activation. The implementation has been moved to
 * `src/widgetManager.ts` to centralize widget-manager logic and to
 * allow different manager implementations (or `undefined`) to be
 * swapped in. We keep a tiny forwarding helper here as a documented
 * placeholder so future maintainers can see the original intent and
 * have a single place to adapt call-sites if needed.
 */
function createWidgetManagerLegacy() {
    // Forward to the real factory in widgetManager.ts for now.
    return (0,_widgets__WEBPACK_IMPORTED_MODULE_5__.createWidgetManager)();
}
// Import package.json to reflect the package version in the UI log.


var CommandIDs;
(function (CommandIDs) {
    CommandIDs.create = 'ggblab:create';
})(CommandIDs || (CommandIDs = {}));
// const PANEL_CLASS = 'jp-ggblabPanel';
/**
 * Initialization data for the ggblab extension.
 */
const plugin = {
    id: 'ggblab:plugin',
    description: 'A JupyterLab extension.',
    autoStart: true,
    optional: [_jupyterlab_settingregistry__WEBPACK_IMPORTED_MODULE_2__.ISettingRegistry, _jupyterlab_application__WEBPACK_IMPORTED_MODULE_0__.ILayoutRestorer],
    activate: (app, settingRegistry, restorer) => {
        console.debug(`JupyterLab extension ggblab-${_package_json__WEBPACK_IMPORTED_MODULE_6__.version} is activated!`);
        // Pragmatic global registration (option B): register a `jupyter.ggblab`
        // comm target on all currently running kernels so kernels that open
        // comms to that target will be delivered to the front-end. Keep the
        // returned unregister function so we can clean up on unload.
        let _unregisterGlobalGGBlab = null;
        (0,_widgets__WEBPACK_IMPORTED_MODULE_5__.registerGlobalGGBlabCommTargets)(app)
            .then(unreg => {
            _unregisterGlobalGGBlab = unreg;
        })
            .catch(e => console.warn('Failed to register global ggblab comm targets', e));
        // Ensure we clean up registrations when the page unloads to avoid
        // leaving dangling front-end KernelConnection objects.
        window.addEventListener('beforeunload', () => {
            _unregisterGlobalGGBlab === null || _unregisterGlobalGGBlab === void 0 ? void 0 : _unregisterGlobalGGBlab();
        });
        if (settingRegistry) {
            settingRegistry
                .load(plugin.id)
                .then(settings => {
                console.debug('ggblab settings loaded:', settings.composite);
            })
                .catch(reason => {
                console.error('Failed to load settings for ggblab.', reason);
            });
        }
        const { commands } = app;
        // Tracker for created GeoGebra widgets so they can be restored after reload
        const tracker = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.WidgetTracker({
            namespace: 'ggblab-tracker'
        });
        const command = CommandIDs.create;
        commands.addCommand(command, {
            caption: 'Create a new React Widget',
            label: 'React Widget',
            icon: args => (args['isPalette'] ? undefined : _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__.reactIcon),
            execute: async (args) => {
                console.debug('socketPath:', args['socketPath']);
                // Precompute widget id so we can detect and remove any existing panel
                const idPart = (args['kernelId'] || '').substring(0, 8);
                const widgetId = `ggblab-${idPart}`;
                // If a widget with the same id exists, close and remove it first.
                try {
                    const existing = tracker.find((w) => w.id === widgetId);
                    if (existing) {
                        try {
                            existing.close();
                        }
                        catch (e) {
                            console.warn('Failed to close existing widget:', e);
                        }
                        try {
                            // tracker.remove may return a Promise
                            await tracker.remove(existing);
                        }
                        catch (e) {
                            // non-fatal
                            console.warn('Failed to remove existing widget from tracker:', e);
                        }
                    }
                }
                catch (e) {
                    // If tracker API differs, ignore and continue
                }
                // Centralized widget-manager factory (currently returns `undefined`)
                // to avoid interfering with ipywidgets. See src/widgetManager.ts
                // for future changes to this behavior.
                const widgetManager = (0,_widgets__WEBPACK_IMPORTED_MODULE_5__.createWidgetManager)();
                const content = new _widget__WEBPACK_IMPORTED_MODULE_4__.GeoGebraWidget({
                    kernelId: args['kernelId'] || '',
                    commTarget: args['commTarget'] || '',
                    insertMode: args['insertMode'] || 'split-right',
                    socketPath: args['socketPath'] || '',
                    appName: args['appName'] || 'suite',
                    wsPort: args['wsPort'] || 8888,
                    widgetManager: widgetManager
                });
                const widget = new _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_1__.MainAreaWidget({ content });
                // make widget id unique so restorer can identify it later
                widget.id = widgetId;
                widget.title.label = `GeoGebra (${idPart})`;
                widget.title.icon = _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_3__.reactIcon;
                // register with tracker so state will be saved for restoration
                try {
                    await tracker.add(widget);
                }
                catch (e) {
                    console.warn('Failed to add widget to tracker:', e);
                }
                app.shell.add(widget, 'main', {
                    mode: args['insertMode'] || 'split-right'
                });
            }
        });
        // palette.addItem({
        //   command,
        //   category: "Tutorial",
        // });
        if (restorer) {
            // Note: we may in future support restoring the applet's internal
            // state from an autosave (e.g. localStorage or a persistent store).
            // That would involve fetching a saved XML/Base64 snapshot and
            // passing it through `args` or a dedicated `initialXml` prop so the
            // recreated widget can rehydrate the GeoGebra applet.
            restorer.restore(tracker, {
                command,
                // use widget.id as the saved name so it is unique per widget
                name: widget => widget.id,
                // reconstruct args (kernelId) from the saved widget id so the
                // command can recreate the widget with the same kernel association
                args: widget => {
                    // Prefer to read the original creation props from the widget content
                    const content = (widget && widget.content) || {};
                    const p = content.props || {};
                    // Fallback to reconstructing kernelId from the widget id if not present
                    const id = widget.id || '';
                    const kernelId = p.kernelId || (id.startsWith('ggblab-') ? id.slice('ggblab-'.length) : '');
                    return {
                        kernelId,
                        commTarget: p.commTarget || '',
                        socketPath: p.socketPath || '',
                        appName: p.appName || 'suite',
                        wsPort: p.wsPort || 8888,
                        insertMode: p.insertMode || 'split-right'
                    };
                }
            });
        }
        // Launcher integration removed: no launcher item will be added.
    }
};
// Export both the main plugin and the manager-detection plugin so JupyterLab
// will activate the manager probe and allow `setWidgetManager` to be called
// when the jupyter-widgets manager becomes available.
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ([plugin, _widgets__WEBPACK_IMPORTED_MODULE_7__["default"]]);


/***/ },

/***/ "./lib/shared/appletOnLoadCommon.js"
/*!******************************************!*\
  !*** ./lib/shared/appletOnLoadCommon.js ***!
  \******************************************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ setupAppletOnLoadCommon)
/* harmony export */ });
/* Shared setup for the front portion of ggbOnLoad used by both
   the JupyterLab widget and the VSCode webview widget. This function
   performs common wiring: expose `appletApi`, send a start message,
   create kernel comm if configured, attach incoming handlers, register
   simple API listeners (add/remove/rename/clear), and install a
   MutationObserver to forward dialog messages.
*/
async function setupAppletOnLoadCommon(api, resources, callRemoteSocketSend, handleIncomingCommMessage, dbg) {
    var _a, _b, _c, _d, _e, _f;
    dbg('Shared ggbOnLoad common setup: start');
    resources.appletApi = api;
    (async () => {
        const msg = { type: 'start', payload: {} };
        try {
            await callRemoteSocketSend(JSON.stringify(msg));
        }
        catch (e) {
            dbg('callRemoteSocketSend failed (start)', e);
        }
    })();
    // Kernel comm creation (when a commTarget is present)
    if (resources.commTarget) {
        try {
            resources.comm = resources.kernelConn.createComm(resources.commTarget);
            try {
                const maybeId = ((_a = resources.comm) === null || _a === void 0 ? void 0 : _a.comm_id) || ((_b = resources.comm) === null || _b === void 0 ? void 0 : _b.commId) || null;
                dbg('Created kernel comm', { target: resources.commTarget, commObject: resources.comm, commId: maybeId });
            }
            catch (e) {
                dbg('Created kernel comm (unable to read id)', resources.commTarget, resources.comm);
            }
            try {
                resources.comm.open && resources.comm.open('HELO from GGB');
            }
            catch (e) {
                dbg('Failed to open kernel comm', e);
            }
        }
        catch (e) {
            dbg('Failed to create kernel comm for', resources.commTarget, e);
            resources.comm = null;
        }
        try {
            resources.comm.onClose = (m) => {
                var _a, _b;
                try {
                    const closedId = (m && m.content && m.content.comm_id) || ((_a = resources.comm) === null || _a === void 0 ? void 0 : _a.comm_id) || ((_b = resources.comm) === null || _b === void 0 ? void 0 : _b.commId) || null;
                    dbg('Kernel comm closed', { target: resources.commTarget, commId: closedId, message: m });
                }
                catch (e) {
                    dbg('Kernel comm closed (no id available)', resources.commTarget, m);
                }
            };
        }
        catch (e) {
            dbg('Unable to attach onClose to kernel comm', e);
        }
    }
    else {
        resources.comm = null;
        dbg('No commTarget provided; skipping kernel comm creation (shared)');
    }
    // Attach incoming handler if comm exists
    if (resources.comm) {
        try {
            resources.comm.onMsg = handleIncomingCommMessage;
        }
        catch (e) {
            dbg('Failed to attach handleIncomingCommMessage to comm', e);
        }
    }
    else {
        dbg('No kernel comm available; messages will be sent via remote socket only (shared)');
    }
    // Close handler
    resources.closeHandler = () => {
        var _a, _b, _c, _d;
        try {
            (_b = (_a = resources.comm) === null || _a === void 0 ? void 0 : _a.close) === null || _b === void 0 ? void 0 : _b.call(_a);
        }
        catch (e) {
            dbg('Error closing comm', e);
        }
        try {
            (_d = (_c = resources.kernel2) === null || _c === void 0 ? void 0 : _c.shutdown) === null || _d === void 0 ? void 0 : _d.call(_c);
        }
        catch (e) {
            dbg('Error shutting down kernel2', e);
        }
        dbg('Kernel and comm closed.');
        if (resources.resizeHandler) {
            try {
                window.removeEventListener('resize', resources.resizeHandler);
            }
            catch (e) {
                /* ignore */
            }
        }
    };
    try {
        window.addEventListener('close', resources.closeHandler);
    }
    catch (e) {
        dbg('addEventListener close failed', e);
    }
    // Register basic API listeners that forward events to the kernel/socket
    const addListener = async function (data) {
        dbg('Add listener triggered for (shared):', data);
        const msg = { type: 'add', payload: data };
        const s = JSON.stringify(msg);
        if (resources.widgetComm) {
            try {
                resources.widgetComm.send(s);
                return;
            }
            catch (e) {
                dbg('widgetComm.send failed, falling back', e);
            }
        }
        try {
            await callRemoteSocketSend(s);
        }
        catch (e) {
            dbg('callRemoteSocketSend failed (add)', e);
        }
    };
    const removeListener = async function (data) {
        dbg('Remove listener triggered for (shared):', data);
        const msg = { type: 'remove', payload: data };
        const s = JSON.stringify(msg);
        if (resources.widgetComm) {
            try {
                resources.widgetComm.send(s);
                return;
            }
            catch (e) {
                dbg('widgetComm.send failed, falling back', e);
            }
        }
        try {
            await callRemoteSocketSend(s);
        }
        catch (e) {
            dbg('callRemoteSocketSend failed (remove)', e);
        }
    };
    const renameListener = async function (data) {
        dbg('Rename listener triggered for (shared):', data);
        const msg = { type: 'rename', payload: data };
        const s = JSON.stringify(msg);
        if (resources.widgetComm) {
            try {
                resources.widgetComm.send(s);
                return;
            }
            catch (e) {
                dbg('widgetComm.send failed, falling back', e);
            }
        }
        try {
            await callRemoteSocketSend(s);
        }
        catch (e) {
            dbg('callRemoteSocketSend failed (rename)', e);
        }
    };
    const clearListener = async function (data) {
        dbg('Clear listener triggered for (shared):', data);
        const msg = { type: 'clear', payload: data };
        const s = JSON.stringify(msg);
        if (resources.widgetComm) {
            try {
                resources.widgetComm.send(s);
                return;
            }
            catch (e) {
                dbg('widgetComm.send failed, falling back', e);
            }
        }
        try {
            await callRemoteSocketSend(s);
        }
        catch (e) {
            dbg('callRemoteSocketSend failed (clear)', e);
        }
    };
    try {
        (_c = api.registerAddListener) === null || _c === void 0 ? void 0 : _c.call(api, addListener);
    }
    catch (e) {
        dbg('registerAddListener failed (shared)', e);
    }
    try {
        (_d = api.registerRemoveListener) === null || _d === void 0 ? void 0 : _d.call(api, removeListener);
    }
    catch (e) {
        dbg('registerRemoveListener failed (shared)', e);
    }
    try {
        (_e = api.registerRenameListener) === null || _e === void 0 ? void 0 : _e.call(api, renameListener);
    }
    catch (e) {
        dbg('registerRenameListener failed (shared)', e);
    }
    try {
        (_f = api.registerClearListener) === null || _f === void 0 ? void 0 : _f.call(api, clearListener);
    }
    catch (e) {
        dbg('registerClearListener failed (shared)', e);
    }
    // MutationObserver to forward dialog messages
    try {
        resources.observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                mutation.addedNodes.forEach(node => {
                    try {
                        node.querySelectorAll &&
                            node.querySelectorAll('div.dialogMainPanel > div.dialogTitle').forEach(n => {
                                var _a;
                                (_a = node
                                    .querySelector('div.dialogContent')) === null || _a === void 0 ? void 0 : _a.querySelectorAll("[class$='Label']").forEach(async (n2) => {
                                    const msg = JSON.stringify({ type: n.textContent, payload: n2.textContent });
                                    try {
                                        await callRemoteSocketSend(msg);
                                    }
                                    catch (e) {
                                        dbg('callRemoteSocketSend failed (dialog)', e);
                                    }
                                });
                            });
                    }
                    catch (e) {
                        /* ignore per-node errors */
                    }
                });
            });
        });
        resources.observer.observe(document.body, { childList: true, subtree: true });
    }
    catch (e) {
        dbg('Failed to install MutationObserver (shared)', e);
    }
    dbg('Shared ggbOnLoad common setup: complete');
}


/***/ },

/***/ "./lib/shared/createApplet.js"
/*!************************************!*\
  !*** ./lib/shared/createApplet.js ***!
  \************************************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__),
/* harmony export */   injectGeoGebraApplet: () => (/* binding */ injectGeoGebraApplet)
/* harmony export */ });
function injectGeoGebraApplet(opts) {
    const { elementId, appName = 'suite', width = 800, height = 600, scaleContainerClass = 'applet-wrapper', allowUpscale = false, appletOnLoad = null, scriptId = 'ggblab-deployggb-script', metaId = 'ggblab-viewport-meta', dbg = () => { } } = opts;
    let scriptTag = null;
    let metaViewport = null;
    let createdScript = false;
    let createdMeta = false;
    let createdApplet = null;
    // Ensure viewport meta exists
    const existingMeta = document.getElementById(metaId);
    if (existingMeta) {
        metaViewport = existingMeta;
    }
    else {
        metaViewport = document.createElement('meta');
        metaViewport.id = metaId;
        metaViewport.name = 'viewport';
        metaViewport.content = 'width=device-width, initial-scale=1';
        document.head.appendChild(metaViewport);
    }
    const existingScript = document.getElementById(scriptId);
    dbg('injectGeoGebraApplet: script lookup', { existingScript: !!existingScript, scriptId });
    const createAppletInternal = () => {
        const params = {
            id: 'ggbApplet-' + elementId,
            appName,
            width,
            height,
            showToolBar: true,
            showAlgebraInput: false,
            showMenuBar: true,
            autoHeight: true,
            allowUpscale
        };
        // Only include scaleContainerClass if a non-empty value was provided.
        // When omitted, the applet will use explicit width/height instead of
        // applying container-scaling which preserves aspect ratio and can leave
        // vertical letterbox space.
        if (scaleContainerClass) {
            params.scaleContainerClass = scaleContainerClass;
        }
        if (appletOnLoad) {
            params.appletOnLoad = appletOnLoad;
        }
        const applet = new window.GGBApplet(params, true);
        applet.inject(elementId);
        window.ggbApplet = applet;
        return applet;
    };
    const appletPromise = new Promise((resolve, reject) => {
        try {
            if (existingScript) {
                scriptTag = existingScript;
                if (window.GGBApplet) {
                    dbg('GGBApplet already on window; creating applet immediately');
                    const a = createAppletInternal();
                    createdApplet = a;
                    resolve(a);
                }
                else {
                    dbg('Attaching load listener to existing script');
                    const listener = () => {
                        try {
                            const a = createAppletInternal();
                            createdApplet = a;
                            resolve(a);
                        }
                        catch (e) {
                            reject(e);
                        }
                    };
                    existingScript.addEventListener('load', listener, { once: true });
                }
            }
            else {
                scriptTag = document.createElement('script');
                scriptTag.id = scriptId;
                scriptTag.src = 'https://cdn.geogebra.org/apps/deployggb.js';
                scriptTag.async = true;
                scriptTag.onload = () => {
                    try {
                        const a = createAppletInternal();
                        createdApplet = a;
                        resolve(a);
                    }
                    catch (e) {
                        reject(e);
                    }
                };
                scriptTag.onerror = e => {
                    reject(new Error('Failed to load deployggb.js'));
                };
                createdScript = true;
                document.body.appendChild(scriptTag);
            }
        }
        catch (e) {
            reject(e);
        }
    });
    const cleanup = () => {
        try {
            if (createdApplet) {
                try {
                    createdApplet.remove();
                }
                catch (e) {
                    /* ignore */
                }
                createdApplet = null;
            }
            if (window.ggbApplet) {
                try {
                    window.ggbApplet.remove();
                }
                catch (e) {
                    /* ignore */
                }
                try {
                    delete window.ggbApplet;
                }
                catch (e) {
                    /* ignore */
                }
            }
            if (createdScript && scriptTag && scriptTag.parentNode) {
                scriptTag.parentNode.removeChild(scriptTag);
                scriptTag = null;
            }
            if (createdMeta && metaViewport && metaViewport.parentNode) {
                metaViewport.parentNode.removeChild(metaViewport);
                metaViewport = null;
            }
        }
        catch (e) {
            dbg('Error during inject cleanup', e);
        }
    };
    // mark whether we created the meta tag (existingMeta was null)
    createdMeta = existingMeta ? false : true;
    return { appletPromise, scriptTag, metaViewport, cleanup };
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (injectGeoGebraApplet);


/***/ },

/***/ "./lib/shared/geoGebraCommon.js"
/*!**************************************!*\
  !*** ./lib/shared/geoGebraCommon.js ***!
  \**************************************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   createProcessCommandMessage: () => (/* binding */ createProcessCommandMessage),
/* harmony export */   isArrayOfArrays: () => (/* binding */ isArrayOfArrays)
/* harmony export */ });
// Shared helpers extracted from GeoGebraApplet and VSCode widget
function isArrayOfArrays(value) {
    return Array.isArray(value) && value.every((subArray) => Array.isArray(subArray));
}
function createProcessCommandMessage(resources, callRemoteSocketSend, isArrayOfArraysFn, dbg) {
    return async (command) => {
        let rmsg = null;
        const handlers = {
            command: async (cmd) => {
                if (resources.appletApi && typeof resources.appletApi.evalCommandGetLabels === 'function') {
                    const label = resources.appletApi.evalCommandGetLabels(cmd.payload);
                    return JSON.stringify({ type: 'created', id: cmd.id, payload: label });
                }
                return JSON.stringify({ type: 'error', id: cmd.id, payload: { message: 'applet API not available' } });
            },
            function: async (cmd) => {
                const apiName = cmd.payload.name;
                dbg('apiName:', apiName);
                let value = [];
                const args = cmd.payload.args;
                value = [];
                (Array.isArray(apiName) ? apiName : [apiName]).forEach((f) => {
                    dbg('call', f, args);
                    if (isArrayOfArraysFn(args)) {
                        const value2 = [];
                        args.forEach((arg2) => {
                            if (resources.appletApi && typeof resources.appletApi[f] === 'function') {
                                value2.push(resources.appletApi[f](...arg2) || null);
                            }
                            else {
                                value2.push(null);
                            }
                        });
                        value.push(value2);
                    }
                    else {
                        if (args) {
                            value.push(resources.appletApi && typeof resources.appletApi[f] === 'function' ? resources.appletApi[f](...args) || null : null);
                        }
                        else {
                            value.push(resources.appletApi && typeof resources.appletApi[f] === 'function' ? resources.appletApi[f]() || null : null);
                        }
                    }
                });
                value = Array.isArray(apiName) ? value : value[0];
                dbg('Function value:', value);
                return JSON.stringify({ type: 'value', id: cmd.id, payload: { value: value } });
            },
            listen: async (cmd) => {
                dbg('Register listen request:', cmd.payload);
                try {
                    let name = null;
                    let enabled = true;
                    const p = cmd.payload;
                    if (Array.isArray(p)) {
                        name = p[0];
                        enabled = !!p[1];
                    }
                    else if (p && typeof p === 'object') {
                        if (typeof p.name === 'string') {
                            name = p.name;
                        }
                        if (p.enabled !== undefined) {
                            enabled = !!p.enabled;
                        }
                        else if (p.enable !== undefined) {
                            enabled = !!p.enable;
                        }
                    }
                    else if (typeof p === 'string') {
                        name = p;
                        enabled = true;
                    }
                    if (!name) {
                        throw new Error('listen payload must include object name');
                    }
                    let result = null;
                    if (enabled) {
                        if (resources.appletApi && typeof resources.appletApi.registerObjectUpdateListener === 'function') {
                            try {
                                const cb = () => {
                                    var _a;
                                    try {
                                        let value = null;
                                        try {
                                            if (resources.appletApi && typeof resources.appletApi.getValueString === 'function') {
                                                value = resources.appletApi.getValueString(name);
                                            }
                                            else {
                                                value = null;
                                            }
                                        }
                                        catch (e) {
                                            dbg('getValueString failed', e);
                                            value = null;
                                        }
                                        try {
                                            const last = (_a = resources._lastValues[name]) !== null && _a !== void 0 ? _a : null;
                                            const cur = value === null || value === undefined ? null : String(value);
                                            if (last !== null && last === cur) {
                                                dbg('Suppressing unchanged value for', name, ':', cur);
                                                return;
                                            }
                                            resources._lastValues[name] = cur;
                                        }
                                        catch (e) {
                                            dbg('value-comparison in object update failed', e);
                                        }
                                        const msg = JSON.stringify({ type: 'object_update', payload: { name, value } });
                                        callRemoteSocketSend(msg).catch((e) => dbg('object_update send failed', e));
                                    }
                                    catch (e) {
                                        dbg('Error in object update callback', e);
                                    }
                                };
                                result = await Promise.resolve(resources.appletApi.registerObjectUpdateListener(name, cb));
                                try {
                                    cb();
                                }
                                catch (e) {
                                    dbg('initial object_update send failed', e);
                                }
                            }
                            catch (e) {
                                dbg('registerObjectUpdateListener failed', e);
                                result = { ok: false, error: String(e) };
                            }
                        }
                        else {
                            result = { ok: false, error: 'registerObjectUpdateListener not available' };
                        }
                    }
                    else {
                        if (resources.appletApi && typeof resources.appletApi.unregisterObjectUpdateListener === 'function') {
                            try {
                                result = await Promise.resolve(resources.appletApi.unregisterObjectUpdateListener(name));
                            }
                            catch (e) {
                                dbg('unregisterObjectUpdateListener failed', e);
                                result = { ok: false, error: String(e) };
                            }
                        }
                        else {
                            result = { ok: false, error: 'unregisterObjectUpdateListener not available' };
                        }
                    }
                    return JSON.stringify({ type: 'listen', id: cmd.id, payload: { result } });
                }
                catch (e) {
                    dbg('Error in listen handler', e);
                    return JSON.stringify({ type: 'error', id: cmd.id, payload: { message: String(e) } });
                }
            }
        };
        try {
            const h = handlers[command.type];
            if (h) {
                rmsg = await h(command);
            }
            else {
                dbg('No handler for command type', command.type);
                rmsg = JSON.stringify({ type: 'error', id: command.id, payload: { message: 'Unsupported command type' } });
            }
        }
        catch (e) {
            dbg('Handler error for command type', command.type, e);
            rmsg = JSON.stringify({ type: 'error', id: command.id, payload: { message: 'Handler execution failed' } });
        }
        return rmsg;
    };
}


/***/ },

/***/ "./lib/widgets/register_widget_manager_plugin.js"
/*!*******************************************************!*\
  !*** ./lib/widgets/register_widget_manager_plugin.js ***!
  \*******************************************************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _widgetManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./widgetManager */ "./lib/widgets/widgetManager.js");

/**
 * Plugin that tries to detect the jupyter-widgets manager plugins at runtime
 * and wraps their activate function to call our global registrar
 * `window.__ggblab_register_widget_manager(kernelId, manager)` when a
 * per-kernel manager instance becomes available.
 */
const registerWidgetManagerPlugin = {
    id: 'ggblab:register-widget-manager',
    autoStart: true,
    activate: (app) => {
        try {
            window.__ggblab_register_widget_manager = function (kernelId, manager) {
                try {
                    (0,_widgetManager__WEBPACK_IMPORTED_MODULE_0__.setWidgetManager)(manager);
                    console.debug('ggblab: __ggblab_register_widget_manager called for', kernelId);
                }
                catch (e) {
                    console.debug('ggblab: __ggblab_register_widget_manager handler failed', e);
                }
            };
        }
        catch (e) {
            console.debug('ggblab: failed to define __ggblab_register_widget_manager', e);
        }
        (async () => {
            try {
                let mod = null;
                try {
                    if (typeof globalThis.require === 'function') {
                        mod = globalThis.require('@jupyter-widgets/jupyterlab-manager');
                        console.debug('ggblab: register-widget-manager found jupyter-widgets module via global require');
                    }
                }
                catch (e) {
                    console.debug('ggblab: jupyter-widgets manager not available via global require', e);
                    mod = null;
                }
                if (!mod) {
                    console.debug('ggblab: jupyter-widgets manager not available for auto-plugin');
                    return;
                }
                const candidates = Array.isArray(mod.default) ? mod.default : Array.isArray(mod) ? mod : [];
                console.debug('ggblab: register-widget-manager candidates count', candidates.length);
                for (const p of candidates) {
                    if (!p || typeof p.activate !== 'function') {
                        continue;
                    }
                    const origActivate = p.activate.bind(p);
                    // Wrap activate to probe its args for manager instances and register them
                    // with our global registrar when detected.
                    p.activate = function (appArg, ...args) {
                        console.info('ggblab: wrapped widget-manager activate called', { argsCount: args.length });
                        const summaries = args.map((a) => {
                            try {
                                return { type: typeof a, keys: Object.keys(a || {}).slice(0, 10) };
                            }
                            catch (e) {
                                return { type: typeof a };
                            }
                        });
                        console.debug('ggblab: wrapped activate args summary', summaries);
                        const result = origActivate(appArg, ...args);
                        try {
                            for (const a of args) {
                                if (!a || typeof a !== 'object') {
                                    continue;
                                }
                                const isManager = typeof a.create_view === 'function' || typeof a.display_view_for_model === 'function' || !!a._create_views_for_model;
                                if (!isManager) {
                                    continue;
                                }
                                const manager = a;
                                let kernelId = '';
                                try {
                                    kernelId = (manager.context && manager.context.session && manager.context.session.kernel && manager.context.session.kernel.id) || (manager.kernel && manager.kernel.id) || '';
                                }
                                catch (e) {
                                    kernelId = '';
                                }
                                if (kernelId && window.__ggblab_register_widget_manager) {
                                    try {
                                        window.__ggblab_register_widget_manager(kernelId, manager);
                                        console.debug('ggblab: auto-registered widgetManager for kernel', kernelId);
                                    }
                                    catch (e) {
                                        console.warn('ggblab: failed to auto-register widgetManager', e);
                                    }
                                    try {
                                        (0,_widgetManager__WEBPACK_IMPORTED_MODULE_0__.setWidgetManager)(manager);
                                    }
                                    catch (e) {
                                        console.debug('ggblab: setWidgetManager failed', e);
                                    }
                                }
                                else if (manager && manager.context && manager.context.session) {
                                    try {
                                        const sess = manager.context.session;
                                        if (sess.kernelChanged && typeof sess.kernelChanged.connect === 'function') {
                                            const handler = (_s, kernel) => {
                                                try {
                                                    const kid = kernel ? kernel.id : '';
                                                    if (kid && window.__ggblab_register_widget_manager) {
                                                        window.__ggblab_register_widget_manager(kid, manager);
                                                        console.debug('ggblab: auto-registered widgetManager on kernelChanged for', kid);
                                                        try {
                                                            (0,_widgetManager__WEBPACK_IMPORTED_MODULE_0__.setWidgetManager)(manager);
                                                        }
                                                        catch (e) {
                                                            console.debug('ggblab: setWidgetManager failed', e);
                                                        }
                                                        try {
                                                            /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */ sess.kernelChanged.disconnect(handler);
                                                        }
                                                        catch (ee) {
                                                            console.debug('ggblab: ignored', ee);
                                                        }
                                                    }
                                                }
                                                catch (ee) {
                                                    console.debug('ggblab: ignored', ee);
                                                }
                                            };
                                            sess.kernelChanged.connect(handler);
                                        }
                                    }
                                    catch (e) {
                                        console.debug('ggblab: ignored', e);
                                    }
                                }
                            }
                        }
                        catch (e) {
                            console.warn('ggblab: error while probing widget-manager activate args', e);
                        }
                        return result;
                    };
                }
            }
            catch (e) {
                console.debug('ggblab: jupyter-widgets manager not available for auto-plugin', e);
            }
        })();
    }
};
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (registerWidgetManagerPlugin);


/***/ },

/***/ "./lib/widgets/widgetManager.js"
/*!**************************************!*\
  !*** ./lib/widgets/widgetManager.js ***!
  \**************************************/
(__unused_webpack_module, __webpack_exports__, __webpack_require__) {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ENABLE_RUNNING_CHANGED: () => (/* binding */ ENABLE_RUNNING_CHANGED),
/* harmony export */   createWidgetManager: () => (/* binding */ createWidgetManager),
/* harmony export */   registerGlobalGGBlabCommTargets: () => (/* binding */ registerGlobalGGBlabCommTargets),
/* harmony export */   registerWidgetCommTargets: () => (/* binding */ registerWidgetCommTargets),
/* harmony export */   setWidgetManager: () => (/* binding */ setWidgetManager)
/* harmony export */ });
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/services */ "webpack/sharing/consume/default/@jupyterlab/services");
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/coreutils */ "webpack/sharing/consume/default/@jupyterlab/coreutils");
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__);
// Minimal widget-manager adapter extracted from plugin/widget code.
// This module centralizes how a frontend WidgetManager (ipywidgets bridge)
// would be created or provided.
let _injectedWidgetManager = undefined;
function setWidgetManager(m) {
    _injectedWidgetManager = m;
    try {
        globalThis.__GGWIDGET_MANAGER__ = m;
        try {
            console.debug('ggblab: setWidgetManager called', { hasManager: !!m });
        }
        catch (e) {
            // eslint-disable-next-line no-empty
        }
    }
    catch (e) {
        // eslint-disable-next-line no-empty
    }
}
function detectWidgetManager() {
    const g = globalThis;
    try {
        console.debug('ggblab: detectWidgetManager probing globals');
    }
    catch (e) {
        // eslint-disable-next-line no-empty
    }
    if (g && g.__GGWIDGET_MANAGER__) {
        try {
            console.debug('ggblab: detected manager via __GGWIDGET_MANAGER__');
        }
        catch (_) {
            // eslint-disable-next-line no-empty
        }
        return g.__GGWIDGET_MANAGER__;
    }
    if (g && g.jupyterWidgetManager) {
        try {
            console.debug('ggblab: detected manager via jupyterWidgetManager');
        }
        catch (_) {
            // eslint-disable-next-line no-empty
        }
        return g.jupyterWidgetManager;
    }
    if (g && g.widgetManager) {
        try {
            console.debug('ggblab: detected manager via widgetManager');
        }
        catch (_) {
            // eslint-disable-next-line no-empty
        }
        return g.widgetManager;
    }
    try {
        console.debug('ggblab: no widget manager detected in globals');
    }
    catch (_) {
        // eslint-disable-next-line no-empty
    }
    return undefined;
}
function createWidgetManager() {
    if (_injectedWidgetManager) {
        return _injectedWidgetManager;
    }
    return detectWidgetManager();
}
function registerWidgetCommTargets(kernelConn, opts) {
    const managerAvailable = Boolean(createWidgetManager());
    const ENABLE_WIDGET_COMM_PASSTHROUGH = !managerAvailable;
    if (!ENABLE_WIDGET_COMM_PASSTHROUGH) {
        opts.dbg && opts.dbg('Widget comm passthrough disabled: WidgetManager present');
        return () => {
            /* noop unregister */
        };
    }
    opts.dbg && opts.dbg('Widget comm passthrough enabled: no WidgetManager detected');
    const dbg = opts.dbg || (() => { });
    const simpleHandler = (commOp, msg) => {
        dbg('widget comm opened (jupyter.widget)', commOp, msg);
        try {
            commOp.onMsg = async (m) => {
                var _a;
                const content = ((_a = m === null || m === void 0 ? void 0 : m.content) === null || _a === void 0 ? void 0 : _a.data) || m;
                try {
                    const command = typeof content === 'string' ? JSON.parse(content) : content;
                    let rmsg = null;
                    const appletApi = opts.getAppletApi();
                    if (command.type === 'command' && appletApi && typeof appletApi.evalCommandGetLabels === 'function') {
                        const label = appletApi.evalCommandGetLabels(command.payload);
                        rmsg = JSON.stringify({ type: 'created', id: command.id, payload: label });
                    }
                    else if (command.type === 'function' && appletApi) {
                        const apiName = command.payload.name;
                        const args = command.payload.args;
                        let value = [];
                        (Array.isArray(apiName) ? apiName : [apiName]).forEach((f) => {
                            if (typeof opts.isArrayOfArrays === 'function' && opts.isArrayOfArrays(args)) {
                                const v2 = [];
                                args.forEach((a) => {
                                    v2.push(typeof appletApi[f] === 'function' ? appletApi[f](...a) : null);
                                });
                                value.push(v2);
                            }
                            else {
                                value.push(args ? (typeof appletApi[f] === 'function' ? appletApi[f](...args) : null) : typeof appletApi[f] === 'function' ? appletApi[f]() : null);
                            }
                        });
                        value = Array.isArray(apiName) ? value : value[0];
                        rmsg = JSON.stringify({ type: 'value', id: command.id, payload: { value } });
                    }
                    if (rmsg) {
                        try {
                            commOp.send(rmsg);
                        }
                        catch (e) {
                            dbg('commOp.send failed', e);
                        }
                        try {
                            await opts.callRemoteSocketSend(rmsg);
                        }
                        catch (e) {
                            dbg('callRemoteSocketSend failed', e);
                        }
                    }
                }
                catch (e) {
                    dbg('Error handling widget comm message', e);
                }
            };
        }
        catch (e) {
            dbg('Failed to attach onMsg to widget comm', e);
        }
    };
    try {
        kernelConn.registerCommTarget('jupyter.widget', simpleHandler);
        kernelConn.registerCommTarget('jupyter.widget.control', simpleHandler);
    }
    catch (e) {
        dbg('Widget comm target registration failed', e);
    }
    return () => {
        try {
            if (typeof kernelConn.unregisterCommTarget === 'function') {
                kernelConn.unregisterCommTarget('jupyter.widget');
                kernelConn.unregisterCommTarget('jupyter.widget.control');
            }
        }
        catch (e) {
            dbg('Error during widget comm cleanup', e);
        }
    };
}


const ENABLE_RUNNING_CHANGED = false;
async function registerGlobalGGBlabCommTargets(app) {
    const baseUrl = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__.PageConfig.getBaseUrl();
    const token = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__.PageConfig.getToken();
    const settings = _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.ServerConnection.makeSettings({ baseUrl: baseUrl, token: token, appendToken: true });
    const registry = new Map();
    const dbg = (..._args) => {
        if (!ENABLE_RUNNING_CHANGED) {
            return;
        }
        console.debug(..._args);
    };
    const registerKernel = (k) => {
        const id = k.id || k.kernelId || (k.model && k.model.id) || null;
        if (!id) {
            return;
        }
        if (registry.has(id)) {
            dbg('Already registered jupyter.ggblab for kernel', id);
            return;
        }
        try {
            const manager = createWidgetManager();
            if (manager && typeof manager.registerGGBlabHandler === 'function') {
                try {
                    const unregisterFromManager = manager.registerGGBlabHandler(id, (commOp, msg) => {
                        try {
                            void 0;
                        }
                        catch (e) {
                            console.warn('Error delegating jupyter.ggblab to manager', e);
                        }
                    });
                    registry.set(id, () => {
                        unregisterFromManager && unregisterFromManager();
                    });
                    return;
                }
                catch (e) {
                    console.warn('Widget manager failed to register jupyter.ggblab', id, e);
                }
            }
            const kc = new _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelConnection({ model: { name: 'python3', id }, serverSettings: settings });
            try {
                kc.registerCommTarget('jupyter.ggblab', (commOp, msg) => {
                    try {
                        dbg('jupyter.ggblab comm opened', { kernelId: id, msg });
                        commOp.onMsg = (m) => {
                            dbg('jupyter.ggblab message', { kernelId: id, m });
                        };
                    }
                    catch (e) {
                        console.warn('Error in jupyter.ggblab handler', e);
                    }
                });
            }
            catch (e) {
                console.warn('Failed to register jupyter.ggblab on kernel', id, e);
            }
            const unregister = () => {
                try {
                    if (typeof kc.unregisterCommTarget === 'function') {
                        kc.unregisterCommTarget('jupyter.ggblab');
                    }
                }
                catch (e) {
                    console.warn('Error while unregistering jupyter.ggblab', e);
                }
            };
            registry.set(id, unregister);
        }
        catch (e) {
            console.warn('Failed to create KernelConnection for kernel', id, e);
        }
    };
    const unregisterKernel = (id) => {
        const fn = registry.get(id);
        if (fn) {
            try {
                fn();
            }
            catch (e) {
                console.warn('Error during unregister for kernel', id, e);
            }
            registry.delete(id);
        }
    };
    try {
        const kernels = await _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelAPI.listRunning();
        (kernels || []).forEach(registerKernel);
    }
    catch (e) {
        console.warn('Failed to list running kernels for ggblab registration', e);
    }
    const onRunningChanged = async () => {
        try {
            const current = await _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelAPI.listRunning();
            const currentIds = new Set((current || []).map((k) => k.id));
            (current || []).forEach(k => registerKernel(k));
            Array.from(registry.keys()).forEach(id => {
                if (!currentIds.has(id)) {
                    unregisterKernel(id);
                }
            });
        }
        catch (e) {
            console.warn('Error handling runningChanged for ggblab', e);
        }
    };
    try {
        if (ENABLE_RUNNING_CHANGED) {
            try {
                if (app &&
                    app.serviceManager &&
                    app.serviceManager.sessions &&
                    typeof app.serviceManager.sessions.runningChanged === 'object' &&
                    typeof app.serviceManager.sessions.runningChanged.connect === 'function') {
                    app.serviceManager.sessions.runningChanged.connect(onRunningChanged);
                }
                else if (_jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelAPI.runningChanged && typeof _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelAPI.runningChanged.connect === 'function') {
                    _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelAPI.runningChanged.connect(onRunningChanged);
                }
                else {
                    const pollInterval = 5000;
                    const timer = setInterval(onRunningChanged, pollInterval);
                    registry.set('__poll_timer__', () => clearInterval(timer));
                }
            }
            catch (e) {
                console.warn('Failed to attach runningChanged listener', e);
            }
        }
        else {
            dbg('Kernel runningChanged detection is disabled (ENABLE_RUNNING_CHANGED=false)');
        }
    }
    catch (e) {
        console.warn('Failed to attach runningChanged listener', e);
    }
    return () => {
        try {
            if (app &&
                app.serviceManager &&
                app.serviceManager.sessions &&
                typeof app.serviceManager.sessions.runningChanged === 'object' &&
                typeof app.serviceManager.sessions.runningChanged.disconnect === 'function') {
                app.serviceManager.sessions.runningChanged.disconnect(onRunningChanged);
            }
            else if (_jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelAPI.runningChanged && typeof _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelAPI.runningChanged.disconnect === 'function') {
                _jupyterlab_services__WEBPACK_IMPORTED_MODULE_0__.KernelAPI.runningChanged.disconnect(onRunningChanged);
            }
            Array.from(registry.keys()).forEach(k => {
                const fn = registry.get(k);
                if (fn) {
                    fn();
                }
            });
            registry.clear();
        }
        catch (e) {
            console.warn('Error during global ggblab unregister-all', e);
        }
    };
}


/***/ },

/***/ "./package.json"
/*!**********************!*\
  !*** ./package.json ***!
  \**********************/
(module) {

module.exports = /*#__PURE__*/JSON.parse('{"name":"ggblab","version":"1.5.0","description":"A JupyterLab extension for learning geometry and Python programming side-by-side with GeoGebra.","keywords":["jupyter","jupyterlab","jupyterlab-extension"],"homepage":"https://github.com/moyhig-ecs/ggblab#readme","bugs":{"url":"https://github.com/moyhig-ecs/ggblab/issues"},"license":"BSD-3-Clause","author":"Manabu Higashida <manabu@higashida.net>","files":["lib/**/*.{d.ts,eot,gif,html,jpg,js,js.map,json,png,svg,woff2,ttf}","style/**/*.{css,js,eot,gif,html,jpg,json,png,svg,woff2,ttf}","src/**/*.{ts,tsx}","schema/*.json"],"main":"lib/index.js","types":"lib/index.d.ts","style":"style/index.css","repository":{"type":"git","url":"https://github.com/moyhig-ecs/ggblab"},"scripts":{"build":"jlpm build:lib && jlpm build:labextension:dev","build:prod":"jlpm clean && jlpm build:lib:prod && jlpm build:labextension","build:labextension":"jupyter labextension build .","build:labextension:dev":"jupyter labextension build --development True .","build:lib":"tsc --sourceMap","build:lib:prod":"tsc","clean":"jlpm clean:lib","clean:lib":"rimraf lib tsconfig.tsbuildinfo","clean:lintcache":"rimraf .eslintcache .stylelintcache","clean:labextension":"rimraf ggblab/labextension ggblab/_version.py","clean:all":"jlpm clean:lib && jlpm clean:labextension && jlpm clean:lintcache","eslint":"jlpm eslint:check --fix","eslint:check":"eslint . --cache --ext .ts,.tsx","install:extension":"jlpm build","lint":"jlpm stylelint && jlpm prettier && jlpm eslint","lint:check":"jlpm stylelint:check && jlpm prettier:check && jlpm eslint:check","prettier":"jlpm prettier:base --write --list-different","prettier:base":"prettier \\"**/*{.ts,.tsx,.js,.jsx,.css,.json,.md}\\"","prettier:check":"jlpm prettier:base --check","stylelint":"jlpm stylelint:check --fix","stylelint:check":"stylelint --cache \\"style/**/*.css\\"","test":"jest --coverage","watch":"run-p watch:src watch:labextension","watch:src":"tsc -w --sourceMap","watch:labextension":"jupyter labextension watch ."},"dependencies":{"@jupyter-widgets/base":"^4.0.0","@jupyterlab/application":"^4.0.0","@jupyterlab/apputils":"^4.6.1","@jupyterlab/launcher":"^4.5.1","@jupyterlab/settingregistry":"^4.0.0","@lumino/widgets":"^2.7.2","@marshallku/react-postscribe":"^0.2.0","cross-fetch":"^3.1.5","react-meta-tags":"^1.0.1"},"devDependencies":{"@jupyterlab/builder":"^4.5.2","@jupyterlab/testutils":"^4.0.0","@types/jest":"^29.2.0","@types/json-schema":"^7.0.11","@types/react":"^18.0.26","@types/react-addons-linked-state-mixin":"^0.14.22","@typescript-eslint/eslint-plugin":"^6.1.0","@typescript-eslint/parser":"^6.1.0","css-loader":"^6.7.1","esbuild":"^0.27.2","eslint":"^8.36.0","eslint-config-prettier":"^8.8.0","eslint-plugin-prettier":"^5.0.0","jest":"^29.2.0","npm-run-all2":"^7.0.1","prettier":"^3.0.0","react":"^19.2.4","react-dom":"^19.2.4","rimraf":"^5.0.1","source-map-loader":"^1.0.2","style-loader":"^3.3.1","stylelint":"^15.10.1","stylelint-config-recommended":"^13.0.0","stylelint-config-standard":"^34.0.0","stylelint-csstree-validator":"^3.0.0","stylelint-prettier":"^4.0.0","typescript":"~5.5.4","yjs":"^13.5.0"},"resolutions":{"lib0":"0.2.111"},"sideEffects":["style/*.css","style/index.js"],"styleModule":"style/index.js","publishConfig":{"access":"public"},"jupyterlab":{"extension":true,"outputDir":"ggblab/labextension","schemaDir":"schema"},"eslintIgnore":["node_modules","dist","coverage","**/*.d.ts","tests","**/__tests__","ui-tests"],"eslintConfig":{"extends":["eslint:recommended","plugin:@typescript-eslint/eslint-recommended","plugin:@typescript-eslint/recommended","plugin:prettier/recommended"],"parser":"@typescript-eslint/parser","parserOptions":{"project":"tsconfig.json","sourceType":"module"},"plugins":["@typescript-eslint"],"rules":{"@typescript-eslint/naming-convention":["error",{"selector":"interface","format":["PascalCase"],"custom":{"regex":"^I[A-Z]","match":true}}],"@typescript-eslint/no-unused-vars":["warn",{"args":"none"}],"@typescript-eslint/no-explicit-any":"off","@typescript-eslint/no-namespace":"off","@typescript-eslint/no-use-before-define":"off","@typescript-eslint/quotes":["error","single",{"avoidEscape":true,"allowTemplateLiterals":false}],"curly":["error","all"],"eqeqeq":"error","prefer-arrow-callback":"error"}},"prettier":{"singleQuote":true,"trailingComma":"none","arrowParens":"avoid","endOfLine":"auto","printWidth":200,"bracketSameLine":true,"jsxSingleQuote":true,"proseWrap":"never","tabWidth":2,"useTabs":true,"overrides":[{"files":"package.json","options":{"tabWidth":4}}]},"stylelint":{"extends":["stylelint-config-recommended","stylelint-config-standard","stylelint-prettier/recommended"],"plugins":["stylelint-csstree-validator"],"rules":{"csstree/validator":true,"property-no-vendor-prefix":null,"selector-class-pattern":"^([a-z][A-z\\\\d]*)(-[A-z\\\\d]+)*$","selector-no-vendor-prefix":null,"value-no-vendor-prefix":null}},"directories":{"doc":"docs","example":"examples","lib":"lib","test":"tests"}}');

/***/ }

}]);
//# sourceMappingURL=lib_index_js.a25c6e7559641863d246.js.map