@notionhq/custom-blocks-dev-shell 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,202 +0,0 @@
1
- # @notionhq/custom-blocks-host
2
-
3
- The host manages the bridge between your application and a custom block iframe. Your application
4
- owns the iframe, permissions, data access, persistence, analytics, and UI. Block authors use
5
- `@notionhq/custom-blocks`.
6
-
7
- Create the host before navigating the iframe. Pass the full block URL as `sandboxUrl`, and call
8
- `stop()` when removing the iframe. A host instance belongs to the required `viewerId`. Supply one
9
- asynchronous `getCurrentUser` profile reader. Its returned ID must match that viewer. Create a fresh
10
- host and iframe when the viewer changes.
11
-
12
- For configuration and lifecycle details, see [Initialization and lifecycle](docs/lifecycle.md).
13
-
14
- For data handlers, query subscriptions, and partial integrations, see the
15
- [Host contract](docs/host-contract.md). The host accepts `CustomBlockHostOptions`.
16
-
17
- Use `BridgeParent` from `@notionhq/custom-blocks-host/protocol` to construct parent references with
18
- plain string IDs. The host validates the parent before sending it to the block.
19
-
20
- Implement `CustomBlockHostHandlers` to connect the host to your application. Handlers that return
21
- results use promises. `CustomBlockHostHandler<Args, Payload>` supplies the shared signature and
22
- request context. Handlers return shared bridge data using `CustomBlockHostHandlerResult`. Use
23
- `makeBridgePage` to construct a complete `BridgePage` from your records. See
24
- [Return bridge data](docs/handlers.md#return-bridge-data).
25
-
26
- ## Create a host
27
-
28
- Install `@notionhq/custom-blocks-host` in your embedding application. Run this TypeScript through
29
- your browser bundler after the document body exists.
30
-
31
- This example embeds a block with no data sources and supplies fixed demo context. Replace
32
- `https://blocks.example.com/hello` with your block's URL. Serve the block from a different origin
33
- than the embedding application.
34
-
35
- ```ts
36
- import { createCustomBlockHost, hostHandlerNotImplemented } from "@notionhq/custom-blocks-host"
37
-
38
- function mountCustomBlock(container: HTMLElement, blockUrl: URL): () => void {
39
- if (
40
- !["http:", "https:"].includes(blockUrl.protocol) ||
41
- blockUrl.origin === window.location.origin
42
- ) {
43
- throw new Error("The block needs an HTTP or HTTPS URL on a separate origin")
44
- }
45
-
46
- const wrapper = document.createElement("section")
47
- const status = document.createElement("p")
48
- status.setAttribute("role", "status")
49
- status.textContent = "Loading block…"
50
- const iframe = document.createElement("iframe")
51
- iframe.title = "Hello custom block"
52
- iframe.setAttribute("sandbox", "allow-scripts allow-same-origin")
53
- iframe.allow = "clipboard-write"
54
- iframe.style.width = "100%"
55
- iframe.style.height = "300px"
56
- iframe.style.visibility = "hidden"
57
- wrapper.append(status, iframe)
58
- container.append(wrapper)
59
-
60
- function setHeight(height: number) {
61
- iframe.style.height = `${Math.min(1200, Math.max(120, height))}px`
62
- }
63
-
64
- const host = createCustomBlockHost({
65
- iframe,
66
- instance: { type: "block", blockId: "11111111-1111-4111-8111-111111111111" },
67
- viewerId: "33333333-3333-4333-8333-333333333333",
68
- getCurrentUser: async () => ({
69
- object: "user",
70
- id: "33333333-3333-4333-8333-333333333333",
71
- type: "person",
72
- name: "Demo viewer",
73
- avatar_url: null,
74
- person: { email: "viewer@example.com" },
75
- }),
76
- theme: "light",
77
- contrastMode: "standard",
78
- containingPage: {
79
- type: "page",
80
- id: "22222222-2222-4222-8222-222222222222",
81
- parent: { type: "workspace", workspace: true },
82
- },
83
- parent: {
84
- type: "page_id",
85
- page_id: "22222222-2222-4222-8222-222222222222",
86
- },
87
- sandboxUrl: blockUrl.href,
88
- manifestSource: "host",
89
- getPersistedManifest: async () => ({
90
- status: "success",
91
- manifest: { version: 1, dataSources: {} },
92
- }),
93
- bindings: { pages: {}, dataSources: {} },
94
- handlers: {
95
- getDataSource: async () => ({ status: "success", state: { status: "unavailable" } }),
96
- subscribeToQuery: ({ onError }) => onError(hostHandlerNotImplemented("subscribeToQuery")),
97
- getPage: async () => ({ status: "error", error: hostHandlerNotImplemented("getPage") }),
98
- createPage: async () => ({ status: "error", error: hostHandlerNotImplemented("createPage") }),
99
- updatePage: async () => ({ status: "error", error: hostHandlerNotImplemented("updatePage") }),
100
- getUser: async () => ({ status: "error", error: hostHandlerNotImplemented("getUser") }),
101
- listUsers: async () => ({ status: "error", error: hostHandlerNotImplemented("listUsers") }),
102
- openPage: async () => ({ status: "error", error: hostHandlerNotImplemented("openPage") }),
103
- openExternalUrl: async () => ({
104
- status: "error",
105
- error: hostHandlerNotImplemented("openExternalUrl"),
106
- }),
107
- resize: message => setHeight(message.height),
108
- },
109
- onStatusChange: state => {
110
- if (state.status === "ready") {
111
- setHeight(state.initialHeight ?? 300)
112
- status.hidden = true
113
- iframe.style.visibility = "visible"
114
- } else if (state.status === "failed") {
115
- iframe.style.visibility = "hidden"
116
- status.hidden = false
117
- status.textContent = `Block failed: ${state.error.code}`
118
- }
119
- },
120
- })
121
-
122
- // The host must listen before the block starts its handshake.
123
- iframe.src = blockUrl.href
124
-
125
- return () => {
126
- host.stop()
127
- wrapper.remove()
128
- }
129
- }
130
-
131
- const dispose = mountCustomBlock(document.body, new URL("https://blocks.example.com/hello"))
132
- window.addEventListener("pagehide", dispose, { once: true })
133
- ```
134
-
135
- The example displays “Loading block…” until the host reports `ready`, then reveals the iframe. A
136
- connection failure displays its error code. The example limits the iframe height to 120–1,200 CSS
137
- pixels.
138
-
139
- Call `dispose()` when your application removes the embed. To retry a failed connection or change the
140
- block URL, dispose of the current embed and call `mountCustomBlock()` again.
141
-
142
- Initial `theme`, `contrastMode`, `containingPage`, and `parent` may be `null` while loading. Call
143
- the corresponding setters as values resolve. Setup waits for the manifest, theme, and contrast mode.
144
- Parent and containing page values can arrive later. See
145
- [manifest and initial state](docs/lifecycle.md#manifest-and-initial-state) for the loading contract.
146
-
147
- For a production integration, replace the demo context and manifest with your application's values.
148
- Supply data source bindings and handlers for the APIs your block uses. Your application must enforce
149
- permissions and record access.
150
-
151
- To connect workspace data, see [Connect a data source](docs/handlers.md#connect-a-data-source).
152
-
153
- `CustomBlockHostInstance` accepts plain string IDs. `instance` identifies the configured block,
154
- page, or view independently of the page currently being displayed. `CustomBlockInstance` uses
155
- `{ type: "block" | "page", blockId }` or `{ type: "view", viewId }`. The identity stays fixed for
156
- the host connection and is included in `init`. A layout module backed by a custom block uses that
157
- block's identity.
158
-
159
- ## Guides and reference
160
-
161
- - [Initialization and lifecycle](docs/lifecycle.md): manifests, initial values, timeouts, live
162
- updates, and cleanup.
163
- - [Handlers and data](docs/handlers.md): application handlers, data source integration, queries, and
164
- navigation.
165
- - [Connection compatibility](docs/compatibility.md): protocol negotiation and version requirements.
166
-
167
- The runtime handles the wire handshake and message validation. The shared protocol references define
168
- message payloads and versioning:
169
-
170
- - [Wire protocol](../bridge/protocol.md)
171
- - [Protocol versioning](../bridge/versioning.md)
172
-
173
- ## Protocol schemas and types
174
-
175
- The `/protocol` entrypoint exposes message schemas and types, data shapes, IDs, and error
176
- definitions. Import these definitions through the host package:
177
-
178
- ```ts
179
- import {
180
- sandboxToHostMessageSchema,
181
- type SandboxToHostMessage,
182
- } from "@notionhq/custom-blocks-host/protocol"
183
- ```
184
-
185
- Host APIs, configuration, handler results, and domain argument types are available from
186
- `@notionhq/custom-blocks-host`.
187
-
188
- These schemas validate wire payloads. Your application still enforces permissions.
189
-
190
- ## Standalone browser module
191
-
192
- `dist/browser.js` is one ES module with all dependencies. Use it when the browser must not fetch
193
- additional modules, such as under an exact-URL Content Security Policy.
194
-
195
- ### Native page icons
196
-
197
- `CustomBlockHostPageIcon` accepts canonical native icon names from hosts. Hosts validate names and
198
- colors before writing. The runtime validates response payloads.
199
-
200
- Hosts must check URL-backed icon and cover writes against the block's network permissions before
201
- mutating records. Notion permits the submitted HTTPS destination only when its origin is
202
- allowlisted. That origin is trusted to redirect.
@@ -1,114 +0,0 @@
1
- # Connection compatibility
2
-
3
- The SDK and host release independently. Their package versions do not determine whether they can
4
- communicate. The connection uses a protocol version that both implement.
5
-
6
- ## Supported versions
7
-
8
- The current SDK connection contract is protocol 12. The SDK sends `connect` with a
9
- `supportedProtocolVersions` array of distinct positive integers. The host selects a version from
10
- that offer and returns it in `connectResult.protocolVersion`. This host selects protocol 12 when the
11
- offer includes it and the configured minimum permits it. Otherwise, it returns
12
- `unsupported_protocol_version`.
13
-
14
- The selected version applies to the connection. `init` does not repeat it. `sdkVersion` identifies
15
- the SDK package for diagnostics. It does not select the protocol.
16
-
17
- `LATEST_BRIDGE_PROTOCOL_VERSION` identifies the latest contract defined by the protocol package.
18
- `MIN_HOST_SUPPORTED_BRIDGE_PROTOCOL_VERSION` defines the host runtime's minimum. The
19
- `minBridgeProtocolVersion` option defaults to that minimum and can restrict which SDKs an embedding
20
- application accepts. Changing this option cannot add support for a contract the host does not
21
- implement.
22
-
23
- The host also accepts the protocol 3–11 handshake, where `connect` declares a single
24
- `bridgeProtocolVersion`. Those connections retain eager initialization and their response formats.
25
- The current SDK requires protocol 12 and cannot connect to a host that supports only protocols 3–11.
26
-
27
- ## Connection requirements
28
-
29
- Create the host before navigating the iframe so it can receive `connect`. Each host and iframe
30
- handle one connection. Create a fresh pair to retry, change the block URL, or change viewers.
31
-
32
- A successful `connectResult` confirms the selected protocol. Setup completes when the sandbox
33
- accepts `init` and sends a successful `initResult`. The host then permits data operations while it
34
- waits for `ready`. The embedding application reveals the iframe when the host reports `ready`. See
35
- [Initialization and lifecycle](lifecycle.md) for payload delivery, callbacks, and timeouts.
36
-
37
- An SDK must implement every protocol version it advertises. If the SDK requires a contract the host
38
- does not implement, update the embedding application's host before adopting that SDK. Publishing a
39
- host package does not update applications that use it.
40
-
41
- The [protocol versioning reference](../../bridge/versioning.md) defines the rules for wire
42
- contract changes.
43
-
44
- ## Host normalization
45
-
46
- The host validates sandbox requests before dispatching them to handlers. Handlers use current data
47
- shapes, and the host converts responses to the sandbox's declared protocol. Setters, query
48
- refreshes, and handler responses use the same conversion. Messages that need no conversion pass
49
- through unchanged.
50
-
51
- ## Current compatibility behavior
52
-
53
- | Target | Query results | Page operation results | Binding schemas | Native icons |
54
- | ------ | --------------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
55
- | 3–4 | Flat ID-keyed values, including synthetic metadata entries | ID-keyed properties with unsupported property objects omitted | Synthetic metadata read schemas restored in outgoing copies | External SVG URLs in page operations. Icons omitted from flat query results |
56
- | 5 | Same query values as protocols 3–4 | Same page format as protocols 3–4 | Actual database schemas. The SDK supplies synthetic read schemas locally | Same as protocols 3–4 |
57
- | 6 | Unified name-keyed properties. Text fallback property objects become `null` | Same unified page format | Actual database schemas | External SVG URLs |
58
- | 7–8 | Unified pages with typed text fallback properties | Same unified page format | Actual database schemas | External SVG URLs |
59
- | 9–12 | Unified pages with typed text fallback properties | Same unified page format | Actual database schemas | Native icon objects |
60
-
61
- The synthetic metadata IDs are `created_time`, `last_edited_time`, `created_by`, and
62
- `last_edited_by`. They retain metadata meaning if an actual property uses the same raw ID. This
63
- matches the protocol 3–4 binding schema precedence. Host validation always uses the unmodified
64
- actual database schema.
65
-
66
- Release-specific compatibility limits are documented in the changelog entries for
67
- [protocol 5 page context](../../bridge/changelog.md#protocol-5-unavailable-containing-page-context)
68
- and
69
- [protocol 6 text fallback properties](../../bridge/changelog.md#protocol-6-richer-fallback-properties).
70
-
71
- ### Native page icons
72
-
73
- Protocol 9 and later receive native icon objects. Protocols 3–8 receive external SVG URLs in page
74
- operation results, and protocols 6–8 also receive them in query results. Protocols 3–5 use flat
75
- query results without page appearance fields. Omitted native colors default to gray when producing
76
- SVG URLs.
77
-
78
- ### Unavailable containing-page context
79
-
80
- Protocols 3–4 receive `context_unavailable` during initialization or stop when containing-page
81
- context becomes unavailable. This concerns `init.page` and `pageChanged.page`, not a page
82
- operation's `page_unavailable` error.
83
-
84
- ### Protocol 3–5 metadata query semantics
85
-
86
- Page creation and edit metadata is readable without corresponding database columns. Current page
87
- objects carry these fields at the top level. Protocol 3–5 query adapters copy them into
88
- `propertiesById` for older SDKs.
89
-
90
- Filters and sorts require actual database properties in the bound schema. The host does not support
91
- queries against synthetic metadata IDs without corresponding database properties.
92
-
93
- ## Data source binding names
94
-
95
- Protocols 11–12 use `dataSourceSchema` and `dataSourcePointer`. Host adapters supply only these
96
- current names. The outgoing boundary restores `collectionSchema` and `collectionPointer` for
97
- protocols 3–10, including initialization and live binding updates.
98
-
99
- ## Initialization and location values
100
-
101
- | Contract | Protocols 3–11 | Protocol 12 |
102
- | ---------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
103
- | Initialization | Eager values include the current user, parent, containing page, and data source bindings | Setup contains `instance`, `manifest`, and `preferences`. Data access does not block setup |
104
- | Reveal | Successful `initResult` supplies the initial height and permits reveal | Successful `initResult` permits data operations. `ready` supplies the initial height and permits reveal |
105
- | Containing-page display mode | Omitted from eager init and `pageChanged` | Required on accessible containing-page descriptors. Defaults to `full_page` |
106
- | Location failures | Known initial failures fail eager initialization. `parentError` and `pageError` are not sent | `parentError` and `pageError` report known failures independently. Later value notifications clear the corresponding error |
107
- | Missing user names | Compatibility encoding omits missing names and preserves empty strings | Full user profiles contain `name: string \| null` |
108
-
109
- For protocols 3–11, the host converts `does_not_exist`, `permission_denied`, and `load_failed`
110
- handler errors to the operation's existing error codes. User lookup and listing use
111
- `get_user_failed` and `list_users_failed`. Page reads, creation, and updates use `get_page_failed`,
112
- `create_page_failed`, or `update_page_failed` for load failures, and `page_unavailable` for missing
113
- or inaccessible pages. Page opening uses `page_unavailable`. Protocol 12 preserves the shared
114
- resource error codes.
@@ -1,110 +0,0 @@
1
- # Host handlers and data
2
-
3
- Handlers connect block requests to your application's data access, persistence, and navigation. The
4
- runtime validates bridge messages and manages subscriptions. Your application enforces viewer
5
- permissions and implements the requested operations.
6
-
7
- The [dev shell](https://www.npmjs.com/package/@notionhq/custom-blocks-dev-shell) is a working host
8
- implementation with local sample data. Use it as a reference for a larger integration. Production
9
- hosts must provide their own permissions, data access, and persistence.
10
-
11
- ## Handler contracts
12
-
13
- Every `CustomBlockHostHandlers` method is required. Use `hostHandlerNotImplemented()` in explicit
14
- wrappers for the
15
- [operations that can report unsupported](host-contract.md#options-and-partial-implementations).
16
- Handlers that return results use promises. Errors carry `{ code, message, isRetryable }`, with open
17
- string codes.
18
-
19
- ### Return bridge data
20
-
21
- Handlers return data in the bridge's shared types. Use bridge builders to construct complete objects
22
- from application records.
23
-
24
- The host validates result shapes and matches responses to requests. Your application checks that
25
- records exist and that the viewer may perform the requested operation.
26
-
27
- The runtime validates query filters and sorts against the bound data source schema before
28
- `subscribeToQuery` runs. See the [wire reference](../../bridge/protocol.md#data-sources) for
29
- query semantics.
30
-
31
- For one-shot requests, a handler that throws, rejects, or returns a malformed result produces
32
- `unknown_error`. Exception details go to `onLog`. The sandbox receives a generic error. Specific
33
- errors returned by handlers pass through unchanged.
34
-
35
- Shared resource errors are `load_failed`, `permission_denied`, and `does_not_exist`. Return
36
- `does_not_exist` only when the underlying operation establishes absence and permits disclosing it.
37
- Missing local records do not establish absence. Preserve an unavailable result when the underlying
38
- operation does not distinguish missing resources from denied access. The embedding application makes
39
- that decision. The shared host forwards its result.
40
-
41
- ## Connect a data source
42
-
43
- To extend the [embed example](../README.md#create-a-host) with a data source, add its manifest
44
- declaration, bindings, metadata handler, and query handler. The block uses the same declaration and
45
- queries the source through the SDK's public APIs.
46
-
47
- Declare `tasks` and its property keys in the manifest. Supply their IDs in `bindings.dataSources`,
48
- and return the schema from `getDataSource({ dataSourceId, signal })`. Missing resources and denied
49
- access both return `{ status: "success", state: { status: "unavailable" } }`. Binding failures
50
- return an error. See [metadata and configuration](host-contract.md#metadata-and-configuration).
51
-
52
- `subscribeToQuery` receives the source ID, query options, limit, signal, and callbacks described in
53
- [queries and cancellation](host-contract.md#queries-and-cancellation). Enforce record access, apply
54
- the requested filters, sorts, and archive selection, and honor the limit before calling
55
- `onSnapshot({ items, hasMore })`. If you reduce the requested limit, include
56
- `limitClamp: { requested, applied }` in the snapshot. See
57
- [query limits](../../bridge/protocol.md#host-applied-query-limits) for the result contract.
58
- Result properties use display names as keys and include raw property IDs. The runtime validates
59
- results before sending them to the SDK.
60
-
61
- ## Refresh active queries
62
-
63
- The platform observer calls `onSnapshot` again when rows change. Release the observer and cancel
64
- pending setup when the subscription signal aborts. The shared host handles subscription IDs,
65
- replacement, unsubscribe, and shutdown. Do not return a second cleanup callback.
66
-
67
- Use `host.refreshDataSource({ dataSourceId })` when source metadata or access changes. The refresh
68
- invalidates metadata and cancels queries for every source, not just `dataSourceId`. It does not
69
- fetch replacement metadata. See [Updates](host-contract.md#updates) for the contract. Ordinary row
70
- changes flow through the active observer and need no metadata refresh.
71
-
72
- ## Page and user operations
73
-
74
- `createPage`, `getPage`, and `updatePage` connect page requests to your application's data access
75
- and persistence. `getUser` and `listUsers` supply user data. Each handler returns a success payload
76
- or an error. The runtime adds the request's correlation ID and sends the response. The application
77
- enforces record access before reading or writing data.
78
-
79
- `openPage` handles navigation to a Notion page. `resize` receives the block's requested height in
80
- CSS pixels. The application owns navigation and iframe sizing.
81
-
82
- ## External navigation
83
-
84
- `openExternalUrl` receives an `AbortSignal` and an absolute HTTP or HTTPS URL without credentials.
85
- The URL is limited to 2,048 JavaScript code units before and after normalization. The host
86
- implementation displays the exact URL, obtains approval, and navigates only after approval. It may
87
- apply further restrictions. Dismiss pending confirmation UI when the signal aborts.
88
-
89
- Each iframe permits one pending navigation. A different request receives `pending_navigation`. A
90
- duplicate of the active request is ignored. Completed requests are forgotten, so later requests
91
- require fresh approval. The runtime redacts the URL from `onLog` payloads and suppresses results
92
- after stop.
93
-
94
- ## Property binding
95
-
96
- `getAutoBoundPropertyIdsByKey({ manifestProperties, propertySchemasById })` requires matching
97
- property types and either an exact raw ID match or a display-name match after trimming and
98
- lowercasing. IDs are not trimmed or case-folded. Exactly one candidate creates a binding. Zero or
99
- multiple candidates leave the property unmapped. The result maps manifest property keys to database
100
- property IDs. An ID match has no priority over a name match: if they identify different compatible
101
- properties, the manifest property stays unmapped.
102
-
103
- ## Date conversion and types
104
-
105
- `toNotionDateValue()` converts `NotionDateInput` into the four `CustomBlockDateValue` variants,
106
- including reminders. Invalid input throws `InvalidNotionDateError`.
107
-
108
- The root exports host configuration, handlers, results, and domain argument types. Wire schemas,
109
- message and page types, and shared constants use the
110
- [protocol subpath](../README.md#protocol-schemas-and-types).
@@ -1,196 +0,0 @@
1
- # Host contract
2
-
3
- `createCustomBlockHost(options: CustomBlockHostOptions)` returns a running `CustomBlockHost`.
4
- `CustomBlockHostHandlers` connects that instance to application data and actions. See
5
- [Connection compatibility](compatibility.md) for protocol negotiation and version requirements.
6
-
7
- Your application supplies authorized data and actions. The shared host owns initialization, message
8
- validation, protocol compatibility, subscriptions, cancellation, and shutdown. Each host instance
9
- belongs to one viewer. Stop the host and create a fresh host and iframe to change viewers.
10
-
11
- ## Options and partial implementations
12
-
13
- Required options are `instance`, `viewerId`, `getCurrentUser`, `theme`, `contrastMode`,
14
- `containingPage`, `parent`, `iframe`, `sandboxUrl`, `manifestSource`, `getPersistedManifest`,
15
- `onStatusChange`, `bindings`, and `handlers`. `instance` and `viewerId` stay fixed for the instance.
16
- Optional settings for this contract are `onLog`, `minBridgeProtocolVersion`, `noConnectTimeoutMs`,
17
- `initialStateTimeoutMs`, `noInitResultTimeoutMs`, and `noReadyTimeoutMs`.
18
-
19
- `theme`, `contrastMode`, `containingPage`, and `parent` accept `null` while unresolved. Supply
20
- resolved values through `setTheme()`, `setContrastMode()`, `setContainingPage()`, and `setParent()`.
21
- The host retains the latest values. Setup waits for theme and contrast mode, but not parent or
22
- containing page values. Your application observes changes and calls the setters. Creating the host
23
- does not subscribe to application state. See
24
- [Manifest and initial state](lifecycle.md#manifest-and-initial-state) for loading and delivery.
25
-
26
- For an accessible containing page, supply `displayMode`: `"full_page"`, `"side_peek"`, or
27
- `"center_peek"`. Call `setContainingPage()` when the mode changes, even if the page ID is unchanged.
28
- Use `full_page` outside peek presentation. It is also the default when the field is omitted.
29
- Unavailable pages carry no display metadata.
30
-
31
- Supply known initial failures through `parentError` and `containingPageError`, or report later
32
- failures with `setParentError(error)` and `setContainingPageError(error)`. Errors carry `code`,
33
- `message`, and `isRetryable`. Setup still succeeds. A later value setter clears the error. Use
34
- unavailable values for resources the host cannot expose. Use errors when loading failed.
35
-
36
- Every handler is required. `hostHandlerNotImplemented` accepts `getPage`, `createPage`,
37
- `updatePage`, `getUser`, `listUsers`, `openPage`, `openExternalUrl`, and `subscribeToQuery`.
38
- Failures from these operations leave initialization and unrelated operations available. The SDK
39
- requests the current user profile and source metadata independently after setup acknowledgment.
40
-
41
- A partial integration supplies an explicit wrapper using `hostHandlerNotImplemented`, which creates
42
- a non-retryable `host_handler_not_implemented` error:
43
-
44
- ```ts
45
- import {
46
- createCustomBlockHost,
47
- hostHandlerNotImplemented,
48
- type CustomBlockHostOptions,
49
- } from "@notionhq/custom-blocks-host"
50
-
51
- declare const options: CustomBlockHostOptions
52
-
53
- options.handlers.getPage = async () => ({
54
- status: "error",
55
- error: hostHandlerNotImplemented("getPage"),
56
- })
57
-
58
- options.handlers.subscribeToQuery = ({ onError }) => {
59
- onError(hostHandlerNotImplemented("subscribeToQuery"))
60
- }
61
-
62
- const host = createCustomBlockHost(options)
63
- host.stop()
64
- ```
65
-
66
- `resize` returns no result and sends no result message. Its handler can do nothing if the embed has
67
- a fixed size. The application enforces authorization and obtains any required approval. Neither
68
- manifest declarations nor bindings establish access.
69
-
70
- Full user profiles require `name: string | null` and `avatar_url: string | null`. Use `null` when a
71
- name is unavailable. Empty strings remain empty strings. The `makeBridgeUser` builder accepts an
72
- omitted name and supplies `null` before validating the full profile. ID-only user references do not
73
- promise profile fields.
74
-
75
- ## Handler inputs and results
76
-
77
- `CustomBlockHostHandlerResult<Payload>` combines `{ status: "success" }` with named payload fields,
78
- or returns `{ status: "error", error: { code, message, isRetryable } }`. For example, `getUser`
79
- returns `{ status: "success", user }` and `listUsers` returns `{ status: "success", list }`.
80
- `getPersistedManifest` returns `{ status: "success", manifest }`. Actions without payloads return
81
- `{ status: "success" }`. The shared host validates results and logs unexpected exceptions before
82
- returning a generic error to the sandbox.
83
-
84
- Asynchronous providers receive `CustomBlockHostRequestContext` with an `AbortSignal`. Inputs omit
85
- sandbox message types and correlation IDs. Named domain arguments such as
86
- `CustomBlockHostCreatePageArgs`, `CustomBlockHostUpdatePageArgs`, and `CustomBlockHostOpenPageArgs`
87
- contain only operation data. Handlers receive those arguments combined with
88
- `CustomBlockHostRequestContext`, which supplies `signal`. Page operations include insertion rules,
89
- properties, and appearance. Source and page operations use raw IDs. The SDK resolves data source
90
- keys before sending requests.
91
-
92
- | Handler | Additional input | Success payload |
93
- | ----------------- | ---------------------------------- | --------------------------------------- |
94
- | `getDataSource` | `dataSourceId` | `state: CustomBlockHostDataSourceState` |
95
- | `getPage` | `pageId`, optional `dataSourceId` | `page: BridgePage` |
96
- | `createPage` | Existing creation payload | `page: BridgePage` |
97
- | `updatePage` | Existing update payload | `page: BridgePage` |
98
- | `getUser` | `userId` | `user: BridgeUser` |
99
- | `listUsers` | Optional `pageSize`, `startCursor` | `list: BridgeUserList` |
100
- | `openPage` | `pageId`, `mode` | None |
101
- | `openExternalUrl` | `url` | None |
102
-
103
- `openPage` completes the requested action without echoing its input. The shared host includes the
104
- requested page ID in the wire response.
105
-
106
- Handlers that return results use promises. `CustomBlockHostHandler<Args, Payload>` combines domain
107
- arguments with `CustomBlockHostRequestContext` and the shared result type. `subscribeToQuery` and
108
- `resize` remain synchronous.
109
-
110
- ## Current viewer
111
-
112
- `viewerId` is a required, nonempty identity supplied before host construction. The application
113
- handles missing authentication before mounting a host. Anonymous viewers are not modeled by this
114
- contract.
115
-
116
- `getCurrentUser({ signal })` is a required constructor callback returning a promise of a complete
117
- `BridgeUser` profile directly, without a success envelope or separate field readers. The shared host
118
- validates the profile and checks its ID against `viewerId`. The host invokes the callback for each
119
- `getCurrentUser` request. A rejected read, mismatched ID, or malformed profile returns a correlated
120
- `unknown_error`. Diagnostics stay in the host log. The host does not cache the profile.
121
-
122
- ## Metadata and configuration
123
-
124
- `customBlockHostBindingsSchema` and `customBlockHostDataSourceStateSchema` are host-only Valibot
125
- schemas exported with their types. They describe application configuration and source metadata
126
- separately from wire payloads.
127
-
128
- ```ts
129
- type CustomBlockHostBindings = {
130
- pages: Record<string, { pageId: string }>
131
- dataSources: Record<
132
- string,
133
- {
134
- dataSourceId: string
135
- propertyIdsByKey: Record<string, string | undefined>
136
- }
137
- >
138
- }
139
- ```
140
-
141
- The host validates configuration shape. `pages` maps page keys to IDs, but the runtime does not use
142
- those mappings to resolve page requests or include them in `init`. A `getDataSource` request reads
143
- metadata for one source key declared in the manifest and configured in `dataSources`. The host
144
- validates its property mappings before returning the binding. Metadata reads do not query rows.
145
-
146
- `CustomBlockHostDataSourceState` is `{ status: "unavailable" }` or
147
- `{ status: "available", dataSource: { dataSourceSchema, capabilities } }`. Capabilities contain
148
- `read`, `create`, `update`, and `archive`. The runtime does not send these flags to the sandbox. An
149
- available source's metadata remains available even when `capabilities.read` is false. The
150
- application handler remains responsible for enforcing viewer permissions on every operation.
151
-
152
- Missing sources and denied access both use `{ status: "unavailable" }`. A `getDataSource` request
153
- for an unavailable source returns `data_source_inaccessible` without source metadata. Invalid
154
- property mappings return a binding error.
155
-
156
- ## Queries and cancellation
157
-
158
- `subscribeToQuery(args: CustomBlockHostSubscribeToQueryArgs): void` receives `dataSourceId`,
159
- optional `filter`, `sorts`, and `archive_status`, plus `limit`, `signal`, `onSnapshot`, and
160
- `onError`. `archive_status` accepts `"active"`, `"archived"`, or `"all"`. See the
161
- [query semantics](../../bridge/protocol.md#data-sources) for archive selection defaults. A
162
- `CustomBlockHostQuerySnapshot` contains `items: BridgePage[]`, `hasMore`, and optional `limitClamp`.
163
- The application validates the limit and enforces its cap. The shared host validates filters and
164
- sorts against the bound schema before starting the observer. See
165
- [query limits](../../bridge/protocol.md#host-applied-query-limits) for the metadata contract.
166
-
167
- The signal controls the subscription lifetime, including asynchronous setup. The application checks
168
- for an already-aborted signal and cancels pending setup and observers on abort. Replacement,
169
- unsubscribe, invalidation, non-retryable errors, and shutdown abort the signal. Retryable errors can
170
- leave the observer active. Callbacks may run synchronously. The host ignores late callbacks after
171
- cancellation. There is no returned cleanup function or top-level query-unsubscribed callback. The
172
- SDK returns its own unsubscribe function, which sends the cancellation request to the host.
173
-
174
- `resize({ height })` requests an iframe height in CSS pixels. The application applies the height.
175
- The [lifecycle reference](lifecycle.md#callbacks) describes when to size and reveal the iframe.
176
-
177
- ## Updates
178
-
179
- `stop()`, `setTheme()`, `setContrastMode()`, `setParent()`, and `setContainingPage()` return `void`.
180
- `setBindings()` and `refreshDataSource()` return promises of `CustomBlockHostHandlerResult`.
181
-
182
- `setBindings(nextBindings)` validates and stores the configuration without reading metadata.
183
- `refreshDataSource({ dataSourceId })` requests a metadata refresh. Once the manifest is available,
184
- both methods clear all cached source metadata, abort pending operations and queries, and notify the
185
- sandbox with `dataSourcesInvalidated`. Neither method fetches replacement metadata. The next source
186
- read validates its property mappings.
187
-
188
- Invalidation affects every source, including unchanged bindings and sources other than the supplied
189
- `dataSourceId`. Before the manifest is available, both methods return success without invalidation.
190
- Malformed `setBindings()` input rejects with a schema validation error.
191
-
192
- A successful configuration change cancels outstanding one-shot host operations, including unrelated
193
- reads. A late completion returns non-retryable `host_state_changed`. A dispatched write may already
194
- have committed. Cancellation does not roll back a write. Stopping or failing the host aborts
195
- initialization, pending operations, metadata refreshes, and subscriptions before reporting its final
196
- status.