@tlockney/cdp-kernel 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -6
- package/dist/browser/channels.d.ts +27 -0
- package/dist/browser/channels.js +90 -0
- package/dist/browser/kernel.js +29674 -0
- package/dist/browser/kernel.js.map +7 -0
- package/dist/browser/mod.d.ts +20 -0
- package/dist/browser/mod.js +38 -0
- package/dist/browser/target.d.ts +71 -0
- package/dist/browser/target.js +206 -0
- package/dist/browser/worker.js +1000 -0
- package/dist/browser/worker.js.map +7 -0
- package/dist/cdp.d.ts +11 -0
- package/dist/cdp.js +6 -1
- package/dist/celld-target.js +9 -12
- package/dist/children.d.ts +25 -3
- package/dist/children.js +84 -2
- package/dist/debugger.d.ts +2 -0
- package/dist/debugger.js +12 -6
- package/dist/deno-types.d.ts +30 -0
- package/dist/deno-types.js +93 -0
- package/dist/kernel-core.d.ts +69 -0
- package/dist/kernel-core.js +754 -0
- package/dist/kernel.d.ts +12 -1
- package/dist/kernel.js +132 -605
- package/dist/language-service-worker.d.ts +1 -0
- package/dist/language-service-worker.js +88 -0
- package/dist/language-service.d.ts +64 -0
- package/dist/language-service.js +128 -0
- package/dist/main.js +102 -8
- package/dist/message.d.ts +34 -0
- package/dist/message.js +14 -0
- package/dist/mod.d.ts +1 -0
- package/dist/mod.js +1 -0
- package/dist/notebook-types.d.ts +62 -0
- package/dist/notebook-types.js +310 -0
- package/dist/package.d.ts +2 -2
- package/dist/package.js +2 -2
- package/dist/parent.d.ts +12 -0
- package/dist/parent.js +39 -0
- package/dist/port-holder.d.ts +13 -0
- package/dist/port-holder.js +105 -0
- package/dist/sourcemap.d.ts +7 -2
- package/dist/sourcemap.js +9 -3
- package/dist/strip-esbuild.d.ts +2 -0
- package/dist/strip-esbuild.js +44 -0
- package/dist/strip-sucrase.d.ts +2 -0
- package/dist/strip-sucrase.js +78 -0
- package/dist/target-api.d.ts +80 -0
- package/dist/target-api.js +22 -0
- package/dist/target.d.ts +26 -74
- package/dist/target.js +232 -58
- package/dist/traceback.d.ts +75 -0
- package/dist/traceback.js +200 -0
- package/dist/transform.d.ts +22 -1
- package/dist/transform.js +46 -43
- package/dist/wire.d.ts +4 -24
- package/dist/wire.js +3 -12
- package/dist/workerd-target.js +1 -1
- package/dist/workers-project.js +13 -2
- package/dist/zmq-channels.d.ts +14 -0
- package/dist/zmq-channels.js +59 -0
- package/dist/zmtp.d.ts +2 -0
- package/dist/zmtp.js +12 -0
- package/package.json +15 -5
- package/runtime/bootstrap.mjs +113 -33
- package/runtime/browser-worker.mjs +119 -0
- package/runtime/cdn.d.mts +2 -0
- package/runtime/cdn.mjs +17 -0
- package/runtime/display.mjs +202 -1
- package/runtime/format.d.mts +2 -0
- package/runtime/format.mjs +125 -0
- package/runtime/introspect.mjs +1 -1
- package/runtime/node-hooks.d.mts +6 -0
- package/runtime/node-hooks.mjs +11 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../runtime/comm.mjs", "../../runtime/widget.mjs", "../../runtime/display.mjs", "../../runtime/evaluator.mjs", "../../runtime/format.mjs", "../../runtime/introspect.mjs", "../../runtime/cdn.mjs", "../../runtime/browser-worker.mjs"],
|
|
4
|
+
"sourcesContent": ["// @ts-self-types=\"./comm.d.mts\"\n// Jupyter comms: bidirectional channels between kernel and frontend, the\n// transport ipywidgets and anywidget are built on (#9). Runs inside the\n// target runtime.\n//\n// Kernel-to-frontend messages (comm_open, comm_msg, comm_close) go out\n// through `send`, the same ordered path as display messages. Frontend\n// messages arrive from the host through `dispatch`, which returns whether\n// anything in the kernel handled them, so the host can answer an unknown\n// target's comm_open with a comm_close, as the protocol asks.\n\nclass Comm {\n #send;\n #onClosed;\n #msgHandlers = [];\n #closeHandlers = [];\n closed = false;\n\n constructor(id, targetName, send, onClosed) {\n this.id = id;\n this.targetName = targetName;\n this.#send = send;\n this.#onClosed = onClosed;\n }\n\n send(data = {}, { metadata = {}, buffers = [] } = {}) {\n if (this.closed) return;\n this.#send(\"comm_msg\", { comm_id: this.id, data }, metadata, buffers);\n }\n\n close(data = {}, { metadata = {}, buffers = [] } = {}) {\n if (this.closed) return;\n this.#send(\"comm_close\", { comm_id: this.id, data }, metadata, buffers);\n // close() is synchronous for callers; its close handlers run detached.\n void this._closed({ data, metadata, buffers });\n }\n\n onMsg(handler) {\n this.#msgHandlers.push(handler);\n }\n\n onClose(handler) {\n this.#closeHandlers.push(handler);\n }\n\n async _receive(msg) {\n for (const handler of this.#msgHandlers) await handler(msg);\n }\n\n async _closed(msg) {\n if (this.closed) return;\n this.closed = true;\n this.#onClosed(this.id);\n for (const handler of this.#closeHandlers) await handler(msg);\n }\n}\n\n/**\n * @param {(msgType: string, content: object, metadata: object, buffers: Uint8Array[]) => void} send\n * @param {() => string} [newId]\n */\nexport function createComms(send, newId = () => crypto.randomUUID()) {\n const comms = new Map(); // comm_id -> Comm\n const targets = new Map(); // target_name -> handler\n const forget = (id) => comms.delete(id);\n\n function track(id, targetName) {\n const comm = new Comm(id, targetName, send, forget);\n comms.set(id, comm);\n return comm;\n }\n\n const api = {\n open(targetName, data = {}, { metadata = {}, buffers = [] } = {}) {\n const comm = track(newId(), targetName);\n send(\"comm_open\", { comm_id: comm.id, target_name: targetName, data }, metadata, buffers);\n return comm;\n },\n registerTarget(targetName, handler) {\n targets.set(targetName, handler);\n },\n unregisterTarget(targetName) {\n targets.delete(targetName);\n },\n };\n\n async function dispatch(msgType, content, metadata, buffers) {\n const msg = { data: content.data ?? {}, metadata: metadata ?? {}, buffers: buffers ?? [] };\n if (msgType === \"comm_open\") {\n const handler = targets.get(content.target_name);\n if (!handler) return false;\n const comm = track(content.comm_id, content.target_name);\n try {\n await handler(comm, msg);\n } catch (err) {\n // The host answers a failed comm_open with comm_close, so the comm\n // is gone on the frontend: drop it here too, without running close\n // handlers or sending anything (#137).\n comm.closed = true;\n forget(comm.id);\n throw err;\n }\n return true;\n }\n const comm = comms.get(content.comm_id);\n if (!comm) return false;\n if (msgType === \"comm_msg\") await comm._receive(msg);\n else if (msgType === \"comm_close\") await comm._closed(msg);\n else return false;\n return true;\n }\n\n function list() {\n return [...comms.values()].map((comm) => ({ commId: comm.id, targetName: comm.targetName }));\n }\n\n return { api, dispatch, list };\n}\n", "// @ts-self-types=\"./widget.d.mts\"\n// anywidget-compatible widgets over Jupyter comms (#9): the kernel half of\n// the ipywidgets model protocol (version 2.1.0) for anywidget's AnyModel,\n// whose frontend is the `anywidget` JupyterLab/Notebook/VS Code extension.\n//\n// const counter = jupyter.widget({ esm, state: { count: 0 } });\n// counter // display it\n// counter.get(\"count\"); counter.set(\"count\", 1);\n// counter.on(\"change:count\", (value, old) => ...);\n//\n// State is synced as in ipywidgets: `update` messages carry changed keys,\n// with binary values lifted out into message buffers at `buffer_paths`\n// (ipywidgets' _remove_buffers/_put_buffers).\n\nexport const WIDGET_PROTOCOL_VERSION = \"2.1.0\";\nconst WIDGET_TARGET = \"jupyter.widget\";\nconst CONTROL_TARGET = \"jupyter.widget.control\";\nconst VIEW_MIME = \"application/vnd.jupyter.widget-view+json\";\n\n// The anywidget model the frontend instantiates. The module version is a\n// semver range for the frontend's registry; anywidget sends \"~major.minor.*\"\n// of its own version, and \"*\" accepts whichever release is installed.\nconst ANYWIDGET_MODEL = {\n _model_name: \"AnyModel\",\n _model_module: \"anywidget\",\n _model_module_version: \"*\",\n _view_name: \"AnyView\",\n _view_module: \"anywidget\",\n _view_module_version: \"*\",\n _view_count: null,\n};\n\nfunction isBinary(value) {\n return value instanceof Uint8Array || value instanceof ArrayBuffer || ArrayBuffer.isView(value);\n}\n\nfunction toBytes(value) {\n if (value instanceof Uint8Array) return value;\n if (value instanceof ArrayBuffer) return new Uint8Array(value);\n return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n}\n\n/** Copies `state` with binary values replaced by null, collecting them. */\nexport function removeBuffers(state) {\n const bufferPaths = [];\n const buffers = [];\n function walk(value, path) {\n if (isBinary(value)) {\n bufferPaths.push(path);\n buffers.push(toBytes(value));\n return null;\n }\n if (Array.isArray(value)) return value.map((item, i) => walk(item, [...path, i]));\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walk(v, [...path, k])]));\n }\n return value;\n }\n return { state: walk(state, []), bufferPaths, buffers };\n}\n\n/** Puts received buffers back into `state` at `bufferPaths` (in place). */\nexport function putBuffers(state, bufferPaths = [], buffers = []) {\n bufferPaths.forEach((path, i) => {\n let obj = state;\n for (const key of path.slice(0, -1)) obj = obj[key];\n obj[path[path.length - 1]] = buffers[i];\n });\n return state;\n}\n\nclass Widget {\n #comm;\n #state;\n #listeners = new Map(); // event -> Set<listener>\n\n constructor(comm, state, $display) {\n this.#comm = comm;\n this.#state = state;\n this[$display] = () => ({\n [VIEW_MIME]: { version_major: 2, version_minor: 1, model_id: this.id },\n \"text/plain\": `Widget(${this.id})`,\n });\n }\n\n get id() {\n return this.#comm.id;\n }\n\n get closed() {\n return this.#comm.closed;\n }\n\n get(key) {\n return this.#state[key];\n }\n\n /** set(\"key\", value) or set({ key: value, ... }); syncs to the frontend. */\n set(keyOrChanges, value) {\n const changes = typeof keyOrChanges === \"string\" ? { [keyOrChanges]: value } : keyOrChanges;\n this.#apply(changes);\n if (this.closed) return;\n const { state, bufferPaths, buffers } = removeBuffers(changes);\n this.#comm.send({ method: \"update\", state, buffer_paths: bufferPaths }, { buffers });\n }\n\n on(event, listener) {\n if (!this.#listeners.has(event)) this.#listeners.set(event, new Set());\n this.#listeners.get(event).add(listener);\n }\n\n off(event, listener) {\n this.#listeners.get(event)?.delete(listener);\n }\n\n /** A custom message, delivered to the view's model.on(\"msg:custom\"). */\n send(content, buffers = []) {\n this.#comm.send({ method: \"custom\", content }, { buffers });\n }\n\n close() {\n this.#comm.close();\n }\n\n /** The full state, as the frontend sees it (for request_state). */\n fullState() {\n return { ...ANYWIDGET_MODEL, ...this.#state };\n }\n\n async #emit(event, ...args) {\n for (const listener of this.#listeners.get(event) ?? []) await listener(...args);\n }\n\n async #apply(changes) {\n const previous = {};\n for (const [key, value] of Object.entries(changes)) {\n previous[key] = this.#state[key];\n this.#state[key] = value;\n }\n for (const key of Object.keys(changes)) await this.#emit(`change:${key}`, changes[key], previous[key]);\n await this.#emit(\"change\", changes);\n }\n\n async _receive(msg) {\n const { method } = msg.data;\n if (method === \"update\") {\n const changes = putBuffers(msg.data.state ?? {}, msg.data.buffer_paths, msg.buffers);\n await this.#apply(changes);\n } else if (method === \"request_state\") {\n const { state, bufferPaths, buffers } = removeBuffers(this.fullState());\n this.#comm.send({ method: \"update\", state, buffer_paths: bufferPaths }, { buffers });\n } else if (method === \"custom\") {\n await this.#emit(\"msg:custom\", msg.data.content, msg.buffers);\n }\n }\n}\n\n/**\n * @param {import(\"./comm.d.mts\").CommApi} commApi\n * @param {symbol} $display\n */\nexport function createWidgetFactory(commApi, $display) {\n const live = new Map(); // model id -> Widget\n\n // The frontend opens this comm to restore every widget's state, e.g.\n // after the page reloads.\n commApi.registerTarget(CONTROL_TARGET, (control) => {\n control.onMsg((msg) => {\n if (msg.data.method !== \"request_states\") return;\n const states = {};\n for (const widget of live.values()) {\n const full = widget.fullState();\n states[widget.id] = {\n model_name: full._model_name,\n model_module: full._model_module,\n model_module_version: full._model_module_version,\n state: full,\n };\n }\n const { state, bufferPaths, buffers } = removeBuffers(states);\n control.send({ method: \"update_states\", states: state, buffer_paths: bufferPaths }, { buffers });\n });\n });\n\n return function widget({ esm, css, state = {} } = {}) {\n if (typeof esm !== \"string\") throw new TypeError(\"jupyter.widget needs an `esm` module string\");\n const initial = { ...state };\n const full = {\n ...ANYWIDGET_MODEL,\n _esm: esm,\n ...(css === undefined ? {} : { _css: css }),\n _anywidget_id: \"cdp-kernel.widget\",\n ...initial,\n };\n const { state: wire, bufferPaths, buffers } = removeBuffers(full);\n const comm = commApi.open(WIDGET_TARGET, { state: wire, buffer_paths: bufferPaths }, {\n metadata: { version: WIDGET_PROTOCOL_VERSION },\n buffers,\n });\n const instance = new Widget(comm, { ...full }, $display);\n live.set(comm.id, instance);\n comm.onMsg((msg) => instance._receive(msg));\n comm.onClose(() => {\n live.delete(comm.id);\n });\n return instance;\n };\n}\n", "// @ts-self-types=\"./display.d.mts\"\n// The Jupyter display API that Deno exposes as `Deno.jupyter`, made\n// runtime-neutral. Runs inside the target runtime (Node or Deno).\n//\n// Ported from Deno's cli/js/40_jupyter.js (v2.9.6), which is\n// Copyright 2018-2026 the Deno authors, MIT license. The formatting rules\n// (display symbol, canvas, Vega, Polars-style DataFrames, JPEG/PNG bytes,\n// HTML/SVG elements) are unchanged; the Deno internals it used are injected:\n// Deno[Deno.internal].inspectArgs -> host.inspect\n// op_base64_encode_from_buffer -> host.base64\n// Deno.readFileSync -> host.readFile\n// op_jupyter_broadcast -> host.send\n// WebGPU texture/buffer display depends on Deno's wgpu bindings and is\n// omitted. Comms and widgets (jupyter.comm, jupyter.widget) are additions\n// Deno doesn't have; see comm.mjs and widget.mjs.\n\nimport { createComms } from \"./comm.mjs\";\nimport { createWidgetFactory } from \"./widget.mjs\";\n\nexport const $display = Symbol.for(\"Jupyter.display\");\n\nconst rawToEntity = new Map([\n [\"&\", \"&\"],\n [\"<\", \"<\"],\n [\">\", \">\"],\n ['\"', \""\"],\n [\"'\", \"'\"],\n]);\nconst rawRe = new RegExp(`[${[...rawToEntity.keys()].join(\"\")}]`, \"g\");\n\nexport function escapeHTML(str) {\n return str.replaceAll(rawRe, (m) => rawToEntity.get(m) ?? m);\n}\n\nfunction isVegaLike(obj) {\n return obj !== null && typeof obj === \"object\" && \"toSpec\" in obj;\n}\n\nfunction extractVega(obj) {\n const spec = obj.toSpec();\n if (typeof spec !== \"object\" || spec === null || !(\"$schema\" in spec)) return null;\n let mediaType = \"application/vnd.vega.v5+json\";\n if (spec.$schema === \"https://vega.github.io/schema/vega-lite/v4.json\") {\n mediaType = \"application/vnd.vegalite.v4+json\";\n } else if (spec.$schema === \"https://vega.github.io/schema/vega-lite/v5.json\") {\n mediaType = \"application/vnd.vegalite.v5+json\";\n }\n const summary = summarizeChart(spec);\n return summary === undefined ? { [mediaType]: spec } : { [mediaType]: spec, \"text/plain\": summary };\n}\n\n// A few lines of text/plain next to a chart, for frontends that can't draw\n// it (jupyter console, nbconvert to text, agents reading the notebook):\n// mark, encodings with value ranges, title and row count (#321). The\n// approach follows nteract's repr-llm summarize_viz (BSD-3).\nconst VL_TYPES = { Q: \"quantitative\", N: \"nominal\", O: \"ordinal\", T: \"temporal\", G: \"geojson\" };\nconst MAX_CHILDREN = 6;\n\nfunction clip(str, max = 60) {\n return str.length > max ? `${str.slice(0, max - 1)}\u2026` : str;\n}\n\nfunction formatNumber(n) {\n return Number.isInteger(n) ? String(n) : String(Number(n.toPrecision(4)));\n}\n\nfunction titleText(title) {\n const text = typeof title === \"object\" && title !== null && !Array.isArray(title) ? title.text : title;\n const str = Array.isArray(text) ? text.join(\" \") : typeof text === \"string\" ? text : \"\";\n return str ? ` \"${clip(str, 80)}\"` : \"\";\n}\n\nfunction getField(row, field) {\n if (row === null || typeof row !== \"object\") return undefined;\n if (field in row) return row[field];\n // Vega-Lite reads \"a.b\" as a nested path and \"a\\.b\" as a key with a dot.\n if (field.includes(\"\\\\\")) return row[field.replace(/\\\\(.)/g, \"$1\")];\n return field.split(\".\").reduce((obj, key) => (obj === null || typeof obj !== \"object\" ? undefined : obj[key]), row);\n}\n\nfunction fieldStats(rows, field, type) {\n const values = [];\n for (const row of rows) {\n const value = getField(row, field);\n if (value !== undefined && value !== null && value !== \"\") values.push(value);\n }\n if (values.length === 0) return \"\";\n if (type === \"quantitative\") {\n let min = Infinity;\n let max = -Infinity;\n for (const value of values) {\n const n = Number(value);\n if (!Number.isFinite(n)) continue;\n if (n < min) min = n;\n if (n > max) max = n;\n }\n if (min > max) return \"\";\n return min === max ? formatNumber(min) : `${formatNumber(min)} to ${formatNumber(max)}`;\n }\n if (type === \"temporal\") {\n let min;\n let max;\n for (const value of values) {\n const t = value instanceof Date ? value.getTime() : typeof value === \"number\" ? value : Date.parse(String(value));\n if (!Number.isFinite(t)) continue;\n if (min === undefined || t < min.t) min = { t, value };\n if (max === undefined || t > max.t) max = { t, value };\n }\n if (min === undefined) return \"\";\n const show = ({ value }) =>\n typeof value === \"string\" ? clip(value, 30) : new Date(value instanceof Date ? value.getTime() : value).toISOString();\n return min.t === max.t ? show(min) : `${show(min)} to ${show(max)}`;\n }\n const distinct = new Set(values.map((value) => typeof value === \"object\" ? JSON.stringify(value) : String(value)));\n return `${distinct.size} ${distinct.size === 1 ? \"value\" : \"values\"}`;\n}\n\nfunction encodingSummary(encoding, rows) {\n const parts = [];\n for (const [channel, def] of Object.entries(encoding)) {\n if (channel === \"tooltip\" || def === null || typeof def !== \"object\" || Array.isArray(def)) continue;\n if (def.field === undefined && def.aggregate === undefined) continue;\n let name = typeof def.field === \"string\" ? def.field : def.field?.repeat ? `repeat ${def.field.repeat}` : \"\";\n if (def.aggregate !== undefined) name = `${def.aggregate}(${name})`;\n else if (def.timeUnit !== undefined) name = `${typeof def.timeUnit === \"string\" ? def.timeUnit : \"time\"}(${name})`;\n const type = VL_TYPES[def.type] ?? def.type;\n const details = [];\n if (typeof type === \"string\") details.push(type);\n if (rows && typeof def.field === \"string\" && def.aggregate === undefined) {\n const stats = fieldStats(rows, def.field, type);\n if (stats) details.push(stats);\n }\n parts.push(`${channel}=${clip(name, 40)}${details.length ? ` (${details.join(\", \")})` : \"\"}`);\n }\n return parts;\n}\n\nfunction vlRows(data, datasets) {\n if (data === null || typeof data !== \"object\") return undefined;\n if (Array.isArray(data.values)) return data.values;\n if (typeof data.name === \"string\" && Array.isArray(datasets?.[data.name])) return datasets[data.name];\n return undefined;\n}\n\nfunction vlDataNote(data, rows) {\n if (rows) return `${rows.length} ${rows.length === 1 ? \"row\" : \"rows\"}`;\n if (typeof data?.url === \"string\") return `data from ${clip(data.url)}`;\n return \"\";\n}\n\nfunction fieldList(def) {\n if (Array.isArray(def)) return def.join(\", \");\n if (def === null || typeof def !== \"object\") return \"\";\n if (typeof def.field === \"string\") return def.field;\n return Object.values(def).map(fieldList).filter(Boolean).join(\", \");\n}\n\nfunction summarizeVegaLiteView(spec, label, inherited, datasets, depth, lines) {\n const indent = \" \".repeat(depth);\n const data = spec.data ?? inherited.data;\n const rows = vlRows(data, datasets);\n const head = `${indent}${label}`;\n const title = titleText(spec.title);\n const children = spec.layer ?? spec.concat ?? spec.hconcat ?? spec.vconcat;\n if (Array.isArray(children)) {\n const noun = spec.layer ? \"layer\" : \"view\";\n const note = [`${children.length} ${children.length === 1 ? noun : `${noun}s`}`, vlDataNote(data, rows)].filter(Boolean);\n lines.push(`${head}${spec.layer ? \"layered\" : \"concatenated\"} chart${title}: ${note.join(\", \")}`);\n const encoding = spec.layer ? { ...inherited.encoding, ...spec.encoding } : {};\n children.slice(0, MAX_CHILDREN).forEach((child, i) => {\n if (child !== null && typeof child === \"object\") {\n summarizeVegaLiteView(child, `${noun} ${i + 1}: `, { data, encoding }, datasets, depth + 1, lines);\n }\n });\n if (children.length > MAX_CHILDREN) lines.push(`${indent} \u2026 ${children.length - MAX_CHILDREN} more`);\n return;\n }\n if ((spec.facet !== undefined || spec.repeat !== undefined) && spec.spec !== null && typeof spec.spec === \"object\") {\n const what = spec.facet !== undefined ? `faceted by ${fieldList(spec.facet)}` : `repeated over ${fieldList(spec.repeat)}`;\n const note = vlDataNote(data, rows);\n lines.push(`${head}chart${title} ${what}${note ? `, ${note}` : \"\"}`);\n summarizeVegaLiteView(spec.spec, \"each panel: \", { data, encoding: {} }, datasets, depth + 1, lines);\n return;\n }\n const mark = typeof spec.mark === \"string\" ? spec.mark : spec.mark?.type;\n const encoding = { ...inherited.encoding, ...spec.encoding };\n const parts = encodingSummary(encoding, rows);\n // A layer's rows were already counted on the layered chart's line.\n if (spec.data !== undefined || depth === 0) {\n const note = vlDataNote(data, rows);\n if (note) parts.push(note);\n }\n lines.push(`${head}${typeof mark === \"string\" ? `${mark} ` : \"\"}chart${title}${parts.length ? `: ${parts.join(\", \")}` : \"\"}`);\n}\n\nfunction vegaMarkTypes(marks, types) {\n if (!Array.isArray(marks)) return types;\n for (const mark of marks) {\n if (typeof mark?.type === \"string\") types.add(mark.type);\n vegaMarkTypes(mark?.marks, types);\n }\n return types;\n}\n\nfunction summarizeVega(spec) {\n const sections = [];\n const marks = [...vegaMarkTypes(spec.marks, new Set())];\n if (marks.length) sections.push(`marks ${marks.join(\", \")}`);\n const list = (items, describe) => {\n const shown = items.slice(0, MAX_CHILDREN).map(describe);\n if (items.length > MAX_CHILDREN) shown.push(`\u2026 ${items.length - MAX_CHILDREN} more`);\n return shown.join(\", \");\n };\n const data = Array.isArray(spec.data) ? spec.data.filter((d) => d !== null && typeof d === \"object\") : [];\n if (data.length) {\n sections.push(`data ${list(data, (d) => {\n const name = clip(String(d.name ?? \"?\"), 30);\n if (Array.isArray(d.values)) return `${name} (${d.values.length} ${d.values.length === 1 ? \"row\" : \"rows\"})`;\n if (typeof d.url === \"string\") return `${name} (from ${clip(d.url)})`;\n if (d.source !== undefined) return `${name} (from ${clip(String(d.source), 30)})`;\n return name;\n })}`);\n }\n const scales = Array.isArray(spec.scales) ? spec.scales.filter((s) => s !== null && typeof s === \"object\") : [];\n if (scales.length) {\n sections.push(`scales ${list(scales, (s) => `${clip(String(s.name ?? \"?\"), 30)} (${s.type ?? \"linear\"})`)}`);\n }\n return `Vega chart${titleText(spec.title)}${sections.length ? `: ${sections.join(\"; \")}` : \"\"}`;\n}\n\nfunction summarizeChart(spec) {\n try {\n if (typeof spec.$schema === \"string\" && spec.$schema.includes(\"/vega-lite/\")) {\n const lines = [];\n summarizeVegaLiteView(spec, \"Vega-Lite \", { encoding: {} }, spec.datasets, 0, lines);\n return lines.join(\"\\n\");\n }\n return summarizeVega(spec);\n } catch {\n // A summary is a fallback; a spec it doesn't understand still renders.\n return undefined;\n }\n}\n\nfunction isDataFrameLike(obj) {\n return obj !== null && typeof obj === \"object\" &&\n obj.schema !== undefined && typeof obj.schema === \"object\" &&\n typeof obj.head === \"function\" && typeof obj.toRecords === \"function\";\n}\n\nfunction mapPolarsTypeToJSONSchema(colType) {\n const typeMapping = {\n Null: \"null\",\n Bool: \"boolean\",\n Int8: \"integer\",\n Int16: \"integer\",\n Int32: \"integer\",\n Int64: \"integer\",\n UInt8: \"integer\",\n UInt16: \"integer\",\n UInt32: \"integer\",\n UInt64: \"integer\",\n Float32: \"number\",\n Float64: \"number\",\n Date: \"string\",\n Datetime: \"string\",\n Utf8: \"string\",\n Categorical: \"string\",\n List: \"array\",\n Struct: \"object\",\n };\n // Polars DataTypes only expose their name through toJSON().\n const dataType = typeof colType?.toJSON === \"function\" ? colType.toJSON()[\"DataType\"] : undefined;\n return typeMapping[dataType] || \"string\";\n}\n\nfunction extractDataFrame(df) {\n const fields = [];\n for (const [name, colType] of Object.entries(df.schema)) {\n fields.push({ name, type: mapPolarsTypeToJSONSchema(colType) });\n }\n const data = df.head(50).toRecords();\n let html = \"<table><thead><tr>\";\n for (const field of fields) html += `<th>${escapeHTML(String(field.name))}</th>`;\n html += \"</tr></thead><tbody>\";\n for (const row of df.head(10).toRecords()) {\n html += \"<tr>\";\n for (const field of fields) html += `<td>${escapeHTML(String(row[field.name]))}</td>`;\n html += \"</tr>\";\n }\n html += \"</tbody></table>\";\n // Polars has `height`; the row count is left out when there isn't one.\n const size = [];\n if (Number.isInteger(df.height)) size.push(`${df.height} ${df.height === 1 ? \"row\" : \"rows\"}`);\n size.push(`${fields.length} ${fields.length === 1 ? \"column\" : \"columns\"}`);\n const columns = fields.slice(0, 20).map((field) => `${clip(String(field.name), 40)} (${field.type})`);\n if (fields.length > 20) columns.push(`\u2026 ${fields.length - 20} more`);\n return {\n \"application/vnd.dataresource+json\": { data, schema: { fields } },\n \"text/html\": html,\n \"text/plain\": `DataFrame (${size.join(\", \")})${columns.length ? `: ${columns.join(\", \")}` : \"\"}`,\n };\n}\n\nfunction isCanvasLike(obj) {\n return obj !== null && typeof obj === \"object\" && \"toDataURL\" in obj;\n}\n\nexport function isJpg(obj) {\n return obj instanceof Uint8Array && obj.length >= 4 &&\n obj[0] === 0xff && obj[1] === 0xd8 &&\n obj[obj.length - 2] === 0xff && obj[obj.length - 1] === 0xd9;\n}\n\nconst PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];\n\nexport function isPng(obj) {\n return obj instanceof Uint8Array && obj.length >= PNG_SIGNATURE.length &&\n PNG_SIGNATURE.every((byte, i) => obj[i] === byte);\n}\n\nfunction isSVGElementLike(obj) {\n return obj !== null && typeof obj === \"object\" && typeof obj.outerHTML === \"string\" &&\n obj.outerHTML.startsWith(\"<svg\");\n}\n\nfunction isHTMLElementLike(obj) {\n return obj !== null && typeof obj === \"object\" && typeof obj.outerHTML === \"string\";\n}\n\nfunction hasDisplaySymbol(obj) {\n return obj !== null && typeof obj === \"object\" && typeof obj[$display] === \"function\";\n}\n\nfunction isMediaBundle(obj) {\n return obj !== null && typeof obj === \"object\" && !Array.isArray(obj);\n}\n\n/**\n * @param {{\n * inspect: (value: unknown) => string,\n * base64: (bytes: Uint8Array) => string,\n * readFile: (path: string) => Uint8Array,\n * send: (msgType: string, content: object, metadata: object, buffers: Uint8Array[]) => void,\n * input: (prompt: string, password: boolean) => string | null,\n * }} host\n */\nexport function createJupyter(host) {\n async function format(obj) {\n return await formatNow(obj);\n }\n\n // format without awaiting: the debugger's variable viewer formats values\n // while the target is paused, when no promise settles (#18). A $display\n // method's promise is the caller's to handle.\n function formatNow(obj) {\n if (hasDisplaySymbol(obj)) return obj[$display]();\n if (typeof obj !== \"object\" || obj === null) return { \"text/plain\": host.inspect(obj) };\n if (isCanvasLike(obj)) {\n const [prefix, data] = obj.toDataURL().split(\",\");\n return { [prefix.split(\":\")[1].split(\";\")[0]]: data };\n }\n if (isVegaLike(obj)) {\n const vega = extractVega(obj);\n if (vega) return vega;\n }\n if (isDataFrameLike(obj)) return extractDataFrame(obj);\n if (isJpg(obj)) return { \"image/jpeg\": host.base64(obj) };\n if (isPng(obj)) return { \"image/png\": host.base64(obj) };\n if (isSVGElementLike(obj)) return { \"image/svg+xml\": obj.outerHTML };\n if (isHTMLElementLike(obj)) return { \"text/html\": obj.outerHTML };\n return { \"text/plain\": host.inspect(obj) };\n }\n\n function taggedTemplate(mediatype) {\n return (strings, ...values) => {\n const payload = strings.reduce((acc, string, i) =>\n acc + string + (values[i] !== undefined ? values[i] : \"\"), \"\");\n return { [$display]: () => ({ [mediatype]: payload }) };\n };\n }\n\n function image(obj) {\n if (typeof obj === \"string\") {\n // As Deno does: a path that can't be read gets the TypeError below.\n try {\n obj = host.readFile(obj);\n } catch {\n // fall through\n }\n }\n if (isJpg(obj)) return { [$display]: () => ({ \"image/jpeg\": host.base64(obj) }) };\n if (isPng(obj)) return { [$display]: () => ({ \"image/png\": host.base64(obj) }) };\n throw new TypeError(\n \"Object is not a valid image or a path to an image. `jupyter.image` supports displaying JPG or PNG images.\",\n );\n }\n\n function broadcast(msgType, content, { metadata = {}, buffers = [] } = {}) {\n host.send(msgType, content, metadata, buffers);\n }\n\n async function display(obj, options = { raw: false, update: false }) {\n const bundle = options.raw && isMediaBundle(obj) ? obj : await format(obj);\n broadcast(options.update ? \"update_display_data\" : \"display_data\", {\n data: bundle,\n metadata: {},\n transient: options.display_id ? { display_id: options.display_id } : {},\n });\n }\n\n async function broadcastResult(executionCount, result) {\n if (result === undefined) return;\n try {\n broadcast(\"execute_result\", {\n execution_count: executionCount,\n data: await format(result),\n metadata: {},\n // nbclient crashes on a null `transient`; Deno learned this too.\n transient: {},\n });\n } catch (err) {\n broadcast(\"error\", {\n ename: err instanceof Error ? err.name : \"Error\",\n evalue: err instanceof Error ? err.message : String(err),\n traceback: err instanceof Error && err.stack ? err.stack.split(\"\\n\") : [],\n });\n }\n }\n\n function confirm(message = \"Confirm\") {\n const answer = host.input(`${message} [y/N] `, false);\n return answer === \"Y\" || answer === \"y\";\n }\n\n function prompt(message = \"Prompt\", defaultValue = \"\", { password = false } = {}) {\n if (defaultValue != \"\") message += ` [${defaultValue}]`;\n const answer = host.input(message, password);\n return answer === \"\" ? defaultValue : answer;\n }\n\n const comms = createComms((msgType, content, metadata, buffers) => host.send(msgType, content, metadata, buffers));\n\n return {\n namespace: {\n broadcast,\n display,\n format,\n md: taggedTemplate(\"text/markdown\"),\n html: taggedTemplate(\"text/html\"),\n svg: taggedTemplate(\"image/svg+xml\"),\n image,\n $display,\n comm: comms.api,\n widget: createWidgetFactory(comms.api, $display),\n },\n broadcastResult,\n formatNow,\n confirm,\n prompt,\n commDispatch: comms.dispatch,\n };\n}\n", "// The in-process evaluator behind the targets that don't use CDP: Bun (#7),\n// over a pipe (bun-channel.mjs), and workerd (#8), inside a request\n// (workerd-worker.mjs). Cells arrive as global code from\n// src/transform.ts's transformCellForEval, whose value is a promise of the\n// boxed result. Requests and replies mirror the CDP calls the kernel makes\n// of the other targets.\n//\n// No imports: this file must load in every target.\n\n/** Own and inherited property names, as Runtime.getProperties lists them. */\nexport function propertyNames(value) {\n if (value === null || value === undefined) return [];\n const names = new Set();\n for (let o = Object(value); o !== null; o = Object.getPrototypeOf(o)) {\n for (const name of Object.getOwnPropertyNames(o)) names.add(name);\n }\n return [...names];\n}\n\n/**\n * Answers the host's requests. `shim` is globalThis.__cdpk; `evaluate` runs\n * global code. Values the host refers to later (a result to display, an\n * error to describe) stay here under a handle, the stand-in for a CDP\n * objectId.\n */\nexport function createHandler(shim, evaluate = (code) => (0, eval)(code)) {\n const handles = new Map();\n let nextHandle = 0;\n const remote = (value) => {\n const objectId = `h${++nextHandle}`;\n handles.set(objectId, value);\n return { type: value === null ? \"object\" : typeof value, objectId };\n };\n const take = (objectId) => {\n const value = handles.get(objectId);\n handles.delete(objectId);\n return value;\n };\n\n return async function handle(request) {\n switch (request.op) {\n case \"ping\":\n return {};\n case \"eval\": {\n // The host uses a result's handle before its next cell.\n handles.clear();\n try {\n const box = await evaluate(request.code);\n return { result: box === undefined ? { type: \"undefined\" } : remote(box[0]) };\n } catch (err) {\n return {\n exceptionDetails: { text: \"Uncaught\", lineNumber: 0, columnNumber: 0, exception: remote(err) },\n };\n }\n }\n case \"broadcast\":\n await shim.broadcastResult(request.count, take(request.handle));\n return {};\n case \"describe\":\n return { value: shim.describeError(take(request.handle)) };\n case \"comm\":\n try {\n const handled = await shim.commDispatch(request.msgType, request.content, request.metadata, request.buffers);\n return { handled: handled === true };\n } catch (err) {\n return { error: JSON.parse(shim.describeError(err)) };\n }\n case \"props\": {\n // Completion's expression is a dotted path; resolved by descriptor\n // where the shim can, so completing `obj.` never runs a getter (#10).\n if (typeof shim.resolvePath === \"function\") {\n const resolved = shim.resolvePath(request.expr);\n return { names: resolved.found && !resolved.accessor ? propertyNames(resolved.value) : [] };\n }\n let value;\n try {\n value = evaluate(`(${request.expr})`);\n } catch {\n return { names: [] };\n }\n return { names: propertyNames(value) };\n }\n case \"inspect\":\n return { text: shim.inspectPath(request.path, request.detail ?? 0) };\n case \"barrier\":\n return { value: shim.barrier() };\n default:\n throw new Error(`unknown request ${JSON.stringify(request.op)}`);\n }\n };\n}\n", "// A small stand-in for util.inspect and util.format, for targets that have\n// neither: the browser Worker (runtime/browser-worker.mjs). Output follows\n// Node's for the common cases (strings quoted when nested, objects and\n// arrays on one line, Map, Set, Date, Error, class names, circular\n// references), without colours.\n//\n// No imports: this file must load in every target.\n\nconst MAX_ITEMS = 100;\n\n// Single quotes, unless the string has some and double quotes or\n// backticks would need no escapes, as util.inspect picks.\nfunction quote(s) {\n const q = !s.includes(\"'\") ? \"'\" : !s.includes('\"') ? '\"' : !s.includes(\"`\") && !s.includes(\"${\") ? \"`\" : \"'\";\n const escaped = s.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"\\n\", \"\\\\n\").replaceAll(q, `\\\\${q}`);\n return `${q}${escaped}${q}`;\n}\n\nfunction key(k) {\n return typeof k === \"symbol\" ? `[${k.toString()}]` : /^[A-Za-z_$][\\w$]*$/.test(k) ? k : quote(k);\n}\n\nfunction className(value) {\n const proto = Object.getPrototypeOf(value);\n if (proto === null) return \"[Object: null prototype]\";\n const name = proto.constructor?.name;\n return name && name !== \"Object\" ? name : \"\";\n}\n\nfunction list(open, items, close, more) {\n if (more > 0) items.push(`... ${more} more item${more === 1 ? \"\" : \"s\"}`);\n return items.length === 0 ? `${open}${close}` : `${open} ${items.join(\", \")} ${close}`;\n}\n\n/** `value` as Node's util.inspect would show it, to `depth` levels. */\nexport function inspect(value, { depth = 2 } = {}) {\n const seen = [];\n const show = (v, level) => {\n switch (typeof v) {\n case \"string\":\n return quote(v);\n case \"bigint\":\n return `${v}n`;\n case \"symbol\":\n return v.toString();\n case \"undefined\":\n return \"undefined\";\n case \"function\": {\n const isClass = /^class\\b/.test(Function.prototype.toString.call(v));\n return isClass ? `[class ${v.name || \"(anonymous)\"}]` : `[Function${v.name ? `: ${v.name}` : \" (anonymous)\"}]`;\n }\n case \"number\":\n return Object.is(v, -0) ? \"-0\" : String(v);\n case \"boolean\":\n return String(v);\n }\n if (v === null) return \"null\";\n if (seen.includes(v)) return \"[Circular *1]\";\n if (v instanceof Date) return Number.isNaN(v.getTime()) ? \"Invalid Date\" : v.toISOString();\n if (v instanceof RegExp) return String(v);\n if (v instanceof Error) return v.stack ?? `${v.name}: ${v.message}`;\n if (v instanceof Promise) return \"Promise { <unknown> }\";\n if (level > depth) return Array.isArray(v) ? \"[Array]\" : `[${className(v) || \"Object\"}]`;\n seen.push(v);\n try {\n if (Array.isArray(v) || ArrayBuffer.isView(v)) {\n const items = Array.from(v).slice(0, MAX_ITEMS).map((x) => show(x, level + 1));\n const prefix = Array.isArray(v) ? \"\" : `${v.constructor.name}(${v.length}) `;\n return prefix + list(\"[\", items, \"]\", v.length - items.length);\n }\n if (v instanceof Map) {\n const items = [...v].slice(0, MAX_ITEMS).map(([k, x]) => `${show(k, level + 1)} => ${show(x, level + 1)}`);\n return `Map(${v.size}) ` + list(\"{\", items, \"}\", v.size - items.length);\n }\n if (v instanceof Set) {\n const items = [...v].slice(0, MAX_ITEMS).map((x) => show(x, level + 1));\n return `Set(${v.size}) ` + list(\"{\", items, \"}\", v.size - items.length);\n }\n const keys = Reflect.ownKeys(v).filter((k) => Object.getOwnPropertyDescriptor(v, k)?.enumerable);\n const items = keys.slice(0, MAX_ITEMS).map((k) => {\n const d = Object.getOwnPropertyDescriptor(v, k);\n const shown = d.get || d.set ? `[${d.get ? \"Getter\" : \"\"}${d.get && d.set ? \"/\" : \"\"}${d.set ? \"Setter\" : \"\"}]` : show(d.value, level + 1);\n return `${key(k)}: ${shown}`;\n });\n const name = className(v);\n return (name ? `${name} ` : \"\") + list(\"{\", items, \"}\", keys.length - items.length);\n } finally {\n seen.pop();\n }\n };\n return show(value, 0);\n}\n\n/** console.log's formatting: strings as they are, everything else inspected, %s/%d/%i/%f/%o/%O/%j substituted. */\nexport function format(...args) {\n let out = [];\n let rest = args;\n if (typeof args[0] === \"string\" && args.length > 1 && args[0].includes(\"%\")) {\n let i = 1;\n const text = args[0].replace(/%[sdifoOjc%]/g, (spec) => {\n if (spec === \"%%\") return \"%\";\n if (i >= args.length) return spec;\n const a = args[i++];\n switch (spec) {\n case \"%s\":\n return typeof a === \"string\" ? a : inspect(a, { depth: 1 });\n case \"%d\":\n case \"%i\":\n return typeof a === \"bigint\" ? `${a}n` : String(spec === \"%i\" ? Math.trunc(Number(a)) : Number(a));\n case \"%f\":\n return String(Number(a));\n case \"%j\":\n return JSON.stringify(a);\n case \"%c\":\n return \"\";\n default:\n return inspect(a, { depth: 4 });\n }\n });\n out = [text];\n rest = args.slice(i);\n }\n for (const a of rest) out.push(typeof a === \"string\" ? a : inspect(a));\n return out.join(\" \");\n}\n", "// What inspect_request (#10) shows for a value: the text of a JupyterLab\n// tooltip (Shift-Tab) or inspector panel. Shared by every target; the host\n// decides how the value is found (src/target.ts: CDP's throwOnSideEffect;\n// in-process targets: resolvePath, below).\n//\n// No imports: this file must load in every target. `inspect` (util.inspect\n// or Deno.inspect) is passed in.\n\nconst PREVIEW_CHARS = 1500;\nconst SOURCE_CHARS = 4000;\nconst MAX_PROPERTIES = 40;\n\nconst IDENTIFIER_PATH = /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)*$/;\n\n/**\n * Looks up a dotted path such as \"a.b.c\" from globalThis, by property\n * descriptor, so nothing runs: a getter along the way is reported rather\n * than called. In-process targets (Bun, workerd, celld) have no way to\n * evaluate without side effects, so inspection and completion use this.\n */\nexport function resolvePath(path, root = globalThis) {\n if (!IDENTIFIER_PATH.test(path)) return { found: false };\n let value = root;\n for (const name of path.split(\".\")) {\n if (value === null || value === undefined) return { found: false };\n let descriptor;\n for (let o = Object(value); o !== null && descriptor === undefined; o = Object.getPrototypeOf(o)) {\n descriptor = Object.getOwnPropertyDescriptor(o, name);\n }\n if (descriptor === undefined) return { found: false };\n if (!(\"value\" in descriptor)) return { found: true, accessor: true, name };\n value = descriptor.value;\n }\n return { found: true, value };\n}\n\nfunction truncate(text, limit) {\n return text.length > limit ? `${text.slice(0, limit)}\u2026 (${text.length - limit} more characters)` : text;\n}\n\n/** \"function add(a, b) {...}\" -> \"add(a, b)\"; \"class K {...}\" -> \"class K\". */\nexport function signatureOf(fn) {\n let source;\n try {\n source = Function.prototype.toString.call(fn);\n } catch {\n return `${fn.name || \"anonymous\"}(\u2026)`;\n }\n if (/^class\\b/.test(source)) return `class ${fn.name || \"(anonymous)\"}`;\n const params = /^[^(]*\\(([^)]*)\\)/.exec(source)?.[1];\n const native = /\\{\\s*\\[native code\\]\\s*\\}$/.test(source);\n // One line, however the parameters were spread over the source.\n const written = (params ?? \"\").replace(/\\s+/g, \" \").replace(/\\s*,\\s*/g, \", \").trim();\n const args = native ? Array.from({ length: fn.length }, (_, i) => `arg${i}`).join(\", \") : written;\n const arrow = !/^(?:async\\s+)?function\\b/.test(source) && /=>/.test(source.split(\"{\")[0] ?? \"\");\n const name = fn.name || (arrow ? \"(arrow function)\" : \"anonymous\");\n const prefix = /^async\\b/.test(source) ? \"async \" : \"\";\n return `${prefix}${name}(${args})`;\n}\n\nfunction typeOf(value) {\n if (value === null) return \"null\";\n if (typeof value !== \"object\" && typeof value !== \"function\") return typeof value;\n const name = Object.getPrototypeOf(value)?.constructor?.name;\n if (typeof value === \"function\") return /^class\\b/.test(safeSource(value)) ? \"class\" : \"function\";\n return name && name !== \"Object\" ? `object (${name})` : \"object\";\n}\n\nfunction safeSource(fn) {\n try {\n return Function.prototype.toString.call(fn);\n } catch {\n return \"\";\n }\n}\n\nfunction propertyNames(value) {\n if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return [];\n try {\n // A function's own internals aren't worth listing; older V8 (Node 22 and 24)\n // also gives sloppy-mode functions own `arguments` and `caller`.\n const internal = [\"length\", \"name\", \"prototype\", \"arguments\", \"caller\"];\n return Object.getOwnPropertyNames(value).filter((n) => !(typeof value === \"function\" && internal.includes(n)));\n } catch {\n return [];\n }\n}\n\n/**\n * The tooltip text for a value. `detail` 1 (Shift-Tab twice, or the\n * inspector panel) adds a function's source.\n */\nexport function describeValue(value, { inspect, detail = 0 }) {\n const lines = [`Type: ${typeOf(value)}`];\n if (typeof value === \"function\") lines.push(`Signature: ${signatureOf(value)}`);\n let preview;\n try {\n preview = inspect(value);\n } catch (err) {\n preview = `(inspect failed: ${err instanceof Error ? err.message : String(err)})`;\n }\n lines.push(`Value: ${truncate(preview, PREVIEW_CHARS)}`);\n const names = propertyNames(value);\n if (names.length > 0) {\n const shown = names.slice(0, MAX_PROPERTIES).join(\", \");\n lines.push(`Properties: ${shown}${names.length > MAX_PROPERTIES ? `, \u2026 (${names.length - MAX_PROPERTIES} more)` : \"\"}`);\n }\n if (detail > 0 && typeof value === \"function\") lines.push(`Source:\\n${truncate(safeSource(value), SOURCE_CHARS)}`);\n return lines.join(\"\\n\");\n}\n\n/** inspect_request for in-process targets: resolvePath, then describeValue. */\nexport function inspectPath(path, { inspect, detail = 0, root = globalThis }) {\n const resolved = resolvePath(path, root);\n if (!resolved.found) return null;\n if (resolved.accessor) {\n return `Type: accessor property\\n${resolved.name} has a getter, which isn't called for inspection: it could have side effects.`;\n }\n return describeValue(resolved.value, { inspect, detail });\n}\n", "// Where a browser cell's imports load from. A Worker resolves only URLs, so\n// packages come from a CDN that serves npm and jsr as ES modules: esm.sh by\n// default, with its jsr/ prefix for jsr packages.\n//\n// No imports: this file must load in every target.\n\nexport const DEFAULT_CDN = \"https://esm.sh/\";\n\n/** The URL `specifier`, imported from `base`, loads from. */\nexport function resolveSpecifier(specifier, base, cdn = DEFAULT_CDN) {\n if (/^(?:https?|data|blob):/.test(specifier)) return specifier;\n if (/^\\.{0,2}\\//.test(specifier)) return new URL(specifier, base).href;\n if (specifier.startsWith(\"npm:\")) return cdn + specifier.slice(4);\n if (specifier.startsWith(\"jsr:\")) return `${cdn}jsr/${specifier.slice(4).replace(/^\\//, \"\")}`;\n // esm.sh serves polyfills for Node's builtins under node:.\n return cdn + specifier;\n}\n", "// The driver for the browser target: a module Web Worker that runs cells.\n//\n// The page's kernel (src/browser/target.ts) sends each request as a\n// message and gets a reply message back, as over the workerd driver's\n// WebSocket (runtime/workerd-worker.mjs), whose shape this follows. Cells\n// come from transformCellForEval and run as global code with indirect\n// eval, so their declarations persist from cell to cell.\n//\n// A Worker has no module resolution beyond URLs, so `npm:` and `jsr:`\n// specifiers, and bare package names, load from a CDN (esm.sh by default).\n\nimport { createJupyter } from \"./display.mjs\";\nimport { createHandler } from \"./evaluator.mjs\";\nimport { format, inspect } from \"./format.mjs\";\nimport { describeValue, inspectPath, resolvePath } from \"./introspect.mjs\";\nimport { DEFAULT_CDN, resolveSpecifier } from \"./cdn.mjs\";\n\nfunction base64(bytes) {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return btoa(binary);\n}\n\nconst post = (message) => globalThis.postMessage(message);\n\n// --- Output -----------------------------------------------------------------\nconst stream = (name) => (...args) => post({ kind: \"stream\", name, text: format(...args) + \"\\n\" });\nObject.assign(console, {\n log: stream(\"stdout\"),\n info: stream(\"stdout\"),\n debug: stream(\"stdout\"),\n dir: (value) => post({ kind: \"stream\", name: \"stdout\", text: inspect(value, { depth: 4 }) + \"\\n\" }),\n warn: stream(\"stderr\"),\n error: stream(\"stderr\"),\n});\n\n// An error thrown later by a cell's timer or promise goes to stderr, as on\n// the other targets.\nfunction reportUncaught(kind, err) {\n post({ kind: \"stream\", name: \"stderr\", text: `${kind}: ${err instanceof Error ? (err.stack ?? err.message) : inspect(err)}\\n` });\n}\nglobalThis.addEventListener(\"unhandledrejection\", (event) => {\n event.preventDefault();\n reportUncaught(\"Uncaught (in promise)\", event.reason);\n});\nglobalThis.addEventListener(\"error\", (event) => {\n event.preventDefault();\n reportUncaught(\"Uncaught\", event.error ?? event.message);\n});\n\nconst jupyter = createJupyter({\n inspect: (value) => inspect(value, { depth: 4 }),\n base64,\n readFile() {\n throw new Error(\"the browser target has no file system to read from; pass the image bytes instead\");\n },\n send(msgType, content, metadata, buffers) {\n post({ kind: \"iopub\", msg_type: msgType, content, metadata, buffers: buffers.map(base64), barrier: 0 });\n },\n // A synchronous prompt would need SharedArrayBuffer and Atomics.wait, so\n // a cross-origin isolated page; until then, as with no stdin.\n input: () => null,\n});\n\n// --- Modules ----------------------------------------------------------------\nlet cdn = DEFAULT_CDN;\n\n\n// --- The shim cells and the evaluator use -----------------------------------\nlet handle = null;\n\nfunction install({ base, cdn: cdnBase }) {\n if (typeof cdnBase === \"string\") cdn = cdnBase.endsWith(\"/\") ? cdnBase : cdnBase + \"/\";\n const url = new URL(\"$cdpk$repl.mjs\", base).href;\n globalThis.__cdpk = {\n import: (specifier, options) => import(resolveSpecifier(specifier, url, cdn), options),\n meta: { url, resolve: (specifier) => resolveSpecifier(specifier, url, cdn) },\n // inspect_request (#10): by descriptor, so nothing runs.\n describeForInspect: (value, detail) => describeValue(value, { inspect: (v) => inspect(v, { depth: 2 }), detail }),\n inspectPath: (path, detail) => inspectPath(path, { inspect: (v) => inspect(v, { depth: 2 }), detail }),\n resolvePath,\n barrier: () => 0,\n broadcastResult: jupyter.broadcastResult,\n async commDispatch(msgType, content, metadata, buffers64) {\n const buffers = buffers64.map((b) => Uint8Array.from(atob(b), (c) => c.charCodeAt(0)));\n return await jupyter.commDispatch(msgType, content, metadata, buffers);\n },\n describeError(value) {\n if (value instanceof Error) {\n return JSON.stringify({ name: value.name, message: value.message, stack: value.stack ?? \"\" });\n }\n return JSON.stringify({ name: \"Error\", message: inspect(value), stack: \"\" });\n },\n };\n Object.defineProperty(globalThis, \"__cdpk\", { enumerable: false });\n globalThis.jupyter = jupyter.namespace;\n globalThis.prompt = jupyter.prompt;\n globalThis.confirm = jupyter.confirm;\n handle = createHandler(globalThis.__cdpk, (code) => (0, eval)(code));\n}\n\nasync function answer(req) {\n if (req.op === \"info\") {\n install(req);\n return { userAgent: globalThis.navigator?.userAgent ?? \"\" };\n }\n if (handle === null) throw new Error(\"the driver wasn't sent info first\");\n return await handle(req);\n}\n\nglobalThis.addEventListener(\"message\", (event) => {\n const req = event.data;\n answer(req).then(\n (reply) => post({ kind: \"reply\", id: req.id, ...reply }),\n (err) => post({ kind: \"reply\", id: req.id, failure: String(err?.stack ?? err) }),\n );\n});\n"],
|
|
5
|
+
"mappings": ";AAWA,IAAM,OAAN,MAAW;AAAA,EACT;AAAA,EACA;AAAA,EACA,eAAe,CAAC;AAAA,EAChB,iBAAiB,CAAC;AAAA,EAClB,SAAS;AAAA,EAET,YAAY,IAAI,YAAY,MAAM,UAAU;AAC1C,SAAK,KAAK;AACV,SAAK,aAAa;AAClB,SAAK,QAAQ;AACb,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,KAAK,OAAO,CAAC,GAAG,EAAE,WAAW,CAAC,GAAG,UAAU,CAAC,EAAE,IAAI,CAAC,GAAG;AACpD,QAAI,KAAK,OAAQ;AACjB,SAAK,MAAM,YAAY,EAAE,SAAS,KAAK,IAAI,KAAK,GAAG,UAAU,OAAO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AG,CAAC;AAAA,MAC9F;AACA,aAAO,KAAK,UAAU,EAAE,MAAM,SAAS,SAAS,QAAQ,KAAK,GAAG,OAAO,GAAG,CAAC;AAAA,IAC7E;AAAA,EACF;AACA,SAAO,eAAe,YAAY,UAAU,EAAE,YAAY,MAAM,CAAC;AACjE,aAAW,UAAU,QAAQ;AAC7B,aAAW,SAAS,QAAQ;AAC5B,aAAW,UAAU,QAAQ;AAC7B,WAAS,cAAc,WAAW,QAAQ,CAAC,UAAU,GAAG,MAAM,IAAI,CAAC;AACrE;AAEA,eAAe,OAAO,KAAK;AACzB,MAAI,IAAI,OAAO,QAAQ;AACrB,YAAQ,GAAG;AACX,WAAO,EAAE,WAAW,WAAW,WAAW,aAAa,GAAG;AAAA,EAC5D;AACA,MAAI,WAAW,KAAM,OAAM,IAAI,MAAM,mCAAmC;AACxE,SAAO,MAAM,OAAO,GAAG;AACzB;AAEA,WAAW,iBAAiB,WAAW,CAAC,UAAU;AAChD,QAAM,MAAM,MAAM;AAClB,SAAO,GAAG,EAAE;AAAA,IACV,CAAC,UAAU,KAAK,EAAE,MAAM,SAAS,IAAI,IAAI,IAAI,GAAG,MAAM,CAAC;AAAA,IACvD,CAAC,QAAQ,KAAK,EAAE,MAAM,SAAS,IAAI,IAAI,IAAI,SAAS,OAAO,KAAK,SAAS,GAAG,EAAE,CAAC;AAAA,EACjF;AACF,CAAC;",
|
|
6
|
+
"names": ["comm", "list", "key", "$display", "key", "encoding", "list", "format", "answer", "handle", "items", "propertyNames", "inspect", "cdn"]
|
|
7
|
+
}
|
package/dist/cdp.d.ts
CHANGED
|
@@ -15,6 +15,15 @@ export interface ExceptionDetails {
|
|
|
15
15
|
lineNumber: number;
|
|
16
16
|
columnNumber: number;
|
|
17
17
|
exception?: RemoteObject;
|
|
18
|
+
/** Where it was thrown, with each script's URL (#322). */
|
|
19
|
+
stackTrace?: {
|
|
20
|
+
callFrames: {
|
|
21
|
+
functionName: string;
|
|
22
|
+
url: string;
|
|
23
|
+
lineNumber: number;
|
|
24
|
+
columnNumber: number;
|
|
25
|
+
}[];
|
|
26
|
+
};
|
|
18
27
|
}
|
|
19
28
|
export interface EvaluateResult {
|
|
20
29
|
result: RemoteObject;
|
|
@@ -33,6 +42,8 @@ export declare class CdpSession {
|
|
|
33
42
|
static connect(url: string): Promise<CdpSession>;
|
|
34
43
|
on(method: string, listener: (params: CdpParams) => void): void;
|
|
35
44
|
send(method: string, params?: CdpParams): Promise<CdpParams>;
|
|
45
|
+
/** In-flight calls, oldest first, with how long each has waited: for a state dump (#237). */
|
|
46
|
+
pendingCalls(): string[];
|
|
36
47
|
/** Reject every in-flight call; their late responses are then ignored. */
|
|
37
48
|
abandonPending(): void;
|
|
38
49
|
close(): void;
|
package/dist/cdp.js
CHANGED
|
@@ -69,10 +69,15 @@ export class CdpSession {
|
|
|
69
69
|
return Promise.reject(new Error("CDP connection closed"));
|
|
70
70
|
const id = ++this.#nextId;
|
|
71
71
|
return new Promise((resolve, reject) => {
|
|
72
|
-
this.#pending.set(id, { method, resolve, reject });
|
|
72
|
+
this.#pending.set(id, { method, sent: Date.now(), resolve, reject });
|
|
73
73
|
this.#ws.send(JSON.stringify({ id, method, params }));
|
|
74
74
|
});
|
|
75
75
|
}
|
|
76
|
+
/** In-flight calls, oldest first, with how long each has waited: for a state dump (#237). */
|
|
77
|
+
pendingCalls() {
|
|
78
|
+
const now = Date.now();
|
|
79
|
+
return [...this.#pending.values()].map((p) => `${p.method} (${now - p.sent} ms)`);
|
|
80
|
+
}
|
|
76
81
|
/** Reject every in-flight call; their late responses are then ignored. */
|
|
77
82
|
abandonPending() {
|
|
78
83
|
for (const pending of this.#pending.values()) {
|
package/dist/celld-target.js
CHANGED
|
@@ -24,7 +24,7 @@ import { build } from "esbuild";
|
|
|
24
24
|
import { isRecord } from "./cdp.js";
|
|
25
25
|
import { parseJsonc } from "./deno-config.js";
|
|
26
26
|
import { runtimeDir } from "./package.js";
|
|
27
|
-
import { killOnExit } from "./children.js";
|
|
27
|
+
import { childPids, killOnExit, reapWith } from "./children.js";
|
|
28
28
|
import { cellMeta, WorkerdTarget } from "./workerd-target.js";
|
|
29
29
|
import { builtinAliases, findWranglerConfig } from "./workers-project.js";
|
|
30
30
|
/** The project keys the generated config keeps: bindings and compatibility. */
|
|
@@ -122,16 +122,10 @@ function channelOf(ws) {
|
|
|
122
122
|
},
|
|
123
123
|
};
|
|
124
124
|
}
|
|
125
|
-
/**
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
}
|
|
130
|
-
catch {
|
|
131
|
-
return []; // none
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
/** Kills celld dev's node, then the supervisor itself. */
|
|
125
|
+
/**
|
|
126
|
+
* Kills celld dev's own children, which run in their own process groups,
|
|
127
|
+
* then the supervisor itself.
|
|
128
|
+
*/
|
|
135
129
|
function killTree(child) {
|
|
136
130
|
for (const pid of childPids(child.pid ?? -1)) {
|
|
137
131
|
try {
|
|
@@ -222,7 +216,7 @@ class CelldHost {
|
|
|
222
216
|
killOnExit(child, () => {
|
|
223
217
|
killTree(child);
|
|
224
218
|
removeFiles();
|
|
225
|
-
});
|
|
219
|
+
}, { dir: projectConfig === null ? dir : undefined });
|
|
226
220
|
// Cell output is captured in the driver; celld's own lines go to the
|
|
227
221
|
// server log.
|
|
228
222
|
// `early` keeps that output for a startup error only, and stops growing
|
|
@@ -262,6 +256,9 @@ class CelldHost {
|
|
|
262
256
|
})();
|
|
263
257
|
try {
|
|
264
258
|
const host = new CelldHost(child, await Promise.race([ready, exited]), `celld ${version}`.trim(), projectConfig ?? undefined);
|
|
259
|
+
// Its server, in its own process group, outlives a SIGKILLed celld dev.
|
|
260
|
+
for (const pid of childPids(child.pid ?? -1))
|
|
261
|
+
reapWith(pid, child);
|
|
265
262
|
starting = false;
|
|
266
263
|
early = "";
|
|
267
264
|
return host;
|
package/dist/children.d.ts
CHANGED
|
@@ -1,7 +1,29 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ChildProcess } from "node:child_process";
|
|
2
|
+
/**
|
|
3
|
+
* The helper's script. Lines on stdin: `+pid` registers a pid, `-pid`
|
|
4
|
+
* forgets it (it exited, and the pid may be reused), `d<path>` registers a
|
|
5
|
+
* directory. In its own session, so a killpg of this process's group (as
|
|
6
|
+
* Jupyter's kill does) doesn't take it down first.
|
|
7
|
+
*/
|
|
8
|
+
export declare const REAPER_SCRIPT = "trap '' HUP INT\npids=\" \"\ndirs=\"\"\nwhile IFS= read -r line; do\n case $line in\n +*) pids=\"$pids${line#?} \" ;;\n -*) pids=$(printf '%s' \"$pids\" | sed \"s/ ${line#?} / /\") ;;\n d*) dirs=\"$dirs${line#?}\n\" ;;\n esac\ndone\nkill -9 $pids 2>/dev/null\nprintf '%s' \"$dirs\" | while IFS= read -r dir; do rm -rf -- \"$dir\"; done\n";
|
|
9
|
+
/**
|
|
10
|
+
* Kills `pid` if this process dies, until the returned function is called
|
|
11
|
+
* (when the process is known to have exited: its pid may be reused).
|
|
12
|
+
*/
|
|
13
|
+
export declare function reap(pid: number): () => void;
|
|
14
|
+
/**
|
|
15
|
+
* Kills `pid`, which isn't this process's child (a runtime's own child in
|
|
16
|
+
* its own process group), if this process dies while `owner` runs.
|
|
17
|
+
*/
|
|
18
|
+
export declare function reapWith(pid: number, owner: ChildProcess): void;
|
|
19
|
+
/** `pid`'s children whose command line matches `pattern` (pgrep's -f). */
|
|
20
|
+
export declare function childPids(pid: number, pattern?: string): number[];
|
|
2
21
|
/**
|
|
3
22
|
* Kills `child` if it's still running when this process exits. `cleanup`
|
|
4
23
|
* replaces the default SIGKILL; it must be synchronous, as exit hooks are,
|
|
5
|
-
* and do whatever the child's own exit listener would have done.
|
|
24
|
+
* and do whatever the child's own exit listener would have done. If this
|
|
25
|
+
* process is SIGKILLed, the helper kills `child` and removes `dir`.
|
|
6
26
|
*/
|
|
7
|
-
export declare function killOnExit(child: ChildProcess, cleanup?: () => void
|
|
27
|
+
export declare function killOnExit(child: ChildProcess, cleanup?: () => void, { dir }?: {
|
|
28
|
+
dir?: string;
|
|
29
|
+
}): void;
|
package/dist/children.js
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
// Runtimes this process started, killed when it exits however it exits
|
|
2
2
|
// short of SIGKILL: a target left behind keeps running, reparented to pid 1,
|
|
3
3
|
// with whatever temp directory it uses (#127, #218).
|
|
4
|
+
//
|
|
5
|
+
// SIGKILL runs no exit hook, so a helper outside this process also knows the
|
|
6
|
+
// runtimes' pids (#240): a detached sh reading this process's pipe, which
|
|
7
|
+
// kills whatever is still registered, and removes the registered temp
|
|
8
|
+
// directories, once the pipe closes. That covers what nothing in a runtime
|
|
9
|
+
// can notice: celld dev and its server, and a Node or Deno runtime stuck in
|
|
10
|
+
// a cell's synchronous loop, where the #219 watchdog never gets to run.
|
|
4
11
|
import process from "node:process";
|
|
12
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
5
13
|
const cleanups = new Set();
|
|
6
14
|
function runAll() {
|
|
7
15
|
for (const cleanup of cleanups) {
|
|
@@ -15,12 +23,82 @@ function runAll() {
|
|
|
15
23
|
cleanups.clear();
|
|
16
24
|
}
|
|
17
25
|
let hooked = false;
|
|
26
|
+
/**
|
|
27
|
+
* The helper's script. Lines on stdin: `+pid` registers a pid, `-pid`
|
|
28
|
+
* forgets it (it exited, and the pid may be reused), `d<path>` registers a
|
|
29
|
+
* directory. In its own session, so a killpg of this process's group (as
|
|
30
|
+
* Jupyter's kill does) doesn't take it down first.
|
|
31
|
+
*/
|
|
32
|
+
export const REAPER_SCRIPT = `trap '' HUP INT
|
|
33
|
+
pids=" "
|
|
34
|
+
dirs=""
|
|
35
|
+
while IFS= read -r line; do
|
|
36
|
+
case $line in
|
|
37
|
+
+*) pids="$pids\${line#?} " ;;
|
|
38
|
+
-*) pids=$(printf '%s' "$pids" | sed "s/ \${line#?} / /") ;;
|
|
39
|
+
d*) dirs="$dirs\${line#?}
|
|
40
|
+
" ;;
|
|
41
|
+
esac
|
|
42
|
+
done
|
|
43
|
+
kill -9 $pids 2>/dev/null
|
|
44
|
+
printf '%s' "$dirs" | while IFS= read -r dir; do rm -rf -- "$dir"; done
|
|
45
|
+
`;
|
|
46
|
+
let reaper;
|
|
47
|
+
/** Sends `line` to the helper, starting it first; a no-op on Windows. */
|
|
48
|
+
function tellReaper(line) {
|
|
49
|
+
if (reaper === undefined) {
|
|
50
|
+
reaper = null;
|
|
51
|
+
if (process.platform === "win32")
|
|
52
|
+
return;
|
|
53
|
+
try {
|
|
54
|
+
const child = spawn("/bin/sh", ["-c", REAPER_SCRIPT], { cwd: "/", detached: true, stdio: ["pipe", "ignore", "ignore"] });
|
|
55
|
+
child.once("error", () => (reaper = null));
|
|
56
|
+
child.stdin?.on("error", () => (reaper = null));
|
|
57
|
+
// Neither the helper nor its pipe keeps this process running.
|
|
58
|
+
child.unref();
|
|
59
|
+
child.stdin?.unref?.();
|
|
60
|
+
reaper = child;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
reaper?.stdin?.write(`${line}\n`);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Kills `pid` if this process dies, until the returned function is called
|
|
70
|
+
* (when the process is known to have exited: its pid may be reused).
|
|
71
|
+
*/
|
|
72
|
+
export function reap(pid) {
|
|
73
|
+
tellReaper(`+${pid}`);
|
|
74
|
+
return () => tellReaper(`-${pid}`);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Kills `pid`, which isn't this process's child (a runtime's own child in
|
|
78
|
+
* its own process group), if this process dies while `owner` runs.
|
|
79
|
+
*/
|
|
80
|
+
export function reapWith(pid, owner) {
|
|
81
|
+
if (owner.exitCode !== null || owner.signalCode !== null)
|
|
82
|
+
return;
|
|
83
|
+
owner.once("exit", reap(pid));
|
|
84
|
+
}
|
|
85
|
+
/** `pid`'s children whose command line matches `pattern` (pgrep's -f). */
|
|
86
|
+
export function childPids(pid, pattern) {
|
|
87
|
+
try {
|
|
88
|
+
const args = ["-P", String(pid), ...(pattern === undefined ? [] : ["-f", pattern])];
|
|
89
|
+
return execFileSync("pgrep", args, { encoding: "utf8" }).split(/\s+/).filter(Boolean).map(Number);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return []; // none, or no pgrep
|
|
93
|
+
}
|
|
94
|
+
}
|
|
18
95
|
/**
|
|
19
96
|
* Kills `child` if it's still running when this process exits. `cleanup`
|
|
20
97
|
* replaces the default SIGKILL; it must be synchronous, as exit hooks are,
|
|
21
|
-
* and do whatever the child's own exit listener would have done.
|
|
98
|
+
* and do whatever the child's own exit listener would have done. If this
|
|
99
|
+
* process is SIGKILLed, the helper kills `child` and removes `dir`.
|
|
22
100
|
*/
|
|
23
|
-
export function killOnExit(child, cleanup = () => child.kill("SIGKILL")) {
|
|
101
|
+
export function killOnExit(child, cleanup = () => child.kill("SIGKILL"), { dir } = {}) {
|
|
24
102
|
if (!hooked) {
|
|
25
103
|
hooked = true;
|
|
26
104
|
process.on("exit", runAll);
|
|
@@ -29,4 +107,8 @@ export function killOnExit(child, cleanup = () => child.kill("SIGKILL")) {
|
|
|
29
107
|
return;
|
|
30
108
|
cleanups.add(cleanup);
|
|
31
109
|
child.once("exit", () => cleanups.delete(cleanup));
|
|
110
|
+
if (dir !== undefined)
|
|
111
|
+
tellReaper(`d${dir}`);
|
|
112
|
+
if (child.pid !== undefined)
|
|
113
|
+
reapWith(child.pid, child);
|
|
32
114
|
}
|
package/dist/debugger.d.ts
CHANGED
|
@@ -8,6 +8,8 @@ export interface DebugChannel {
|
|
|
8
8
|
readonly contextId: number;
|
|
9
9
|
/** Enumerable globals the runtime had before any cell ran. */
|
|
10
10
|
readonly baselineGlobals: ReadonlySet<string>;
|
|
11
|
+
/** Runs a call of the kernel's own with pausing on exceptions held off (#307). */
|
|
12
|
+
withoutPausing?<T>(call: () => Promise<T>): Promise<T>;
|
|
11
13
|
}
|
|
12
14
|
export type DapMessage = {
|
|
13
15
|
[key: string]: unknown;
|
package/dist/debugger.js
CHANGED
|
@@ -15,7 +15,7 @@ import process from "node:process";
|
|
|
15
15
|
import { fileURLToPath } from "node:url";
|
|
16
16
|
import { isRecord, isRemoteObject } from "./cdp.js";
|
|
17
17
|
import { murmur2 } from "./murmur2.js";
|
|
18
|
-
import { SETTLE, transformCellWithLines } from "./transform.js";
|
|
18
|
+
import { SETTLE, transformCellWithLines, YIELD } from "./transform.js";
|
|
19
19
|
/** ipykernel's seed, so a kernel switch doesn't move JupyterLab's breakpoints. */
|
|
20
20
|
export const HASH_SEED = 0xc70f6907;
|
|
21
21
|
export const THREAD_ID = 1;
|
|
@@ -472,13 +472,14 @@ export class Debugger {
|
|
|
472
472
|
// While paused, only a frame can evaluate: use the top one if none was named.
|
|
473
473
|
const frame = typeof frameId === "number" ? this.#frames[frameId] : this.#stopped ? this.#frames[0] : undefined;
|
|
474
474
|
// replMode (for the console's `await`) returns a promise the inspector
|
|
475
|
-
// holds only weakly: SETTLE
|
|
476
|
-
// side-effect-free lookup can't await, so it uses a plain
|
|
475
|
+
// holds only weakly: YIELD and SETTLE close that window, as for cells
|
|
476
|
+
// (#55, #329). A side-effect-free lookup can't await, so it uses a plain
|
|
477
|
+
// evaluate.
|
|
477
478
|
const res = frame
|
|
478
479
|
? await channel.send("Debugger.evaluateOnCallFrame", { callFrameId: frame.callFrameId, expression, throwOnSideEffect: pure })
|
|
479
480
|
: pure
|
|
480
481
|
? await channel.send("Runtime.evaluate", { expression, contextId: channel.contextId, throwOnSideEffect: true })
|
|
481
|
-
: await channel.send("Runtime.evaluate", { expression: expression + SETTLE, contextId: channel.contextId, replMode: true });
|
|
482
|
+
: await this.#withoutPausing(() => channel.send("Runtime.evaluate", { expression: YIELD + expression + SETTLE, contextId: channel.contextId, replMode: true }));
|
|
482
483
|
if (isRecord(res.exceptionDetails)) {
|
|
483
484
|
const exception = res.exceptionDetails.exception;
|
|
484
485
|
throw new Error(exception ? describeRemote(exception) : String(res.exceptionDetails.text ?? "evaluation failed"));
|
|
@@ -500,12 +501,12 @@ export class Debugger {
|
|
|
500
501
|
const value = await this.#valueOf(name, frameId, true);
|
|
501
502
|
const arg = value.objectId ? { objectId: value.objectId } : { value: value.value };
|
|
502
503
|
// Synchronous: while the target is paused, no promise would settle.
|
|
503
|
-
const res = await channel.send("Runtime.callFunctionOn", {
|
|
504
|
+
const res = await this.#withoutPausing(() => channel.send("Runtime.callFunctionOn", {
|
|
504
505
|
functionDeclaration: "function (v) { return globalThis.__cdpk.richBundle(v); }",
|
|
505
506
|
arguments: [arg],
|
|
506
507
|
executionContextId: channel.contextId,
|
|
507
508
|
returnByValue: true,
|
|
508
|
-
});
|
|
509
|
+
}));
|
|
509
510
|
const text = res.result?.value;
|
|
510
511
|
const data = typeof text === "string" ? JSON.parse(text) : {};
|
|
511
512
|
return { data: isRecord(data) ? data : {}, metadata: {} };
|
|
@@ -537,6 +538,11 @@ export class Debugger {
|
|
|
537
538
|
// The frontend has the cell itself; the file is a convenience.
|
|
538
539
|
}
|
|
539
540
|
}
|
|
541
|
+
/** The kernel's own evaluation, unpaused by exceptions; while stopped, nothing more pauses anyway. */
|
|
542
|
+
#withoutPausing(call) {
|
|
543
|
+
const channel = this.#channel;
|
|
544
|
+
return channel?.withoutPausing && !this.#stopped ? channel.withoutPausing(call) : call();
|
|
545
|
+
}
|
|
540
546
|
#event(event, body) {
|
|
541
547
|
const message = { type: "event", seq: ++this.#seq, event, body };
|
|
542
548
|
trace("event", message);
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export type DenoResolution = {
|
|
2
|
+
kind: "npm";
|
|
3
|
+
dir: string;
|
|
4
|
+
subpath: string;
|
|
5
|
+
} | {
|
|
6
|
+
kind: "remote";
|
|
7
|
+
path: string;
|
|
8
|
+
};
|
|
9
|
+
export type RunDeno = (args: string[]) => {
|
|
10
|
+
status: number | null;
|
|
11
|
+
stdout: string;
|
|
12
|
+
};
|
|
13
|
+
export declare class DenoResolver {
|
|
14
|
+
#private;
|
|
15
|
+
/** Where remote modules appear to the language service. */
|
|
16
|
+
readonly root: string;
|
|
17
|
+
constructor({ deno, config, root }: {
|
|
18
|
+
deno?: string;
|
|
19
|
+
config?: string | null;
|
|
20
|
+
root: string;
|
|
21
|
+
}, run?: RunDeno);
|
|
22
|
+
/** The virtual path for a remote module's URL, e.g. <root>/https/jsr.io/@std/path/1.1.6/mod.ts. */
|
|
23
|
+
pathFor(url: string): string | null;
|
|
24
|
+
/** The cached file behind a virtual path, if a lookup has found it. */
|
|
25
|
+
localFile(path: string): string | undefined;
|
|
26
|
+
/** Where `specifier` resolves for Deno, from what's already in its cache. */
|
|
27
|
+
lookup(specifier: string): DenoResolution | null;
|
|
28
|
+
}
|
|
29
|
+
/** `deno types`: declarations for the Deno namespace and its web globals. */
|
|
30
|
+
export declare function denoTypes(run?: RunDeno): string | null;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Types for a Deno target's imports (#275). Deno resolves npm:, jsr:, URLs
|
|
2
|
+
// and its project's import map itself and keeps what it fetched in its own
|
|
3
|
+
// cache, so the language service asks it where a specifier went:
|
|
4
|
+
// `deno info --json` over a one-line module importing it. npm packages map
|
|
5
|
+
// to their directory in Deno's npm cache; remote modules (jsr:, https:)
|
|
6
|
+
// are stored under hashed names without an extension, so the language
|
|
7
|
+
// service sees each under a virtual path built from its URL, which keeps
|
|
8
|
+
// relative imports between them working.
|
|
9
|
+
import { spawnSync } from "node:child_process";
|
|
10
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
function runDeno(deno) {
|
|
14
|
+
return (args) => {
|
|
15
|
+
const result = spawnSync(deno, args, { encoding: "utf8", timeout: 30_000, maxBuffer: 64 * 1024 * 1024 });
|
|
16
|
+
return { status: result.status, stdout: result.stdout ?? "" };
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export class DenoResolver {
|
|
20
|
+
#run;
|
|
21
|
+
#config;
|
|
22
|
+
/** Where remote modules appear to the language service. */
|
|
23
|
+
root;
|
|
24
|
+
#lookups = new Map();
|
|
25
|
+
/** Virtual path -> the cached file holding that URL's module. */
|
|
26
|
+
#remote = new Map();
|
|
27
|
+
constructor({ deno = "deno", config = null, root }, run = runDeno(deno)) {
|
|
28
|
+
this.#run = run;
|
|
29
|
+
this.#config = config;
|
|
30
|
+
this.root = root;
|
|
31
|
+
}
|
|
32
|
+
/** The virtual path for a remote module's URL, e.g. <root>/https/jsr.io/@std/path/1.1.6/mod.ts. */
|
|
33
|
+
pathFor(url) {
|
|
34
|
+
const m = /^(https?):\/\/(.+)$/.exec(url);
|
|
35
|
+
return m ? join(this.root, m[1], m[2]) : null;
|
|
36
|
+
}
|
|
37
|
+
/** The cached file behind a virtual path, if a lookup has found it. */
|
|
38
|
+
localFile(path) {
|
|
39
|
+
return this.#remote.get(path);
|
|
40
|
+
}
|
|
41
|
+
/** Where `specifier` resolves for Deno, from what's already in its cache. */
|
|
42
|
+
lookup(specifier) {
|
|
43
|
+
if (this.#lookups.has(specifier))
|
|
44
|
+
return this.#lookups.get(specifier) ?? null;
|
|
45
|
+
const resolution = this.#lookup(specifier);
|
|
46
|
+
this.#lookups.set(specifier, resolution);
|
|
47
|
+
return resolution;
|
|
48
|
+
}
|
|
49
|
+
#lookup(specifier) {
|
|
50
|
+
const dir = mkdtempSync(join(tmpdir(), "cdpk-deno-info-"));
|
|
51
|
+
try {
|
|
52
|
+
const entry = join(dir, "entry.ts");
|
|
53
|
+
writeFileSync(entry, `import ${JSON.stringify(specifier)};\n`);
|
|
54
|
+
const flags = this.#config === null ? ["--node-modules-dir=none"] : ["--config", this.#config];
|
|
55
|
+
const result = this.#run(["info", "--json", "--no-lock", ...flags, entry]);
|
|
56
|
+
if (result.status !== 0)
|
|
57
|
+
return null;
|
|
58
|
+
return this.#read(JSON.parse(result.stdout));
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
rmSync(dir, { recursive: true, force: true });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
#read(info) {
|
|
68
|
+
for (const mod of info.modules) {
|
|
69
|
+
const path = mod.local === undefined ? null : this.pathFor(mod.specifier);
|
|
70
|
+
if (path !== null && mod.local !== undefined)
|
|
71
|
+
this.#remote.set(path, mod.local);
|
|
72
|
+
}
|
|
73
|
+
const root = info.modules.find((m) => m.specifier === info.roots[0]);
|
|
74
|
+
const dep = root?.dependencies?.[0];
|
|
75
|
+
let target = dep?.code?.specifier ?? dep?.specifier;
|
|
76
|
+
if (target === undefined)
|
|
77
|
+
return null;
|
|
78
|
+
for (let i = 0; i < 10 && info.redirects[target] !== undefined; i++)
|
|
79
|
+
target = info.redirects[target];
|
|
80
|
+
const npm = /^npm:\/?((?:@[^/]+\/)?[^/@]+@[^/]+)(\/.*)?$/.exec(target);
|
|
81
|
+
if (npm) {
|
|
82
|
+
const dir = info.npmPackages[npm[1]]?.localPath;
|
|
83
|
+
return dir === undefined ? null : { kind: "npm", dir, subpath: npm[2] ?? "" };
|
|
84
|
+
}
|
|
85
|
+
const path = this.pathFor(target);
|
|
86
|
+
return path !== null && this.#remote.has(path) ? { kind: "remote", path } : null;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** `deno types`: declarations for the Deno namespace and its web globals. */
|
|
90
|
+
export function denoTypes(run = runDeno("deno")) {
|
|
91
|
+
const result = run(["types"]);
|
|
92
|
+
return result.status === 0 ? result.stdout : null;
|
|
93
|
+
}
|