From 4a42c4fb3a58e1e18f35eadc6e8a8a1183c1754b Mon Sep 17 00:00:00 2001 From: broisnees Date: Sun, 15 Nov 2026 18:31:41 +0000 Subject: [PATCH] SQL notebook: import and export, variables, autosave, a cell UI you can work in - Open .sqlnb, Jupyter .ipynb (%%sql magics), Markdown (```sql fences become cells) and .sql scripts (-- %% markers or blank-line groups); Import adds another file's cells to the notebook you are in. - Export: HTML report (results included, light and dark, printable), Markdown with result tables, Jupyter (%%sql), SQL script (-- %% cells). - {{name}} variables, filled from a bar under the toolbar; a placeholder without a value says so instead of reaching the database. - Autosave once the notebook has a file (toggle in the Save menu), Save as (Mod+Shift+S), and a Recent list in Open. - Cells: Jupyter-style run counter, rows / ms / when it ran, the variables a query uses, editor sized to the query (drag to override, double-click to fit), Shift+Enter runs and moves on, duplicate, clear outputs, Run all stops at the first failing cell (Mod+Shift+Enter), copy results as TSV. - Markdown cells: rendered through the sanitising renderer (a notebook can be a downloaded file), list continuation and Tab indent while typing. Converters and variables are pure functions in notebook.js with tests. Co-Authored-By: Claude Opus 5.5 --- src/lib/components/NotebookEditor.svelte | 568 ++++++++++++------ .../components/notebook/MarkdownCell.svelte | 26 +- src/lib/components/notebook/SqlCell.svelte | 268 ++++----- src/lib/markdown-safe.js | 37 ++ src/lib/markdown-safe.test.js | 12 + src/lib/notebook.js | 241 +++++++- src/lib/notebook.test.js | 102 ++++ 7 files changed, 923 insertions(+), 331 deletions(-) create mode 100644 src/lib/notebook.test.js diff --git a/src/lib/components/NotebookEditor.svelte b/src/lib/components/NotebookEditor.svelte index b17efd2d..1af9641b 100644 --- a/src/lib/components/NotebookEditor.svelte +++ b/src/lib/components/NotebookEditor.svelte @@ -1,5 +1,18 @@
- - -
- + +
+ - {#if dirty} - ● - {/if} - {#if filePath} - - {filePath.split(/[/\\]/).pop()} - - {/if} + + {#if saving} + Saving… + {:else if !filePath} + Not saved + {:else if dirty} + {fileName} + {:else} + {fileName} + {/if} + -
- - - +
- + + {#if vars.length || undefinedVars.length} +
+ Variables + {#each vars as v, i (i)} + + setVariable(i, { name: /** @type {HTMLInputElement} */ (e.target).value.replace(/[^\w]/g, '') })} /> + = + setVariable(i, { value: /** @type {HTMLInputElement} */ (e.target).value })} /> + + + {/each} + {#each undefinedVars as n (n)} + + {/each} + +
+ {/if} + +
{#if notebook.cells.length === 0}

Empty notebook

- +
+ + +
{:else} - - {@render Adder(-1)} - - {#each notebook.cells as cell, idx (cell.id)} - -
- {#if cell.type === 'sql'} - updateCell(cell.id, { content: v })} - onrun={() => runCell(cell.id)} - onmoveup={() => moveCell(cell.id, -1)} - onmovedown={() => moveCell(cell.id, 1)} - onremove={() => removeCell(cell.id)} - canmoveup={idx > 0} - canmovedown={idx < notebook.cells.length - 1} - canremove={notebook.cells.length > 1} - /> - {:else} - updateCell(cell.id, { content: v })} - onmoveup={() => moveCell(cell.id, -1)} - onmovedown={() => moveCell(cell.id, 1)} - onremove={() => removeCell(cell.id)} - canmoveup={idx > 0} - canmovedown={idx < notebook.cells.length - 1} - canremove={notebook.cells.length > 1} - /> - {/if} +
+ {@render Adder(-1)} + {#each notebook.cells as cell, idx (cell.id)} +
+ {#if cell.type === 'sql'} + updateCell(cell.id, { content: v })} + onrun={() => void runCell(cell.id)} + onrunadvance={() => void runAndAdvance(cell.id)} + onduplicate={() => duplicateCell(cell.id)} + onmoveup={() => moveCell(cell.id, -1)} + onmovedown={() => moveCell(cell.id, 1)} + onremove={() => removeCell(cell.id)} + canmoveup={idx > 0} + canmovedown={idx < notebook.cells.length - 1} + canremove={notebook.cells.length > 1} + /> + {:else} + updateCell(cell.id, { content: v })} + onadvance={() => { const n = notebook.cells[idx + 1] ?? addCell(idx, 'sql'); focusCell(n.id) }} + onmoveup={() => moveCell(cell.id, -1)} + onmovedown={() => moveCell(cell.id, 1)} + onremove={() => removeCell(cell.id)} + canmoveup={idx > 0} + canmovedown={idx < notebook.cells.length - 1} + canremove={notebook.cells.length > 1} + /> + {/if} +
+ {@render Adder(idx)} + {/each} +
+ +
- - - {@render Adder(idx)} - {/each} +

+ {comboTitle('Mod+Enter')} run · ⇧↵ run and next · {comboTitle('Mod+Shift+Enter')} run all · write {'{{name}}'} in a query for a variable +

+
{/if} - - -
- + {#if addMenuOpen} -
{ addMenuOpen = false }} - role="presentation" - >
-
- -
{/if} - - -{#snippet Adder(idx)} -
+{#snippet Adder(/** @type {number} */ idx)} +
-
diff --git a/src/lib/components/notebook/MarkdownCell.svelte b/src/lib/components/notebook/MarkdownCell.svelte index 836c520a..14abcaaa 100644 --- a/src/lib/components/notebook/MarkdownCell.svelte +++ b/src/lib/components/notebook/MarkdownCell.svelte @@ -1,5 +1,6 @@ -
- -
- - [{cellIndex + 1}] sql +
+ +
+ + [{running ? '*' : runCount ?? ' '}] - ⌘↵ run - {#if running} - - running… + SQL + {#each usedVars as v (v)} + {v} + {/each} +
+ {#if running} + running… + {:else if result && !hasError} + + {result.columns.length ? `${result.rows.length}${truncated ? '+' : ''} row${result.rows.length === 1 ? '' : 's'} · ` : ''}{result.queryMs} ms{ranLabel ? ` · ${ranLabel}` : ''} + + {:else if hasError} + failed + {/if} + + + + + - {/if} -
- - -
- +
- +
- +
(manualHeight = null)} + title="Drag to resize · double-click to fit the query" >
- - {#if hasResults} + + {#if result}
-
- - - {#if !resultsCollapsed && result?.columns.length && !hasError} - + {/if}
{#if !resultsCollapsed} {#if hasError} -
- {result?.error} -
- {:else if result?.columns.length} +
{result.error}
+ {:else if result.columns.length}
- - {#each result.columns as col} - + {#each result.columns as col, ci (ci)} + {/each} - {#each displayRows as row, ri} - - - {#each row as cell} + {#each displayRows as row, ri (ri)} + + + {#each row as cell, ci (ci)} {/each} {/each} {#if truncated} - - - + {/if}
# + # {col.name} - {#if col.dataType} - {col.dataType} - {/if} + {#if col.dataType}{col.dataType}{/if}
{ri + 1}
{ri + 1} - {#if cell === null} - NULL + {#if cell === null || cell === undefined} + NULL {:else} - {String(cell)} + {show(cell)} {/if}
- Showing first {MAX_DISPLAY_ROWS} of {result.rows.length} rows -
Showing first {MAX_DISPLAY_ROWS} of {result.rows.length} rows
- {:else if result?.message} -
{result.message}
{/if} {/if}
diff --git a/src/lib/markdown-safe.js b/src/lib/markdown-safe.js index 3d99a441..b70e873a 100644 --- a/src/lib/markdown-safe.js +++ b/src/lib/markdown-safe.js @@ -14,6 +14,7 @@ */ import { escapeHtml } from './json-inspector.js' +import { Marked } from 'marked' // Each tag alone, as marked hands inline HTML over one tag at a time. const SAFE_TAG = /^<\/?(br|b|i|em|strong|u|s|del|ins|mark|small|sub|sup|kbd|code)\s*\/?>$/i @@ -32,3 +33,39 @@ export function isSafeHref(href) { const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(h.replace(/[\u0000- ]/g, '')) return !scheme || /^(https?|mailto)$/i.test(scheme[1]) } + +/** @type {import('marked').Marked | null} */ +let _safe = null + +/** + * Markdown to HTML for anything that came from a file or a person: raw HTML + * renders as text (a few inline tags aside), links go only to web or mail + * targets, and images become plain links. Notebook markdown cells use it: a + * notebook can be a downloaded .ipynb or .md, and {@html} puts it in the app. + * @param {string} md + */ +export function renderSafeMarkdown(md) { + if (!_safe) { + _safe = new Marked({ gfm: true, breaks: true }) + _safe.use({ + renderer: { + html: ({ text }) => safeRawHtml(text), + link(token) { + if (!isSafeHref(token.href)) return this.parser.parseInline(token.tokens) + const href = escapeHtml(token.href).replace(/"/g, '"') + return `${this.parser.parseInline(token.tokens)}` + }, + image({ href, text }) { + const label = escapeHtml(text || href || 'image') + if (!isSafeHref(href)) return label + return `${label}` + }, + }, + }) + } + try { + return /** @type {string} */ (_safe.parse(String(md ?? ''))) + } catch { + return escapeHtml(String(md ?? '')) + } +} diff --git a/src/lib/markdown-safe.test.js b/src/lib/markdown-safe.test.js index 180e0600..86274e92 100644 --- a/src/lib/markdown-safe.test.js +++ b/src/lib/markdown-safe.test.js @@ -45,3 +45,15 @@ describe('isSafeHref', () => { } }) }) + +import { renderSafeMarkdown } from './markdown-safe.js' +describe('renderSafeMarkdown', () => { + it('renders markdown but not raw HTML, script links or images', () => { + const html = renderSafeMarkdown('# T\n\n**b** [x](javascript:alert(1)) [ok](https://a.b) ![i](https://a.b/i.png)') + expect(html).toContain('b') + expect(html).not.toContain('} [variables] * @property {string} createdAt * @property {string} updatedAt */ @@ -40,7 +42,7 @@ export function createMarkdownCell(content = '') { /** @param {string} [title] @returns {Notebook} */ export function createNotebook(title = 'Untitled Notebook') { const now = new Date().toISOString() - return { version: '1', title, cells: [createSqlCell()], createdAt: now, updatedAt: now } + return { version: '1', title, cells: [createSqlCell()], variables: [], createdAt: now, updatedAt: now } } /** @param {Notebook} notebook @returns {string} */ @@ -59,6 +61,7 @@ export function deserializeNotebook(json) { result: c.result ?? null, collapsed: c.collapsed ?? false, })) + nb.variables = Array.isArray(nb.variables) ? nb.variables.filter((v) => v && typeof v.name === 'string').map((v) => ({ name: v.name, value: String(v.value ?? '') })) : [] return nb } @@ -67,3 +70,239 @@ export function titleFromPath(path) { const base = path.split(/[/\\]/).pop() ?? path return base.replace(/\.sqlnb$/i, '') } + +// ── Variables ──────────────────────────────────────────────────────────────── + +/** @typedef {{ name: string, value: string }} NotebookVariable */ + +/** `{{ name }}` placeholders in a cell. @param {string} sql */ +export function variableNames(sql) { + return [...new Set([...String(sql).matchAll(/\{\{\s*([A-Za-z_][\w]*)\s*\}\}/g)].map((m) => m[1]))] +} + +/** + * Fill `{{ name }}` placeholders from the notebook's variables. Text, not + * parameters: the value goes in as written, so `'{{status}}'` quotes a string + * and `{{limit}}` stays a number. Unknown names are left for the database to + * reject, with the list returned so the cell can say which. + * @param {string} sql + * @param {NotebookVariable[]} vars + * @returns {{ sql: string, missing: string[] }} + */ +export function substituteVars(sql, vars = []) { + const map = new Map(vars.filter((v) => v.name).map((v) => [v.name, v.value])) + /** @type {string[]} */ + const missing = [] + const out = String(sql).replace(/\{\{\s*([A-Za-z_][\w]*)\s*\}\}/g, (all, name) => { + if (map.has(name)) return /** @type {string} */ (map.get(name)) + if (!missing.includes(name)) missing.push(name) + return all + }) + return { sql: out, missing } +} + +// ── Import ─────────────────────────────────────────────────────────────────── + +/** @param {string} s */ +const lines = (s) => (Array.isArray(s) ? s.join('') : String(s ?? '')) + +/** + * A notebook from another format, picked by file extension: .sqlnb, Jupyter + * .ipynb (SQL code cells, `%%sql` magics, markdown), Markdown (```sql fences + * become SQL cells, the prose between them markdown cells) or a .sql script + * (cells split on `-- %%` markers, or one cell per statement group). + * @param {string} name file name or path + * @param {string} text + * @returns {Notebook} + */ +export function importNotebook(name, text) { + const ext = /\.([a-z0-9]+)$/i.exec(name)?.[1]?.toLowerCase() ?? '' + const title = titleFromPath(name).replace(/\.(ipynb|md|markdown|sql)$/i, '') + /** @type {NotebookCell[]} */ + let cells + if (ext === 'sqlnb') return deserializeNotebook(text) + if (ext === 'ipynb') cells = cellsFromIpynb(text) + else if (ext === 'md' || ext === 'markdown') cells = cellsFromMarkdown(text) + else cells = cellsFromSql(text) + const nb = createNotebook(title || 'Imported notebook') + nb.cells = cells.length ? cells : [createSqlCell()] + return nb +} + +/** @param {string} text @returns {NotebookCell[]} */ +export function cellsFromIpynb(text) { + const nb = JSON.parse(text) + if (!Array.isArray(nb?.cells)) throw new Error('Not a Jupyter notebook: no cells') + /** @type {NotebookCell[]} */ + const out = [] + for (const c of nb.cells) { + const src = lines(c.source) + if (!src.trim()) continue + if (c.cell_type === 'markdown') out.push(createMarkdownCell(src.trim())) + else if (c.cell_type === 'code') { + // %%sql / %sql magics (ipython-sql, JupySQL) carry the SQL after them. + const sql = src.replace(/^\s*%%sql[^\n]*\n?/, '').replace(/^\s*%sql\s+/gm, '') + out.push(createSqlCell(sql.trim())) + } + } + return out +} + +/** @param {string} text @returns {NotebookCell[]} */ +export function cellsFromMarkdown(text) { + /** @type {NotebookCell[]} */ + const out = [] + const re = /^```(\w*)[^\n]*\n([\s\S]*?)^```\s*$/gm + let last = 0 + for (const m of String(text).matchAll(re)) { + const lang = m[1].toLowerCase() + if (lang && !/^(sql|pgsql|postgres|postgresql|mysql|sqlite|plsql|tsql)$/.test(lang)) continue + const before = text.slice(last, m.index).trim() + if (before) out.push(createMarkdownCell(before)) + out.push(createSqlCell(m[2].trim())) + last = /** @type {number} */ (m.index) + m[0].length + } + const rest = text.slice(last).trim() + if (rest) out.push(createMarkdownCell(rest)) + return out +} + +/** @param {string} text @returns {NotebookCell[]} */ +export function cellsFromSql(text) { + const src = String(text) + // Explicit cells: `-- %%` (or `-- CELL`) lines, as VS Code and DataGrip write them. + if (/^\s*--\s*(%%|cell\b)/im.test(src)) { + return src + .split(/^\s*--\s*(?:%%|cell\b)[^\n]*$/im) + .map((s) => s.trim()) + .filter(Boolean) + .map((s) => createSqlCell(s)) + } + // Otherwise blank-line separated groups: a script's own paragraphs. + return src + .split(/\n\s*\n(?=\s*\S)/) + .map((s) => s.trim()) + .filter(Boolean) + .map((s) => createSqlCell(s)) +} + +// ── Export ─────────────────────────────────────────────────────────────────── + +/** @param {unknown} v */ +const cellText = (v) => (v === null || v === undefined ? 'NULL' : typeof v === 'object' ? JSON.stringify(v) : String(v)) +const MAX_EXPORT_ROWS = 200 + +/** A result as a Markdown table. @param {CellResult} r */ +function resultMarkdown(r) { + if (r.error) return `> Error: ${r.error.replace(/\n/g, ' ')}` + if (!r.columns.length) return r.message ? `> ${r.message}` : '' + const esc = (/** @type {string} */ s) => s.replace(/\|/g, '\\|').replace(/\n/g, ' ') + const head = `| ${r.columns.map((c) => esc(c.name)).join(' | ')} |` + const sep = `| ${r.columns.map(() => '---').join(' | ')} |` + const body = r.rows.slice(0, MAX_EXPORT_ROWS).map((row) => `| ${row.map((v) => esc(cellText(v))).join(' | ')} |`) + const more = r.rows.length > MAX_EXPORT_ROWS ? [`\n_${r.rows.length - MAX_EXPORT_ROWS} more rows not shown._`] : [] + return [head, sep, ...body, ...more].join('\n') +} + +/** @param {Notebook} nb @param {{ results?: boolean }} [o] */ +export function toMarkdown(nb, { results = true } = {}) { + const parts = [`# ${nb.title || 'Notebook'}`] + for (const c of nb.cells) { + if (c.type === 'markdown') parts.push(c.content.trim()) + else { + parts.push('```sql\n' + c.content.trim() + '\n```') + if (results && c.result) { + const md = resultMarkdown(c.result) + if (md) parts.push(md) + } + } + } + return parts.filter(Boolean).join('\n\n') + '\n' +} + +/** @param {Notebook} nb */ +export function toSqlScript(nb) { + const parts = [`-- ${nb.title || 'Notebook'}`] + for (const c of nb.cells) { + if (c.type === 'markdown') parts.push(c.content.trim().split('\n').map((l) => `-- ${l}`.trimEnd()).join('\n')) + else parts.push(`-- %%\n${c.content.trim()}`) + } + return parts.join('\n\n') + '\n' +} + +/** Jupyter nbformat 4, SQL as %%sql cells so JupySQL runs them. @param {Notebook} nb */ +export function toIpynb(nb) { + const src = (/** @type {string} */ s) => s.split(/(?<=\n)/) + return JSON.stringify({ + nbformat: 4, + nbformat_minor: 5, + metadata: { title: nb.title, language_info: { name: 'sql' } }, + cells: nb.cells.map((c) => + c.type === 'markdown' + ? { cell_type: 'markdown', id: c.id.slice(0, 8), metadata: {}, source: src(c.content) } + : { cell_type: 'code', id: c.id.slice(0, 8), metadata: {}, execution_count: null, outputs: [], source: src(`%%sql\n${c.content}`) }, + ), + }, null, 1) +} + +/** @param {string} s */ +const esc = (s) => String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') + +/** + * A self-contained HTML report: prose, queries and their results, readable in + * any browser and printable to PDF. `renderMd` turns a markdown cell into + * HTML (the app passes its sanitising renderer). + * @param {Notebook} nb + * @param {(md: string) => string} renderMd + */ +export function toHtml(nb, renderMd) { + const body = nb.cells.map((c) => { + if (c.type === 'markdown') return `
${renderMd(c.content)}
` + let out = `
${esc(c.content.trim())}
` + const r = c.result + if (r?.error) out += `

${esc(r.error)}

` + else if (r?.columns.length) { + const rows = r.rows.slice(0, MAX_EXPORT_ROWS) + out += `
${r.columns.map((col) => ``).join('')}${rows + .map((row) => `${row.map((v) => (v === null || v === undefined ? '' : ``)).join('')}`) + .join('')}
${esc(col.name)}
NULL${esc(cellText(v))}

${r.rows.length} row${r.rows.length === 1 ? '' : 's'}${r.rows.length > MAX_EXPORT_ROWS ? ` (first ${MAX_EXPORT_ROWS} shown)` : ''} · ${r.queryMs} ms

` + } else if (r?.message) out += `

${esc(r.message)}

` + return `
${out}
` + }).join('\n') + return `${esc(nb.title || 'Notebook')}

${esc(nb.title || 'Notebook')}

+${body} +

Exported from Stroke · ${new Date().toLocaleString()}

` +} + +// ── Recent notebooks ───────────────────────────────────────────────────────── + +const RECENT_KEY = 'stroke:notebooks:recent' + +/** @returns {Array<{ path: string, title: string, at: number }>} */ +export function recentNotebooks() { + try { + const v = JSON.parse(localStorage.getItem(RECENT_KEY) ?? '[]') + return Array.isArray(v) ? v : [] + } catch { + return [] + } +} + +/** @param {string} path @param {string} title */ +export function rememberNotebook(path, title) { + try { + const list = recentNotebooks().filter((r) => r.path !== path) + list.unshift({ path, title, at: Date.now() }) + localStorage.setItem(RECENT_KEY, JSON.stringify(list.slice(0, 12))) + } catch { /* not kept */ } +} diff --git a/src/lib/notebook.test.js b/src/lib/notebook.test.js new file mode 100644 index 00000000..951a2d46 --- /dev/null +++ b/src/lib/notebook.test.js @@ -0,0 +1,102 @@ +import { describe, expect, test } from 'vitest' +import { + createNotebook, + createSqlCell, + createMarkdownCell, + serializeNotebook, + deserializeNotebook, + substituteVars, + variableNames, + importNotebook, + cellsFromMarkdown, + cellsFromSql, + cellsFromIpynb, + toMarkdown, + toSqlScript, + toIpynb, + toHtml, +} from './notebook.js' + +describe('variables', () => { + test('fills {{ name }} and reports the unknown ones', () => { + const r = substituteVars("select * from t where status = '{{status}}' limit {{ n }} -- {{ other }}", [ + { name: 'status', value: 'paid' }, + { name: 'n', value: '10' }, + ]) + expect(r.sql).toBe("select * from t where status = 'paid' limit 10 -- {{ other }}") + expect(r.missing).toEqual(['other']) + expect(variableNames('{{a}} {{ b }} {{a}}')).toEqual(['a', 'b']) + }) + test('round-trips through .sqlnb', () => { + const nb = createNotebook('x') + nb.variables = [{ name: 'a', value: '1' }] + expect(deserializeNotebook(serializeNotebook(nb)).variables).toEqual([{ name: 'a', value: '1' }]) + // Older files without variables still open. + const old = JSON.stringify({ version: '1', title: 'o', cells: [] }) + expect(deserializeNotebook(old).variables).toEqual([]) + }) +}) + +describe('import', () => { + test('markdown: sql fences become SQL cells, prose stays markdown, other code stays prose', () => { + const cells = cellsFromMarkdown('# Report\n\nIntro\n\n```sql\nselect 1\n```\n\nMore\n\n```js\nx()\n```\n') + expect(cells.map((c) => [c.type, c.content])).toEqual([ + ['markdown', '# Report\n\nIntro'], + ['sql', 'select 1'], + ['markdown', 'More\n\n```js\nx()\n```'], + ]) + }) + test('sql script: -- %% markers, or blank-line groups', () => { + expect(cellsFromSql('select 1;\n-- %% second\nselect 2;').map((c) => c.content)).toEqual(['select 1;', 'select 2;']) + expect(cellsFromSql('select 1;\n\nselect 2;\nselect 3;').map((c) => c.content)).toEqual(['select 1;', 'select 2;\nselect 3;']) + }) + test('jupyter: %%sql magics and markdown', () => { + const ipynb = JSON.stringify({ cells: [ + { cell_type: 'markdown', source: ['# Hi\n', 'there'] }, + { cell_type: 'code', source: ['%%sql\n', 'select 1'] }, + { cell_type: 'code', source: '%sql select 2' }, + { cell_type: 'code', source: '' }, + ] }) + expect(cellsFromIpynb(ipynb).map((c) => [c.type, c.content])).toEqual([ + ['markdown', '# Hi\nthere'], + ['sql', 'select 1'], + ['sql', 'select 2'], + ]) + expect(() => cellsFromIpynb('{}')).toThrow() + }) + test('importNotebook picks the format by extension and names the notebook', () => { + const nb = importNotebook('/x/sales report.md', '```sql\nselect 1\n```') + expect(nb.title).toBe('sales report') + expect(nb.cells[0].type).toBe('sql') + expect(importNotebook('a.sql', '').cells.length).toBe(1) + }) +}) + +describe('export', () => { + const nb = createNotebook('Sales') + nb.cells = [createMarkdownCell('Some *prose*'), createSqlCell('select 1 as n')] + nb.cells[1].result = { columns: [{ name: 'n' }], rows: [[1], [null]], queryMs: 3, error: '', message: '' } + test('markdown with result tables', () => { + const md = toMarkdown(nb) + expect(md).toContain('# Sales') + expect(md).toContain('```sql\nselect 1 as n\n```') + expect(md).toContain('| n |\n| --- |\n| 1 |\n| NULL |') + }) + test('sql script keeps prose as comments and cells as -- %%', () => { + const sql = toSqlScript(nb) + expect(sql).toContain('-- Some *prose*') + expect(cellsFromSql(sql).map((c) => c.content).at(-1)).toBe('select 1 as n') + }) + test('ipynb round-trips back to the same cells', () => { + const back = cellsFromIpynb(toIpynb(nb)) + expect(back.map((c) => [c.type, c.content])).toEqual([['markdown', 'Some *prose*'], ['sql', 'select 1 as n']]) + }) + test('html escapes and includes results', () => { + const n2 = createNotebook('') + n2.cells = [createSqlCell("select ''")] + const html = toHtml(n2, (m) => m) + expect(html).toContain('<x>') + expect(html).toContain('select '<b>''.replace(''', "'").replace(''', "'")) + expect(toHtml(nb, (m) => `

${m}

`)).toContain('NULL') + }) +})