Skip to content

feat: Add support for creating Python and Markdown content from Deepnote blocks. - #25

Merged
Artmann merged 10 commits into
mainfrom
chris/add-deepnote-blocks
Oct 7, 2025
Merged

Artmann merged 10 commits into
mainfrom
chris/add-deepnote-blocks

Conversation

@Artmann

@Artmann Artmann commented Oct 3, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Added a new package to generate Markdown and Python code from notebook blocks, covering text, separators, images, code, SQL, visualizations, big numbers, buttons, and full input types (text, textarea, checkbox, select, slider, file, date, date range).
    • Utilities for safe Python string/variable handling and SQL environment name resolution; date-range helpers included.
  • Documentation
    • Added package README with overview, supported block types, and usage examples.
  • Tests
    • Added comprehensive unit tests for markdown, Python generation, and input block handling.
  • Chores
    • Expanded spell-check dictionary with relevant terms.

@coderabbitai

coderabbitai Bot commented Oct 3, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a new package @deepnote/blocks with package.json and README and implements a broad block model plus per-block modules and utilities. New core types and dispatchers: blocks.ts, python-code.ts (createPythonCode), markdown.ts (createMarkdown, stripMarkdown), python-snippets.ts, python-utils.ts, sql-utils.ts. Per-block modules added for code, sql, inputs, text, image, visualization, button, big-number, and separator, each with type guards and generation helpers. Adds unit tests for markdown, python-code, and inputs, and updates cspell wordlist. Exports aggregated helpers from src/index.ts.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller
  participant Dispatcher as createPythonCode
  participant Guards as TypeGuards
  participant Gen as Generators (code/sql/inputs/visualization/button/big-number)
  participant Snips as pythonCode (snippets)
  participant Err as UnsupportedBlockTypeError

  rect rgb(235,242,250)
    Caller->>Dispatcher: createPythonCode(block, executionContext?)
    Dispatcher->>Guards: check block type
    alt matched
      Guards-->>Dispatcher: type X
      Dispatcher->>Gen: createPythonCodeForXBlock(block, ctx?)
      Gen->>Snips: use python snippets / utils
      Gen-->>Dispatcher: python code string
      Dispatcher-->>Caller: return code
    else no match
      Guards-->>Dispatcher: none
      Dispatcher->>Err: throw UnsupportedBlockTypeError(block.type)
      Err-->>Caller: error
    end
  end
Loading
sequenceDiagram
  autonumber
  participant Caller
  participant Markdown as createMarkdown
  participant Text as text-blocks
  participant Image as image-blocks
  participant Sep as separator
  participant Err as UnsupportedBlockTypeError

  rect rgb(240,248,240)
    Caller->>Markdown: createMarkdown(block)
    alt text block
      Markdown->>Text: createMarkdownForTextBlock
      Text-->>Markdown: markdown
      Markdown-->>Caller: markdown
    else image
      Markdown->>Image: createMarkdownForImageBlock
      Image-->>Markdown: markdown
      Markdown-->>Caller: markdown
    else separator
      Markdown->>Sep: createMarkdownForSeparatorBlock
      Sep-->>Markdown: markdown
      Markdown-->>Caller: markdown
    else unsupported
      Markdown->>Err: throw UnsupportedBlockTypeError(block.type)
      Err-->>Caller: error
    end
  end
Loading
sequenceDiagram
  autonumber
  participant Caller
  participant Strip as stripMarkdown
  participant Text as text-blocks
  participant Err as UnsupportedBlockTypeError

  rect rgb(252,246,236)
    Caller->>Strip: stripMarkdown(block)
    alt text block
      Strip->>Text: stripMarkdownFromTextBlock
      Text-->>Strip: plain text
      Strip-->>Caller: plain text
    else non-text
      Strip->>Err: throw UnsupportedBlockTypeError(block.type)
      Err-->>Caller: error
    end
  end
Loading

Possibly related PRs

Suggested reviewers

  • saltenasl
  • jamesbhobbs

Pre-merge checks

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly and concisely summarizes the primary change—adding support to generate Python and Markdown content from Deepnote blocks—and is directly related to the implemented functionality without unnecessary detail.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5ce16ba and b6ab456.

📒 Files selected for processing (1)
  • packages/blocks/package.json (1 hunks)

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Oct 3, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.62948% with 37 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.67%. Comparing base (6208895) to head (b6ab456).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
packages/blocks/src/blocks/input-blocks.ts 81.63% 27 Missing ⚠️
packages/blocks/src/blocks/text-blocks.ts 94.36% 4 Missing ⚠️
packages/blocks/src/blocks/python-utils.ts 88.23% 2 Missing ⚠️
packages/blocks/src/index.ts 0.00% 2 Missing ⚠️
packages/blocks/src/python-code.ts 95.91% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##              main      #25      +/-   ##
===========================================
- Coverage   100.00%   92.67%   -7.33%     
===========================================
  Files            1       16      +15     
  Lines            3      505     +502     
  Branches         1      110     +109     
===========================================
+ Hits             3      468     +465     
- Misses           0       37      +37     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 14

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f61a336 and 50f36c6.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (24)
  • package.json (1 hunks)
  • packages/blocks/README.md (1 hunks)
  • packages/blocks/package.json (1 hunks)
  • packages/blocks/src/blocks.ts (1 hunks)
  • packages/blocks/src/blocks/big-number-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/blocks.test.ts (1 hunks)
  • packages/blocks/src/blocks/button-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/code-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/image-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/input-blocks.test.ts (1 hunks)
  • packages/blocks/src/blocks/input-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/markdown-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/python-utils.ts (1 hunks)
  • packages/blocks/src/blocks/separator-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/sql-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/sql-utils.ts (1 hunks)
  • packages/blocks/src/blocks/text-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/visualization-blocks.ts (1 hunks)
  • packages/blocks/src/index.ts (1 hunks)
  • packages/blocks/src/markdown.test.ts (1 hunks)
  • packages/blocks/src/markdown.ts (1 hunks)
  • packages/blocks/src/python-code.test.ts (1 hunks)
  • packages/blocks/src/python-code.ts (1 hunks)
  • packages/blocks/src/python-snippets.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-03T12:54:35.368Z
Learnt from: CR
PR: deepnote/vscode-extension#0
File: .github/instructions/interactiveWindow.instructions.md:0-0
Timestamp: 2025-09-03T12:54:35.368Z
Learning: Applies to src/interactive-window/**/*.ts : Add unit and integration tests for new features and modifications; include performance and cross-platform test coverage

Applied to files:

  • packages/blocks/src/markdown.test.ts
🧬 Code graph analysis (13)
packages/blocks/src/markdown.ts (2)
packages/blocks/src/blocks.ts (2)
  • DeepnoteBlock (1-7)
  • UnsupportedBlockTypeError (23-28)
packages/blocks/src/blocks/text-blocks.ts (3)
  • isTextBlock (117-132)
  • createMarkdownForTextBlock (134-167)
  • stripMarkdownFromTextBlock (169-199)
packages/blocks/src/blocks/image-blocks.ts (1)
packages/blocks/src/blocks.ts (2)
  • BlockMetadata (9-9)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/code-blocks.ts (1)
packages/blocks/src/blocks.ts (2)
  • ExecutableBlockMetadata (11-21)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/markdown-blocks.ts (1)
packages/blocks/src/blocks.ts (2)
  • BlockMetadata (9-9)
  • DeepnoteBlock (1-7)
packages/blocks/src/markdown.test.ts (2)
packages/blocks/src/blocks/text-blocks.ts (7)
  • Heading1TextBlock (73-77)
  • Heading2TextBlock (79-83)
  • Heading3TextBlock (85-89)
  • BulletTextBlock (93-97)
  • TodoTextBlock (99-103)
  • CalloutTextBlock (109-113)
  • ParagraphTextBlock (59-63)
packages/blocks/src/markdown.ts (2)
  • createMarkdown (4-10)
  • stripMarkdown (12-18)
packages/blocks/src/blocks/big-number-blocks.ts (2)
packages/blocks/src/blocks.ts (2)
  • ExecutableBlockMetadata (11-21)
  • DeepnoteBlock (1-7)
packages/blocks/src/python-snippets.ts (1)
  • pythonCode (5-112)
packages/blocks/src/blocks/blocks.test.ts (6)
packages/blocks/src/blocks/markdown-blocks.ts (2)
  • MarkdownBlock (7-11)
  • createPythonCodeForMarkdownBlock (13-15)
packages/blocks/src/blocks/separator-blocks.ts (2)
  • SeparatorBlock (5-9)
  • createPythonCodeForSeparatorBlock (11-13)
packages/blocks/src/blocks/image-blocks.ts (2)
  • ImageBlock (9-13)
  • createPythonCodeForImageBlock (15-21)
packages/blocks/src/blocks/button-blocks.ts (3)
  • ButtonBlock (12-16)
  • createPythonCodeForButtonBlock (26-38)
  • ButtonExecutionContext (18-24)
packages/blocks/src/blocks/big-number-blocks.ts (2)
  • BigNumberBlock (15-19)
  • createPythonCodeForBigNumberBlock (21-28)
packages/blocks/src/blocks/visualization-blocks.ts (2)
  • VisualizationBlock (12-16)
  • createPythonCodeForVisualizationBlock (18-31)
packages/blocks/src/python-snippets.ts (1)
packages/blocks/src/blocks/python-utils.ts (2)
  • sanitizePythonVariableName (9-27)
  • escapePythonString (1-7)
packages/blocks/src/blocks/sql-blocks.ts (3)
packages/blocks/src/blocks.ts (2)
  • ExecutableBlockMetadata (11-21)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/python-utils.ts (2)
  • sanitizePythonVariableName (9-27)
  • escapePythonString (1-7)
packages/blocks/src/blocks/sql-utils.ts (2)
  • convertToEnvironmentVariableName (1-9)
  • getSqlEnvVarName (11-13)
packages/blocks/src/blocks/separator-blocks.ts (2)
packages/blocks/src/blocks/text-blocks.ts (2)
  • SeparatorBlockMetadata (41-41)
  • SeparatorBlock (43-47)
packages/blocks/src/blocks.ts (2)
  • BlockMetadata (9-9)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/input-blocks.ts (3)
packages/blocks/src/python-snippets.ts (1)
  • pythonCode (5-112)
packages/blocks/src/blocks.ts (2)
  • ExecutableBlockMetadata (11-21)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/python-utils.ts (2)
  • sanitizePythonVariableName (9-27)
  • escapePythonString (1-7)
packages/blocks/src/blocks/input-blocks.test.ts (1)
packages/blocks/src/blocks/input-blocks.ts (16)
  • InputTextBlock (100-104)
  • createPythonCodeForInputTextBlock (159-162)
  • InputTextareaBlock (106-110)
  • createPythonCodeForInputTextareaBlock (164-167)
  • InputCheckboxBlock (112-116)
  • createPythonCodeForInputCheckboxBlock (169-172)
  • InputSelectBlock (118-122)
  • createPythonCodeForInputSelectBlock (174-187)
  • InputSliderBlock (124-128)
  • createPythonCodeForInputSliderBlock (189-192)
  • InputFileBlock (130-134)
  • createPythonCodeForInputFileBlock (194-200)
  • InputDateBlock (136-140)
  • createPythonCodeForInputDateBlock (202-222)
  • InputDateRangeBlock (142-146)
  • createPythonCodeForInputDateRangeBlock (224-255)
packages/blocks/src/python-code.test.ts (4)
packages/blocks/src/blocks/sql-blocks.ts (1)
  • SqlBlock (17-21)
packages/blocks/src/index.ts (1)
  • createPythonCode (2-2)
packages/blocks/src/python-code.ts (1)
  • createPythonCode (29-95)
packages/blocks/src/blocks/code-blocks.ts (1)
  • CodeBlock (5-9)
🪛 GitHub Actions: CI
packages/blocks/src/markdown.test.ts

[error] 15-15: Property 'blockGroup' is missing in type '{ id: string; type: "text-cell-h1"; content: string; metadata: {}; sortingKey: string; }' but required in type 'Heading1TextBlock'.

🪛 GitHub Check: Typecheck
packages/blocks/src/markdown.test.ts

[failure] 147-147:
Property 'blockGroup' is missing in type '{ id: string; type: "text-cell-h2"; content: string; metadata: {}; sortingKey: string; }' but required in type 'Heading2TextBlock'.


[failure] 133-133:
Property 'blockGroup' is missing in type '{ id: string; type: "text-cell-h1"; content: string; metadata: {}; sortingKey: string; }' but required in type 'Heading1TextBlock'.


[failure] 117-117:
Property 'blockGroup' is missing in type '{ id: string; type: "text-cell-p"; content: string; metadata: {}; sortingKey: string; }' but required in type 'ParagraphTextBlock'.


[failure] 103-103:
Property 'blockGroup' is missing in type '{ id: string; type: "text-cell-callout"; content: string; metadata: {}; sortingKey: string; }' but required in type 'CalloutTextBlock'.


[failure] 87-87:
Property 'blockGroup' is missing in type '{ id: string; type: "text-cell-todo"; content: string; metadata: { checked: true; }; sortingKey: string; }' but required in type 'TodoTextBlock'.


[failure] 71-71:
Property 'blockGroup' is missing in type '{ id: string; type: "text-cell-todo"; content: string; metadata: { checked: false; }; sortingKey: string; }' but required in type 'TodoTextBlock'.


[failure] 57-57:
Property 'blockGroup' is missing in type '{ id: string; type: "text-cell-bullet"; content: string; metadata: {}; sortingKey: string; }' but required in type 'BulletTextBlock'.


[failure] 43-43:
Property 'blockGroup' is missing in type '{ id: string; type: "text-cell-h3"; content: string; metadata: {}; sortingKey: string; }' but required in type 'Heading3TextBlock'.


[failure] 29-29:
Property 'blockGroup' is missing in type '{ id: string; type: "text-cell-h2"; content: string; metadata: {}; sortingKey: string; }' but required in type 'Heading2TextBlock'.


[failure] 15-15:
Property 'blockGroup' is missing in type '{ id: string; type: "text-cell-h1"; content: string; metadata: {}; sortingKey: string; }' but required in type 'Heading1TextBlock'.

🔇 Additional comments (21)
packages/blocks/src/index.ts (1)

1-2: LGTM!

Clean public API surface. Exports align with the new markdown and Python code generation features.

packages/blocks/src/blocks/sql-utils.ts (1)

11-13: LGTM!

Simple and clear SQL environment variable name construction.

packages/blocks/src/blocks/code-blocks.ts (1)

1-17: LGTM!

Well-defined CodeBlock type and straightforward Python code generation that simply returns the block content.

packages/blocks/src/blocks/markdown-blocks.ts (2)

13-15: Verify: Is returning raw markdown content as Python code intentional?

The function returns block.content directly, which for a markdown block would be markdown text, not Python code. If markdown blocks are meant to be displayed/rendered rather than executed, consider renaming or documenting this behavior to avoid confusion.

Do you want markdown blocks to generate Python code that displays the markdown, or is the current pass-through behavior correct for your use case?


17-19: LGTM!

Type guard is correct.

packages/blocks/src/markdown.ts (1)

4-18: LGTM!

Clear delegation pattern with descriptive error messages for unsupported block types. Currently handles text blocks only, which is well-communicated.

packages/blocks/src/blocks/python-utils.ts (1)

1-27: LGTM!

Well-implemented Python string escaping and variable name sanitization. Correct escape order (backslashes first) and sensible fallback for empty names.

packages/blocks/src/blocks/separator-blocks.ts (2)

11-13: LGTM!

Separator blocks render as HTML <hr> for display purposes. Consistent with other visual block types.


15-17: LGTM!

Type guard is correct.

packages/blocks/src/blocks/blocks.test.ts (1)

1-190: LGTM!

Comprehensive test coverage for block-to-Python code generation across multiple block types. Tests are clear, well-structured, and validate expected outputs.

packages/blocks/src/blocks/image-blocks.ts (1)

23-25: LGTM!

Type guard is correct and follows the standard pattern.

packages/blocks/src/python-code.ts (1)

29-95: LGTM!

Dispatcher pattern is clear, maintainable, and provides a helpful error message for unsupported types.

packages/blocks/src/blocks.ts (1)

1-28: LGTM!

Foundational types are well-defined and serve as building blocks for the ecosystem.

packages/blocks/src/blocks/button-blocks.ts (2)

26-38: LGTM!

Logic correctly handles variable context and behavior modes.


40-42: LGTM!

Type guard is correct.

packages/blocks/src/blocks/big-number-blocks.ts (1)

30-32: LGTM!

Type guard is correct.

packages/blocks/src/blocks/sql-blocks.ts (1)

54-56: LGTM!

Type guard is correct.

packages/blocks/src/blocks/text-blocks.ts (2)

117-132: LGTM!

Type guard correctly identifies all text block types with case-insensitive matching.


169-199: LGTM!

Regex patterns correctly strip Markdown syntax for each block type.

packages/blocks/src/blocks/input-blocks.ts (2)

45-50: Regex validates format, not date validity.

The regex /^\d{4}-\d{2}-\d{2}$/ accepts syntactically valid strings like "2025-02-30" that aren't real dates. If strict date validation is required, consider parsing with Date or a library.

Are invalid calendar dates (e.g., Feb 30) acceptable here, or should they be rejected?


218-221: V1 date parsing assumes strict ISO 8601 format.

The format string "%Y-%m-%dT%H:%M:%S.%fZ" will fail at runtime if deepnote_variable_value doesn't match exactly. V2 uses a more lenient parser. Ensure V1 values are always in this format.

Confirm that V1 date values always match this format, or consider adding error handling.

Comment thread packages/blocks/package.json Resolved
Comment thread packages/blocks/src/markdown.test.ts Resolved
Comment thread packages/blocks/src/python-snippets.ts Resolved
Comment thread packages/blocks/src/python-snippets.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 50f36c6 and a0d15e7.

📒 Files selected for processing (3)
  • packages/blocks/README.md (1 hunks)
  • packages/blocks/src/python-code.test.ts (1 hunks)
  • packages/blocks/src/python-code.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-03T12:54:35.368Z
Learnt from: CR
PR: deepnote/vscode-extension#0
File: .github/instructions/interactiveWindow.instructions.md:0-0
Timestamp: 2025-09-03T12:54:35.368Z
Learning: Applies to src/interactive-window/**/*.ts : Add unit and integration tests for new features and modifications; include performance and cross-platform test coverage

Applied to files:

  • packages/blocks/src/python-code.test.ts
🧬 Code graph analysis (1)
packages/blocks/src/python-code.test.ts (8)
packages/blocks/src/blocks/sql-blocks.ts (1)
  • SqlBlock (17-21)
packages/blocks/src/python-code.ts (1)
  • createPythonCode (27-85)
packages/blocks/src/index.ts (1)
  • createPythonCode (2-2)
packages/blocks/src/blocks/code-blocks.ts (1)
  • CodeBlock (5-9)
packages/blocks/src/blocks/image-blocks.ts (1)
  • ImageBlock (9-13)
packages/blocks/src/blocks/button-blocks.ts (2)
  • ButtonBlock (12-16)
  • ButtonExecutionContext (18-24)
packages/blocks/src/blocks/big-number-blocks.ts (1)
  • BigNumberBlock (15-19)
packages/blocks/src/blocks/visualization-blocks.ts (1)
  • VisualizationBlock (12-16)
🪛 GitHub Actions: CI
packages/blocks/README.md

[error] 72-72: cspell: Unknown word 'dntk'.


[error] 95-95: cspell: Unknown word 'timedelta'.


[error] 95-95: cspell: Unknown word 'timedelta'.


[error] 96-96: cspell: Unknown word 'timedelta'.

packages/blocks/src/python-code.test.ts

[error] 14-14: Unknown word (dataframe)


[error] 23-23: Unknown word (millis)


[error] 34-34: Unknown word (dntk)


[error] 39-39: Unknown word (dataframe)


[error] 192-192: Unknown word (dntk)

🔇 Additional comments (11)
packages/blocks/README.md (3)

1-45: LGTM!

Clear overview and comprehensive block type listing.


50-97: Examples are accurate.

Pipeline cspell errors for dntk and timedelta are false positives—these are valid domain-specific and Python standard library terms.

Add these terms to your cspell configuration or inline comments to suppress warnings:

<!-- cspell:ignore dntk timedelta -->

99-121: LGTM!

Markdown conversion examples are clear and correct.

packages/blocks/src/python-code.test.ts (7)

1-12: LGTM!

Imports and test structure are appropriate.


13-44: Comprehensive SQL block test.

Validates all key parameters of SQL code generation. Pipeline cspell errors (dataframe, millis, dntk) are false positives for technical terms.


46-62: LGTM!

Code block test correctly validates pass-through behavior.


64-83: LGTM!

Image block test validates HTML generation correctly.


85-142: LGTM!

Button block tests cover default state, execution context, and behavior modes comprehensively.


144-167: LGTM!

Big number test validates essential parts using partial assertions, appropriate for complex generated code.


169-210: LGTM!

Visualization tests cover both scenarios correctly. Pipeline cspell error (dntk) is a false positive.

packages/blocks/src/python-code.ts (1)

1-26: LGTM!

Imports are comprehensive and well-organized.

Comment thread packages/blocks/src/python-code.ts Resolved
@Artmann
Artmann force-pushed the chris/add-deepnote-blocks branch from 8e21231 to f530bd1 Compare October 3, 2025 10:48
@Artmann Artmann changed the title Chris/add deepnote blocks feat: Add support for creating Python and Markdown content from Deepnote blocks. Oct 3, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (9)
packages/blocks/package.json (1)

18-18: Correct the license field spelling.

npm only recognizes the license key; licence drops license metadata from the published package.

-  "licence": "Apache-2.0"
+  "license": "Apache-2.0"
packages/blocks/src/blocks/sql-utils.ts (1)

8-8: Remove unnecessary multiline flag.

The m flag in /[^\w]/gm is unnecessary since character classes don't use ^/$ anchors.

-  return upperCased.replace(/[^\w]/gm, '_')
+  return upperCased.replace(/[^\w]/g, '_')
packages/blocks/src/blocks/image-blocks.ts (1)

15-21: XSS risk: HTML attributes not escaped.

Raw metadata interpolation into HTML enables injection. Same issue as previous review.

packages/blocks/src/blocks/visualization-blocks.ts (1)

1-30: Sanitize the visualization variable name before emission.
deepnote_variable_name is emitted straight into Python, so spaces or punctuation break the generated code. Run it through sanitizePythonVariableName before calling pythonCode.executeVisualization.

-import { pythonCode } from '../python-snippets'
+import { pythonCode } from '../python-snippets'
+import { sanitizePythonVariableName } from './python-utils'
@@
-  return pythonCode.executeVisualization(variableName, escapedVegaLiteSpec, JSON.stringify(filters))
+  const sanitizedVariableName = sanitizePythonVariableName(variableName)
+
+  return pythonCode.executeVisualization(sanitizedVariableName, escapedVegaLiteSpec, JSON.stringify(filters))
packages/blocks/src/blocks/sql-blocks.ts (1)

44-51: Use the sanitized SQL variable name in generated code.
We compute sanitizedPythonVariableName but still emit the original identifier, so invalid characters slip through and the Python breaks. Emit the sanitized value in both assignment and return.

   if (sanitizedPythonVariableName === undefined) {
     return executeSqlFunctionCall
   }
 
   return dedent`
-    ${pythonVariableName} = ${executeSqlFunctionCall}
-    ${pythonVariableName}
+    ${sanitizedPythonVariableName} = ${executeSqlFunctionCall}
+    ${sanitizedPythonVariableName}
   `
packages/blocks/src/python-snippets.ts (2)

17-47: Escape big-number templates before embedding in Python.
titleTemplate and comparisonTitleTemplate go straight into Python strings; quotes or backslashes break the generated code. Escape them with the existing helper and call render_template on the safe form.

   ) => {
     const valuePart = valueVariableName ? `f"{${valueVariableName}}"` : `""`
     const comparisonValuePart = comparisonVariableName ? `f"{${comparisonVariableName}}"` : `""`
+    const escapedTitleTemplate = escapePythonString(titleTemplate)
+    const escapedComparisonTitleTemplate = escapePythonString(comparisonTitleTemplate)
 
     return `
 def __deepnote_big_number__():
@@
-    rendered_title = render_template("${titleTemplate}")
-    rendered_comparison_title = render_template("${comparisonTitleTemplate}")
+    rendered_title = render_template(${escapedTitleTemplate})
+    rendered_comparison_title = render_template(${escapedComparisonTitleTemplate})

65-110: Sanitize date range variable names.
Every helper drops name directly into Python, so spaces or punctuation produce invalid syntax. Sanitize the identifier before rendering.

-  dateRangePast7days: (name: string) => dedent`
-    from datetime import datetime as _deepnote_datetime, timedelta as _deepnote_timedelta
-    ${name} = [_deepnote_datetime.now().date() - _deepnote_timedelta(days=7), _deepnote_datetime.now().date()]
-  `,
+  dateRangePast7days: (name: string) => {
+    const sanitizedName = sanitizePythonVariableName(name)
+    return dedent`
+      from datetime import datetime as _deepnote_datetime, timedelta as _deepnote_timedelta
+      ${sanitizedName} = [_deepnote_datetime.now().date() - _deepnote_timedelta(days=7), _deepnote_datetime.now().date()]
+    `
+  },
@@
-  dateRangePast14days: (name: string) => dedent`
-    from datetime import datetime as _deepnote_datetime, timedelta as _deepnote_timedelta
-    ${name} = [_deepnote_datetime.now().date() - _deepnote_timedelta(days=14), _deepnote_datetime.now().date()]
-  `,
+  dateRangePast14days: (name: string) => {
+    const sanitizedName = sanitizePythonVariableName(name)
+    return dedent`
+      from datetime import datetime as _deepnote_datetime, timedelta as _deepnote_timedelta
+      ${sanitizedName} = [_deepnote_datetime.now().date() - _deepnote_timedelta(days=14), _deepnote_datetime.now().date()]
+    `
+  },
@@
-  dateRangePastMonth: (name: string) => dedent`
-    from datetime import datetime as _deepnote_datetime
-    from dateutil.relativedelta import relativedelta
-    ${name} = [_deepnote_datetime.now().date() - relativedelta(months=1), _deepnote_datetime.now().date()]
-  `,
+  dateRangePastMonth: (name: string) => {
+    const sanitizedName = sanitizePythonVariableName(name)
+    return dedent`
+      from datetime import datetime as _deepnote_datetime
+      from dateutil.relativedelta import relativedelta
+      ${sanitizedName} = [_deepnote_datetime.now().date() - relativedelta(months=1), _deepnote_datetime.now().date()]
+    `
+  },
@@
-  dateRangePast3months: (name: string) => dedent`
-    from datetime import datetime as _deepnote_datetime
-    from dateutil.relativedelta import relativedelta
-    ${name} = [_deepnote_datetime.now().date() - relativedelta(months=3), _deepnote_datetime.now().date()]
-  `,
+  dateRangePast3months: (name: string) => {
+    const sanitizedName = sanitizePythonVariableName(name)
+    return dedent`
+      from datetime import datetime as _deepnote_datetime
+      from dateutil.relativedelta import relativedelta
+      ${sanitizedName} = [_deepnote_datetime.now().date() - relativedelta(months=3), _deepnote_datetime.now().date()]
+    `
+  },
@@
-  dateRangePast6months: (name: string) => dedent`
-    from datetime import datetime as _deepnote_datetime
-    from dateutil.relativedelta import relativedelta
-    ${name} = [_deepnote_datetime.now().date() - relativedelta(months=6), _deepnote_datetime.now().date()]
-  `,
+  dateRangePast6months: (name: string) => {
+    const sanitizedName = sanitizePythonVariableName(name)
+    return dedent`
+      from datetime as _deepnote_datetime
+      from dateutil.relativedelta import relativedelta
+      ${sanitizedName} = [_deepnote_datetime.now().date() - relativedelta(months=6), _deepnote_datetime.now().date()]
+    `
+  },
@@
-  dateRangePastYear: (name: string) => dedent`
-    from datetime import datetime as _deepnote_datetime
-    from dateutil.relativedelta import relativedelta
-    ${name} = [_deepnote_datetime.now().date() - relativedelta(years=1), _deepnote_datetime.now().date()]
-  `,
+  dateRangePastYear: (name: string) => {
+    const sanitizedName = sanitizePythonVariableName(name)
+    return dedent`
+      from datetime import datetime as _deepnote_datetime
+      from dateutil.relativedelta import relativedelta
+      ${sanitizedName} = [_deepnote_datetime.now().date() - relativedelta(years=1), _deepnote_datetime.now().date()]
+    `
+  },
@@
-  dateRangeCustomDays: (name: string, days: number) => dedent`
-    from datetime import datetime, timedelta
-    ${name} = [datetime.now().date() - timedelta(days=${days}), datetime.now().date()]
-  `,
+  dateRangeCustomDays: (name: string, days: number) => {
+    const sanitizedName = sanitizePythonVariableName(name)
+    return dedent`
+      from datetime import datetime, timedelta
+      ${sanitizedName} = [datetime.now().date() - timedelta(days=${days}), datetime.now().date()]
+    `
+  },
@@
-  dateRangeAbsolute: (name: string, startDate: string, endDate: string) => {
-    const escapedStartDate = escapePythonString(startDate)
-    const escapedEndDate = escapePythonString(endDate)
-    return dedent`
-      from dateutil.parser import parse as _deepnote_parse
-      ${name} = [${startDate ? `_deepnote_parse(${escapedStartDate}).date()` : 'None'}, ${endDate ? `_deepnote_parse(${escapedEndDate}).date()` : 'None'}]
-    `
-  },
+  dateRangeAbsolute: (name: string, startDate: string, endDate: string) => {
+    const sanitizedName = sanitizePythonVariableName(name)
+    const escapedStartDate = escapePythonString(startDate)
+    const escapedEndDate = escapePythonString(endDate)
+    return dedent`
+      from dateutil.parser import parse as _deepnote_parse
+      ${sanitizedName} = [${startDate ? `_deepnote_parse(${escapedStartDate}).date()` : 'None'}, ${endDate ? `_deepnote_parse(${escapedEndDate}).date()` : 'None'}]
+    `
+  },
packages/blocks/src/blocks/text-blocks.ts (1)

134-167: Escape Markdown before interpolation.

User text inserted at Lines 134‑167 isn’t escaped, so characters like #, *, or [ break formatting. Add a small escape helper and use it for every branch (including todos/callouts) to keep literals intact.

@@
-import type { BlockMetadata, DeepnoteBlock } from '../blocks'
+import type { BlockMetadata, DeepnoteBlock } from '../blocks'
@@
 export type TextBlock = ParagraphTextBlock | HeadingTextBlock | BulletTextBlock | TodoTextBlock | CalloutTextBlock
+
+const MARKDOWN_ESCAPE = /([\\`*_{}\[\]()#+\-.!|>])/g
+
+function escapeMarkdown(text: string): string {
+  return text.replace(MARKDOWN_ESCAPE, '\\$1')
+}
 
 export function createMarkdownForTextBlock(block: TextBlock): string {
+  const escapedContent = escapeMarkdown(block.content)
+
   if (block.type === 'text-cell-h1') {
-    return `# ${block.content}`
+    return `# ${escapedContent}`
   }
 
   if (block.type === 'text-cell-h2') {
-    return `## ${block.content}`
+    return `## ${escapedContent}`
   }
 
   if (block.type === 'text-cell-h3') {
-    return `### ${block.content}`
+    return `### ${escapedContent}`
   }
 
   if (block.type === 'text-cell-bullet') {
-    return `- ${block.content}`
+    return `- ${escapedContent}`
   }
 
   if (block.type === 'text-cell-todo') {
     const metadata = block.metadata as TodoTextBlockMetadata
     const checkbox = metadata.checked ? '[x]' : '[ ]'
 
-    return `- ${checkbox} ${block.content}`
+    return `- ${checkbox} ${escapedContent}`
   }
 
   if (block.type === 'text-cell-callout') {
-    return `> ${block.content}`
+    return `> ${escapedContent}`
   }
 
   if (block.type === 'text-cell-p') {
-    return block.content
+    return escapedContent
   }
packages/blocks/src/blocks/input-blocks.ts (1)

189-192: Sanitize slider value before emitting Python.

Line 191 writes the raw string into Python. Non-numeric metadata (e.g., “abc” or “1e309foo”) produces invalid code. Parse and validate before emitting, falling back to None when it’s not finite.

 export function createPythonCodeForInputSliderBlock(block: InputSliderBlock): string {
   const sanitizedPythonVariableName = sanitizePythonVariableName(block.metadata.deepnote_variable_name)
-  return `${sanitizedPythonVariableName} = ${block.metadata.deepnote_variable_value}`
+  const numericValue = Number(block.metadata.deepnote_variable_value)
+  if (!Number.isFinite(numericValue)) {
+    return `${sanitizedPythonVariableName} = None`
+  }
+  return `${sanitizedPythonVariableName} = ${numericValue}`
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8e21231 and f530bd1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (23)
  • package.json (1 hunks)
  • packages/blocks/README.md (1 hunks)
  • packages/blocks/package.json (1 hunks)
  • packages/blocks/src/blocks.ts (1 hunks)
  • packages/blocks/src/blocks/big-number-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/button-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/code-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/image-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/input-blocks.test.ts (1 hunks)
  • packages/blocks/src/blocks/input-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/markdown-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/python-utils.ts (1 hunks)
  • packages/blocks/src/blocks/separator-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/sql-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/sql-utils.ts (1 hunks)
  • packages/blocks/src/blocks/text-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/visualization-blocks.ts (1 hunks)
  • packages/blocks/src/index.ts (1 hunks)
  • packages/blocks/src/markdown.test.ts (1 hunks)
  • packages/blocks/src/markdown.ts (1 hunks)
  • packages/blocks/src/python-code.test.ts (1 hunks)
  • packages/blocks/src/python-code.ts (1 hunks)
  • packages/blocks/src/python-snippets.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-03T12:54:35.368Z
Learnt from: CR
PR: deepnote/vscode-extension#0
File: .github/instructions/interactiveWindow.instructions.md:0-0
Timestamp: 2025-09-03T12:54:35.368Z
Learning: Applies to src/interactive-window/**/*.ts : Add unit and integration tests for new features and modifications; include performance and cross-platform test coverage

Applied to files:

  • packages/blocks/src/python-code.test.ts
🧬 Code graph analysis (9)
packages/blocks/src/blocks/markdown-blocks.ts (1)
packages/blocks/src/blocks.ts (2)
  • BlockMetadata (9-9)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/image-blocks.ts (1)
packages/blocks/src/blocks.ts (2)
  • BlockMetadata (9-9)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/separator-blocks.ts (2)
packages/blocks/src/blocks/text-blocks.ts (2)
  • SeparatorBlockMetadata (41-41)
  • SeparatorBlock (43-47)
packages/blocks/src/blocks.ts (2)
  • BlockMetadata (9-9)
  • DeepnoteBlock (1-7)
packages/blocks/src/python-snippets.ts (1)
packages/blocks/src/blocks/python-utils.ts (2)
  • sanitizePythonVariableName (9-27)
  • escapePythonString (1-7)
packages/blocks/src/blocks/text-blocks.ts (2)
packages/blocks/src/blocks.ts (2)
  • BlockMetadata (9-9)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/separator-blocks.ts (2)
  • SeparatorBlockMetadata (3-3)
  • SeparatorBlock (5-9)
packages/blocks/src/blocks/visualization-blocks.ts (2)
packages/blocks/src/blocks.ts (2)
  • ExecutableBlockMetadata (11-21)
  • DeepnoteBlock (1-7)
packages/blocks/src/python-snippets.ts (1)
  • pythonCode (5-112)
packages/blocks/src/blocks/code-blocks.ts (1)
packages/blocks/src/blocks.ts (2)
  • ExecutableBlockMetadata (11-21)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/input-blocks.test.ts (1)
packages/blocks/src/blocks/input-blocks.ts (16)
  • InputTextBlock (100-104)
  • createPythonCodeForInputTextBlock (159-162)
  • InputTextareaBlock (106-110)
  • createPythonCodeForInputTextareaBlock (164-167)
  • InputCheckboxBlock (112-116)
  • createPythonCodeForInputCheckboxBlock (169-172)
  • InputSelectBlock (118-122)
  • createPythonCodeForInputSelectBlock (174-187)
  • InputSliderBlock (124-128)
  • createPythonCodeForInputSliderBlock (189-192)
  • InputFileBlock (130-134)
  • createPythonCodeForInputFileBlock (194-200)
  • InputDateBlock (136-140)
  • createPythonCodeForInputDateBlock (202-222)
  • InputDateRangeBlock (142-146)
  • createPythonCodeForInputDateRangeBlock (224-255)
packages/blocks/src/markdown.test.ts (4)
packages/blocks/src/blocks/text-blocks.ts (8)
  • Heading1TextBlock (73-77)
  • Heading2TextBlock (79-83)
  • Heading3TextBlock (85-89)
  • BulletTextBlock (93-97)
  • TodoTextBlock (99-103)
  • CalloutTextBlock (109-113)
  • ParagraphTextBlock (59-63)
  • SeparatorBlock (43-47)
packages/blocks/src/markdown.ts (2)
  • createMarkdown (6-20)
  • stripMarkdown (22-28)
packages/blocks/src/blocks/separator-blocks.ts (1)
  • SeparatorBlock (5-9)
packages/blocks/src/blocks/image-blocks.ts (1)
  • ImageBlock (9-13)
🪛 GitHub Actions: CI
packages/blocks/src/blocks.ts

[error] 13-13: Unknown word 'millis'.

packages/blocks/README.md

[error] 73-73: Unknown word 'dntk'.


[error] 96-96: Unknown word 'timedelta'.


[error] 97-97: Unknown word 'timedelta'.

package.json

[error] 18-18: Unknown word 'licence'.

packages/blocks/src/blocks/input-blocks.test.ts

[error] 254-254: Unknown word 'dateutil'.


[error] 300-300: Unknown word 'dateutil'.


[error] 321-321: Unknown word 'timedelta'.


[error] 321-321: Unknown word 'timedelta'.


[error] 322-322: Unknown word 'timedelta'.


[error] 342-342: Unknown word 'timedelta'.


[error] 343-343: Unknown word 'timedelta'.

packages/blocks/package.json

[error] 18-18: Unknown word 'licence'.

🔇 Additional comments (22)
packages/blocks/README.md (1)

73-73: Add Python identifiers to spell-checker dictionary.

The CI spell-checker flags dntk and timedelta as unknown, but these are valid Python module/class names used in the generated code examples.

Add these terms to your cspell configuration (typically .cspell.json or similar):

{
  "words": [
    "dntk",
    "timedelta",
    "dateutil"
  ]
}

Also applies to: 96-97

packages/blocks/src/blocks/input-blocks.test.ts (1)

1-346: LGTM! Comprehensive test coverage.

The test suite thoroughly validates Python code generation for all input block types with proper escaping, type conversion, and edge cases.

Note: The spell-checker flags dateutil and timedelta (lines 254, 300, 321-322, 342-343) are false positives—these are valid Python standard library identifiers. Add them to your spell-checker dictionary as suggested in the README review.

packages/blocks/src/markdown.test.ts (1)

1-280: LGTM! Test fixtures are complete.

All block fixtures now include the required blockGroup field, and todo blocks properly include checked metadata. The test suite comprehensively validates markdown conversion for all supported block types.

packages/blocks/src/index.ts (1)

1-2: LGTM! Clean public API surface.

The exports provide a focused interface for markdown and Python code generation.

packages/blocks/src/blocks/python-utils.ts (2)

1-7: LGTM! Proper escape ordering.

Escaping backslashes first prevents double-escaping downstream replacements.


9-27: LGTM! Correct Python identifier rules.

The sanitization properly enforces Python's identifier syntax (alphanumeric + underscore, no leading digit) with a sensible fallback.

packages/blocks/src/blocks/markdown-blocks.ts (2)

3-11: LGTM!

Type definitions are clean and consistent with the block architecture.


13-19: LGTM!

Functions correctly implement the Markdown block contract. Returning raw content is appropriate here.

packages/blocks/src/python-code.test.ts (1)

1-407: Excellent test coverage!

Comprehensive tests across all block types with good edge case handling. Meets the learning requirement for thorough unit testing.

packages/blocks/src/blocks/code-blocks.ts (2)

1-9: LGTM!

Type definitions correctly extend ExecutableBlockMetadata for execution tracking.


11-17: LGTM!

Functions correctly implement code block behavior.

packages/blocks/src/blocks/separator-blocks.ts (2)

1-9: LGTM!

Good use of literal type content: '' to enforce separator blocks have no content.


11-17: LGTM!

Hardcoded output eliminates injection risk. Type guard correct.

packages/blocks/src/blocks/image-blocks.ts (2)

1-13: LGTM!

Type definitions are sound.


23-25: LGTM!

Type guard correct.

packages/blocks/src/python-code.ts (2)

1-26: LGTM!

Clean imports and proper typing.


27-80: Dispatcher logic correct.

Systematically routes all block types. Past map-based refactor suggestion was optional; current approach is clear.

packages/blocks/src/markdown.ts (2)

1-20: LGTM!

Dispatcher correctly routes text, separator, and image blocks to Markdown generators.


22-28: LGTM!

Correctly limits strip operation to text blocks only.

packages/blocks/src/blocks.ts (3)

1-9: LGTM!

Base types are well-defined.


11-21: Pipeline spell-check false positive.

"millis" on line 13 is a standard abbreviation for milliseconds. Add to dictionary or ignore.


23-28: LGTM!

Error class follows standard pattern.

Comment thread package.json Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

♻️ Duplicate comments (1)
packages/blocks/src/blocks/input-blocks.ts (1)

35-37: Tighten customDays validation to avoid NaN output.

Line 35 lets inputs like customDays10abc slip through because parseInt ignores the suffix. When we later hit Line 252, Number('10abc') becomes NaN, so the emitted Python ends up with timedelta(days=NaN) and crashes at runtime. Please require the value to be exactly customDays followed by digits before parsing.

-  const days = Number.parseInt(value.split('customDays')[1] ?? '0', 10)
-
-  return value.startsWith('customDays') && !Number.isNaN(days) && days >= 0
+  const match = /^customDays(\d+)$/.exec(value)
+  if (!match) {
+    return false
+  }
+  const days = Number.parseInt(match[1], 10)
+  return days >= 0
-    const customDays = block.metadata.deepnote_variable_value.replace('customDays', '')
-    return pythonCode.dateRangeCustomDays(sanitizedPythonVariableName, Number(customDays))
+    const match = /^customDays(\d+)$/.exec(block.metadata.deepnote_variable_value)
+    if (!match) {
+      throw new Error(`Invalid customDays range: "${block.metadata.deepnote_variable_value}".`)
+    }
+    const customDays = Number.parseInt(match[1], 10)
+    return pythonCode.dateRangeCustomDays(sanitizedPythonVariableName, customDays)

Also applies to: 251-253

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f530bd1 and 1dd48d4.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (9)
  • packages/blocks/package.json (1 hunks)
  • packages/blocks/src/blocks/input-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/sql-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/sql-utils.ts (1 hunks)
  • packages/blocks/src/blocks/text-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/visualization-blocks.ts (1 hunks)
  • packages/blocks/src/markdown.test.ts (1 hunks)
  • packages/blocks/src/python-code.test.ts (1 hunks)
  • packages/blocks/src/python-snippets.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-09-24T21:30:04.182Z
Learnt from: jankuca
PR: deepnote/deepnote#18525
File: apps/webapp-client/src/features/project-table-of-contents/markdown-toc-utils.test.ts:230-239
Timestamp: 2025-09-24T21:30:04.182Z
Learning: In the markdown ToC parsing functionality (apps/webapp-client/src/features/project-table-of-contents/markdown-toc-utils.ts), only 3-backtick fenced code blocks are recognized and their content is ignored when parsing headings. 4-backtick or other fence lengths are intentionally not supported and their content will be processed as regular markdown.

Applied to files:

  • packages/blocks/src/blocks/text-blocks.ts
📚 Learning: 2025-09-03T12:54:35.368Z
Learnt from: CR
PR: deepnote/vscode-extension#0
File: .github/instructions/interactiveWindow.instructions.md:0-0
Timestamp: 2025-09-03T12:54:35.368Z
Learning: Applies to src/interactive-window/**/*.ts : Add unit and integration tests for new features and modifications; include performance and cross-platform test coverage

Applied to files:

  • packages/blocks/src/python-code.test.ts
🧬 Code graph analysis (3)
packages/blocks/src/blocks/sql-blocks.ts (3)
packages/blocks/src/blocks.ts (2)
  • ExecutableBlockMetadata (11-21)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/python-utils.ts (2)
  • sanitizePythonVariableName (9-27)
  • escapePythonString (1-7)
packages/blocks/src/blocks/sql-utils.ts (2)
  • convertToEnvironmentVariableName (1-9)
  • getSqlEnvVarName (11-13)
packages/blocks/src/python-snippets.ts (1)
packages/blocks/src/blocks/python-utils.ts (2)
  • sanitizePythonVariableName (9-27)
  • escapePythonString (1-7)
packages/blocks/src/blocks/input-blocks.ts (3)
packages/blocks/src/python-snippets.ts (1)
  • pythonCode (5-135)
packages/blocks/src/blocks.ts (2)
  • ExecutableBlockMetadata (11-21)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/python-utils.ts (2)
  • sanitizePythonVariableName (9-27)
  • escapePythonString (1-7)
🪛 GitHub Actions: CI
packages/blocks/src/blocks/sql-blocks.ts

[error] 7-7: Unknown word: dataframe


[error] 27-27: Unknown word: dataframe


[error] 36-36: Unknown word: dntk

packages/blocks/src/python-snippets.ts

[error] 55-55: Unknown word: compitability


[error] 57-57: Unknown word: dntk


[error] 58-58: Unknown word: dntk


[error] 61-61: Unknown word: dntk


[error] 69-69: Unknown word: timedelta


[error] 69-69: Unknown word: timedelta


[error] 70-70: Unknown word: timedelta


[error] 77-77: Unknown word: timedelta


[error] 77-77: Unknown word: timedelta


[error] 86-86: Unknown word: dateutil


[error] 86-86: Unknown word: relativedelta


[error] 86-86: Unknown word: relativedelta


[error] 87-87: Unknown word: relativedelta


[error] 95-95: Unknown word: dateutil

packages/blocks/src/python-code.test.ts

[error] 23-23: Unknown word: dataframe


[error] 32-32: Unknown word: millis


[error] 43-43: Unknown word: dntk


[error] 48-48: Unknown word: dataframe


[error] 211-211: Unknown word: dntk


[error] 211-211: Unknown word: dntk


[error] 211-211: Unknown word: dntk


[error] 358-358: Unknown word: dateutil


[error] 380-380: Unknown word: dateutil


[error] 401-401: Unknown word: timedelta


[error] 401-401: Unknown word: timedelta


[error] 402-402: Unknown word: timedelta

packages/blocks/src/blocks/input-blocks.ts

[error] 229-229: Unknown word: dateutil


[error] 235-235: Unknown word: strptime

Comment thread packages/blocks/src/python-code.test.ts Resolved
Comment thread packages/blocks/src/python-snippets.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1dd48d4 and aa72a1f.

📒 Files selected for processing (4)
  • cspell.json (1 hunks)
  • packages/blocks/src/blocks/sql-blocks.ts (1 hunks)
  • packages/blocks/src/python-code.test.ts (1 hunks)
  • packages/blocks/src/python-snippets.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-03T12:54:35.368Z
Learnt from: CR
PR: deepnote/vscode-extension#0
File: .github/instructions/interactiveWindow.instructions.md:0-0
Timestamp: 2025-09-03T12:54:35.368Z
Learning: Applies to src/interactive-window/**/*.ts : Add unit and integration tests for new features and modifications; include performance and cross-platform test coverage

Applied to files:

  • packages/blocks/src/python-code.test.ts
🧬 Code graph analysis (3)
packages/blocks/src/python-code.test.ts (8)
packages/blocks/src/blocks/sql-blocks.ts (1)
  • SqlBlock (17-21)
packages/blocks/src/index.ts (1)
  • createPythonCode (2-2)
packages/blocks/src/python-code.ts (1)
  • createPythonCode (26-80)
packages/blocks/src/blocks/code-blocks.ts (1)
  • CodeBlock (5-9)
packages/blocks/src/blocks/button-blocks.ts (1)
  • ButtonBlock (12-16)
packages/blocks/src/blocks/big-number-blocks.ts (1)
  • BigNumberBlock (15-19)
packages/blocks/src/blocks/visualization-blocks.ts (1)
  • VisualizationBlock (13-17)
packages/blocks/src/blocks/input-blocks.ts (8)
  • InputTextBlock (100-104)
  • InputTextareaBlock (106-110)
  • InputCheckboxBlock (112-116)
  • InputSelectBlock (118-122)
  • InputSliderBlock (124-128)
  • InputFileBlock (130-134)
  • InputDateBlock (136-140)
  • InputDateRangeBlock (142-146)
packages/blocks/src/python-snippets.ts (1)
packages/blocks/src/blocks/python-utils.ts (2)
  • sanitizePythonVariableName (9-27)
  • escapePythonString (1-7)
packages/blocks/src/blocks/sql-blocks.ts (3)
packages/blocks/src/blocks.ts (2)
  • ExecutableBlockMetadata (11-21)
  • DeepnoteBlock (1-7)
packages/blocks/src/blocks/python-utils.ts (2)
  • sanitizePythonVariableName (9-27)
  • escapePythonString (1-7)
packages/blocks/src/blocks/sql-utils.ts (2)
  • convertToEnvironmentVariableName (1-9)
  • getSqlEnvVarName (11-13)
🔇 Additional comments (8)
cspell.json (1)

48-55: New vocabulary aligns with the added block features.
Looks consistent with the new dateutil/dataframe machinery.

packages/blocks/src/python-snippets.ts (4)

6-9: LGTM!

Variable name is sanitized and boolean mapping is correct.


40-41: Previous injection issue resolved.

Templates are now escaped correctly.


61-111: Previous sanitization issues resolved.

All date range helpers now correctly sanitize variable names.


121-129: LGTM!

Variable name sanitization and date string escaping are correct.

packages/blocks/src/python-code.test.ts (3)

55-71: LGTM!

Code block passthrough correctly tested.


73-130: LGTM!

Button block tests cover all behaviors: set_variable with/without context, and run behavior.


187-228: LGTM!

Visualization tests cover main path and missing variable name guard.

Comment thread packages/blocks/src/python-code.test.ts Resolved
Comment thread packages/blocks/src/python-code.test.ts Resolved
Comment thread packages/blocks/src/python-code.test.ts Resolved
Comment thread packages/blocks/src/python-snippets.ts Resolved
Comment thread packages/blocks/src/python-snippets.ts Resolved
Comment thread packages/blocks/src/python-snippets.ts Resolved
@Artmann

Artmann commented Oct 3, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai can you review again?

@coderabbitai

coderabbitai Bot commented Oct 3, 2025

Copy link
Copy Markdown
Contributor

@Artmann: I'll review the changes in this PR.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

1 similar comment
@coderabbitai

coderabbitai Bot commented Oct 3, 2025

Copy link
Copy Markdown
Contributor

@Artmann: I'll review the changes in this PR.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 3, 2025
coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 3, 2025
@Artmann
Artmann marked this pull request as ready for review October 3, 2025 13:34
@Artmann
Artmann requested a review from jankuca October 3, 2025 13:34
@jankuca

jankuca commented Oct 3, 2025

Copy link
Copy Markdown
Contributor

It's currently dead code right? I'm not seeing any usage of the createPythonCode function.

@Artmann

Artmann commented Oct 3, 2025

Copy link
Copy Markdown
Contributor Author

It's currently dead code right? I'm not seeing any usage of the createPythonCode function.

Yeah, it will be used in the extensions.

@jankuca

jankuca commented Oct 3, 2025

Copy link
Copy Markdown
Contributor

Ok, what are the next steps when it comes to unifying this with the deepnote-internal logic?

@Artmann

Artmann commented Oct 3, 2025

Copy link
Copy Markdown
Contributor Author

Ok, what are the next steps when it comes to unifying this with the deepnote-internal logic?

Once we are happy with this, we should be able to use it from our internal app as well. The way we map the blocks against the database is slightly different, so I haven't included it here; we'll have to handle that separately.

So, deepnote.com and the Code extension will have their own code to handle the blocks and persist them, but we can use this package to generate the Python and Markdown code that the Deepnote Kernel will use.

@jankuca

jankuca commented Oct 3, 2025

Copy link
Copy Markdown
Contributor

Great, so the goal is to replace our internal block->python logic with this package. We should do that ASAP to avoid any potential drift between these implementations. The code already looks a little different I notice.

Comment thread packages/blocks/src/blocks.ts Outdated
Comment on lines +6 to +9
type: string
}

export type BlockMetadata = Record<string, unknown>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this deliberately loosely typed without a strict discriminated union with keys based on the supported block types?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do see that this is being extended by the specific subtypes but we are still using this type in functions like createPythonCode(). I would expect that such functions would get a union of the specific types, not the permissive base type.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that's a good point. I'll change that :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e3e725a and 5ce16ba.

📒 Files selected for processing (5)
  • packages/blocks/src/blocks.ts (1 hunks)
  • packages/blocks/src/blocks/image-blocks.ts (1 hunks)
  • packages/blocks/src/blocks/text-blocks.ts (1 hunks)
  • packages/blocks/src/markdown.test.ts (1 hunks)
  • packages/blocks/src/markdown.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-09-03T12:54:35.368Z
Learnt from: CR
PR: deepnote/vscode-extension#0
File: .github/instructions/interactiveWindow.instructions.md:0-0
Timestamp: 2025-09-03T12:54:35.368Z
Learning: Applies to src/interactive-window/**/*.ts : Add unit and integration tests for new features and modifications; include performance and cross-platform test coverage

Applied to files:

  • packages/blocks/src/markdown.test.ts
📚 Learning: 2025-09-24T21:30:04.182Z
Learnt from: jankuca
PR: deepnote/deepnote#18525
File: apps/webapp-client/src/features/project-table-of-contents/markdown-toc-utils.test.ts:230-239
Timestamp: 2025-09-24T21:30:04.182Z
Learning: In the markdown ToC parsing functionality (apps/webapp-client/src/features/project-table-of-contents/markdown-toc-utils.ts), only 3-backtick fenced code blocks are recognized and their content is ignored when parsing headings. 4-backtick or other fence lengths are intentionally not supported and their content will be processed as regular markdown.

Applied to files:

  • packages/blocks/src/blocks/text-blocks.ts
🧬 Code graph analysis (4)
packages/blocks/src/blocks/image-blocks.ts (1)
packages/blocks/src/blocks.ts (1)
  • DeepnoteBlock (19-25)
packages/blocks/src/markdown.ts (3)
packages/blocks/src/blocks.ts (2)
  • DeepnoteBlock (19-25)
  • UnsupportedBlockTypeError (58-63)
packages/blocks/src/blocks/text-blocks.ts (5)
  • isTextBlock (111-123)
  • createMarkdownForTextBlock (129-162)
  • isSeparatorBlock (201-203)
  • createMarkdownForSeparatorBlock (197-199)
  • stripMarkdownFromTextBlock (164-195)
packages/blocks/src/blocks/image-blocks.ts (2)
  • isImageBlock (44-46)
  • createMarkdownForImageBlock (36-42)
packages/blocks/src/markdown.test.ts (5)
packages/blocks/src/blocks/text-blocks.ts (8)
  • Heading1TextBlock (67-71)
  • Heading2TextBlock (73-77)
  • Heading3TextBlock (79-83)
  • BulletTextBlock (87-91)
  • TodoTextBlock (93-97)
  • CalloutTextBlock (103-107)
  • ParagraphTextBlock (59-63)
  • SeparatorBlock (43-47)
packages/blocks/src/markdown.ts (2)
  • createMarkdown (11-25)
  • stripMarkdown (27-33)
packages/blocks/src/blocks/image-blocks.ts (1)
  • ImageBlock (9-13)
packages/blocks/src/blocks.ts (1)
  • UnsupportedBlockTypeError (58-63)
packages/blocks/src/blocks/code-blocks.ts (1)
  • CodeBlock (5-9)
packages/blocks/src/blocks/text-blocks.ts (1)
packages/blocks/src/blocks.ts (1)
  • DeepnoteBlock (19-25)
🔇 Additional comments (4)
packages/blocks/src/markdown.ts (1)

11-33: LGTM!

Clean dispatch pattern with appropriate error handling. The routing logic is clear and extensible.

packages/blocks/src/markdown.test.ts (1)

17-315: LGTM!

Comprehensive test coverage across all supported block types with proper error handling verification.

packages/blocks/src/blocks/image-blocks.ts (1)

15-42: LGTM!

Proper HTML attribute escaping and input sanitization address the XSS concerns from the previous review.

packages/blocks/src/blocks.ts (1)

19-63: LGTM!

Core type definitions and error class are well-structured. The loose typing concern is acknowledged and tracked separately per the PR discussion.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 5, 2025
andyjakubowski
andyjakubowski previously approved these changes Oct 6, 2025
@andyjakubowski

Copy link
Copy Markdown
Contributor

I opened a stacked PR to add config for tsdown build outputs, so that the @deepnote/blocks can be installed in other projects like vscode-deepnote or jupyterlab-deepnote for local development: #27

…#27)

* chore(blocks): build package in ESM and CommonJS formats

Signed-off-by: Andy Jakubowski <hello@andyjakubowski.com>

* Tweak exports setup

Signed-off-by: Andy Jakubowski <hello@andyjakubowski.com>

* Tweak paths

Signed-off-by: Andy Jakubowski <hello@andyjakubowski.com>

* Update packages/blocks/package.json

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Signed-off-by: Andy Jakubowski <hello@andyjakubowski.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants