@notionhq/custom-blocks 0.6.0 → 0.7.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 (191) hide show
  1. package/README.md +32 -18
  2. package/dist/bridge/SandboxBridge.d.ts +7 -8
  3. package/dist/bridge/SandboxBridge.d.ts.map +1 -1
  4. package/dist/bridge/SandboxBridge.js +39 -114
  5. package/dist/bridge/applyHostStateMessage.d.ts.map +1 -1
  6. package/dist/bridge/createBrowserSandboxBridge.d.ts +3 -0
  7. package/dist/bridge/createBrowserSandboxBridge.d.ts.map +1 -0
  8. package/dist/bridge/createBrowserSandboxBridge.js +54 -0
  9. package/dist/bridge/getBridge.d.ts +1 -1
  10. package/dist/bridge/getBridge.d.ts.map +1 -1
  11. package/dist/bridge/getBridge.js +2 -2
  12. package/dist/bridge/getInitializedHostState.d.ts.map +1 -1
  13. package/dist/bridge/hostState.d.ts +2 -2
  14. package/dist/bridge/hostState.d.ts.map +1 -1
  15. package/dist/bridge/initialization/SandboxInitialization.d.ts +6 -0
  16. package/dist/bridge/initialization/SandboxInitialization.d.ts.map +1 -1
  17. package/dist/bridge/initialization/SandboxInitialization.js +13 -10
  18. package/dist/bridge/messageInterceptor.d.ts.map +1 -1
  19. package/dist/bridge/requests.d.ts.map +1 -1
  20. package/dist/bridge/sandboxEnvironment.d.ts +30 -0
  21. package/dist/bridge/sandboxEnvironment.d.ts.map +1 -0
  22. package/dist/bridge/sandboxEnvironment.js +1 -0
  23. package/dist/bridge/subscribeToHostStateField.d.ts.map +1 -1
  24. package/dist/bridge.d.ts.map +1 -1
  25. package/dist/data-sources.d.ts.map +1 -1
  26. package/dist/dataSources/NotionDataSource.d.ts.map +1 -1
  27. package/dist/dataSources/bridge/DataSourceCache.d.ts +18 -0
  28. package/dist/dataSources/bridge/DataSourceCache.d.ts.map +1 -0
  29. package/dist/dataSources/bridge/DataSourceCache.js +75 -0
  30. package/dist/dataSources/bridge/applyDataSourceBindings.d.ts.map +1 -1
  31. package/dist/dataSources/bridge/makeDataSourceReadResponseSchema.d.ts.map +1 -1
  32. package/dist/dataSources/bridge/resolveDataSourceQuery.d.ts.map +1 -1
  33. package/dist/dataSources/bridge/resolveDataSources.d.ts.map +1 -1
  34. package/dist/dataSources/bridge/resolveSorts.d.ts.map +1 -1
  35. package/dist/dataSources/bridge/reuseDataSourcesForUnchangedBindings.d.ts +0 -3
  36. package/dist/dataSources/bridge/reuseDataSourcesForUnchangedBindings.d.ts.map +1 -1
  37. package/dist/dataSources/bridge/reuseDataSourcesForUnchangedBindings.js +2 -5
  38. package/dist/dataSources/dataSourceInaccessibleError.d.ts.map +1 -1
  39. package/dist/dataSources/dataSourceState.d.ts.map +1 -1
  40. package/dist/dataSources/ensureDataSource.d.ts.map +1 -1
  41. package/dist/dataSources/filters/resolveFilter.d.ts.map +1 -1
  42. package/dist/dataSources/filters/types.d.ts.map +1 -1
  43. package/dist/dataSources/getDataSourcePage.d.ts.map +1 -1
  44. package/dist/dataSources/observeDataSource.d.ts.map +1 -1
  45. package/dist/dataSources/properties/resolvePropertyAddress.d.ts.map +1 -1
  46. package/dist/dataSources/properties/resolvePropertyWriteMapForDataSource.d.ts.map +1 -1
  47. package/dist/dataSources/properties/resolvePropertyWriteMapForDataSource.js +2 -2
  48. package/dist/dataSources/resolvePageDataSource.d.ts.map +1 -1
  49. package/dist/dataSources/subscribeToDataSource.d.ts.map +1 -1
  50. package/dist/dataSources/types.d.ts.map +1 -1
  51. package/dist/files/files.d.ts +1 -1
  52. package/dist/files/files.d.ts.map +1 -1
  53. package/dist/files/icons.d.ts.map +1 -1
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/initialization/NotInIframeError.d.ts.map +1 -1
  56. package/dist/initialization/initCustomBlock.d.ts.map +1 -1
  57. package/dist/initialization/notifyReady.d.ts.map +1 -1
  58. package/dist/initialization/react/useCustomBlockInit.d.ts.map +1 -1
  59. package/dist/initialization/resolveInitialState.d.ts.map +1 -1
  60. package/dist/initialization/types.d.ts.map +1 -1
  61. package/dist/layout/autoResize.d.ts.map +1 -1
  62. package/dist/layout/getInitialContentHeight.d.ts.map +1 -1
  63. package/dist/location/getContainingPage.d.ts.map +1 -1
  64. package/dist/location/getInstance.d.ts.map +1 -1
  65. package/dist/location/getParent.d.ts.map +1 -1
  66. package/dist/location/mapContainingPage.d.ts +2 -2
  67. package/dist/location/mapContainingPage.d.ts.map +1 -1
  68. package/dist/location/mapParent.d.ts.map +1 -1
  69. package/dist/location/subscribeToContainingPage.d.ts.map +1 -1
  70. package/dist/location/subscribeToParent.d.ts.map +1 -1
  71. package/dist/location/types.d.ts.map +1 -1
  72. package/dist/manifest/getManifest.d.ts.map +1 -1
  73. package/dist/manifest/readLocalManifest.d.ts.map +1 -1
  74. package/dist/manifest/types.d.ts.map +1 -1
  75. package/dist/navigation/openExternalUrl.d.ts.map +1 -1
  76. package/dist/navigation/types.d.ts.map +1 -1
  77. package/dist/navigation.d.ts.map +1 -1
  78. package/dist/pages/NotionPage.d.ts.map +1 -1
  79. package/dist/pages/bridge/buildCreatePageRequest.d.ts.map +1 -1
  80. package/dist/pages/bridge/getPageForDataSource.d.ts.map +1 -1
  81. package/dist/pages/bridge/resolveCreatePageDestination.d.ts.map +1 -1
  82. package/dist/pages/bridge/sendCreatePageRequest.d.ts.map +1 -1
  83. package/dist/pages/bridge/toNotionPageFromBridgePage.d.ts.map +1 -1
  84. package/dist/pages/bridge/toNotionPagePropertyFromBridgeProperty.d.ts +2 -2
  85. package/dist/pages/bridge/toNotionPagePropertyFromBridgeProperty.d.ts.map +1 -1
  86. package/dist/pages/bridge/updatePage.d.ts.map +1 -1
  87. package/dist/pages/createPage.d.ts.map +1 -1
  88. package/dist/pages/getPage.d.ts.map +1 -1
  89. package/dist/pages/identityBlockKey.d.ts.map +1 -1
  90. package/dist/pages/identityPageKey.d.ts.map +1 -1
  91. package/dist/pages/openPage.d.ts.map +1 -1
  92. package/dist/pages/parent.d.ts.map +1 -1
  93. package/dist/pages/types.d.ts +5 -3
  94. package/dist/pages/types.d.ts.map +1 -1
  95. package/dist/pages.d.ts.map +1 -1
  96. package/dist/preferences/backgroundColors.d.ts.map +1 -1
  97. package/dist/preferences/getContrastMode.d.ts.map +1 -1
  98. package/dist/preferences/getTheme.d.ts.map +1 -1
  99. package/dist/preferences/react/useContrastMode.d.ts.map +1 -1
  100. package/dist/preferences/react/useTheme.d.ts.map +1 -1
  101. package/dist/preferences/subscribeToContrastMode.d.ts.map +1 -1
  102. package/dist/preferences/subscribeToTheme.d.ts.map +1 -1
  103. package/dist/preferences/syncDocumentAppearance.d.ts +1 -1
  104. package/dist/preferences/syncDocumentAppearance.d.ts.map +1 -1
  105. package/dist/preferences/syncDocumentAppearance.js +2 -1
  106. package/dist/preferences.d.ts.map +1 -1
  107. package/dist/protocol/compatibility/protocol12/hostToSandbox.d.ts +3356 -0
  108. package/dist/protocol/compatibility/protocol12/hostToSandbox.js +38 -0
  109. package/dist/protocol/compatibility/protocol12/page.d.ts +296 -0
  110. package/dist/protocol/compatibility/protocol12/page.js +7 -0
  111. package/dist/protocol/context/containingPage.d.ts +4 -2
  112. package/dist/protocol/context/containingPage.js +1 -1
  113. package/dist/protocol/context/messages/pageChanged.js +2 -2
  114. package/dist/protocol/dataSources/areDataSourceBindingsEqual.d.ts +3 -0
  115. package/dist/protocol/dataSources/areDataSourceBindingsEqual.js +26 -0
  116. package/dist/protocol/dataSources/messages/queryDataSource.d.ts +24 -19
  117. package/dist/protocol/dataSources/messages/queryDataSource.js +2 -0
  118. package/dist/protocol/files.d.ts +18 -0
  119. package/dist/protocol/files.js +9 -0
  120. package/dist/protocol/messages/hostToSandbox.d.ts +2200 -68
  121. package/dist/protocol/messages/hostToSandbox.js +6 -2
  122. package/dist/protocol/messages/sandboxToHost.d.ts +51 -51
  123. package/dist/protocol/pages/bridgePage.d.ts +20 -17
  124. package/dist/protocol/pages/messages/createPage.d.ts +88 -85
  125. package/dist/protocol/pages/messages/getPage.d.ts +24 -19
  126. package/dist/protocol/pages/messages/getPage.js +2 -0
  127. package/dist/protocol/pages/messages/updatePage.d.ts +37 -34
  128. package/dist/protocol/pages/properties/bridgePagePropertyMaps.d.ts +37 -34
  129. package/dist/protocol/pages/properties/bridgePagePropertyMaps.js +3 -3
  130. package/dist/protocol/pages/properties/bridgePagePropertyValue.d.ts +236 -2
  131. package/dist/protocol/pages/properties/bridgePagePropertyValue.js +20 -7
  132. package/dist/protocol/utils/errors.d.ts +6 -0
  133. package/dist/protocol/utils/errors.js +8 -0
  134. package/dist/protocol/utils/protocolVersion.d.ts +4 -2
  135. package/dist/protocol/utils/protocolVersion.js +4 -2
  136. package/dist/react/InitializationErrorDetails.d.ts.map +1 -1
  137. package/dist/react/MissingHostCommand.d.ts.map +1 -1
  138. package/dist/react/MissingHostScreen.d.ts.map +1 -1
  139. package/dist/react/NotionCustomBlock.d.ts.map +1 -1
  140. package/dist/react/index.d.ts +0 -2
  141. package/dist/react/index.d.ts.map +1 -1
  142. package/dist/react/index.js +0 -1
  143. package/dist/react/useAsyncRead.d.ts.map +1 -1
  144. package/dist/react/useContainingPage.d.ts.map +1 -1
  145. package/dist/react/useLiveLocationRead.d.ts.map +1 -1
  146. package/dist/react/usePage.d.ts.map +1 -1
  147. package/dist/react/useParent.d.ts.map +1 -1
  148. package/dist/react/useQuerySubscription.d.ts.map +1 -1
  149. package/dist/react/useUserFields.d.ts.map +1 -1
  150. package/dist/react/useViewer.d.ts.map +1 -1
  151. package/dist/styles/scrollbars.css +18 -0
  152. package/dist/users/NotionUser.d.ts.map +1 -1
  153. package/dist/users/bridge/toNotionUserDataFromBridgeUser.d.ts.map +1 -1
  154. package/dist/users/getUser.d.ts.map +1 -1
  155. package/dist/users/getViewer.d.ts.map +1 -1
  156. package/dist/users/listUsers.d.ts.map +1 -1
  157. package/dist/users/types.d.ts.map +1 -1
  158. package/dist/users.d.ts.map +1 -1
  159. package/dist/utils/makeUuid.d.ts.map +1 -1
  160. package/dist/utils/notifyListener.d.ts.map +1 -1
  161. package/dist/utils/typeUtils.d.ts.map +1 -1
  162. package/dist/utils/unreachable.d.ts.map +1 -1
  163. package/dist/utils/version.d.ts.map +1 -1
  164. package/dist/utils/version.js +1 -1
  165. package/docs/block-location.md +22 -9
  166. package/docs/deployment.md +5 -11
  167. package/docs/errors.md +4 -0
  168. package/docs/grants.md +7 -2
  169. package/docs/local-development.md +39 -0
  170. package/docs/pages.md +97 -62
  171. package/package.json +2 -1
  172. package/src/bridge/SandboxBridge.ts +49 -144
  173. package/src/bridge/createBrowserSandboxBridge.ts +64 -0
  174. package/src/bridge/getBridge.ts +3 -2
  175. package/src/bridge/hostState.ts +2 -2
  176. package/src/bridge/initialization/SandboxInitialization.ts +24 -10
  177. package/src/bridge/sandboxEnvironment.ts +38 -0
  178. package/src/dataSources/bridge/DataSourceCache.ts +94 -0
  179. package/src/dataSources/bridge/reuseDataSourcesForUnchangedBindings.ts +5 -5
  180. package/src/dataSources/properties/resolvePropertyWriteMapForDataSource.ts +2 -2
  181. package/src/files/files.ts +1 -1
  182. package/src/location/mapContainingPage.ts +2 -2
  183. package/src/pages/bridge/toNotionPagePropertyFromBridgeProperty.ts +2 -2
  184. package/src/pages/types.ts +9 -3
  185. package/src/preferences/syncDocumentAppearance.ts +2 -1
  186. package/src/react/index.ts +0 -2
  187. package/src/styles/scrollbars.css +18 -0
  188. package/dist/react/NotionTokenScope.d.ts +0 -10
  189. package/dist/react/NotionTokenScope.d.ts.map +0 -1
  190. package/dist/react/NotionTokenScope.js +0 -12
  191. package/src/react/NotionTokenScope.tsx +0 -26
@@ -1,5 +1,5 @@
1
+ import { hostToSandboxMessageForProtocol12Schema } from "@notionhq/custom-blocks-protocol/compatibility/protocol12/hostToSandbox.js"
1
2
  import { DEFAULT_CONTRAST_MODE } from "@notionhq/custom-blocks-protocol/context/contrast.js"
2
- import type { BridgeDataSourceBindings } from "@notionhq/custom-blocks-protocol/dataSources/bridgeDataSourceBindings.js"
3
3
  import type {
4
4
  CustomBlockQueryDataSourceErrorInfo,
5
5
  QueryDataSourceResultMessage,
@@ -11,19 +11,15 @@ import { readIncomingType } from "@notionhq/custom-blocks-protocol/messages/inco
11
11
  import type { InvalidHostMessage } from "@notionhq/custom-blocks-protocol/messages/invalidHostMessage.js"
12
12
  import type { SandboxToHostMessage } from "@notionhq/custom-blocks-protocol/messages/sandboxToHost.js"
13
13
  import type { CustomBlockErrorInfo } from "@notionhq/custom-blocks-protocol/utils/errors.js"
14
-
14
+ import { PROTOCOL_VERSION_12_MINIMAL_INIT } from "@notionhq/custom-blocks-protocol/utils/protocolVersion.js"
15
15
  import { readRequestId } from "@notionhq/custom-blocks-protocol/utils/readRequestId.js"
16
16
  import { readSubscriptionId } from "@notionhq/custom-blocks-protocol/utils/readSubscriptionId.js"
17
17
  import * as v from "valibot"
18
- import { applyDataSourceBindings } from "../dataSources/bridge/applyDataSourceBindings.js"
19
- import { makeDataSourceReadResponseSchema } from "../dataSources/bridge/makeDataSourceReadResponseSchema.js"
18
+ import { DataSourceCache } from "../dataSources/bridge/DataSourceCache.js"
20
19
  import type { DataSourceReadResult } from "../dataSources/types.js"
21
20
  import type { NotifyReadyResult } from "../initialization/notifyReady.js"
22
21
  import { resolveInitialState } from "../initialization/resolveInitialState.js"
23
22
  import type { InitCustomBlockOptions } from "../initialization/types.js"
24
- import { autoResize } from "../layout/autoResize.js"
25
- import { getInitialContentHeight } from "../layout/getInitialContentHeight.js"
26
- import { syncDocumentAppearance } from "../preferences/syncDocumentAppearance.js"
27
23
  import { notifyListener } from "../utils/notifyListener.js"
28
24
  import { unreachable } from "../utils/unreachable.js"
29
25
  import { applyHostStateMessage } from "./applyHostStateMessage.js"
@@ -36,8 +32,7 @@ import {
36
32
  Requests,
37
33
  type ResponseSchema,
38
34
  } from "./requests.js"
39
-
40
- const AUTOMATIC_READINESS_FALLBACK_MS = 100
35
+ import type { SandboxEnvironment } from "./sandboxEnvironment.js"
41
36
 
42
37
  export class SandboxBridge {
43
38
  private hostState: CustomBlockHostState = {
@@ -53,30 +48,28 @@ export class SandboxBridge {
53
48
  >()
54
49
  private messageInterceptors = new Set<MessageInterceptor>()
55
50
  private readonly requests = new Requests(message => this.postToHost(message))
56
- private latestDataSourceBindings: BridgeDataSourceBindings = {}
57
- private readonly pendingDataSourceReads = new Map<
58
- string,
59
- {
60
- generation: number
61
- result: Promise<DataSourceReadResult>
62
- }
63
- >()
64
- private dataSourceReadGeneration = 0
51
+ private readonly dataSources = new DataSourceCache(
52
+ this.requests,
53
+ () => this.hostState,
54
+ state => this.commitHostState(state),
55
+ )
65
56
  private readonly locationLifetime = new AbortController()
66
- private isListening = false
57
+ private stopListening: (() => void) | undefined
67
58
  private isDisposed = false
68
59
  private readonly initialization: SandboxInitialization
69
60
  private automaticReadinessCleanup: (() => void) | undefined
70
61
  private resizeObserverCleanup: (() => void) | undefined
71
62
 
72
- constructor() {
63
+ constructor(private readonly environment: SandboxEnvironment) {
73
64
  this.initialization = new SandboxInitialization({
74
65
  start: () => this.startListening(),
66
+ isEmbedded: () => this.environment.transport.isEmbedded(),
67
+ readLocalManifest: () => this.environment.document.readLocalManifest(),
75
68
  post: message => this.sendToHost(message),
76
69
  apply: (message, protocolVersion) =>
77
70
  this.applyInit(message, protocolVersion),
78
71
  getState: () => this.hostState,
79
- getInitialHeight: getInitialContentHeight,
72
+ getInitialHeight: () => this.environment.document.getInitialHeight(),
80
73
  })
81
74
  }
82
75
 
@@ -96,27 +89,26 @@ export class SandboxBridge {
96
89
  */
97
90
  dispose() {
98
91
  this.isDisposed = true
99
- this.automaticReadinessCleanup?.()
92
+ this.cancelAutomaticReadiness()
100
93
  this.locationLifetime.abort()
101
- this.dataSourceReadGeneration++
94
+ this.dataSources.invalidate()
102
95
  this.resizeObserverCleanup?.()
103
96
  this.resizeObserverCleanup = undefined
104
97
  this.requests.disposeAll()
105
98
  this.initialization.dispose()
106
- if (this.isListening) {
107
- window.removeEventListener("message", this.handleMessage)
108
- this.isListening = false
109
- }
99
+ this.stopListening?.()
100
+ this.stopListening = undefined
110
101
  this.listeners.clear()
111
102
  this.dataSourceQueryListeners.clear()
112
103
  }
113
104
 
114
- startListening() {
115
- if (this.isDisposed || this.isListening || typeof window === "undefined") {
105
+ private startListening() {
106
+ if (this.isDisposed || this.stopListening !== undefined) {
116
107
  return
117
108
  }
118
- this.isListening = true
119
- window.addEventListener("message", this.handleMessage)
109
+ this.stopListening = this.environment.transport.subscribe(message =>
110
+ this.receiveMessage(message),
111
+ )
120
112
  }
121
113
 
122
114
  registerMessageInterceptor(interceptor: MessageInterceptor): () => void {
@@ -136,14 +128,7 @@ export class SandboxBridge {
136
128
  return
137
129
  }
138
130
  }
139
- window.parent.postMessage(message, "*")
140
- }
141
-
142
- private handleMessage = (event: MessageEvent) => {
143
- if (event.source !== window.parent) {
144
- return
145
- }
146
- this.receiveMessage(event.data)
131
+ this.environment.transport.send(message)
147
132
  }
148
133
 
149
134
  private receiveMessage(data: unknown) {
@@ -151,7 +136,11 @@ export class SandboxBridge {
151
136
  return
152
137
  }
153
138
 
154
- const parsed = v.safeParse(hostToSandboxMessageSchema, data)
139
+ // Protocol 12 uses the previous page schema, which has no unavailable Files entry.
140
+ const parsed =
141
+ this.initialization.protocolVersion === PROTOCOL_VERSION_12_MINIMAL_INIT
142
+ ? v.safeParse(hostToSandboxMessageForProtocol12Schema, data)
143
+ : v.safeParse(hostToSandboxMessageSchema, data)
155
144
  if (!parsed.success) {
156
145
  console.warn(
157
146
  "[custom-blocks-sdk] ignoring malformed host message",
@@ -289,8 +278,7 @@ export class SandboxBridge {
289
278
  return
290
279
 
291
280
  case "dataSourcesInvalidated": {
292
- this.dataSourceReadGeneration++
293
- this.latestDataSourceBindings = {}
281
+ this.dataSources.invalidate()
294
282
  this.commitHostState({ ...hostState, dataSources: [] })
295
283
  return
296
284
  }
@@ -326,7 +314,7 @@ export class SandboxBridge {
326
314
  previous.theme !== state.theme ||
327
315
  previous.contrastMode !== state.contrastMode
328
316
  ) {
329
- syncDocumentAppearance(state)
317
+ this.environment.document.applyAppearance(state)
330
318
  }
331
319
  for (const listener of this.listeners) {
332
320
  notifyListener(listener)
@@ -362,21 +350,15 @@ export class SandboxBridge {
362
350
 
363
351
  notifyReady(): NotifyReadyResult {
364
352
  const result = this.initialization.notifyReady()
365
- if (result.status === "success") {
366
- this.automaticReadinessCleanup?.()
353
+ if (result.status === "error") {
354
+ return result
367
355
  }
368
- if (
369
- result.status === "success" &&
370
- this.resizeObserverCleanup === undefined
371
- ) {
356
+ this.cancelAutomaticReadiness()
357
+ if (this.resizeObserverCleanup === undefined) {
372
358
  try {
373
- this.resizeObserverCleanup = autoResize({
374
- target:
375
- typeof document === "undefined"
376
- ? null
377
- : document.getElementById("root"),
378
- onResize: height => this.postToHost({ type: "resize", height }),
379
- })
359
+ this.resizeObserverCleanup = this.environment.document.observeHeight(
360
+ height => this.postToHost({ type: "resize", height }),
361
+ )
380
362
  } catch (error) {
381
363
  return {
382
364
  status: "error",
@@ -399,7 +381,7 @@ export class SandboxBridge {
399
381
  return
400
382
  }
401
383
  const reportReady = () => {
402
- this.automaticReadinessCleanup?.()
384
+ this.cancelAutomaticReadiness()
403
385
  const result = this.notifyReady()
404
386
  if (result.status === "error") {
405
387
  console.error(
@@ -408,26 +390,20 @@ export class SandboxBridge {
408
390
  )
409
391
  }
410
392
  }
411
- // Hidden iframes may not receive animation frames.
412
- const timeout = window.setTimeout(
413
- reportReady,
414
- AUTOMATIC_READINESS_FALLBACK_MS,
415
- )
416
- const frame = window.requestAnimationFrame?.(reportReady)
417
- this.automaticReadinessCleanup = () => {
418
- window.clearTimeout(timeout)
419
- if (frame !== undefined) {
420
- window.cancelAnimationFrame(frame)
421
- }
422
- this.automaticReadinessCleanup = undefined
423
- }
393
+ this.automaticReadinessCleanup =
394
+ this.environment.document.scheduleReady(reportReady)
395
+ }
396
+
397
+ private cancelAutomaticReadiness() {
398
+ const cancel = this.automaticReadinessCleanup
399
+ this.automaticReadinessCleanup = undefined
400
+ cancel?.()
424
401
  }
425
402
 
426
403
  private applyInit(
427
404
  message: SetupInitMessage,
428
405
  protocolVersion: number,
429
406
  ): CustomBlockInitResultErrorInfo | undefined {
430
- this.latestDataSourceBindings = {}
431
407
  const state = resolveInitialState(message, protocolVersion)
432
408
  this.commitHostState(state)
433
409
  return undefined
@@ -441,7 +417,7 @@ export class SandboxBridge {
441
417
  }
442
418
 
443
419
  getDataSourceReadGeneration(): number {
444
- return this.dataSourceReadGeneration
420
+ return this.dataSources.getGeneration()
445
421
  }
446
422
 
447
423
  async readParent() {
@@ -545,67 +521,7 @@ export class SandboxBridge {
545
521
  if (setup.status === "error") {
546
522
  return setup
547
523
  }
548
- const generation = this.dataSourceReadGeneration
549
- const existing = this.pendingDataSourceReads.get(key)
550
- if (existing?.generation === generation) {
551
- return existing.result
552
- }
553
- const pending = {
554
- generation,
555
- result: this.requestDataSource(key, generation),
556
- }
557
- this.pendingDataSourceReads.set(key, pending)
558
- try {
559
- return await pending.result
560
- } finally {
561
- if (this.pendingDataSourceReads.get(key) === pending) {
562
- this.pendingDataSourceReads.delete(key)
563
- }
564
- }
565
- }
566
-
567
- private async requestDataSource(
568
- key: string,
569
- generation: number,
570
- ): Promise<DataSourceReadResult> {
571
- const initialState = this.hostState
572
- if (initialState.status !== "initialized") {
573
- throw new Error("Source read started without initialized state.")
574
- }
575
- const result = await this.request(
576
- { type: "getDataSource", key },
577
- makeDataSourceReadResponseSchema(initialState.manifest, key),
578
- )
579
- if (result.status === "error") {
580
- return result
581
- }
582
- if (generation !== this.dataSourceReadGeneration || this.isDisposed) {
583
- return staleReadError()
584
- }
585
- const state = this.hostState
586
- if (state.status !== "initialized") {
587
- throw new Error("Source read completed without initialized state.")
588
- }
589
- const previousBindings = this.latestDataSourceBindings
590
- this.latestDataSourceBindings = {
591
- ...previousBindings,
592
- [key]: result.binding,
593
- }
594
- const next = applyDataSourceBindings(
595
- state,
596
- this.latestDataSourceBindings,
597
- previousBindings,
598
- )
599
- // Only explicitly read source keys belong in the cache.
600
- next.dataSources = next.dataSources.filter(source =>
601
- Object.hasOwn(this.latestDataSourceBindings, source.key),
602
- )
603
- this.commitHostState(next)
604
- const dataSource = next.dataSources.find(source => source.key === key)
605
- if (dataSource === undefined) {
606
- throw new Error("The host returned metadata for an undeclared source.")
607
- }
608
- return { status: "success" as const, dataSource }
524
+ return this.dataSources.read(key)
609
525
  }
610
526
 
611
527
  request<Schema extends ResponseSchema>(
@@ -646,14 +562,3 @@ function formatInvalidHostReason(
646
562
  const extra = issues.length > 1 ? ` (+${issues.length - 1} more)` : ""
647
563
  return `Could not parse ${labelled}: ${detail}${extra}`
648
564
  }
649
-
650
- function staleReadError() {
651
- return {
652
- status: "error" as const,
653
- error: {
654
- code: "host_state_changed",
655
- message: "The host configuration changed during the read.",
656
- isRetryable: true,
657
- },
658
- }
659
- }
@@ -0,0 +1,64 @@
1
+ import { autoResize } from "../layout/autoResize.js"
2
+ import { getInitialContentHeight } from "../layout/getInitialContentHeight.js"
3
+ import { readLocalManifest } from "../manifest/readLocalManifest.js"
4
+ import { syncDocumentAppearance } from "../preferences/syncDocumentAppearance.js"
5
+ import { SandboxBridge } from "./SandboxBridge.js"
6
+ import type { SandboxEnvironment } from "./sandboxEnvironment.js"
7
+
8
+ const AUTOMATIC_READINESS_FALLBACK_MS = 100
9
+
10
+ export function createBrowserSandboxBridge(): SandboxBridge {
11
+ return new SandboxBridge(browserEnvironment)
12
+ }
13
+
14
+ const browserEnvironment: SandboxEnvironment = {
15
+ transport: {
16
+ isEmbedded: () => typeof window !== "undefined" && window.parent !== window,
17
+ subscribe(receive) {
18
+ if (typeof window === "undefined") {
19
+ return undefined
20
+ }
21
+ const sandbox = window
22
+ const onMessage = (event: MessageEvent<unknown>) => {
23
+ if (event.source === sandbox.parent) {
24
+ receive(event.data)
25
+ }
26
+ }
27
+ sandbox.addEventListener("message", onMessage)
28
+ return () => sandbox.removeEventListener("message", onMessage)
29
+ },
30
+ send: message => window.parent.postMessage(message, "*"),
31
+ },
32
+ document: {
33
+ readLocalManifest: () =>
34
+ readLocalManifest({
35
+ document: window.document,
36
+ url: new URL(window.location.href),
37
+ }),
38
+ applyAppearance: syncDocumentAppearance,
39
+ getInitialHeight: getInitialContentHeight,
40
+ scheduleReady(reportReady) {
41
+ const sandbox = window
42
+ // Hidden iframes may not receive animation frames.
43
+ const timeout = sandbox.setTimeout(
44
+ reportReady,
45
+ AUTOMATIC_READINESS_FALLBACK_MS,
46
+ )
47
+ const frame = sandbox.requestAnimationFrame?.(reportReady)
48
+ return () => {
49
+ sandbox.clearTimeout(timeout)
50
+ if (frame !== undefined) {
51
+ sandbox.cancelAnimationFrame(frame)
52
+ }
53
+ }
54
+ },
55
+ observeHeight: onResize =>
56
+ autoResize({
57
+ target:
58
+ typeof document === "undefined"
59
+ ? null
60
+ : document.getElementById("root"),
61
+ onResize,
62
+ }),
63
+ },
64
+ }
@@ -1,10 +1,11 @@
1
- import { SandboxBridge } from "./SandboxBridge.js"
1
+ import { createBrowserSandboxBridge } from "./createBrowserSandboxBridge.js"
2
+ import type { SandboxBridge } from "./SandboxBridge.js"
2
3
 
3
4
  let bridge: SandboxBridge | undefined
4
5
 
5
6
  export function getBridge(): SandboxBridge {
6
7
  if (!bridge) {
7
- bridge = new SandboxBridge()
8
+ bridge = createBrowserSandboxBridge()
8
9
  }
9
10
  return bridge
10
11
  }
@@ -1,4 +1,4 @@
1
- import type { CustomBlockPage } from "@notionhq/custom-blocks-protocol/context/containingPage.js"
1
+ import type { ContainingPage } from "@notionhq/custom-blocks-protocol/context/containingPage.js"
2
2
  import type { NotionContrastMode } from "@notionhq/custom-blocks-protocol/context/contrast.js"
3
3
  import type { CustomBlockInstance } from "@notionhq/custom-blocks-protocol/context/instance.js"
4
4
  import type { NotionParent } from "@notionhq/custom-blocks-protocol/context/parent.js"
@@ -22,7 +22,7 @@ export type InitializedHostState = {
22
22
  theme: NotionTheme
23
23
  contrastMode: NotionContrastMode
24
24
  parent?: NotionParent
25
- page?: CustomBlockPage
25
+ page?: ContainingPage
26
26
  parentError?: CustomBlockErrorInfo
27
27
  pageError?: CustomBlockErrorInfo
28
28
  dataSources: NotionDataSource[]
@@ -9,15 +9,22 @@ import type {
9
9
  import type { ReadyMessage } from "@notionhq/custom-blocks-protocol/handshake/ready.js"
10
10
  import type { SandboxToHostMessage } from "@notionhq/custom-blocks-protocol/messages/sandboxToHost.js"
11
11
  import type { CustomBlockErrorInfo } from "@notionhq/custom-blocks-protocol/utils/errors.js"
12
+ import {
13
+ LATEST_BRIDGE_PROTOCOL_VERSION,
14
+ PROTOCOL_VERSION_12_MINIMAL_INIT,
15
+ } from "@notionhq/custom-blocks-protocol/utils/protocolVersion.js"
12
16
  import { NotInIframeError } from "../../initialization/NotInIframeError.js"
13
17
  import type { CustomBlockInitData } from "../../initialization/types.js"
14
- import { readLocalManifest } from "../../manifest/readLocalManifest.js"
18
+ import type { LocalManifestReadResult } from "../../manifest/readLocalManifest.js"
15
19
  import { makeUuid } from "../../utils/makeUuid.js"
16
20
  import { CUSTOM_BLOCKS_SDK_VERSION } from "../../utils/version.js"
17
21
  import type { CustomBlockHostState } from "../hostState.js"
18
22
  import { DEFAULT_REQUEST_TIMEOUT_MS } from "../requests.js"
19
23
 
20
- const SUPPORTED_PROTOCOL_VERSION = 12
24
+ const SUPPORTED_PROTOCOL_VERSIONS: readonly number[] = [
25
+ LATEST_BRIDGE_PROTOCOL_VERSION,
26
+ PROTOCOL_VERSION_12_MINIMAL_INIT,
27
+ ]
21
28
 
22
29
  /** Startup handshake states, including setup acknowledgment and render readiness. */
23
30
  type SandboxInitializationPhase =
@@ -51,6 +58,12 @@ export type InitializationOptions = {
51
58
  /** Starts listening for host messages on the first initialization call, before `connect` is sent. */
52
59
  start: () => void
53
60
 
61
+ /** Checks whether the sandbox is embedded in a host before connecting. */
62
+ isEmbedded: () => boolean
63
+
64
+ /** Reads the local development manifest, if the sandbox has one. */
65
+ readLocalManifest: () => LocalManifestReadResult
66
+
54
67
  /** Sends directly to the host, bypassing the outbound queue. */
55
68
  post: (message: SandboxToHostMessage) => void
56
69
 
@@ -81,6 +94,10 @@ export class SandboxInitialization {
81
94
  private initPromise: Promise<CustomBlockInitData> | undefined
82
95
  private connectRequestId: string | undefined
83
96
  private negotiatedProtocolVersion: number | undefined
97
+
98
+ get protocolVersion() {
99
+ return this.negotiatedProtocolVersion
100
+ }
84
101
  private initRequestId: string | undefined
85
102
  private earlyInit: SetupInitMessage | undefined
86
103
  private hostResponseTimeout: ReturnType<typeof setTimeout> | undefined
@@ -135,7 +152,7 @@ export class SandboxInitialization {
135
152
  onSetupComplete: (() => void) | undefined,
136
153
  ): Promise<CustomBlockInitData> {
137
154
  try {
138
- if (typeof window === "undefined" || window.parent === window) {
155
+ if (!this.options.isEmbedded()) {
139
156
  throw new NotInIframeError()
140
157
  }
141
158
  this.sendConnect()
@@ -175,10 +192,7 @@ export class SandboxInitialization {
175
192
  console.warn("[custom-blocks-sdk] ignoring duplicate connect message")
176
193
  return
177
194
  }
178
- const result = readLocalManifest({
179
- document: window.document,
180
- url: new URL(window.location.href),
181
- })
195
+ const result = this.options.readLocalManifest()
182
196
  if (result.status === "error") {
183
197
  this.phase = "failed"
184
198
  this.reject(new CustomBlockInitializationError(result.error))
@@ -187,7 +201,7 @@ export class SandboxInitialization {
187
201
  const message: ConnectRequestMessage = {
188
202
  type: "connect",
189
203
  requestId: makeUuid(),
190
- supportedProtocolVersions: [SUPPORTED_PROTOCOL_VERSION],
204
+ supportedProtocolVersions: [...SUPPORTED_PROTOCOL_VERSIONS],
191
205
 
192
206
  sdkVersion: CUSTOM_BLOCKS_SDK_VERSION,
193
207
  ...(result.manifest !== undefined ? { manifest: result.manifest } : {}),
@@ -222,10 +236,10 @@ export class SandboxInitialization {
222
236
  this.fail(message.error)
223
237
  return
224
238
  }
225
- if (message.protocolVersion !== SUPPORTED_PROTOCOL_VERSION) {
239
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(message.protocolVersion)) {
226
240
  this.fail({
227
241
  code: "unsupported_protocol_version",
228
- message: `This SDK requires host protocol ${SUPPORTED_PROTOCOL_VERSION}; the host selected protocol ${message.protocolVersion}.`,
242
+ message: `This SDK supports host protocols ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")}; the host selected protocol ${message.protocolVersion}.`,
229
243
 
230
244
  isRetryable: false,
231
245
  })
@@ -0,0 +1,38 @@
1
+ import type { SandboxToHostMessage } from "@notionhq/custom-blocks-protocol/messages/sandboxToHost.js"
2
+ import type { LocalManifestReadResult } from "../manifest/readLocalManifest.js"
3
+ import type { CustomBlockHostState } from "./hostState.js"
4
+
5
+ /** Host messaging and document effects used by the sandbox bridge. */
6
+ export type SandboxEnvironment = {
7
+ transport: {
8
+ /** Reports whether the sandbox has a parent window it can connect to. */
9
+ isEmbedded: () => boolean
10
+
11
+ /**
12
+ * Delivers payloads from the parent window for the bridge to validate.
13
+ * Returns a function that removes the listener, or `undefined` if no window is available.
14
+ */
15
+ subscribe: (receive: (message: unknown) => void) => (() => void) | undefined
16
+
17
+ /** Sends a bridge message to the parent host. */
18
+ send: (message: SandboxToHostMessage) => void
19
+ }
20
+ document: {
21
+ /** Reads the optional local manifest before the bridge sends `connect`. */
22
+ readLocalManifest: () => LocalManifestReadResult
23
+
24
+ /** Applies the host’s theme and contrast before the bridge acknowledges setup. */
25
+ applyAppearance: (
26
+ appearance: Pick<CustomBlockHostState, "theme" | "contrastMode">,
27
+ ) => void
28
+
29
+ /** Measures the initial content height in CSS pixels for `ready`. */
30
+ getInitialHeight: () => number
31
+
32
+ /** Schedules `reportReady` after setup and returns a function that cancels it. */
33
+ scheduleReady: (reportReady: () => void) => () => void
34
+
35
+ /** Reports content heights in CSS pixels and returns a function that stops observation. */
36
+ observeHeight: (reportHeight: (height: number) => void) => () => void
37
+ }
38
+ }
@@ -0,0 +1,94 @@
1
+ import type { BridgeDataSourceBindings } from "@notionhq/custom-blocks-protocol/dataSources/bridgeDataSourceBindings.js"
2
+ import type {
3
+ CustomBlockHostState,
4
+ InitializedHostState,
5
+ } from "../../bridge/hostState.js"
6
+ import type { Requests } from "../../bridge/requests.js"
7
+ import type { DataSourceReadResult } from "../types.js"
8
+ import { applyDataSourceBindings } from "./applyDataSourceBindings.js"
9
+ import { makeDataSourceReadResponseSchema } from "./makeDataSourceReadResponseSchema.js"
10
+
11
+ /** Owns the bindings and in-flight metadata reads for one sandbox connection. */
12
+ export class DataSourceCache {
13
+ private bindings: BridgeDataSourceBindings = {}
14
+ private pendingReads = new Map<string, Promise<DataSourceReadResult>>()
15
+ private generation = 0
16
+
17
+ constructor(
18
+ private readonly requests: Requests,
19
+ private readonly getState: () => CustomBlockHostState,
20
+ private readonly publish: (state: InitializedHostState) => void,
21
+ ) {}
22
+
23
+ getGeneration(): number {
24
+ return this.generation
25
+ }
26
+
27
+ invalidate(): void {
28
+ this.generation++
29
+ this.bindings = {}
30
+ this.pendingReads = new Map()
31
+ }
32
+
33
+ async read(key: string): Promise<DataSourceReadResult> {
34
+ // Each generation owns its map. An old read can only clean up its own entry.
35
+ const pendingReads = this.pendingReads
36
+ const existing = pendingReads.get(key)
37
+ if (existing !== undefined) {
38
+ return existing
39
+ }
40
+
41
+ const pending = this.requestBinding(key, this.generation)
42
+ pendingReads.set(key, pending)
43
+ try {
44
+ return await pending
45
+ } finally {
46
+ pendingReads.delete(key)
47
+ }
48
+ }
49
+
50
+ private async requestBinding(
51
+ key: string,
52
+ generation: number,
53
+ ): Promise<DataSourceReadResult> {
54
+ const initialState = this.getState()
55
+ if (initialState.status !== "initialized") {
56
+ throw new Error("Source read started without initialized state.")
57
+ }
58
+ const result = await this.requests.send(
59
+ { type: "getDataSource", key },
60
+ makeDataSourceReadResponseSchema(initialState.manifest, key),
61
+ )
62
+ if (result.status === "error") {
63
+ return result
64
+ }
65
+ if (generation !== this.generation) {
66
+ return {
67
+ status: "error",
68
+ error: {
69
+ code: "host_state_changed",
70
+ message: "The host configuration changed during the read.",
71
+ isRetryable: true,
72
+ },
73
+ }
74
+ }
75
+
76
+ const state = this.getState()
77
+ if (state.status !== "initialized") {
78
+ throw new Error("Source read completed without initialized state.")
79
+ }
80
+ const previousBindings = this.bindings
81
+ this.bindings = { ...previousBindings, [key]: result.binding }
82
+ const next = applyDataSourceBindings(state, this.bindings, previousBindings)
83
+ // Resolving the manifest also produces entries for keys the SDK has not read.
84
+ next.dataSources = next.dataSources.filter(source =>
85
+ Object.hasOwn(this.bindings, source.key),
86
+ )
87
+ this.publish(next)
88
+ const dataSource = next.dataSources.find(source => source.key === key)
89
+ if (dataSource === undefined) {
90
+ throw new Error("The host returned metadata for an undeclared source.")
91
+ }
92
+ return { status: "success", dataSource }
93
+ }
94
+ }
@@ -1,12 +1,10 @@
1
+ import { areDataSourceBindingsEqual } from "@notionhq/custom-blocks-protocol/dataSources/areDataSourceBindingsEqual.js"
1
2
  import type { BridgeDataSourceBindings } from "@notionhq/custom-blocks-protocol/dataSources/bridgeDataSourceBindings.js"
2
3
  import type { NotionDataSource } from "@notionhq/custom-blocks-protocol/dataSources/notionDataSource.js"
3
4
 
4
5
  /**
5
6
  * `postMessage` cloning creates new objects even for bindings that did not change. Preserve their
6
7
  * resolved object identity so React effects only run for changed bindings.
7
- *
8
- * This comparison runs when the host sends an update instead of on every component render. Bindings
9
- * are validated JSON-like bridge payloads, so serialization is sufficient here.
10
8
  */
11
9
  export function reuseDataSourcesForUnchangedBindings(args: {
12
10
  previousDataSources: NotionDataSource[]
@@ -22,8 +20,10 @@ export function reuseDataSourcesForUnchangedBindings(args: {
22
20
  const previousDataSource = previousDataSourcesByKey.get(dataSource.key)
23
21
  if (
24
22
  previousDataSource !== undefined &&
25
- JSON.stringify(args.previousBindings[dataSource.key]) ===
26
- JSON.stringify(args.nextBindings[dataSource.key])
23
+ areDataSourceBindingsEqual(
24
+ args.previousBindings[dataSource.key],
25
+ args.nextBindings[dataSource.key],
26
+ )
27
27
  ) {
28
28
  return previousDataSource
29
29
  }