@notionhq/custom-blocks 0.2.21 → 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
@@ -0,0 +1,295 @@
1
+ import type { ConnectMessage } from "@notionhq/custom-blocks-protocol/messages/connect.js"
2
+ import {
3
+ CustomBlockInitializationError,
4
+ type InitMessage,
5
+ } from "@notionhq/custom-blocks-protocol/messages/init.js"
6
+ import type {
7
+ CustomBlockInitResultErrorInfo,
8
+ InitResultMessage,
9
+ } from "@notionhq/custom-blocks-protocol/messages/initResult.js"
10
+ import type { SandboxToHostMessage } from "@notionhq/custom-blocks-protocol/messages/sandboxToHost.js"
11
+ import { LATEST_BRIDGE_PROTOCOL_VERSION } from "@notionhq/custom-blocks-protocol/protocolVersion.js"
12
+ import { type CustomBlockInitPayload, NotInIframeError } from "../initTypes.js"
13
+ import { CUSTOM_BLOCKS_SDK_VERSION } from "../version.js"
14
+ import type { CustomBlockHostState } from "./hostState.js"
15
+ import {
16
+ attemptToLoadSelfHostedManifest,
17
+ type ManifestLoadResult,
18
+ } from "./loadManifest.js"
19
+
20
+ const INITIALIZATION_ID = "custom-block-initialization-1"
21
+
22
+ /** Tracks the startup handshake and when outbound messages can be sent. */
23
+ type SandboxInitializationPhase =
24
+ /** No connect message has been sent. Manifest loading can still be in progress. */
25
+ | "idle"
26
+ /** Standalone preview state is available without a host handshake. */
27
+ | "preview"
28
+ /** Startup is stopped, acknowledgment callbacks are cancelled, and outbound messages are dropped. */
29
+ | "disposed"
30
+ /** Connect has been sent; the SDK is waiting for a matching init response. */
31
+ | "waiting"
32
+ /** A matching init is being processed. Outbound messages from subscribers are queued. */
33
+ | "applying"
34
+ /** Host state is applied and startup is resolved. Outbound messages wait for acknowledgment after the initial render. */
35
+ | "rendering"
36
+ /** Successful initialization is acknowledged. Outbound messages can be sent immediately. */
37
+ | "ready"
38
+ /** A matching init was rejected by the host or SDK. Further init responses are ignored. */
39
+ | "failed"
40
+
41
+ /** Bridge callbacks used by the initialization controller. */
42
+ export type InitializationOptions = {
43
+ /** Starts listening for host messages on the first call to initialize, before connect is sent. */
44
+ start: () => void
45
+ /** Sends a message immediately, bypassing the controller's outbound queue. */
46
+ post: (message: SandboxToHostMessage) => void
47
+ /**
48
+ * Applies a validated, matching init response and notifies state subscribers.
49
+ * Returns an error if the host context cannot be accepted, or undefined on success.
50
+ */
51
+ apply: (
52
+ message: Extract<InitMessage, { status: "success" }>,
53
+ ) => CustomBlockInitResultErrorInfo | undefined
54
+ /** Reads the current host state to build the context returned after initialization. */
55
+ getState: () => CustomBlockHostState
56
+ /** Measures the initial content height in pixels when sending initResult.success. */
57
+ getInitialHeight: () => number
58
+ }
59
+
60
+ /** Owns one document's startup, acknowledgement, and messages queued during rendering. */
61
+ export class SandboxInitialization {
62
+ private phase: SandboxInitializationPhase = "idle"
63
+ private pendingMessages: SandboxToHostMessage[] = []
64
+ private initPromise: Promise<CustomBlockInitPayload> | undefined
65
+ private frameId: number | undefined
66
+ private fallbackId: ReturnType<typeof setTimeout> | undefined
67
+ private resolveInit: (() => void) | undefined
68
+ private rejectInit: ((error: Error) => void) | undefined
69
+ private readonly initialized = new Promise<void>((resolve, reject) => {
70
+ this.resolveInit = resolve
71
+ this.rejectInit = reject
72
+ })
73
+
74
+ constructor(private readonly options: InitializationOptions) {
75
+ // A host can report an error before a caller starts awaiting initialization.
76
+ void this.initialized.catch(() => {})
77
+ }
78
+
79
+ initialize(): Promise<CustomBlockInitPayload> {
80
+ if (this.initPromise === undefined) {
81
+ this.options.start()
82
+ this.initPromise = this.run()
83
+ }
84
+ return this.initPromise
85
+ }
86
+
87
+ private async run(): Promise<CustomBlockInitPayload> {
88
+ try {
89
+ if (typeof window !== "undefined" && window.parent === window) {
90
+ throw new NotInIframeError()
91
+ }
92
+ await Promise.all([this.loadManifestAndConnect(), this.initialized])
93
+ const state = this.options.getState()
94
+ if (state.status !== "initialized") {
95
+ throw new CustomBlockInitializationError({
96
+ code: "context_unavailable",
97
+ message: "Host block payload is unavailable.",
98
+ isRetryable: true,
99
+ })
100
+ }
101
+ return {
102
+ theme: state.theme,
103
+ contrastMode: state.contrastMode,
104
+ blockId: state.blockId,
105
+ parent: state.parent,
106
+ page: state.page,
107
+ currentUser: state.currentUser,
108
+ dataSources: state.dataSources,
109
+ }
110
+ } catch (error) {
111
+ if (error instanceof CustomBlockInitializationError) {
112
+ throw error
113
+ }
114
+ throw new CustomBlockInitializationError({
115
+ code: "unknown_error",
116
+ message: error instanceof Error ? error.message : String(error),
117
+ isRetryable: false,
118
+ })
119
+ }
120
+ }
121
+
122
+ private async loadManifestAndConnect() {
123
+ const manifest = await attemptToLoadSelfHostedManifest()
124
+ if (this.phase !== "disposed") {
125
+ this.sendConnect(manifest)
126
+ }
127
+ }
128
+
129
+ sendConnect(result: ManifestLoadResult) {
130
+ if (typeof window === "undefined") {
131
+ return
132
+ }
133
+ if (this.phase !== "idle" && this.phase !== "preview") {
134
+ console.warn("[custom-blocks-sdk] ignoring duplicate connect message")
135
+ return
136
+ }
137
+ this.phase = "waiting"
138
+ const identity = {
139
+ type: "connect" as const,
140
+ initializationId: INITIALIZATION_ID,
141
+ bridgeProtocolVersion: LATEST_BRIDGE_PROTOCOL_VERSION,
142
+ sdkVersion: CUSTOM_BLOCKS_SDK_VERSION,
143
+ }
144
+ const message: ConnectMessage =
145
+ result.error !== undefined
146
+ ? { ...identity, status: "error", error: result.error }
147
+ : {
148
+ ...identity,
149
+ status: "success",
150
+ ...(result.manifest !== null ? { manifest: result.manifest } : {}),
151
+ }
152
+ this.options.post(message)
153
+ }
154
+
155
+ handleInit(message: InitMessage) {
156
+ if (
157
+ this.phase === "idle" ||
158
+ this.phase === "preview" ||
159
+ this.phase === "disposed" ||
160
+ message.initializationId !== INITIALIZATION_ID
161
+ ) {
162
+ console.warn(
163
+ `[custom-blocks-sdk] ignoring init for unknown initializationId ${message.initializationId}`,
164
+ )
165
+ return
166
+ }
167
+ if (this.phase !== "waiting") {
168
+ console.warn("[custom-blocks-sdk] ignoring duplicate init message")
169
+ return
170
+ }
171
+ this.phase = "applying"
172
+ if (message.status === "error") {
173
+ console.error(
174
+ `[custom-blocks-sdk] host reported init error (${message.error.code}): ${message.error.message}`,
175
+ )
176
+ this.phase = "failed"
177
+ this.reject(new CustomBlockInitializationError(message.error))
178
+ return
179
+ }
180
+ const error = this.options.apply(message)
181
+ if (error !== undefined) {
182
+ this.fail(error)
183
+ return
184
+ }
185
+ // Subscribers can complete or dispose initialization while apply notifies them.
186
+ if (this.phase !== "applying") {
187
+ return
188
+ }
189
+ this.phase = "rendering"
190
+ this.resolve()
191
+ this.fallbackId = setTimeout(() => this.complete(), 100)
192
+ if (typeof requestAnimationFrame === "function") {
193
+ this.frameId = requestAnimationFrame(() => this.complete())
194
+ }
195
+ }
196
+
197
+ handleInvalidInit(
198
+ id: string | undefined,
199
+ error: CustomBlockInitResultErrorInfo,
200
+ ): boolean {
201
+ if (this.phase !== "waiting" || INITIALIZATION_ID !== id) {
202
+ return false
203
+ }
204
+ this.fail(error)
205
+ return true
206
+ }
207
+
208
+ post(message: SandboxToHostMessage) {
209
+ if (this.phase === "disposed") {
210
+ return
211
+ }
212
+ if (this.phase === "rendering" || this.phase === "applying") {
213
+ this.pendingMessages.push(message)
214
+ } else {
215
+ this.options.post(message)
216
+ }
217
+ }
218
+
219
+ complete() {
220
+ if (this.phase !== "rendering") {
221
+ return
222
+ }
223
+ const message: InitResultMessage = {
224
+ type: "initResult",
225
+ initializationId: INITIALIZATION_ID,
226
+ status: "success",
227
+ initialHeight: this.options.getInitialHeight(),
228
+ }
229
+ this.phase = "ready"
230
+ this.clearAcknowledgement()
231
+ this.options.post(message)
232
+ const pending = this.pendingMessages
233
+ this.pendingMessages = []
234
+ for (const message of pending) {
235
+ this.post(message)
236
+ }
237
+ }
238
+
239
+ setPreview() {
240
+ this.clearAcknowledgement()
241
+ this.phase = "preview"
242
+ this.resolve()
243
+ }
244
+
245
+ dispose() {
246
+ this.phase = "disposed"
247
+ this.clearAcknowledgement()
248
+ this.pendingMessages = []
249
+ this.reject(
250
+ new CustomBlockInitializationError({
251
+ code: "unknown_error",
252
+ message: "SDK runtime was disposed before initialization completed.",
253
+ isRetryable: false,
254
+ }),
255
+ )
256
+ }
257
+
258
+ private fail(error: CustomBlockInitResultErrorInfo) {
259
+ if (this.phase !== "waiting" && this.phase !== "applying") {
260
+ return
261
+ }
262
+ this.phase = "failed"
263
+ this.options.post({
264
+ type: "initResult",
265
+ initializationId: INITIALIZATION_ID,
266
+ status: "error",
267
+ error,
268
+ } satisfies InitResultMessage)
269
+ this.reject(new CustomBlockInitializationError(error))
270
+ }
271
+
272
+ private resolve() {
273
+ this.resolveInit?.()
274
+ this.resolveInit = undefined
275
+ this.rejectInit = undefined
276
+ }
277
+
278
+ private reject(error: Error) {
279
+ this.rejectInit?.(error)
280
+ this.resolveInit = undefined
281
+ this.rejectInit = undefined
282
+ }
283
+
284
+ private clearAcknowledgement() {
285
+ clearTimeout(this.fallbackId)
286
+ this.fallbackId = undefined
287
+ if (
288
+ this.frameId !== undefined &&
289
+ typeof cancelAnimationFrame === "function"
290
+ ) {
291
+ cancelAnimationFrame(this.frameId)
292
+ this.frameId = undefined
293
+ }
294
+ }
295
+ }
@@ -1,5 +1,6 @@
1
1
  import type { NotionDataSource } from "@notionhq/custom-blocks-protocol/dataSources/dataSource.js"
2
2
  import { CUSTOM_BLOCK_DATA_SOURCE_SORTABLE_PROPERTY_TYPES } from "@notionhq/custom-blocks-protocol/dataSources/propertySchema.js"
3
+ import { notionSortDirectionSchema } from "@notionhq/custom-blocks-protocol/dataSources/sortDirection.js"
3
4
  import type { NotionDataSourceId } from "@notionhq/custom-blocks-protocol/ids.js"
4
5
  import {
5
6
  CUSTOM_BLOCK_DATA_SOURCE_QUERY_MAX_SORTS,
@@ -10,6 +11,8 @@ import {
10
11
  customBlockNumberFilterOperatorSchema,
11
12
  customBlockOptionFilterOperatorSchema,
12
13
  customBlockPeopleFilterOperatorSchema,
14
+ customBlockRelativeDateValueSchema,
15
+ customBlockStatusFilterOperatorSchema,
13
16
  customBlockTextFilterOperatorSchema,
14
17
  type ResolvedCustomBlockDataSourceFilter,
15
18
  type ResolvedCustomBlockDataSourcePropertyFilter,
@@ -365,7 +368,7 @@ function resolveSort(
365
368
  const direction = sortObject.direction
366
369
  if (
367
370
  !Object.hasOwn(sortObject, "direction") ||
368
- (direction !== "ascending" && direction !== "descending")
371
+ !v.is(notionSortDirectionSchema, direction)
369
372
  ) {
370
373
  return {
371
374
  status: "error",
@@ -406,12 +409,13 @@ function resolvePropertyFilter(
406
409
  }
407
410
  const branch = branchKeys[0]
408
411
  const value = filterObject[branch]
409
- if (
410
- typeof value !== "object" ||
411
- value === null ||
412
- Array.isArray(value) ||
413
- Object.keys(value).length !== 1
414
- ) {
412
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
413
+ return invalidOperator(branch)
414
+ }
415
+ const operatorKeys = Object.keys(value).filter(
416
+ key => branch !== "date" || key !== "target",
417
+ )
418
+ if (operatorKeys.length !== 1) {
415
419
  return invalidOperator(branch)
416
420
  }
417
421
  if (property.propertyType !== branch) {
@@ -449,12 +453,26 @@ function resolvePropertyFilterBranch(args: {
449
453
  case "checkbox":
450
454
  return resolveCheckboxPropertyFilter(args.propertyId, args.value)
451
455
  case "select":
452
- case "status":
453
456
  return resolveOptionPropertyFilter({
454
457
  propertyId: args.propertyId,
455
- branch: args.branch,
458
+ branch: "select",
456
459
  value: args.value,
457
460
  })
461
+ case "status": {
462
+ const parsed = v.safeParse(
463
+ customBlockStatusFilterOperatorSchema,
464
+ args.value,
465
+ )
466
+ return parsed.success
467
+ ? {
468
+ status: "ok",
469
+ filter: {
470
+ propertyId: args.propertyId,
471
+ status: parsed.output,
472
+ },
473
+ }
474
+ : invalidOperator("status")
475
+ }
458
476
  case "multi_select":
459
477
  return resolveMultiSelectPropertyFilter(args.propertyId, args.value)
460
478
  case "date":
@@ -542,26 +560,16 @@ function resolveCheckboxPropertyFilter(
542
560
 
543
561
  function resolveOptionPropertyFilter(args: {
544
562
  propertyId: string
545
- branch: "select" | "status"
563
+ branch: "select"
546
564
  value: Record<string, unknown>
547
565
  }): ResolvePropertyFilterResult {
548
566
  const parsed = v.safeParse(customBlockOptionFilterOperatorSchema, args.value)
549
567
  if (!parsed.success) {
550
568
  return invalidOperator(args.branch)
551
569
  }
552
- switch (args.branch) {
553
- case "select":
554
- return {
555
- status: "ok",
556
- filter: { propertyId: args.propertyId, select: parsed.output },
557
- }
558
- case "status":
559
- return {
560
- status: "ok",
561
- filter: { propertyId: args.propertyId, status: parsed.output },
562
- }
563
- default:
564
- return unreachable(args.branch)
570
+ return {
571
+ status: "ok",
572
+ filter: { propertyId: args.propertyId, select: parsed.output },
565
573
  }
566
574
  }
567
575
 
@@ -582,8 +590,13 @@ function resolveDatePropertyFilter(
582
590
  const parsed = v.safeParse(customBlockDateFilterOperatorSchema, value)
583
591
  if (
584
592
  !parsed.success ||
585
- !Object.values(parsed.output).every(
586
- entry => entry === true || isValidIsoDate(entry),
593
+ !Object.entries(parsed.output).every(
594
+ ([key, entry]) =>
595
+ key === "target" ||
596
+ entry === true ||
597
+ typeof entry === "object" ||
598
+ v.safeParse(customBlockRelativeDateValueSchema, entry).success ||
599
+ isValidIsoDate(entry),
587
600
  )
588
601
  ) {
589
602
  return invalidOperator("date")
@@ -0,0 +1,6 @@
1
+ import type { HostToSandboxMessage } from "@notionhq/custom-blocks-protocol/messages/hostToSandbox.js"
2
+ import type { SandboxToHostMessage } from "@notionhq/custom-blocks-protocol/messages/sandboxToHost.js"
3
+
4
+ export type MessageInterceptor = (
5
+ message: SandboxToHostMessage,
6
+ ) => HostToSandboxMessage | undefined
@@ -19,6 +19,7 @@ import {
19
19
  getDataSourceQueryView as getDataSourceQueryViewWithBridge,
20
20
  } from "./hostState.js"
21
21
  import type { ManifestLoadResult } from "./loadManifest.js"
22
+ import type { MessageInterceptor } from "./messageInterceptor.js"
22
23
  import {
23
24
  type MessageLogEntry,
24
25
  type QueryDataSourceArgs,
@@ -35,17 +36,17 @@ function getBridge(): SandboxBridge {
35
36
  }
36
37
 
37
38
  export const customBlockHost = {
38
- start: () => {
39
- getBridge().startListening()
39
+ registerMessageInterceptor: (
40
+ interceptor: MessageInterceptor,
41
+ ): (() => void) => {
42
+ return getBridge().registerMessageInterceptor(interceptor)
40
43
  },
41
44
 
42
45
  sendConnect: (manifestResult: ManifestLoadResult) => {
43
46
  getBridge().sendConnect(manifestResult)
44
47
  },
45
48
 
46
- awaitInit: (): Promise<void> => {
47
- return getBridge().awaitInit()
48
- },
49
+ initialize: () => getBridge().initialize(),
49
50
 
50
51
  subscribe: (listener: () => void) => {
51
52
  return getBridge().subscribe(listener)
package/src/bridge.ts ADDED
@@ -0,0 +1,17 @@
1
+ import type { MessageInterceptor } from "./bridge/messageInterceptor.js"
2
+ import { customBlockHost } from "./bridge/sandboxClient.js"
3
+
4
+ export type { MessageInterceptor } from "./bridge/messageInterceptor.js"
5
+
6
+ /**
7
+ * Add a handler for SDK messages sent to the host.
8
+ * Return a host message to replace an outgoing message.
9
+ * Return undefined to let other handlers inspect the message.
10
+ * The SDK sends the message to the host if no handler returns a response.
11
+ * Call the returned function to remove the handler.
12
+ */
13
+ export function registerMessageInterceptor(
14
+ interceptor: MessageInterceptor,
15
+ ): () => void {
16
+ return customBlockHost.registerMessageInterceptor(interceptor)
17
+ }
package/src/index.ts CHANGED
@@ -44,6 +44,7 @@ export {
44
44
  NOTION_PROPERTY_TYPES,
45
45
  } from "@notionhq/custom-blocks-protocol/dataSources/propertySchema.js"
46
46
  export type { NotionRecordPointer } from "@notionhq/custom-blocks-protocol/dataSources/recordPointer.js"
47
+ export type { NotionSortDirection } from "@notionhq/custom-blocks-protocol/dataSources/sortDirection.js"
47
48
  export type { CustomBlockErrorInfo } from "@notionhq/custom-blocks-protocol/errors.js"
48
49
  export type {
49
50
  NotionAgentId,
package/src/init.ts CHANGED
@@ -1,126 +1,15 @@
1
- import type { NotionContrastMode } from "@notionhq/custom-blocks-protocol/contrast.js"
2
- import type { NotionDataSource } from "@notionhq/custom-blocks-protocol/dataSources/dataSource.js"
3
- import type { NotionBlockId } from "@notionhq/custom-blocks-protocol/ids.js"
4
- import { CustomBlockInitializationError } from "@notionhq/custom-blocks-protocol/messages/init.js"
5
- import type { CustomBlockPage } from "@notionhq/custom-blocks-protocol/pages/page.js"
6
- import type { NotionParent } from "@notionhq/custom-blocks-protocol/parent.js"
7
- import type { NotionTheme } from "@notionhq/custom-blocks-protocol/theme.js"
8
- import type { NotionUser } from "@notionhq/custom-blocks-protocol/users/user.js"
9
- import { attemptToLoadSelfHostedManifest } from "./bridge/loadManifest.js"
10
1
  import { customBlockHost } from "./bridge/sandboxClient.js"
11
- import { unreachable } from "./utils.js"
2
+ import type { CustomBlockInitPayload } from "./initTypes.js"
12
3
 
13
- /**
14
- * The payload sent by the host in the `init` message in response to the sandbox's `connect` message.
15
- */
16
- export type CustomBlockInitPayload = {
17
- theme: NotionTheme
18
- contrastMode: NotionContrastMode
19
- blockId: NotionBlockId
20
- parent: NotionParent
21
- page: CustomBlockPage
22
- currentUser: NotionUser
23
- dataSources: NotionDataSource[]
24
- }
4
+ export {
5
+ type CustomBlockInitPayload,
6
+ NotInIframeError,
7
+ } from "./initTypes.js"
25
8
 
26
9
  /**
27
- * Error thrown when the SDK is loaded in a top-level standalone window with no parent frame.
28
- * `postMessage` would just hit the same window and the handshake can never complete.
29
- * `<NotionCustomBlock>` catches this specifically and falls back to a standalone preview with a
30
- * warning banner. Direct callers can `instanceof` it to apply their own policy.
31
- */
32
- export class NotInIframeError extends CustomBlockInitializationError {
33
- constructor(message: string = NOT_IN_IFRAME_MESSAGE) {
34
- super({
35
- code: "not_in_iframe",
36
- message,
37
- isRetryable: false,
38
- })
39
- this.name = "NotInIframeError"
40
- }
41
-
42
- declare code: "not_in_iframe"
43
- }
44
-
45
- const NOT_IN_IFRAME_MESSAGE =
46
- "<NotionCustomBlock> only works inside an iframe — use the dev shell or deploy to Notion."
47
-
48
- let initPromise: Promise<CustomBlockInitPayload> | undefined
49
-
50
- /**
51
- * Initializes the custom block by running the SDK <-> host handshake.
52
- *
53
- * Resolves with the block's initial context (theme, block location, current
54
- * user, data sources) once the host has initialized the block. Rejects with a
55
- * `CustomBlockInitializationError` if initialization fails.
56
- *
57
- * Idempotent: subsequent calls return the same promise as the first.
58
- * Mount your React tree (or call any SDK hook) only after the returned promise resolves.
10
+ * Initializes the block once. Later calls reuse the first promise.
11
+ * Await this promise before reading initialized state or mounting SDK hooks.
59
12
  */
60
13
  export function initCustomBlock(): Promise<CustomBlockInitPayload> {
61
- if (initPromise === undefined) {
62
- customBlockHost.start()
63
- initPromise = performHandshake()
64
- }
65
- return initPromise
66
- }
67
-
68
- /**
69
- * Performs the host <-> sandbox SDK handshake:
70
- * 1. On localhost, attempts to load the worker manifest from the page-relative
71
- * `manifest` path
72
- * 2. Sends `connect` with the manifest
73
- * 3. Awaits the host's `init` message
74
- * 4. Applies the `init` payload and acknowledges with `initResult` (fire-and-forget)
75
- *
76
- * Resolves with the `init` payload after the process above. Rejects with a
77
- * `CustomBlockInitializationError` if any step fails.
78
- */
79
- async function performHandshake(): Promise<CustomBlockInitPayload> {
80
- try {
81
- // Fail fast with a typed error when rendered as a standalone tab and not in a parent frame.
82
- // Otherwise, `postMessage` to `window.parent` would just hit the same window and never
83
- // arrive.
84
- if (typeof window !== "undefined" && window.parent === window) {
85
- throw new NotInIframeError()
86
- }
87
-
88
- // Load the manifest and send it to the host.
89
- const manifestResult = await attemptToLoadSelfHostedManifest()
90
- customBlockHost.sendConnect(manifestResult)
91
-
92
- await customBlockHost.awaitInit()
93
-
94
- const hostState = customBlockHost.getState()
95
- switch (hostState.status) {
96
- case "initialized":
97
- return {
98
- theme: hostState.theme,
99
- contrastMode: hostState.contrastMode,
100
- blockId: hostState.blockId,
101
- parent: hostState.parent,
102
- page: hostState.page,
103
- currentUser: hostState.currentUser,
104
- dataSources: hostState.dataSources,
105
- }
106
- case "uninitialized":
107
- throw new CustomBlockInitializationError({
108
- code: "context_unavailable",
109
- message: "Host block payload is unavailable.",
110
- isRetryable: true,
111
- })
112
- default:
113
- return unreachable(hostState)
114
- }
115
- } catch (error) {
116
- if (error instanceof CustomBlockInitializationError) {
117
- throw error
118
- }
119
- const message = error instanceof Error ? error.message : String(error)
120
- throw new CustomBlockInitializationError({
121
- code: "unknown_error",
122
- message,
123
- isRetryable: false,
124
- })
125
- }
14
+ return customBlockHost.initialize()
126
15
  }
@@ -0,0 +1,43 @@
1
+ import type { NotionContrastMode } from "@notionhq/custom-blocks-protocol/contrast.js"
2
+ import type { NotionDataSource } from "@notionhq/custom-blocks-protocol/dataSources/dataSource.js"
3
+ import type { NotionBlockId } from "@notionhq/custom-blocks-protocol/ids.js"
4
+ import { CustomBlockInitializationError } from "@notionhq/custom-blocks-protocol/messages/init.js"
5
+ import type { CustomBlockPage } from "@notionhq/custom-blocks-protocol/pages/page.js"
6
+ import type { NotionParent } from "@notionhq/custom-blocks-protocol/parent.js"
7
+ import type { NotionTheme } from "@notionhq/custom-blocks-protocol/theme.js"
8
+ import type { NotionUser } from "@notionhq/custom-blocks-protocol/users/user.js"
9
+
10
+ /**
11
+ * Initial context returned by `initCustomBlock()`.
12
+ */
13
+ export type CustomBlockInitPayload = {
14
+ theme: NotionTheme
15
+ contrastMode: NotionContrastMode
16
+ blockId: NotionBlockId
17
+ parent: NotionParent
18
+ page: CustomBlockPage
19
+ currentUser: NotionUser
20
+ dataSources: NotionDataSource[]
21
+ }
22
+
23
+ /**
24
+ * Error thrown when the SDK is loaded in a top-level standalone window with no parent frame.
25
+ * `postMessage` would just hit the same window and the handshake can never complete.
26
+ * `<NotionCustomBlock>` catches this specifically and falls back to a standalone preview with a
27
+ * warning banner. Direct callers can `instanceof` it to apply their own policy.
28
+ */
29
+ export class NotInIframeError extends CustomBlockInitializationError {
30
+ constructor(message: string = NOT_IN_IFRAME_MESSAGE) {
31
+ super({
32
+ code: "not_in_iframe",
33
+ message,
34
+ isRetryable: false,
35
+ })
36
+ this.name = "NotInIframeError"
37
+ }
38
+
39
+ declare code: "not_in_iframe"
40
+ }
41
+
42
+ const NOT_IN_IFRAME_MESSAGE =
43
+ "Custom block initialization requires a Notion host. For local development, open the block in the dev shell. Otherwise, deploy it to Notion."