@notionhq/custom-blocks 0.2.20 → 0.2.22

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 (66) hide show
  1. package/README.md +2 -0
  2. package/dist/bridge/SandboxBridge.d.ts +14 -18
  3. package/dist/bridge/SandboxBridge.d.ts.map +1 -1
  4. package/dist/bridge/SandboxBridge.js +59 -201
  5. package/dist/bridge/SandboxInitialization.d.ts +52 -0
  6. package/dist/bridge/SandboxInitialization.d.ts.map +1 -0
  7. package/dist/bridge/SandboxInitialization.js +217 -0
  8. package/dist/bridge/dataSources/query.d.ts.map +1 -1
  9. package/dist/bridge/dataSources/query.js +30 -23
  10. package/dist/bridge/messageInterceptor.d.ts +4 -0
  11. package/dist/bridge/messageInterceptor.d.ts.map +1 -0
  12. package/dist/bridge/messageInterceptor.js +1 -0
  13. package/dist/bridge/sandboxClient.d.ts +3 -2
  14. package/dist/bridge/sandboxClient.d.ts.map +1 -1
  15. package/dist/bridge/sandboxClient.js +3 -5
  16. package/dist/bridge.d.ts +11 -0
  17. package/dist/bridge.d.ts.map +1 -0
  18. package/dist/bridge.js +11 -0
  19. package/dist/index.d.ts +1 -0
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/init.d.ts +4 -38
  22. package/dist/init.d.ts.map +1 -1
  23. package/dist/init.js +4 -91
  24. package/dist/initTypes.d.ts +31 -0
  25. package/dist/initTypes.d.ts.map +1 -0
  26. package/dist/initTypes.js +18 -0
  27. package/dist/protocol/dataSources/propertySchema.d.ts +1 -1
  28. package/dist/protocol/dataSources/propertySchema.js +2 -0
  29. package/dist/protocol/dataSources/sortDirection.d.ts +3 -0
  30. package/dist/protocol/dataSources/sortDirection.js +2 -0
  31. package/dist/protocol/index.d.ts +1 -0
  32. package/dist/protocol/index.js +1 -0
  33. package/dist/protocol/messages/hostToSandbox.d.ts +0 -3
  34. package/dist/protocol/messages/init.d.ts +1 -1
  35. package/dist/protocol/messages/queryDataSource.d.ts +259 -47
  36. package/dist/protocol/messages/queryDataSource.js +94 -8
  37. package/dist/protocol/messages/sandboxToHost.d.ts +80 -16
  38. package/dist/styles/nds.css +1 -1
  39. package/dist/types.d.ts +5 -3
  40. package/dist/types.d.ts.map +1 -1
  41. package/dist/version.js +1 -1
  42. package/docs/bridge-interceptors.md +27 -0
  43. package/docs/data-sources.md +80 -13
  44. package/docs/errors.md +2 -0
  45. package/docs/pages.md +22 -10
  46. package/package.json +4 -4
  47. package/src/bridge/SandboxBridge.ts +74 -239
  48. package/src/bridge/SandboxInitialization.ts +295 -0
  49. package/src/bridge/dataSources/query.ts +38 -25
  50. package/src/bridge/messageInterceptor.ts +6 -0
  51. package/src/bridge/sandboxClient.ts +6 -5
  52. package/src/bridge.ts +17 -0
  53. package/src/index.ts +1 -0
  54. package/src/init.ts +8 -119
  55. package/src/initTypes.ts +43 -0
  56. package/src/styles/nds.css +1 -1
  57. package/src/styles/nds.css.metadata.json +3 -3
  58. package/src/types.ts +6 -2
  59. package/dist/bridge/primedResponses.d.ts +0 -8
  60. package/dist/bridge/primedResponses.d.ts.map +0 -1
  61. package/dist/bridge/primedResponses.js +0 -5
  62. package/dist/testing.d.ts +0 -12
  63. package/dist/testing.d.ts.map +0 -1
  64. package/dist/testing.js +0 -9
  65. package/src/bridge/primedResponses.ts +0 -11
  66. package/src/testing.ts +0 -19
@@ -6,36 +6,29 @@ import type {
6
6
  } from "@notionhq/custom-blocks-protocol/dataSources/dataSource.js"
7
7
  import type { NotionPageId } from "@notionhq/custom-blocks-protocol/ids.js"
8
8
  import type { CustomBlockManifest } from "@notionhq/custom-blocks-protocol/manifest.js"
9
- import type { ConnectMessage } from "@notionhq/custom-blocks-protocol/messages/connect.js"
10
9
  import type {
11
10
  CreatePageMessage,
12
11
  CreatePageMessageParent,
13
12
  } from "@notionhq/custom-blocks-protocol/messages/createPage.js"
14
13
  import type { CustomBlockCreatePageErrorInfo } from "@notionhq/custom-blocks-protocol/messages/createPageResult.js"
14
+ import type { GetPageMessage } from "@notionhq/custom-blocks-protocol/messages/getPage.js"
15
15
  import type { GetUserMessage } from "@notionhq/custom-blocks-protocol/messages/getUser.js"
16
- import {
17
- hostToSandboxMessageSchema,
18
- type PrimeableHostToSandboxMessage,
19
- } from "@notionhq/custom-blocks-protocol/messages/hostToSandbox.js"
16
+ import { hostToSandboxMessageSchema } from "@notionhq/custom-blocks-protocol/messages/hostToSandbox.js"
20
17
  import { readIncomingType } from "@notionhq/custom-blocks-protocol/messages/incomingType.js"
21
18
  import {
22
- CustomBlockInitializationError,
23
19
  type InitMessage,
24
20
  initMessageSchema,
25
21
  } from "@notionhq/custom-blocks-protocol/messages/init.js"
26
- import type {
27
- CustomBlockInitResultErrorInfo,
28
- InitResultMessage,
29
- } from "@notionhq/custom-blocks-protocol/messages/initResult.js"
22
+ import type { CustomBlockInitResultErrorInfo } from "@notionhq/custom-blocks-protocol/messages/initResult.js"
30
23
  import type { InvalidHostMessage } from "@notionhq/custom-blocks-protocol/messages/invalidHostMessage.js"
31
24
  import type { ListUsersMessage } from "@notionhq/custom-blocks-protocol/messages/listUsers.js"
32
25
  import type { OpenPageMessage } from "@notionhq/custom-blocks-protocol/messages/openPage.js"
33
26
  import type { QueryDataSourceMessage } from "@notionhq/custom-blocks-protocol/messages/queryDataSource.js"
34
27
  import type { CustomBlockQueryDataSourceErrorInfo } from "@notionhq/custom-blocks-protocol/messages/queryDataSourceResult.js"
35
28
  import type { ResizeMessage } from "@notionhq/custom-blocks-protocol/messages/resize.js"
29
+ import type { SandboxToHostMessage } from "@notionhq/custom-blocks-protocol/messages/sandboxToHost.js"
36
30
  import type { UnsubscribeDataSourceQueryMessage } from "@notionhq/custom-blocks-protocol/messages/unsubscribeDataSourceQuery.js"
37
31
  import type { UpdatePageMessage } from "@notionhq/custom-blocks-protocol/messages/updatePage.js"
38
- import { LATEST_BRIDGE_PROTOCOL_VERSION } from "@notionhq/custom-blocks-protocol/protocolVersion.js"
39
32
  import type { NotionTheme } from "@notionhq/custom-blocks-protocol/theme.js"
40
33
  import * as v from "valibot"
41
34
  import type {
@@ -54,7 +47,6 @@ import type {
54
47
  UpdatePageResult,
55
48
  } from "../types.js"
56
49
  import { unreachable } from "../utils.js"
57
- import { CUSTOM_BLOCKS_SDK_VERSION } from "../version.js"
58
50
  import {
59
51
  NOTION_DARK_BACKGROUND_BASE,
60
52
  NOTION_LIGHT_BACKGROUND_BASE,
@@ -71,9 +63,10 @@ import {
71
63
  type DataSourceQueryState,
72
64
  } from "./hostState.js"
73
65
  import type { ManifestLoadResult } from "./loadManifest.js"
66
+ import type { MessageInterceptor } from "./messageInterceptor.js"
74
67
  import { notifyListener } from "./notifyListener.js"
75
68
  import { PendingRequests } from "./pendingRequests.js"
76
- import { globalPrimedResponsesCache } from "./primedResponses.js"
69
+ import { SandboxInitialization } from "./SandboxInitialization.js"
77
70
 
78
71
  /**
79
72
  * A single entry in the bridge message log. Kept intentionally plain so the log is copy-pasteable
@@ -85,18 +78,6 @@ export type MessageLogEntry = {
85
78
  data: unknown
86
79
  }
87
80
 
88
- const RESPONSE_TYPE_BY_REQUEST = new Map([
89
- ["getPage", "getPageResult"],
90
- ["openPage", "openPageResult"],
91
- ["createPage", "createPageResult"],
92
- ["updatePage", "updatePageResult"],
93
- ["getUser", "getUserResult"],
94
- ["listUsers", "listUsersResult"],
95
- ["queryDataSource", "queryDataSourceResult"],
96
- ]) satisfies ReadonlyMap<string, PrimeableHostToSandboxMessage["type"]>
97
-
98
- const INIT_RESULT_TIMER_FALLBACK_MS = 100
99
-
100
81
  export type QueryDataSourceArgs = {
101
82
  subscriptionId: string
102
83
  key: string
@@ -104,7 +85,6 @@ export type QueryDataSourceArgs = {
104
85
  /** Send the query even if an identical query is already loading. */
105
86
  forceRequery?: boolean
106
87
  }
107
-
108
88
  export class SandboxBridge {
109
89
  private hostState: CustomBlockHostState = {
110
90
  status: "uninitialized",
@@ -112,9 +92,9 @@ export class SandboxBridge {
112
92
  contrastMode: DEFAULT_CONTRAST_MODE,
113
93
  }
114
94
  private listeners = new Set<() => void>()
95
+ private messageInterceptors = new Set<MessageInterceptor>()
115
96
  private messageLog: MessageLogEntry[] = []
116
97
  private messageLogListeners = new Set<() => void>()
117
- private nextRequestId = 1
118
98
  private readonly pendingCreatePage = new PendingRequests<CreatePageResult>(
119
99
  "custom-block-create-page",
120
100
  )
@@ -133,25 +113,42 @@ export class SandboxBridge {
133
113
  private readonly pendingUpdatePage = new PendingRequests<UpdatePageResult>(
134
114
  "custom-block-update-page",
135
115
  )
136
- private hasSentConnect = false
137
- private hasReceivedInit = false
138
- private initializationId: string | undefined
139
- private hasSentInitResult = false
140
- private pendingOutboundMessages: unknown[] = []
141
116
  private latestDataSourceBindings: NotionDataSourceBindings = {}
142
117
  private isMockState = false
143
118
  private isListening = false
144
- private resolveInit: (() => void) | undefined
145
- private rejectInit: ((reason: Error) => void) | undefined
146
- private readonly initMessage: Promise<void> = new Promise(
147
- (resolve, reject) => {
148
- this.resolveInit = resolve
149
- this.rejectInit = reject
150
- },
151
- )
119
+ private isDisposed = false
120
+ private readonly initialization = new SandboxInitialization({
121
+ start: () => this.startListening(),
122
+ post: message => this.sendToHost(message),
123
+ apply: message => this.applyInit(message, true),
124
+ getState: () => this.hostState,
125
+ getInitialHeight: getInitialContentHeight,
126
+ })
127
+
128
+ initialize() {
129
+ return this.initialization.initialize()
130
+ }
131
+
132
+ /**
133
+ * Stops this bridge permanently. Rejects pending initialization, cancels
134
+ * acknowledgment callbacks, removes the message listener, and discards queued
135
+ * outbound messages. Further host messages are ignored.
136
+ *
137
+ * Pending page and user requests are not settled by disposal.
138
+ */
139
+ dispose() {
140
+ this.isDisposed = true
141
+ this.initialization.dispose()
142
+ if (this.isListening) {
143
+ window.removeEventListener("message", this.handleMessage)
144
+ this.isListening = false
145
+ }
146
+ this.listeners.clear()
147
+ this.messageLogListeners.clear()
148
+ }
152
149
 
153
150
  startListening() {
154
- if (this.isListening || typeof window === "undefined") {
151
+ if (this.isDisposed || this.isListening || typeof window === "undefined") {
155
152
  return
156
153
  }
157
154
  this.isListening = true
@@ -183,102 +180,31 @@ export class SandboxBridge {
183
180
  return () => this.messageLogListeners.delete(listener)
184
181
  }
185
182
 
186
- awaitInit(): Promise<void> {
187
- return this.initMessage
183
+ registerMessageInterceptor(interceptor: MessageInterceptor): () => void {
184
+ this.messageInterceptors.add(interceptor)
185
+ return () => this.messageInterceptors.delete(interceptor)
188
186
  }
189
187
 
190
188
  sendConnect(manifestResult: ManifestLoadResult) {
191
- if (typeof window === "undefined") {
192
- return
193
- }
194
- if (this.hasSentConnect) {
195
- console.warn("[custom-blocks-sdk] ignoring duplicate connect message")
196
- return
197
- }
198
- const { manifest, error } = manifestResult
199
- this.hasSentConnect = true
200
- const initializationId = `custom-block-initialization-${this.nextRequestId}`
201
- this.nextRequestId += 1
202
- this.initializationId = initializationId
203
- const connectMessage: ConnectMessage =
204
- error !== undefined
205
- ? {
206
- type: "connect",
207
- initializationId,
208
- status: "error",
209
- bridgeProtocolVersion: LATEST_BRIDGE_PROTOCOL_VERSION,
210
- sdkVersion: CUSTOM_BLOCKS_SDK_VERSION,
211
- error,
212
- }
213
- : {
214
- type: "connect",
215
- initializationId,
216
- status: "success",
217
- bridgeProtocolVersion: LATEST_BRIDGE_PROTOCOL_VERSION,
218
- sdkVersion: CUSTOM_BLOCKS_SDK_VERSION,
219
- ...(manifest !== null ? { manifest } : {}),
220
- }
221
- this.postToHost(connectMessage)
189
+ this.initialization.sendConnect(manifestResult)
222
190
  }
223
191
 
224
- private postToHost(message: unknown) {
225
- if (
226
- this.hostState.status === "initialized" &&
227
- !this.hasSentInitResult &&
228
- !this.isMockState &&
229
- this.getMessageType(message) !== "initResult"
230
- ) {
231
- this.pendingOutboundMessages.push(message)
232
- return
233
- }
234
- this.sendToHost(message)
192
+ private postToHost(message: SandboxToHostMessage) {
193
+ this.initialization.post(message)
235
194
  }
236
195
 
237
- private sendToHost(message: unknown) {
238
- // Check if the message is a primed response
239
- const messageType = readIncomingType(message)
240
- if (
241
- messageType !== undefined &&
242
- typeof message === "object" &&
243
- message !== null
244
- ) {
245
- const responseType = RESPONSE_TYPE_BY_REQUEST.get(messageType)
246
- const primed =
247
- responseType && globalPrimedResponsesCache.get(responseType)
248
- if (responseType !== undefined && primed !== undefined) {
249
- globalPrimedResponsesCache.delete(responseType)
250
- const response = {
251
- ...primed,
252
- type: responseType,
253
- ...("requestId" in message ? { requestId: message.requestId } : {}),
254
- ...("subscriptionId" in message
255
- ? { subscriptionId: message.subscriptionId }
256
- : {}),
257
- }
196
+ private sendToHost(message: SandboxToHostMessage) {
197
+ for (const interceptor of [...this.messageInterceptors]) {
198
+ const response = interceptor(message)
199
+ if (response !== undefined) {
258
200
  queueMicrotask(() => this.receiveMessage(response))
259
201
  return
260
202
  }
261
203
  }
262
-
263
- // If no primed response is found, proceed as normal
264
204
  this.logMessage("sent", message)
265
205
  window.parent.postMessage(message, "*")
266
206
  }
267
207
 
268
- private flushPendingOutboundMessages() {
269
- const pendingMessages = this.pendingOutboundMessages
270
- this.pendingOutboundMessages = []
271
- for (const message of pendingMessages) {
272
- this.sendToHost(message)
273
- }
274
- }
275
-
276
- private getMessageType(message: unknown): unknown {
277
- return typeof message === "object" && message !== null && "type" in message
278
- ? message.type
279
- : undefined
280
- }
281
-
282
208
  private notify = () => {
283
209
  for (const listener of this.listeners) {
284
210
  notifyListener(listener)
@@ -293,6 +219,9 @@ export class SandboxBridge {
293
219
  }
294
220
 
295
221
  private receiveMessage(data: unknown) {
222
+ if (this.isDisposed) {
223
+ return
224
+ }
296
225
  this.logMessage("received", data)
297
226
 
298
227
  const parsed = v.safeParse(hostToSandboxMessageSchema, data)
@@ -303,18 +232,18 @@ export class SandboxBridge {
303
232
  )
304
233
  const incomingType = readIncomingType(data)
305
234
  if (
306
- !this.hasReceivedInit &&
307
235
  incomingType === "init" &&
308
- this.initializationId !== undefined &&
309
- readInitializationId(data) === this.initializationId
236
+ this.initialization.handleInvalidInit(
237
+ readInitializationId(data),
238
+ invalidInitPayloadError(parsed.issues),
239
+ )
310
240
  ) {
311
- this.hasReceivedInit = true
312
- this.sendInitResultError(invalidInitPayloadError(parsed.issues))
313
241
  return
314
242
  }
315
- // Loop guard: never NACK a NACK. Excludes both directions — `invalidSandboxMessage` is
316
- // what the host normally sends, but a buggy host that echoes our own
317
- // `invalidHostMessage` back would otherwise spin a NACK feedback loop.
243
+ // Loop guard: never NACK a NACK. Excludes both directions —
244
+ // `invalidSandboxMessage` is what the host normally sends, but
245
+ // a buggy host that echoes our own `invalidHostMessage` back
246
+ // would otherwise spin a NACK feedback loop.
318
247
  if (
319
248
  incomingType !== "invalidSandboxMessage" &&
320
249
  incomingType !== "invalidHostMessage"
@@ -344,18 +273,7 @@ export class SandboxBridge {
344
273
  // `init` is the only message valid before initialization. Handle it up front so every later
345
274
  // case can assume `status === "initialized"`.
346
275
  if (message.type === "init") {
347
- if (message.initializationId !== this.initializationId) {
348
- console.warn(
349
- `[custom-blocks-sdk] ignoring init for unknown initializationId ${message.initializationId}`,
350
- )
351
- return
352
- }
353
- if (this.hasReceivedInit) {
354
- console.warn("[custom-blocks-sdk] ignoring duplicate init message")
355
- return
356
- }
357
- this.hasReceivedInit = true
358
- this.applyInit(message, true)
276
+ this.initialization.handleInit(message)
359
277
  return
360
278
  }
361
279
 
@@ -603,69 +521,25 @@ export class SandboxBridge {
603
521
  */
604
522
  setMockState(message: InitMessage) {
605
523
  this.isMockState = true
606
- this.applyInit(v.parse(initMessageSchema, message), false)
607
- }
608
-
609
- completeInitialization() {
610
- if (
611
- this.hasSentInitResult ||
612
- this.initializationId === undefined ||
613
- this.hostState.status !== "initialized"
614
- ) {
615
- return
616
- }
617
- const result: InitResultMessage = {
618
- type: "initResult",
619
- initializationId: this.initializationId,
620
- status: "success",
621
- initialHeight: getInitialContentHeight(),
524
+ const parsed = v.parse(initMessageSchema, message)
525
+ if (parsed.status === "success") {
526
+ this.startListening()
527
+ this.applyInit(parsed, false)
528
+ this.initialization.setPreview()
622
529
  }
623
- this.hasSentInitResult = true
624
- this.postToHost(result)
625
- this.flushPendingOutboundMessages()
626
530
  }
627
531
 
628
- private sendInitResultError(error: CustomBlockInitResultErrorInfo) {
629
- if (this.hasSentInitResult || this.initializationId === undefined) {
630
- return
631
- }
632
- const result: InitResultMessage = {
633
- type: "initResult",
634
- initializationId: this.initializationId,
635
- status: "error",
636
- error,
637
- }
638
- this.hasSentInitResult = true
639
- this.postToHost(result)
640
- if (this.rejectInit) {
641
- this.rejectInit(new CustomBlockInitializationError(error))
642
- this.resolveInit = undefined
643
- this.rejectInit = undefined
644
- }
532
+ completeInitialization() {
533
+ this.initialization.complete()
645
534
  }
646
535
 
647
- private applyInit(message: InitMessage, postResult: boolean) {
536
+ private applyInit(
537
+ message: Extract<InitMessage, { status: "success" }>,
538
+ postResult: boolean,
539
+ ): CustomBlockInitResultErrorInfo | undefined {
648
540
  if (postResult) {
649
541
  this.isMockState = false
650
542
  }
651
- if (message.status === "error") {
652
- // The host couldn't construct block location for this block (most commonly the parent
653
- // record failed to resolve). Surface the failure through the `awaitInit` promise so
654
- // callers see it through `useCustomBlockInit().error` instead of timing out. We also
655
- // log here because not every consumer renders the error UI, and we want the failure
656
- // visible in the browser console either way. We deliberately don't NACK the host or
657
- // post anything back over the bridge since the host has already given up.
658
- console.error(
659
- `[custom-blocks-sdk] host reported init error (${message.error.code}): ${message.error.message}`,
660
- )
661
- if (this.rejectInit) {
662
- this.rejectInit(new CustomBlockInitializationError(message.error))
663
- this.resolveInit = undefined
664
- this.rejectInit = undefined
665
- }
666
- return
667
- }
668
-
669
543
  const { blockId, parent, page } = message
670
544
 
671
545
  this.latestDataSourceBindings = message.dataSources.bindings
@@ -677,8 +551,7 @@ export class SandboxBridge {
677
551
  : resolveMockDataSources(this.latestDataSourceBindings)
678
552
  const bindingError = getInitBindingError(message.manifest, dataSources)
679
553
  if (postResult && bindingError !== undefined) {
680
- this.sendInitResultError(bindingError)
681
- return
554
+ return bindingError
682
555
  }
683
556
  this.hostState = {
684
557
  status: "initialized",
@@ -697,45 +570,7 @@ export class SandboxBridge {
697
570
  contrastMode: message.contrastMode,
698
571
  })
699
572
  this.notify()
700
- // Resolve the awaitInit promise once. Subsequent `init` messages (the host shouldn't send
701
- // these, but be tolerant) update state but don't re-resolve.
702
- if (this.resolveInit) {
703
- this.resolveInit()
704
- this.resolveInit = undefined
705
- this.rejectInit = undefined
706
- }
707
- if (postResult) {
708
- this.scheduleInitResult(message.initializationId)
709
- }
710
- }
711
-
712
- /**
713
- * Lets the initial application render commit before we acknowledge init. The host keeps the
714
- * iframe covered throughout this frame, so it can apply the measured height before first paint.
715
- */
716
- private scheduleInitResult(initializationId: string) {
717
- let didAcknowledge = false
718
- let fallbackTimerId: number | undefined
719
- const acknowledge = () => {
720
- if (didAcknowledge) {
721
- return
722
- }
723
- didAcknowledge = true
724
- if (fallbackTimerId !== undefined) {
725
- window.clearTimeout(fallbackTimerId)
726
- }
727
- if (this.initializationId !== initializationId) {
728
- return
729
- }
730
- this.completeInitialization()
731
- }
732
- fallbackTimerId = window.setTimeout(
733
- acknowledge,
734
- INIT_RESULT_TIMER_FALLBACK_MS,
735
- )
736
- if (typeof requestAnimationFrame === "function") {
737
- requestAnimationFrame(acknowledge)
738
- }
573
+ return undefined
739
574
  }
740
575
 
741
576
  createDataSourceSubscriptionId(): string {
@@ -928,7 +763,7 @@ export class SandboxBridge {
928
763
  getPage(pageId: NotionPageId): Promise<GetPageResult> {
929
764
  return new Promise(resolve => {
930
765
  const requestId = this.pendingGetPage.allocate(resolve)
931
- const outbound = {
766
+ const outbound: GetPageMessage = {
932
767
  type: "getPage",
933
768
  requestId,
934
769
  pageId,