Skip to content

feat(block-schema): more strict block schema based on discriminated union of block types - #201

Merged
saltenasl merged 18 commits into
mainfrom
ls/more-strict-block-schema
Jan 8, 2026
Merged

saltenasl merged 18 commits into
mainfrom
ls/more-strict-block-schema

Conversation

@saltenasl

@saltenasl saltenasl commented Jan 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Input-select blocks now serialize a selected-variable field.
    • Consolidated block schema exposes many block variants for broader format support.
  • Refactor

    • Centralized type/schema surface and unified imports.
    • Outputs are now sorted alphabetically for stable serialization.
  • Bug Fixes

    • More resilient handling of optional metadata and execution fields.
  • Tests

    • Fixtures and assertions updated to match the new schema and conditional checks.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 7, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Centralizes block schemas into packages/blocks/src/deserialize-file/deepnote-file-schema.ts as a discriminated union (DeepnoteBlock) and exports concrete block variant types. Removes many locally exported block-type interfaces across blocks/* and updates those modules to import types from the shared schema. Adds an input-select metadata field (deepnote_variable_selected_variable) and other input metadata. Makes metadata and execution-field access defensive (optional chaining / guarded extraction). Conversion now validates via the schema, sorts keys alphabetically before emitting, and adjusts tests to account for optional execution fields and the new schema types.

Sequence Diagram(s)

sequenceDiagram
  participant File as Deepnote file (YAML/JSON)
  participant Parser as deepnote-file-schema.parse
  participant Blocks as blocks/* (generators)
  participant Convert as convert/* (serializers)
  participant Output as Jupyter/Deepnote output

  File->>Parser: load & validate blocks (discriminated union)
  Note right of Parser: unified block schemas\nincludes new input-select metadata
  Parser-->>Blocks: typed DeepnoteBlock objects
  Blocks->>Blocks: generate code/markdown (use optional chaining)
  Blocks-->>Convert: blocks (execution fields guarded)
  Convert->>Convert: sortKeysAlphabetically(parsed)
  Convert-->>Output: emit cells/doc (stable keys, guarded execution/outputs)
Loading

Suggested reviewers

  • Artmann
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.53% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Title clearly summarizes the main change: migrating to a stricter block schema using discriminated unions by block type.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@codecov

codecov Bot commented Jan 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.52%. Comparing base (8c555e2) to head (f23bbc6).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #201      +/-   ##
==========================================
+ Coverage   91.30%   91.52%   +0.21%     
==========================================
  Files          40       40              
  Lines        1979     2029      +50     
  Branches      631      645      +14     
==========================================
+ Hits         1807     1857      +50     
  Misses        172      172              

☔ 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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/convert/src/jupyter-to-deepnote.ts (1)

231-243: Type assertion masks potential discriminated union mismatches.

The as DeepnoteBlock assertion bypasses compile-time verification that the constructed object satisfies all block type variants. If specific block types require additional fields, this won't be caught.

Consider validating the constructed block against the schema before returning:

// At the end of convertCellToBlock, before returning:
const block = { /* ... current construction ... */ }
const validated = deepnoteBlockSchema.parse(block) // throws if invalid
return validated

This ensures runtime validation catches any mismatches between the constructed object and the discriminated union requirements.

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

186-198: Double type assertion bypasses type safety.

The as unknown as ImageBlock cast circumvents TypeScript's type checking. While the comment explains it's for testing sanitization of arbitrary values, this pattern can hide genuine type mismatches.

Consider alternatives:

  1. Create a test helper that constructs valid ImageBlocks
  2. Use type satisfaction (satisfies ImageBlock) to maintain some type checking
  3. Mock only the specific fields needed for the test
♻️ Alternative approach using type satisfaction
-    // Using type assertion since the test checks sanitization of arbitrary width values
-    const block = {
+    const block: ImageBlock = {
       id: '123',
-      type: 'image' as const,
+      type: 'image',
       content: '',
       blockGroup: 'abc',
       sortingKey: 'a0',
       metadata: {
         deepnote_img_src: 'https://example.com/image.png',
         deepnote_img_width: '500',
         deepnote_img_alignment: 'center',
       },
-    } as unknown as ImageBlock
+    }

If this fails compilation, it indicates the schema should be updated to allow the test data.

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

6-9: Missing optional chaining on metadata access.

Lines 6-9 access block.metadata.deepnote_big_number_title etc. directly, but other refactored files (button-blocks.ts:14, visualization-blocks.ts:6-8) use optional chaining (block.metadata?.field). If metadata is optional in the shared schema, this will throw at runtime.

🔧 Proposed fix
 export function createPythonCodeForBigNumberBlock(block: BigNumberBlock): string {
   return pythonCode.executeBigNumber(
-    block.metadata.deepnote_big_number_title ?? '',
-    block.metadata.deepnote_big_number_value ?? '',
-    block.metadata.deepnote_big_number_comparison_title,
-    block.metadata.deepnote_big_number_comparison_value
+    block.metadata?.deepnote_big_number_title ?? '',
+    block.metadata?.deepnote_big_number_value ?? '',
+    block.metadata?.deepnote_big_number_comparison_title,
+    block.metadata?.deepnote_big_number_comparison_value
   )
 }
🤖 Fix all issues with AI agents
In @packages/blocks/src/blocks/text-blocks.ts:
- Around line 113-118: The cast to TodoTextBlockMetadata in the text-cell-todo
branch is redundant and can hide schema type drift; instead, use the
schema-inferred metadata directly (access block.metadata.checked) or narrow the
block to the TextCellTodoBlock type before reading metadata so you don't bypass
compiler-checked types—remove the explicit "as TodoTextBlockMetadata" cast in
the block.type === 'text-cell-todo' branch and read checked from the inferred
metadata (or add a local type guard that asserts TextCellTodoBlock) so the
checkbox logic uses the schema type rather than a manual cast.

In @packages/convert/src/deepnote-to-jupyter.ts:
- Around line 131-137: The current type assertion on DeepnoteBlock (assigned to
executableBlock) bypasses the discriminated union; implement a type guard
function isExecutableBlock(block: DeepnoteBlock): block is DeepnoteBlock & {
executionStartedAt?: string; executionFinishedAt?: string; executionCount?:
number; outputs?: unknown[] } that checks the block.type for the executable
kind(s) (e.g., 'code'), then replace the assertion by setting executableBlock
only when isExecutableBlock(block) returns true (e.g., const executableBlock =
isExecutableBlock(block) ? block : null) and update subsequent accesses to use
the guarded executableBlock.

In @packages/convert/src/jupyter-to-deepnote.ts:
- Line 210: The code assigns blockType by force-casting untrusted
deepnoteCellType from notebook metadata to DeepnoteBlock['type'] which bypasses
validation; update the logic in jupyter-to-deepnote.ts (around the blockType
assignment) to validate deepnoteCellType at runtime before using it — either
check it against the allowed DeepnoteBlock types (e.g., an isValidDeepnoteType
helper or a set/enum of allowed values) or run it through the DeepnoteBlock
schema validator (e.g., DeepnoteBlockSchema.parse/validate) and fall back to the
existing ternary (cell.cell_type === 'code' ? 'code' : 'markdown') if invalid,
ensuring no direct type assertion of metadata values.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d390e71 and f9563be.

📒 Files selected for processing (24)
  • examples/2_blocks.deepnote
  • packages/blocks/src/blocks.ts
  • packages/blocks/src/blocks/big-number-blocks.ts
  • packages/blocks/src/blocks/button-blocks.ts
  • packages/blocks/src/blocks/code-blocks.ts
  • packages/blocks/src/blocks/data-frame.test.ts
  • packages/blocks/src/blocks/data-frame.ts
  • packages/blocks/src/blocks/image-blocks.ts
  • packages/blocks/src/blocks/input-blocks.test.ts
  • packages/blocks/src/blocks/input-blocks.ts
  • packages/blocks/src/blocks/sql-blocks.ts
  • packages/blocks/src/blocks/text-blocks.ts
  • packages/blocks/src/blocks/visualization-blocks.ts
  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
  • packages/blocks/src/deserialize-file/deserialize-deepnote-file.test.ts
  • packages/blocks/src/markdown.test.ts
  • packages/blocks/src/python-code.test.ts
  • packages/convert/src/deepnote-to-jupyter.ts
  • packages/convert/src/deepnote-to-percent.test.ts
  • packages/convert/src/jupyter-to-deepnote.test.ts
  • packages/convert/src/jupyter-to-deepnote.ts
  • packages/convert/src/marimo-to-deepnote.ts
  • packages/convert/src/roundtrip.test.ts
  • packages/reactivity/src/ast-analyzer.test.ts
💤 Files with no reviewable changes (1)
  • packages/blocks/src/blocks.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Place test files next to source files with .test.ts or .test.tsx extension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Use const for immutable values
Avoid any types - use proper type definitions
Follow Biome's rules (configured in biome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards

Files:

  • packages/convert/src/roundtrip.test.ts
  • packages/convert/src/jupyter-to-deepnote.test.ts
  • packages/convert/src/jupyter-to-deepnote.ts
  • packages/blocks/src/blocks/input-blocks.test.ts
  • packages/reactivity/src/ast-analyzer.test.ts
  • packages/blocks/src/blocks/data-frame.test.ts
  • packages/convert/src/deepnote-to-jupyter.ts
  • packages/convert/src/deepnote-to-percent.test.ts
  • packages/blocks/src/deserialize-file/deserialize-deepnote-file.test.ts
  • packages/blocks/src/blocks/code-blocks.ts
  • packages/blocks/src/blocks/big-number-blocks.ts
  • packages/convert/src/marimo-to-deepnote.ts
  • packages/blocks/src/blocks/input-blocks.ts
  • packages/blocks/src/blocks/button-blocks.ts
  • packages/blocks/src/blocks/image-blocks.ts
  • packages/blocks/src/blocks/data-frame.ts
  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
  • packages/blocks/src/blocks/visualization-blocks.ts
  • packages/blocks/src/python-code.test.ts
  • packages/blocks/src/blocks/sql-blocks.ts
  • packages/blocks/src/markdown.test.ts
  • packages/blocks/src/blocks/text-blocks.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.{ts,tsx}: Use Vitest as the testing framework
Follow existing test patterns in the codebase (see packages/blocks/src/blocks/*.test.ts)
Test edge cases, error handling, and special characters

Files:

  • packages/convert/src/roundtrip.test.ts
  • packages/convert/src/jupyter-to-deepnote.test.ts
  • packages/blocks/src/blocks/input-blocks.test.ts
  • packages/reactivity/src/ast-analyzer.test.ts
  • packages/blocks/src/blocks/data-frame.test.ts
  • packages/convert/src/deepnote-to-percent.test.ts
  • packages/blocks/src/deserialize-file/deserialize-deepnote-file.test.ts
  • packages/blocks/src/python-code.test.ts
  • packages/blocks/src/markdown.test.ts
packages/blocks/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

For functions that generate code, test the exact output format

Files:

  • packages/blocks/src/blocks/input-blocks.test.ts
  • packages/blocks/src/blocks/data-frame.test.ts
  • packages/blocks/src/deserialize-file/deserialize-deepnote-file.test.ts
  • packages/blocks/src/python-code.test.ts
  • packages/blocks/src/markdown.test.ts
packages/blocks/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

packages/blocks/src/**/*.{ts,tsx}: Use escapePythonString() for safely embedding strings in Python code in the blocks package
Use ts-dedent for clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks

Files:

  • packages/blocks/src/blocks/input-blocks.test.ts
  • packages/blocks/src/blocks/data-frame.test.ts
  • packages/blocks/src/deserialize-file/deserialize-deepnote-file.test.ts
  • packages/blocks/src/blocks/code-blocks.ts
  • packages/blocks/src/blocks/big-number-blocks.ts
  • packages/blocks/src/blocks/input-blocks.ts
  • packages/blocks/src/blocks/button-blocks.ts
  • packages/blocks/src/blocks/image-blocks.ts
  • packages/blocks/src/blocks/data-frame.ts
  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
  • packages/blocks/src/blocks/visualization-blocks.ts
  • packages/blocks/src/python-code.test.ts
  • packages/blocks/src/blocks/sql-blocks.ts
  • packages/blocks/src/markdown.test.ts
  • packages/blocks/src/blocks/text-blocks.ts
🧬 Code graph analysis (7)
packages/convert/src/jupyter-to-deepnote.ts (2)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
  • DeepnoteBlock (325-325)
packages/blocks/src/index.ts (1)
  • DeepnoteBlock (3-3)
packages/reactivity/src/ast-analyzer.test.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
  • DeepnoteBlock (325-325)
packages/blocks/src/blocks/data-frame.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (2)
  • CodeBlock (341-341)
  • SqlBlock (342-342)
packages/blocks/src/blocks/visualization-blocks.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
  • VisualizationBlock (344-344)
packages/blocks/src/blocks/sql-blocks.ts (2)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
  • SqlBlock (342-342)
packages/blocks/src/blocks/python-utils.ts (1)
  • sanitizePythonVariableName (9-27)
packages/blocks/src/markdown.test.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
  • ImageBlock (332-332)
packages/blocks/src/blocks/text-blocks.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (7)
  • TextCellPBlock (337-337)
  • TextCellH1Block (334-334)
  • TextCellH2Block (335-335)
  • TextCellH3Block (336-336)
  • TextCellBulletBlock (338-338)
  • TextCellTodoBlock (339-339)
  • TextCellCalloutBlock (340-340)
🔇 Additional comments (43)
packages/reactivity/src/ast-analyzer.test.ts (1)

15-15: Correct use of double assertion for invalid test data.

The unknown intermediate cast is necessary because DeepnoteBlock is now a discriminated union that excludes type: 'unsupported'. This pattern properly bypasses the type system to test runtime filtering behavior.

packages/convert/src/deepnote-to-jupyter.ts (1)

147-148: Guard these accesses conditionally.

Once the type assertion is replaced with a proper type guard (see comment on lines 131-137), wrap these field accesses in conditional logic to maintain type safety.

Also applies to: 162-162, 164-164

packages/convert/src/marimo-to-deepnote.ts (1)

404-404: Type narrowing improves safety.

Explicit union type prevents invalid block types at compile time.

packages/convert/src/roundtrip.test.ts (1)

440-447: Type narrowing correctly guards code-specific fields.

The type check ensures executionStartedAt and executionFinishedAt are only accessed on code blocks, aligning with the discriminated union schema.

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

4-13: Import consolidation aligns with centralized schema.

Type definitions correctly imported from the shared schema, maintaining clear separation between types and implementations.

packages/blocks/src/deserialize-file/deserialize-deepnote-file.test.ts (1)

174-177: Type guard correctly limits execution field access to code blocks.

The conditional check ensures type safety when accessing fields specific to code blocks in the discriminated union.

packages/convert/src/deepnote-to-percent.test.ts (1)

246-246: The block type 'text-cell-p' is properly defined in the schema as part of a structured family of text cell types (paragraph, headings, bullets, todos, callouts). The change from the generic 'text' type to granular types is valid.

packages/blocks/src/blocks/data-frame.ts (2)

3-3: LGTM! Import consolidation aligns with centralized schema.

The import from the shared schema is clean and follows the PR's refactoring pattern.


7-7: Good defensive programming with optional chaining.

The change from block.metadata.deepnote_table_state to block.metadata?.deepnote_table_state ?? {} safely handles potentially undefined metadata, which is important given the schema consolidation.

packages/blocks/src/blocks/data-frame.test.ts (1)

4-4: LGTM! Import path updated to use shared schema.

The import consolidation is correct and all tests remain unchanged, ensuring no regression.

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

4-19: LGTM! Import consolidation aligns with shared schema pattern.

The consolidated imports from deepnote-file-schema are clean and consistent with the PR's refactoring objectives.


93-93: Field is required in schema but unused in code generation.

deepnote_big_number_format is defined as a required field (z.string()) in the schema, so the test data correctly includes it. However, this field is never referenced in createPythonCodeForBigNumberBlock() or executeBigNumber(). Either implement the field's functionality or mark it as .optional() in the schema if it's not yet needed.

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

1-1: LGTM! Import from shared schema.

The consolidated import is consistent with the PR's centralization pattern.


25-27: Good use of optional chaining with safe defaults.

The optional chaining with fallback to empty strings (?? '') safely handles potentially undefined metadata while providing appropriate defaults for HTML attributes.


32-34: Well-implemented type guard.

The isImageBlock type guard correctly narrows the type from DeepnoteBlock to ImageBlock by checking the type property.

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

12-12: LGTM! Import updated to shared schema.

The import consolidation is correct and consistent with the PR's refactoring pattern.


19-19: Good use of const assertions for type literals.

The as const assertions improve type precision by treating 'markdown' as a literal type rather than string.

Also applies to: 34-34

packages/convert/src/jupyter-to-deepnote.test.ts (7)

165-165: LGTM!

Switched from .toBeUndefined() to 'outputs' in markdownBlock check—correctly tests absence rather than undefined value.


171-174: LGTM!

Type guard ensures executionCount and outputs are only accessed on code blocks. Consistent with discriminated union pattern.


180-182: LGTM!

Same defensive pattern applied consistently.


232-234: LGTM!

Guards executionCount access appropriately.


409-417: LGTM!

Properly guards code-specific outputs property.


449-449: LGTM!

Consistent with line 165 pattern.


1330-1333: LGTM!

Final occurrence correctly guarded.

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

1-1: LGTM!

Import from shared schema and optional chaining on metadata access are correct.

Also applies to: 14-14

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

3-3: LGTM!

Clean refactor to shared schema imports.

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

1-1: LGTM!

Import from shared schema and consistent optional chaining on metadata access.

Also applies to: 6-8

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

3-3: LGTM!

Import updated to use centralized schema.


8-18: LGTM!

Optional chaining and nullish coalescing correctly handle potentially undefined metadata/content fields per the updated schema.


50-52: LGTM!

Type guard correctly narrows DeepnoteBlock to SqlBlock.

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

1-22: LGTM!

Clean import consolidation and backwards-compatible type aliases.


94-129: LGTM!

Local content variable with nullish coalescing correctly handles optional content across all branches.


131-164: LGTM!

Same resilient pattern applied consistently.


166-172: LGTM!

Separator block handling is straightforward.

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

3-14: LGTM!

All input block types imported from centralized schema.


65-175: LGTM!

Direct metadata access is correct—input block schemas define metadata as required (non-optional).


177-221: LGTM!

Type guards correctly narrow to specific input block types.

packages/blocks/src/deserialize-file/deepnote-file-schema.ts (5)

7-49: LGTM!

Base metadata schemas with .passthrough() allow schema evolution while preserving known fields.


84-117: LGTM!

Factory helpers reduce boilerplate effectively.


295-323: LGTM!

Discriminated union on type enables proper type narrowing.


331-375: LGTM!

Clean type exports with union types for related block groups.


230-244: bigNumberBlockSchema metadata is not optional, unlike all other block schemas.

Every other block schema (code, SQL, visualization, button, markdown, image, separator) marks metadata .optional(), but bigNumberBlockSchema doesn't. This is inconsistent. Confirm if this deviation is intentional or an oversight.

examples/2_blocks.deepnote (1)

95-95: All concerns verified and code is correct.

  • Field properly defined in schema as required string (line 265 of deepnote-file-schema.ts)
  • Empty string is correct choice: represents "no variable selected" vs deepnote_variable_default_value: null which means "no default set"
  • Schema uses .passthrough() but strictly requires this field (intentional breaking change per PR's "more strict block schema" goal)
  • Example file properly updated

sortingKey: sortingKey ?? createSortingKey(index),
type: blockType,
}
} as DeepnoteBlock

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.

note to self - we must factor out this typecast here

@saltenasl

Copy link
Copy Markdown
Contributor Author

@coderabbitai - please check the schema changes in packages/blocks/src/deserialize-file/deepnote-file-schema.ts and outline all breaking changes.

@coderabbitai

coderabbitai Bot commented Jan 7, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the schema file to analyze breaking changes
cat packages/blocks/src/deserialize-file/deepnote-file-schema.ts

Length of output: 17284


@saltenasl: Here are all breaking changes in the schema:

1. Block Type Removal & Fragmentation

  • 'text' type removed – replaced with specific types: 'text-cell-h1', 'text-cell-h2', 'text-cell-h3', 'text-cell-p', 'text-cell-bullet', 'text-cell-todo', 'text-cell-callout'
  • Existing blocks with type: 'text' will fail validation

2. Discriminated Union Enforcement

  • Schema changed from flexible structure to strict discriminated union on type field
  • Each block must match exactly one specific schema
  • Unknown block types will be rejected
  • Cannot have fields from multiple block types mixed

3. Required Metadata Fields

Several blocks now require metadata fields:

  • BigNumberBlock: requires deepnote_big_number_title, deepnote_big_number_value, deepnote_big_number_format
  • All input blocks: require deepnote_variable_name in metadata
  • InputSelectBlock: requires deepnote_variable_options, deepnote_variable_custom_options, deepnote_variable_selected_variable, deepnote_variable_select_type
  • InputSliderBlock: requires deepnote_slider_min_value, deepnote_slider_max_value, deepnote_slider_step
  • NotebookFunctionBlock: requires function_notebook_id (nullable)

4. Stricter Field Validations

contentHash regex:

contentHash: z.string().regex(/^(md5|sha256):[a-f0-9]+$/i)
  • Must match md5:... or sha256:... format

Datetime strings:

  • executionStartedAt, executionFinishedAt, execution.startedAt, execution.finishedAt must be valid ISO datetime strings

Enum constraints:

  • deepnote_img_width: only 'actual' | '50%' | '75%' | '100%'
  • deepnote_button_color_scheme: only 'blue' | 'red' | 'neutral' | 'green' | 'yellow'
  • deepnote_return_variable_type: only 'dataframe' | 'query_preview'
  • Many others now strictly validated

5. Content Field Constraints

These blocks now require empty content:

  • image: content: z.literal('').optional()
  • separator: content: z.literal('').optional()
  • button: content: z.literal('').optional()
  • visualization: content: z.literal('').optional()
  • notebook-function: content: z.literal('').optional()

Non-empty content will fail validation for these types.

6. Execution Fields Scope

Execution-related fields are now only valid on executable blocks:

  • executionCount, executionStartedAt, executionFinishedAt, outputs
  • Non-executable blocks (markdown, image, separator, text-cell-*) cannot have these fields in the discriminated union structure

7. Type Safety Impact

  • DeepnoteBlock type is now a discriminated union
  • Type narrowing required to access block-specific fields
  • Generic code accessing fields across block types may need type guards

Migration Path

Files using the old schema will need:

  1. Update 'text' → appropriate 'text-cell-*' type
  2. Add required metadata fields
  3. Ensure contentHash matches regex pattern
  4. Convert timestamps to ISO datetime strings
  5. Remove execution fields from non-executable blocks
  6. Clear content for blocks requiring empty content
  7. Validate all enum values against new constraints

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/blocks/src/blocks/text-blocks.ts (1)

85-85: Redundant .toLowerCase() with strict schema.

The discriminated union guarantees block.type is an exact string literal; case normalization is unnecessary.

♻️ Simplify
-  return textBlockTypes.includes(block.type.toLowerCase())
+  return textBlockTypes.includes(block.type)
🤖 Fix all issues with AI agents
In @packages/convert/src/utils.ts:
- Around line 78-83: The function sortKeysAlphabetically uses an unsound cast by
creating a plain object and asserting it as T; constrain the generic to be
indexable or return a safer type: change the signature to either <T extends
Record<string, unknown>>(obj: T): T and build the result as const sorted:
Partial<T> = {} then assign keys and return sorted as T, or change the return
type to Partial<T> (or Record<string, unknown>) to avoid asserting a freshly
constructed object as an arbitrary T; update references to
sortKeysAlphabetically accordingly.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f9563be and efb7528.

📒 Files selected for processing (5)
  • packages/blocks/src/blocks/text-blocks.ts
  • packages/blocks/src/markdown.test.ts
  • packages/convert/src/jupyter-to-deepnote.ts
  • packages/convert/src/utils.test.ts
  • packages/convert/src/utils.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Place test files next to source files with .test.ts or .test.tsx extension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Use const for immutable values
Avoid any types - use proper type definitions
Follow Biome's rules (configured in biome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards

Files:

  • packages/convert/src/jupyter-to-deepnote.ts
  • packages/convert/src/utils.test.ts
  • packages/convert/src/utils.ts
  • packages/blocks/src/markdown.test.ts
  • packages/blocks/src/blocks/text-blocks.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.{ts,tsx}: Use Vitest as the testing framework
Follow existing test patterns in the codebase (see packages/blocks/src/blocks/*.test.ts)
Test edge cases, error handling, and special characters

Files:

  • packages/convert/src/utils.test.ts
  • packages/blocks/src/markdown.test.ts
packages/blocks/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

For functions that generate code, test the exact output format

Files:

  • packages/blocks/src/markdown.test.ts
packages/blocks/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

packages/blocks/src/**/*.{ts,tsx}: Use escapePythonString() for safely embedding strings in Python code in the blocks package
Use ts-dedent for clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks

Files:

  • packages/blocks/src/markdown.test.ts
  • packages/blocks/src/blocks/text-blocks.ts
🧬 Code graph analysis (4)
packages/convert/src/jupyter-to-deepnote.ts (3)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (2)
  • DeepnoteBlock (325-325)
  • deepnoteBlockSchema (295-323)
packages/blocks/src/index.ts (2)
  • DeepnoteBlock (3-3)
  • deepnoteBlockSchema (11-11)
packages/convert/src/utils.ts (1)
  • sortKeysAlphabetically (78-84)
packages/convert/src/utils.test.ts (1)
packages/convert/src/utils.ts (3)
  • sortKeysAlphabetically (78-84)
  • createSortingKey (8-33)
  • isMarkdownBlockType (58-69)
packages/blocks/src/markdown.test.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (8)
  • TextCellH1Block (334-334)
  • TextCellH2Block (335-335)
  • TextCellH3Block (336-336)
  • TextCellBulletBlock (338-338)
  • TextCellTodoBlock (339-339)
  • TextCellCalloutBlock (340-340)
  • TextCellPBlock (337-337)
  • ImageBlock (332-332)
packages/blocks/src/blocks/text-blocks.ts (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (7)
  • TextCellPBlock (337-337)
  • TextCellH1Block (334-334)
  • TextCellH2Block (335-335)
  • TextCellH3Block (336-336)
  • TextCellBulletBlock (338-338)
  • TextCellTodoBlock (339-339)
  • TextCellCalloutBlock (340-340)
🔇 Additional comments (7)
packages/convert/src/utils.test.ts (1)

1-116: LGTM!

Comprehensive test coverage with good edge-case handling. The numeric key ordering caveat (lines 61-69) is well-documented.

packages/convert/src/jupyter-to-deepnote.ts (2)

231-246: Verify fail-fast error handling is intentional.

deepnoteBlockSchema.parse() throws on validation failure. If convertCellToBlock is called with malformed Jupyter cells (e.g., invalid metadata, wrong types), conversion will crash without graceful degradation.

Is this the intended behavior? If so, consider documenting it. If not, use .safeParse() and handle errors.

Alternative: graceful fallback
const parseResult = deepnoteBlockSchema.safeParse({
  blockGroup,
  content: source,
  // ... rest of fields
})

if (!parseResult.success) {
  // Log warning and fall back to basic block structure
  console.warn(`Invalid block at index ${index}:`, parseResult.error)
  return createFallbackBlock(cell, index, idGenerator)
}

return sortKeysAlphabetically(parseResult.data)

210-210: Type assertion acknowledged in past review.

The developer confirmed this is safe for roundtrip conversion and noted the need to factor out the typecast. Since it's tracked and understood, skipping further comment.

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

3-14: Imports correctly updated to centralized schema.

The migration from local type definitions to the shared deepnote-file-schema module aligns with the discriminated union approach.


19-170: Test blocks correctly migrated to new schema.

All test blocks updated with proper discriminated types (as const for literals, specific TextCell* variants) and include the new sortingKey field.


209-346: stripMarkdown tests correctly updated.

All test blocks migrated to new discriminated types. Error handling tests properly validate unsupported block type behavior, and the CodeBlock test correctly includes executionCount as an executable block field.


187-205: Type cast is intentional and correctly tests sanitization logic.

The test uses as unknown as ImageBlock to test how sanitizeWidth() handles arbitrary numeric values outside the enum schema. This is valid: schema validation occurs during deserialization, not unit test execution. The function is designed to extract digits from any string input—the type cast is documented and appropriate for testing edge cases.

No changes needed.

Comment thread packages/convert/src/utils.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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/convert/src/deepnote-to-jupyter.ts (1)

131-161: Use type guard based on discriminant instead of in checks.

The in operator checks are safer than type assertions but don't leverage the discriminated union. For discriminated unions, check the discriminant (block.type) and let TypeScript narrow the type:

function isExecutableBlock(block: DeepnoteBlock): block is Extract<DeepnoteBlock, { executionCount?: number }> {
  return block.type === 'code' || block.type === 'sql' // add other executable types
}

const execFields = isExecutableBlock(block) 
  ? { 
      executionStartedAt: block.executionStartedAt,
      executionFinishedAt: block.executionFinishedAt,
      executionCount: block.executionCount ?? null,
      outputs: block.outputs
    }
  : { 
      executionStartedAt: undefined,
      executionFinishedAt: undefined,
      executionCount: null,
      outputs: undefined
    }

Then use execFields.* in metadata and cell construction.

As per coding guidelines, prefer type safety over convenience.

📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between efb7528 and 2ab612d.

📒 Files selected for processing (1)
  • packages/convert/src/deepnote-to-jupyter.ts
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Place test files next to source files with .test.ts or .test.tsx extension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Use const for immutable values
Avoid any types - use proper type definitions
Follow Biome's rules (configured in biome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards

Files:

  • packages/convert/src/deepnote-to-jupyter.ts

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jan 7, 2026
@saltenasl
saltenasl marked this pull request as ready for review January 7, 2026 14:10
@saltenasl
saltenasl requested a review from a team as a code owner January 7, 2026 14:10

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)

430-435: Inconsistent timestamp validation in metadata.

createdAt, exportedAt, and modifiedAt use z.string() without .datetime() validation, but execution timestamps (lines 70-71, 417, 419) require ISO datetime strings. Consider applying .datetime() here too for consistency.

🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Line 9: The schema entry cell_id uses z.unknown().optional(), which gives no
type safety; update it to a more specific union of expected types (e.g., replace
with z.union([z.string(), z.number()]).optional() or
z.string().nullable().optional() depending on actual shapes) or, if truly
variable, add a comment explaining the allowed shapes and replace z.unknown()
with a documented union like z.union([z.string(), z.number(),
z.object({...})]).optional() so consumers get proper typing from the cell_id
schema.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 2ab612d and 7d7b1ef.

📒 Files selected for processing (1)
  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Place test files next to source files with .test.ts or .test.tsx extension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Use const for immutable values
Avoid any types - use proper type definitions
Follow Biome's rules (configured in biome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards

Files:

  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
packages/blocks/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

packages/blocks/src/**/*.{ts,tsx}: Use escapePythonString() for safely embedding strings in Python code in the blocks package
Use ts-dedent for clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks

Files:

  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🔇 Additional comments (6)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (6)

79-112: Factory helpers correctly compose block schemas.

Both createTextCellBlockSchema and createInputBlockSchema properly spread base fields and extend metadata schemas. The conditional noDefaultValue handling is clean.


118-155: Non-executable block schemas correctly structured.

Empty content constraints for image/separator blocks align with PR objectives. Text cell variants properly use factory helper. Enum values for image width and callout colors are well-defined.


161-239: Executable block schemas correctly enforce constraints.

Empty content requirements (notebook-function, visualization, button) and required metadata fields (big-number title/value/format, notebook-function function_notebook_id) align with PR breaking changes. Execution fields properly scoped to executable variants.


245-284: Input block schemas properly require metadata per PR objectives.

All input blocks inherit required deepnote_variable_name. Input-select correctly requires four metadata fields (options, custom_options, selected_variable, select_type). Input-slider requires min/max/step. File input appropriately omits default value.


290-318: Discriminated union correctly composed.

All 24 block schemas included with unique type literals. Generic text type properly removed in favor of explicit text-cell variants as per PR objectives. Union enables type narrowing in consumer code.


320-370: Type exports comprehensive and well-organized.

Individual block types, InputBlock, and TextCellBlock union types provide convenient type access for consumers. Exporting granular types alongside the discriminated union supports flexible type narrowing.

Artmann
Artmann previously approved these changes Jan 7, 2026
@saltenasl
saltenasl marked this pull request as draft January 8, 2026 08:31

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/convert/src/deepnote-to-percent.test.ts (1)

1-465: Consider adding validation failure tests.

Migration to text-cell-* types is complete across all test files. Optionally, add test cases that verify the old text type blocks fail validation under the new discriminated union schema.

🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Around line 237-247: bigNumberBlockSchema's metadata is currently required
because the metadata object is not given a default; update the metadata schema
in bigNumberBlockSchema to use .default({}) so metadata is optional by default
(or alternatively make the individual fields optional if required metadata was
unintended) — locate the metadata object inside bigNumberBlockSchema (the
metadata: executableCellMetadataSchema.extend({...}) block containing
deepnote_big_number_title, deepnote_big_number_value, etc.) and apply
.default({}) to that extended schema to prevent metadata being required when
absent.

In @packages/convert/src/deepnote-to-marimo.test.ts:
- Line 292: The test object sets metadata: {} explicitly even though the schema
already uses .default({}); remove the explicit metadata property from the test
fixture in deepnote-to-marimo.test.ts (the object literal containing "metadata:
{}") so the code relies on the schema default instead, and run tests to confirm
no behavior change.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7d7b1ef and f4a30b1.

📒 Files selected for processing (10)
  • packages/blocks/src/blocks/input-blocks.test.ts
  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
  • packages/blocks/src/python-code.test.ts
  • packages/convert/src/deepnote-to-jupyter.test.ts
  • packages/convert/src/deepnote-to-jupyter.ts
  • packages/convert/src/deepnote-to-marimo.test.ts
  • packages/convert/src/deepnote-to-percent.test.ts
  • packages/convert/src/deepnote-to-quarto.test.ts
  • packages/convert/src/roundtrip-all-formats.test.ts
  • packages/convert/src/roundtrip.test.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Place test files next to source files with .test.ts or .test.tsx extension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Use const for immutable values
Avoid any types - use proper type definitions
Follow Biome's rules (configured in biome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards

Files:

  • packages/convert/src/deepnote-to-jupyter.test.ts
  • packages/convert/src/deepnote-to-marimo.test.ts
  • packages/convert/src/deepnote-to-quarto.test.ts
  • packages/convert/src/roundtrip.test.ts
  • packages/convert/src/deepnote-to-jupyter.ts
  • packages/convert/src/deepnote-to-percent.test.ts
  • packages/blocks/src/blocks/input-blocks.test.ts
  • packages/blocks/src/python-code.test.ts
  • packages/convert/src/roundtrip-all-formats.test.ts
  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.test.{ts,tsx}: Use Vitest as the testing framework
Follow existing test patterns in the codebase (see packages/blocks/src/blocks/*.test.ts)
Test edge cases, error handling, and special characters

Files:

  • packages/convert/src/deepnote-to-jupyter.test.ts
  • packages/convert/src/deepnote-to-marimo.test.ts
  • packages/convert/src/deepnote-to-quarto.test.ts
  • packages/convert/src/roundtrip.test.ts
  • packages/convert/src/deepnote-to-percent.test.ts
  • packages/blocks/src/blocks/input-blocks.test.ts
  • packages/blocks/src/python-code.test.ts
  • packages/convert/src/roundtrip-all-formats.test.ts
packages/blocks/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

For functions that generate code, test the exact output format

Files:

  • packages/blocks/src/blocks/input-blocks.test.ts
  • packages/blocks/src/python-code.test.ts
packages/blocks/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

packages/blocks/src/**/*.{ts,tsx}: Use escapePythonString() for safely embedding strings in Python code in the blocks package
Use ts-dedent for clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks

Files:

  • packages/blocks/src/blocks/input-blocks.test.ts
  • packages/blocks/src/python-code.test.ts
  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧬 Code graph analysis (1)
packages/convert/src/deepnote-to-jupyter.ts (2)
packages/convert/src/index.ts (1)
  • JupyterCell (84-84)
packages/convert/src/types/jupyter.ts (1)
  • JupyterCell (6-16)
🔇 Additional comments (23)
packages/convert/src/deepnote-to-percent.test.ts (4)

146-146: Schema alignment: metadata addition.

Correct addition for stricter schema validation.


186-186: Schema alignment: metadata addition.

Correct addition for stricter schema validation.


248-248: Required migration: 'text' → 'text-cell-p'.

Correctly migrates to discriminated union schema. The test properly validates that text-cell-p blocks convert to markdown cells in percent format.

Also applies to: 252-252


432-432: Schema alignment: metadata addition.

Correct addition for stricter schema validation.

packages/convert/src/roundtrip.test.ts (1)

443-449: Type narrowing correctly handles discriminated union.

The conditional check ensures execution timing fields are only accessed on code blocks, properly reflecting the new discriminated union schema where these fields exist only on executable variants.

packages/convert/src/deepnote-to-jupyter.ts (2)

131-134: Defensive extraction handles discriminated union correctly.

Using the in operator to guard execution field access is appropriate for the new schema where these fields exist only on executable block types.


137-150: Metadata merge order is correct.

Spreading block.metadata first, then applying explicit fields ensures proper precedence. Extracted execution variables are safely applied to metadata.

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

381-385: New required metadata fields added correctly.

The added fields (deepnote_variable_options, deepnote_variable_custom_options, deepnote_variable_selected_variable, deepnote_variable_select_type) align with the PR's breaking change #3, which makes these fields required on InputSelectBlock.


93-93: No action needed. The field deepnote_big_number_format is defined as z.string() with no constraints, so empty strings are valid values.

packages/convert/src/roundtrip-all-formats.test.ts (1)

475-500: Empty metadata objects align with schema requirements.

Adding metadata: {} to test blocks ensures fixtures match the new schema structure.

packages/convert/src/deepnote-to-quarto.test.ts (1)

121-121: Test fixture updated for schema consistency.

Adding metadata: {} ensures the test block matches the new schema structure.

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

4-13: LGTM: Type centralization.

Importing from shared schema aligns with PR goals and improves maintainability.


132-136: New required metadata fields added.

Test data correctly includes deepnote_variable_options, deepnote_variable_custom_options, deepnote_variable_selected_variable, and deepnote_variable_select_type as required by the updated schema.

Also applies to: 154-158, 177-181


202-204: LGTM: Required slider metadata.

Correctly adds required slider bounds and step fields per updated schema.

packages/convert/src/deepnote-to-jupyter.test.ts (1)

467-470: LGTM: Consistent with schema.

Input-select metadata correctly updated with required fields.

packages/blocks/src/deserialize-file/deepnote-file-schema.ts (8)

7-48: LGTM: Flexible metadata schemas.

Using .passthrough() allows additional fields while validating known ones. All fields appropriately optional.


51-54: Required field for input blocks.

deepnote_variable_name is now required for all input blocks. This breaking change aligns with PR objectives.


60-77: LGTM: Base field definitions.

ContentHash regex and datetime validations match PR requirements. ExecutionCount correctly nullable.


87-163: LGTM: Non-executable blocks.

Correctly enforces empty content for image/separator blocks and uses appropriate enum constraints.


169-231: LGTM: Executable blocks.

Empty content correctly enforced for notebook-function, visualization, and button. Enum constraints and defaults properly applied.


253-349: LGTM: Input block schemas.

Required metadata fields for select and slider blocks align with test changes. The z.preprocess pattern for null handling in deepnote_variable_default_value prevents breaking changes as noted in commit messages.


355-383: LGTM: Discriminated union structure.

All 23 block variants properly included. Union enforces strict type checking per PR objectives.


385-543: LGTM: Type exports and file schema.

Comprehensive type exports and helper unions. File schema correctly uses datetime validation for execution timestamps per PR objectives.

@saltenasl

Copy link
Copy Markdown
Contributor Author

@coderabbitai please map all the fields that have breaking changes in the schemas i added. I will want to pre-process those fields so they will still have breaking changes in TS types, however, the old files should be handled gracefully when parsing. I need a list of all fields and i will then decide from there how to handle each.

@coderabbitai

coderabbitai Bot commented Jan 8, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the schema file to analyze all field-level breaking changes
cat packages/blocks/src/deserialize-file/deepnote-file-schema.ts

Length of output: 18868


@saltenasl: Here's a complete field-by-field mapping of all breaking changes:

1. Block Type Discrimination (Core Breaking Change)

Field Old New Impact
type 'text' allowed Must be one of: 'text-cell-h1', 'text-cell-h2', 'text-cell-h3', 'text-cell-p', 'text-cell-bullet', 'text-cell-todo', 'text-cell-callout' All existing 'text' blocks will fail

2. Required Metadata Fields (Previously Optional/Missing)

BigNumberBlock

  • metadata.deepnote_big_number_title → now z.string() (required)
  • metadata.deepnote_big_number_value → now z.string() (required)
  • metadata.deepnote_big_number_format → now z.string() (required)

All Input Blocks (base requirement)

  • metadata.deepnote_variable_name → now z.string() (required)

InputTextBlock & InputTextareaBlock

  • metadata.deepnote_variable_value → now z.string() (required)

InputCheckboxBlock

  • metadata.deepnote_variable_value → now z.boolean() (required)

InputSelectBlock

  • metadata.deepnote_variable_value → now z.union([z.string(), z.array(z.string())]) (required)
  • metadata.deepnote_variable_options → now z.array(z.string()) (required)
  • metadata.deepnote_variable_custom_options → now z.array(z.string()) (required)
  • metadata.deepnote_variable_selected_variable → now z.string() (required)
  • metadata.deepnote_variable_select_type → now z.enum(['from-options', 'from-variable']) (required)

InputSliderBlock

  • metadata.deepnote_variable_value → now z.string() (required)
  • metadata.deepnote_slider_min_value → now z.number() (required)
  • metadata.deepnote_slider_max_value → now z.number() (required)
  • metadata.deepnote_slider_step → now z.number() (required)

InputDateBlock

  • metadata.deepnote_variable_value → now z.string() (required)

InputDateRangeBlock

  • metadata.deepnote_variable_value → now z.union([z.tuple([z.string(), z.string()]), z.string()]) (required)

InputFileBlock

  • metadata.deepnote_variable_value → now z.string() (required)

NotebookFunctionBlock

  • metadata.function_notebook_id → now z.string().nullable() (required, but can be null)

3. Stricter Validation Patterns

contentHash (ALL block types)

  • Old: z.string().optional() (any string)
  • New: z.string().regex(/^(md5|sha256):[a-f0-9]+$/i).optional()
  • Impact: Must match md5:abc123 or sha256:def456 format

Execution Timestamps (all executable blocks)

  • executionStartedAt → now z.string().datetime() (must be ISO datetime)
  • executionFinishedAt → now z.string().datetime() (must be ISO datetime)

File-level Execution Timestamps

  • execution.startedAt → now z.string().datetime()
  • execution.finishedAt → now z.string().datetime()

Enum Constraints

ImageBlock metadata

  • deepnote_img_width → now z.enum(['actual', '50%', '75%', '100%'])
  • deepnote_img_alignment → now z.enum(['left', 'center', 'right'])

TextCellCalloutBlock metadata

  • color → now z.enum(['blue', 'green', 'yellow', 'red', 'purple'])

SqlBlock metadata

  • deepnote_return_variable_type → now z.enum(['dataframe', 'query_preview'])

ButtonBlock metadata

  • deepnote_button_color_scheme → now z.enum(['blue', 'red', 'neutral', 'green', 'yellow'])
  • deepnote_button_behavior → now z.enum(['run', 'set_variable'])

InputSelectBlock metadata

  • deepnote_variable_select_type → now z.enum(['from-options', 'from-variable'])

File-level execution

  • execution.triggeredBy → now z.enum(['user', 'schedule', 'api', 'ci'])

File-level environment

  • environment.python.environment → now z.enum(['uv', 'conda', 'venv', 'poetry', 'system'])

4. Content Field Constraints (Must Be Empty)

These blocks require content: z.literal('').optional():

  • ImageBlock.content
  • SeparatorBlock.content
  • ButtonBlock.content
  • VisualizationBlock.content
  • NotebookFunctionBlock.content

Impact: Non-empty content will fail validation

5. Execution Fields Scope (Field Presence)

These fields now ONLY exist on executable blocks:

  • executionCount
  • executionStartedAt
  • executionFinishedAt
  • outputs

Cannot be present on:

  • markdown
  • image
  • separator
  • All text-cell-* variants

Impact: Non-executable blocks with these fields will fail discriminated union validation

6. Special Preprocessing Note

Already handled gracefully in schema:

  • deepnote_variable_default_value uses z.preprocess(val => (val === null ? undefined : val), ...) to convert null to undefined

Summary by Preprocessing Strategy Needed:

  1. Type mapping (1 field): type: 'text' → infer correct text-cell-* variant
  2. Provide defaults (26 fields): All required metadata fields above
  3. Pattern validation (1 field): contentHash format
  4. Datetime conversion (4 fields): All timestamp fields
  5. Enum validation (11 fields): All enum-constrained fields
  6. Content clearing (5 fields): Empty content requirement
  7. Field removal (4 fields): Remove execution fields from non-executable blocks

@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

🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Around line 240-254: bigNumberBlockSchema currently requires the metadata
object while all other block schemas use metadata.default({}); update
bigNumberBlockSchema's metadata definition to add .default({}) on the
executableCellMetadataSchema.extend(...) so metadata becomes optional like other
blocks and parsing won't fail when metadata is omitted; locate the metadata
property in bigNumberBlockSchema and append .default({}) to that schema
definition.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f4a30b1 and f15eb52.

📒 Files selected for processing (1)
  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Place test files next to source files with .test.ts or .test.tsx extension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Use const for immutable values
Avoid any types - use proper type definitions
Follow Biome's rules (configured in biome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards

Files:

  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
packages/blocks/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

packages/blocks/src/**/*.{ts,tsx}: Use escapePythonString() for safely embedding strings in Python code in the blocks package
Use ts-dedent for clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks

Files:

  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧬 Code graph analysis (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
packages/blocks/src/index.ts (2)
  • deepnoteBlockSchema (11-11)
  • DeepnoteBlock (3-3)
🔇 Additional comments (8)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (8)

14-61: Well-structured base schemas with good backward compatibility.

The layered approach (base → executable → specialized) and use of .passthrough() enable graceful handling of legacy and future fields.


67-84: Clean field separation for discriminated union.

Base and executable field sets are well-designed. Regex and datetime validations are appropriate.


94-170: Consistent non-executable block schemas.

All schemas follow the same pattern: base fields, type literal, optional content (or empty for image/separator), and defaulted metadata. Enum constraints tighten validation as intended.


176-239: Consistent executable block schemas.

Code, SQL, notebook-function, visualization, and button schemas follow consistent patterns with appropriate use of emptyContent() and defaulted metadata.


260-356: Well-designed input block schemas with strong defaults.

The null-to-undefined preprocessing pattern for default_value fields is elegant. Comprehensive defaults ensure backward compatibility.


362-390: Properly structured discriminated union.

All block schemas correctly included. Grouping by category aids readability.


392-442: Comprehensive type exports.

Individual types and union helpers (InputBlock, TextCellBlock) provide good ergonomics for consumers.


448-551: File-level schemas correctly integrated.

New discriminated block schema properly referenced. Enum constraints and datetime validation align with stricter validation goals.

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)

504-509: Inconsistent timestamp validation.

execution.startedAt/finishedAt use .datetime() but metadata.createdAt/exportedAt/modifiedAt are plain strings. Apply consistent validation if all should be ISO format.

♻️ If ISO format is required
   metadata: z.object({
     checksum: z.string().optional(),
-    createdAt: z.string(),
-    exportedAt: z.string().optional(),
-    modifiedAt: z.string().optional(),
+    createdAt: z.string().datetime(),
+    exportedAt: z.string().datetime().optional(),
+    modifiedAt: z.string().datetime().optional(),
   }),
🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Around line 40-46: The schema uses z.record(z.any()) for deepnote_table_state
and function_notebook_export_states which allows any value; change these to
z.record(z.unknown()) to tighten runtime validation while keeping the fields
opaque — update the definitions of deepnote_table_state and
function_notebook_export_states to use z.record(z.unknown()). Ensure any code
that reads these records handles unknown-typed values appropriately (e.g.,
validating before accessing specific properties).
- Around line 268-269: The repeated z.preprocess(val => (val === null ?
undefined : val), ...) logic should be extracted into a small helper (e.g.
nullToUndefined or preprocessNullToUndefined) and reused; add a helper function
that accepts a Zod schema and returns z.preprocess(val => val === null ?
undefined : val, schema), then replace each inline usage (including the
deepnote_variable_default_value field and the other seven occurrences) with
helper(schema) to deduplicate the logic while keeping existing schemas intact.
- Around line 198-209: The metadata property in notebookFunctionBlockSchema
currently defines function_notebook_id as z.string().nullable(), which makes the
key required even when null; change it to z.string().nullable().optional() so
the field can be omitted or null, matching the pattern used by
deepnote_app_block_group_id and ensuring partial metadata objects validate
correctly; keep the surrounding metadata schema default({ function_notebook_id:
null }) intact.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f15eb52 and 789d2a7.

📒 Files selected for processing (1)
  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Place test files next to source files with .test.ts or .test.tsx extension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Use const for immutable values
Avoid any types - use proper type definitions
Follow Biome's rules (configured in biome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards

Files:

  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
packages/blocks/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

packages/blocks/src/**/*.{ts,tsx}: Use escapePythonString() for safely embedding strings in Python code in the blocks package
Use ts-dedent for clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks

Files:

  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🔇 Additional comments (6)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (6)

7-8: Looks good.

Preprocess helper correctly coerces any content to empty string for content-less blocks.


67-84: LGTM.

Base and executable field definitions are well-structured. Regex validation for contentHash and datetime validation for timestamps are appropriate.


94-170: Clean implementation.

Non-executable block schemas follow consistent patterns. Enum constraints for image dimensions/alignment and callout colors are well-defined.


316-322: Mixed types: string value with numeric bounds.

deepnote_variable_value is string while deepnote_slider_min_value/max_value/step are number. Intentional for compatibility, or should value be numeric?


364-392: Well-structured discriminated union.

All 24 block variants correctly included. The type discriminator enables efficient validation and type narrowing.


536-550: Good deprecation documentation.

JSDoc comment clearly marks the legacy settings.environment field. Consumers can migrate to top-level environment.

@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

🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Around line 82-84: The "Schema factory helpers" comment block (the separator
and header text "Schema factory helpers") is empty and should be removed or
populated; either delete the three-line header/section (the "//
============================================================================="
separators and the "// Schema factory helpers" line) to avoid an empty section,
or implement and export the intended factory helper functions (e.g., add
properly named factory functions and their exports) in place of the header so
the section is meaningful.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 789d2a7 and 67f0d76.

📒 Files selected for processing (1)
  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Place test files next to source files with .test.ts or .test.tsx extension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Use const for immutable values
Avoid any types - use proper type definitions
Follow Biome's rules (configured in biome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards

Files:

  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
packages/blocks/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

packages/blocks/src/**/*.{ts,tsx}: Use escapePythonString() for safely embedding strings in Python code in the blocks package
Use ts-dedent for clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks

Files:

  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧬 Code graph analysis (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
packages/blocks/src/index.ts (2)
  • deepnoteBlockSchema (11-11)
  • DeepnoteBlock (3-3)
🔇 Additional comments (9)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (9)

7-8: Clean backward compatibility helper.

The emptyContent preprocessor correctly coerces any value to an empty string for blocks that don't use content. The pattern ensures old data is normalized while enforcing the constraint.


63-80: Solid field definitions.

Regex for contentHash, datetime validation for execution timestamps, and scoping of execution fields to executable blocks all align with requirements.


90-166: Non-executable blocks implemented correctly.

All variants use proper base fields, emptyContent() where required, and enum constraints match the spec. The discriminated types are well-structured.


236-252: Verify required vs. default for BigNumberBlock fields.

PR objectives state deepnote_big_number_title, deepnote_big_number_value, and deepnote_big_number_format are required. Using .default('') makes them optional (with fallback). If backward compatibility is needed, this is correct; otherwise, remove .default() and omit .optional().

Is this backward-compat intentional, or should these be truly required fields?


258-354: Input blocks well-structured.

Preprocessing null → undefined ensures backward compatibility. The new deepnote_variable_selected_variable field (line 301) and enum constraints align with requirements. Consistent patterns across all input variants.


360-388: Discriminated union correctly implemented.

Using z.discriminatedUnion('type', [...]) enables TypeScript to narrow types based on the discriminator. All 26 block variants are included.


390-441: Type exports comprehensive.

All block variants exported. The InputBlock and TextCellBlock union types provide convenient subsets for consumers.


446-549: File-level schemas complete.

Environment enum (line 454), execution datetime validation (lines 487, 489), triggeredBy enum (line 491), and the deprecated notice (lines 533-536) all align with requirements. The file structure properly references deepnoteBlockSchema for block validation.


54-57: The .default('unnamed_variable') is intentional for backward compatibility—this schema deserializes potentially legacy files that may lack the field. The app layer (per tests) always provides meaningful names when blocks are created/updated. This design is correct.

@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: 3

🤖 Fix all issues with AI agents
In @packages/blocks/src/deserialize-file/deepnote-file-schema.ts:
- Around line 290-309: inputSelectBlockSchema sets deepnote_variable_value as
z.union([z.string(), z.array(z.string())]) but uses default(''), causing a type
mismatch for multi-select scenarios; change the default to an array (e.g.,
default([])) so the default value matches the union's array option and aligns
with multi-select users (update the default for deepnote_variable_value inside
inputSelectBlockSchema).
- Around line 7-8: The helper emptyContent() currently uses z.preprocess(() =>
'', z.literal('').optional()), which is redundant because the preprocesser
always returns the empty string so the schema can never be undefined; remove the
.optional() and change the inner schema to z.literal('') (i.e., use
z.preprocess(() => '', z.literal('')) in emptyContent) so the produced type is
correctly '' instead of string | undefined while keeping the same runtime
behavior.
- Around line 62-71: The schema in baseBlockFields currently requires sortingKey
which will cause validation failures for older files missing that field; either
make sortingKey optional in baseBlockFields (add .optional()) or add a
preprocessing step before validation that populates a sensible fallback
sortingKey for blocks missing it (e.g., derive from id or creation order) so
deserialization remains backward compatible; update references where
baseBlockFields is used so the sanitizer/factory sets the fallback when needed.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 67f0d76 and f23bbc6.

📒 Files selected for processing (1)
  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Place test files next to source files with .test.ts or .test.tsx extension
Use strict type checking in TypeScript files
Prefer type safety over convenience in TypeScript
Use const for immutable values
Avoid any types - use proper type definitions
Follow Biome's rules (configured in biome.json)
Use literal keys instead of bracket notation when possible
Prefer single quotes for strings (except when avoiding escapes)
Keep code clean and readable following Biome standards

Files:

  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
packages/blocks/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

packages/blocks/src/**/*.{ts,tsx}: Use escapePythonString() for safely embedding strings in Python code in the blocks package
Use ts-dedent for clean multiline template strings in code generation
Always include DataFrame config when generating code for code/SQL blocks

Files:

  • packages/blocks/src/deserialize-file/deepnote-file-schema.ts
🧬 Code graph analysis (1)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (1)
packages/blocks/src/index.ts (2)
  • deepnoteBlockSchema (11-11)
  • DeepnoteBlock (3-3)
🔇 Additional comments (5)
packages/blocks/src/deserialize-file/deepnote-file-schema.ts (5)

14-56: Well-structured base metadata hierarchy.

Good use of .passthrough() for forward compatibility. Schema composition is clean.


85-161: Non-executable block schemas look solid.

Consistent structure. emptyContent() correctly enforces empty content for image/separator. Text cell variants properly extend textCellMetadataSchema.


167-247: Executable block schemas are well-defined.

notebookFunctionBlockSchema correctly enforces function_notebook_id as nullable with sensible default. Enum constraints are appropriate.


371-451: Discriminated union and type exports are comprehensive.

Clean organization. InputBlock and TextCellBlock unions will help with type guards downstream.


508-560: File schema correctly integrates the new block discriminated union.

Structure is solid.

@saltenasl
saltenasl marked this pull request as ready for review January 8, 2026 12:53
@saltenasl
saltenasl requested a review from Artmann January 8, 2026 12:54
@saltenasl

Copy link
Copy Markdown
Contributor Author

@coderabbitai this PR introduces quite a few breaking changes in the deepnote file schema, some of them have been addressed by e.g. providing sensible defaults - this is applicable only when parsing, TS types will still have breaking changes. Can you please list all of the breaking changes in a table format so i can use this in the changelog when informing consumers about them? Include if it has been automatically handled when parsing files (TS types will still have the breaking change).

@coderabbitai

coderabbitai Bot commented Jan 8, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the schema file to identify which breaking changes have automatic handling
cat packages/blocks/src/deserialize-file/deepnote-file-schema.ts

Length of output: 19301


@saltenasl: Here's a comprehensive table of all breaking changes for the changelog:

Breaking Changes in Deepnote File Schema

Category Breaking Change TypeScript Impact Auto-Handled When Parsing Notes
Type Discrimination type: 'text' removed ✅ Yes - must use specific text-cell-* types ❌ No Must manually migrate to: text-cell-h1, text-cell-h2, text-cell-h3, text-cell-p, text-cell-bullet, text-cell-todo, text-cell-callout
Type System DeepnoteBlock now a discriminated union ✅ Yes - requires type narrowing N/A Consumer code must use type guards to access variant-specific fields
Type System Unknown block types rejected ✅ Yes ❌ No Discriminated union will fail validation for any unrecognized type value
Type System Cannot mix fields from different block types ✅ Yes ❌ No Each block must match exactly one schema variant
Required Metadata BigNumberBlock.metadata.deepnote_big_number_title ✅ Yes - now required string ✅ Yes - defaults to '' TS type shows required; parsing provides default
Required Metadata BigNumberBlock.metadata.deepnote_big_number_value ✅ Yes - now required string ✅ Yes - defaults to '' TS type shows required; parsing provides default
Required Metadata BigNumberBlock.metadata.deepnote_big_number_format ✅ Yes - now required string ✅ Yes - defaults to '' TS type shows required; parsing provides default
Required Metadata All input blocks: metadata.deepnote_variable_name ✅ Yes - now required string ✅ Yes - defaults to 'unnamed_variable' TS type shows required; parsing provides default
Required Metadata InputTextBlock.metadata.deepnote_variable_value ✅ Yes - now required string ✅ Yes - defaults to '' TS type shows required; parsing provides default
Required Metadata InputTextareaBlock.metadata.deepnote_variable_value ✅ Yes - now required string ✅ Yes - defaults to '' TS type shows required; parsing provides default
Required Metadata InputCheckboxBlock.metadata.deepnote_variable_value ✅ Yes - now required boolean ✅ Yes - defaults to false TS type shows required; parsing provides default
Required Metadata InputSelectBlock.metadata.deepnote_variable_value ✅ Yes - now required ✅ Yes - defaults to '' TS type shows required; parsing provides default
Required Metadata InputSelectBlock.metadata.deepnote_variable_options ✅ Yes - now required array ✅ Yes - defaults to [] TS type shows required; parsing provides default
Required Metadata InputSelectBlock.metadata.deepnote_variable_custom_options ✅ Yes - now required array ✅ Yes - defaults to [] TS type shows required; parsing provides default
Required Metadata InputSelectBlock.metadata.deepnote_variable_selected_variable ✅ Yes - now required string ✅ Yes - defaults to '' TS type shows required; parsing provides default
Required Metadata InputSelectBlock.metadata.deepnote_variable_select_type ✅ Yes - now required enum ✅ Yes - defaults to 'from-options' TS type shows required; parsing provides default
Required Metadata InputSliderBlock.metadata.deepnote_variable_value ✅ Yes - now required string ✅ Yes - defaults to '0' TS type shows required; parsing provides default
Required Metadata InputSliderBlock.metadata.deepnote_slider_min_value ✅ Yes - now required number ✅ Yes - defaults to 0 TS type shows required; parsing provides default
Required Metadata InputSliderBlock.metadata.deepnote_slider_max_value ✅ Yes - now required number ✅ Yes - defaults to 100 TS type shows required; parsing provides default
Required Metadata InputSliderBlock.metadata.deepnote_slider_step ✅ Yes - now required number ✅ Yes - defaults to 1 TS type shows required; parsing provides default
Required Metadata InputDateBlock.metadata.deepnote_variable_value ✅ Yes - now required string ✅ Yes - defaults to '' TS type shows required; parsing provides default
Required Metadata InputDateRangeBlock.metadata.deepnote_variable_value ✅ Yes - now required ✅ Yes - defaults to '' TS type shows required; parsing provides default
Required Metadata InputFileBlock.metadata.deepnote_variable_value ✅ Yes - now required string ✅ Yes - defaults to '' TS type shows required; parsing provides default
Required Metadata NotebookFunctionBlock.metadata.function_notebook_id ✅ Yes - now required (nullable) ✅ Yes - defaults to null TS type shows required; parsing provides default
Required Metadata Missing metadata object on any block ✅ Yes - metadata now required ✅ Yes - defaults to {} All block schemas have .default({})
Validation contentHash must match /^(md5|sha256):[a-f0-9]+$/i ✅ Yes - stricter type ❌ No Old format hashes will fail validation
Validation executionStartedAt must be ISO datetime string ✅ Yes - stricter type ❌ No Non-ISO formats will fail validation
Validation executionFinishedAt must be ISO datetime string ✅ Yes - stricter type ❌ No Non-ISO formats will fail validation
Validation execution.startedAt must be ISO datetime string ✅ Yes - stricter type ❌ No Non-ISO formats will fail validation
Validation execution.finishedAt must be ISO datetime string ✅ Yes - stricter type ❌ No Non-ISO formats will fail validation
Validation ImageBlock.metadata.deepnote_img_width enum constraint ✅ Yes - limited to specific values ❌ No Only 'actual', '50%', '75%', '100%' allowed
Validation ImageBlock.metadata.deepnote_img_alignment enum constraint ✅ Yes - limited to specific values ❌ No Only 'left', 'center', 'right' allowed
Validation TextCellCalloutBlock.metadata.color enum constraint ✅ Yes - limited to specific values ❌ No Only 'blue', 'green', 'yellow', 'red', 'purple' allowed
Validation SqlBlock.metadata.deepnote_return_variable_type enum constraint ✅ Yes - limited to specific values ❌ No Only 'dataframe', 'query_preview' allowed
Validation ButtonBlock.metadata.deepnote_button_color_scheme enum constraint ✅ Yes - limited to specific values ❌ No Only 'blue', 'red', 'neutral', 'green', 'yellow' allowed
Validation ButtonBlock.metadata.deepnote_button_behavior enum constraint ✅ Yes - limited to specific values ❌ No Only 'run', 'set_variable' allowed
Validation InputSelectBlock.metadata.deepnote_variable_select_type enum constraint ✅ Yes - limited to specific values ✅ Yes - defaults to 'from-options' Only 'from-options', 'from-variable' allowed
Validation execution.triggeredBy enum constraint ✅ Yes - limited to specific values ❌ No Only 'user', 'schedule', 'api', 'ci' allowed
Validation environment.python.environment enum constraint ✅ Yes - limited to specific values ❌ No Only 'uv', 'conda', 'venv', 'poetry', 'system' allowed
Content Constraints ImageBlock.content must be empty ✅ Yes - typed as literal('') ✅ Yes - preprocessed to '' Non-empty content automatically cleared
Content Constraints SeparatorBlock.content must be empty ✅ Yes - typed as literal('') ✅ Yes - preprocessed to '' Non-empty content automatically cleared
Content Constraints ButtonBlock.content must be empty ✅ Yes - typed as literal('') ✅ Yes - preprocessed to '' Non-empty content automatically cleared
Content Constraints VisualizationBlock.content must be empty ✅ Yes - typed as literal('') ✅ Yes - preprocessed to '' Non-empty content automatically cleared
Content Constraints NotebookFunctionBlock.content must be empty ✅ Yes - typed as literal('') ✅ Yes - preprocessed to '' Non-empty content automatically cleared
Field Scope Execution fields only on executable blocks ✅ Yes - not present in non-executable types ❌ No executionCount, executionStartedAt, executionFinishedAt, outputs will cause validation failure on non-executable blocks
Public API Removed BlockMetadata union type export ✅ Yes - no longer exported N/A Import from schema instead
Public API Removed ExecutableBlockMetadata interface export ✅ Yes - no longer exported N/A Types now inferred from schema
Public API Removed individual block metadata type exports ✅ Yes - no longer exported N/A Use schema-inferred types instead

Summary by Handling Status

✅ Automatically Handled When Parsing (26 items):

  • All required metadata fields with defaults
  • Empty content constraints (5 blocks)
  • Missing metadata object

❌ Requires Manual Migration (23 items):

  • Type discrimination ('text' → 'text-cell-*')
  • Unknown block types
  • Field mixing validation
  • contentHash format
  • All datetime validations (5 fields)
  • All enum constraints (10 fields)
  • Execution fields on non-executable blocks

N/A - API Changes (4 items):

  • Discriminated union type narrowing requirement
  • Removed public type exports

@saltenasl
saltenasl merged commit fcc864e into main Jan 8, 2026
@saltenasl
saltenasl deleted the ls/more-strict-block-schema branch January 8, 2026 13:15
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.

2 participants