@jordancoin/notioncli 1.2.1 → 1.3.1

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.
package/bin/notion.js CHANGED
@@ -1,1621 +1,28 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  const { program } = require('commander');
4
- const { Client } = require('@notionhq/client');
5
- const fs = require('fs');
6
- const path = require('path');
7
- const helpers = require('../lib/helpers');
8
-
9
- // ─── Config file system ────────────────────────────────────────────────────────
10
-
11
- const { CONFIG_DIR, CONFIG_PATH } = helpers.getConfigPaths();
12
-
13
- function loadConfig() {
14
- return helpers.loadConfig(CONFIG_PATH);
15
- }
16
-
17
- function saveConfig(config) {
18
- helpers.saveConfig(config, CONFIG_DIR, CONFIG_PATH);
19
- }
20
-
21
- /**
22
- * Get the active workspace name from --workspace flag or config.
23
- */
24
- function getWorkspaceName() {
25
- return program.opts().workspace || undefined;
26
- }
27
-
28
- /**
29
- * Get the active workspace config { apiKey, aliases, name }.
30
- */
31
- function getWorkspaceConfig() {
32
- const config = loadConfig();
33
- const ws = helpers.resolveWorkspace(config, getWorkspaceName());
34
- if (ws.error) {
35
- console.error(`Error: ${ws.error}`);
36
- if (ws.available && ws.available.length > 0) {
37
- console.error(`Available workspaces: ${ws.available.join(', ')}`);
38
- }
39
- process.exit(1);
40
- }
41
- return ws;
42
- }
43
-
44
- /**
45
- * Resolve API key: env var → workspace config → error with setup instructions
46
- */
47
- function getApiKey() {
48
- if (process.env.NOTION_API_KEY) return process.env.NOTION_API_KEY;
49
- const ws = getWorkspaceConfig();
50
- if (ws.apiKey) return ws.apiKey;
51
- console.error('Error: No Notion API key found.');
52
- console.error('');
53
- console.error('Set it up with one of:');
54
- console.error(' 1. notion init --key ntn_your_api_key');
55
- console.error(' 2. export NOTION_API_KEY=ntn_your_api_key');
56
- console.error('');
57
- console.error('Get a key at: https://www.notion.so/profile/integrations');
58
- process.exit(1);
59
- }
60
-
61
- /**
62
- * Resolve a user-given alias or UUID to { database_id, data_source_id }.
63
- * If given a raw UUID, we use it for both IDs (the SDK figures it out).
64
- */
65
- function resolveDb(aliasOrId) {
66
- const ws = getWorkspaceConfig();
67
- if (ws.aliases && ws.aliases[aliasOrId]) {
68
- return ws.aliases[aliasOrId];
69
- }
70
- if (UUID_REGEX.test(aliasOrId)) {
71
- return { database_id: aliasOrId, data_source_id: aliasOrId };
72
- }
73
- const aliasNames = ws.aliases ? Object.keys(ws.aliases) : [];
74
- console.error(`Unknown database alias: "${aliasOrId}"`);
75
- if (aliasNames.length > 0) {
76
- console.error(`Available aliases: ${aliasNames.join(', ')}`);
77
- } else {
78
- console.error('No aliases configured. Add one with: notion alias add <name> <database-id>');
79
- }
80
- process.exit(1);
81
- }
82
-
83
- /**
84
- * Resolve alias + filter → page ID, or pass through a raw UUID.
85
- * Used by update, delete, get, blocks, comments, comment, append.
86
- *
87
- * Returns { pageId, dbIds } where dbIds is non-null when resolved via alias.
88
- */
89
- async function resolvePageId(aliasOrId, filterStr) {
90
- const ws = getWorkspaceConfig();
91
- if (ws.aliases && ws.aliases[aliasOrId]) {
92
- if (!filterStr) {
93
- console.error('When using an alias, --filter is required to identify a specific page.');
94
- console.error(`Example: notion update ${aliasOrId} --filter "Name=My Page" --prop "Status=Done"`);
95
- process.exit(1);
96
- }
97
- const dbIds = ws.aliases[aliasOrId];
98
- const notion = getNotion();
99
- const filter = await buildFilter(dbIds, filterStr);
100
- const res = await notion.dataSources.query({
101
- data_source_id: dbIds.data_source_id,
102
- filter,
103
- page_size: 5,
104
- });
105
- if (res.results.length === 0) {
106
- console.error('No matching page found.');
107
- process.exit(1);
108
- }
109
- if (res.results.length > 1) {
110
- console.error(`Multiple pages match (${res.results.length}). Use a more specific filter or pass a page ID directly.`);
111
- const rows = pagesToRows(res.results);
112
- const cols = Object.keys(rows[0]).slice(0, 4);
113
- printTable(rows, cols);
114
- process.exit(1);
115
- }
116
- return { pageId: res.results[0].id, dbIds };
117
- }
118
- // Check if it looks like a UUID — if not, it's probably a typo'd alias
119
- if (!UUID_REGEX.test(aliasOrId)) {
120
- const aliasNames = ws.aliases ? Object.keys(ws.aliases) : [];
121
- console.error(`Unknown alias: "${aliasOrId}"`);
122
- if (aliasNames.length > 0) {
123
- console.error(`Available aliases: ${aliasNames.join(', ')}`);
124
- } else {
125
- console.error('No aliases configured. Run: notion init --key <your-api-key>');
126
- }
127
- process.exit(1);
128
- }
129
- // Treat as raw page ID
130
- return { pageId: aliasOrId, dbIds: null };
131
- }
132
-
133
- // ─── Lazy Notion client ────────────────────────────────────────────────────────
134
-
135
- let _notion = null;
136
- function getNotion() {
137
- if (!_notion) {
138
- _notion = new Client({ auth: getApiKey() });
139
- }
140
- return _notion;
141
- }
142
-
143
- // ─── Helpers (imported from lib/helpers.js) ────────────────────────────────────
144
-
145
- const {
146
- richTextToPlain,
147
- propValue,
148
- buildPropValue,
149
- printTable,
150
- pagesToRows,
151
- formatCsv,
152
- formatYaml,
153
- outputFormatted,
154
- buildFilterFromSchema,
155
- UUID_REGEX,
156
- } = helpers;
157
-
158
- /** Check if --json flag is set anywhere in the command chain */
159
- function getGlobalJson(cmd) {
160
- let c = cmd;
161
- while (c) {
162
- if (c.opts().json) return true;
163
- c = c.parent;
164
- }
165
- return false;
166
- }
167
-
168
- /**
169
- * Fetch data source schema — returns map of lowercase_name → { type, name }
170
- * Uses dataSources.retrieve() which accepts the data_source_id.
171
- */
172
- async function getDbSchema(dbIds) {
173
- const notion = getNotion();
174
- const dsId = dbIds.data_source_id;
175
- const ds = await notion.dataSources.retrieve({ data_source_id: dsId });
176
- const schema = {};
177
- for (const [name, prop] of Object.entries(ds.properties)) {
178
- schema[name.toLowerCase()] = { type: prop.type, name };
179
- }
180
- return schema;
181
- }
182
-
183
- /** Build properties object from --prop key=value pairs using schema */
184
- async function buildProperties(dbIds, props) {
185
- const schema = await getDbSchema(dbIds);
186
- const properties = {};
187
-
188
- for (const kv of props) {
189
- const eqIdx = kv.indexOf('=');
190
- if (eqIdx === -1) {
191
- console.error(`Invalid property format: ${kv} (expected key=value)`);
192
- process.exit(1);
193
- }
194
- const key = kv.slice(0, eqIdx);
195
- const value = kv.slice(eqIdx + 1);
196
-
197
- const schemaEntry = schema[key.toLowerCase()];
198
- if (!schemaEntry) {
199
- console.error(`Property "${key}" not found in database schema.`);
200
- console.error(`Available: ${Object.values(schema).map(s => s.name).join(', ')}`);
201
- process.exit(1);
202
- }
203
-
204
- properties[schemaEntry.name] = buildPropValue(schemaEntry.type, value);
205
- }
206
-
207
- return properties;
208
- }
209
-
210
- /** Parse filter string key=value into a Notion filter object */
211
- async function buildFilter(dbIds, filterStr) {
212
- const schema = await getDbSchema(dbIds);
213
- const result = buildFilterFromSchema(schema, filterStr);
214
- if (result.error) {
215
- console.error(result.error);
216
- if (result.available) {
217
- console.error(`Available: ${result.available.join(', ')}`);
218
- }
219
- process.exit(1);
220
- }
221
- return result.filter;
222
- }
223
-
224
- // ─── Commands ──────────────────────────────────────────────────────────────────
4
+ const { createContext } = require('../lib/context');
225
5
 
226
6
  program
227
7
  .name('notion')
228
8
  .description('A powerful CLI for the Notion API — query databases, manage pages, and automate your workspace from the terminal.')
229
- .version('1.2.0')
9
+ .version('1.3.1')
230
10
  .option('--json', 'Output raw JSON instead of formatted tables')
231
11
  .option('-w, --workspace <name>', 'Use a specific workspace profile');
232
12
 
233
- // ─── init ──────────────────────────────────────────────────────────────────────
234
- program
235
- .command('init')
236
- .description('Initialize notioncli with your API key and discover databases')
237
- .option('--key <api-key>', 'Notion integration API key (starts with ntn_)')
238
- .action(async (opts) => {
239
- const config = loadConfig();
240
- const wsName = getWorkspaceName() || config.activeWorkspace || 'default';
241
- const apiKey = opts.key || process.env.NOTION_API_KEY;
242
-
243
- if (!apiKey) {
244
- console.error('Error: Provide an API key with --key or set NOTION_API_KEY env var.');
245
- console.error('');
246
- console.error('To create an integration:');
247
- console.error(' 1. Go to https://www.notion.so/profile/integrations');
248
- console.error(' 2. Click "New integration"');
249
- console.error(' 3. Copy the API key (starts with ntn_)');
250
- console.error(' 4. Share your databases with the integration');
251
- console.error('');
252
- console.error('Then run: notion init --key ntn_your_api_key');
253
- console.error(' Or with workspace: notion init --workspace work --key ntn_your_api_key');
254
- process.exit(1);
255
- }
256
-
257
- if (!config.workspaces) config.workspaces = {};
258
- if (!config.workspaces[wsName]) config.workspaces[wsName] = { aliases: {} };
259
- config.workspaces[wsName].apiKey = apiKey;
260
- config.activeWorkspace = wsName;
261
- saveConfig(config);
262
- console.log(`✅ API key saved to workspace "${wsName}" in ${CONFIG_PATH}`);
263
- console.log('');
264
-
265
- // Discover databases
266
- const notion = new Client({ auth: apiKey });
267
- try {
268
- const res = await notion.search({
269
- filter: { value: 'data_source', property: 'object' },
270
- page_size: 100,
271
- });
272
-
273
- if (res.results.length === 0) {
274
- console.log('No databases found. Make sure you\'ve shared databases with your integration.');
275
- console.log('In Notion: open a database → ••• menu → Connections → Add your integration');
276
- return;
277
- }
278
-
279
- const aliases = config.workspaces[wsName].aliases || {};
280
-
281
- console.log(`Found ${res.results.length} database${res.results.length !== 1 ? 's' : ''}:\n`);
282
-
283
- const added = [];
284
- for (const db of res.results) {
285
- const title = richTextToPlain(db.title) || '';
286
- const dsId = db.id;
287
- const dbId = (db.parent && db.parent.type === 'database_id' && db.parent.database_id) || db.database_id || dsId;
288
-
289
- // Auto-generate a slug from the title
290
- let slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 30);
291
- if (!slug) slug = `db-${dsId.slice(0, 8)}`;
292
-
293
- // Avoid collisions — append a number if needed
294
- let finalSlug = slug;
295
- let counter = 2;
296
- while (aliases[finalSlug] && aliases[finalSlug].data_source_id !== dsId) {
297
- finalSlug = `${slug}-${counter}`;
298
- counter++;
299
- }
300
-
301
- aliases[finalSlug] = {
302
- database_id: dbId,
303
- data_source_id: dsId,
304
- };
305
-
306
- console.log(` ✅ ${finalSlug.padEnd(25)} → ${title || '(untitled)'}`);
307
- added.push(finalSlug);
308
- }
309
-
310
- config.workspaces[wsName].aliases = aliases;
311
- saveConfig(config);
312
- console.log('');
313
- console.log(`${added.length} alias${added.length !== 1 ? 'es' : ''} saved to workspace "${wsName}".`);
314
- console.log('');
315
- console.log('Ready! Try:');
316
- if (added.length > 0) {
317
- console.log(` notion query ${added[0]}`);
318
- console.log(` notion add ${added[0]} --prop "Name=Hello World"`);
319
- }
320
- console.log('');
321
- console.log('Manage aliases:');
322
- console.log(' notion alias list — see all aliases');
323
- console.log(' notion alias rename <old> <new> — rename an alias');
324
- console.log(' notion alias remove <name> — remove an alias');
325
- } catch (err) {
326
- console.error(`Failed to discover databases: ${err.message}`);
327
- console.error('Your API key was saved. You can add databases manually with: notion alias add <name> <id>');
328
- }
329
- });
330
-
331
- // ─── alias ─────────────────────────────────────────────────────────────────────
332
- const alias = program
333
- .command('alias')
334
- .description('Manage database aliases for quick access');
335
-
336
- alias
337
- .command('add <name> <database-id>')
338
- .description('Add a database alias (auto-discovers data_source_id)')
339
- .action(async (name, databaseId) => {
340
- const config = loadConfig();
341
- const wsName = getWorkspaceName() || config.activeWorkspace || 'default';
342
- if (!config.workspaces[wsName]) config.workspaces[wsName] = { aliases: {} };
343
- const aliases = config.workspaces[wsName].aliases || {};
344
-
345
- // Try to discover the data_source_id by searching for this database
346
- const notion = getNotion();
347
- let dataSourceId = databaseId;
348
-
349
- try {
350
- const res = await notion.search({
351
- filter: { value: 'data_source', property: 'object' },
352
- page_size: 100,
353
- });
354
-
355
- const match = res.results.find(db => {
356
- // Match by data_source_id or database_id
357
- return db.id === databaseId ||
358
- db.id.replace(/-/g, '') === databaseId.replace(/-/g, '');
359
- });
360
-
361
- if (match) {
362
- dataSourceId = match.id;
363
- // The database_id might differ from data_source_id — check parent
364
- const dbId = (match.parent && match.parent.type === 'database_id' && match.parent.database_id) || match.database_id || databaseId;
365
- aliases[name] = {
366
- database_id: dbId,
367
- data_source_id: dataSourceId,
368
- };
369
- const title = richTextToPlain(match.title) || '(untitled)';
370
- console.log(`✅ Added alias "${name}" → ${title}`);
371
- console.log(` database_id: ${dbId}`);
372
- console.log(` data_source_id: ${dataSourceId}`);
373
- } else {
374
- // Couldn't find via search — use the ID for both
375
- aliases[name] = {
376
- database_id: databaseId,
377
- data_source_id: databaseId,
378
- };
379
- console.log(`✅ Added alias "${name}" → ${databaseId}`);
380
- console.log(' (Could not auto-discover data_source_id — using same ID for both)');
381
- }
382
- } catch (err) {
383
- // Fallback: use same ID for both
384
- aliases[name] = {
385
- database_id: databaseId,
386
- data_source_id: databaseId,
387
- };
388
- console.log(`✅ Added alias "${name}" → ${databaseId}`);
389
- console.log(` (Auto-discovery failed: ${err.message})`);
390
- }
391
-
392
- config.workspaces[wsName].aliases = aliases;
393
- saveConfig(config);
394
- });
395
-
396
- alias
397
- .command('list')
398
- .description('Show all configured database aliases')
399
- .action(() => {
400
- const ws = getWorkspaceConfig();
401
- const aliases = ws.aliases || {};
402
- const names = Object.keys(aliases);
403
-
404
- if (names.length === 0) {
405
- console.log(`No aliases in workspace "${ws.name}".`);
406
- console.log('Add one with: notion alias add <name> <database-id>');
407
- return;
408
- }
409
-
410
- console.log(`Workspace: ${ws.name}\n`);
411
- const rows = names.map(name => ({
412
- alias: name,
413
- database_id: aliases[name].database_id,
414
- data_source_id: aliases[name].data_source_id,
415
- }));
416
- printTable(rows, ['alias', 'database_id', 'data_source_id']);
417
- });
418
-
419
- alias
420
- .command('remove <name>')
421
- .description('Remove a database alias')
422
- .action((name) => {
423
- const config = loadConfig();
424
- const wsName = getWorkspaceName() || config.activeWorkspace || 'default';
425
- const aliases = config.workspaces[wsName]?.aliases || {};
426
- if (!aliases[name]) {
427
- console.error(`Alias "${name}" not found in workspace "${wsName}".`);
428
- const names = Object.keys(aliases);
429
- if (names.length > 0) {
430
- console.error(`Available: ${names.join(', ')}`);
431
- }
432
- process.exit(1);
433
- }
434
- delete aliases[name];
435
- config.workspaces[wsName].aliases = aliases;
436
- saveConfig(config);
437
- console.log(`✅ Removed alias "${name}" from workspace "${wsName}"`);
438
- });
439
-
440
- alias
441
- .command('rename <old-name> <new-name>')
442
- .description('Rename a database alias')
443
- .action((oldName, newName) => {
444
- const config = loadConfig();
445
- const wsName = getWorkspaceName() || config.activeWorkspace || 'default';
446
- const aliases = config.workspaces[wsName]?.aliases || {};
447
- if (!aliases[oldName]) {
448
- console.error(`Alias "${oldName}" not found in workspace "${wsName}".`);
449
- const names = Object.keys(aliases);
450
- if (names.length > 0) {
451
- console.error(`Available: ${names.join(', ')}`);
452
- }
453
- process.exit(1);
454
- }
455
- if (aliases[newName]) {
456
- console.error(`Alias "${newName}" already exists. Remove it first or pick a different name.`);
457
- process.exit(1);
458
- }
459
- aliases[newName] = aliases[oldName];
460
- delete aliases[oldName];
461
- config.workspaces[wsName].aliases = aliases;
462
- saveConfig(config);
463
- console.log(`✅ Renamed "${oldName}" → "${newName}" in workspace "${wsName}"`);
464
- });
465
-
466
- // ─── workspace ─────────────────────────────────────────────────────────────────
467
- const workspace = program
468
- .command('workspace')
469
- .description('Manage workspace profiles (multiple Notion accounts)');
470
-
471
- workspace
472
- .command('add <name>')
473
- .description('Add a new workspace profile')
474
- .requiredOption('--key <api-key>', 'Notion API key for this workspace')
475
- .action(async (name, opts) => {
476
- const config = loadConfig();
477
- if (config.workspaces[name]) {
478
- console.error(`Workspace "${name}" already exists. Use "notion init --workspace ${name} --key ..." to update it.`);
479
- process.exit(1);
480
- }
481
- config.workspaces[name] = { apiKey: opts.key, aliases: {} };
482
- saveConfig(config);
483
- console.log(`✅ Added workspace "${name}"`);
484
- console.log('');
485
- console.log(`Discover databases: notion init --workspace ${name}`);
486
- console.log(`Or set as active: notion workspace use ${name}`);
487
- });
488
-
489
- workspace
490
- .command('list')
491
- .description('List all workspace profiles')
492
- .action(() => {
493
- const config = loadConfig();
494
- const names = Object.keys(config.workspaces || {});
495
- if (names.length === 0) {
496
- console.log('No workspaces configured. Run: notion init --key ntn_...');
497
- return;
498
- }
499
- for (const name of names) {
500
- const ws = config.workspaces[name];
501
- const active = name === config.activeWorkspace ? ' ← active' : '';
502
- const aliasCount = Object.keys(ws.aliases || {}).length;
503
- const keyPreview = ws.apiKey ? `${ws.apiKey.slice(0, 8)}...` : '(no key)';
504
- console.log(` ${name}${active}`);
505
- console.log(` Key: ${keyPreview} | Aliases: ${aliasCount}`);
506
- }
507
- });
508
-
509
- workspace
510
- .command('use <name>')
511
- .description('Set the active workspace')
512
- .action((name) => {
513
- const config = loadConfig();
514
- if (!config.workspaces[name]) {
515
- console.error(`Workspace "${name}" not found.`);
516
- const names = Object.keys(config.workspaces || {});
517
- if (names.length > 0) {
518
- console.error(`Available: ${names.join(', ')}`);
519
- }
520
- process.exit(1);
521
- }
522
- config.activeWorkspace = name;
523
- saveConfig(config);
524
- console.log(`✅ Active workspace: ${name}`);
525
- });
526
-
527
- workspace
528
- .command('remove <name>')
529
- .description('Remove a workspace profile')
530
- .action((name) => {
531
- const config = loadConfig();
532
- if (!config.workspaces[name]) {
533
- console.error(`Workspace "${name}" not found.`);
534
- process.exit(1);
535
- }
536
- if (name === config.activeWorkspace) {
537
- console.error(`Cannot remove the active workspace. Switch first: notion workspace use <other>`);
538
- process.exit(1);
539
- }
540
- delete config.workspaces[name];
541
- saveConfig(config);
542
- console.log(`✅ Removed workspace "${name}"`);
543
- });
544
-
545
- // ─── search ────────────────────────────────────────────────────────────────────
546
- program
547
- .command('search <query>')
548
- .description('Search across all pages and databases shared with your integration')
549
- .action(async (query, opts, cmd) => {
550
- try {
551
- const notion = getNotion();
552
- const res = await notion.search({ query, page_size: 20 });
553
- if (getGlobalJson(cmd)) {
554
- console.log(JSON.stringify(res, null, 2));
555
- return;
556
- }
557
- const rows = res.results.map(r => {
558
- let title = '';
559
- if (r.object === 'data_source' || r.object === 'database') {
560
- title = richTextToPlain(r.title);
561
- } else if (r.properties) {
562
- for (const [, prop] of Object.entries(r.properties)) {
563
- if (prop.type === 'title') {
564
- title = propValue(prop);
565
- break;
566
- }
567
- }
568
- }
569
- return {
570
- id: r.id,
571
- type: r.object,
572
- title: title || '(untitled)',
573
- url: r.url || '',
574
- };
575
- });
576
- printTable(rows, ['id', 'type', 'title', 'url']);
577
- } catch (err) {
578
- console.error('Search failed:', err.message);
579
- process.exit(1);
580
- }
581
- });
582
-
583
- // ─── query ─────────────────────────────────────────────────────────────────────
584
- program
585
- .command('query <database>')
586
- .description('Query a database by alias or ID (e.g. notion query projects --filter Status=Active)')
587
- .option('--filter <key=value>', 'Filter by property (e.g. Status=Active)')
588
- .option('--sort <key:direction>', 'Sort by property (e.g. Date:desc)')
589
- .option('--limit <n>', 'Max results (default: 100, max: 100)', '100')
590
- .option('--output <format>', 'Output format: table, csv, json, yaml (default: table)')
591
- .action(async (db, opts, cmd) => {
592
- try {
593
- const notion = getNotion();
594
- const dbIds = resolveDb(db);
595
- const params = {
596
- data_source_id: dbIds.data_source_id,
597
- page_size: Math.min(parseInt(opts.limit), 100),
598
- };
599
-
600
- if (opts.filter) {
601
- params.filter = await buildFilter(dbIds, opts.filter);
602
- }
603
-
604
- if (opts.sort) {
605
- const [key, dir] = opts.sort.split(':');
606
- const schema = await getDbSchema(dbIds);
607
- const entry = schema[key.toLowerCase()];
608
- if (!entry) {
609
- console.error(`Sort property "${key}" not found.`);
610
- console.error(`Available: ${Object.values(schema).map(s => s.name).join(', ')}`);
611
- process.exit(1);
612
- }
613
- params.sorts = [{ property: entry.name, direction: dir === 'desc' ? 'descending' : 'ascending' }];
614
- }
615
-
616
- const res = await notion.dataSources.query(params);
617
-
618
- // Determine output format: --output takes precedence, --json is shorthand
619
- const format = opts.output || (getGlobalJson(cmd) ? 'json' : 'table');
620
-
621
- if (format === 'json') {
622
- console.log(JSON.stringify(res, null, 2));
623
- return;
624
- }
625
-
626
- const rows = pagesToRows(res.results);
627
- if (rows.length === 0) {
628
- console.log('(no results)');
629
- return;
630
- }
631
- const columns = Object.keys(rows[0]);
632
- outputFormatted(rows, columns, format);
633
- } catch (err) {
634
- console.error('Query failed:', err.message);
635
- process.exit(1);
636
- }
637
- });
638
-
639
- // ─── add ───────────────────────────────────────────────────────────────────────
640
- program
641
- .command('add <database>')
642
- .description('Add a new page to a database (e.g. notion add projects --prop "Name=New Task")')
643
- .option('--prop <key=value...>', 'Property value — repeatable (e.g. --prop "Name=Hello" --prop "Status=Todo")', (v, prev) => prev.concat([v]), [])
644
- .action(async (db, opts, cmd) => {
645
- try {
646
- const notion = getNotion();
647
- const dbIds = resolveDb(db);
648
- const properties = await buildProperties(dbIds, opts.prop);
649
- const res = await notion.pages.create({
650
- parent: { type: 'data_source_id', data_source_id: dbIds.data_source_id },
651
- properties,
652
- });
653
- if (getGlobalJson(cmd)) {
654
- console.log(JSON.stringify(res, null, 2));
655
- return;
656
- }
657
- console.log(`✅ Created page: ${res.id}`);
658
- console.log(` URL: ${res.url}`);
659
- } catch (err) {
660
- console.error('Add failed:', err.message);
661
- process.exit(1);
662
- }
663
- });
664
-
665
- // ─── update ────────────────────────────────────────────────────────────────────
666
- program
667
- .command('update <page-or-alias>')
668
- .description('Update a page\'s properties by ID or alias + filter')
669
- .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
670
- .option('--prop <key=value...>', 'Property value — repeatable', (v, prev) => prev.concat([v]), [])
671
- .action(async (target, opts, cmd) => {
672
- try {
673
- const notion = getNotion();
674
- const { pageId, dbIds: resolvedDbIds } = await resolvePageId(target, opts.filter);
675
- let dbIds = resolvedDbIds;
676
- if (!dbIds) {
677
- const page = await notion.pages.retrieve({ page_id: pageId });
678
- const dsId = page.parent?.data_source_id;
679
- if (!dsId) {
680
- console.error('Page is not in a database — cannot auto-detect property types.');
681
- process.exit(1);
682
- }
683
- dbIds = { data_source_id: dsId, database_id: page.parent?.database_id || dsId };
684
- }
685
- const properties = await buildProperties(dbIds, opts.prop);
686
- const res = await notion.pages.update({ page_id: pageId, properties });
687
- if (getGlobalJson(cmd)) {
688
- console.log(JSON.stringify(res, null, 2));
689
- return;
690
- }
691
- console.log(`✅ Updated page: ${res.id}`);
692
- } catch (err) {
693
- console.error('Update failed:', err.message);
694
- process.exit(1);
695
- }
696
- });
697
-
698
- // ─── delete (archive) ──────────────────────────────────────────────────────────
699
- program
700
- .command('delete <page-or-alias>')
701
- .description('Delete (archive) a page by ID or alias + filter')
702
- .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
703
- .action(async (target, opts, cmd) => {
704
- try {
705
- const notion = getNotion();
706
- const { pageId } = await resolvePageId(target, opts.filter);
707
- const res = await notion.pages.update({ page_id: pageId, archived: true });
708
- if (getGlobalJson(cmd)) {
709
- console.log(JSON.stringify(res, null, 2));
710
- return;
711
- }
712
- console.log(`🗑️ Archived page: ${res.id}`);
713
- console.log(' (Restore it from the trash in Notion if needed)');
714
- } catch (err) {
715
- console.error('Delete failed:', err.message);
716
- process.exit(1);
717
- }
718
- });
719
-
720
- // ─── get ───────────────────────────────────────────────────────────────────────
721
- program
722
- .command('get <page-or-alias>')
723
- .description('Get a page\'s properties by ID or alias + filter')
724
- .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
725
- .action(async (target, opts, cmd) => {
726
- try {
727
- const notion = getNotion();
728
- const { pageId } = await resolvePageId(target, opts.filter);
729
- const page = await notion.pages.retrieve({ page_id: pageId });
730
- if (getGlobalJson(cmd)) {
731
- console.log(JSON.stringify(page, null, 2));
732
- return;
733
- }
734
- console.log(`Page: ${page.id}`);
735
- console.log(`URL: ${page.url}`);
736
- console.log(`Created: ${page.created_time}`);
737
- console.log(`Updated: ${page.last_edited_time}`);
738
- console.log('');
739
- console.log('Properties:');
740
- for (const [name, prop] of Object.entries(page.properties)) {
741
- if (prop.type === 'relation') {
742
- const rels = prop.relation || [];
743
- if (rels.length === 0) {
744
- console.log(` ${name}: (none)`);
745
- } else {
746
- // Resolve relation titles
747
- const titles = [];
748
- for (const rel of rels) {
749
- try {
750
- const linked = await notion.pages.retrieve({ page_id: rel.id });
751
- let t = '';
752
- for (const [, p] of Object.entries(linked.properties)) {
753
- if (p.type === 'title') { t = propValue(p); break; }
754
- }
755
- titles.push(t || rel.id.slice(0, 8) + '…');
756
- } catch {
757
- titles.push(rel.id.slice(0, 8) + '…');
758
- }
759
- }
760
- console.log(` ${name}: ${titles.join(', ')}`);
761
- }
762
- } else if (prop.type === 'rollup') {
763
- const r = prop.rollup;
764
- if (!r) {
765
- console.log(` ${name}: (empty)`);
766
- } else if (r.type === 'number') {
767
- console.log(` ${name}: ${r.number != null ? r.number : '(empty)'}`);
768
- } else if (r.type === 'date') {
769
- console.log(` ${name}: ${r.date ? r.date.start : '(empty)'}`);
770
- } else if (r.type === 'array' && r.array) {
771
- console.log(` ${name}: ${r.array.map(item => propValue(item)).join(', ')}`);
772
- } else {
773
- console.log(` ${name}: ${JSON.stringify(r)}`);
774
- }
775
- } else {
776
- console.log(` ${name}: ${propValue(prop)}`);
777
- }
778
- }
779
- } catch (err) {
780
- console.error('Get failed:', err.message);
781
- process.exit(1);
782
- }
783
- });
784
-
785
- // ─── blocks ────────────────────────────────────────────────────────────────────
786
- program
787
- .command('blocks <page-or-alias>')
788
- .description('Get page content as rendered blocks by ID or alias + filter')
789
- .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
790
- .option('--ids', 'Show block IDs alongside content (for editing/deleting)')
791
- .action(async (target, opts, cmd) => {
792
- try {
793
- const notion = getNotion();
794
- const { pageId } = await resolvePageId(target, opts.filter);
795
- const res = await notion.blocks.children.list({ block_id: pageId, page_size: 100 });
796
- if (getGlobalJson(cmd)) {
797
- console.log(JSON.stringify(res, null, 2));
798
- return;
799
- }
800
- if (res.results.length === 0) {
801
- console.log('(no blocks)');
802
- return;
803
- }
804
- for (const block of res.results) {
805
- const type = block.type;
806
- const content = block[type];
807
- let text = '';
808
- if (content?.rich_text) {
809
- text = richTextToPlain(content.rich_text);
810
- } else if (content?.text) {
811
- text = richTextToPlain(content.text);
812
- }
813
- const prefix = type === 'heading_1' ? '# '
814
- : type === 'heading_2' ? '## '
815
- : type === 'heading_3' ? '### '
816
- : type === 'bulleted_list_item' ? '• '
817
- : type === 'numbered_list_item' ? ' 1. '
818
- : type === 'to_do' ? (content?.checked ? '☑ ' : '☐ ')
819
- : type === 'code' ? '```\n'
820
- : '';
821
- const suffix = type === 'code' ? '\n```' : '';
822
- const idTag = opts.ids ? `[${block.id.slice(0, 8)}] ` : '';
823
- console.log(`${idTag}${prefix}${text}${suffix}`);
824
- }
825
- } catch (err) {
826
- console.error('Blocks failed:', err.message);
827
- process.exit(1);
828
- }
829
- });
830
-
831
- // ─── block-edit ────────────────────────────────────────────────────────────────
832
- program
833
- .command('block-edit <block-id> <text>')
834
- .description('Update a block\'s text content')
835
- .action(async (blockId, text, opts, cmd) => {
836
- try {
837
- const notion = getNotion();
838
- // First retrieve the block to know its type
839
- const block = await notion.blocks.retrieve({ block_id: blockId });
840
- const type = block.type;
841
-
842
- // Build the update payload based on block type
843
- const supportedTextTypes = [
844
- 'paragraph', 'heading_1', 'heading_2', 'heading_3',
845
- 'bulleted_list_item', 'numbered_list_item', 'quote', 'callout', 'toggle',
846
- ];
847
-
848
- if (type === 'to_do') {
849
- const res = await notion.blocks.update({
850
- block_id: blockId,
851
- to_do: {
852
- rich_text: [{ text: { content: text } }],
853
- checked: block.to_do?.checked || false,
854
- },
855
- });
856
- if (getGlobalJson(cmd)) { console.log(JSON.stringify(res, null, 2)); return; }
857
- console.log(`✅ Updated ${type} block: ${blockId.slice(0, 8)}…`);
858
- } else if (supportedTextTypes.includes(type)) {
859
- const res = await notion.blocks.update({
860
- block_id: blockId,
861
- [type]: {
862
- rich_text: [{ text: { content: text } }],
863
- },
864
- });
865
- if (getGlobalJson(cmd)) { console.log(JSON.stringify(res, null, 2)); return; }
866
- console.log(`✅ Updated ${type} block: ${blockId.slice(0, 8)}…`);
867
- } else if (type === 'code') {
868
- const res = await notion.blocks.update({
869
- block_id: blockId,
870
- code: {
871
- rich_text: [{ text: { content: text } }],
872
- language: block.code?.language || 'plain text',
873
- },
874
- });
875
- if (getGlobalJson(cmd)) { console.log(JSON.stringify(res, null, 2)); return; }
876
- console.log(`✅ Updated code block: ${blockId.slice(0, 8)}…`);
877
- } else {
878
- console.error(`Block type "${type}" doesn't support text editing.`);
879
- console.error('Supported types: paragraph, headings, lists, to_do, quote, callout, toggle, code');
880
- process.exit(1);
881
- }
882
- } catch (err) {
883
- console.error('Block edit failed:', err.message);
884
- process.exit(1);
885
- }
886
- });
887
-
888
- // ─── block-delete ──────────────────────────────────────────────────────────────
889
- program
890
- .command('block-delete <block-id>')
891
- .description('Delete a block from a page')
892
- .action(async (blockId, opts, cmd) => {
893
- try {
894
- const notion = getNotion();
895
- const res = await notion.blocks.delete({ block_id: blockId });
896
- if (getGlobalJson(cmd)) {
897
- console.log(JSON.stringify(res, null, 2));
898
- return;
899
- }
900
- console.log(`🗑️ Deleted block: ${blockId.slice(0, 8)}…`);
901
- } catch (err) {
902
- console.error('Block delete failed:', err.message);
903
- process.exit(1);
904
- }
905
- });
906
-
907
- // ─── relations ─────────────────────────────────────────────────────────────────
908
- program
909
- .command('relations <page-or-alias>')
910
- .description('Show all relation and rollup properties with resolved titles')
911
- .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
912
- .action(async (target, opts, cmd) => {
913
- try {
914
- const notion = getNotion();
915
- const { pageId } = await resolvePageId(target, opts.filter);
916
- const page = await notion.pages.retrieve({ page_id: pageId });
917
-
918
- if (getGlobalJson(cmd)) {
919
- console.log(JSON.stringify(page, null, 2));
920
- return;
921
- }
922
-
923
- let found = false;
924
-
925
- for (const [name, prop] of Object.entries(page.properties)) {
926
- if (prop.type === 'relation') {
927
- const rels = prop.relation || [];
928
- if (rels.length === 0) {
929
- console.log(`\n${name}: (no linked pages)`);
930
- continue;
931
- }
932
- found = true;
933
- console.log(`\n${name}: ${rels.length} linked page${rels.length !== 1 ? 's' : ''}`);
934
-
935
- // Resolve each related page title
936
- const rows = [];
937
- for (const rel of rels) {
938
- try {
939
- const linked = await notion.pages.retrieve({ page_id: rel.id });
940
- let title = '';
941
- for (const [, p] of Object.entries(linked.properties)) {
942
- if (p.type === 'title') {
943
- title = propValue(p);
944
- break;
945
- }
946
- }
947
- rows.push({
948
- id: rel.id.slice(0, 8) + '…',
949
- title: title || '(untitled)',
950
- url: linked.url || '',
951
- });
952
- } catch {
953
- rows.push({ id: rel.id.slice(0, 8) + '…', title: '(access denied)', url: '' });
954
- }
955
- }
956
- printTable(rows, ['id', 'title', 'url']);
957
- }
958
-
959
- if (prop.type === 'rollup') {
960
- found = true;
961
- const r = prop.rollup;
962
- console.log(`\n${name} (rollup):`);
963
- if (!r) {
964
- console.log(' (empty)');
965
- continue;
966
- }
967
- if (r.type === 'number') {
968
- console.log(` ${r.function || 'value'}: ${r.number}`);
969
- } else if (r.type === 'date') {
970
- console.log(` ${r.date ? r.date.start : '(empty)'}`);
971
- } else if (r.type === 'array' && r.array) {
972
- for (const item of r.array) {
973
- console.log(` • ${propValue(item)}`);
974
- }
975
- } else {
976
- console.log(` ${JSON.stringify(r)}`);
977
- }
978
- }
979
- }
980
-
981
- if (!found) {
982
- console.log('This page has no relation or rollup properties.');
983
- }
984
- } catch (err) {
985
- console.error('Relations failed:', err.message);
986
- process.exit(1);
987
- }
988
- });
989
-
990
- // ─── dbs ───────────────────────────────────────────────────────────────────────
991
- program
992
- .command('dbs')
993
- .description('List all databases shared with your integration')
994
- .action(async (opts, cmd) => {
995
- try {
996
- const notion = getNotion();
997
- const res = await notion.search({
998
- filter: { value: 'data_source', property: 'object' },
999
- page_size: 100,
1000
- });
1001
- if (getGlobalJson(cmd)) {
1002
- console.log(JSON.stringify(res, null, 2));
1003
- return;
1004
- }
1005
- const rows = res.results.map(db => ({
1006
- id: db.id,
1007
- title: richTextToPlain(db.title),
1008
- url: db.url || '',
1009
- }));
1010
- if (rows.length === 0) {
1011
- console.log('No databases found. Make sure you\'ve shared databases with your integration.');
1012
- console.log('In Notion: open a database → ••• menu → Connections → Add your integration');
1013
- return;
1014
- }
1015
- printTable(rows, ['id', 'title', 'url']);
1016
- } catch (err) {
1017
- console.error('List databases failed:', err.message);
1018
- process.exit(1);
1019
- }
1020
- });
1021
-
1022
- // ─── users ─────────────────────────────────────────────────────────────────────
1023
- program
1024
- .command('users')
1025
- .description('List all users in the workspace')
1026
- .action(async (opts, cmd) => {
1027
- try {
1028
- const notion = getNotion();
1029
- const res = await notion.users.list({});
1030
- if (getGlobalJson(cmd)) {
1031
- console.log(JSON.stringify(res, null, 2));
1032
- return;
1033
- }
1034
- const rows = res.results.map(u => ({
1035
- id: u.id,
1036
- name: u.name || '',
1037
- type: u.type || '',
1038
- email: (u.person && u.person.email) || '',
1039
- }));
1040
- printTable(rows, ['id', 'name', 'type', 'email']);
1041
- } catch (err) {
1042
- console.error('Users failed:', err.message);
1043
- process.exit(1);
1044
- }
1045
- });
1046
-
1047
- // ─── user ──────────────────────────────────────────────────────────────────────
1048
- program
1049
- .command('user <user-id>')
1050
- .description('Get user details')
1051
- .action(async (userId, opts, cmd) => {
1052
- try {
1053
- const notion = getNotion();
1054
- const user = await notion.users.retrieve({ user_id: userId });
1055
- if (getGlobalJson(cmd)) {
1056
- console.log(JSON.stringify(user, null, 2));
1057
- return;
1058
- }
1059
- console.log(`User: ${user.id}`);
1060
- console.log(`Name: ${user.name || '(unnamed)'}`);
1061
- console.log(`Type: ${user.type || ''}`);
1062
- if (user.person && user.person.email) {
1063
- console.log(`Email: ${user.person.email}`);
1064
- }
1065
- if (user.avatar_url) {
1066
- console.log(`Avatar: ${user.avatar_url}`);
1067
- }
1068
- if (user.bot) {
1069
- console.log(`Bot Owner: ${JSON.stringify(user.bot.owner || {})}`);
1070
- }
1071
- } catch (err) {
1072
- console.error('User failed:', err.message);
1073
- process.exit(1);
1074
- }
1075
- });
1076
-
1077
- // ─── comments ──────────────────────────────────────────────────────────────────
1078
- program
1079
- .command('comments <page-or-alias>')
1080
- .description('List comments on a page by ID or alias + filter')
1081
- .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
1082
- .action(async (target, opts, cmd) => {
1083
- try {
1084
- const notion = getNotion();
1085
- const { pageId } = await resolvePageId(target, opts.filter);
1086
- const res = await notion.comments.list({ block_id: pageId });
1087
- if (getGlobalJson(cmd)) {
1088
- console.log(JSON.stringify(res, null, 2));
1089
- return;
1090
- }
1091
- if (res.results.length === 0) {
1092
- console.log('(no comments)');
1093
- return;
1094
- }
1095
- const rows = res.results.map(c => ({
1096
- id: c.id,
1097
- text: richTextToPlain(c.rich_text),
1098
- created: c.created_time || '',
1099
- author: c.created_by?.name || c.created_by?.id || '',
1100
- }));
1101
- printTable(rows, ['id', 'text', 'created', 'author']);
1102
- } catch (err) {
1103
- console.error('Comments failed:', err.message);
1104
- process.exit(1);
1105
- }
1106
- });
1107
-
1108
- // ─── comment ───────────────────────────────────────────────────────────────────
1109
- program
1110
- .command('comment <page-or-alias> <text>')
1111
- .description('Add a comment to a page by ID or alias + filter')
1112
- .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
1113
- .action(async (target, text, opts, cmd) => {
1114
- try {
1115
- const notion = getNotion();
1116
- const { pageId } = await resolvePageId(target, opts.filter);
1117
- const res = await notion.comments.create({
1118
- parent: { page_id: pageId },
1119
- rich_text: [{ text: { content: text } }],
1120
- });
1121
- if (getGlobalJson(cmd)) {
1122
- console.log(JSON.stringify(res, null, 2));
1123
- return;
1124
- }
1125
- console.log(`✅ Comment added: ${res.id}`);
1126
- } catch (err) {
1127
- console.error('Comment failed:', err.message);
1128
- process.exit(1);
1129
- }
1130
- });
1131
-
1132
- // ─── append ────────────────────────────────────────────────────────────────────
1133
- program
1134
- .command('append <page-or-alias> <text>')
1135
- .description('Append a text block to a page by ID or alias + filter')
1136
- .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
1137
- .action(async (target, text, opts, cmd) => {
1138
- try {
1139
- const notion = getNotion();
1140
- const { pageId } = await resolvePageId(target, opts.filter);
1141
- const res = await notion.blocks.children.append({
1142
- block_id: pageId,
1143
- children: [{
1144
- object: 'block',
1145
- type: 'paragraph',
1146
- paragraph: {
1147
- rich_text: [{ text: { content: text } }],
1148
- },
1149
- }],
1150
- });
1151
- if (getGlobalJson(cmd)) {
1152
- console.log(JSON.stringify(res, null, 2));
1153
- return;
1154
- }
1155
- console.log(`✅ Appended text block to page ${pageId}`);
1156
- } catch (err) {
1157
- console.error('Append failed:', err.message);
1158
- process.exit(1);
1159
- }
1160
- });
1161
-
1162
- // ─── me ────────────────────────────────────────────────────────────────────────
1163
- program
1164
- .command('me')
1165
- .description('Show details about the current integration/bot')
1166
- .action(async (opts, cmd) => {
1167
- try {
1168
- const notion = getNotion();
1169
- const me = await notion.users.me({});
1170
- if (getGlobalJson(cmd)) {
1171
- console.log(JSON.stringify(me, null, 2));
1172
- return;
1173
- }
1174
- console.log(`Bot: ${me.name || '(unnamed)'}`);
1175
- console.log(`ID: ${me.id}`);
1176
- console.log(`Type: ${me.type}`);
1177
- if (me.bot?.owner) {
1178
- const owner = me.bot.owner;
1179
- console.log(`Owner: ${owner.type === 'workspace' ? 'Workspace' : owner.user?.name || owner.type}`);
1180
- }
1181
- if (me.avatar_url) {
1182
- console.log(`Avatar: ${me.avatar_url}`);
1183
- }
1184
- } catch (err) {
1185
- console.error('Me failed:', err.message);
1186
- process.exit(1);
1187
- }
1188
- });
1189
-
1190
- // ─── move ──────────────────────────────────────────────────────────────────────
1191
- program
1192
- .command('move <page-or-alias>')
1193
- .description('Move a page to a new parent (page or database)')
1194
- .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
1195
- .option('--to <parent-id-or-alias>', 'Destination parent (page ID, database alias, or database ID)')
1196
- .action(async (target, opts, cmd) => {
1197
- try {
1198
- if (!opts.to) {
1199
- console.error('--to is required. Specify a parent page ID or database alias.');
1200
- process.exit(1);
1201
- }
1202
- const notion = getNotion();
1203
- const { pageId } = await resolvePageId(target, opts.filter);
1204
-
1205
- // Resolve --to target
1206
- let parent;
1207
- const ws = getWorkspaceConfig();
1208
- if (ws.aliases && ws.aliases[opts.to]) {
1209
- const db = ws.aliases[opts.to];
1210
- // pages.move() requires data_source_id parent, not database_id
1211
- parent = { type: 'data_source_id', data_source_id: db.data_source_id };
1212
- } else if (UUID_REGEX.test(opts.to)) {
1213
- // Assume page ID — user can also pass a database_id
1214
- parent = { type: 'page_id', page_id: opts.to };
1215
- } else {
1216
- console.error(`Unknown destination: "${opts.to}". Use a page ID or database alias.`);
1217
- const aliasNames = ws.aliases ? Object.keys(ws.aliases) : [];
1218
- if (aliasNames.length > 0) {
1219
- console.error(`Available aliases: ${aliasNames.join(', ')}`);
1220
- }
1221
- process.exit(1);
1222
- }
1223
-
1224
- const res = await notion.pages.move({ page_id: pageId, parent });
1225
- if (getGlobalJson(cmd)) {
1226
- console.log(JSON.stringify(res, null, 2));
1227
- return;
1228
- }
1229
- console.log(`✅ Moved page: ${pageId.slice(0, 8)}…`);
1230
- if (res.url) console.log(` URL: ${res.url}`);
1231
- } catch (err) {
1232
- console.error('Move failed:', err.message);
1233
- process.exit(1);
1234
- }
1235
- });
1236
-
1237
- // ─── templates ─────────────────────────────────────────────────────────────────
1238
- program
1239
- .command('templates <database>')
1240
- .description('List page templates available for a database')
1241
- .action(async (db, opts, cmd) => {
1242
- try {
1243
- const notion = getNotion();
1244
- const dbIds = resolveDb(db);
1245
- const res = await notion.dataSources.listTemplates({
1246
- data_source_id: dbIds.data_source_id,
1247
- });
1248
- if (getGlobalJson(cmd)) {
1249
- console.log(JSON.stringify(res, null, 2));
1250
- return;
1251
- }
1252
- if (!res.results || res.results.length === 0) {
1253
- console.log('No templates found for this database.');
1254
- return;
1255
- }
1256
- const rows = res.results.map(t => {
1257
- let title = '';
1258
- if (t.properties) {
1259
- for (const [, prop] of Object.entries(t.properties)) {
1260
- if (prop.type === 'title') {
1261
- title = propValue(prop);
1262
- break;
1263
- }
1264
- }
1265
- }
1266
- return {
1267
- id: t.id,
1268
- title: title || '(untitled)',
1269
- url: t.url || '',
1270
- };
1271
- });
1272
- printTable(rows, ['id', 'title', 'url']);
1273
- } catch (err) {
1274
- console.error('Templates failed:', err.message);
1275
- process.exit(1);
1276
- }
1277
- });
1278
-
1279
- // ─── db-create ─────────────────────────────────────────────────────────────────
1280
- program
1281
- .command('db-create <parent-page-id> <title>')
1282
- .description('Create a new database under a page')
1283
- .option('--prop <name:type...>', 'Property definition — repeatable (e.g. --prop "Status:select" --prop "Priority:number")', (v, prev) => prev.concat([v]), [])
1284
- .option('--alias <name>', 'Auto-create an alias for the new database')
1285
- .action(async (parentPageId, title, opts, cmd) => {
1286
- try {
1287
- const notion = getNotion();
1288
-
1289
- // Build properties — always include a title property
1290
- const properties = {};
1291
- let hasTitleProp = false;
1292
-
1293
- for (const kv of opts.prop) {
1294
- const colonIdx = kv.indexOf(':');
1295
- if (colonIdx === -1) {
1296
- console.error(`Invalid property format: ${kv} (expected name:type)`);
1297
- console.error('Supported types: title, rich_text, number, select, multi_select, date, checkbox, url, email, phone_number, status');
1298
- process.exit(1);
1299
- }
1300
- const name = kv.slice(0, colonIdx);
1301
- const type = kv.slice(colonIdx + 1).toLowerCase();
1302
- if (type === 'title') hasTitleProp = true;
1303
- properties[name] = { [type]: {} };
1304
- }
1305
-
1306
- // Ensure there's a title property
1307
- if (!hasTitleProp) {
1308
- properties['Name'] = { title: {} };
1309
- }
1310
-
1311
- // 2025 API: databases.create() only handles title property reliably.
1312
- // Non-title properties must be added via dataSources.update() after creation.
1313
- const titleProps = {};
1314
- const extraProps = {};
1315
- for (const [name, prop] of Object.entries(properties)) {
1316
- if (prop.title) {
1317
- titleProps[name] = prop;
1318
- } else {
1319
- extraProps[name] = prop;
1320
- }
1321
- }
1322
- // Ensure title property exists in create call
1323
- if (Object.keys(titleProps).length === 0) {
1324
- titleProps['Name'] = { title: {} };
1325
- }
1326
-
1327
- const res = await notion.databases.create({
1328
- parent: { type: 'page_id', page_id: parentPageId },
1329
- title: [{ text: { content: title } }],
1330
- properties: titleProps,
1331
- });
1332
-
1333
- // Extract correct dual IDs from response
1334
- const databaseId = res.id;
1335
- const dataSourceId = (res.data_sources && res.data_sources[0])
1336
- ? res.data_sources[0].id
1337
- : res.id;
1338
-
1339
- // Add non-title properties via dataSources.update()
1340
- if (Object.keys(extraProps).length > 0) {
1341
- await notion.dataSources.update({
1342
- data_source_id: dataSourceId,
1343
- properties: extraProps,
1344
- });
1345
- }
1346
-
1347
- if (getGlobalJson(cmd)) {
1348
- console.log(JSON.stringify(res, null, 2));
1349
- return;
1350
- }
1351
-
1352
- console.log(`✅ Created database: ${databaseId.slice(0, 8)}…`);
1353
- console.log(` Title: ${title}`);
1354
- console.log(` Properties: ${Object.keys(properties).join(', ')}`);
1355
-
1356
- // Auto-create alias if requested
1357
- if (opts.alias) {
1358
- const config = loadConfig();
1359
- const wsName = getWorkspaceName() || config.activeWorkspace || 'default';
1360
- if (!config.workspaces[wsName]) config.workspaces[wsName] = { aliases: {} };
1361
- if (!config.workspaces[wsName].aliases) config.workspaces[wsName].aliases = {};
1362
- config.workspaces[wsName].aliases[opts.alias] = {
1363
- database_id: databaseId,
1364
- data_source_id: dataSourceId,
1365
- };
1366
- saveConfig(config);
1367
- console.log(` Alias: ${opts.alias}`);
1368
- }
1369
- } catch (err) {
1370
- console.error('Database create failed:', err.message);
1371
- process.exit(1);
1372
- }
1373
- });
1374
-
1375
- // ─── db-update ─────────────────────────────────────────────────────────────────
1376
- program
1377
- .command('db-update <database>')
1378
- .description('Update a database title or add properties')
1379
- .option('--title <text>', 'New database title')
1380
- .option('--add-prop <name:type...>', 'Add a property (e.g. --add-prop "Priority:number")', (v, prev) => prev.concat([v]), [])
1381
- .option('--remove-prop <name...>', 'Remove a property by name', (v, prev) => prev.concat([v]), [])
1382
- .action(async (db, opts, cmd) => {
1383
- try {
1384
- const notion = getNotion();
1385
- const dbIds = resolveDb(db);
1386
-
1387
- // 2025 API: property changes go through dataSources.update(), NOT databases.update().
1388
- // databases.update() silently ignores property modifications.
1389
- // Title changes still go through databases.update().
1390
- let canonicalId = dbIds.database_id;
1391
- const dataSourceId = dbIds.data_source_id;
1392
-
1393
- // Resolve canonical database_id if both IDs are the same
1394
- if (canonicalId === dataSourceId) {
1395
- try {
1396
- const ds = await notion.dataSources.retrieve({ data_source_id: canonicalId });
1397
- if (ds.parent && ds.parent.type === 'database_id') {
1398
- canonicalId = ds.parent.database_id;
1399
- }
1400
- } catch (_) { /* fall through with what we have */ }
1401
- }
1402
-
1403
- // Build property changes for dataSources.update()
1404
- let propChanges = null;
1405
- if (opts.addProp.length > 0 || opts.removeProp.length > 0) {
1406
- propChanges = {};
1407
-
1408
- for (const kv of opts.addProp) {
1409
- const colonIdx = kv.indexOf(':');
1410
- if (colonIdx === -1) {
1411
- console.error(`Invalid property format: ${kv} (expected name:type)`);
1412
- process.exit(1);
1413
- }
1414
- const name = kv.slice(0, colonIdx);
1415
- const type = kv.slice(colonIdx + 1).toLowerCase();
1416
- propChanges[name] = { [type]: {} };
1417
- }
1418
-
1419
- for (const name of opts.removeProp) {
1420
- propChanges[name] = null;
1421
- }
1422
- }
1423
-
1424
- let res;
1425
-
1426
- // Title changes go through databases.update()
1427
- if (opts.title) {
1428
- res = await notion.databases.update({
1429
- database_id: canonicalId,
1430
- title: [{ text: { content: opts.title } }],
1431
- });
1432
- }
1433
-
1434
- // Property changes go through dataSources.update()
1435
- if (propChanges) {
1436
- res = await notion.dataSources.update({
1437
- data_source_id: dataSourceId,
1438
- properties: propChanges,
1439
- });
1440
- }
1441
-
1442
- if (getGlobalJson(cmd)) {
1443
- console.log(JSON.stringify(res, null, 2));
1444
- return;
1445
- }
1446
-
1447
- console.log(`✅ Updated database: ${(dbIds.database_id || dbIds.data_source_id).slice(0, 8)}…`);
1448
- if (opts.title) console.log(` Title: ${opts.title}`);
1449
- if (opts.addProp.length > 0) console.log(` Added: ${opts.addProp.join(', ')}`);
1450
- if (opts.removeProp.length > 0) console.log(` Removed: ${opts.removeProp.join(', ')}`);
1451
- } catch (err) {
1452
- console.error('Database update failed:', err.message);
1453
- process.exit(1);
1454
- }
1455
- });
1456
-
1457
- // ─── upload ────────────────────────────────────────────────────────────────────
1458
- program
1459
- .command('upload <page-or-alias> <file-path>')
1460
- .description('Upload a file to a page')
1461
- .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
1462
- .action(async (target, filePath, opts, cmd) => {
1463
- try {
1464
- const notion = getNotion();
1465
- const { pageId } = await resolvePageId(target, opts.filter);
1466
-
1467
- // Resolve file path
1468
- const absPath = path.resolve(filePath);
1469
- if (!fs.existsSync(absPath)) {
1470
- console.error(`File not found: ${absPath}`);
1471
- process.exit(1);
1472
- }
1473
-
1474
- const filename = path.basename(absPath);
1475
- const fileData = fs.readFileSync(absPath);
1476
- const fileSize = fileData.length;
1477
-
1478
- // Detect MIME type from extension
1479
- const MIME_MAP = {
1480
- '.txt': 'text/plain', '.csv': 'text/csv', '.html': 'text/html',
1481
- '.json': 'application/json', '.pdf': 'application/pdf',
1482
- '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
1483
- '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml',
1484
- '.mp4': 'video/mp4', '.mp3': 'audio/mpeg', '.wav': 'audio/wav',
1485
- '.zip': 'application/zip', '.doc': 'application/msword',
1486
- '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
1487
- '.xls': 'application/vnd.ms-excel',
1488
- '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
1489
- };
1490
- const ext = path.extname(filename).toLowerCase();
1491
- const mimeType = MIME_MAP[ext] || 'application/octet-stream';
1492
-
1493
- // Step 1: Create file upload
1494
- const upload = await notion.fileUploads.create({
1495
- parent: { type: 'page_id', page_id: pageId },
1496
- filename,
1497
- });
1498
- const uploadId = upload.id;
1499
-
1500
- // Step 2: Send file data with correct content type
1501
- await notion.fileUploads.send({
1502
- file_upload_id: uploadId,
1503
- file: { data: new Blob([fileData], { type: mimeType }), filename },
1504
- part_number: '1',
1505
- });
1506
-
1507
- // Step 3: Append file block to page (no complete() needed — attach directly)
1508
- await notion.blocks.children.append({
1509
- block_id: pageId,
1510
- children: [{
1511
- object: 'block',
1512
- type: 'file',
1513
- file: {
1514
- type: 'file_upload',
1515
- file_upload: { id: uploadId },
1516
- },
1517
- }],
1518
- });
1519
-
1520
- if (getGlobalJson(cmd)) {
1521
- console.log(JSON.stringify({ upload_id: uploadId, filename, size: fileSize, page_id: pageId }, null, 2));
1522
- return;
1523
- }
1524
-
1525
- const sizeStr = fileSize > 1024 * 1024
1526
- ? `${(fileSize / (1024 * 1024)).toFixed(1)} MB`
1527
- : `${(fileSize / 1024).toFixed(1)} KB`;
1528
-
1529
- console.log(`✅ Uploaded: ${filename} (${sizeStr})`);
1530
- console.log(` Page: ${pageId.slice(0, 8)}…`);
1531
- } catch (err) {
1532
- console.error('Upload failed:', err.message);
1533
- process.exit(1);
1534
- }
1535
- });
1536
-
1537
- // ─── props ─────────────────────────────────────────────────────────────────────
1538
- program
1539
- .command('props <page-or-alias>')
1540
- .description('List all properties with full paginated values')
1541
- .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
1542
- .action(async (target, opts, cmd) => {
1543
- try {
1544
- const notion = getNotion();
1545
- const { pageId } = await resolvePageId(target, opts.filter);
1546
- const page = await notion.pages.retrieve({ page_id: pageId });
1547
-
1548
- if (getGlobalJson(cmd)) {
1549
- console.log(JSON.stringify(page, null, 2));
1550
- return;
1551
- }
1552
-
1553
- console.log(`Page: ${page.id}`);
1554
- console.log(`URL: ${page.url}\n`);
1555
-
1556
- for (const [name, prop] of Object.entries(page.properties)) {
1557
- // For paginated properties (relation, rollup, rich_text, title, people),
1558
- // use the property retrieval endpoint to get full values
1559
- const needsPagination = ['relation', 'rollup', 'rich_text', 'title', 'people'].includes(prop.type);
1560
-
1561
- if (needsPagination && prop.id) {
1562
- try {
1563
- const fullProp = await notion.pages.properties.retrieve({
1564
- page_id: pageId,
1565
- property_id: prop.id,
1566
- });
1567
-
1568
- if (fullProp.results) {
1569
- // Paginated property — collect all results
1570
- const items = fullProp.results;
1571
- if (prop.type === 'relation') {
1572
- if (items.length === 0) {
1573
- console.log(` ${name}: (none)`);
1574
- } else {
1575
- const titles = [];
1576
- for (const item of items) {
1577
- const relId = item.relation?.id;
1578
- if (relId) {
1579
- try {
1580
- const linked = await notion.pages.retrieve({ page_id: relId });
1581
- let t = '';
1582
- for (const [, p] of Object.entries(linked.properties)) {
1583
- if (p.type === 'title') { t = propValue(p); break; }
1584
- }
1585
- titles.push(t || relId.slice(0, 8) + '…');
1586
- } catch {
1587
- titles.push(relId.slice(0, 8) + '…');
1588
- }
1589
- }
1590
- }
1591
- console.log(` ${name}: ${titles.join(', ')}`);
1592
- }
1593
- } else if (prop.type === 'rich_text' || prop.type === 'title') {
1594
- const text = items.map(i => i[prop.type]?.plain_text || '').join('');
1595
- console.log(` ${name}: ${text}`);
1596
- } else if (prop.type === 'people') {
1597
- const people = items.map(i => i.people?.name || i.people?.id || '').join(', ');
1598
- console.log(` ${name}: ${people}`);
1599
- } else {
1600
- console.log(` ${name}: ${JSON.stringify(items)}`);
1601
- }
1602
- } else {
1603
- // Non-paginated response
1604
- console.log(` ${name}: ${propValue(fullProp)}`);
1605
- }
1606
- } catch {
1607
- // Fallback to basic propValue
1608
- console.log(` ${name}: ${propValue(prop)}`);
1609
- }
1610
- } else {
1611
- console.log(` ${name}: ${propValue(prop)}`);
1612
- }
1613
- }
1614
- } catch (err) {
1615
- console.error('Props failed:', err.message);
1616
- process.exit(1);
1617
- }
1618
- });
1619
-
1620
- // ─── Run ───────────────────────────────────────────────────────────────────────
1621
- program.parse();
13
+ const ctx = createContext(program);
14
+
15
+ // Register all command modules
16
+ require('../commands/config').register(program, ctx);
17
+ require('../commands/search').register(program, ctx);
18
+ require('../commands/query').register(program, ctx);
19
+ require('../commands/crud').register(program, ctx);
20
+ require('../commands/blocks').register(program, ctx);
21
+ require('../commands/database').register(program, ctx);
22
+ require('../commands/users').register(program, ctx);
23
+ require('../commands/comments').register(program, ctx);
24
+ require('../commands/pages').register(program, ctx);
25
+ require('../commands/import-export').register(program, ctx);
26
+ require('../commands/upload').register(program, ctx);
27
+
28
+ program.parseAsync(process.argv);