@dreamlake/dreamlake-cli 0.89.0 → 0.90.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/notes.js CHANGED
@@ -2,8 +2,11 @@ import { validateHtmlSnapshot } from "./note-html-read.js";
2
2
  import { characterDiff } from "./note-character-plan.js";
3
3
  import * as editing from "./note-editing.js";
4
4
  import { markdownToc as outline } from "./note-toc.js";
5
+ import { parse as parseHtml, select as selectHtml, textPieces } from './note-html.js';
5
6
  /** Notes: search, read, sections, conditional writes. Mirrors the CLI `notes` group. */
6
7
  import { noteFilesApi } from "./note-files.js";
8
+ import { notePresenceApi } from "./note-presence.js";
9
+ import { watchNote } from "./note-linger.js";
7
10
  import { sharingApi } from "./workspace.js";
8
11
  import { createHash } from "node:crypto";
9
12
  import { noteEdits, } from "./note-edits.js";
@@ -49,7 +52,26 @@ export function notesApi(t, namespace) {
49
52
  return receipt;
50
53
  };
51
54
  return {
55
+ ...notePresenceApi(t, base),
56
+ linger: (noteId, options, receive) => watchNote(t, `${base}/${id(noteId)}`, noteId, options, receive),
52
57
  namespace,
58
+ /** Resolve the same ID, exact slug or exact title accepted by the CLI in this namespace. */
59
+ resolve: async (ref) => {
60
+ if (/^[a-f0-9]{24}$/i.test(ref))
61
+ return ref;
62
+ const result = await t.request('GET', base, { query: { limit: 200 } });
63
+ const hit = result.notes.find(row => row.slug === ref || row.id === ref || row.name === ref);
64
+ if (!hit)
65
+ throw new ApiError(404, 'note_not_found', { namespace, ref });
66
+ return hit.id;
67
+ },
68
+ /** CSS inspection is read-only; selectText publishes a separate agent selection. */
69
+ selectElement: async (noteId, css) => {
70
+ const body = await t.request('GET', `${base}/${id(noteId)}/body`);
71
+ const document = parseHtml(body.text), element = selectHtml(document, css);
72
+ return { etag: body.etag, tag: element.tag, attrs: element.attrs, outer: element.outer, inner: element.inner,
73
+ text: textPieces(document, element).map(piece => piece.decoded).join('') };
74
+ },
53
75
  source,
54
76
  patch,
55
77
  replaceContent: async (noteId, baseRevision, content, mode = "exact") => {
@@ -96,7 +118,14 @@ export function notesApi(t, namespace) {
96
118
  move: (noteId, input) => t.request("POST", `${base}/${id(noteId)}/move`, { json: input }),
97
119
  share: (noteId) => sharingApi(t, namespace, "notes", id(noteId)),
98
120
  files: (noteId) => noteFilesApi(t, `${base}/${id(noteId)}`),
99
- media: (form) => t.request("POST", "/notes/media", { body: form }),
121
+ media: async (form) => {
122
+ const receipt = await t.request('POST', '/notes/media', { body: form, redirect: 'error' });
123
+ if (!receipt || typeof receipt.url !== 'string' || !/^https?:\/\/[^\s]+$/.test(receipt.url) ||
124
+ !['http:', 'https:'].includes(new URL(receipt.url).protocol) || typeof receipt.contentType !== 'string' ||
125
+ !Number.isSafeInteger(receipt.sizeBytes) || receipt.sizeBytes < 0)
126
+ throw new Error('invalid media upload response: expected url, contentType and sizeBytes');
127
+ return receipt;
128
+ },
100
129
  read: (noteId, query = {}) => t.request("GET", `${base}/${id(noteId)}/body`, {
101
130
  query: { contract: "v2", ...query },
102
131
  }),
@@ -132,7 +161,6 @@ export function notesApi(t, namespace) {
132
161
  return { note: noteId, revision: snapshot.revision, html, bytes };
133
162
  },
134
163
  diff: (noteId, query) => t.request("GET", `${base}/${id(noteId)}/diff`, { query }),
135
- presence: (noteId, input) => t.request("POST", `${base}/${id(noteId)}/presence`, { json: input }),
136
164
  saveVersion: (noteId, input) => t.request("POST", `${base}/${id(noteId)}/versions`, { json: input }),
137
165
  find: (query) => t.request("GET", `${base}/search`, { query }),
138
166
  create: (input) => t.request("POST", base, {
@@ -0,0 +1,5 @@
1
+ import type { Transport } from '../../api/client.js';
2
+ export declare function noteTransport(c: {
3
+ remote: string;
4
+ token: string;
5
+ }): Transport;
@@ -0,0 +1,20 @@
1
+ /** Adapt explicit resolved CLI credentials; attribution remains owned by the CLI transport. */
2
+ import { requestJson, requestRaw } from '../client.js';
3
+ import { requestUrl } from '../../api/http.js';
4
+ export function noteTransport(c) {
5
+ return {
6
+ request: (method, path, options) => {
7
+ if (method === 'HEAD')
8
+ throw new Error('Notes JSON transport does not support HEAD');
9
+ const { body, timeoutMs, ...request } = options ?? {};
10
+ if (body !== undefined)
11
+ throw new Error('Notes collaboration transport requires JSON');
12
+ return requestJson(c.remote, path, { token: c.token, method, ...request, timeoutMs: timeoutMs ?? undefined });
13
+ },
14
+ raw: (method, path, options) => {
15
+ if (method !== 'GET' && method !== 'HEAD')
16
+ throw new Error('Notes streaming transport requires GET or HEAD');
17
+ return requestRaw(requestUrl(c.remote, path, options?.query), { token: c.token, method, headers: options?.headers, signal: options?.signal, timeoutMs: options?.timeoutMs ?? undefined, followRedirects: false });
18
+ },
19
+ };
20
+ }
@@ -1,29 +1,6 @@
1
- /**
2
- * `dreamlake notes files …` — list, upload, download, move, copy, trash.
3
- *
4
- * Bytes are never decoded on this path. Upload reads the local file as a
5
- * Buffer and sends it raw; download writes the response body straight out.
6
- * Only `--text` touches a string, and the server refuses that for anything not
7
- * text-typed rather than round-tripping it through UTF-8.
8
- *
9
- * Downloads refuse to replace a local file unless asked. Everything else here
10
- * goes to a recoverable trash; something overwritten on the caller's disk does
11
- * not come back.
12
- */
1
+ import { type NoteFile } from '../../api/note-files.js';
13
2
  import { type ConnOpts, ctx } from "./index.js";
14
- export interface FileRow {
15
- id: string;
16
- path: string;
17
- contentType: string;
18
- sizeBytes: number;
19
- etag: string;
20
- createdBy: string;
21
- createdAt: string;
22
- updatedAt: string;
23
- trashed: boolean;
24
- previewKind: string | null;
25
- text: boolean;
26
- }
3
+ export type FileRow = NoteFile;
27
4
  /** Exit code for "the file or path was wrong", distinct from a transport failure. */
28
5
  export declare const EXIT_NO_FILE = 6;
29
6
  /** Exit code for a refused overwrite — a script can branch on it and retry. */
@@ -1,3 +1,5 @@
1
+ import { noteFilesApi, noteFileOperationId, validateNoteFileKey } from '../../api/note-files.js';
2
+ import { noteTransport } from './api-transport.js';
1
3
  /**
2
4
  * `dreamlake notes files …` — list, upload, download, move, copy, trash.
3
5
  *
@@ -87,16 +89,17 @@ function reportFile(err, recovery) {
87
89
  return report(err);
88
90
  }
89
91
  function operationIdOf(value) {
90
- return typeof value === "string" && /^[a-f0-9]{24}$/i.test(value) ? value : undefined;
92
+ return noteFileOperationId(value);
91
93
  }
92
94
  function keyValid(key) {
93
- // HTTP field values cannot represent arbitrary Unicode with fetch. Never
94
- // trim, normalize or silently replace the user's operation identity.
95
- if (key !== undefined && (!/^[\x20-\x7e]{1,256}$/.test(key) || key.trim() !== key)) {
96
- fail("--idempotency-key must be 1–256 printable ASCII bytes without surrounding spaces");
95
+ try {
96
+ validateNoteFileKey(key);
97
+ return true;
98
+ }
99
+ catch (error) {
100
+ fail(error.message);
97
101
  return false;
98
102
  }
99
- return true;
100
103
  }
101
104
  function requireFileResult(row) {
102
105
  if (!row || typeof row !== "object" || typeof row.id !== "string" || typeof row.path !== "string") {
@@ -486,24 +489,15 @@ export async function runFilesRestore(ref, opts) {
486
489
  * has to guess.
487
490
  */
488
491
  export async function resolveFile(c, noteId, ref, opts = {}) {
489
- if (/^[0-9a-f]{24}$/i.test(ref)) {
490
- try {
491
- return await requestJson(c.remote, `${filesBase(c, noteId)}/${seg(ref)}`, { token: c.token });
492
- }
493
- catch {
494
- fail(`no file with id ${ref}`);
495
- return null;
496
- }
492
+ try {
493
+ return await noteFilesApi(noteTransport(c), `/namespaces/${seg(c.ns)}/notes/${seg(noteId)}`).resolve(ref, opts.includeTrashed);
497
494
  }
498
- const lists = opts.includeTrashed ? ["", "?trashed=true"] : [""];
499
- for (const qs of lists) {
500
- const res = await requestJson(c.remote, `${filesBase(c, noteId)}${qs}`, { token: c.token });
501
- const hit = res.files.find((f) => f.path === ref);
502
- if (hit)
503
- return hit;
495
+ catch (error) {
496
+ if (error.status !== 404)
497
+ throw error;
498
+ fail(/^[a-f0-9]{24}$/i.test(ref) ? `no file with id ${ref}` : `no file at '${ref}' — 'notes files list --note …' shows what is there`);
499
+ return null;
504
500
  }
505
- fail(`no file at '${ref}' — 'notes files list --note …' shows what is there`);
506
- return null;
507
501
  }
508
502
  /**
509
503
  * `dreamlake notes files preview <file> --note N [--share] [--open]`
@@ -1,3 +1,5 @@
1
+ import { notePresenceApi, notePresenceIntent } from '../../api/note-presence.js';
2
+ import { noteTransport } from './api-transport.js';
1
3
  import { collectionList } from "../collection-list.js";
2
4
  import { registerVersionCommands, runSavedVersionRead } from "./version-commands.js";
3
5
  import { registerMoveCommand } from "./move-command.js";
@@ -1250,12 +1252,7 @@ export async function runNotesPresence(ref, opts) {
1250
1252
  /** The agent's self-reported purpose, validated before any presence request.
1251
1253
  * undefined means the flag was not given — the server then preserves intent. */
1252
1254
  export function presenceIntent(value) {
1253
- if (value === undefined)
1254
- return undefined;
1255
- const summary = value.trim();
1256
- if (!summary || Array.from(summary).length > 280)
1257
- throw new Error('--intent requires 1–280 characters of plain text (one short sentence of purpose)');
1258
- return { summary };
1255
+ return notePresenceIntent(value);
1259
1256
  }
1260
1257
  /** One-shot participation; linger owns its own maintained lease. */
1261
1258
  export async function runNotesVisit(ref, opts) {
@@ -1267,11 +1264,11 @@ export async function runNotesVisit(ref, opts) {
1267
1264
  if (!c)
1268
1265
  return 1;
1269
1266
  try {
1270
- const intent = presenceIntent(opts.intent);
1267
+ presenceIntent(opts.intent);
1271
1268
  const id = await resolveNote(c, ref);
1272
1269
  if (!id)
1273
1270
  return 1;
1274
- const result = await requestJson(c.remote, `/namespaces/${seg(c.ns)}/notes/${seg(id)}/presence`, { method: 'POST', token: c.token, json: { action: 'join', ...(intent ? { intent } : {}) } });
1271
+ const result = await notePresenceApi(noteTransport(c), `/namespaces/${seg(c.ns)}/notes`).visit(id, { intent: opts.intent });
1275
1272
  if (opts.json)
1276
1273
  emitJson(result);
1277
1274
  else
@@ -1,59 +1,4 @@
1
- import { type DocumentReadOptions } from "./document.js";
2
- import { readNoteEvents, type Participant } from "./events.js";
3
- export declare const LINGER_BATCH_MS = 2000;
4
- /** Durations are bounded to avoid accidental busy loops or effectively silent sessions. */
5
- export declare function lingerDuration(value: string | undefined, option: string): number;
6
- interface Activity {
7
- id: string;
8
- agent: {
9
- id: string;
10
- name: string;
11
- owner: string;
12
- };
13
- kind: "read" | "insert";
14
- scope: string;
15
- hash: string;
16
- ranges: {
17
- start: number;
18
- end: number;
19
- }[];
20
- at: number;
21
- expiresAt: number;
22
- }
23
- interface Read {
24
- note: string;
25
- hash: string;
26
- revision: string;
27
- content?: string;
28
- base?: string;
29
- patch?: string;
30
- format?: string;
31
- }
32
- interface Observation {
33
- body: Read;
34
- participants: Participant[];
35
- activities: Activity[];
36
- }
37
- export interface LingerRuntime {
38
- signal?: AbortSignal;
39
- events?: typeof readNoteEvents;
40
- now(): number;
41
- wait(ms: number, signal: AbortSignal): Promise<void>;
42
- }
43
- /** Stable activity fingerprints suppress renewed read/typing observations each poll. */
44
- export declare class LingerBatch {
45
- private readonly self;
46
- private participants;
47
- private activity;
48
- private selections;
49
- constructor(initial: Observation, self: string);
50
- others(rows: Participant[]): Participant[];
51
- diff(next: Observation): {
52
- joined: Participant[];
53
- left: Participant[];
54
- activities: Activity[];
55
- selections: Participant[];
56
- };
57
- }
1
+ import type { DocumentReadOptions } from './document.js';
2
+ import { type LingerRuntime } from '../../api/note-linger.js';
3
+ export { LINGER_BATCH_MS, lingerDuration, LingerBatch, type LingerRuntime } from '../../api/note-linger.js';
58
4
  export declare function runNotesLinger(ref: string | undefined, opts: DocumentReadOptions, clock?: LingerRuntime): Promise<number>;
59
- export {};