@creator-notes/cnotes 0.122.0 → 0.124.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.
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { ApiClient } from "../lib/api-client.js";
|
|
2
|
+
import { resolveConfig } from "../lib/config.js";
|
|
3
|
+
import { handleError, ValidationError } from "../lib/errors.js";
|
|
4
|
+
import { outputJson, outputQuiet } from "../lib/output.js";
|
|
5
|
+
import { setIntentPreflight } from "../lib/intent-run.js";
|
|
6
|
+
import { buildImportItems, chunk, collectMarkdownFiles, DEFAULT_IMPORT_BATCH, MAX_IMPORT_BATCH, } from "../lib/note-import.js";
|
|
7
|
+
function collectTag(value, previous) {
|
|
8
|
+
return [...previous, value];
|
|
9
|
+
}
|
|
10
|
+
export function registerNotesImport(notes, program) {
|
|
11
|
+
const importCmd = notes
|
|
12
|
+
.command("import")
|
|
13
|
+
.description("Import published text (a newsletter archive, a blog) as notes: one note per markdown file.\n" +
|
|
14
|
+
" Each file names its published page in frontmatter (`source: <url>`). The note keeps the\n" +
|
|
15
|
+
" author's own title, unchecked by the headline rule, and stores the source, so importing\n" +
|
|
16
|
+
" the same folder again adds only the files that are new.")
|
|
17
|
+
.argument("<paths...>", "Folders of .md files (read recursively, in name order) or the files themselves")
|
|
18
|
+
.option("--type <type>", "Type for files whose frontmatter names none (an existing type, e.g. Essay)")
|
|
19
|
+
.option("--tag <tag>", "Tag every imported note (repeatable)", collectTag, [])
|
|
20
|
+
.option("--batch-size <n>", `Notes per request (default ${DEFAULT_IMPORT_BATCH}, at most ${MAX_IMPORT_BATCH})`)
|
|
21
|
+
.option("--dry-run", "Read and check every file, print what would be imported, and write nothing")
|
|
22
|
+
.addHelpText("after", `
|
|
23
|
+
File shape:
|
|
24
|
+
---
|
|
25
|
+
type: Essay
|
|
26
|
+
tags: [2024, strategy]
|
|
27
|
+
source: https://cutlefish.substack.com/p/tbm-383-maximizers-vs-focusers
|
|
28
|
+
---
|
|
29
|
+
# TBM 383: Maximizers vs. Focusers
|
|
30
|
+
|
|
31
|
+
The post as published.
|
|
32
|
+
|
|
33
|
+
The title is the file's # h1. \`tags\` also takes \`a, b\` or one \`- a\` line each;
|
|
34
|
+
\`sourceUrl\` and \`url\` are read as \`source\`. A file without a source is refused:
|
|
35
|
+
for notes of your own, use \`cnotes notes create\`.
|
|
36
|
+
|
|
37
|
+
Re-running:
|
|
38
|
+
A source the workspace already holds is returned as alreadyImported and not
|
|
39
|
+
written again, so a stopped import is finished by running it again, and next
|
|
40
|
+
week's posts are added by importing the whole folder again.
|
|
41
|
+
|
|
42
|
+
Examples:
|
|
43
|
+
$ cnotes notes import ./posts --type Essay --dry-run
|
|
44
|
+
$ cnotes notes import ./posts --type Essay --tag newsletter --intent "Imported The Beautiful Mess archive"
|
|
45
|
+
|
|
46
|
+
Output (--json):
|
|
47
|
+
{ files, imported: [{ key, displayId, title }], alreadyImported: [...] }. key is
|
|
48
|
+
the file's path relative to the current directory.
|
|
49
|
+
`)
|
|
50
|
+
.action(async (paths, opts) => {
|
|
51
|
+
const cfg = resolveConfig(program.opts());
|
|
52
|
+
try {
|
|
53
|
+
const size = opts.batchSize === undefined ? DEFAULT_IMPORT_BATCH : Number(opts.batchSize);
|
|
54
|
+
if (!Number.isInteger(size) || size < 1 || size > MAX_IMPORT_BATCH) {
|
|
55
|
+
throw new ValidationError(`--batch-size must be a whole number from 1 to ${MAX_IMPORT_BATCH}`);
|
|
56
|
+
}
|
|
57
|
+
const files = collectMarkdownFiles(paths);
|
|
58
|
+
if (files.length === 0) {
|
|
59
|
+
throw new ValidationError(`No .md files under ${paths.join(", ")}`);
|
|
60
|
+
}
|
|
61
|
+
const items = buildImportItems(files, { type: opts.type, tags: opts.tag });
|
|
62
|
+
if (opts.dryRun) {
|
|
63
|
+
if (cfg.json) {
|
|
64
|
+
outputJson({ files: files.length, dryRun: true, items: items.map(({ markdown, ...rest }) => ({ ...rest, chars: markdown.length })) });
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
console.log(`${items.length} file${items.length === 1 ? "" : "s"} ready to import; nothing was written.`);
|
|
68
|
+
for (const item of items)
|
|
69
|
+
console.log(` ${item.key} · ${item.type} · ${item.sourceUrl}`);
|
|
70
|
+
}
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const api = new ApiClient(cfg.serverUrl, cfg.token, cfg.workspaceId);
|
|
74
|
+
const imported = [];
|
|
75
|
+
const already = [];
|
|
76
|
+
const batches = chunk(items, size);
|
|
77
|
+
for (const [i, batch] of batches.entries()) {
|
|
78
|
+
let data;
|
|
79
|
+
try {
|
|
80
|
+
data = await api.post("/api/notes/bulk", {
|
|
81
|
+
action: "bulkCreate",
|
|
82
|
+
workspaceId: cfg.workspaceId,
|
|
83
|
+
notes: batch,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
// Every earlier batch is in; the same command run again skips
|
|
88
|
+
// them by their sources and carries on from here.
|
|
89
|
+
if (imported.length + already.length > 0) {
|
|
90
|
+
console.error(`Stopped at batch ${i + 1} of ${batches.length} (${batch[0].key} onward). ` +
|
|
91
|
+
`${imported.length} notes were imported before it. Run the same command again: ` +
|
|
92
|
+
"the notes already in are skipped, not copied.");
|
|
93
|
+
}
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
for (const result of data.results ?? []) {
|
|
97
|
+
(result.alreadyImported ? already : imported).push(result);
|
|
98
|
+
}
|
|
99
|
+
if (!cfg.json && !cfg.quiet && batches.length > 1) {
|
|
100
|
+
console.error(` batch ${i + 1}/${batches.length}: ${imported.length} imported, ${already.length} already in`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (cfg.quiet) {
|
|
104
|
+
imported.forEach((r) => outputQuiet(r.displayId));
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
const brief = (r) => ({ key: r.key, displayId: r.displayId, title: r.title });
|
|
108
|
+
if (cfg.json) {
|
|
109
|
+
outputJson({ files: files.length, imported: imported.map(brief), alreadyImported: already.map(brief) });
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
console.log(`Imported ${imported.length} note${imported.length === 1 ? "" : "s"}` +
|
|
113
|
+
(already.length > 0 ? `; ${already.length} already in the workspace, not copied` : ""));
|
|
114
|
+
for (const r of imported)
|
|
115
|
+
console.log(` ${r.displayId}: ${r.title || "(untitled)"}`);
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
handleError(error, cfg.json);
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
// Under --intent the run opens before the command runs: a folder that
|
|
122
|
+
// cannot be imported is refused here first, so it leaves no empty run.
|
|
123
|
+
setIntentPreflight(importCmd, (opts) => {
|
|
124
|
+
buildImportItems(collectMarkdownFiles(importCmd.args), {
|
|
125
|
+
type: opts.type,
|
|
126
|
+
tags: opts.tag,
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
}
|
package/dist/commands/notes.js
CHANGED
|
@@ -13,11 +13,13 @@ import { noteBatchIdempotencyKey, resolveNoteBatchItems } from "../lib/note-batc
|
|
|
13
13
|
import { describeUnresolvedMentions, lintNarratedVerbMentions, lintPlainTextDisplayIdsBatch, hasGenericMention, fetchRelationshipTypeOptions, } from "../lib/mention-lint.js";
|
|
14
14
|
import { attachRubricsToResults, loadRubricMap, rubricsForTypes, } from "../lib/rubrics.js";
|
|
15
15
|
import { DECISION_CARD_RULE, } from "../lib/decision-citation.js";
|
|
16
|
+
import { registerNotesImport } from "./notes-import.js";
|
|
16
17
|
export function registerNotesCommands(program) {
|
|
17
18
|
const notes = program
|
|
18
19
|
.command("notes")
|
|
19
20
|
.alias("n")
|
|
20
21
|
.description("Manage notes");
|
|
22
|
+
registerNotesImport(notes, program);
|
|
21
23
|
notes
|
|
22
24
|
.command("list")
|
|
23
25
|
.description("List notes in the current workspace")
|
package/dist/lib/intent-run.js
CHANGED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { join, relative, resolve } from "node:path";
|
|
3
|
+
import { ValidationError } from "./errors.js";
|
|
4
|
+
import { readFileSafe } from "./fs-utils.js";
|
|
5
|
+
/**
|
|
6
|
+
* `cnotes notes import`: published text (a newsletter archive, a blog) read
|
|
7
|
+
* from markdown files, one note per file. Each file names where it was
|
|
8
|
+
* published (`source:` in its frontmatter), which is what lets the server
|
|
9
|
+
* keep the author's own title and create each source once.
|
|
10
|
+
*/
|
|
11
|
+
/** The server takes at most 50 notes per batch; 25 keeps a batch of long posts well under a request's size. */
|
|
12
|
+
export const DEFAULT_IMPORT_BATCH = 25;
|
|
13
|
+
export const MAX_IMPORT_BATCH = 50;
|
|
14
|
+
const MARKDOWN_FILE = /\.(md|markdown)$/i;
|
|
15
|
+
/** Every markdown file under the given paths, sorted, so dated file names import oldest first. */
|
|
16
|
+
export function collectMarkdownFiles(paths) {
|
|
17
|
+
const files = [];
|
|
18
|
+
const walk = (path) => {
|
|
19
|
+
const stat = statSync(path);
|
|
20
|
+
if (stat.isDirectory()) {
|
|
21
|
+
for (const entry of readdirSync(path)) {
|
|
22
|
+
if (entry.startsWith("."))
|
|
23
|
+
continue;
|
|
24
|
+
walk(join(path, entry));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
else if (MARKDOWN_FILE.test(path)) {
|
|
28
|
+
files.push(path);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
for (const path of paths) {
|
|
32
|
+
try {
|
|
33
|
+
walk(resolve(path));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new ValidationError(`Cannot read ${path}: give a folder of .md files or the files themselves`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return Array.from(new Set(files)).sort();
|
|
40
|
+
}
|
|
41
|
+
function unquote(value) {
|
|
42
|
+
const v = value.trim();
|
|
43
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'")))
|
|
44
|
+
return v.slice(1, -1);
|
|
45
|
+
return v;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The frontmatter a markdown file opens with, as flat fields, and the body
|
|
49
|
+
* after it. Lists are `[a, b]`, `a, b`, or `- a` lines under the key.
|
|
50
|
+
*/
|
|
51
|
+
export function parseFrontmatter(text) {
|
|
52
|
+
const match = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text);
|
|
53
|
+
if (!match)
|
|
54
|
+
return { fields: {}, body: text };
|
|
55
|
+
const fields = {};
|
|
56
|
+
let listKey;
|
|
57
|
+
for (const line of match[1].split(/\r?\n/)) {
|
|
58
|
+
const item = /^\s*-\s+(.*)$/.exec(line);
|
|
59
|
+
if (item && listKey) {
|
|
60
|
+
const current = fields[listKey];
|
|
61
|
+
fields[listKey] = [...(Array.isArray(current) ? current : []), unquote(item[1])];
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const pair = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(line);
|
|
65
|
+
if (!pair)
|
|
66
|
+
continue;
|
|
67
|
+
const [, key, raw] = pair;
|
|
68
|
+
const value = raw.trim();
|
|
69
|
+
listKey = value === "" ? key : undefined;
|
|
70
|
+
if (value === "")
|
|
71
|
+
continue;
|
|
72
|
+
if (value.startsWith("[") && value.endsWith("]")) {
|
|
73
|
+
fields[key] = value.slice(1, -1).split(",").map(unquote).filter(Boolean);
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
fields[key] = unquote(value);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return { fields, body: text.slice(match[0].length) };
|
|
80
|
+
}
|
|
81
|
+
function asList(value) {
|
|
82
|
+
if (value === undefined)
|
|
83
|
+
return [];
|
|
84
|
+
return (Array.isArray(value) ? value : value.split(",")).map((t) => t.trim()).filter(Boolean);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* One import item per file, or every problem across all files at once so the
|
|
88
|
+
* whole folder is fixed in one pass before anything is written.
|
|
89
|
+
*/
|
|
90
|
+
export function buildImportItems(files, opts) {
|
|
91
|
+
const root = opts.root ?? process.cwd();
|
|
92
|
+
const errors = [];
|
|
93
|
+
const items = [];
|
|
94
|
+
for (const file of files) {
|
|
95
|
+
const name = relative(root, file) || file;
|
|
96
|
+
const { fields, body } = parseFrontmatter(readFileSafe(file));
|
|
97
|
+
const type = (typeof fields.type === "string" ? fields.type : opts.type ?? "").trim();
|
|
98
|
+
const rawSource = fields.source ?? fields.sourceUrl ?? fields.url;
|
|
99
|
+
const sourceUrl = typeof rawSource === "string" ? rawSource.trim() : "";
|
|
100
|
+
const markdown = body.trim();
|
|
101
|
+
if (!type)
|
|
102
|
+
errors.push({ file: name, field: "type", message: "no type: add `type: <Type>` to its frontmatter or pass --type" });
|
|
103
|
+
if (!sourceUrl) {
|
|
104
|
+
errors.push({
|
|
105
|
+
file: name,
|
|
106
|
+
field: "source",
|
|
107
|
+
message: "no source: add `source: <url of the published page>` to its frontmatter (for notes of your own, use `cnotes notes create`)",
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
if (!markdown)
|
|
111
|
+
errors.push({ file: name, field: "markdown", message: "the file has no text after its frontmatter" });
|
|
112
|
+
if (!type || !sourceUrl || !markdown)
|
|
113
|
+
continue;
|
|
114
|
+
const tags = Array.from(new Set([...asList(fields.tags), ...(opts.tags ?? [])]));
|
|
115
|
+
items.push({ key: name, type, markdown, sourceUrl, ...(tags.length > 0 ? { tags } : {}) });
|
|
116
|
+
}
|
|
117
|
+
if (errors.length > 0) {
|
|
118
|
+
const lines = errors.map((e) => ` - ${e.file}: ${e.message}`);
|
|
119
|
+
throw new ValidationError(`${new Set(errors.map((e) => e.file)).size} of ${files.length} file${files.length === 1 ? "" : "s"} cannot be imported; nothing was sent\n${lines.join("\n")}`, undefined, { files: errors });
|
|
120
|
+
}
|
|
121
|
+
return items;
|
|
122
|
+
}
|
|
123
|
+
export function chunk(items, size) {
|
|
124
|
+
const out = [];
|
|
125
|
+
for (let i = 0; i < items.length; i += size)
|
|
126
|
+
out.push(items.slice(i, i + size));
|
|
127
|
+
return out;
|
|
128
|
+
}
|