onenote-cli 0.2.1-win32-arm64 → 0.2.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/.env.example +10 -0
- package/.gitattributes +7 -0
- package/.github/workflows/release.yml +170 -0
- package/.github/workflows/rust-npm-release.yml +109 -0
- package/.husky/pre-commit +1 -0
- package/.releaserc.json +15 -0
- package/.secretlintrc.json +3 -0
- package/CLAUDE.md +42 -0
- package/README.md +267 -0
- package/SKILL.md +77 -0
- package/docs/azure-app-registration.md +80 -0
- package/docs/development-notes.md +84 -0
- package/docs/graph-api-endpoints.md +131 -0
- package/docs/local-search-architecture.md +132 -0
- package/docs/onen0te-cli-analysis.md +130 -0
- package/docs/setup.md +141 -0
- package/docs/zhihu-intro.md +92 -0
- package/package.json +46 -12
- package/rustify/onenote +556 -0
- package/rustify/onenote-cli +556 -0
- package/rustify/package.json +3 -0
- package/src/auth.ts +359 -0
- package/src/cache.ts +1709 -0
- package/src/debug-tags.ts +207 -0
- package/src/export.ts +367 -0
- package/src/graph.ts +1480 -0
- package/src/index.ts +1176 -0
- package/src/markdown.ts +134 -0
- package/src/read-render.ts +621 -0
- package/src/sync-ui.tsx +220 -0
- package/tsconfig.json +16 -0
- package/bin/onenote-cli.exe +0 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Debug tool: scan .one binary files and dump all property IDs found near NoteTags property
|
|
3
|
+
* to help identify shape IDs for #question, #star, etc.
|
|
4
|
+
*
|
|
5
|
+
* Usage:
|
|
6
|
+
* bun run src/debug-tags.ts [section.one] [--page <title-fragment>]
|
|
7
|
+
* bun run src/debug-tags.ts --all
|
|
8
|
+
*
|
|
9
|
+
* Output: for each NoteTag occurrence, lists all 4-byte prid candidates in ±300 bytes
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
import { dirname } from "node:path";
|
|
15
|
+
|
|
16
|
+
const PKG_ROOT = dirname(import.meta.dir);
|
|
17
|
+
const CACHE_ROOT = join(PKG_ROOT, ".onenote", "cache");
|
|
18
|
+
|
|
19
|
+
// MS-ONESTORE property markers
|
|
20
|
+
const NOTE_TAGS_PROP = Buffer.from([0x89, 0x34, 0x00, 0x40]); // 0x40003489: NoteTags property container
|
|
21
|
+
const ACTION_ITEM_STATUS = Buffer.from([0x70, 0x34, 0x00, 0x10]); // 0x10003470: ActionItemStatus
|
|
22
|
+
const SIZE_MARKER = Buffer.from([0x10, 0x00, 0x00, 0x00]); // page GUID anchor marker
|
|
23
|
+
|
|
24
|
+
// Known property IDs for annotation
|
|
25
|
+
const KNOWN_PRIDS: Record<number, string> = {
|
|
26
|
+
0x10003470: "ActionItemStatus",
|
|
27
|
+
0x40003489: "NoteTags",
|
|
28
|
+
0x1c003481: "NoteTagHighlightColor?",
|
|
29
|
+
0x1c003483: "NoteTagTextColor?",
|
|
30
|
+
0x0c003482: "NoteTagShape?",
|
|
31
|
+
0x14003484: "NoteTagCreated?",
|
|
32
|
+
0x14003485: "NoteTagModified?",
|
|
33
|
+
0x1c003486: "NoteTagFontColor?",
|
|
34
|
+
0x2000346f: "ActionItemSchemaVersion?",
|
|
35
|
+
0x10003472: "ActionItemType?",
|
|
36
|
+
0x14003471: "ActionItemCompletionTime?",
|
|
37
|
+
0x10346f: "SchemaRevision?",
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function hex32(n: number) {
|
|
41
|
+
return "0x" + n.toString(16).padStart(8, "0");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function scanFile(buf: Buffer, label: string, pageFilter?: string) {
|
|
45
|
+
const pageAnchors: { offset: number; guidHex: string }[] = [];
|
|
46
|
+
|
|
47
|
+
// Extract page anchors (SIZE_MARKER + 16-byte GUID)
|
|
48
|
+
let p = 0;
|
|
49
|
+
while (p < buf.length - 20) {
|
|
50
|
+
const m = buf.indexOf(SIZE_MARKER, p);
|
|
51
|
+
if (m < 0) break;
|
|
52
|
+
const guidHex = buf.slice(m + 4, m + 20).toString("hex");
|
|
53
|
+
// Only accept if it looks like a real GUID (not all zeros)
|
|
54
|
+
if (!/^0{32}$/.test(guidHex)) {
|
|
55
|
+
pageAnchors.push({ offset: m, guidHex });
|
|
56
|
+
}
|
|
57
|
+
p = m + 1;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Find page name anchors: look for UTF-16LE strings near page GUID markers
|
|
61
|
+
// (simplified: just use offsets)
|
|
62
|
+
const getPageGuidAt = (offset: number): string => {
|
|
63
|
+
for (let i = pageAnchors.length - 1; i >= 0; i--) {
|
|
64
|
+
if (pageAnchors[i].offset <= offset) return pageAnchors[i].guidHex.slice(0, 8);
|
|
65
|
+
}
|
|
66
|
+
return "????????";
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
// Scan for all NOTE_TAGS_PROP occurrences
|
|
70
|
+
const tagOccurrences: { offset: number; props: Map<number, number[]> }[] = [];
|
|
71
|
+
|
|
72
|
+
let pos = 0;
|
|
73
|
+
while (true) {
|
|
74
|
+
const idx = buf.indexOf(NOTE_TAGS_PROP, pos);
|
|
75
|
+
if (idx < 0) break;
|
|
76
|
+
|
|
77
|
+
const windowStart = Math.max(0, idx - 16);
|
|
78
|
+
const windowEnd = Math.min(buf.length, idx + 400);
|
|
79
|
+
const window = buf.slice(windowStart, windowEnd);
|
|
80
|
+
|
|
81
|
+
// Extract all 4-byte values in window (aligned to 4)
|
|
82
|
+
const props = new Map<number, number[]>();
|
|
83
|
+
for (let i = 0; i + 4 <= window.length; i += 4) {
|
|
84
|
+
const v = window.readUInt32LE(i);
|
|
85
|
+
// Filter: top byte must be a known type prefix (0x10, 0x14, 0x18, 0x1c, 0x20, 0x24, 0x40, 0x0c)
|
|
86
|
+
const top = (v >>> 24) & 0xff;
|
|
87
|
+
if ([0x10, 0x14, 0x18, 0x1c, 0x20, 0x24, 0x40, 0x0c, 0x08].includes(top)) {
|
|
88
|
+
const offs = windowStart + i;
|
|
89
|
+
if (!props.has(v)) props.set(v, []);
|
|
90
|
+
props.get(v)!.push(offs);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
tagOccurrences.push({ offset: idx, props });
|
|
95
|
+
pos = idx + 1;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (tagOccurrences.length === 0) return;
|
|
99
|
+
|
|
100
|
+
console.log(`\n=== ${label} ===`);
|
|
101
|
+
console.log(` ${tagOccurrences.length} NoteTags occurrences found`);
|
|
102
|
+
|
|
103
|
+
// Aggregate: count how many occurrences each prop appears in
|
|
104
|
+
const propFreq = new Map<number, number>();
|
|
105
|
+
for (const occ of tagOccurrences) {
|
|
106
|
+
for (const [v] of occ.props) {
|
|
107
|
+
propFreq.set(v, (propFreq.get(v) ?? 0) + 1);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Print sorted by frequency (most common first)
|
|
112
|
+
console.log("\n Property ID frequencies (top byte = type prefix, next 3 = prop#):");
|
|
113
|
+
const sorted = [...propFreq.entries()]
|
|
114
|
+
.sort((a, b) => b[1] - a[1])
|
|
115
|
+
.slice(0, 30);
|
|
116
|
+
|
|
117
|
+
for (const [v, count] of sorted) {
|
|
118
|
+
const known = KNOWN_PRIDS[v] ?? "";
|
|
119
|
+
const freq = `(${count}/${tagOccurrences.length} occurrences)`;
|
|
120
|
+
console.log(` ${hex32(v)} ${freq} ${known}`);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// For each occurrence, print AIS status and all prid values
|
|
124
|
+
console.log("\n Per-occurrence detail:");
|
|
125
|
+
for (let i = 0; i < tagOccurrences.length; i++) {
|
|
126
|
+
const occ = tagOccurrences[i];
|
|
127
|
+
const pageHex = getPageGuidAt(occ.offset);
|
|
128
|
+
|
|
129
|
+
// Find AIS in vicinity
|
|
130
|
+
const vicinity = buf.slice(occ.offset, Math.min(buf.length, occ.offset + 300));
|
|
131
|
+
const aisRel = vicinity.indexOf(ACTION_ITEM_STATUS);
|
|
132
|
+
let statusStr = "no-AIS";
|
|
133
|
+
if (aisRel >= 0) {
|
|
134
|
+
const aisAbs = occ.offset + aisRel;
|
|
135
|
+
if (aisAbs + 14 <= buf.length) {
|
|
136
|
+
const status = buf.readUInt16LE(aisAbs + 12);
|
|
137
|
+
statusStr = status === 0 ? "☐ unchecked" : status === 1 ? "☑ checked" : `status=${status}`;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Collect ALL 4-byte aligned values near this occurrence with following value
|
|
142
|
+
const rawStart = Math.max(0, occ.offset - 4);
|
|
143
|
+
const raw = buf.slice(rawStart, Math.min(buf.length, occ.offset + 300));
|
|
144
|
+
const allVals: string[] = [];
|
|
145
|
+
for (let j = 0; j + 8 <= raw.length; j += 4) {
|
|
146
|
+
const v = raw.readUInt32LE(j);
|
|
147
|
+
const next = raw.readUInt32LE(j + 4);
|
|
148
|
+
const top = (v >>> 24) & 0xff;
|
|
149
|
+
if ([0x10, 0x14, 0x18, 0x1c, 0x20, 0x24, 0x40, 0x0c, 0x08].includes(top)) {
|
|
150
|
+
const known = KNOWN_PRIDS[v] ? `[${KNOWN_PRIDS[v]}]` : "";
|
|
151
|
+
allVals.push(`${hex32(v)}${known}=${hex32(next)}`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
console.log(` [${i + 1}] @${occ.offset} page~${pageHex} ${statusStr}`);
|
|
156
|
+
console.log(` prids: ${allVals.join(" ")}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function findOneFiles(dir: string): Promise<string[]> {
|
|
161
|
+
const files: string[] = [];
|
|
162
|
+
try {
|
|
163
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
164
|
+
for (const e of entries) {
|
|
165
|
+
const full = join(dir, e.name);
|
|
166
|
+
if (e.isDirectory()) {
|
|
167
|
+
files.push(...(await findOneFiles(full)));
|
|
168
|
+
} else if (e.name.endsWith(".one")) {
|
|
169
|
+
files.push(full);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
} catch {}
|
|
173
|
+
return files;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function main() {
|
|
177
|
+
const args = process.argv.slice(2);
|
|
178
|
+
const allMode = args.includes("--all");
|
|
179
|
+
const pageIdx = args.indexOf("--page");
|
|
180
|
+
const pageFilter = pageIdx >= 0 ? args[pageIdx + 1] : undefined;
|
|
181
|
+
const fileArgs = args.filter((a) => !a.startsWith("--") && a !== (pageFilter ?? "___"));
|
|
182
|
+
|
|
183
|
+
let files: string[];
|
|
184
|
+
if (fileArgs.length > 0) {
|
|
185
|
+
files = fileArgs;
|
|
186
|
+
} else if (allMode) {
|
|
187
|
+
files = await findOneFiles(CACHE_ROOT);
|
|
188
|
+
} else {
|
|
189
|
+
// Default: only files that have NOTE_TAGS_PROP hits
|
|
190
|
+
files = await findOneFiles(CACHE_ROOT);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
console.log(`Scanning ${files.length} .one file(s) for NoteTags property patterns...`);
|
|
194
|
+
|
|
195
|
+
let totalOcc = 0;
|
|
196
|
+
for (const f of files) {
|
|
197
|
+
const buf = await readFile(f);
|
|
198
|
+
const label = f.replace(CACHE_ROOT + "/", "");
|
|
199
|
+
// Quick check: has any NoteTags at all?
|
|
200
|
+
if (buf.indexOf(NOTE_TAGS_PROP) < 0) continue;
|
|
201
|
+
totalOcc++;
|
|
202
|
+
scanFile(buf, label, pageFilter);
|
|
203
|
+
}
|
|
204
|
+
console.log(`\nTotal files with NoteTags: ${totalOcc}`);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
main().catch(console.error);
|
package/src/export.ts
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
import { mkdir, readdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
3
|
+
import * as graph from "./graph";
|
|
4
|
+
import { renderHtmlForExport, renderHtmlForRead } from "./read-render";
|
|
5
|
+
|
|
6
|
+
export type ExportFormat = "md" | "html";
|
|
7
|
+
|
|
8
|
+
/** YYYY-MM-DD in local time, for [date] token expansion and frontmatter. */
|
|
9
|
+
function todayStamp(): string {
|
|
10
|
+
const d = new Date();
|
|
11
|
+
const pad = (n: number) => String(n).padStart(2, "0");
|
|
12
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Expand path tokens: [date] -> today's date (YYYY-MM-DD). */
|
|
16
|
+
export function substituteTokens(p: string): string {
|
|
17
|
+
return p.replace(/\[date\]/gi, todayStamp());
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const FILE_EXTS = new Set([".md", ".markdown", ".html", ".htm"]);
|
|
21
|
+
|
|
22
|
+
export function inferFormat(pathOrExplicit: string, explicit?: string): ExportFormat {
|
|
23
|
+
if (explicit) {
|
|
24
|
+
const f = explicit.toLowerCase();
|
|
25
|
+
if (f === "md" || f === "markdown") return "md";
|
|
26
|
+
if (f === "html" || f === "htm") return "html";
|
|
27
|
+
throw new Error(`Unknown format '${explicit}'. Use 'md' or 'html'.`);
|
|
28
|
+
}
|
|
29
|
+
const ext = extname(pathOrExplicit).toLowerCase();
|
|
30
|
+
if (ext === ".html" || ext === ".htm") return "html";
|
|
31
|
+
return "md";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Make a title safe as a single filesystem name. Unicode is preserved; only
|
|
35
|
+
* path-illegal characters, control chars, and trailing dots/spaces are removed. */
|
|
36
|
+
export function sanitizeFilename(title: string, fallback = "untitled"): string {
|
|
37
|
+
let s = (title ?? "")
|
|
38
|
+
// eslint-disable-next-line no-control-regex -- intentionally stripping control chars
|
|
39
|
+
.replace(/[\u0000-\u001f\u007f]/g, " ") // newlines/tabs are invalid in filenames
|
|
40
|
+
.replace(/[/\\:*?"<>|]/g, "-") // illegal on Windows/Unix
|
|
41
|
+
.replace(/\s+/g, " ")
|
|
42
|
+
.trim()
|
|
43
|
+
.replace(/^\.+/, "") // no leading dots (hidden files / traversal)
|
|
44
|
+
.replace(/[. ]+$/, ""); // no trailing dot/space (Windows)
|
|
45
|
+
// Keep filenames comfortably under the 255-byte limit, leaving room for an
|
|
46
|
+
// extension and a collision suffix. Truncate by codepoint on a byte budget.
|
|
47
|
+
const MAX_BYTES = 180;
|
|
48
|
+
if (Buffer.byteLength(s, "utf8") > MAX_BYTES) {
|
|
49
|
+
let out = "";
|
|
50
|
+
for (const ch of s) {
|
|
51
|
+
if (Buffer.byteLength(out + ch, "utf8") > MAX_BYTES) break;
|
|
52
|
+
out += ch;
|
|
53
|
+
}
|
|
54
|
+
s = out.trim().replace(/[. ]+$/, "");
|
|
55
|
+
}
|
|
56
|
+
// Windows reserved device names.
|
|
57
|
+
if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(s)) s = `_${s}`;
|
|
58
|
+
return s || fallback;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Return `name` (or `name.ext`) unique within `used`, appending " (2)", " (3)"… */
|
|
62
|
+
function uniqueName(base: string, used: Set<string>, ext = ""): string {
|
|
63
|
+
const make = (n: number) => (n === 1 ? `${base}${ext}` : `${base} (${n})${ext}`);
|
|
64
|
+
let n = 1;
|
|
65
|
+
while (used.has(make(n).toLowerCase())) n++;
|
|
66
|
+
const chosen = make(n);
|
|
67
|
+
used.add(chosen.toLowerCase());
|
|
68
|
+
return chosen;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function yamlQuote(v: string): string {
|
|
72
|
+
return `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, " ")}"`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function htmlAttr(v: string): string {
|
|
76
|
+
return v.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
type FrontMatter = {
|
|
80
|
+
title?: string;
|
|
81
|
+
source?: string;
|
|
82
|
+
notebook?: string;
|
|
83
|
+
section?: string;
|
|
84
|
+
exported?: string;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
function mdFrontMatter(fm: FrontMatter): string {
|
|
88
|
+
const lines = Object.entries(fm)
|
|
89
|
+
.filter(([, v]) => v !== undefined && v !== "")
|
|
90
|
+
.map(([k, v]) => `${k}: ${yamlQuote(String(v))}`);
|
|
91
|
+
return lines.length ? `---\n${lines.join("\n")}\n---\n\n` : "";
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Inject <meta name="onenote-*"> tags into an HTML document's <head>. */
|
|
95
|
+
function htmlWithMeta(html: string, fm: FrontMatter): string {
|
|
96
|
+
const metas = Object.entries(fm)
|
|
97
|
+
.filter(([, v]) => v !== undefined && v !== "")
|
|
98
|
+
.map(([k, v]) => `<meta name="onenote-${k}" content="${htmlAttr(String(v))}" />`)
|
|
99
|
+
.join("\n\t\t");
|
|
100
|
+
if (!metas) return html;
|
|
101
|
+
if (/<head\b[^>]*>/i.test(html)) {
|
|
102
|
+
return html.replace(/<head\b[^>]*>/i, (m) => `${m}\n\t\t${metas}`);
|
|
103
|
+
}
|
|
104
|
+
return `<head>\n\t\t${metas}\n\t</head>\n${html}`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function countFiles(dir: string): Promise<number> {
|
|
108
|
+
try {
|
|
109
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
110
|
+
return entries.filter((e) => e.isFile()).length;
|
|
111
|
+
} catch {
|
|
112
|
+
return 0;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Run `fn` over items with bounded concurrency, preserving order. */
|
|
117
|
+
async function mapPool<T, R>(items: T[], concurrency: number, fn: (item: T, i: number) => Promise<R>): Promise<R[]> {
|
|
118
|
+
const results: R[] = Array.from({ length: items.length });
|
|
119
|
+
let cursor = 0;
|
|
120
|
+
const width = Math.max(1, Math.min(concurrency, items.length));
|
|
121
|
+
await Promise.all(
|
|
122
|
+
Array.from({ length: width }, async () => {
|
|
123
|
+
while (true) {
|
|
124
|
+
const i = cursor++;
|
|
125
|
+
if (i >= items.length) break;
|
|
126
|
+
results[i] = await fn(items[i]!, i);
|
|
127
|
+
}
|
|
128
|
+
})
|
|
129
|
+
);
|
|
130
|
+
return results;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export type ExportSummary = {
|
|
134
|
+
rootPath: string;
|
|
135
|
+
format: ExportFormat;
|
|
136
|
+
kind: graph.ExportNode["kind"];
|
|
137
|
+
title: string;
|
|
138
|
+
pageCount: number;
|
|
139
|
+
assetCount: number;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
type Ctx = {
|
|
143
|
+
format: ExportFormat;
|
|
144
|
+
assetsDirOverride?: string;
|
|
145
|
+
log?: (msg: string) => void;
|
|
146
|
+
assetDirs: Set<string>;
|
|
147
|
+
pageCount: { n: number };
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
/** Render one page's HTML into a Markdown/HTML file at `filePath`, with media
|
|
151
|
+
* downloaded next to it (or into the shared --assets-dir) and frontmatter. */
|
|
152
|
+
async function writePageFile(
|
|
153
|
+
base: string,
|
|
154
|
+
page: { id: string; title: string; webUrl?: string },
|
|
155
|
+
filePath: string,
|
|
156
|
+
ctx: Ctx,
|
|
157
|
+
crumbs: { notebook?: string; section?: string }
|
|
158
|
+
): Promise<void> {
|
|
159
|
+
const outDir = dirname(filePath);
|
|
160
|
+
const assetDir = ctx.assetsDirOverride ?? join(outDir, "assets");
|
|
161
|
+
const html = await graph.fetchPageHtml(base, page.id);
|
|
162
|
+
|
|
163
|
+
const fm: FrontMatter = {
|
|
164
|
+
title: page.title || undefined,
|
|
165
|
+
source: page.webUrl,
|
|
166
|
+
notebook: crumbs.notebook,
|
|
167
|
+
section: crumbs.section,
|
|
168
|
+
exported: todayStamp(),
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
let body: string;
|
|
172
|
+
if (ctx.format === "html") {
|
|
173
|
+
const rendered = await renderHtmlForExport(html, { assetDir, linkBaseDir: outDir });
|
|
174
|
+
body = htmlWithMeta(rendered, fm);
|
|
175
|
+
} else {
|
|
176
|
+
const md = await renderHtmlForRead(html, { assetDir, linkBaseDir: outDir });
|
|
177
|
+
const heading = page.title ? `# ${page.title}\n\n` : "";
|
|
178
|
+
body = `${mdFrontMatter(fm)}${heading}${md}\n`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
await mkdir(outDir, { recursive: true });
|
|
182
|
+
await writeFile(filePath, body);
|
|
183
|
+
ctx.assetDirs.add(assetDir);
|
|
184
|
+
ctx.pageCount.n++;
|
|
185
|
+
ctx.log?.(` ${filePath}`);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Write an already-listed set of pages into `dir` (one file per page, by title). */
|
|
189
|
+
async function writeSectionPages(
|
|
190
|
+
base: string,
|
|
191
|
+
pages: { id: string; title: string; webUrl?: string }[],
|
|
192
|
+
dir: string,
|
|
193
|
+
ctx: Ctx,
|
|
194
|
+
crumbs: { notebook?: string; section?: string }
|
|
195
|
+
): Promise<void> {
|
|
196
|
+
ctx.log?.(`${crumbs.section ?? "section"}: ${pages.length} page(s) -> ${dir}`);
|
|
197
|
+
await mkdir(dir, { recursive: true });
|
|
198
|
+
|
|
199
|
+
// Assign unique filenames sequentially before fetching pages in parallel.
|
|
200
|
+
const used = new Set<string>();
|
|
201
|
+
const ext = ctx.format === "html" ? ".html" : ".md";
|
|
202
|
+
const planned = pages.map((p) => ({
|
|
203
|
+
page: p,
|
|
204
|
+
filePath: join(dir, uniqueName(sanitizeFilename(p.title, "untitled"), used, ext)),
|
|
205
|
+
}));
|
|
206
|
+
|
|
207
|
+
await mapPool(planned, 5, ({ page, filePath }) => writePageFile(base, page, filePath, ctx, crumbs));
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Export a section (by Graph section id) into `dir`. */
|
|
211
|
+
async function exportSection(
|
|
212
|
+
base: string,
|
|
213
|
+
sectionId: string,
|
|
214
|
+
dir: string,
|
|
215
|
+
ctx: Ctx,
|
|
216
|
+
crumbs: { notebook?: string; section?: string }
|
|
217
|
+
): Promise<void> {
|
|
218
|
+
const pages = await graph.listSectionPages(base, sectionId);
|
|
219
|
+
await writeSectionPages(base, pages, dir, ctx, crumbs);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Recursively export a notebook/section-group folder via the OneDrive tree.
|
|
224
|
+
* Used when the OneNote API refuses to enumerate a >5,000-item library.
|
|
225
|
+
*/
|
|
226
|
+
async function exportContainerViaDrive(
|
|
227
|
+
drivePath: string,
|
|
228
|
+
dir: string,
|
|
229
|
+
ctx: Ctx,
|
|
230
|
+
crumbs: { notebook?: string; section?: string }
|
|
231
|
+
): Promise<void> {
|
|
232
|
+
const { sections, groups } = await graph.listDriveContainer(drivePath);
|
|
233
|
+
await mkdir(dir, { recursive: true });
|
|
234
|
+
const usedDirs = new Set<string>();
|
|
235
|
+
for (const s of sections) {
|
|
236
|
+
const subdir = join(dir, uniqueName(sanitizeFilename(s.name, "section"), usedDirs));
|
|
237
|
+
const pages = await graph.listSectionPagesByGuidAll(s.sectionGuid);
|
|
238
|
+
await writeSectionPages("/me", pages, subdir, ctx, { ...crumbs, section: s.name });
|
|
239
|
+
}
|
|
240
|
+
for (const g of groups) {
|
|
241
|
+
const subdir = join(dir, uniqueName(sanitizeFilename(g.name, "group"), usedDirs));
|
|
242
|
+
await exportContainerViaDrive(g.drivePath, subdir, ctx, crumbs);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Recursively export a notebook or section group as a directory tree. */
|
|
247
|
+
async function exportContainer(
|
|
248
|
+
node: graph.ExportNode,
|
|
249
|
+
dir: string,
|
|
250
|
+
ctx: Ctx,
|
|
251
|
+
crumbs: { notebook?: string; section?: string }
|
|
252
|
+
): Promise<void> {
|
|
253
|
+
const parentType = node.kind === "notebook" ? "notebooks" : "sectionGroups";
|
|
254
|
+
const nextCrumbs = node.kind === "notebook" ? { ...crumbs, notebook: node.title } : crumbs;
|
|
255
|
+
const drivePath = "drivePath" in node ? node.drivePath : undefined;
|
|
256
|
+
await mkdir(dir, { recursive: true });
|
|
257
|
+
|
|
258
|
+
let sections: { id: string; displayName: string }[];
|
|
259
|
+
let groups: { id: string; displayName: string }[];
|
|
260
|
+
try {
|
|
261
|
+
[sections, groups] = await Promise.all([
|
|
262
|
+
graph.listChildSections(node.base, parentType, node.id),
|
|
263
|
+
graph.listChildSectionGroups(node.base, parentType, node.id),
|
|
264
|
+
]);
|
|
265
|
+
} catch (err: any) {
|
|
266
|
+
const over5000 =
|
|
267
|
+
err?.statusCode === 403 && /5,?000 OneNote items|document librar/i.test(err?.message ?? "");
|
|
268
|
+
if (over5000 && drivePath) {
|
|
269
|
+
// Library too large for the OneNote API — enumerate via the OneDrive tree.
|
|
270
|
+
ctx.log?.(
|
|
271
|
+
`(library exceeds Graph 5,000-item limit — enumerating "${node.title}" via OneDrive)`
|
|
272
|
+
);
|
|
273
|
+
return exportContainerViaDrive(drivePath, dir, ctx, nextCrumbs);
|
|
274
|
+
}
|
|
275
|
+
if (over5000) {
|
|
276
|
+
throw new Error(
|
|
277
|
+
`Cannot enumerate the ${node.kind} "${node.title}": this OneDrive library exceeds the ` +
|
|
278
|
+
`Graph API's 5,000-OneNote-item limit and its OneDrive path could not be resolved. ` +
|
|
279
|
+
`Export sections individually instead — pass a section URL or path to 'onenote export'.`
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
throw err;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const usedDirs = new Set<string>();
|
|
286
|
+
for (const s of sections) {
|
|
287
|
+
const subdir = join(dir, uniqueName(sanitizeFilename(s.displayName, "section"), usedDirs));
|
|
288
|
+
await exportSection(node.base, s.id, subdir, ctx, { ...nextCrumbs, section: s.displayName });
|
|
289
|
+
}
|
|
290
|
+
for (const g of groups) {
|
|
291
|
+
const subdir = join(dir, uniqueName(sanitizeFilename(g.displayName, "group"), usedDirs));
|
|
292
|
+
await exportContainer(
|
|
293
|
+
{ kind: "sectionGroup", base: node.base, id: g.id, title: g.displayName },
|
|
294
|
+
subdir,
|
|
295
|
+
ctx,
|
|
296
|
+
nextCrumbs
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Export a OneNote page, section, section group, or notebook.
|
|
303
|
+
* - page -> a single Markdown/HTML file (format from output extension).
|
|
304
|
+
* - section/group/notebook -> a directory tree, one file per page named by its
|
|
305
|
+
* sanitized title, format chosen by --format (default Markdown).
|
|
306
|
+
* Media is downloaded next to each file (`<dir>/assets`, or --assets-dir).
|
|
307
|
+
*/
|
|
308
|
+
export async function exportRef(
|
|
309
|
+
ref: string,
|
|
310
|
+
output: string,
|
|
311
|
+
opts?: { assetsDir?: string; format?: string; log?: (msg: string) => void }
|
|
312
|
+
): Promise<ExportSummary> {
|
|
313
|
+
const node = await graph.resolveExportNode(ref);
|
|
314
|
+
const outPath = resolve(substituteTokens(output));
|
|
315
|
+
const assetsDirOverride = opts?.assetsDir ? resolve(substituteTokens(opts.assetsDir)) : undefined;
|
|
316
|
+
|
|
317
|
+
const ctx: Ctx = {
|
|
318
|
+
format: "md",
|
|
319
|
+
assetsDirOverride,
|
|
320
|
+
log: opts?.log,
|
|
321
|
+
assetDirs: new Set<string>(),
|
|
322
|
+
pageCount: { n: 0 },
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
if (node.kind === "page") {
|
|
326
|
+
// Output may be a concrete file, or a directory to place <title>.<ext> in.
|
|
327
|
+
const asFile = FILE_EXTS.has(extname(outPath).toLowerCase());
|
|
328
|
+
ctx.format = inferFormat(asFile ? outPath : "", opts?.format);
|
|
329
|
+
const ext = ctx.format === "html" ? ".html" : ".md";
|
|
330
|
+
const filePath = asFile
|
|
331
|
+
? outPath
|
|
332
|
+
: join(outPath, `${sanitizeFilename(node.title, "untitled")}${ext}`);
|
|
333
|
+
const pageForFm = { id: node.id, title: node.title, webUrl: node.webUrl ?? (/^https?:\/\//i.test(ref) ? ref : undefined) };
|
|
334
|
+
await writePageFile(node.base, pageForFm, filePath, ctx, {});
|
|
335
|
+
return {
|
|
336
|
+
rootPath: filePath,
|
|
337
|
+
format: ctx.format,
|
|
338
|
+
kind: node.kind,
|
|
339
|
+
title: node.title,
|
|
340
|
+
pageCount: ctx.pageCount.n,
|
|
341
|
+
assetCount: await sumAssets(ctx.assetDirs),
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// Container export -> directory tree.
|
|
346
|
+
ctx.format = inferFormat("", opts?.format);
|
|
347
|
+
if (node.kind === "section") {
|
|
348
|
+
await exportSection(node.base, node.id, outPath, ctx, { section: node.title });
|
|
349
|
+
} else {
|
|
350
|
+
await exportContainer(node, outPath, ctx, {});
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
return {
|
|
354
|
+
rootPath: outPath,
|
|
355
|
+
format: ctx.format,
|
|
356
|
+
kind: node.kind,
|
|
357
|
+
title: node.title,
|
|
358
|
+
pageCount: ctx.pageCount.n,
|
|
359
|
+
assetCount: await sumAssets(ctx.assetDirs),
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async function sumAssets(dirs: Set<string>): Promise<number> {
|
|
364
|
+
let total = 0;
|
|
365
|
+
for (const d of dirs) total += await countFiles(d);
|
|
366
|
+
return total;
|
|
367
|
+
}
|