@notionhq/custom-blocks-dev-shell 0.1.115 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +92 -13
  3. package/THIRD_PARTY_LICENSES.md +133 -0
  4. package/dist/assets/index-Do-x8yIt.css +2 -0
  5. package/dist/assets/index-n0_PUieY.js +11 -0
  6. package/dist/index.html +2 -2
  7. package/dist-cli/cli/published-cli.js +8572 -51
  8. package/docs/bindings.md +17 -12
  9. package/docs/bridge/changelog.md +94 -0
  10. package/docs/bridge/protocol.md +239 -0
  11. package/docs/bridge/versioning.md +39 -0
  12. package/docs/data-sources.md +49 -36
  13. package/docs/host/README.md +193 -0
  14. package/docs/host/docs/compatibility.md +76 -0
  15. package/docs/host/docs/handlers.md +210 -0
  16. package/docs/host/docs/lifecycle.md +131 -0
  17. package/package.json +5 -3
  18. package/dist/assets/index-DXzPwq_J.js +0 -11
  19. package/dist/assets/index-E1j3FxAu.css +0 -2
  20. package/dist-cli/cli/binding-cli-flags.js +0 -33
  21. package/dist-cli/cli/binding-errors.js +0 -15
  22. package/dist-cli/cli/block-csp.js +0 -84
  23. package/dist-cli/cli/build-block-registry.js +0 -30
  24. package/dist-cli/cli/convert-values.js +0 -222
  25. package/dist-cli/cli/convert.js +0 -210
  26. package/dist-cli/cli/data-source-files.js +0 -6
  27. package/dist-cli/cli/data-sources.js +0 -114
  28. package/dist-cli/cli/dev-shell-launcher.js +0 -239
  29. package/dist-cli/cli/dev-shell-run.js +0 -72
  30. package/dist-cli/cli/errors.js +0 -12
  31. package/dist-cli/cli/launcher-bindings.js +0 -144
  32. package/dist-cli/cli/materialize.js +0 -105
  33. package/dist-cli/cli/ports.js +0 -20
  34. package/dist-cli/cli/prebuilt.js +0 -23
  35. package/dist-cli/cli/runtime-error-client.js +0 -52
  36. package/dist-cli/cli/serve-ui.js +0 -110
  37. package/dist-cli/cli/shared-server.js +0 -70
  38. package/dist-cli/cli/utils.js +0 -52
  39. package/dist-cli/cli/vite-block-server.js +0 -125
  40. package/dist-cli/cli/vite-middleware.js +0 -111
  41. package/dist-cli/cli/worker-manifest.js +0 -158
  42. package/dist-cli/protocol/contrast.d.ts +0 -4
  43. package/dist-cli/protocol/contrast.js +0 -3
  44. package/dist-cli/protocol/dataSources/dataSource.d.ts +0 -786
  45. package/dist-cli/protocol/dataSources/dataSource.js +0 -66
  46. package/dist-cli/protocol/dataSources/dataSourcePage.d.ts +0 -74
  47. package/dist-cli/protocol/dataSources/dataSourcePage.js +0 -15
  48. package/dist-cli/protocol/dataSources/dataSourceValue.d.ts +0 -66
  49. package/dist-cli/protocol/dataSources/dataSourceValue.js +0 -14
  50. package/dist-cli/protocol/dataSources/dateValue.d.ts +0 -157
  51. package/dist-cli/protocol/dataSources/dateValue.js +0 -61
  52. package/dist-cli/protocol/dataSources/errors.d.ts +0 -8
  53. package/dist-cli/protocol/dataSources/errors.js +0 -7
  54. package/dist-cli/protocol/dataSources/propertySchema.d.ts +0 -200
  55. package/dist-cli/protocol/dataSources/propertySchema.js +0 -174
  56. package/dist-cli/protocol/dataSources/recordPointer.d.ts +0 -9
  57. package/dist-cli/protocol/dataSources/recordPointer.js +0 -8
  58. package/dist-cli/protocol/dataSources/sortDirection.d.ts +0 -3
  59. package/dist-cli/protocol/dataSources/sortDirection.js +0 -2
  60. package/dist-cli/protocol/errors.d.ts +0 -12
  61. package/dist-cli/protocol/errors.js +0 -6
  62. package/dist-cli/protocol/ids.d.ts +0 -31
  63. package/dist-cli/protocol/ids.js +0 -26
  64. package/dist-cli/protocol/index.d.ts +0 -53
  65. package/dist-cli/protocol/index.js +0 -53
  66. package/dist-cli/protocol/manifest.d.ts +0 -67
  67. package/dist-cli/protocol/manifest.js +0 -36
  68. package/dist-cli/protocol/messages/connect.d.ts +0 -54
  69. package/dist-cli/protocol/messages/connect.js +0 -39
  70. package/dist-cli/protocol/messages/contrastModeChanged.d.ts +0 -7
  71. package/dist-cli/protocol/messages/contrastModeChanged.js +0 -7
  72. package/dist-cli/protocol/messages/createPage.d.ts +0 -290
  73. package/dist-cli/protocol/messages/createPage.js +0 -51
  74. package/dist-cli/protocol/messages/createPageResult.d.ts +0 -897
  75. package/dist-cli/protocol/messages/createPageResult.js +0 -43
  76. package/dist-cli/protocol/messages/currentUserChanged.d.ts +0 -18
  77. package/dist-cli/protocol/messages/currentUserChanged.js +0 -9
  78. package/dist-cli/protocol/messages/dataSourcesChanged.d.ts +0 -157
  79. package/dist-cli/protocol/messages/dataSourcesChanged.js +0 -13
  80. package/dist-cli/protocol/messages/getPage.d.ts +0 -902
  81. package/dist-cli/protocol/messages/getPage.js +0 -48
  82. package/dist-cli/protocol/messages/getUser.d.ts +0 -44
  83. package/dist-cli/protocol/messages/getUser.js +0 -32
  84. package/dist-cli/protocol/messages/hostToSandbox.d.ts +0 -4385
  85. package/dist-cli/protocol/messages/hostToSandbox.js +0 -48
  86. package/dist-cli/protocol/messages/incomingType.d.ts +0 -9
  87. package/dist-cli/protocol/messages/incomingType.js +0 -17
  88. package/dist-cli/protocol/messages/init.d.ts +0 -273
  89. package/dist-cli/protocol/messages/init.js +0 -57
  90. package/dist-cli/protocol/messages/initResult.d.ts +0 -37
  91. package/dist-cli/protocol/messages/initResult.js +0 -29
  92. package/dist-cli/protocol/messages/invalidHostMessage.d.ts +0 -14
  93. package/dist-cli/protocol/messages/invalidHostMessage.js +0 -13
  94. package/dist-cli/protocol/messages/invalidSandboxMessage.d.ts +0 -14
  95. package/dist-cli/protocol/messages/invalidSandboxMessage.js +0 -13
  96. package/dist-cli/protocol/messages/isInitHandshakeMessage.d.ts +0 -4
  97. package/dist-cli/protocol/messages/isInitHandshakeMessage.js +0 -11
  98. package/dist-cli/protocol/messages/listUsers.d.ts +0 -52
  99. package/dist-cli/protocol/messages/listUsers.js +0 -33
  100. package/dist-cli/protocol/messages/messagePayload.d.ts +0 -19
  101. package/dist-cli/protocol/messages/messagePayload.js +0 -1
  102. package/dist-cli/protocol/messages/openExternalUrl.d.ts +0 -32
  103. package/dist-cli/protocol/messages/openExternalUrl.js +0 -26
  104. package/dist-cli/protocol/messages/openPage.d.ts +0 -38
  105. package/dist-cli/protocol/messages/openPage.js +0 -34
  106. package/dist-cli/protocol/messages/pageChanged.d.ts +0 -32
  107. package/dist-cli/protocol/messages/pageChanged.js +0 -9
  108. package/dist-cli/protocol/messages/parentChanged.d.ts +0 -26
  109. package/dist-cli/protocol/messages/parentChanged.js +0 -9
  110. package/dist-cli/protocol/messages/queryDataSource.d.ts +0 -1446
  111. package/dist-cli/protocol/messages/queryDataSource.js +0 -252
  112. package/dist-cli/protocol/messages/queryDataSourceResult.d.ts +0 -686
  113. package/dist-cli/protocol/messages/queryDataSourceResult.js +0 -44
  114. package/dist-cli/protocol/messages/resize.d.ts +0 -11
  115. package/dist-cli/protocol/messages/resize.js +0 -10
  116. package/dist-cli/protocol/messages/sandboxToHost.d.ts +0 -1091
  117. package/dist-cli/protocol/messages/sandboxToHost.js +0 -33
  118. package/dist-cli/protocol/messages/themeChanged.d.ts +0 -10
  119. package/dist-cli/protocol/messages/themeChanged.js +0 -10
  120. package/dist-cli/protocol/messages/unsubscribeDataSourceQuery.d.ts +0 -10
  121. package/dist-cli/protocol/messages/unsubscribeDataSourceQuery.js +0 -9
  122. package/dist-cli/protocol/messages/updatePage.d.ts +0 -271
  123. package/dist-cli/protocol/messages/updatePage.js +0 -23
  124. package/dist-cli/protocol/messages/updatePageResult.d.ts +0 -895
  125. package/dist-cli/protocol/messages/updatePageResult.js +0 -41
  126. package/dist-cli/protocol/pages/page.d.ts +0 -1422
  127. package/dist-cli/protocol/pages/page.js +0 -318
  128. package/dist-cli/protocol/parent.d.ts +0 -32
  129. package/dist-cli/protocol/parent.js +0 -13
  130. package/dist-cli/protocol/protocolVersion.d.ts +0 -8
  131. package/dist-cli/protocol/protocolVersion.js +0 -11
  132. package/dist-cli/protocol/theme.d.ts +0 -3
  133. package/dist-cli/protocol/theme.js +0 -2
  134. package/dist-cli/protocol/users/user.d.ts +0 -32
  135. package/dist-cli/protocol/users/user.js +0 -20
  136. package/dist-cli/shared/block-registry.js +0 -28
  137. package/dist-cli/shared/data-source.js +0 -22
  138. package/dist-cli/shared/runtime-config.js +0 -10
  139. package/dist-cli/shared/sample-data-source.js +0 -12
@@ -0,0 +1,193 @@
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.
9
+
10
+ For configuration and lifecycle details, see [Initialization and lifecycle](docs/lifecycle.md).
11
+
12
+ Use `BridgeParent` from `@notionhq/custom-blocks-host/protocol` to construct parent references with
13
+ plain string IDs. The host validates the parent before sending it to the block.
14
+
15
+ Implement `CustomBlockHostHandlers` to connect the host to your application. Handlers return shared
16
+ bridge data using `CustomBlockHostResult`. Use `makeBridgePage` to construct a complete `BridgePage`
17
+ from your records. See [Return bridge data](docs/handlers.md#return-bridge-data).
18
+
19
+ ## Create a host
20
+
21
+ Install `@notionhq/custom-blocks-host` in your embedding application. Run this TypeScript through
22
+ your browser bundler after the document body exists.
23
+
24
+ This example embeds a block with no data sources and supplies fixed demo context. Replace
25
+ `https://blocks.example.com/hello` with your block's URL. Serve the block from a different origin
26
+ than the embedding application.
27
+
28
+ ```ts
29
+ import { createCustomBlockHost } from "@notionhq/custom-blocks-host"
30
+
31
+ function mountCustomBlock(container: HTMLElement, blockUrl: URL): () => void {
32
+ if (
33
+ !["http:", "https:"].includes(blockUrl.protocol) ||
34
+ blockUrl.origin === window.location.origin
35
+ ) {
36
+ throw new Error("The block needs an HTTP or HTTPS URL on a separate origin")
37
+ }
38
+
39
+ const wrapper = document.createElement("section")
40
+ const status = document.createElement("p")
41
+ status.setAttribute("role", "status")
42
+ status.textContent = "Loading block…"
43
+ const iframe = document.createElement("iframe")
44
+ iframe.title = "Hello custom block"
45
+ iframe.setAttribute("sandbox", "allow-scripts allow-same-origin")
46
+ iframe.allow = "clipboard-write"
47
+ iframe.style.width = "100%"
48
+ iframe.style.height = "300px"
49
+ iframe.style.visibility = "hidden"
50
+ wrapper.append(status, iframe)
51
+ container.append(wrapper)
52
+
53
+ function setHeight(height: number) {
54
+ iframe.style.height = `${Math.min(1200, Math.max(120, height))}px`
55
+ }
56
+
57
+ const host = createCustomBlockHost({
58
+ iframe,
59
+ sandboxUrl: blockUrl.href,
60
+ manifestSource: "host",
61
+ getPersistedManifest: async () => ({
62
+ status: "success",
63
+ manifest: { version: 1, dataSources: {} },
64
+ }),
65
+ prepareInitialState: async () => ({
66
+ status: "success",
67
+ initialState: {
68
+ theme: "light",
69
+ contrastMode: "standard",
70
+ blockId: "11111111-1111-4111-8111-111111111111",
71
+ parent: {
72
+ type: "page_id",
73
+ page_id: "22222222-2222-4222-8222-222222222222",
74
+ },
75
+ page: {
76
+ type: "page",
77
+ id: "22222222-2222-4222-8222-222222222222",
78
+ parent: { type: "workspace", workspace: true },
79
+ },
80
+ currentUser: {
81
+ object: "user",
82
+ id: "33333333-3333-4333-8333-333333333333",
83
+ name: "Demo viewer",
84
+ avatar_url: null,
85
+ type: "person",
86
+ person: { email: "viewer@example.com" },
87
+ },
88
+ dataSources: { bindings: {} },
89
+ },
90
+ }),
91
+ handlers: {
92
+ queryDataSource: () => ({
93
+ status: "error",
94
+ error: {
95
+ code: "unknown_data_source_key",
96
+ message: "This demo has no data sources.",
97
+ isRetryable: false,
98
+ },
99
+ }),
100
+ resize: message => setHeight(message.height),
101
+ },
102
+ onStatusChange: state => {
103
+ if (state.status === "initialized") {
104
+ setHeight(state.initialHeight ?? 300)
105
+ status.hidden = true
106
+ iframe.style.visibility = "visible"
107
+ } else if (state.status === "failed") {
108
+ iframe.style.visibility = "hidden"
109
+ status.hidden = false
110
+ status.textContent = `Block failed: ${state.error.code}`
111
+ }
112
+ },
113
+ onQueryUnsubscribed: undefined,
114
+ })
115
+
116
+ // The host must listen before the block starts its handshake.
117
+ iframe.src = blockUrl.href
118
+
119
+ return () => {
120
+ host.stop()
121
+ wrapper.remove()
122
+ }
123
+ }
124
+
125
+ const dispose = mountCustomBlock(document.body, new URL("https://blocks.example.com/hello"))
126
+ window.addEventListener("pagehide", dispose, { once: true })
127
+ ```
128
+
129
+ You should see “Loading block…” until the block completes initialization, then the block iframe. A
130
+ connection failure displays its error code. The example limits the iframe height to 120–1,200 CSS
131
+ pixels.
132
+
133
+ Call `dispose()` when your application removes the embed. To retry a failed connection or change the
134
+ block URL, dispose of the current embed and call `mountCustomBlock()` again.
135
+
136
+ For a production integration, replace the demo context and manifest with your application's values.
137
+ Supply data-source bindings and handlers for the APIs your block uses. Your application must enforce
138
+ permissions and record access.
139
+
140
+ To connect workspace data, see [Connect a data source](docs/handlers.md#connect-a-data-source).
141
+
142
+ ## Guides and reference
143
+
144
+ - [Initialization and lifecycle](docs/lifecycle.md): manifests, context, timeouts, live state, and
145
+ cleanup.
146
+ - [Handlers and data](docs/handlers.md): application handlers, data-source integration, queries, and
147
+ navigation.
148
+ - [Host compatibility](docs/compatibility.md): supported versions and response conversions.
149
+
150
+ The runtime handles the wire handshake and message validation. The shared protocol references cover
151
+ payload semantics, version rules, and contract history:
152
+
153
+ - [Wire protocol](../bridge/protocol.md)
154
+ - [Protocol versioning](../bridge/versioning.md)
155
+ - [Protocol changelog](../bridge/changelog.md)
156
+
157
+ ## Protocol schemas and types
158
+
159
+ The `/protocol` entrypoint exposes the protocol definitions bundled with this host release. It
160
+ provides message schemas and types, data shapes, IDs, error definitions, and protocol-version
161
+ constants.
162
+
163
+ Import these definitions through the host package to use the protocol version shipped with that
164
+ host:
165
+
166
+ ```ts
167
+ import {
168
+ sandboxToHostMessageSchema,
169
+ type SandboxToHostMessage,
170
+ } from "@notionhq/custom-blocks-host/protocol"
171
+ ```
172
+
173
+ `LATEST_BRIDGE_PROTOCOL_VERSION` identifies the latest bridge protocol version defined by the
174
+ bundled protocol.
175
+
176
+ Host APIs, configuration, handler results, and `*MessageInput` types are available from
177
+ `@notionhq/custom-blocks-host`.
178
+
179
+ These schemas validate wire payloads. Your application still enforces permissions.
180
+
181
+ ## Standalone browser module
182
+
183
+ `dist/browser.js` is one ES module with all dependencies. Use it when the browser must not fetch
184
+ additional modules, such as under an exact-URL Content Security Policy.
185
+
186
+ ### Native page icons
187
+
188
+ `CustomBlockHostPageIcon` accepts canonical native icon names from adapters. Adapters validate names
189
+ and colors before writing. The runtime validates response payloads.
190
+
191
+ Adapters must check URL-backed icon and cover writes against the block's network permissions before
192
+ mutating records. Notion permits the submitted HTTPS destination only when its origin is
193
+ allowlisted; that origin is trusted to redirect.
@@ -0,0 +1,76 @@
1
+ # Host compatibility
2
+
3
+ A host can update while deployed blocks keep older SDKs. The runtime accepts supported protocol
4
+ versions and converts current handler results to each block's declared contract. This reference
5
+ covers version admission, normalization, and the formats sent to older blocks. Protocol version
6
+ rules and release history are in the [versioning guide](../../bridge/versioning.md) and
7
+ [changelog](../../bridge/changelog.md).
8
+
9
+ ## Supported versions
10
+
11
+ The protocol subpath exports `LATEST_BRIDGE_PROTOCOL_VERSION` and
12
+ `MIN_HOST_SUPPORTED_BRIDGE_PROTOCOL_VERSION`. These constants define the package's latest known
13
+ protocol and runtime minimum. Embedders can raise the minimum but cannot enable retired versions.
14
+ The host admits future positive integer versions and validates them against known schemas. Admission
15
+ does not guarantee that future features work.
16
+
17
+ `sdkVersion` is analytics metadata. Compatibility behavior depends on the protocol version.
18
+
19
+ The current SDK declares protocol 10. The shared runtime minimum is 3. The dev shell uses the Worker
20
+ manifest in host mode and accepts the shared runtime's supported protocol versions. Protocols 7 and
21
+ 8 use the same page and query response formats. Protocol 8's local manifest declaration is selected
22
+ only in sandbox mode; host mode uses the persisted manifest. See the
23
+ [protocol 8 release entry](../../bridge/changelog.md#protocol-8-local-manifest-declarations).
24
+
25
+ The `minBridgeProtocolVersion` option defaults to the runtime minimum. Raising the option rejects
26
+ older SDKs for this embedding application. Lowering it cannot restore retired versions. Raising
27
+ `MIN_HOST_SUPPORTED_BRIDGE_PROTOCOL_VERSION` retires those versions across the runtime.
28
+
29
+ ## Host normalization
30
+
31
+ The host validates sandbox requests before dispatching them to handlers. Handlers use current data
32
+ shapes, and the host converts responses to the sandbox's declared protocol. Setters, query
33
+ refreshes, and handler responses use the same conversion. Unchanged messages and errors pass
34
+ through.
35
+
36
+ ## Current compatibility behavior
37
+
38
+ | Target | Query results | Page operation results | Binding schemas | Native icons |
39
+ | ------ | --------------------------------------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
40
+ | 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 |
41
+ | 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 |
42
+ | 6 | Unified name-keyed properties. Text fallback property objects become `null` | Same unified page format | Actual database schemas | External SVG URLs |
43
+ | 7–8 | Unified pages with typed text fallback properties | Same unified page format | Actual database schemas | External SVG URLs |
44
+ | 9+ | Unified pages with typed text fallback properties | Same unified page format | Actual database schemas | Native icon objects |
45
+
46
+ The synthetic metadata IDs are `created_time`, `last_edited_time`, `created_by`, and
47
+ `last_edited_by`. They retain metadata meaning if an actual property uses the same raw ID. This
48
+ matches the protocol 3–4 binding schema precedence. Host validation always uses the unmodified
49
+ actual database schema.
50
+
51
+ Release-specific compatibility limits are documented in the changelog entries for
52
+ [protocol 5 page context](../../bridge/changelog.md#protocol-5-unavailable-containing-page-context)
53
+ and
54
+ [protocol 6 text fallback properties](../../bridge/changelog.md#protocol-6-richer-fallback-properties).
55
+
56
+ ### Native page icons
57
+
58
+ Protocol 9 and later receive native icon objects. Protocols 3–8 receive external SVG URLs in page
59
+ operation results, and protocols 6–8 also receive them in query results. Protocols 3–5 use flat
60
+ query results without page appearance fields. Omitted native colors default to gray when producing
61
+ SVG URLs.
62
+
63
+ ### Unavailable containing-page context
64
+
65
+ Protocols 3–4 receive `context_unavailable` during initialization or stop when containing-page
66
+ context becomes unavailable. This concerns `init.page` and `pageChanged.page`, not a page
67
+ operation's `page_unavailable` error.
68
+
69
+ ### Protocol 3–5 metadata query semantics
70
+
71
+ Page creation and edit metadata is readable without corresponding database columns. Current page
72
+ objects carry these fields at the top level. Protocol 3–5 query adapters copy them into
73
+ `propertiesById` for older SDKs.
74
+
75
+ Filters and sorts require actual database properties in the bound schema. The host does not support
76
+ queries against synthetic metadata IDs without corresponding database properties.
@@ -0,0 +1,210 @@
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. This guide covers handler contracts, a
6
+ data-source example, refreshes, and external navigation.
7
+
8
+ The [dev shell](https://www.npmjs.com/package/@notionhq/custom-blocks-dev-shell) is a working host
9
+ implementation with local sample data. Use it as a reference for a larger integration. Production
10
+ hosts must provide their own permissions, data access, and persistence.
11
+
12
+ ## Handler contracts
13
+
14
+ `queryDataSource` is required. Other handlers are optional. A handler returns a result synchronously
15
+ or as a promise. Errors carry `{ code, message, isRetryable }`, with open string codes.
16
+
17
+ ### Return bridge data
18
+
19
+ Handlers return data in the bridge's shared types. Use bridge builders to construct complete objects
20
+ from application records.
21
+
22
+ The host validates result shapes, matches responses to requests, and converts responses for the
23
+ block's protocol version. Your application checks that records exist and that the viewer may perform
24
+ the requested operation.
25
+
26
+ Query filters and sorts are validated against the actual bound database schema before
27
+ `queryDataSource` runs. See the [wire reference](../../bridge/protocol.md#data-sources) for
28
+ query semantics.
29
+
30
+ For one-shot requests, a missing handler returns `unsupported_operation`. A handler that throws,
31
+ rejects, or returns a malformed result produces `unknown_error`. Exception details go to `onLog`;
32
+ the sandbox receives a generic error. Specific errors returned by handlers pass through unchanged.
33
+
34
+ ## Connect a data source
35
+
36
+ Connect an embedded block to an in-memory Tasks data source with one numeric Estimate property. This
37
+ walkthrough extends the [README's embed example](../README.md#create-a-host): declare the data
38
+ source, bind its keys to IDs, return a query result, and refresh that result after a value changes.
39
+
40
+ Keep the iframe, context, and lifecycle callbacks from the embed example. The block must declare the
41
+ same manifest and query `tasks` through the SDK's public APIs.
42
+
43
+ ### Declare and bind the data source
44
+
45
+ The manifest uses block-defined keys. Bindings connect those keys to actual data-source and property
46
+ IDs. Add these definitions before creating the host:
47
+
48
+ ```ts
49
+ import type {
50
+ CustomBlockHostDataSourcesPayload,
51
+ CustomBlockHostHandlers,
52
+ } from "@notionhq/custom-blocks-host"
53
+ import {
54
+ makeBridgePage,
55
+ type BridgeCustomBlockManifest,
56
+ type BridgePage,
57
+ } from "@notionhq/custom-blocks-host/protocol"
58
+
59
+ const tasksId = "44444444-4444-4444-8444-444444444444"
60
+
61
+ const manifest: BridgeCustomBlockManifest = {
62
+ version: 1,
63
+ dataSources: {
64
+ tasks: {
65
+ name: "Tasks",
66
+ properties: {
67
+ estimate: { name: "Estimate", type: "number" },
68
+ },
69
+ },
70
+ },
71
+ }
72
+
73
+ const taskBindings: CustomBlockHostDataSourcesPayload = {
74
+ bindings: {
75
+ tasks: {
76
+ collectionPointer: { table: "collection", id: tasksId },
77
+ collectionSchema: {
78
+ propertiesById: {
79
+ "estimate-id": { name: "Estimate", type: "number" },
80
+ },
81
+ },
82
+ propertyIdsByKey: { estimate: "estimate-id" },
83
+ },
84
+ },
85
+ }
86
+ ```
87
+
88
+ In the embed example, return `{ status: "success", manifest }` from `getPersistedManifest` and
89
+ replace `initialState.dataSources` with `taskBindings`. Here, `tasks` and `estimate` are semantic
90
+ keys; `tasksId` and `estimate-id` identify the bound data source and property.
91
+
92
+ ### Return query results
93
+
94
+ Add this handler and use it as the embed example's `handlers.queryDataSource`. Keep its existing
95
+ `resize` handler.
96
+
97
+ ```ts
98
+ let estimate = 3
99
+
100
+ const handlers: CustomBlockHostHandlers = {
101
+ queryDataSource: message => {
102
+ if (message.dataSourceId !== tasksId) {
103
+ return {
104
+ status: "error",
105
+ error: {
106
+ code: "unmapped_data_source",
107
+ message: "This data source is not available.",
108
+ isRetryable: false,
109
+ },
110
+ }
111
+ }
112
+
113
+ if (message.filter || message.sorts?.length) {
114
+ return {
115
+ status: "error",
116
+ error: {
117
+ code: "invalid_data_source_query",
118
+ message: "This demo supports only unfiltered, unsorted queries.",
119
+ isRetryable: false,
120
+ },
121
+ }
122
+ }
123
+
124
+ const items: BridgePage[] = [
125
+ makeBridgePage({
126
+ id: "55555555-5555-4555-8555-555555555555",
127
+ parent: { type: "data_source_id", data_source_id: tasksId },
128
+ is_archived: false,
129
+ in_trash: false,
130
+ properties: {
131
+ Estimate: { id: "estimate-id", type: "number", number: estimate },
132
+ },
133
+ }),
134
+ ]
135
+
136
+ return {
137
+ status: "success",
138
+ items: items.slice(0, message.limit),
139
+ hasMore: items.length > message.limit,
140
+ }
141
+ },
142
+ }
143
+ ```
144
+
145
+ The SDK resolves `tasks` to `tasksId` before the host receives the request. Result properties use
146
+ display names as keys (`Estimate`) and include their raw property IDs (`estimate-id`). The runtime
147
+ handles subscription IDs, validates results, and converts them for supported older SDKs.
148
+
149
+ This demo rejects filters and sorts rather than silently ignoring them. A production adapter must
150
+ enforce record access, execute the requested filter and sorts, and honor the result limit. See
151
+ [query semantics](../../bridge/protocol.md#data-sources).
152
+
153
+ ## Refresh active queries
154
+
155
+ After creating the host, update the in-memory value and notify active subscriptions:
156
+
157
+ ```ts
158
+ estimate = 5
159
+ host.refreshQuery({ dataSourceId: tasksId })
160
+ ```
161
+
162
+ If the block has an active query for Tasks, its next result contains an estimate of `5`. A query
163
+ started later also reads the updated value. The application triggers refreshes when its underlying
164
+ data changes; the runtime re-runs matching subscriptions. Call `host.stop()` when removing the
165
+ embed.
166
+
167
+ `refreshQuery()` re-runs active subscriptions for the supplied data-source ID with their existing
168
+ filter, sorts, and limit. Overlapping refreshes queue one follow-up query. The running query
169
+ delivers its result first. Unsubscribe, replacement, and stop discard queued work and suppress late
170
+ results. Non-retryable query errors end subscriptions. Retryable errors retain them.
171
+
172
+ ## Page and user operations
173
+
174
+ `createPage`, `getPage`, and `updatePage` connect page requests to your application's data access
175
+ and persistence. `getUser` and `listUsers` supply user data. Each handler returns a success payload
176
+ or an error. The runtime adds the request's correlation ID and sends the response. The application
177
+ enforces record access before reading or writing data.
178
+
179
+ `openPage` handles navigation to a Notion page. `resize` receives the block's requested height in
180
+ CSS pixels. The application owns navigation and iframe sizing.
181
+
182
+ ## External navigation
183
+
184
+ `openExternalUrl` receives an `AbortSignal` and an absolute HTTP or HTTPS URL without credentials.
185
+ The URL is limited to 2,048 JavaScript code units before and after normalization. The adapter
186
+ displays the exact URL, obtains approval, and navigates only after approval. It may apply further
187
+ restrictions. Dismiss pending confirmation UI when the signal aborts.
188
+
189
+ Each iframe permits one pending navigation. A different request receives `pending_navigation`. A
190
+ duplicate of the active request is ignored. Completed requests are forgotten, so later requests
191
+ require fresh approval. The runtime redacts the URL from `onLog` payloads and suppresses results
192
+ after stop.
193
+
194
+ ## Property binding
195
+
196
+ `getAutoBoundPropertyIdsByKey({ manifestProperties, propertySchemasById })` requires matching
197
+ property types and either an exact raw ID match or a display-name match after trimming and
198
+ lowercasing. IDs are not trimmed or case-folded. Exactly one candidate creates a binding. Zero or
199
+ multiple candidates leave the property unmapped. The result maps manifest property keys to database
200
+ property IDs. An ID match has no priority over a name match: if they identify different compatible
201
+ properties, the manifest property stays unmapped.
202
+
203
+ ## Date conversion and types
204
+
205
+ `toNotionDateValue()` converts `NotionDateInput` into the four `CustomBlockDateValue` variants,
206
+ including reminders. Invalid input throws `InvalidNotionDateError`.
207
+
208
+ The root exports host configuration, handlers, results, and `*MessageInput` types. Wire schemas,
209
+ message and page types, and constants such as `LATEST_BRIDGE_PROTOCOL_VERSION` use the
210
+ [protocol subpath](../README.md#protocol-schemas-and-types).
@@ -0,0 +1,131 @@
1
+ # Host initialization and lifecycle
2
+
3
+ The host prepares a block's manifest and context, completes initialization, and manages the
4
+ connection until the iframe is removed. This reference covers state preparation, timeouts,
5
+ callbacks, live state, and cleanup. Start with the [embed example](../README.md#create-a-host).
6
+
7
+ ## Manifest and initial state
8
+
9
+ Pass the full block URL as `sandboxUrl`. The host derives the origin used to authenticate incoming
10
+ messages and target outgoing messages. `CustomBlockManifestSource` selects the manifest:
11
+
12
+ | `manifestSource` | Manifest source |
13
+ | ---------------- | ---------------------------------------------------------------------------------------------------------- |
14
+ | `"host"` | The manifest returned by `getPersistedManifest({ signal })` |
15
+ | `"sandbox"` | The local declaration supplied in `connect.manifest`, subject to the [local URL policy](#local-block-urls) |
16
+
17
+ `getPersistedManifest` is required in both modes and starts when the host is created. It returns
18
+ `CustomBlockHostManifestResult`: either `{ status: "success", manifest }` or
19
+ `{ status: "error", error }`. It must not resolve to `null` or `undefined`. A definition that is
20
+ still loading keeps the promise pending; a failed load returns an error result. The host validates
21
+ the result and normalizes the manifest before calling `prepareInitialState`. Omitted `dataSources`
22
+ and each source's omitted `properties` default to `{}`.
23
+
24
+ The sandbox loads independently and sends `connect`. In sandbox mode, the SDK reads the manifest
25
+ from JSON metadata injected into the local block HTML by dev tooling. The host validates the
26
+ declaration in `connect`. The two sources do not wait for each other; only the selected result
27
+ determines initialization. Sandbox mode has no persisted fallback. The
28
+ [wire reference](../../bridge/protocol.md#initialization) describes the declaration and its
29
+ validation errors.
30
+
31
+ Once the selected manifest is ready, the host calls `prepareInitialState({ manifest, signal })`
32
+ once. Return `{ status: "success", initialState }` with context and data-source bindings, or
33
+ `{ status: "error", error }`. This callback also must not resolve to `null` or `undefined`. The host
34
+ validates its result. The prepared state omits the manifest; the host adds the selected manifest to
35
+ `init`. Host-mode preparation runs concurrently with connection setup. Sandbox-mode preparation
36
+ starts after `connect` supplies the declaration. The host sends `init` after preparation and a valid
37
+ connection succeed. A preparation failure is retained until the sandbox connects.
38
+
39
+ Errors from the selected manifest source retain their `code`, `message`, and `isRetryable`. A
40
+ missing sandbox declaration produces `manifest_unavailable`. A sandbox `manifest_invalid` error is
41
+ ignored in host mode because that mode uses the persisted manifest; other connect errors remain
42
+ fatal. Unexpected exceptions or invalid results from either callback produce `unknown_error`.
43
+ Diagnostics go to `onLog("warn", payload)`. Stopping aborts preparation and suppresses late results
44
+ without a cancellation warning.
45
+
46
+ ## Timeouts
47
+
48
+ | Option | Waits for | Default | Failure code |
49
+ | ----------------------- | ------------------------------------- | --------- | ----------------------- |
50
+ | `noConnectTimeoutMs` | `connect` after the first iframe load | 5 seconds | `no_connect` |
51
+ | `initialStateTimeoutMs` | State preparation after `connect` | 5 seconds | `initial_state_timeout` |
52
+ | `noInitResultTimeoutMs` | `initResult` after `init` | 5 seconds | `no_init_result` |
53
+
54
+ The SDK waits for `init` without its own timeout. Handshake failures abort preparation and suppress
55
+ late results. Manifest and state preparation providers must respect their `signal`.
56
+
57
+ ## Live state
58
+
59
+ `setTheme()`, `setContrastMode()`, `setParent()`, `setPage()`, `setDataSources()`, and
60
+ `setCurrentUser()` hold updates during initialization and send them after `initResult.success`. For
61
+ data-source query refreshes, see [Handlers and data](handlers.md#refresh-active-queries).
62
+
63
+ `setDataSources()` returns a synchronous `CustomBlockHostSetDataSourcesResult`. Success means local
64
+ acceptance only; it does not guarantee sandbox delivery or successful initialization. Existing
65
+ callers can ignore the return value. Malformed bindings can throw during schema parsing.
66
+
67
+ - `{ status: "success" }`: accepts the bindings into local state.
68
+ - `{ status: "error", error: { code, message, isRetryable } }`: logs a warning, keeps the last
69
+ accepted bindings and pending update, and sends no update. Codes are
70
+ `missing_data_source_binding`, `missing_property_binding`, and `invalid_property_binding`. All
71
+ have `isRetryable: false`; correct the bindings before resubmitting.
72
+
73
+ Pre-connect updates are checked against the selected manifest during initialization. Later updates
74
+ are validated once that manifest is available. Accepted updates wait for `initResult.success` before
75
+ sending; after failed initialization, they only change local state and do not restart it.
76
+
77
+ ## Callbacks
78
+
79
+ The required `onStatusChange(state)` callback receives the `CustomBlockHostStatus` union:
80
+
81
+ | Status | Behavior | Payload |
82
+ | ---------------------- | -------------------------------------------------------------- | ------------------------------------------------------ |
83
+ | `waitingForConnect` | The host is listening; reported synchronously during creation | None |
84
+ | `preparingInit` | The host accepted a connection and is preparing initialization | `localManifest`, `sdkVersion`, `bridgeProtocolVersion` |
85
+ | `waitingForInitResult` | Successful `init` was sent; acknowledgment is pending | None |
86
+ | `initialized` | The sandbox accepted initialization | `resolvedManifest`, optional `initialHeight` |
87
+ | `failed` | Initialization or runtime failed | `error` |
88
+ | `stopped` | The application explicitly disposed of the host | None |
89
+
90
+ `localManifest` is optional and comes only from a permitted local sandbox. It is available before
91
+ initialization completes, so an adapter can use its requirements to prepare bindings.
92
+ `resolvedManifest` is the selected declaration sent in `init`. Rejected connections can skip
93
+ intermediate statuses. Both `failed` and `stopped` are terminal; stopping a failed host releases
94
+ resources without replacing its failure status.
95
+
96
+ Connection failures contain `{ phase, source, code, message, isRetryable }`. The phase is `connect`,
97
+ `init`, `initResult`, or `runtime`. The source identifies who reported the failure. Failures can
98
+ occur after initialization succeeds.
99
+
100
+ At `initialized`, apply a supplied `initialHeight` in CSS pixels before revealing the iframe. If the
101
+ height is absent, use your application's default size. The `resize` handler applies later height
102
+ changes. Reveal, sizing, and failure UI belong to the embedding application.
103
+
104
+ | Other callback | Behavior |
105
+ | ------------------------------------- | -------------------------------------------------------------------------------------------- |
106
+ | `onQueryUnsubscribed(subscriptionId)` | Runs once when a subscription ends through unsubscribe, replacement, terminal error, or stop |
107
+ | `onLog(direction, payload)` | Receives bridge messages and warnings |
108
+
109
+ ## Iframe lifetime
110
+
111
+ Each host handles one handshake. Create a new host and iframe to retry or replace the block URL. The
112
+ [wire reference](../../bridge/protocol.md#initialization) defines handshake and
113
+ malformed-message behavior.
114
+
115
+ The first observed iframe `load` is allowed. A second load stops the host and reports retryable
116
+ `iframe_reloaded`. Load-event cleanup does not isolate documents before that event. A replacement
117
+ document at the same origin can receive messages and invoke handlers until the host stops.
118
+
119
+ `stop()` removes listeners, cancels preparation, clears timers, ends subscriptions, and suppresses
120
+ pending responses. Call it when removing the iframe.
121
+
122
+ ## Local block URLs
123
+
124
+ `isAllowedLocalPreviewUrl({ url, hostOrigin })` accepts HTTP or HTTPS URLs on `localhost`,
125
+ `*.localhost`, or `127.0.0.1` without credentials. It rejects the embedding page's origin.
126
+ `hostOrigin` must be nonempty. Pass the embedding page's serialized origin.
127
+
128
+ The protocol helper `isLocalBlockServerUrl(url)` checks the server URL without requiring origin
129
+ isolation. The host adds the embedding-origin restriction. `manifestSource: "sandbox"` enforces this
130
+ policy before the host starts. An invalid sandbox-mode URL throws `CustomBlockInitializationError`
131
+ with code `invalid_local_preview_url`.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@notionhq/custom-blocks-dev-shell",
3
- "version": "0.1.115",
4
- "description": "Local preview shell for Notion custom block workers.",
3
+ "version": "0.2.0",
4
+ "description": "Local development shell for Notion custom block workers.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "bin": {
@@ -16,7 +16,9 @@
16
16
  "dist",
17
17
  "dist-cli",
18
18
  "docs",
19
- "README.md"
19
+ "README.md",
20
+ "LICENSE",
21
+ "THIRD_PARTY_LICENSES.md"
20
22
  ],
21
23
  "dependencies": {
22
24
  "react": "^19.3.1",