@deveye/types 0.19.0 → 0.19.2

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,435 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ import { FeatureError, type MovableCell, type SdkCipher, type SdkQueryable } from './server';
4
+
5
+ /**
6
+ * Copying an item to another workspace, of this DevEye or of another one.
7
+ *
8
+ * You DESCRIBE your item as a tree of tables; the engine below does the rest,
9
+ * once, for every feature: reading the rows, opening the encrypted cells,
10
+ * writing them elsewhere under new ids and another key. A copy between two
11
+ * DevEye instances is the same two halves with the user's browser in between:
12
+ * `exportItemTree` runs on the source server, `importItemTree` on the
13
+ * destination, and the two servers never talk to each other.
14
+ *
15
+ * What travels is PLAINTEXT, by design: the destination seals it under its own
16
+ * key, which the source does not know. It only ever exists in the memory of the
17
+ * two servers and of the browser that carries it.
18
+ */
19
+
20
+ /** One table of an item's tree, see {@link ItemTree}. */
21
+ export interface ItemTreeTable {
22
+ table: string;
23
+ /**
24
+ * Primary key. Never copied: the destination gives the row a new one.
25
+ * Absent on a pure link table (two references and nothing else), which
26
+ * nothing points at and which holds no sealed column.
27
+ */
28
+ idColumn?: string;
29
+ /** `'auto'` (default): AUTO_INCREMENT. `'uuid'`: the engine draws a fresh UUID. */
30
+ idKind?: 'auto' | 'uuid';
31
+ /** Column tying the row to the item. On the root table, the same as `idColumn`. */
32
+ ownerColumn: string;
33
+ /**
34
+ * For a row hanging off the item INDIRECTLY: a SQL subquery selecting the
35
+ * `ownerColumn` values that belong to it, taking the item's id as its only
36
+ * `?`. Interpolated into the query, so a literal written in your module,
37
+ * exactly like `table`. Never build it from input.
38
+ */
39
+ ownerScope?: string;
40
+ /**
41
+ * Columns of encrypted text: opened with the source key, sealed again with
42
+ * the destination's.
43
+ *
44
+ * ⚠️ Held BY HAND: an encrypted column left out is copied as a blob no key
45
+ * of the destination can open, and moved under the old key, where it becomes
46
+ * unreadable. Nothing can detect it, one encrypted blob being
47
+ * indistinguishable from another. Revisit it whenever you add one.
48
+ */
49
+ sealed?: readonly string[];
50
+ /**
51
+ * Columns pointing at a row of a table of this tree (this one included),
52
+ * by that table's name: rewritten to the ids the destination handed out. A
53
+ * reference to anything OUTSIDE the tree belongs in `omit`.
54
+ */
55
+ refs?: Readonly<Record<string, string>>;
56
+ /** Column holding the workspace id, rewritten to the destination's. */
57
+ workspaceColumn?: string;
58
+ /**
59
+ * Column holding the account the row belongs to, rewritten to whoever makes
60
+ * the copy: the original account may not exist where the copy lands. A user
61
+ * reference that is only informative (an assignee) belongs in `omit`.
62
+ */
63
+ userColumn?: string;
64
+ /**
65
+ * Columns the copy leaves to their default: what means nothing elsewhere (a
66
+ * source of the origin workspace, a folder, a sort order) and what the
67
+ * destination must rebuild by itself (a sync state, a last error).
68
+ */
69
+ omit?: readonly string[];
70
+ /**
71
+ * Rows the destination rebuilds by itself (a cache of commits, a history of
72
+ * checks): moved with the item, never copied.
73
+ */
74
+ cache?: boolean;
75
+ /**
76
+ * ROOT only: the column that orders your items within a workspace. The copy
77
+ * lands at the end of the destination's list, whatever rank it had at home.
78
+ * Needs `workspaceColumn`.
79
+ */
80
+ orderColumn?: string;
81
+ /**
82
+ * ROOT only: the column that makes an item unique within a workspace (the
83
+ * digest of its name, encryption being non-deterministic), and the sentence
84
+ * shown when the destination already holds one. Needs `workspaceColumn`.
85
+ */
86
+ unique?: { column: string; message: string };
87
+ /**
88
+ * ROOT only, for a feature whose items choose their tier: the column that
89
+ * says which key seals the whole tree, and its two values. Without it every
90
+ * item is open.
91
+ */
92
+ tier?: { column: string; open: string | number; private: string | number };
93
+ }
94
+
95
+ /**
96
+ * Which key seals an item: `'open'`, the workspace's, that the server can
97
+ * always use, or `'private'`, the caller's password-derived one (see
98
+ * `StorageEncryption`).
99
+ */
100
+ export type ItemTier = 'open' | 'private';
101
+
102
+ /**
103
+ * An item as a tree of tables: the root first, then every table BEFORE the ones
104
+ * that reference it. The single hand-held description of what an item is made
105
+ * of, for the two gestures that need it: `copy` reads it whole, and `move`
106
+ * derives its cells from it ({@link movableCellsOf}).
107
+ */
108
+ export type ItemTree = readonly ItemTreeTable[];
109
+
110
+ /** The cells a `move` re-seals: every sealed column of the tree, caches included. */
111
+ export function movableCellsOf(tree: ItemTree): MovableCell[] {
112
+ return tree.flatMap((t) =>
113
+ (t.sealed ?? []).map((column) => ({
114
+ table: t.table,
115
+ // `itemTreeProblem` refuse une table scellée sans identifiant.
116
+ idColumn: t.idColumn ?? '',
117
+ ownerColumn: t.ownerColumn,
118
+ column,
119
+ ...(t.ownerScope ? { ownerScope: t.ownerScope } : {})
120
+ }))
121
+ );
122
+ }
123
+
124
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
125
+
126
+ /**
127
+ * Why a tree cannot be used, or `null`. The host checks it at boot: every name
128
+ * in it ends up interpolated into SQL, and a table listed before the one it
129
+ * references would be written before the id it needs exists.
130
+ */
131
+ export function itemTreeProblem(tree: ItemTree): string | null {
132
+ const [root] = tree;
133
+ if (!root) return 'the tree is empty';
134
+ if (root.ownerColumn !== root.idColumn) {
135
+ return `${root.table}: the root owns itself, ownerColumn must be idColumn`;
136
+ }
137
+ if (root.cache || root.ownerScope) {
138
+ return `${root.table}: the root is neither a cache nor scoped`;
139
+ }
140
+ const seen = new Set<string>();
141
+ for (const t of tree) {
142
+ const names = [
143
+ t.table,
144
+ ...(t.idColumn ? [t.idColumn] : []),
145
+ t.ownerColumn,
146
+ ...(t.workspaceColumn ? [t.workspaceColumn] : []),
147
+ ...(t.userColumn ? [t.userColumn] : []),
148
+ ...(t.orderColumn ? [t.orderColumn] : []),
149
+ ...(t.unique ? [t.unique.column] : []),
150
+ ...(t.tier ? [t.tier.column] : []),
151
+ ...(t.sealed ?? []),
152
+ ...(t.omit ?? []),
153
+ ...Object.keys(t.refs ?? {})
154
+ ];
155
+ const bad = names.find((n) => !IDENTIFIER.test(n));
156
+ if (bad !== undefined) return `${t.table}: "${bad}" is not a plain SQL identifier`;
157
+ if (seen.has(t.table)) return `${t.table}: listed twice`;
158
+ if (t.tier && t !== root) return `${t.table}: only the root chooses the tier`;
159
+ if ((t.orderColumn || t.unique) && (t !== root || !t.workspaceColumn)) {
160
+ return `${t.table}: orderColumn and unique are for a root that names its workspaceColumn`;
161
+ }
162
+ if (
163
+ !t.idColumn &&
164
+ (t === root ||
165
+ (t.sealed ?? []).length > 0 ||
166
+ Object.values(t.refs ?? {}).includes(t.table))
167
+ ) {
168
+ return `${t.table}: only a pure link table goes without idColumn`;
169
+ }
170
+ for (const [column, target] of Object.entries(t.refs ?? {})) {
171
+ if (target !== t.table && !seen.has(target)) {
172
+ return `${t.table}.${column}: references ${target}, which must be listed before it`;
173
+ }
174
+ }
175
+ if (t.ownerScope && t.refs?.[t.ownerColumn] === undefined && !t.cache) {
176
+ return `${t.table}: a scoped table must declare what ${t.ownerColumn} references`;
177
+ }
178
+ seen.add(t.table);
179
+ }
180
+ return null;
181
+ }
182
+
183
+ /** A row as it travels: column name to a JSON-safe value. */
184
+ export type ItemTreeRow = Record<string, unknown>;
185
+
186
+ /** The rows of an item, per table name. Sealed cells are in the clear. */
187
+ export type ItemTreeRows = Record<string, ItemTreeRow[]>;
188
+
189
+ /** How a value that JSON cannot carry travels. */
190
+ const BINARY_TAG = '$deveye:base64';
191
+
192
+ function ownerFilter(t: ItemTreeTable): string {
193
+ return t.ownerScope ? `${t.ownerColumn} IN (${t.ownerScope})` : `${t.ownerColumn} = ?`;
194
+ }
195
+
196
+ /** The writable columns of a table, as the database knows them: generated ones are not. */
197
+ async function writableColumns(q: SdkQueryable, table: string): Promise<Set<string>> {
198
+ const rows = await q.query<{ Field: string; Extra: string }>(`SHOW COLUMNS FROM ${table}`);
199
+ // `DEFAULT_GENERATED` n'est qu'une valeur par défaut calculée : la colonne s'écrit.
200
+ return new Set(
201
+ rows.filter((r) => !/(VIRTUAL|STORED) GENERATED/i.test(r.Extra ?? '')).map((r) => r.Field)
202
+ );
203
+ }
204
+
205
+ /** MySQL wants `YYYY-MM-DD HH:MM:SS`, not the ISO form JSON would give a `Date`. */
206
+ function toWire(value: unknown): unknown {
207
+ if (value instanceof Date) return value.toISOString().slice(0, 19).replace('T', ' ');
208
+ if (typeof value === 'bigint') return value.toString();
209
+ if (value instanceof Uint8Array) return { [BINARY_TAG]: Buffer.from(value).toString('base64') };
210
+ return value;
211
+ }
212
+
213
+ function fromWire(value: unknown): unknown {
214
+ if (value === null || typeof value !== 'object') return value;
215
+ const binary = (value as Record<string, unknown>)[BINARY_TAG];
216
+ if (typeof binary === 'string') return Buffer.from(binary, 'base64');
217
+ // A JSON column, parsed by the driver on the way out.
218
+ return JSON.stringify(value);
219
+ }
220
+
221
+ /** The tier of an item still in the database; `null` when it is gone. */
222
+ export async function itemTierOf(
223
+ q: SdkQueryable,
224
+ tree: ItemTree,
225
+ itemId: string | number
226
+ ): Promise<ItemTier | null> {
227
+ const root = tree[0];
228
+ const rows = await q.query<Record<string, unknown>>(
229
+ `SELECT ${root.tier ? root.tier.column : root.idColumn} AS tier FROM ${root.table} WHERE ${root.idColumn} = ?`,
230
+ [itemId]
231
+ );
232
+ if (rows.length === 0) return null;
233
+ return root.tier && String(rows[0].tier) === String(root.tier.private) ? 'private' : 'open';
234
+ }
235
+
236
+ /**
237
+ * Reads an item out of the database, sealed cells opened with `cipher`: the
238
+ * one of the item's tier ({@link itemTierOf}).
239
+ *
240
+ * Throws before returning anything if one cell resists: a copy missing a cell
241
+ * would look whole, and nobody would know what it lost.
242
+ */
243
+ export async function exportItemTree(
244
+ q: SdkQueryable,
245
+ tree: ItemTree,
246
+ itemId: string | number,
247
+ cipher: SdkCipher
248
+ ): Promise<ItemTreeRows> {
249
+ const out: ItemTreeRows = {};
250
+ for (const t of tree) {
251
+ if (t.cache) continue;
252
+ const columns = await writableColumns(q, t.table);
253
+ const skipped = new Set(t.omit ?? []);
254
+ if (t.workspaceColumn) skipped.add(t.workspaceColumn);
255
+ if (t.userColumn) skipped.add(t.userColumn);
256
+ if (t.orderColumn) skipped.add(t.orderColumn);
257
+ // The destination decides the tier: it may not have the private one.
258
+ if (t.tier) skipped.add(t.tier.column);
259
+ const sealed = new Set(t.sealed ?? []);
260
+ const rows = await q.query<ItemTreeRow>(
261
+ `SELECT * FROM ${t.table} WHERE ${ownerFilter(t)}${t.idColumn ? ` ORDER BY ${t.idColumn} ASC` : ''}`,
262
+ [itemId]
263
+ );
264
+ out[t.table] = [];
265
+ for (const row of rows) {
266
+ const copy: ItemTreeRow = {};
267
+ for (const [column, value] of Object.entries(row)) {
268
+ if (!columns.has(column) || skipped.has(column)) continue;
269
+ if (sealed.has(column) && typeof value === 'string' && value !== '') {
270
+ const plain = await cipher.tryDecrypt(value);
271
+ if (plain === null) {
272
+ throw new FeatureError(
273
+ 'internal',
274
+ `Une ligne de ${t.table} est illisible : copie annulée, rien n’a été écrit.`
275
+ );
276
+ }
277
+ copy[column] = plain;
278
+ } else copy[column] = toWire(value);
279
+ }
280
+ out[t.table].push(copy);
281
+ }
282
+ }
283
+ return out;
284
+ }
285
+
286
+ /** How many rows a bundle holds, for a progress bar or a refusal. */
287
+ export function countItemTreeRows(rows: ItemTreeRows): number {
288
+ return Object.values(rows).reduce((n, list) => n + list.length, 0);
289
+ }
290
+
291
+ /** Where a copy lands, and as whom. */
292
+ export interface ItemTreeDestination {
293
+ workspaceId: number;
294
+ /** Whoever makes the copy: the account every `userColumn` is rewritten to. */
295
+ userId: number;
296
+ /** The cipher of `tier` in that workspace. */
297
+ cipher: SdkCipher;
298
+ /** Defaults to `'open'`. The root's tier column says so. */
299
+ tier?: ItemTier;
300
+ }
301
+
302
+ /**
303
+ * Writes an item into `into.workspaceId`, sealed cells under `into.cipher`, and
304
+ * returns the id of its new root row. `q` MUST be transactional: a tree written
305
+ * halfway is an item that opens on missing pieces.
306
+ *
307
+ * `rows` comes from a browser, possibly from another DevEye: it is validated
308
+ * against the tree and against the database, never trusted. Table names are
309
+ * taken from the tree alone, column names must exist in the table, and every
310
+ * value is bound.
311
+ */
312
+ export async function importItemTree(
313
+ q: SdkQueryable,
314
+ tree: ItemTree,
315
+ rows: ItemTreeRows,
316
+ into: ItemTreeDestination
317
+ ): Promise<string> {
318
+ const { workspaceId: toWorkspaceId, cipher, tier = 'open' } = into;
319
+ const copied = tree.filter((t) => !t.cache);
320
+ const known = new Set(copied.map((t) => t.table));
321
+ for (const table of Object.keys(rows)) {
322
+ if (!known.has(table)) {
323
+ throw new FeatureError('validation', `Table inattendue dans la copie : ${table}.`);
324
+ }
325
+ }
326
+ const root = copied[0];
327
+ if (!root || (rows[root.table] ?? []).length !== 1) {
328
+ throw new FeatureError('validation', 'La copie doit porter exactement un élément.');
329
+ }
330
+
331
+ /** Old id to new id, per table. */
332
+ const ids = new Map<string, Map<string, string | number>>();
333
+ /** A row pointing at its own table: set once every row of that table has its new id. */
334
+ const selfRefs: { t: ItemTreeTable; newId: string | number; column: string; oldRef: string }[] =
335
+ [];
336
+ const rootOldId = String(rows[root.table][0][root.idColumn!]);
337
+
338
+ for (const t of copied) {
339
+ const columns = await writableColumns(q, t.table);
340
+ const sealed = new Set(t.sealed ?? []);
341
+ const refs = t.refs ?? {};
342
+ const mine = new Map<string, string | number>();
343
+ ids.set(t.table, mine);
344
+
345
+ for (const row of rows[t.table] ?? []) {
346
+ const values: ItemTreeRow = {};
347
+ const pending: { column: string; oldRef: string }[] = [];
348
+ for (const [column, raw] of Object.entries(row)) {
349
+ if (column === t.idColumn) continue;
350
+ if (
351
+ !columns.has(column) ||
352
+ column === t.workspaceColumn ||
353
+ column === t.userColumn ||
354
+ column === t.orderColumn ||
355
+ column === t.tier?.column ||
356
+ (t.omit ?? []).includes(column)
357
+ ) {
358
+ throw new FeatureError(
359
+ 'validation',
360
+ `Colonne inattendue dans la copie : ${t.table}.${column}.`
361
+ );
362
+ }
363
+ const target = refs[column];
364
+ if (target !== undefined && raw !== null) {
365
+ if (target === t.table) {
366
+ pending.push({ column, oldRef: String(raw) });
367
+ values[column] = null;
368
+ continue;
369
+ }
370
+ const mapped = ids.get(target)?.get(String(raw));
371
+ if (mapped === undefined) {
372
+ throw new FeatureError(
373
+ 'validation',
374
+ `Référence orpheline dans la copie : ${t.table}.${column}.`
375
+ );
376
+ }
377
+ values[column] = mapped;
378
+ } else if (sealed.has(column) && typeof raw === 'string' && raw !== '') {
379
+ values[column] = await cipher.encrypt(raw);
380
+ } else values[column] = fromWire(raw);
381
+ }
382
+ if (t.workspaceColumn) values[t.workspaceColumn] = toWorkspaceId;
383
+ if (t.userColumn) values[t.userColumn] = into.userId;
384
+ if (t.unique && t.workspaceColumn) {
385
+ const taken = await q.query<{ n: number }>(
386
+ `SELECT COUNT(*) AS n FROM ${t.table} WHERE ${t.workspaceColumn} = ? AND ${t.unique.column} = ?`,
387
+ [toWorkspaceId, values[t.unique.column] ?? null]
388
+ );
389
+ if (Number(taken[0]?.n ?? 0) > 0) {
390
+ throw new FeatureError('conflict', t.unique.message);
391
+ }
392
+ }
393
+ if (t.orderColumn && t.workspaceColumn) {
394
+ const last = await q.query<{ next: number }>(
395
+ `SELECT COALESCE(MAX(${t.orderColumn}) + 1, 0) AS next FROM ${t.table} WHERE ${t.workspaceColumn} = ?`,
396
+ [toWorkspaceId]
397
+ );
398
+ values[t.orderColumn] = Number(last[0]?.next ?? 0);
399
+ }
400
+ if (t.tier) values[t.tier.column] = t.tier[tier];
401
+ // Whatever the row said, it hangs off the COPY: left as it came, it
402
+ // would attach itself to the original, or to a stranger's item.
403
+ if (t !== root && refs[t.ownerColumn] === undefined) {
404
+ values[t.ownerColumn] = ids.get(root.table)!.get(rootOldId);
405
+ }
406
+ if (t.idColumn && t.idKind === 'uuid') values[t.idColumn] = randomUUID();
407
+
408
+ const names = Object.keys(values);
409
+ const res = await q.execute(
410
+ `INSERT INTO ${t.table} (${names.join(', ')}) VALUES (${names.map(() => '?').join(', ')})`,
411
+ names.map((n) => values[n])
412
+ );
413
+ if (!t.idColumn) continue;
414
+ const newId = t.idKind === 'uuid' ? (values[t.idColumn] as string) : res.insertId;
415
+ mine.set(String(row[t.idColumn]), newId);
416
+ for (const { column, oldRef } of pending) selfRefs.push({ t, newId, column, oldRef });
417
+ }
418
+ }
419
+
420
+ for (const ref of selfRefs) {
421
+ const mapped = ids.get(ref.t.table)?.get(ref.oldRef);
422
+ if (mapped === undefined) {
423
+ throw new FeatureError(
424
+ 'validation',
425
+ `Référence orpheline dans la copie : ${ref.t.table}.${ref.column}.`
426
+ );
427
+ }
428
+ await q.execute(
429
+ `UPDATE ${ref.t.table} SET ${ref.column} = ? WHERE ${ref.t.idColumn!} = ?`,
430
+ [mapped, ref.newId]
431
+ );
432
+ }
433
+
434
+ return String(ids.get(root.table)!.get(rootOldId));
435
+ }
@@ -127,8 +127,9 @@ export type NativeCapability =
127
127
  | 'live.publish'
128
128
  /**
129
129
  * Read accounts (id, email, username, creation date): the caller's own in a
130
- * handler, any account from a service. For what belongs to an account and
131
- * not to a workspace (a subscription, a receipt to address).
130
+ * handler, any account from a service, by id, by email or by search. For
131
+ * what belongs to an account and not to a workspace (a subscription, a
132
+ * receipt to address).
132
133
  */
133
134
  | 'accounts.read';
134
135
 
package/src/sdk/server.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ItemTree, ItemTreeRows } from './copy';
1
2
  import type { z, ZodType } from 'zod';
2
3
  import type { ErrorCode } from '../protocol/error';
3
4
  import type { FeatureAccess } from '../domain/workspaceRole';
@@ -306,6 +307,13 @@ export interface SdkAccounts {
306
307
  find(userId: number): Promise<SdkAccount | null>;
307
308
  findByEmail(email: string): Promise<SdkAccount | null>;
308
309
  list(userIds: readonly number[]): Promise<readonly SdkAccount[]>;
310
+ /**
311
+ * Accounts whose username or email contains `query`, case-insensitively,
312
+ * by username. An all-digit query also matches that account id, listed
313
+ * first. An empty query returns the first accounts. `limit` defaults to 20
314
+ * and is capped at 50.
315
+ */
316
+ search(query: string, limit?: number): Promise<readonly SdkAccount[]>;
309
317
  }
310
318
 
311
319
  /**
@@ -900,6 +908,37 @@ export interface SdkRedeemedTicket {
900
908
 
901
909
  export type SdkPublicHandler = (req: SdkPublicRequest, reply: SdkPublicReply) => Promise<unknown>;
902
910
 
911
+ /**
912
+ * The body of a streamed route: never decoded, never buffered. The HOST counts
913
+ * the bytes and cuts the connection at `maxBytes`, so a module that forgets to
914
+ * count cannot open a bottomless pit.
915
+ */
916
+ export interface SdkPublicStreamBody {
917
+ /** The announced `Content-Length`, `null` when chunked. Unverified: compare it with what you read. */
918
+ contentLength: number | null;
919
+ /** The bytes, in order. Throws `FeatureError('validation')` past `maxBytes`. Consumable once. */
920
+ bytes(): AsyncIterable<Buffer>;
921
+ }
922
+
923
+ /** The request of a streamed route: the same, its decoded body replaced by its bytes. */
924
+ export interface SdkPublicStreamRequest extends Omit<SdkPublicRequest, 'body' | 'rawBody'> {
925
+ body: SdkPublicStreamBody;
926
+ }
927
+
928
+ export interface SdkPublicStreamRouteOptions {
929
+ /** Counts REQUESTS, not bytes: a 5 GiB upload is one request. Not what protects the disk. */
930
+ rateLimit?: { max: number; timeWindow: string };
931
+ /** Absolute ceiling of the body, enforced by the host. A per-account ceiling is yours to check on top. */
932
+ maxBytes: number;
933
+ /** Written, not defaulted: a route that swallows gigabytes never opens on the public listener by omission. */
934
+ exposure: 'app';
935
+ }
936
+
937
+ export type SdkPublicStreamHandler = (
938
+ req: SdkPublicStreamRequest,
939
+ reply: SdkPublicReply
940
+ ) => Promise<unknown>;
941
+
903
942
  /**
904
943
  * Where a module declares its public routes (capability `'routes.public'`).
905
944
  * Paths are absolute (`/t.js`, `/api/t/b`); a path the host already serves
@@ -908,6 +947,17 @@ export type SdkPublicHandler = (req: SdkPublicRequest, reply: SdkPublicReply) =>
908
947
  export interface SdkPublicApp {
909
948
  get(path: string, opts: SdkPublicRouteOptions, handler: SdkPublicHandler): void;
910
949
  post(path: string, opts: SdkPublicRouteOptions, handler: SdkPublicHandler): void;
950
+ /**
951
+ * A POST whose body is NOT decoded: the host hands it over as a bounded
952
+ * stream, whatever its content type. For what no parser should ever hold in
953
+ * full, an uploaded file. No path parameter, app origin only, and kept out
954
+ * of the CORS-widened paths: authenticate it with a ticket (`SdkSecrecy.ticket`).
955
+ */
956
+ postStream(
957
+ path: string,
958
+ opts: SdkPublicStreamRouteOptions,
959
+ handler: SdkPublicStreamHandler
960
+ ): void;
911
961
  }
912
962
 
913
963
  /**
@@ -1062,6 +1112,74 @@ export interface FeatureItemsEntry<Repo = unknown> {
1062
1112
  * credential, a destination) that cannot follow it.
1063
1113
  */
1064
1114
  move?: FeatureItemsMove<Repo>;
1115
+ /**
1116
+ * Copy this item to another workspace, of this DevEye or of ANOTHER one.
1117
+ * You describe what the item is made of, the app reads and writes it (see
1118
+ * `copy.ts`). Omit it and your items cannot be copied: the screen says so.
1119
+ */
1120
+ copy?: FeatureItemsCopy<Repo>;
1121
+ }
1122
+
1123
+ /** What copying one item leaves behind, decided on the SOURCE before a row is read. */
1124
+ export interface SdkCopyPlan {
1125
+ /** Why the copy is impossible, in sentences the screen shows as they are. Empty means it can go. */
1126
+ blockers: readonly string[];
1127
+ /**
1128
+ * What the copy will NOT carry, named one by one for the confirmation: a
1129
+ * token of the origin workspace, a history the destination rebuilds.
1130
+ */
1131
+ drops: readonly string[];
1132
+ }
1133
+
1134
+ /** See {@link FeatureItemsEntry.copy}. */
1135
+ export interface FeatureItemsCopy<Repo = unknown> {
1136
+ /**
1137
+ * What an item is made of. Build your `move` cells from the same tree
1138
+ * (`movableCellsOf`) and you hold one list instead of two.
1139
+ */
1140
+ tree: ItemTree;
1141
+ /** SOURCE side. Reads only; the destination is unknown here, it may be another DevEye. */
1142
+ plan?(ctx: FeatureItemsCopyPlanContext<Repo>): Promise<SdkCopyPlan>;
1143
+ /**
1144
+ * DESTINATION side, inside the transaction, before the first row is
1145
+ * written. Refuse by throwing a `FeatureError` (a name already taken there,
1146
+ * a quota reached), or amend `rows` in place: they are in the clear (a
1147
+ * title to suffix, a derived column to recompute).
1148
+ */
1149
+ admit?(ctx: FeatureItemsCopyAdmitContext<Repo>): Promise<void>;
1150
+ /**
1151
+ * DESTINATION side, same transaction, once the rows are written: give the
1152
+ * copy its place (the end of its list).
1153
+ */
1154
+ settle?(ctx: FeatureItemsCopySettleContext<Repo>): Promise<void>;
1155
+ }
1156
+
1157
+ export interface FeatureItemsCopyPlanContext<Repo = unknown> {
1158
+ q: SdkQueryable;
1159
+ repo: Repo;
1160
+ itemId: string;
1161
+ workspaceId: number;
1162
+ }
1163
+
1164
+ export interface FeatureItemsCopyAdmitContext<Repo = unknown> {
1165
+ /** Transactional, see {@link FeatureItemsMoveContext.q}. */
1166
+ q: SdkQueryable;
1167
+ /** Your repo. For reads only. */
1168
+ repo: Repo;
1169
+ toWorkspaceId: number;
1170
+ /** The rows about to be written, sealed cells in the clear. Yours to amend. */
1171
+ rows: ItemTreeRows;
1172
+ /** The quotas of the DESTINATION workspace's owner, as `ctx.quota` in a handler. */
1173
+ quota: SdkQuota;
1174
+ }
1175
+
1176
+ export interface FeatureItemsCopySettleContext<Repo = unknown> {
1177
+ /** Transactional, see {@link FeatureItemsMoveContext.q}. */
1178
+ q: SdkQueryable;
1179
+ repo: Repo;
1180
+ toWorkspaceId: number;
1181
+ /** The id the copy was given. */
1182
+ itemId: string;
1065
1183
  }
1066
1184
 
1067
1185
  /**
@@ -1246,6 +1364,23 @@ export async function resealCells(
1246
1364
  return pending.length;
1247
1365
  }
1248
1366
 
1367
+ export {
1368
+ countItemTreeRows,
1369
+ exportItemTree,
1370
+ importItemTree,
1371
+ itemTierOf,
1372
+ itemTreeProblem,
1373
+ movableCellsOf
1374
+ } from './copy';
1375
+ export type {
1376
+ ItemTier,
1377
+ ItemTree,
1378
+ ItemTreeDestination,
1379
+ ItemTreeRow,
1380
+ ItemTreeRows,
1381
+ ItemTreeTable
1382
+ } from './copy';
1383
+
1249
1384
  // Le conteneur chiffré que CloudSync et Backup partagent (voir `devb.ts`).
1250
1385
  export {
1251
1386
  BLOB_CHUNK_BYTES,
@@ -67,6 +67,28 @@ test('createTestServiceDeps: one store per workspace, hand-driven tickers, a wra
67
67
  assert.equal((await deps.devicesFor(1).list()).length, 1);
68
68
  });
69
69
 
70
+ test('the harness searches accounts like the app: substring, exact id first, capped', async () => {
71
+ const account = (id: number, username: string) => ({
72
+ id,
73
+ username,
74
+ email: `${username}@example.com`,
75
+ isAdmin: false,
76
+ created: 0
77
+ });
78
+ const { accounts } = createTestServiceDeps({
79
+ accounts: [account(7, 'zoe'), account(12, 'Alice'), account(3, 'bob12')]
80
+ });
81
+ const ids = async (query: string, limit?: number) =>
82
+ (await accounts.search(query, limit)).map((a) => a.id);
83
+
84
+ assert.deepEqual(await ids(' '), [12, 3, 7], 'an empty query lists by username');
85
+ assert.deepEqual(await ids('aLiCe@EXAMPLE'), [12]);
86
+ assert.deepEqual(await ids('12'), [12, 3], 'the exact id comes before a substring hit');
87
+ assert.deepEqual(await ids('12abc'), []);
88
+ assert.deepEqual(await ids('', 1), [12]);
89
+ assert.equal((await ids('', 0)).length, 1, 'a limit below one is raised to one');
90
+ });
91
+
70
92
  test('the harness scopes domains to the workspace, and finds a host whatever its spelling', async () => {
71
93
  const domains = [
72
94
  testDomain({ id: 1, host: 'a.example.com' }),
@@ -673,7 +673,27 @@ export function createTestServiceDeps<Repo = undefined>(
673
673
  ) ?? null
674
674
  ),
675
675
  list: (userIds) =>
676
- Promise.resolve((overrides.accounts ?? []).filter((a) => userIds.includes(a.id)))
676
+ Promise.resolve((overrides.accounts ?? []).filter((a) => userIds.includes(a.id))),
677
+ search: (query, limit) => {
678
+ const needle = query.trim().toLowerCase();
679
+ const id = /^\d+$/.test(needle) ? Number(needle) : null;
680
+ const found = (overrides.accounts ?? [])
681
+ .filter(
682
+ (a) =>
683
+ needle === '' ||
684
+ a.id === id ||
685
+ a.username.toLowerCase().includes(needle) ||
686
+ a.email.toLowerCase().includes(needle)
687
+ )
688
+ .sort(
689
+ (a, b) =>
690
+ Number(b.id === id) - Number(a.id === id) ||
691
+ a.username.localeCompare(b.username)
692
+ );
693
+ return Promise.resolve(
694
+ found.slice(0, Math.min(Math.max(1, Math.trunc(limit ?? 20)), 50))
695
+ );
696
+ }
677
697
  },
678
698
  audit: (entry) => {
679
699
  recorded.audits.push({ action: entry.action, description: entry.description });