@jordancoin/notioncli 1.0.0 → 1.2.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.
package/bin/notion.js CHANGED
@@ -19,12 +19,35 @@ function saveConfig(config) {
19
19
  }
20
20
 
21
21
  /**
22
- * Resolve API key: env var config file error with setup instructions
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
23
46
  */
24
47
  function getApiKey() {
25
48
  if (process.env.NOTION_API_KEY) return process.env.NOTION_API_KEY;
26
- const config = loadConfig();
27
- if (config.apiKey) return config.apiKey;
49
+ const ws = getWorkspaceConfig();
50
+ if (ws.apiKey) return ws.apiKey;
28
51
  console.error('Error: No Notion API key found.');
29
52
  console.error('');
30
53
  console.error('Set it up with one of:');
@@ -40,14 +63,14 @@ function getApiKey() {
40
63
  * If given a raw UUID, we use it for both IDs (the SDK figures it out).
41
64
  */
42
65
  function resolveDb(aliasOrId) {
43
- const config = loadConfig();
44
- if (config.aliases && config.aliases[aliasOrId]) {
45
- return config.aliases[aliasOrId];
66
+ const ws = getWorkspaceConfig();
67
+ if (ws.aliases && ws.aliases[aliasOrId]) {
68
+ return ws.aliases[aliasOrId];
46
69
  }
47
70
  if (UUID_REGEX.test(aliasOrId)) {
48
71
  return { database_id: aliasOrId, data_source_id: aliasOrId };
49
72
  }
50
- const aliasNames = config.aliases ? Object.keys(config.aliases) : [];
73
+ const aliasNames = ws.aliases ? Object.keys(ws.aliases) : [];
51
74
  console.error(`Unknown database alias: "${aliasOrId}"`);
52
75
  if (aliasNames.length > 0) {
53
76
  console.error(`Available aliases: ${aliasNames.join(', ')}`);
@@ -64,14 +87,14 @@ function resolveDb(aliasOrId) {
64
87
  * Returns { pageId, dbIds } where dbIds is non-null when resolved via alias.
65
88
  */
66
89
  async function resolvePageId(aliasOrId, filterStr) {
67
- const config = loadConfig();
68
- if (config.aliases && config.aliases[aliasOrId]) {
90
+ const ws = getWorkspaceConfig();
91
+ if (ws.aliases && ws.aliases[aliasOrId]) {
69
92
  if (!filterStr) {
70
93
  console.error('When using an alias, --filter is required to identify a specific page.');
71
94
  console.error(`Example: notion update ${aliasOrId} --filter "Name=My Page" --prop "Status=Done"`);
72
95
  process.exit(1);
73
96
  }
74
- const dbIds = config.aliases[aliasOrId];
97
+ const dbIds = ws.aliases[aliasOrId];
75
98
  const notion = getNotion();
76
99
  const filter = await buildFilter(dbIds, filterStr);
77
100
  const res = await notion.dataSources.query({
@@ -94,7 +117,7 @@ async function resolvePageId(aliasOrId, filterStr) {
94
117
  }
95
118
  // Check if it looks like a UUID — if not, it's probably a typo'd alias
96
119
  if (!UUID_REGEX.test(aliasOrId)) {
97
- const aliasNames = config.aliases ? Object.keys(config.aliases) : [];
120
+ const aliasNames = ws.aliases ? Object.keys(ws.aliases) : [];
98
121
  console.error(`Unknown alias: "${aliasOrId}"`);
99
122
  if (aliasNames.length > 0) {
100
123
  console.error(`Available aliases: ${aliasNames.join(', ')}`);
@@ -203,8 +226,9 @@ async function buildFilter(dbIds, filterStr) {
203
226
  program
204
227
  .name('notion')
205
228
  .description('A powerful CLI for the Notion API — query databases, manage pages, and automate your workspace from the terminal.')
206
- .version('1.0.0')
207
- .option('--json', 'Output raw JSON instead of formatted tables');
229
+ .version('1.2.0')
230
+ .option('--json', 'Output raw JSON instead of formatted tables')
231
+ .option('-w, --workspace <name>', 'Use a specific workspace profile');
208
232
 
209
233
  // ─── init ──────────────────────────────────────────────────────────────────────
210
234
  program
@@ -213,6 +237,7 @@ program
213
237
  .option('--key <api-key>', 'Notion integration API key (starts with ntn_)')
214
238
  .action(async (opts) => {
215
239
  const config = loadConfig();
240
+ const wsName = getWorkspaceName() || config.activeWorkspace || 'default';
216
241
  const apiKey = opts.key || process.env.NOTION_API_KEY;
217
242
 
218
243
  if (!apiKey) {
@@ -225,12 +250,16 @@ program
225
250
  console.error(' 4. Share your databases with the integration');
226
251
  console.error('');
227
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');
228
254
  process.exit(1);
229
255
  }
230
256
 
231
- config.apiKey = apiKey;
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;
232
261
  saveConfig(config);
233
- console.log(`✅ API key saved to ${CONFIG_PATH}`);
262
+ console.log(`✅ API key saved to workspace "${wsName}" in ${CONFIG_PATH}`);
234
263
  console.log('');
235
264
 
236
265
  // Discover databases
@@ -247,7 +276,7 @@ program
247
276
  return;
248
277
  }
249
278
 
250
- if (!config.aliases) config.aliases = {};
279
+ const aliases = config.workspaces[wsName].aliases || {};
251
280
 
252
281
  console.log(`Found ${res.results.length} database${res.results.length !== 1 ? 's' : ''}:\n`);
253
282
 
@@ -255,7 +284,7 @@ program
255
284
  for (const db of res.results) {
256
285
  const title = richTextToPlain(db.title) || '';
257
286
  const dsId = db.id;
258
- const dbId = db.database_id || dsId;
287
+ const dbId = (db.parent && db.parent.type === 'database_id' && db.parent.database_id) || db.database_id || dsId;
259
288
 
260
289
  // Auto-generate a slug from the title
261
290
  let slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 30);
@@ -264,12 +293,12 @@ program
264
293
  // Avoid collisions — append a number if needed
265
294
  let finalSlug = slug;
266
295
  let counter = 2;
267
- while (config.aliases[finalSlug] && config.aliases[finalSlug].data_source_id !== dsId) {
296
+ while (aliases[finalSlug] && aliases[finalSlug].data_source_id !== dsId) {
268
297
  finalSlug = `${slug}-${counter}`;
269
298
  counter++;
270
299
  }
271
300
 
272
- config.aliases[finalSlug] = {
301
+ aliases[finalSlug] = {
273
302
  database_id: dbId,
274
303
  data_source_id: dsId,
275
304
  };
@@ -278,9 +307,10 @@ program
278
307
  added.push(finalSlug);
279
308
  }
280
309
 
310
+ config.workspaces[wsName].aliases = aliases;
281
311
  saveConfig(config);
282
312
  console.log('');
283
- console.log(`${added.length} alias${added.length !== 1 ? 'es' : ''} saved automatically.`);
313
+ console.log(`${added.length} alias${added.length !== 1 ? 'es' : ''} saved to workspace "${wsName}".`);
284
314
  console.log('');
285
315
  console.log('Ready! Try:');
286
316
  if (added.length > 0) {
@@ -308,7 +338,9 @@ alias
308
338
  .description('Add a database alias (auto-discovers data_source_id)')
309
339
  .action(async (name, databaseId) => {
310
340
  const config = loadConfig();
311
- if (!config.aliases) config.aliases = {};
341
+ const wsName = getWorkspaceName() || config.activeWorkspace || 'default';
342
+ if (!config.workspaces[wsName]) config.workspaces[wsName] = { aliases: {} };
343
+ const aliases = config.workspaces[wsName].aliases || {};
312
344
 
313
345
  // Try to discover the data_source_id by searching for this database
314
346
  const notion = getNotion();
@@ -328,9 +360,9 @@ alias
328
360
 
329
361
  if (match) {
330
362
  dataSourceId = match.id;
331
- // The database_id might differ from data_source_id
332
- const dbId = match.database_id || databaseId;
333
- config.aliases[name] = {
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] = {
334
366
  database_id: dbId,
335
367
  data_source_id: dataSourceId,
336
368
  };
@@ -340,7 +372,7 @@ alias
340
372
  console.log(` data_source_id: ${dataSourceId}`);
341
373
  } else {
342
374
  // Couldn't find via search — use the ID for both
343
- config.aliases[name] = {
375
+ aliases[name] = {
344
376
  database_id: databaseId,
345
377
  data_source_id: databaseId,
346
378
  };
@@ -349,7 +381,7 @@ alias
349
381
  }
350
382
  } catch (err) {
351
383
  // Fallback: use same ID for both
352
- config.aliases[name] = {
384
+ aliases[name] = {
353
385
  database_id: databaseId,
354
386
  data_source_id: databaseId,
355
387
  };
@@ -357,6 +389,7 @@ alias
357
389
  console.log(` (Auto-discovery failed: ${err.message})`);
358
390
  }
359
391
 
392
+ config.workspaces[wsName].aliases = aliases;
360
393
  saveConfig(config);
361
394
  });
362
395
 
@@ -364,16 +397,17 @@ alias
364
397
  .command('list')
365
398
  .description('Show all configured database aliases')
366
399
  .action(() => {
367
- const config = loadConfig();
368
- const aliases = config.aliases || {};
400
+ const ws = getWorkspaceConfig();
401
+ const aliases = ws.aliases || {};
369
402
  const names = Object.keys(aliases);
370
403
 
371
404
  if (names.length === 0) {
372
- console.log('No aliases configured.');
405
+ console.log(`No aliases in workspace "${ws.name}".`);
373
406
  console.log('Add one with: notion alias add <name> <database-id>');
374
407
  return;
375
408
  }
376
409
 
410
+ console.log(`Workspace: ${ws.name}\n`);
377
411
  const rows = names.map(name => ({
378
412
  alias: name,
379
413
  database_id: aliases[name].database_id,
@@ -387,17 +421,20 @@ alias
387
421
  .description('Remove a database alias')
388
422
  .action((name) => {
389
423
  const config = loadConfig();
390
- if (!config.aliases || !config.aliases[name]) {
391
- console.error(`Alias "${name}" not found.`);
392
- const names = config.aliases ? Object.keys(config.aliases) : [];
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);
393
429
  if (names.length > 0) {
394
430
  console.error(`Available: ${names.join(', ')}`);
395
431
  }
396
432
  process.exit(1);
397
433
  }
398
- delete config.aliases[name];
434
+ delete aliases[name];
435
+ config.workspaces[wsName].aliases = aliases;
399
436
  saveConfig(config);
400
- console.log(`✅ Removed alias "${name}"`);
437
+ console.log(`✅ Removed alias "${name}" from workspace "${wsName}"`);
401
438
  });
402
439
 
403
440
  alias
@@ -405,22 +442,104 @@ alias
405
442
  .description('Rename a database alias')
406
443
  .action((oldName, newName) => {
407
444
  const config = loadConfig();
408
- if (!config.aliases || !config.aliases[oldName]) {
409
- console.error(`Alias "${oldName}" not found.`);
410
- const names = config.aliases ? Object.keys(config.aliases) : [];
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);
411
450
  if (names.length > 0) {
412
451
  console.error(`Available: ${names.join(', ')}`);
413
452
  }
414
453
  process.exit(1);
415
454
  }
416
- if (config.aliases[newName]) {
455
+ if (aliases[newName]) {
417
456
  console.error(`Alias "${newName}" already exists. Remove it first or pick a different name.`);
418
457
  process.exit(1);
419
458
  }
420
- config.aliases[newName] = config.aliases[oldName];
421
- delete config.aliases[oldName];
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;
422
523
  saveConfig(config);
423
- console.log(`✅ Renamed "${oldName}" → "${newName}"`);
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}"`);
424
543
  });
425
544
 
426
545
  // ─── search ────────────────────────────────────────────────────────────────────
@@ -619,7 +738,43 @@ program
619
738
  console.log('');
620
739
  console.log('Properties:');
621
740
  for (const [name, prop] of Object.entries(page.properties)) {
622
- console.log(` ${name}: ${propValue(prop)}`);
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
+ }
623
778
  }
624
779
  } catch (err) {
625
780
  console.error('Get failed:', err.message);
@@ -632,6 +787,7 @@ program
632
787
  .command('blocks <page-or-alias>')
633
788
  .description('Get page content as rendered blocks by ID or alias + filter')
634
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)')
635
791
  .action(async (target, opts, cmd) => {
636
792
  try {
637
793
  const notion = getNotion();
@@ -663,7 +819,8 @@ program
663
819
  : type === 'code' ? '```\n'
664
820
  : '';
665
821
  const suffix = type === 'code' ? '\n```' : '';
666
- console.log(`${prefix}${text}${suffix}`);
822
+ const idTag = opts.ids ? `[${block.id.slice(0, 8)}] ` : '';
823
+ console.log(`${idTag}${prefix}${text}${suffix}`);
667
824
  }
668
825
  } catch (err) {
669
826
  console.error('Blocks failed:', err.message);
@@ -671,6 +828,165 @@ program
671
828
  }
672
829
  });
673
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
+
674
990
  // ─── dbs ───────────────────────────────────────────────────────────────────────
675
991
  program
676
992
  .command('dbs')
@@ -843,5 +1159,417 @@ program
843
1159
  }
844
1160
  });
845
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
+ const res = await notion.databases.create({
1312
+ parent: { type: 'page_id', page_id: parentPageId },
1313
+ title: [{ text: { content: title } }],
1314
+ properties,
1315
+ });
1316
+
1317
+ if (getGlobalJson(cmd)) {
1318
+ console.log(JSON.stringify(res, null, 2));
1319
+ return;
1320
+ }
1321
+
1322
+ console.log(`✅ Created database: ${res.id.slice(0, 8)}…`);
1323
+ console.log(` Title: ${title}`);
1324
+ console.log(` Properties: ${Object.keys(properties).join(', ')}`);
1325
+
1326
+ // Auto-create alias if requested
1327
+ if (opts.alias) {
1328
+ const config = loadConfig();
1329
+ const wsName = getWorkspaceName() || config.activeWorkspace || 'default';
1330
+ if (!config.workspaces[wsName]) config.workspaces[wsName] = { aliases: {} };
1331
+ if (!config.workspaces[wsName].aliases) config.workspaces[wsName].aliases = {};
1332
+ config.workspaces[wsName].aliases[opts.alias] = {
1333
+ database_id: res.database_id || res.id,
1334
+ data_source_id: res.id,
1335
+ };
1336
+ saveConfig(config);
1337
+ console.log(` Alias: ${opts.alias}`);
1338
+ }
1339
+ } catch (err) {
1340
+ console.error('Database create failed:', err.message);
1341
+ process.exit(1);
1342
+ }
1343
+ });
1344
+
1345
+ // ─── db-update ─────────────────────────────────────────────────────────────────
1346
+ program
1347
+ .command('db-update <database>')
1348
+ .description('Update a database title or add properties')
1349
+ .option('--title <text>', 'New database title')
1350
+ .option('--add-prop <name:type...>', 'Add a property (e.g. --add-prop "Priority:number")', (v, prev) => prev.concat([v]), [])
1351
+ .option('--remove-prop <name...>', 'Remove a property by name', (v, prev) => prev.concat([v]), [])
1352
+ .action(async (db, opts, cmd) => {
1353
+ try {
1354
+ const notion = getNotion();
1355
+ const dbIds = resolveDb(db);
1356
+
1357
+ // databases.update() requires the canonical database_id, which may differ
1358
+ // from data_source_id. Resolve via dataSources.retrieve().parent.database_id.
1359
+ let canonicalId = dbIds.database_id;
1360
+ if (canonicalId === dbIds.data_source_id) {
1361
+ try {
1362
+ const ds = await notion.dataSources.retrieve({ data_source_id: canonicalId });
1363
+ if (ds.parent && ds.parent.type === 'database_id') {
1364
+ canonicalId = ds.parent.database_id;
1365
+ }
1366
+ } catch (_) { /* fall through with what we have */ }
1367
+ }
1368
+
1369
+ const params = { database_id: canonicalId };
1370
+
1371
+ if (opts.title) {
1372
+ params.title = [{ text: { content: opts.title } }];
1373
+ }
1374
+
1375
+ if (opts.addProp.length > 0 || opts.removeProp.length > 0) {
1376
+ params.properties = {};
1377
+
1378
+ for (const kv of opts.addProp) {
1379
+ const colonIdx = kv.indexOf(':');
1380
+ if (colonIdx === -1) {
1381
+ console.error(`Invalid property format: ${kv} (expected name:type)`);
1382
+ process.exit(1);
1383
+ }
1384
+ const name = kv.slice(0, colonIdx);
1385
+ const type = kv.slice(colonIdx + 1).toLowerCase();
1386
+ params.properties[name] = { [type]: {} };
1387
+ }
1388
+
1389
+ for (const name of opts.removeProp) {
1390
+ params.properties[name] = null;
1391
+ }
1392
+ }
1393
+
1394
+ const res = await notion.databases.update(params);
1395
+
1396
+ if (getGlobalJson(cmd)) {
1397
+ console.log(JSON.stringify(res, null, 2));
1398
+ return;
1399
+ }
1400
+
1401
+ console.log(`✅ Updated database: ${(dbIds.database_id || dbIds.data_source_id).slice(0, 8)}…`);
1402
+ if (opts.title) console.log(` Title: ${opts.title}`);
1403
+ if (opts.addProp.length > 0) console.log(` Added: ${opts.addProp.join(', ')}`);
1404
+ if (opts.removeProp.length > 0) console.log(` Removed: ${opts.removeProp.join(', ')}`);
1405
+ } catch (err) {
1406
+ console.error('Database update failed:', err.message);
1407
+ process.exit(1);
1408
+ }
1409
+ });
1410
+
1411
+ // ─── upload ────────────────────────────────────────────────────────────────────
1412
+ program
1413
+ .command('upload <page-or-alias> <file-path>')
1414
+ .description('Upload a file to a page')
1415
+ .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
1416
+ .action(async (target, filePath, opts, cmd) => {
1417
+ try {
1418
+ const notion = getNotion();
1419
+ const { pageId } = await resolvePageId(target, opts.filter);
1420
+
1421
+ // Resolve file path
1422
+ const absPath = path.resolve(filePath);
1423
+ if (!fs.existsSync(absPath)) {
1424
+ console.error(`File not found: ${absPath}`);
1425
+ process.exit(1);
1426
+ }
1427
+
1428
+ const filename = path.basename(absPath);
1429
+ const fileData = fs.readFileSync(absPath);
1430
+ const fileSize = fileData.length;
1431
+
1432
+ // Detect MIME type from extension
1433
+ const MIME_MAP = {
1434
+ '.txt': 'text/plain', '.csv': 'text/csv', '.html': 'text/html',
1435
+ '.json': 'application/json', '.pdf': 'application/pdf',
1436
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
1437
+ '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml',
1438
+ '.mp4': 'video/mp4', '.mp3': 'audio/mpeg', '.wav': 'audio/wav',
1439
+ '.zip': 'application/zip', '.doc': 'application/msword',
1440
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
1441
+ '.xls': 'application/vnd.ms-excel',
1442
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
1443
+ };
1444
+ const ext = path.extname(filename).toLowerCase();
1445
+ const mimeType = MIME_MAP[ext] || 'application/octet-stream';
1446
+
1447
+ // Step 1: Create file upload
1448
+ const upload = await notion.fileUploads.create({
1449
+ parent: { type: 'page_id', page_id: pageId },
1450
+ filename,
1451
+ });
1452
+ const uploadId = upload.id;
1453
+
1454
+ // Step 2: Send file data with correct content type
1455
+ await notion.fileUploads.send({
1456
+ file_upload_id: uploadId,
1457
+ file: { data: new Blob([fileData], { type: mimeType }), filename },
1458
+ part_number: '1',
1459
+ });
1460
+
1461
+ // Step 3: Append file block to page (no complete() needed — attach directly)
1462
+ await notion.blocks.children.append({
1463
+ block_id: pageId,
1464
+ children: [{
1465
+ object: 'block',
1466
+ type: 'file',
1467
+ file: {
1468
+ type: 'file_upload',
1469
+ file_upload: { id: uploadId },
1470
+ },
1471
+ }],
1472
+ });
1473
+
1474
+ if (getGlobalJson(cmd)) {
1475
+ console.log(JSON.stringify({ upload_id: uploadId, filename, size: fileSize, page_id: pageId }, null, 2));
1476
+ return;
1477
+ }
1478
+
1479
+ const sizeStr = fileSize > 1024 * 1024
1480
+ ? `${(fileSize / (1024 * 1024)).toFixed(1)} MB`
1481
+ : `${(fileSize / 1024).toFixed(1)} KB`;
1482
+
1483
+ console.log(`✅ Uploaded: ${filename} (${sizeStr})`);
1484
+ console.log(` Page: ${pageId.slice(0, 8)}…`);
1485
+ } catch (err) {
1486
+ console.error('Upload failed:', err.message);
1487
+ process.exit(1);
1488
+ }
1489
+ });
1490
+
1491
+ // ─── props ─────────────────────────────────────────────────────────────────────
1492
+ program
1493
+ .command('props <page-or-alias>')
1494
+ .description('List all properties with full paginated values')
1495
+ .option('--filter <key=value>', 'Filter to find the page (required when using an alias)')
1496
+ .action(async (target, opts, cmd) => {
1497
+ try {
1498
+ const notion = getNotion();
1499
+ const { pageId } = await resolvePageId(target, opts.filter);
1500
+ const page = await notion.pages.retrieve({ page_id: pageId });
1501
+
1502
+ if (getGlobalJson(cmd)) {
1503
+ console.log(JSON.stringify(page, null, 2));
1504
+ return;
1505
+ }
1506
+
1507
+ console.log(`Page: ${page.id}`);
1508
+ console.log(`URL: ${page.url}\n`);
1509
+
1510
+ for (const [name, prop] of Object.entries(page.properties)) {
1511
+ // For paginated properties (relation, rollup, rich_text, title, people),
1512
+ // use the property retrieval endpoint to get full values
1513
+ const needsPagination = ['relation', 'rollup', 'rich_text', 'title', 'people'].includes(prop.type);
1514
+
1515
+ if (needsPagination && prop.id) {
1516
+ try {
1517
+ const fullProp = await notion.pages.properties.retrieve({
1518
+ page_id: pageId,
1519
+ property_id: prop.id,
1520
+ });
1521
+
1522
+ if (fullProp.results) {
1523
+ // Paginated property — collect all results
1524
+ const items = fullProp.results;
1525
+ if (prop.type === 'relation') {
1526
+ if (items.length === 0) {
1527
+ console.log(` ${name}: (none)`);
1528
+ } else {
1529
+ const titles = [];
1530
+ for (const item of items) {
1531
+ const relId = item.relation?.id;
1532
+ if (relId) {
1533
+ try {
1534
+ const linked = await notion.pages.retrieve({ page_id: relId });
1535
+ let t = '';
1536
+ for (const [, p] of Object.entries(linked.properties)) {
1537
+ if (p.type === 'title') { t = propValue(p); break; }
1538
+ }
1539
+ titles.push(t || relId.slice(0, 8) + '…');
1540
+ } catch {
1541
+ titles.push(relId.slice(0, 8) + '…');
1542
+ }
1543
+ }
1544
+ }
1545
+ console.log(` ${name}: ${titles.join(', ')}`);
1546
+ }
1547
+ } else if (prop.type === 'rich_text' || prop.type === 'title') {
1548
+ const text = items.map(i => i[prop.type]?.plain_text || '').join('');
1549
+ console.log(` ${name}: ${text}`);
1550
+ } else if (prop.type === 'people') {
1551
+ const people = items.map(i => i.people?.name || i.people?.id || '').join(', ');
1552
+ console.log(` ${name}: ${people}`);
1553
+ } else {
1554
+ console.log(` ${name}: ${JSON.stringify(items)}`);
1555
+ }
1556
+ } else {
1557
+ // Non-paginated response
1558
+ console.log(` ${name}: ${propValue(fullProp)}`);
1559
+ }
1560
+ } catch {
1561
+ // Fallback to basic propValue
1562
+ console.log(` ${name}: ${propValue(prop)}`);
1563
+ }
1564
+ } else {
1565
+ console.log(` ${name}: ${propValue(prop)}`);
1566
+ }
1567
+ }
1568
+ } catch (err) {
1569
+ console.error('Props failed:', err.message);
1570
+ process.exit(1);
1571
+ }
1572
+ });
1573
+
846
1574
  // ─── Run ───────────────────────────────────────────────────────────────────────
847
1575
  program.parse();