@notionhq/custom-blocks 0.0.79 → 0.1.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.
@@ -1,158 +0,0 @@
1
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import { resolve as resolvePath } from "node:path";
3
- import { NOTION_BUILTIN_PROPERTY_IDS } from "../src/bridge/dataSources/propertySchema.js";
4
- import { extractId, formatUuid } from "./ids.js";
5
- import { loginHintCommand, ntnApi } from "./ntn.js";
6
- import { mergeTarget, readTarget, writeTarget } from "./target.js";
7
- const MANIFEST_FILENAME = "custom_blocks.json";
8
- const BUILTIN_TYPES = new Set(NOTION_BUILTIN_PROPERTY_IDS);
9
- // ── Helpers ───────────────────────────────────────────────────────
10
- function deriveKey(name) {
11
- return name
12
- .toLowerCase()
13
- .replace(/\s+/g, "_")
14
- .replace(/[^a-z0-9_]/g, "");
15
- }
16
- function plainText(items) {
17
- if (!items?.length) {
18
- return "Data source";
19
- }
20
- return items.map(t => t.plain_text ?? "").join("") || "Data source";
21
- }
22
- function is404(error) {
23
- return error instanceof Error && error.message.includes("404");
24
- }
25
- // ── Schema transform ─────────────────────────────────────────────
26
- function transformProperties(props) {
27
- const out = {};
28
- for (const prop of Object.values(props)) {
29
- if (BUILTIN_TYPES.has(prop.type)) {
30
- continue;
31
- }
32
- const key = deriveKey(prop.name);
33
- if (key) {
34
- out[key] = { name: prop.name, type: prop.type };
35
- }
36
- }
37
- return out;
38
- }
39
- function fetchDataSource(dataSourceId, quiet) {
40
- const id = formatUuid(dataSourceId);
41
- if (!quiet) {
42
- console.log(` Fetching data source ${id}…`);
43
- }
44
- const ds = ntnApi(`/v1/data_sources/${id}`);
45
- if (!ds.properties || Object.keys(ds.properties).length === 0) {
46
- throw new Error(`Data source ${id} has no properties.`);
47
- }
48
- return {
49
- dataSourceId: id,
50
- name: plainText(ds.title),
51
- properties: transformProperties(ds.properties),
52
- };
53
- }
54
- /**
55
- * Pull schema from a database or data source ID. Tries `/v1/databases/<id>`
56
- * first (most common entry point); falls back to `/v1/data_sources/<id>` if
57
- * that 404s. ID-type classification (block / view / database / wrong-workspace)
58
- * happens upstream in `init.ts` — by the time we get here, the ID is expected
59
- * to point at a database or data source.
60
- */
61
- function fetchSchema(id, quiet) {
62
- const uuid = formatUuid(id);
63
- let dbError;
64
- try {
65
- if (!quiet) {
66
- console.log(` Fetching database ${uuid}…`);
67
- }
68
- const db = ntnApi(`/v1/databases/${uuid}`);
69
- if (db.object === "database") {
70
- if (!db.data_sources?.length) {
71
- throw new Error(`Database ${uuid} has no data sources. Confirm you're logged in to the right workspace with \`${loginHintCommand()}\`.`);
72
- }
73
- return fetchDataSource(db.data_sources[0].id, quiet);
74
- }
75
- }
76
- catch (error) {
77
- if (!is404(error)) {
78
- throw error;
79
- }
80
- dbError = error;
81
- }
82
- try {
83
- return fetchDataSource(uuid, quiet);
84
- }
85
- catch (error) {
86
- if (!is404(error)) {
87
- throw error;
88
- }
89
- }
90
- throw new Error(dbError instanceof Error
91
- ? `${uuid} isn't a database or data source. Confirm you're logged in to the right workspace with \`${loginHintCommand()}\`.`
92
- : `${uuid} isn't a database or data source.`);
93
- }
94
- export function pullManifest(options) {
95
- const { idOrUrl, key = "default", out = MANIFEST_FILENAME, dryRun = false, quiet = false, } = options;
96
- const outPath = resolvePath(process.cwd(), out);
97
- const id = extractId(idOrUrl);
98
- if (quiet) {
99
- console.log("\nPulling data source schema…");
100
- }
101
- else {
102
- console.log(`\nResolving ${idOrUrl}…\n`);
103
- }
104
- const result = fetchSchema(id, quiet);
105
- const entry = {
106
- name: result.name,
107
- properties: result.properties,
108
- };
109
- // Read existing manifest or start fresh. The entry for `key` is fully
110
- // replaced so stale properties are automatically removed.
111
- let manifest;
112
- if (existsSync(outPath)) {
113
- try {
114
- const existing = JSON.parse(readFileSync(outPath, "utf-8"));
115
- manifest = { version: 1, dataSources: existing.dataSources ?? {} };
116
- }
117
- catch {
118
- manifest = { version: 1, dataSources: {} };
119
- }
120
- }
121
- else {
122
- manifest = { version: 1, dataSources: {} };
123
- }
124
- manifest.dataSources[key] = entry;
125
- const json = JSON.stringify(manifest, null, "\t") + "\n";
126
- if (dryRun) {
127
- console.log(json);
128
- return;
129
- }
130
- writeFileSync(outPath, json);
131
- // Stash the resolved data-source ID in .notion/target.json so `connect`
132
- // can wire the block without the user re-typing it. Don't touch block_id
133
- // or property_ids_by_key — init seeds block_id at scaffold time, and
134
- // `connect` fills in property_ids_by_key.
135
- const existingTarget = readTarget();
136
- const existingEntry = existingTarget?.data_sources[key];
137
- const merged = mergeTarget(existingTarget, {
138
- data_sources: {
139
- [key]: {
140
- data_source_id: result.dataSourceId,
141
- property_ids_by_key: existingEntry?.property_ids_by_key ?? {},
142
- },
143
- },
144
- });
145
- writeTarget(merged);
146
- const count = Object.keys(result.properties).length;
147
- if (quiet) {
148
- console.log(`Found database "${result.name}" (${count} properties)`);
149
- return;
150
- }
151
- console.log(`\n✓ Updated ${out} (key: "${key}")\n`);
152
- console.log(` → recorded data_source_id in .notion/target.json (${key})`);
153
- console.log(` ${count} properties from "${result.name}":`);
154
- for (const [k, p] of Object.entries(result.properties)) {
155
- console.log(` ${k}: ${p.name} (${p.type})`);
156
- }
157
- console.log("");
158
- }
package/bin/cli/target.js DELETED
@@ -1,95 +0,0 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { dirname, resolve as resolvePath } from "node:path";
3
- export const TARGET_PATH = ".notion/target.json";
4
- function defaultTarget() {
5
- return { env: "production", block_id: [], data_sources: {} };
6
- }
7
- export function resolveTargetPath(cwd = process.cwd()) {
8
- return resolvePath(cwd, TARGET_PATH);
9
- }
10
- export function readTarget(cwd = process.cwd()) {
11
- const path = resolveTargetPath(cwd);
12
- if (!existsSync(path)) {
13
- return null;
14
- }
15
- let raw;
16
- try {
17
- raw = readFileSync(path, "utf-8");
18
- }
19
- catch (error) {
20
- const message = error instanceof Error ? error.message : String(error);
21
- throw new Error(`Error: failed to read ${TARGET_PATH}: ${message}\n Check file permissions.`);
22
- }
23
- let parsed;
24
- try {
25
- parsed = JSON.parse(raw);
26
- }
27
- catch {
28
- throw new Error(`Error: ${TARGET_PATH} contains invalid JSON.\n Fix the syntax or delete the file to regenerate it with 'ncblock connect'.`);
29
- }
30
- return normalizeTarget(parsed);
31
- }
32
- export function writeTarget(config, cwd = process.cwd()) {
33
- const path = resolveTargetPath(cwd);
34
- mkdirSync(dirname(path), { recursive: true });
35
- writeFileSync(path, JSON.stringify(config, null, "\t") + "\n");
36
- }
37
- function normalizeTarget(value) {
38
- if (!isRecord(value)) {
39
- throw new Error(`Error: ${TARGET_PATH} must be a JSON object.\n Delete the file to regenerate it with 'ncblock connect'.`);
40
- }
41
- const env = typeof value.env === "string" ? value.env : "production";
42
- const block_id = [];
43
- if (Array.isArray(value.block_id)) {
44
- for (const entry of value.block_id) {
45
- if (typeof entry === "string" && entry.length > 0) {
46
- block_id.push(entry);
47
- }
48
- }
49
- }
50
- else if (typeof value.block_id === "string" && value.block_id.length > 0) {
51
- block_id.push(value.block_id);
52
- }
53
- const data_sources = {};
54
- if (isRecord(value.data_sources)) {
55
- for (const [key, ds] of Object.entries(value.data_sources)) {
56
- if (!isRecord(ds) || typeof ds.data_source_id !== "string") {
57
- continue;
58
- }
59
- const property_ids_by_key = {};
60
- if (isRecord(ds.property_ids_by_key)) {
61
- for (const [k, v] of Object.entries(ds.property_ids_by_key)) {
62
- if (typeof v === "string") {
63
- property_ids_by_key[k] = v;
64
- }
65
- }
66
- }
67
- data_sources[key] = {
68
- data_source_id: ds.data_source_id,
69
- property_ids_by_key,
70
- };
71
- }
72
- }
73
- return { env, block_id, data_sources };
74
- }
75
- /**
76
- * Merge a new partial target into the existing one. Block IDs from `incoming`
77
- * are appended (de-duplicated). Data source bindings replace any existing
78
- * binding for matching keys; unrelated keys are preserved.
79
- */
80
- export function mergeTarget(existing, incoming) {
81
- const base = existing ?? defaultTarget();
82
- const env = incoming.env ?? base.env;
83
- const blockIds = new Set(base.block_id);
84
- for (const id of incoming.block_id ?? []) {
85
- blockIds.add(id);
86
- }
87
- const data_sources = {
88
- ...base.data_sources,
89
- ...(incoming.data_sources ?? {}),
90
- };
91
- return { env, block_id: [...blockIds], data_sources };
92
- }
93
- function isRecord(value) {
94
- return value !== null && typeof value === "object" && !Array.isArray(value);
95
- }
@@ -1,148 +0,0 @@
1
- import * as v from "valibot";
2
- /**
3
- * Hex-token identifiers for Notion's named colors. Mirrors the public API's
4
- * `select.options[].color` enum
5
- * (https://developers.notion.com/reference/property-object#select).
6
- */
7
- export const notionPropertyColorSchema = v.picklist([
8
- "default",
9
- "gray",
10
- "brown",
11
- "orange",
12
- "yellow",
13
- "green",
14
- "blue",
15
- "purple",
16
- "pink",
17
- "red",
18
- "gray_background",
19
- "brown_background",
20
- "orange_background",
21
- "yellow_background",
22
- "green_background",
23
- "blue_background",
24
- "purple_background",
25
- "pink_background",
26
- "red_background",
27
- "default_background",
28
- ]);
29
- export const notionPropertyOptionSchema = v.object({
30
- id: v.string(),
31
- name: v.string(),
32
- color: v.optional(notionPropertyColorSchema),
33
- description: v.optional(v.string()),
34
- });
35
- export const notionStatusGroupSchema = v.object({
36
- id: v.string(),
37
- name: v.string(),
38
- color: v.optional(notionPropertyColorSchema),
39
- option_ids: v.array(v.string()),
40
- });
41
- export const notionDualPropertySchema = v.object({
42
- synced_property_id: v.string(),
43
- synced_property_name: v.string(),
44
- });
45
- const baseProp = v.object({
46
- name: v.string(),
47
- description: v.optional(v.string()),
48
- });
49
- /**
50
- * Every Notion property type the bridge speaks, in a single readable list.
51
- * Mirrors the Notion public API
52
- * [property object](https://developers.notion.com/reference/property-object)
53
- * type field. Internal-only types (`button`, `verification`,
54
- * `last_visited_time`, `location`) and the four built-ins (`created_time`,
55
- * `last_edited_time`, `created_by`, `last_edited_by`) are included under their
56
- * bridge-native names.
57
- */
58
- export const NOTION_PROPERTY_TYPES = [
59
- "title",
60
- "rich_text",
61
- "number",
62
- "checkbox",
63
- "url",
64
- "email",
65
- "phone_number",
66
- "select",
67
- "multi_select",
68
- "status",
69
- "date",
70
- "people",
71
- "files",
72
- "unique_id",
73
- "relation",
74
- "place",
75
- "formula",
76
- "rollup",
77
- "button",
78
- "verification",
79
- "last_visited_time",
80
- "location",
81
- "created_time",
82
- "last_edited_time",
83
- "created_by",
84
- "last_edited_by",
85
- ];
86
- export const notionPropertyTypeSchema = v.picklist(NOTION_PROPERTY_TYPES);
87
- /**
88
- * Per-property schema as exposed by the host over the custom-block bridge.
89
- * The `type` discriminator must be one of {@link NOTION_PROPERTY_TYPES}.
90
- */
91
- export const notionPropertySchemaSchema = v.variant("type", [
92
- v.object({ ...baseProp.entries, type: v.literal("title") }),
93
- v.object({ ...baseProp.entries, type: v.literal("rich_text") }),
94
- v.object({ ...baseProp.entries, type: v.literal("number") }),
95
- v.object({ ...baseProp.entries, type: v.literal("checkbox") }),
96
- v.object({ ...baseProp.entries, type: v.literal("url") }),
97
- v.object({ ...baseProp.entries, type: v.literal("email") }),
98
- v.object({ ...baseProp.entries, type: v.literal("phone_number") }),
99
- v.object({
100
- ...baseProp.entries,
101
- type: v.literal("select"),
102
- options: v.array(notionPropertyOptionSchema),
103
- }),
104
- v.object({
105
- ...baseProp.entries,
106
- type: v.literal("multi_select"),
107
- options: v.array(notionPropertyOptionSchema),
108
- }),
109
- v.object({
110
- ...baseProp.entries,
111
- type: v.literal("status"),
112
- options: v.array(notionPropertyOptionSchema),
113
- groups: v.array(notionStatusGroupSchema),
114
- }),
115
- v.object({ ...baseProp.entries, type: v.literal("date") }),
116
- v.object({ ...baseProp.entries, type: v.literal("people") }),
117
- v.object({ ...baseProp.entries, type: v.literal("files") }),
118
- v.object({ ...baseProp.entries, type: v.literal("unique_id") }),
119
- v.object({
120
- ...baseProp.entries,
121
- type: v.literal("relation"),
122
- data_source_id: v.optional(v.string()),
123
- dual_property: v.optional(notionDualPropertySchema),
124
- }),
125
- v.object({ ...baseProp.entries, type: v.literal("place") }),
126
- v.object({ ...baseProp.entries, type: v.literal("formula") }),
127
- v.object({ ...baseProp.entries, type: v.literal("rollup") }),
128
- // Internal-only types passed through under their bridge-native names.
129
- v.object({ ...baseProp.entries, type: v.literal("button") }),
130
- v.object({ ...baseProp.entries, type: v.literal("verification") }),
131
- v.object({ ...baseProp.entries, type: v.literal("last_visited_time") }),
132
- v.object({ ...baseProp.entries, type: v.literal("location") }),
133
- // Synthetic built-ins. The host always emits one of each per data source.
134
- v.object({ ...baseProp.entries, type: v.literal("created_time") }),
135
- v.object({ ...baseProp.entries, type: v.literal("last_edited_time") }),
136
- v.object({ ...baseProp.entries, type: v.literal("created_by") }),
137
- v.object({ ...baseProp.entries, type: v.literal("last_edited_by") }),
138
- ]);
139
- /**
140
- * The four synthetic built-in property IDs the host always includes in every
141
- * data source's `propertySchemasById` and every row's `propertiesById`.
142
- */
143
- export const NOTION_BUILTIN_PROPERTY_IDS = [
144
- "created_time",
145
- "last_edited_time",
146
- "created_by",
147
- "last_edited_by",
148
- ];
@@ -1,40 +0,0 @@
1
- import * as v from "valibot";
2
- import { notionPropertyTypeSchema } from "./dataSources/propertySchema.js";
3
- /**
4
- * User-authored manifest declaring the data sources the custom block expects.
5
- * Lives at `custom_blocks.json` in the project root. The sandbox may send it in
6
- * `connect`, and the host returns the authoritative manifest in `init`. The
7
- * `notionCustomBlock` Vite plugin from
8
- * `@notionhq/custom-blocks/vite` wires the JSON file into the dev server and
9
- * the build output.
10
- */
11
- /**
12
- * Decorative icon attached to a manifest data source. Mirrors the
13
- * `emoji` / `external` icon variants the public Notion API uses, so the host
14
- * can render a recognizable affordance next to the slot in setup UI.
15
- */
16
- export const manifestIconSchema = v.variant("type", [
17
- v.object({
18
- type: v.literal("emoji"),
19
- emoji: v.string(),
20
- }),
21
- v.object({
22
- type: v.literal("external"),
23
- url: v.string(),
24
- }),
25
- ]);
26
- export const manifestPropertySchema = v.object({
27
- name: v.string(),
28
- description: v.optional(v.string()),
29
- type: notionPropertyTypeSchema,
30
- });
31
- export const manifestDataSourceSchema = v.object({
32
- name: v.string(),
33
- description: v.optional(v.string()),
34
- icon: v.optional(manifestIconSchema),
35
- properties: v.optional(v.record(v.string(), manifestPropertySchema), {}),
36
- });
37
- export const manifestSchema = v.object({
38
- version: v.literal(1),
39
- dataSources: v.record(v.string(), manifestDataSourceSchema),
40
- });
package/docs/manifest.md DELETED
@@ -1,42 +0,0 @@
1
- # Manifest
2
-
3
- A custom block declares its required data sources in `custom_blocks.json` at the project root. Notion uses the manifest to know what semantic keys the block expects, what shape each property should be, and what to show when an admin is configuring the block.
4
-
5
- ```json
6
- {
7
- "version": 1,
8
- "dataSources": {
9
- "tasks": {
10
- "name": "Tasks",
11
- "description": "The collection of tasks to render",
12
- "properties": {
13
- "title": { "name": "Title", "type": "title" },
14
- "dueDate": { "name": "Due date", "type": "date" }
15
- }
16
- }
17
- }
18
- }
19
- ```
20
-
21
- `initCustomBlock()` fetches the manifest and forwards it with `connect`. The `notionCustomBlock()` Vite plugin from `@notionhq/custom-blocks/vite` serves it in dev and emits it into `dist/` on build. If the file is missing, the SDK omits `manifest` from `connect`. If the file is unavailable for another reason or invalid, the SDK sends `connect` with `status: "error"` and an `error` payload. The host returns its authoritative manifest in `init`. The SDK uses that manifest even when it differs from the manifest sent in `connect`.
22
-
23
- ## Vite plugin
24
-
25
- ```ts
26
- import { defineConfig } from "vite";
27
- import react from "@vitejs/plugin-react";
28
- import { notionCustomBlock } from "@notionhq/custom-blocks/vite";
29
-
30
- export default defineConfig({
31
- plugins: [react(), notionCustomBlock()],
32
- });
33
- ```
34
-
35
- In dev, the plugin serves `custom_blocks.json` from the project root so HMR + the SDK handshake see the same file. On `vite build`, it emits `custom_blocks.json` into `dist/` as a separate asset alongside the bundled HTML and JS.
36
-
37
- ## Types
38
-
39
- - `CustomBlockManifest` — the parsed shape of `custom_blocks.json`.
40
- - `ManifestDataSource` — a single entry in `dataSources` (name, description, properties).
41
- - `ManifestProperty` — a single property declaration inside a `ManifestDataSource`.
42
- - `ManifestIcon` — the icon variant accepted on a `ManifestDataSource`.