@helpfeel/cosense-cli 1.18.0 → 1.19.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@helpfeel/cosense-cli",
3
- "version": "1.18.0",
3
+ "version": "1.19.0",
4
4
  "description": "Cosense (旧Scrapbox) のページを読み・調べ・編集するAgent Skillのハーネス",
5
5
  "homepage": "https://github.com/helpfeel/cosense-cli",
6
6
  "license": "MIT",
@@ -29,8 +29,8 @@
29
29
  "devDependencies": {
30
30
  "@types/node": "24.19.2",
31
31
  "npm-run-all": "4.1.5",
32
- "oxfmt": "0.73.0",
33
- "oxlint": "1.88.0",
32
+ "oxfmt": "0.77.0",
33
+ "oxlint": "1.92.0",
34
34
  "typescript": "7.0.2"
35
35
  },
36
36
  "engines": {
package/src/cli.ts CHANGED
@@ -22,11 +22,21 @@ import {
22
22
  deleteFileHelp,
23
23
  deleteFileSummary
24
24
  } from './commands/deleteFile.ts';
25
+ import {
26
+ downloadCodeBlock,
27
+ downloadCodeBlockHelp,
28
+ downloadCodeBlockSummary
29
+ } from './commands/downloadCodeBlock.ts';
25
30
  import {
26
31
  downloadFile,
27
32
  downloadFileHelp,
28
33
  downloadFileSummary
29
34
  } from './commands/downloadFile.ts';
35
+ import {
36
+ downloadTable,
37
+ downloadTableHelp,
38
+ downloadTableSummary
39
+ } from './commands/downloadTable.ts';
30
40
  import {
31
41
  list1hopLinks,
32
42
  list1hopLinksHelp,
@@ -164,6 +174,16 @@ const commands: Record<string, CommandSpec> = {
164
174
  summary: readPageSnapshotSummary,
165
175
  help: readPageSnapshotHelp
166
176
  },
177
+ downloadCodeBlock: {
178
+ handler: downloadCodeBlock,
179
+ summary: downloadCodeBlockSummary,
180
+ help: downloadCodeBlockHelp
181
+ },
182
+ downloadTable: {
183
+ handler: downloadTable,
184
+ summary: downloadTableSummary,
185
+ help: downloadTableHelp
186
+ },
167
187
  readFileInfo: {
168
188
  handler: readFileInfo,
169
189
  summary: readFileInfoSummary,
@@ -1,3 +1,4 @@
1
+ import { listBlockFiles, renderBlockFiles } from '../lib/blocks.ts';
1
2
  import { enrichTimestampsOf } from '../lib/enrichTimestamps.ts';
2
3
  import {
3
4
  encodeTitleForReadableLink,
@@ -23,9 +24,9 @@ import {
23
24
  import { resolveCredential } from '../lib/settings.ts';
24
25
 
25
26
  export const browsePageSummary =
26
- '単一ページを読む。メタデータ+アイコン記法+テロメア+Infobox+本文をAIが読みやすい形式で出力する。行permalink (`#<lineId>`) 付きなら該当行をマークする';
27
+ '単一ページを読む。メタデータ+アイコン記法+テロメア+Infobox+コードブロック・テーブルのURL+本文をAIが読みやすい形式で出力する。行permalink (`#<lineId>`) 付きなら該当行をマークする';
27
28
 
28
- export const browsePageHelp = `browsePage - 単一ページを読む。メタデータ+アイコン記法+テロメア+Infobox+本文をAIが読みやすい形式で出力する。行permalink (#<lineId>) 付きなら該当行をマークする
29
+ export const browsePageHelp = `browsePage - 単一ページを読む。メタデータ+アイコン記法+テロメア+Infobox+コードブロック・テーブルのURL+本文をAIが読みやすい形式で出力する。行permalink (#<lineId>) 付きなら該当行をマークする
29
30
 
30
31
  Usage:
31
32
  cosense browsePage <pageUrl>
@@ -61,6 +62,14 @@ Usage:
61
62
  hallucination または truncated と判定された Infobox は除外する。
62
63
  0件の場合はセクションごと省略
63
64
 
65
+ ## コードブロック・テーブル
66
+ 本文中のコードブロック記法 (code:<ファイル名>) とテーブル記法 (table:<テーブル名>) が
67
+ 配信するファイルを、 - code:<ファイル名> (Nブロック) または - table:<テーブル名> (Nブロック)
68
+ と、次の行のURLで列挙する。同じ名前のブロックは上から順に連結されて1つのファイルに
69
+ なるので、1件にまとめる。URLを cosense downloadCodeBlock または cosense downloadTable に
70
+ 渡すと、そのファイルを保存できる。
71
+ 0件の場合はセクションごと省略
72
+
64
73
  ## 本文
65
74
  各行の text を改行で結合。fragment 指定行のみ末尾に #<lineId> を付与。
66
75
  本文中の、ページと同じhostのアップロードファイルURL (https://<host>/files/<fileId>[.<ext>])
@@ -96,7 +105,7 @@ Usage:
96
105
  ## 1 hop link(表に載っていないページ) に出力する
97
106
 
98
107
  persistent: false の時:
99
- アイコン・テロメア・Infoboxは省略し、メタデータはURLとReadable linkだけを出力する。
108
+ アイコン・テロメア・Infobox・コードブロック・テーブルは省略し、メタデータはURLとReadable linkだけを出力する。
100
109
  (このページはまだ作成されていません) と 本文(テンプレート)と Related Pages を出力する
101
110
 
102
111
  URLに #<lineId> fragmentが指定された時:
@@ -437,6 +446,14 @@ export const browsePage = async (args: string[]): Promise<void> => {
437
446
  const infoboxSection = renderInfobox(page.infoboxResult);
438
447
  if (infoboxSection) sections.push(infoboxSection);
439
448
 
449
+ const blockFilesSection = renderBlockFiles(
450
+ listBlockFiles(
451
+ (page.lines ?? []).map(line => line.text ?? ''),
452
+ { origin, projectName, title }
453
+ )
454
+ );
455
+ if (blockFilesSection) sections.push(blockFilesSection);
456
+
440
457
  sections.push(`## 本文\n\n${body}`);
441
458
 
442
459
  const related = renderRelatedPages(hopValue, page);
@@ -0,0 +1,48 @@
1
+ import { downloadBlock } from '../lib/downloadBlock.ts';
2
+
3
+ export const downloadCodeBlockSummary =
4
+ 'コードブロックをダウンロードしてローカルに保存する';
5
+
6
+ export const downloadCodeBlockHelp = `downloadCodeBlock - コードブロックをダウンロードしてローカルに保存する
7
+
8
+ Usage:
9
+ cosense downloadCodeBlock <codeBlockUrl> <outputPath>
10
+
11
+ 引数:
12
+ <codeBlockUrl> コードブロックのURL(例: https://scrapbox.io/api/code/shokai/foo/script.js)。
13
+ browsePage の「コードブロック・テーブル」に出力される。query/hashは付けない
14
+ <outputPath> 保存先ファイルパス。既存ファイルは上書きする。親ディレクトリは自動作成しない
15
+
16
+ 保存される内容:
17
+ 同じページにある同じファイル名のコードブロックを、上から順に連結した1つのファイル。
18
+ ファイル名は本文の code: の後ろの文字列。末尾に (言語名) を付けた code:Rakefile(rb) の
19
+ ファイル名は Rakefile。
20
+ コードブロックは、code: の行よりインデントが深い行が続く間。インデントが同じか浅い行で
21
+ 終わり、インデントの無い空行でも終わる
22
+
23
+ 出力(JSON):
24
+ path string 保存したファイルの絶対パス
25
+ contentType string | null 取得したファイルのContent-Type
26
+ size number 保存したファイルのbyte数
27
+
28
+ 例:
29
+ cosense downloadCodeBlock 'https://scrapbox.io/api/code/shokai/foo/script.js' ./script.js
30
+
31
+ HTTPエラー:
32
+ 401/403: 認証・権限が無い。private projectのコードブロックはproject member権限が必要
33
+ 404: ページが存在しない。または、そのファイル名のコードブロックがページに存在しないか、中身が1行も無い
34
+ `;
35
+
36
+ export const downloadCodeBlock = async (args: string[]): Promise<void> => {
37
+ const usage = 'Usage: cosense downloadCodeBlock <codeBlockUrl> <outputPath>';
38
+ const option = args.find(arg => arg.startsWith('--'));
39
+ if (option !== undefined) {
40
+ throw new Error(`Unknown option: ${option}\n${usage}`);
41
+ }
42
+ if (args.length !== 2) {
43
+ throw new Error(usage);
44
+ }
45
+ const [codeBlockUrl, outputPath] = args as [string, string];
46
+ const result = await downloadBlock('code', codeBlockUrl, outputPath);
47
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
48
+ };
@@ -0,0 +1,46 @@
1
+ import { downloadBlock } from '../lib/downloadBlock.ts';
2
+
3
+ export const downloadTableSummary =
4
+ 'テーブルをCSVでダウンロードしてローカルに保存する';
5
+
6
+ export const downloadTableHelp = `downloadTable - テーブルをCSVでダウンロードしてローカルに保存する
7
+
8
+ Usage:
9
+ cosense downloadTable <tableUrl> <outputPath>
10
+
11
+ 引数:
12
+ <tableUrl> テーブルのURL(例: https://scrapbox.io/api/table/shokai/foo/members.csv)。
13
+ browsePage の「コードブロック・テーブル」に出力される。query/hashは付けない
14
+ <outputPath> 保存先ファイルパス。既存ファイルは上書きする。親ディレクトリは自動作成しない
15
+
16
+ 保存される内容:
17
+ 同じページにある同じ名前のテーブルを、上から順に連結した1つのCSVファイル。
18
+ テーブルは、table: の行よりインデントが深い行が続く間。インデントが同じか浅い行で
19
+ 終わり、インデントの無い空行でも終わる
20
+
21
+ 出力(JSON):
22
+ path string 保存したファイルの絶対パス
23
+ contentType string | null 取得したファイルのContent-Type
24
+ size number 保存したファイルのbyte数
25
+
26
+ 例:
27
+ cosense downloadTable 'https://scrapbox.io/api/table/shokai/foo/members.csv' ./members.csv
28
+
29
+ HTTPエラー:
30
+ 401/403: 認証・権限が無い。private projectのテーブルはproject member権限が必要
31
+ 404: ページが存在しない。または、その名前のテーブルがページに存在しないか、中身が1行も無い
32
+ `;
33
+
34
+ export const downloadTable = async (args: string[]): Promise<void> => {
35
+ const usage = 'Usage: cosense downloadTable <tableUrl> <outputPath>';
36
+ const option = args.find(arg => arg.startsWith('--'));
37
+ if (option !== undefined) {
38
+ throw new Error(`Unknown option: ${option}\n${usage}`);
39
+ }
40
+ if (args.length !== 2) {
41
+ throw new Error(usage);
42
+ }
43
+ const [tableUrl, outputPath] = args as [string, string];
44
+ const result = await downloadBlock('table', tableUrl, outputPath);
45
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
46
+ };
@@ -0,0 +1,102 @@
1
+ import { encodePathSegment, encodeTitleForUrl } from './encodeTitle.ts';
2
+ import type { BlockKind } from './parseUrl.ts';
3
+
4
+ export interface BlockFile {
5
+ kind: BlockKind;
6
+ name: string;
7
+ blockCount: number;
8
+ url: string;
9
+ }
10
+
11
+ const countIndent = (text: string): number =>
12
+ (text.match(/^\s*/) as RegExpMatchArray)[0].length;
13
+
14
+ // 開始行でなければnull、開始行だが配信されないブロックなら空文字列を返す
15
+ type DetectStart = (text: string) => string | null;
16
+
17
+ const detectCodeBlockStart: DetectStart = text => {
18
+ // `code:Rakefile(rb)`の末尾の括弧は言語名で、ファイル名に含まれない
19
+ const match =
20
+ text.match(/^\s*code:(.+)\(([^()]+)\)$/) ?? text.match(/^\s*code:(.+)$/);
21
+ if (!match) return null;
22
+ const name = (match[1] as string).trim();
23
+ // 言語名が決まらない`code:foo.`のような行は、コードブロックにならない
24
+ const lang = match[2] ?? name.split('.').pop();
25
+ return lang ? name : null;
26
+ };
27
+
28
+ const detectTableStart: DetectStart = text => {
29
+ const match = text.match(/^\s*table:(.+)$/);
30
+ if (!match) return null;
31
+ // 名前が空白だけのテーブルは、半角スペース1個の名前で配信される
32
+ return (match[1] as string).trim() || ' ';
33
+ };
34
+
35
+ // 同じ名前のブロックは上から順に連結されて1つのファイルとして配信されるので、名前ごとにまとめる
36
+ const collectBlocks = (
37
+ lines: string[],
38
+ detectStart: DetectStart
39
+ ): Map<string, number> => {
40
+ const blockCounts = new Map<string, number>();
41
+ // 1行目はページタイトルで、ブロックの開始行にならない
42
+ for (let i = 1; i < lines.length; i += 1) {
43
+ const name = detectStart(lines[i] as string);
44
+ if (name === null) continue;
45
+ const indent = countIndent(lines[i] as string);
46
+ let end = i;
47
+ while (
48
+ end + 1 < lines.length &&
49
+ countIndent(lines[end + 1] as string) > indent
50
+ ) {
51
+ end += 1;
52
+ }
53
+ // 中身が1行も無い名前は配信されず404になる
54
+ if (name !== '' && end > i) {
55
+ blockCounts.set(name, (blockCounts.get(name) ?? 0) + 1);
56
+ }
57
+ // ブロックの中の`code:`や`table:`の行は、同じ種類のブロックの開始行にならない
58
+ i = end;
59
+ }
60
+ return blockCounts;
61
+ };
62
+
63
+ export const listBlockFiles = (
64
+ lines: string[],
65
+ page: { origin: string; projectName: string; title: string }
66
+ ): BlockFile[] => {
67
+ const pagePath = `${page.projectName}/${encodeTitleForUrl(page.title)}`;
68
+ const files: BlockFile[] = [];
69
+ // コードブロックとテーブルは互いに独立に検出する。コードブロックの中の`table:`行もテーブルとして配信される
70
+ for (const [name, blockCount] of collectBlocks(lines, detectCodeBlockStart)) {
71
+ files.push({
72
+ kind: 'code',
73
+ name,
74
+ blockCount,
75
+ // ファイル名の半角スペースは、タイトルと違って`_`に置換すると別の名前になる
76
+ url: `${page.origin}/api/code/${pagePath}/${encodePathSegment(name)}`
77
+ });
78
+ }
79
+ for (const [name, blockCount] of collectBlocks(lines, detectTableStart)) {
80
+ files.push({
81
+ kind: 'table',
82
+ name,
83
+ blockCount,
84
+ url: `${page.origin}/api/table/${pagePath}/${encodePathSegment(name)}.csv`
85
+ });
86
+ }
87
+ return files;
88
+ };
89
+
90
+ export const renderBlockFiles = (files: BlockFile[]): string | null => {
91
+ if (files.length === 0) return null;
92
+ const items = files.map(
93
+ file =>
94
+ `- ${file.kind}:${file.name} (${file.blockCount}ブロック)\n ${file.url}`
95
+ );
96
+ return (
97
+ '## コードブロック・テーブル\n\n' +
98
+ '同じ名前のブロックは上から順に連結され、1つのファイルとして配信される。' +
99
+ 'downloadCodeBlockコマンドやdownloadTableコマンドで保存できる\n\n' +
100
+ items.join('\n')
101
+ );
102
+ };
@@ -0,0 +1,13 @@
1
+ import { type BlockKind, parseBlockUrl } from './parseUrl.ts';
2
+ import { type DownloadResult, downloadToFile } from './request.ts';
3
+ import { resolveCredential } from './settings.ts';
4
+
5
+ export const downloadBlock = async (
6
+ kind: BlockKind,
7
+ url: string,
8
+ outputPath: string
9
+ ): Promise<DownloadResult> => {
10
+ const { origin, projectName, requestUrl } = parseBlockUrl(url, kind);
11
+ const credential = resolveCredential(origin, projectName);
12
+ return downloadToFile(requestUrl, outputPath, { credential });
13
+ };
@@ -1,14 +1,17 @@
1
1
  // 非ASCIIを生で残すと、`%2F`等と混ざったURLをmacOSのターミナルが開く時に`%`が再エンコードされ、別のページに飛ぶ
2
- // 半角スペースはCosenseの慣習で`_`に置換する
3
- export const encodeTitleForUrl = (title: string): string => {
2
+ export const encodePathSegment = (segment: string): string => {
4
3
  // 孤立サロゲートが残っているとencodeURIComponentが例外を投げる
5
- return encodeURIComponent(title.toWellFormed().replace(/ /g, '_')).replace(
4
+ return encodeURIComponent(segment.toWellFormed()).replace(
6
5
  // encodeURIComponentが残すRFC 3986の予約文字。括弧はMarkdownリンクのリンク先を、`'`はshellのクォートを壊しうる
7
6
  /[!'()*]/g,
8
7
  c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`
9
8
  );
10
9
  };
11
10
 
11
+ // 半角スペースはCosenseの慣習で`_`に置換する
12
+ export const encodeTitleForUrl = (title: string): string =>
13
+ encodePathSegment(title.replace(/ /g, '_'));
14
+
12
15
  // Cosenseの「Copy readable link」と同じく、日本語等を生で残して人が読めるURLにする
13
16
  // URLパーサーは`\`を`/`と解釈し、末尾のC0制御文字を取り除く。空白文字と`<>`は貼った先でURLの自動リンクを途中で切り、`'`はshellのクォートを壊す。これらを`/` `%` `?` `#`と共にエスケープする
14
17
  export const encodeTitleForReadableLink = (title: string): string =>
@@ -89,6 +89,49 @@ export const parseFileUrl = (input: string): FileUrl => {
89
89
  return { origin: u.origin, fileId: m[1] as string };
90
90
  };
91
91
 
92
+ export type BlockKind = 'code' | 'table';
93
+
94
+ export interface BlockUrl extends ProjectUrl {
95
+ requestUrl: string;
96
+ }
97
+
98
+ const BLOCK_URL_FORMATS: Record<BlockKind, string> = {
99
+ code: 'https://<host>/api/code/<project>/<title>/<filename>',
100
+ table: 'https://<host>/api/table/<project>/<title>/<name>.csv'
101
+ };
102
+
103
+ const BLOCK_COMMANDS: Record<BlockKind, string> = {
104
+ code: 'downloadCodeBlock',
105
+ table: 'downloadTable'
106
+ };
107
+
108
+ export const parseBlockUrl = (input: string, kind: BlockKind): BlockUrl => {
109
+ const label = kind === 'code' ? 'Code block' : 'Table';
110
+ const u = new URL(input);
111
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') {
112
+ throw new Error(`${label} URL must use http: or https: scheme: ${input}`);
113
+ }
114
+ if (u.search || u.hash) {
115
+ throw new Error(`${label} URL must not have query/hash, got: ${input}`);
116
+ }
117
+ const m = u.pathname.match(/^\/api\/(code|table)\/([^/]+)\/[^/]+\/([^/]+)$/);
118
+ if (m && m[1] !== kind) {
119
+ throw new Error(
120
+ `This is a ${m[1]} URL. Use \`cosense ${BLOCK_COMMANDS[m[1] as BlockKind]}\` instead: ${input}`
121
+ );
122
+ }
123
+ if (!m || (kind === 'table' && !/.\.csv$/.test(m[3] as string))) {
124
+ throw new Error(
125
+ `${label} URL must be ${BLOCK_URL_FORMATS[kind]}, got: ${input}`
126
+ );
127
+ }
128
+ return {
129
+ origin: u.origin,
130
+ projectName: m[2] as string,
131
+ requestUrl: `${u.origin}${u.pathname}`
132
+ };
133
+ };
134
+
92
135
  export const parsePageUrl = (input: string): PageUrl => {
93
136
  const u = new URL(input);
94
137
  const m = u.pathname.match(/^\/([^/]+)\/(.+?)\/?$/);