@dreamlake/dreamlake-cli 0.97.1 → 0.98.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/dist/api/client.d.ts +1 -1
- package/dist/api/client.js +4 -4
- package/dist/api/http.d.ts +48 -1
- package/dist/api/http.js +111 -4
- package/dist/api/index.d.ts +17 -513
- package/dist/api/index.js +6 -2
- package/dist/api/note-edits.d.ts +40 -2
- package/dist/api/note-edits.js +197 -2
- package/dist/api/note-events.d.ts +40 -4
- package/dist/api/note-events.js +55 -2
- package/dist/api/note-facade.d.ts +268 -0
- package/dist/api/note-facade.js +376 -0
- package/dist/api/note-reading.d.ts +27 -0
- package/dist/api/note-reading.js +27 -0
- package/dist/api/note-write.d.ts +110 -0
- package/dist/api/note-write.js +217 -0
- package/dist/api/notes.d.ts +33 -44
- package/dist/api/notes.js +44 -34
- package/dist/api/sessions.d.ts +5 -5
- package/dist/cli/client.d.ts +2 -41
- package/dist/cli/client.js +13 -90
- package/dist/cli/help-examples.generated.js +1 -1
- package/dist/cli/notes/api-transport.js +6 -6
- package/dist/cli/notes/document.d.ts +32 -26
- package/dist/cli/notes/document.js +150 -95
- package/dist/cli/notes/edit-commands.d.ts +26 -5
- package/dist/cli/notes/edit-commands.js +163 -36
- package/dist/cli/notes/events.d.ts +3 -33
- package/dist/cli/notes/events.js +4 -51
- package/dist/cli/notes/html-read.d.ts +6 -0
- package/dist/cli/notes/html-read.js +12 -0
- package/dist/cli/notes/index.d.ts +10 -1
- package/dist/cli/notes/index.js +98 -27
- package/dist/cli/notes/move-command.d.ts +4 -0
- package/dist/cli/notes/move-command.js +7 -0
- package/dist/cli/sessions/runner/native.js +14 -4
- package/dist/cli/sessions/runner/serve.d.ts +1 -1
- package/dist/cli/vault/sshTransfer.d.ts +1 -1
- package/dist/cli/version.d.ts +1 -1
- package/dist/cli/version.js +1 -1
- package/package.json +9 -9
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
/** The Notes API facade (Notes API contract, "Shared rules"):
|
|
2
|
+
*
|
|
3
|
+
* const note = dl.notes(noteId) // local and synchronous; IDs are primary
|
|
4
|
+
* const snapshot = await note.read()
|
|
5
|
+
* const receipt = await note.append({ text: "\nHello\n", at: snapshot })
|
|
6
|
+
* const page = await dl.notes.list({ namespace: "fortyfive", limit: 20, offset: 0 })
|
|
7
|
+
* const created = await dl.notes.create({ namespace: "fortyfive", name: "Review", text: "# Review\n" })
|
|
8
|
+
*
|
|
9
|
+
* `notes` is callable and carries the collection operations. Every operation
|
|
10
|
+
* takes one named object. A handle opened by stable ID needs no namespace: the
|
|
11
|
+
* owner is read from the note's metadata on first use; `{ namespace }` or a
|
|
12
|
+
* qualified `"namespace/slug"` reference supplies lookup context for slugs.
|
|
13
|
+
* `at` is a snapshot or a bare revision; a content hash is never accepted in
|
|
14
|
+
* its place. Edits compile to the same PATCH as the CLI through note-write.ts. */
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { seg } from "./client.js";
|
|
17
|
+
import { RequestNotSent } from "./http.js";
|
|
18
|
+
import { documentInsertion, noteEdits } from "./note-edits.js";
|
|
19
|
+
import * as editing from "./note-editing.js";
|
|
20
|
+
import { focusedRead, lineRange, readNoteView } from "./note-reading.js";
|
|
21
|
+
import { appendPlan, failureInfo, refuseReadingView, validateCommandId, writePlan } from "./note-write.js";
|
|
22
|
+
import { notesApi } from "./notes.js";
|
|
23
|
+
export class NoteReferenceInvalid extends Error {
|
|
24
|
+
constructor(ref) { super(`note reference must be a 24-hex id or "namespace/note", got ${JSON.stringify(ref)}`); this.name = "NoteReferenceInvalid"; }
|
|
25
|
+
}
|
|
26
|
+
export class RevisionExpected extends Error {
|
|
27
|
+
constructor(message) { super(message); this.name = "RevisionExpected"; }
|
|
28
|
+
}
|
|
29
|
+
export class ModeRequired extends Error {
|
|
30
|
+
constructor(received) { super(`mode must be "exact" or "merge" (received ${JSON.stringify(received)})`); this.name = "ModeRequired"; }
|
|
31
|
+
}
|
|
32
|
+
/** The Note's metadata was created but its initial source was not written (`definite`) or not confirmed
|
|
33
|
+
* (`uncertain`). Retry by writing or appending to `note`; creating again would make a second Note. */
|
|
34
|
+
export class NoteCreatedWithoutSource extends Error {
|
|
35
|
+
note;
|
|
36
|
+
namespace;
|
|
37
|
+
outcome;
|
|
38
|
+
constructor(note, namespace, outcome, options) {
|
|
39
|
+
super(`note ${note} was created in ${namespace} but its initial source was ${outcome === "definite" ? "not written" : "not confirmed"}; retry by writing or appending to that id, never by creating again`, options);
|
|
40
|
+
this.note = note;
|
|
41
|
+
this.namespace = namespace;
|
|
42
|
+
this.outcome = outcome;
|
|
43
|
+
this.name = "NoteCreatedWithoutSource";
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** A write through a handle with an explicit namespace found the note elsewhere: the asserted scope no longer
|
|
47
|
+
* holds it. Nothing was written; reopen the note by id (or with the discovered owner) and reconcile. */
|
|
48
|
+
export class NoteMoved extends Error {
|
|
49
|
+
note;
|
|
50
|
+
namespace;
|
|
51
|
+
owner;
|
|
52
|
+
constructor(note, namespace, owner, options) {
|
|
53
|
+
super(`note ${note} is not in the asserted namespace ${namespace}; its owner is ${owner}. Nothing was written: reopen it by id or with {namespace: "${owner}"} and reconcile`, options);
|
|
54
|
+
this.note = note;
|
|
55
|
+
this.namespace = namespace;
|
|
56
|
+
this.owner = owner;
|
|
57
|
+
this.name = "NoteMoved";
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** A documented target this client (or the current server) does not implement; nothing is invented in its place. */
|
|
61
|
+
export class UnsupportedTarget extends Error {
|
|
62
|
+
constructor(what) { super(`${what} is a documented Notes API target without an implementation in this client; nothing was sent`); this.name = "UnsupportedTarget"; }
|
|
63
|
+
}
|
|
64
|
+
const isId = (value) => /^[a-f0-9]{24}$/i.test(value);
|
|
65
|
+
export function parseNoteRef(ref) {
|
|
66
|
+
const slash = typeof ref === "string" ? ref.indexOf("/") : -1;
|
|
67
|
+
if (slash < 1 || slash === ref.length - 1 || /\s/.test(ref))
|
|
68
|
+
throw new NoteReferenceInvalid(ref);
|
|
69
|
+
return { namespace: ref.slice(0, slash), note: ref.slice(slash + 1) };
|
|
70
|
+
}
|
|
71
|
+
function validRevision(value, what) {
|
|
72
|
+
if (typeof value !== "string" || !value.trim() || value === "*" || /[\r\n]/.test(value))
|
|
73
|
+
throw new RevisionExpected(`${what} must be a retained revision string`);
|
|
74
|
+
if (/^sha256:/.test(value))
|
|
75
|
+
throw new RevisionExpected(`${what} is a sha256: content hash, not a revision; pass the snapshot or its revision`);
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
/** The baseline an edit was planned from: a snapshot's own revision, or the bare string. */
|
|
79
|
+
export function revisionOf(at) {
|
|
80
|
+
if (at !== null && typeof at === "object")
|
|
81
|
+
return validRevision(at.revision, "at.revision");
|
|
82
|
+
return validRevision(at, "at");
|
|
83
|
+
}
|
|
84
|
+
function validSnapshot(at, note) {
|
|
85
|
+
if (at.note !== note)
|
|
86
|
+
throw new RevisionExpected(`snapshot belongs to note ${at.note}, not ${note}`);
|
|
87
|
+
if (typeof at.content !== "string" || at.hash !== `sha256:${createHash("sha256").update(at.content, "utf8").digest("hex")}`)
|
|
88
|
+
throw new RevisionExpected("snapshot content does not match its hash");
|
|
89
|
+
validRevision(at.revision, "at.revision");
|
|
90
|
+
return at;
|
|
91
|
+
}
|
|
92
|
+
function modeOf(mode, fallback) {
|
|
93
|
+
if (mode === undefined && fallback)
|
|
94
|
+
return fallback;
|
|
95
|
+
if (mode !== "exact" && mode !== "merge")
|
|
96
|
+
throw new ModeRequired(mode);
|
|
97
|
+
return mode;
|
|
98
|
+
}
|
|
99
|
+
function exactlyOne(input, keys, what) {
|
|
100
|
+
const given = keys.filter(key => input[key] !== undefined);
|
|
101
|
+
if (given.length !== 1)
|
|
102
|
+
throw new TypeError(`${what} takes exactly one of ${keys.join(", ")}`);
|
|
103
|
+
return given[0];
|
|
104
|
+
}
|
|
105
|
+
/** A write that compiles to nothing is reported, not sent: the server observed nothing. */
|
|
106
|
+
function localNoWrite(snapshot, mode, commandId) {
|
|
107
|
+
return { note: snapshot.note, hash: snapshot.hash, revision: snapshot.revision, baseRevision: snapshot.revision, mode, outcome: "no-write", commandId: commandId ?? null, replayed: false };
|
|
108
|
+
}
|
|
109
|
+
const withCommand = (request, commandId) => commandId === undefined ? request : { ...request, commandId };
|
|
110
|
+
export function noteHandle(t, ref, context = {}) {
|
|
111
|
+
if (typeof ref !== "string")
|
|
112
|
+
throw new NoteReferenceInvalid(String(ref));
|
|
113
|
+
// An id needs no namespace; a slug needs one, qualified ("ns/slug") or given as context.
|
|
114
|
+
const parsed = isId(ref) ? { namespace: context.namespace, note: ref }
|
|
115
|
+
: ref.includes("/") ? parseNoteRef(ref)
|
|
116
|
+
: context.namespace !== undefined ? { namespace: context.namespace, note: ref }
|
|
117
|
+
: parseNoteRef(ref);
|
|
118
|
+
if (ref.includes("/") && context.namespace !== undefined && context.namespace !== parsed.namespace)
|
|
119
|
+
throw new NoteReferenceInvalid(ref);
|
|
120
|
+
let namespace = parsed.namespace;
|
|
121
|
+
/** An explicit scope (context or qualified reference) is an assertion: writes never cross it. */
|
|
122
|
+
const explicitScope = parsed.namespace !== undefined;
|
|
123
|
+
let resolved = isId(parsed.note) ? parsed.note : undefined;
|
|
124
|
+
const owner = async () => {
|
|
125
|
+
const row = await t.request("GET", `/notes/${resolved}`, { redirect: "error" });
|
|
126
|
+
if (!row || row.id !== resolved || typeof row.namespaceSlug !== "string" || !row.namespaceSlug)
|
|
127
|
+
throw new Error("note metadata did not name the owning namespace");
|
|
128
|
+
return row.namespaceSlug;
|
|
129
|
+
};
|
|
130
|
+
/** The namespace-scoped API; a bare id learns its owner from the note's metadata (one GET, cached). */
|
|
131
|
+
const scope = async () => notesApi(t, (namespace ??= await owner()));
|
|
132
|
+
const id = async (api) => (resolved ??= await api.resolve(parsed.note));
|
|
133
|
+
/** Run against the scope; on a 404 re-read the owner once. A handle opened by bare id follows a changed
|
|
134
|
+
* owner (cache updated, one retry, reads and writes alike). With an explicit scope a read may follow the
|
|
135
|
+
* discovered owner for this call only, while a write surfaces NoteMoved: nothing crosses the assertion. */
|
|
136
|
+
const guarded = async (run, kind = "read") => {
|
|
137
|
+
try {
|
|
138
|
+
return await run(await scope());
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
if (failureInfo(error).status !== 404 || resolved === undefined)
|
|
142
|
+
throw error;
|
|
143
|
+
const current = await owner();
|
|
144
|
+
if (current === namespace)
|
|
145
|
+
throw error;
|
|
146
|
+
if (explicitScope) {
|
|
147
|
+
if (kind === "write")
|
|
148
|
+
throw new NoteMoved(resolved, namespace, current, { cause: error });
|
|
149
|
+
return run(notesApi(t, current));
|
|
150
|
+
}
|
|
151
|
+
namespace = current;
|
|
152
|
+
return run(await scope());
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
/** The snapshot an edit is planned from: the one given, or the retained revision read now. */
|
|
156
|
+
const baseline = async (api, at) => at !== null && typeof at === "object" ? validSnapshot(at, await id(api)) : api.source(await id(api), revisionOf(at));
|
|
157
|
+
/** The exact span a selector names in this snapshot: source lines, or an element's full original span. */
|
|
158
|
+
const span = async (api, snapshot, selector) => {
|
|
159
|
+
if (selector.lines !== undefined)
|
|
160
|
+
return lineRange(snapshot.content, selector.lines).chars;
|
|
161
|
+
const range = await api.addressRange(snapshot.note, selector.address, snapshot.revision);
|
|
162
|
+
return [range.start, range.end];
|
|
163
|
+
};
|
|
164
|
+
const submit = (api, snapshot, request, commandId) => {
|
|
165
|
+
if (commandId !== undefined)
|
|
166
|
+
validateCommandId(commandId);
|
|
167
|
+
return api.patch(snapshot.note, withCommand(request, commandId), { baseline: snapshot });
|
|
168
|
+
};
|
|
169
|
+
const read = async (options = {}) => {
|
|
170
|
+
if (options.view !== undefined && options.view !== "source" && options.view !== "mapped")
|
|
171
|
+
throw new Error('view must be "source" or "mapped"');
|
|
172
|
+
const selectors = [options.lines, options.section, options.address].filter(v => v !== undefined).length;
|
|
173
|
+
if (selectors > 1)
|
|
174
|
+
throw new Error("select lines, section or address: exactly one");
|
|
175
|
+
if ((options.section !== undefined || options.address !== undefined) && options.view !== "mapped")
|
|
176
|
+
throw new Error('section and address select a mapped scope: pass view: "mapped"');
|
|
177
|
+
const at = options.at === undefined ? undefined : revisionOf(options.at);
|
|
178
|
+
return guarded(async (api) => {
|
|
179
|
+
const noteId = await id(api);
|
|
180
|
+
if (options.lines !== undefined)
|
|
181
|
+
return focusedRead(await api.source(noteId, at), options.lines);
|
|
182
|
+
if (options.view !== "mapped")
|
|
183
|
+
return api.source(noteId, at);
|
|
184
|
+
let start = 0, revision = at, text = "", first;
|
|
185
|
+
for (;;) {
|
|
186
|
+
const page = await readNoteView(t, namespace, noteId, { at: revision, start, section: options.section, tag: options.address });
|
|
187
|
+
first ??= page;
|
|
188
|
+
if (page.hash !== first.hash || page.total !== first.total)
|
|
189
|
+
throw new Error("Note reading view changed during pagination");
|
|
190
|
+
revision = page.revision;
|
|
191
|
+
text += page.text;
|
|
192
|
+
if (page.complete)
|
|
193
|
+
break;
|
|
194
|
+
start = page.next;
|
|
195
|
+
}
|
|
196
|
+
return { note: noteId, hash: first.hash, revision: first.revision, view: "mapped", sourceType: first.sourceType, scope: first.scope, text };
|
|
197
|
+
});
|
|
198
|
+
};
|
|
199
|
+
return {
|
|
200
|
+
ref, note: parsed.note,
|
|
201
|
+
get namespace() { return namespace; },
|
|
202
|
+
read: read,
|
|
203
|
+
async append(input) {
|
|
204
|
+
const mode = modeOf(input.mode, "merge");
|
|
205
|
+
if (typeof input.text !== "string")
|
|
206
|
+
throw new TypeError("text must be a string");
|
|
207
|
+
refuseReadingView(input.text, "append text");
|
|
208
|
+
return guarded(async (api) => {
|
|
209
|
+
const snapshot = await baseline(api, input.at), plan = appendPlan(snapshot, input.text, mode);
|
|
210
|
+
if (plan.request.patch === "")
|
|
211
|
+
return localNoWrite(snapshot, mode, input.commandId);
|
|
212
|
+
return submit(api, snapshot, plan.request, input.commandId);
|
|
213
|
+
}, "write");
|
|
214
|
+
},
|
|
215
|
+
async replace(input) {
|
|
216
|
+
const mode = modeOf(input.mode, "merge");
|
|
217
|
+
if (typeof input.text !== "string")
|
|
218
|
+
throw new TypeError("text must be a string");
|
|
219
|
+
exactlyOne(input, ["lines", "address"], "replace");
|
|
220
|
+
return guarded(async (api) => {
|
|
221
|
+
const snapshot = await baseline(api, input.at), [start, end] = await span(api, snapshot, input);
|
|
222
|
+
return submit(api, snapshot, noteEdits(snapshot, [{ start, end, text: input.text }], mode), input.commandId);
|
|
223
|
+
}, "write");
|
|
224
|
+
},
|
|
225
|
+
async insert(input) {
|
|
226
|
+
const mode = modeOf(input.mode, "merge");
|
|
227
|
+
if (typeof input.text !== "string")
|
|
228
|
+
throw new TypeError("text must be a string");
|
|
229
|
+
const placement = exactlyOne(input, ["before", "after", "cursor"], "insert");
|
|
230
|
+
return guarded(async (api) => {
|
|
231
|
+
const snapshot = await baseline(api, input.at);
|
|
232
|
+
let at;
|
|
233
|
+
if (placement === "cursor") {
|
|
234
|
+
const length = Array.from(snapshot.content).length;
|
|
235
|
+
if (!Number.isSafeInteger(input.cursor) || input.cursor < 0 || input.cursor > length)
|
|
236
|
+
throw new RangeError(`cursor must be a code-point position between 0 and ${length}`);
|
|
237
|
+
at = input.cursor;
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
const [start, end] = await span(api, snapshot, { address: placement === "before" ? input.before : input.after });
|
|
241
|
+
at = placement === "before" ? start : end;
|
|
242
|
+
}
|
|
243
|
+
return submit(api, snapshot, documentInsertion(snapshot, at, input.text, mode === "exact"), input.commandId);
|
|
244
|
+
}, "write");
|
|
245
|
+
},
|
|
246
|
+
async remove(input) {
|
|
247
|
+
const mode = modeOf(input.mode, "merge");
|
|
248
|
+
if ("text" in input)
|
|
249
|
+
throw new TypeError("remove takes no text; use replace to substitute a span");
|
|
250
|
+
exactlyOne(input, ["lines", "address"], "remove");
|
|
251
|
+
return guarded(async (api) => {
|
|
252
|
+
const snapshot = await baseline(api, input.at), [start, end] = await span(api, snapshot, input);
|
|
253
|
+
return submit(api, snapshot, noteEdits(snapshot, [{ start, end, text: "" }], mode), input.commandId);
|
|
254
|
+
}, "write");
|
|
255
|
+
},
|
|
256
|
+
async write(input) {
|
|
257
|
+
const mode = modeOf(input.mode);
|
|
258
|
+
if (typeof input.text !== "string")
|
|
259
|
+
throw new TypeError("text must be a string");
|
|
260
|
+
return guarded(async (api) => {
|
|
261
|
+
const snapshot = await baseline(api, input.at), request = writePlan(snapshot, input.text, mode);
|
|
262
|
+
// As the CLI: an unchanged merge write sends nothing, an unchanged exact write still asks the server to validate the baseline.
|
|
263
|
+
if (request.patch === "" && mode === "merge")
|
|
264
|
+
return localNoWrite(snapshot, mode, input.commandId);
|
|
265
|
+
return submit(api, snapshot, request, input.commandId);
|
|
266
|
+
}, "write");
|
|
267
|
+
},
|
|
268
|
+
async patch(input) {
|
|
269
|
+
const mode = modeOf(input.mode);
|
|
270
|
+
if (typeof input.patch !== "string" || !input.patch.trim())
|
|
271
|
+
throw new Error("patch is empty; nothing to send");
|
|
272
|
+
if (input.format !== "inline-dff" && input.format !== "diff")
|
|
273
|
+
throw new Error('format must be "inline-dff" or "diff"');
|
|
274
|
+
return guarded(async (api) => {
|
|
275
|
+
const snapshot = await baseline(api, input.at);
|
|
276
|
+
return submit(api, snapshot, { format: input.format, patch: input.patch, baseRevision: snapshot.revision, mode }, input.commandId);
|
|
277
|
+
}, "write");
|
|
278
|
+
},
|
|
279
|
+
async outline(options = {}) {
|
|
280
|
+
const at = options.at === undefined ? undefined : revisionOf(options.at);
|
|
281
|
+
return guarded(async (api) => api.outline(await id(api), at));
|
|
282
|
+
},
|
|
283
|
+
async find(input) {
|
|
284
|
+
const at = input.at === undefined || typeof input.at === "object" ? undefined : revisionOf(input.at);
|
|
285
|
+
return guarded(async (api) => {
|
|
286
|
+
const snapshot = input.at !== undefined && typeof input.at === "object" ? validSnapshot(input.at, await id(api)) : await api.source(await id(api), at);
|
|
287
|
+
// Literal searches are case-sensitive unless caseSensitive: false, which searches the escaped literal with the i flag.
|
|
288
|
+
const matches = input.text !== undefined && input.caseSensitive === false
|
|
289
|
+
? editing.find(snapshot.content, undefined, { regex: input.text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), flags: "i", limit: input.limit })
|
|
290
|
+
: editing.find(snapshot.content, input.text, { regex: input.regex, flags: input.flags, limit: input.limit });
|
|
291
|
+
return { note: snapshot.note, hash: snapshot.hash, revision: snapshot.revision, matches };
|
|
292
|
+
});
|
|
293
|
+
},
|
|
294
|
+
/** The same v2 incremental read as `notes read --since`: `since` is a retained revision, content hash or time reference. */
|
|
295
|
+
async diff(input) {
|
|
296
|
+
if (typeof input.since !== "string" || !input.since.trim())
|
|
297
|
+
throw new RevisionExpected("since must be a retained revision, content hash or time reference");
|
|
298
|
+
const format = input.format ?? "diff";
|
|
299
|
+
if (format !== "diff" && format !== "inline-dff")
|
|
300
|
+
throw new Error('format must be "diff" or "inline-dff"');
|
|
301
|
+
return guarded(async (api) => {
|
|
302
|
+
const noteId = await id(api);
|
|
303
|
+
const result = (await api.read(noteId, { since: input.since, format }));
|
|
304
|
+
if (!result || result.note !== noteId || result.format !== format || typeof result.patch !== "string" || !/^sha256:[a-f0-9]{64}$/.test(result.base ?? "")
|
|
305
|
+
|| !/^sha256:[a-f0-9]{64}$/.test(result.hash ?? "") || typeof result.revision !== "string" || !result.revision.trim() || /^sha256:/.test(result.revision)
|
|
306
|
+
|| (result.baseRevision !== undefined && (typeof result.baseRevision !== "string" || !result.baseRevision.trim() || /^sha256:/.test(result.baseRevision)))
|
|
307
|
+
|| (result.since !== undefined && typeof result.since !== "string"))
|
|
308
|
+
throw new Error("invalid incremental Notes v2 response");
|
|
309
|
+
return result;
|
|
310
|
+
});
|
|
311
|
+
},
|
|
312
|
+
async presence() { return guarded(async (api) => api.presence(await id(api))); },
|
|
313
|
+
async visit(input = {}) {
|
|
314
|
+
if (input.address !== undefined || input.cursor !== undefined)
|
|
315
|
+
throw new UnsupportedTarget("visit with a location (address/cursor)");
|
|
316
|
+
return guarded(async (api) => api.visit(await id(api), { intent: input.intent }), "write");
|
|
317
|
+
},
|
|
318
|
+
versions: {
|
|
319
|
+
list: async (options = {}) => guarded(async (api) => api.versions(await id(api), options)),
|
|
320
|
+
read: async ({ versionId }) => guarded(async (api) => api.version(await id(api), versionId)),
|
|
321
|
+
},
|
|
322
|
+
files: {
|
|
323
|
+
/** Destination = (`toFolder` or the file's current folder) / (`name` or the file's current name). */
|
|
324
|
+
move: async ({ file, toFolder, name }) => {
|
|
325
|
+
if (toFolder === undefined && name === undefined)
|
|
326
|
+
throw new TypeError("files.move needs toFolder, name or both");
|
|
327
|
+
return guarded(async (api) => {
|
|
328
|
+
const files = api.files(await id(api)), current = await files.resolve(file);
|
|
329
|
+
const segments = current.path.split("/"), currentName = segments.pop();
|
|
330
|
+
const folder = toFolder ?? segments.join("/"), base = name ?? currentName;
|
|
331
|
+
return files.move(current.id, folder ? `${folder}/${base}` : base);
|
|
332
|
+
}, "write");
|
|
333
|
+
},
|
|
334
|
+
},
|
|
335
|
+
async move(input) {
|
|
336
|
+
if (input.name !== undefined)
|
|
337
|
+
throw new UnsupportedTarget("move with a display-name change");
|
|
338
|
+
if (input.toFolder !== undefined)
|
|
339
|
+
throw new UnsupportedTarget("move into a deep project folder through the API");
|
|
340
|
+
if (input.toNamespace === undefined && input.toProject === undefined)
|
|
341
|
+
throw new TypeError("move needs at least one of toNamespace, toProject");
|
|
342
|
+
return guarded(async (api) => {
|
|
343
|
+
const noteId = await id(api);
|
|
344
|
+
const receipt = (await api.move(noteId, { namespace: input.toNamespace ?? namespace, projects: input.toProject === undefined ? [] : [input.toProject], dryRun: input.dryRun }));
|
|
345
|
+
// The note now lives in the destination: later calls through this handle target it.
|
|
346
|
+
if (!input.dryRun && input.toNamespace !== undefined && receipt?.moved !== false)
|
|
347
|
+
namespace = input.toNamespace;
|
|
348
|
+
return receipt;
|
|
349
|
+
}, "write");
|
|
350
|
+
},
|
|
351
|
+
commandStatus: async (commandId) => guarded(async (api) => api.commandStatus(await id(api), commandId)),
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
/** `dl.notes`: open one note by stable id or `"namespace/note"`, or reach the namespace API with a bare namespace literal. */
|
|
355
|
+
export function notesFacade(t) {
|
|
356
|
+
const open = ((ref, context) => typeof ref === "string" && (isId(ref) || ref.includes("/") || context?.namespace !== undefined) ? noteHandle(t, ref, context) : notesApi(t, ref));
|
|
357
|
+
open.open = (ref, context) => noteHandle(t, ref, context);
|
|
358
|
+
open.list = ({ namespace, ...query }) => notesApi(t, namespace).list(query);
|
|
359
|
+
open.namespace = namespace => notesApi(t, namespace);
|
|
360
|
+
open.create = async ({ namespace, name, text, visibility, projects }) => {
|
|
361
|
+
const created = await notesApi(t, namespace).create({ name: name ?? "Untitled", visibility, projects });
|
|
362
|
+
// Initial source is a second, unconditional write (as the CLI does); atomic creation is a server target.
|
|
363
|
+
if (text !== undefined) {
|
|
364
|
+
try {
|
|
365
|
+
await t.request("PUT", `/namespaces/${seg(namespace)}/notes/${created.note.id}/body`, { json: { text }, redirect: "error" });
|
|
366
|
+
}
|
|
367
|
+
catch (error) {
|
|
368
|
+
const status = failureInfo(error).status;
|
|
369
|
+
const outcome = error instanceof RequestNotSent || (status !== undefined && status >= 400 && status < 500) ? "definite" : "uncertain";
|
|
370
|
+
throw new NoteCreatedWithoutSource(created.note.id, namespace, outcome, { cause: error });
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return Object.assign(noteHandle(t, created.note.id, { namespace }), { id: created.note.id, created: created.note });
|
|
374
|
+
};
|
|
375
|
+
return open;
|
|
376
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type Transport } from './client.js';
|
|
2
|
+
import type { NoteSource } from './note-edits.js';
|
|
2
3
|
export interface NoteReadingOptions {
|
|
3
4
|
at?: string;
|
|
4
5
|
start?: number;
|
|
@@ -22,3 +23,29 @@ export interface NoteReadingPage {
|
|
|
22
23
|
}
|
|
23
24
|
/** Same addressed, revision-pinned reading contract as the built-in agent. */
|
|
24
25
|
export declare function readNoteView(t: Transport, namespace: string, note: string, options?: NoteReadingOptions): Promise<NoteReadingPage>;
|
|
26
|
+
export declare class InvalidLineRange extends Error {
|
|
27
|
+
constructor(message: string);
|
|
28
|
+
}
|
|
29
|
+
/** A focused read (contract section C): the exact slice with its global address. Never a complete body. */
|
|
30
|
+
export interface NoteFocusedRead {
|
|
31
|
+
note: string;
|
|
32
|
+
hash: string;
|
|
33
|
+
revision: string;
|
|
34
|
+
/** 1-based, inclusive source lines. */
|
|
35
|
+
lines: [number, number];
|
|
36
|
+
/** [start, end) in Unicode code points of the complete source. */
|
|
37
|
+
chars: [number, number];
|
|
38
|
+
/** What was selected, in the terms it was asked for. */
|
|
39
|
+
scope: {
|
|
40
|
+
lines: [number, number];
|
|
41
|
+
};
|
|
42
|
+
content: string;
|
|
43
|
+
complete: false;
|
|
44
|
+
/** The line after `lines[1]`, when the source has one. */
|
|
45
|
+
next?: number;
|
|
46
|
+
}
|
|
47
|
+
/** 1-based inclusive lines → a [start, end) code-point range of the source. The
|
|
48
|
+
* last line's newline belongs to it; a final newline does not start a line.
|
|
49
|
+
* Code points, never UTF-16 units, so CJK and emoji address correctly. */
|
|
50
|
+
export declare function lineRange(content: string, lines: [number, number]): Pick<NoteFocusedRead, 'lines' | 'chars' | 'content' | 'next'>;
|
|
51
|
+
export declare function focusedRead(snapshot: NoteSource, lines: [number, number]): NoteFocusedRead;
|
package/dist/api/note-reading.js
CHANGED
|
@@ -13,3 +13,30 @@ export async function readNoteView(t, namespace, note, options = {}) {
|
|
|
13
13
|
throw new Error('invalid Note reading page');
|
|
14
14
|
return page;
|
|
15
15
|
}
|
|
16
|
+
export class InvalidLineRange extends Error {
|
|
17
|
+
constructor(message) { super(message); this.name = 'InvalidLineRange'; }
|
|
18
|
+
}
|
|
19
|
+
/** 1-based inclusive lines → a [start, end) code-point range of the source. The
|
|
20
|
+
* last line's newline belongs to it; a final newline does not start a line.
|
|
21
|
+
* Code points, never UTF-16 units, so CJK and emoji address correctly. */
|
|
22
|
+
export function lineRange(content, lines) {
|
|
23
|
+
if (!Array.isArray(lines) || lines.length !== 2 || !lines.every(n => Number.isSafeInteger(n)))
|
|
24
|
+
throw new InvalidLineRange('lines must be two integers [first, last], 1-based and inclusive');
|
|
25
|
+
const [first, last] = lines;
|
|
26
|
+
if (first < 1 || last < first)
|
|
27
|
+
throw new InvalidLineRange(`line range ${first}:${last} is not a range; lines are 1-based and inclusive`);
|
|
28
|
+
const points = Array.from(content), starts = [0];
|
|
29
|
+
for (let i = 0; i < points.length; i++)
|
|
30
|
+
if (points[i] === '\n' && i + 1 < points.length)
|
|
31
|
+
starts.push(i + 1);
|
|
32
|
+
const total = points.length === 0 ? 0 : starts.length;
|
|
33
|
+
// Refused, not clamped: a range past the end is a misread length, not a request for "to the end".
|
|
34
|
+
if (last > total)
|
|
35
|
+
throw new InvalidLineRange(`line ${last} is past the end of a ${total}-line note`);
|
|
36
|
+
const start = starts[first - 1], end = last < total ? starts[last] : points.length;
|
|
37
|
+
return { lines: [first, last], chars: [start, end], content: points.slice(start, end).join(''), ...(last < total ? { next: last + 1 } : {}) };
|
|
38
|
+
}
|
|
39
|
+
export function focusedRead(snapshot, lines) {
|
|
40
|
+
const range = lineRange(snapshot.content, lines);
|
|
41
|
+
return { note: snapshot.note, hash: snapshot.hash, revision: snapshot.revision, lines: range.lines, chars: range.chars, scope: { lines: range.lines }, content: range.content, complete: false, ...(range.next === undefined ? {} : { next: range.next }) };
|
|
42
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/** Notes v2 body mutations: one submission path with command identity, receipt
|
|
2
|
+
* verification and typed outcomes. The CLI, the facade and the built-in agent
|
|
3
|
+
* all compile to this PATCH; nothing here reads process state. */
|
|
4
|
+
import { type Transport } from "./client.js";
|
|
5
|
+
import { type NotePatch, type NoteSource } from "./note-edits.js";
|
|
6
|
+
export { READING_VIEW_MARKER, READING_VIEW_HEADER, ReadingViewMarkerRefused, refuseReadingView, refuseNewReadingViewLines, refuseReadingViewPatch, applyInlineDff, applyUnifiedDiff } from "./note-edits.js";
|
|
7
|
+
/** Caller-stable command identity: 8–128 characters of `[A-Za-z0-9._:-]`, the server's rule. */
|
|
8
|
+
export declare const COMMAND_ID_PATTERN: RegExp;
|
|
9
|
+
export type NoteWriteMode = "merge" | "exact";
|
|
10
|
+
export type NoteWriteOutcome = "accepted" | "no-write";
|
|
11
|
+
export interface NotePatchRequest extends NotePatch {
|
|
12
|
+
/** Sent only when supplied; the receipt must echo it. */
|
|
13
|
+
commandId?: string;
|
|
14
|
+
}
|
|
15
|
+
/** The v2 write receipt. `outcome`, `commandId` and `replayed` are filled in for servers that predate them. */
|
|
16
|
+
export interface NoteWriteReceipt {
|
|
17
|
+
note: string;
|
|
18
|
+
hash: string;
|
|
19
|
+
revision: string;
|
|
20
|
+
baseRevision: string;
|
|
21
|
+
mode: NoteWriteMode;
|
|
22
|
+
outcome: NoteWriteOutcome;
|
|
23
|
+
commandId: string | null;
|
|
24
|
+
replayed: boolean;
|
|
25
|
+
}
|
|
26
|
+
export interface NoteCommandStatus {
|
|
27
|
+
commandId: string;
|
|
28
|
+
state: "pending" | "accepted" | "no-write" | "unknown";
|
|
29
|
+
outcome?: NoteWriteOutcome;
|
|
30
|
+
receipt?: NoteWriteReceipt;
|
|
31
|
+
error?: unknown;
|
|
32
|
+
createdAt: string;
|
|
33
|
+
updatedAt: string;
|
|
34
|
+
}
|
|
35
|
+
export declare class InvalidCommandId extends Error {
|
|
36
|
+
readonly commandId: unknown;
|
|
37
|
+
constructor(commandId: unknown);
|
|
38
|
+
}
|
|
39
|
+
/** The server accepted the write but did not echo the command id: it predates command identity, so a retry is not deduplicated. */
|
|
40
|
+
export declare class CommandIdentityUnsupported extends Error {
|
|
41
|
+
readonly commandId: string;
|
|
42
|
+
readonly receipt: unknown;
|
|
43
|
+
constructor(commandId: string, receipt: unknown);
|
|
44
|
+
}
|
|
45
|
+
/** The request may or may not have been applied. Keep the original baseline and draft.
|
|
46
|
+
* `transport`: lost acknowledgment (network, 5xx, 503); `receipt`: the server
|
|
47
|
+
* answered but the receipt cannot be verified; `server`: the server recorded
|
|
48
|
+
* the command and reports its own outcome as unknown (409 command_outcome_unknown). */
|
|
49
|
+
export declare class UncertainOutcome extends Error {
|
|
50
|
+
readonly commandId: string | null;
|
|
51
|
+
readonly reason: "transport" | "receipt" | "server";
|
|
52
|
+
readonly status?: number;
|
|
53
|
+
constructor(commandId: string | null, reason: "transport" | "receipt" | "server", options?: {
|
|
54
|
+
cause?: unknown;
|
|
55
|
+
status?: number;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/** The server proved the edit never started (503 `rtc_unavailable` with the typed baseline marker): nothing to reconcile. */
|
|
59
|
+
export declare class NoteWriteNotSubmitted extends Error {
|
|
60
|
+
constructor(options?: {
|
|
61
|
+
cause?: unknown;
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/** 409 `command_in_progress`: an earlier request with this id is still running. */
|
|
65
|
+
export declare class CommandInProgress extends Error {
|
|
66
|
+
readonly commandId: string | null;
|
|
67
|
+
constructor(commandId: string | null, options?: {
|
|
68
|
+
cause?: unknown;
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/** 409 `command_intent_mismatch`: the id was already bound to a different note, baseline, mode, format or patch. */
|
|
72
|
+
export declare class CommandIntentMismatch extends Error {
|
|
73
|
+
readonly commandId: string | null;
|
|
74
|
+
constructor(commandId: string | null, options?: {
|
|
75
|
+
cause?: unknown;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/** Status, stable code and parsed body of a transport failure, for either error class. */
|
|
79
|
+
export declare function failureInfo(error: unknown): {
|
|
80
|
+
status?: number;
|
|
81
|
+
code?: string;
|
|
82
|
+
body?: unknown;
|
|
83
|
+
};
|
|
84
|
+
/** Current API proof only: exactly `{apiVersion: 1, started: false, phase: "baseline_read"}`. Human text proves nothing. */
|
|
85
|
+
export declare function provenUnsubmitted(body: unknown): boolean;
|
|
86
|
+
export declare function validateCommandId(commandId: string): string;
|
|
87
|
+
/** The exact request body: `commandId` is present only when the caller supplied one. */
|
|
88
|
+
export declare function patchRequestBody(input: NotePatchRequest): NotePatchRequest;
|
|
89
|
+
/** Validate a receipt against the request it answers; older servers' receipts are normalized, never guessed beyond the empty-patch case. */
|
|
90
|
+
export declare function verifyNoteReceipt(raw: unknown, noteId: string, input: NotePatchRequest): NoteWriteReceipt;
|
|
91
|
+
/** PATCH one compiled edit set. Deterministic refusals pass through; a lost
|
|
92
|
+
* acknowledgment or an unverifiable receipt is an UncertainOutcome and is
|
|
93
|
+
* never retried here. The reading-view header check is exact when
|
|
94
|
+
* `options.baseline` is given and best-effort (payload inspection) for a
|
|
95
|
+
* read-free patch; the server is the authoritative enforcement point. */
|
|
96
|
+
export declare function submitNotePatch(t: Transport, bodyPath: string, noteId: string, input: NotePatchRequest, options?: {
|
|
97
|
+
ifMatch?: string;
|
|
98
|
+
baseline?: NoteSource;
|
|
99
|
+
}): Promise<NoteWriteReceipt>;
|
|
100
|
+
/** GET the durable record of one command; 404 `command_not_found` passes through as the transport's error. */
|
|
101
|
+
export declare function readNoteCommand(t: Transport, commandPath: string, commandId: string): Promise<NoteCommandStatus>;
|
|
102
|
+
/** Append is verbatim (Notes API contract): the given text, every intended
|
|
103
|
+
* newline included and nothing added, at the end of the retained source. An
|
|
104
|
+
* empty addition compiles to an empty patch — nothing to send. */
|
|
105
|
+
export declare function appendPlan(source: NoteSource, text: string, mode: NoteWriteMode): {
|
|
106
|
+
suffix: string;
|
|
107
|
+
request: NotePatch;
|
|
108
|
+
};
|
|
109
|
+
/** Replace the whole source: a code-point character diff against the retained snapshot, within the alignment limits. */
|
|
110
|
+
export declare function writePlan(source: NoteSource, content: string, mode: NoteWriteMode): NotePatch;
|