@deveye/types 0.16.1 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -241,8 +241,10 @@ export {
241
241
  export type { LogCategory, LogEntry, LogLevelName, LogRow, LogSource } from './domain/logs';
242
242
  export {
243
243
  DEVICE_LOG_LEVELS,
244
+ DEVICE_LOG_OFFSET_MAX,
244
245
  DEVICE_LOG_PAGE_DEFAULT,
245
246
  DEVICE_LOG_PAGE_MAX,
247
+ deviceLogAnchorSchema,
246
248
  deviceLogFilterSchema,
247
249
  deviceLogLevelSchema,
248
250
  deviceLogLineSchema,
@@ -280,6 +282,7 @@ export type {
280
282
  SyncShareStatus
281
283
  } from './domain/syncProtocol';
282
284
  export type {
285
+ DeviceLogAnchor,
283
286
  DeviceLogFilter,
284
287
  DeviceLogLevel,
285
288
  DeviceLogLine,
@@ -437,6 +440,7 @@ export type {
437
440
  ExternalFeatureId,
438
441
  FeatureAccess,
439
442
  FeatureId,
443
+ ItemGrantOverride,
440
444
  WorkspaceCapability,
441
445
  WorkspaceFeatureGrant,
442
446
  WorkspaceFeatureId,
@@ -456,15 +460,10 @@ export {
456
460
  DEFAULT_RETENTION_DAYS,
457
461
  devicePlatformSchema,
458
462
  deviceSchema,
459
- deviceStatusSchema
460
- } from './domain/device';
461
- export type {
462
- Device,
463
- DevicePlatform,
464
- DeviceRow,
465
- DeviceStatus,
466
- DeviceWorkspaceRow
463
+ deviceStatusSchema,
464
+ terminalUser
467
465
  } from './domain/device';
466
+ export type { Device, DevicePlatform, DeviceRow, DeviceStatus } from './domain/device';
468
467
  export { packageManagerIdSchema, packageManagerSchema } from './domain/packages';
469
468
  export type { PackageManager, PackageManagerId } from './domain/packages';
470
469
  export {
@@ -560,7 +559,10 @@ export type { FeatureDescriptor } from './domain/featureRegistry';
560
559
  export {
561
560
  foreignRefSchema,
562
561
  itemAccessSchema,
562
+ itemExtraOverridesSchema,
563
563
  itemGrantStateSchema,
564
+ itemMoveDependencySchema,
565
+ itemMovePreviewSchema,
564
566
  itemRefSchema,
565
567
  itemRoleGrantSchema,
566
568
  itemRoleGrantViewSchema,
@@ -571,7 +573,10 @@ export {
571
573
  export type {
572
574
  ForeignRef,
573
575
  ItemAccess,
576
+ ItemExtraOverrides,
574
577
  ItemGrantState,
578
+ ItemMoveDependency,
579
+ ItemMovePreview,
575
580
  ItemRef,
576
581
  ItemRoleGrant,
577
582
  ItemRoleGrantRow,
@@ -584,6 +589,8 @@ export type {
584
589
  export {
585
590
  itemGrantList,
586
591
  itemGrantSet,
592
+ itemMove,
593
+ itemMovePreview,
587
594
  shareGet,
588
595
  shareSet,
589
596
  sharingCommands
@@ -689,8 +696,7 @@ export {
689
696
  agentTermResize,
690
697
  agentUnsubscribe,
691
698
  agentUpdate,
692
- agentUpgradePackages,
693
- terminalUser
699
+ agentUpgradePackages
694
700
  } from './features/agent';
695
701
  export {
696
702
  notifyChannelAdd,
@@ -22,6 +22,7 @@ import {
22
22
  fileUsageEntrySchema
23
23
  } from '../domain/deviceFiles';
24
24
  import {
25
+ deviceLogAnchorSchema,
25
26
  deviceLogFilterSchema,
26
27
  deviceLogLineSchema,
27
28
  deviceLogSourceSchema
@@ -589,7 +590,9 @@ export const agentLogQueryPayloadSchema = z.object({
589
590
  queryId: z.string().max(64),
590
591
  sourceId: z.string().min(1).max(512),
591
592
  filter: deviceLogFilterSchema.optional(),
592
- limit: z.number().int().positive().optional()
593
+ limit: z.number().int().positive().optional(),
594
+ offset: z.number().int().nonnegative().optional(),
595
+ anchor: deviceLogAnchorSchema.optional()
593
596
  });
594
597
  export type AgentLogQueryPayload = z.infer<typeof agentLogQueryPayloadSchema>;
595
598
 
@@ -156,7 +156,7 @@ declare module 'deveye-sdk-client' {
156
156
  | {
157
157
  kind: 'item';
158
158
  feature: FeatureId;
159
- itemId: number | string;
159
+ itemId: string;
160
160
  itemLabel: string;
161
161
  shareable?: boolean;
162
162
  };
@@ -171,6 +171,37 @@ declare module 'deveye-sdk-client' {
171
171
  */
172
172
  onOpenChange?: (open: boolean) => void;
173
173
  }>;
174
+ /**
175
+ * One provider of a feature and the key it wants. The row carries the state
176
+ * and the gesture; the key itself is typed in a dialog.
177
+ */
178
+ export interface ProviderKeyRow {
179
+ id: string;
180
+ label: string;
181
+ /** What the key unlocks, or what the provider brings. */
182
+ hint: string;
183
+ /** A key is on file for this provider. */
184
+ held: boolean;
185
+ /** `false` for a provider that needs none (Open-Meteo): shown, nothing to set. */
186
+ needsKey?: boolean;
187
+ /** Where to get one. Only offered while no key is held. */
188
+ signupUrl?: string;
189
+ /** Icon class suffix, without the `icon-` prefix. */
190
+ icon?: string;
191
+ }
192
+ /**
193
+ * The `sources` tab of a feature whose providers are a fixed list, each
194
+ * wanting one key. Renders the rows, the add/edit button on each, and the
195
+ * dialog. `onSave` / `onRemove` reject to keep the dialog open on the error.
196
+ */
197
+ export const ProviderKeys: ComponentType<{
198
+ rows: ProviderKeyRow[];
199
+ canWrite: boolean;
200
+ onSave: (id: string, key: string) => Promise<void>;
201
+ onRemove: (id: string) => Promise<void>;
202
+ /** Shown to a caller without write access. */
203
+ readOnlyHint: string;
204
+ }>;
174
205
  /** The canonical settings row classes (channelRow, field, sectionHint...). */
175
206
  export const settingsStyles: Readonly<Record<string, string>>;
176
207
  /** A plain count on a home card: a big number, a noun, a secondary line. */
@@ -385,9 +416,12 @@ declare module 'deveye-sdk-client' {
385
416
  export function useWorkspacePermissions(): {
386
417
  isOwner: boolean;
387
418
  can: (c: WorkspaceCapability) => boolean;
388
- canFeature: (f: FeatureId, level?: FeatureAccess) => boolean;
419
+ /** `itemId` répond pour CET élément, surcharge comprise. */
420
+ canFeature: (f: FeatureId, level?: FeatureAccess, itemId?: string) => boolean;
389
421
  canChannels: (f: FeatureId) => boolean;
390
- canExtra: (f: FeatureId, key: string) => boolean;
422
+ canManageItemGrants: (f: FeatureId) => boolean;
423
+ /** `itemId` répond pour CET élément, surcharge comprise. */
424
+ canExtra: (f: FeatureId, key: string, itemId?: string) => boolean;
391
425
  extraValue: (
392
426
  f: FeatureId,
393
427
  key: string,
@@ -446,7 +480,7 @@ declare module 'deveye-sdk-client' {
446
480
  * host's teleport, the same mechanism as "join someone". The access guard
447
481
  * is the host's; a missing item is ignored after a short grace.
448
482
  */
449
- export function openFeature(feature: string, itemId?: number): void;
483
+ export function openFeature(feature: string, itemId?: number | string): void;
450
484
  /**
451
485
  * Ask the feature popup for a wider frame (px) while the calling
452
486
  * component is mounted, `null` to ask for nothing. Several requests
package/src/sdk/client.ts CHANGED
@@ -11,18 +11,24 @@ import type { ComponentType, ReactNode } from 'react';
11
11
  */
12
12
 
13
13
  /**
14
- * The scope a settings panel is opened for. An item id is a number for every
15
- * row-keyed feature (the default), a string for a device (a UUID): a module
16
- * whose items are strings types its panels `SettingsPanelProps<string>`. The
17
- * shell's own sections (sharing, permissions, notifications) key on the number.
14
+ * The scope a settings panel is opened for. An item id is text, whatever key
15
+ * the feature's own table uses: a row-keyed feature reads it back with
16
+ * `Number(...)`, a device is a UUID as it stands.
18
17
  */
19
- export type SdkSettingsScope<Id extends number | string = number> =
20
- { kind: 'feature' } | { kind: 'item'; itemId: Id; itemLabel: string };
18
+ export type SdkSettingsScope =
19
+ { kind: 'feature' } | { kind: 'item'; itemId: string; itemLabel: string };
21
20
 
22
- export interface SettingsPanelProps<Id extends number | string = number> {
23
- scope: SdkSettingsScope<Id>;
21
+ export interface SettingsPanelProps {
22
+ scope: SdkSettingsScope;
24
23
  /** Caller has `write` on the feature. Render read-only when false. */
25
24
  canWrite: boolean;
25
+ /**
26
+ * Closes the settings dialog. For a panel that removes the very item being
27
+ * configured: the scope it was opened on no longer exists, and the shell
28
+ * would otherwise fall back to the feature's own tabs under the item's name.
29
+ * Not a substitute for saving — every other change applies in place.
30
+ */
31
+ close(): void;
26
32
  }
27
33
 
28
34
  export interface FeatureViewProps {
@@ -47,10 +53,7 @@ export interface FeatureClient {
47
53
  * `'sources'`, `'encryption'`, and any custom tab id. Generic tabs
48
54
  * (`'notifications'`, `'permissions'`) need no panel.
49
55
  */
50
- // `never` as the id: a panel typed for numbers and one typed for strings
51
- // are both assignable here (props are contravariant), and the shell, which
52
- // holds a `number | string`, casts once at that boundary.
53
- settingsPanels?: Readonly<Record<string, ComponentType<SettingsPanelProps<never>>>>;
56
+ settingsPanels?: Readonly<Record<string, ComponentType<SettingsPanelProps>>>;
54
57
  /**
55
58
  * The compact topbar widget declared by `manifest.topbarWidget`. Rendered
56
59
  * with NO props: everything it shows must come through YOUR feature's
@@ -0,0 +1,140 @@
1
+ import assert from 'node:assert/strict';
2
+ import { describe, it } from 'node:test';
3
+
4
+ import {
5
+ countMovableCells,
6
+ FeatureError,
7
+ resealCells,
8
+ type MovableCell,
9
+ type SdkCipher,
10
+ type SdkQueryable
11
+ } from './server';
12
+
13
+ /**
14
+ * Le rescellement d'un élément qui change d'espace. Ce qui se vérifie ici est
15
+ * ce qui ne pardonne pas : une seule cellule illisible doit tout annuler AVANT
16
+ * la première écriture, un arbre à moitié converti étant définitivement illisible
17
+ * sans que rien puisse le détecter.
18
+ */
19
+
20
+ interface Row {
21
+ row_id: number;
22
+ value: string;
23
+ }
24
+
25
+ /**
26
+ * Un queryable qui ne comprend du SQL que la table et la colonne lues, et qui
27
+ * retient ce qu'on a tenté d'écrire.
28
+ */
29
+ function fakeQ(cells: Record<string, Row[]>) {
30
+ const writes: { sql: string; params: unknown[] }[] = [];
31
+ const q: SdkQueryable = {
32
+ query: async <T extends object>(sql: string, params?: unknown[]) => {
33
+ void params;
34
+ const count = /SELECT COUNT\(\*\) AS n FROM (\w+)\s+WHERE (\w+)/.exec(sql);
35
+ if (count) {
36
+ return [
37
+ { n: (cells[`${count[1]}.${columnOf(sql)}`] ?? []).length }
38
+ ] as unknown as T[];
39
+ }
40
+ const read = /AS row_id, (\w+) AS value\s+FROM (\w+)/.exec(sql);
41
+ return (read ? (cells[`${read[2]}.${read[1]}`] ?? []) : []) as unknown as T[];
42
+ },
43
+ execute: async (sql: string, params?: unknown[]) => {
44
+ writes.push({ sql, params: params ?? [] });
45
+ return { affectedRows: 1, insertId: 0 };
46
+ }
47
+ };
48
+ return { q, writes };
49
+ }
50
+
51
+ /** La colonne d'un COUNT, que le SQL ne nomme que dans son `WHERE`. */
52
+ function columnOf(sql: string): string {
53
+ return /AND (\w+) IS NOT NULL/.exec(sql)?.[1] ?? '';
54
+ }
55
+
56
+ function cipherOf(tag: string): SdkCipher {
57
+ return {
58
+ encrypt: async (plain) => `${tag}:${plain}`,
59
+ decrypt: async (blob) => blob.slice(tag.length + 1),
60
+ tryDecrypt: async (blob) => (blob.startsWith(`${tag}:`) ? blob.slice(tag.length + 1) : null)
61
+ };
62
+ }
63
+
64
+ const ciphers = { from: cipherOf('A'), to: cipherOf('B') };
65
+
66
+ const CELLS: MovableCell[] = [
67
+ { table: 'ft_x_items', idColumn: 'id', ownerColumn: 'id', column: 'content' },
68
+ { table: 'ft_x_children', idColumn: 'id', ownerColumn: 'item_id', column: 'body' }
69
+ ];
70
+
71
+ describe('resealCells', () => {
72
+ it('rescelle chaque cellule sous la clé cible, la garde du propriétaire comprise', async () => {
73
+ const { q, writes } = fakeQ({
74
+ 'ft_x_items.content': [{ row_id: 7, value: 'A:corps' }],
75
+ 'ft_x_children.body': [
76
+ { row_id: 1, value: 'A:un' },
77
+ { row_id: 2, value: 'A:deux' }
78
+ ]
79
+ });
80
+
81
+ assert.equal(await resealCells(q, CELLS, 7, ciphers), 3);
82
+ assert.deepEqual(
83
+ writes.map((w) => w.params),
84
+ [
85
+ ['B:corps', 7, 7],
86
+ ['B:un', 1, 7],
87
+ ['B:deux', 2, 7]
88
+ ]
89
+ );
90
+ // La ligne se cible par son identifiant ET son propriétaire : une
91
+ // conversion ne peut pas déborder sur un voisin.
92
+ assert.match(writes[1]!.sql, /WHERE id = \? AND item_id = \?/);
93
+ });
94
+
95
+ it('annule tout sur une cellule illisible, sans avoir écrit une seule ligne', async () => {
96
+ const { q, writes } = fakeQ({
97
+ 'ft_x_items.content': [{ row_id: 7, value: 'A:corps' }],
98
+ // Scellée sous une troisième clé : la conversion doit renoncer.
99
+ 'ft_x_children.body': [{ row_id: 1, value: 'Z:perdu' }]
100
+ });
101
+
102
+ await assert.rejects(
103
+ resealCells(q, CELLS, 7, ciphers),
104
+ (err: unknown) => err instanceof FeatureError && /illisible/.test(err.message)
105
+ );
106
+ assert.equal(writes.length, 0);
107
+ });
108
+
109
+ it('suit un sous-parcours pour une ligne qui pend indirectement', async () => {
110
+ const indirect: MovableCell[] = [
111
+ {
112
+ table: 'ft_x_leaves',
113
+ idColumn: 'id',
114
+ ownerColumn: 'child_id',
115
+ ownerScope: 'SELECT id FROM ft_x_children WHERE item_id = ?',
116
+ column: 'body'
117
+ }
118
+ ];
119
+ const { q, writes } = fakeQ({ 'ft_x_leaves.body': [{ row_id: 5, value: 'A:feuille' }] });
120
+
121
+ await resealCells(q, indirect, 7, ciphers);
122
+ assert.match(
123
+ writes[0]!.sql,
124
+ /WHERE id = \? AND child_id IN \(SELECT id FROM ft_x_children WHERE item_id = \?\)/
125
+ );
126
+ assert.deepEqual(writes[0]!.params, ['B:feuille', 5, 7]);
127
+ });
128
+
129
+ it('compte ce qu’il y aurait à convertir sans rien convertir', async () => {
130
+ const { q, writes } = fakeQ({
131
+ 'ft_x_items.content': [{ row_id: 7, value: 'A:corps' }],
132
+ 'ft_x_children.body': [
133
+ { row_id: 1, value: 'A:un' },
134
+ { row_id: 2, value: 'A:deux' }
135
+ ]
136
+ });
137
+ assert.equal(await countMovableCells(q, CELLS, 7), 3);
138
+ assert.equal(writes.length, 0);
139
+ });
140
+ });
@@ -261,6 +261,16 @@ export interface ProjectsUsageProvider {
261
261
  usageOf(feature: string, itemId: number, workspaceId: number): Promise<readonly ProjectUsage[]>;
262
262
  /** How many projects of the workspace link each item of this feature (absent = zero). */
263
263
  countByItem(feature: string, workspaceId: number): Promise<ReadonlyMap<number, number>>;
264
+ /**
265
+ * The item leaves the workspace: drop every link pointing at it from
266
+ * there, and answer how many projects lost one. A link never spans two
267
+ * workspaces, so a departing item takes none with it; left alone the rows
268
+ * would keep naming an item that lives elsewhere now.
269
+ *
270
+ * Called by the app when an item is moved out, not by the module that owns
271
+ * the item. Idempotent, and zero for a feature that links nothing.
272
+ */
273
+ detach(feature: string, itemId: number, workspaceId: number): Promise<number>;
264
274
  /**
265
275
  * Writes one line in a project's timeline (a deployment triggered from a
266
276
  * project's tab). Open tier only: an event aimed at a guarded project is
package/src/sdk/server.ts CHANGED
@@ -476,13 +476,13 @@ export interface SdkItems {
476
476
  * feature grants, never raise it. Empty for the owner and for a member
477
477
  * without a role. Listings filter with it.
478
478
  */
479
- restrictions(): Promise<ReadonlyMap<number, ItemAccess>>;
479
+ restrictions(): Promise<ReadonlyMap<string, ItemAccess>>;
480
480
  /**
481
481
  * Throws `forbidden` unless THIS item is open to the caller at `level`
482
482
  * (default `'read'`), role restriction included. Commands that target one
483
483
  * item call it first.
484
484
  */
485
- assert(itemId: number, level?: FeatureAccess): Promise<void>;
485
+ assert(itemId: string, level?: FeatureAccess): Promise<void>;
486
486
  /**
487
487
  * The item no longer exists: drops its projections, its role restrictions
488
488
  * and its notification route. Call it from your delete handler; nothing
@@ -490,7 +490,7 @@ export interface SdkItems {
490
490
  * feature), so without this call the next item to inherit the id would
491
491
  * inherit them too.
492
492
  */
493
- forget(itemId: number): Promise<void>;
493
+ forget(itemId: string): Promise<void>;
494
494
  }
495
495
 
496
496
  /**
@@ -504,11 +504,17 @@ export interface SdkItems {
504
504
  */
505
505
  export interface SdkShareScope {
506
506
  /** The ids of the items projected into the active workspace from elsewhere. */
507
- readonly foreignIds: ReadonlySet<number>;
507
+ readonly foreignIds: ReadonlySet<string>;
508
508
  /** The home workspace of a projected item, or null when it is at home. */
509
- homeOf(itemId: number): number | null;
509
+ homeOf(itemId: string): number | null;
510
510
  /** The open cipher of the workspace the item lives in (the active one when it is at home). */
511
- cipherFor(itemId: number): Promise<SdkCipher>;
511
+ cipherFor(itemId: string): Promise<SdkCipher>;
512
+ /**
513
+ * The rank a projected item holds in the ACTIVE workspace, or null when it
514
+ * is at home (its own table carries the rank there). Each workspace orders
515
+ * what it sees independently.
516
+ */
517
+ orderOf(itemId: string): number | null;
512
518
  }
513
519
 
514
520
  /** Cross-workspace projection of your items (manifest `shareTier` other than `'never'`). */
@@ -518,6 +524,11 @@ export interface SdkSharing {
518
524
  * read command; the result does not outlive the command.
519
525
  */
520
526
  scope(): Promise<SdkShareScope>;
527
+ /**
528
+ * Sets the rank of a projected item in the ACTIVE workspace. For an item
529
+ * at home, rank belongs to your own table: write it there instead.
530
+ */
531
+ setOrder(itemId: string, order: number): Promise<void>;
521
532
  }
522
533
 
523
534
  /** Live invalidation from a background service, which writes without a command. */
@@ -802,7 +813,7 @@ export interface FeatureItemsEntry<Repo = unknown> {
802
813
  * (its own, or one it is projected into); null when it does not exist
803
814
  * there. The sharing commands rely on it to tell a home from a window.
804
815
  */
805
- homeOf(repo: Repo, itemId: number, workspaceId: number): Promise<number | null>;
816
+ homeOf(repo: Repo, itemId: string, workspaceId: number): Promise<number | null>;
806
817
  /**
807
818
  * The item's display name, decrypted with `cipher` (the open cipher of
808
819
  * `workspaceId`), or null when the item is gone or unreadable. Names the
@@ -812,7 +823,7 @@ export interface FeatureItemsEntry<Repo = unknown> {
812
823
  labelOf(
813
824
  repo: Repo,
814
825
  cipher: SdkCipher,
815
- itemId: number,
826
+ itemId: string,
816
827
  workspaceId: number
817
828
  ): Promise<string | null>;
818
829
  /**
@@ -823,7 +834,187 @@ export interface FeatureItemsEntry<Repo = unknown> {
823
834
  * moment it is asked, with a message that says why. Called with the item's
824
835
  * HOME workspace.
825
836
  */
826
- shareable?(repo: Repo, itemId: number, workspaceId: number): Promise<boolean>;
837
+ shareable?(repo: Repo, itemId: string, workspaceId: number): Promise<boolean>;
838
+ /**
839
+ * Move this item to another workspace. The ONLY operation of the whole
840
+ * system that re-encrypts (read under key A, written under key B); every
841
+ * other one keeps a blob under the key it was sealed with. Omit it and
842
+ * your items cannot be moved: the screen offers nothing and `item.move`
843
+ * refuses. That default is the safe one, and staying on it is a valid
844
+ * answer for a feature whose item depends on a workspace source (a
845
+ * credential, a destination) that cannot follow it.
846
+ */
847
+ move?: FeatureItemsMove<Repo>;
848
+ }
849
+
850
+ /**
851
+ * What moving one item would cost, decided while it is still at home and
852
+ * before a single row is written.
853
+ */
854
+ export interface SdkMovePlan {
855
+ /**
856
+ * Why the move is impossible, in sentences the screen shows as they are.
857
+ * Empty means it can go. Put the decisive one first: a name already taken
858
+ * in the target, a source of the origin workspace that cannot follow.
859
+ */
860
+ blockers: readonly string[];
861
+ /**
862
+ * What the move destroys, named one by one, for the confirmation to list
863
+ * verbatim: a history left behind, a setting that means nothing there.
864
+ * Say it here or the caller discovers it afterwards.
865
+ */
866
+ drops: readonly string[];
867
+ /**
868
+ * Encrypted cells to convert, so the confirmation can say how much rather
869
+ * than spin. An estimate is fine; zero is a legitimate answer.
870
+ */
871
+ rows: number;
872
+ }
873
+
874
+ /** See {@link FeatureItemsEntry.move}. */
875
+ export interface FeatureItemsMove<Repo = unknown> {
876
+ /**
877
+ * Everything the confirmation must say, and every refusal, with the item
878
+ * still at home and nothing written yet. Answer for THAT target: a name
879
+ * collision or a missing source is decidable only against it.
880
+ */
881
+ plan(ctx: FeatureItemsMovePlanContext<Repo>): Promise<SdkMovePlan>;
882
+ /**
883
+ * Re-home the item: `workspace_id` on every row it owns, and every
884
+ * encrypted cell read with `ciphers.from` and written with `ciphers.to`.
885
+ *
886
+ * Read and convert EVERYTHING before the first write. A tree half
887
+ * converted is unreadable forever and nothing can detect it: one encrypted
888
+ * blob is indistinguishable from another. `reencryptProjectTree` in the
889
+ * Projects module is the reference implementation.
890
+ */
891
+ apply(ctx: FeatureItemsMoveContext<Repo>): Promise<void>;
892
+ }
893
+
894
+ /** The handles {@link FeatureItemsMove.plan} works with. Reads only. */
895
+ export interface FeatureItemsMovePlanContext<Repo = unknown> {
896
+ /** Not transactional: planning writes nothing. {@link countMovableCells} takes it. */
897
+ q: SdkQueryable;
898
+ repo: Repo;
899
+ itemId: string;
900
+ fromWorkspaceId: number;
901
+ toWorkspaceId: number;
902
+ }
903
+
904
+ /** The handles {@link FeatureItemsMove.apply} works with. */
905
+ export interface FeatureItemsMoveContext<Repo = unknown> {
906
+ /**
907
+ * Transactional: what you write here commits with the app's own cleanup,
908
+ * or rolls back with it. Write through this, NEVER through `repo`, which
909
+ * is bound to the pool and would land outside the transaction.
910
+ */
911
+ q: SdkQueryable;
912
+ /** Your repo. For reads only, see `q`. */
913
+ repo: Repo;
914
+ itemId: string;
915
+ fromWorkspaceId: number;
916
+ toWorkspaceId: number;
917
+ /** The open ciphers of the two workspaces: decrypt with `from`, seal with `to`. */
918
+ ciphers: { from: SdkCipher; to: SdkCipher };
919
+ }
920
+
921
+ /**
922
+ * One column of encrypted text hanging off an item, for {@link resealCells}.
923
+ *
924
+ * ⚠️ The list you build out of these is held BY HAND: an encrypted column left
925
+ * out of it stays under the old key and becomes unreadable, and nothing can
926
+ * detect it, one encrypted blob being indistinguishable from another. Revisit
927
+ * it whenever you add an encrypted column.
928
+ */
929
+ export interface MovableCell {
930
+ table: string;
931
+ /** Identifying column of the row, to rewrite exactly one. */
932
+ idColumn: string;
933
+ /** Column tying the row to the item. */
934
+ ownerColumn: string;
935
+ column: string;
936
+ /**
937
+ * For a row hanging off the item INDIRECTLY: a SQL subquery selecting the
938
+ * `ownerColumn` values that belong to it, taking the item's id as its only
939
+ * `?` (a mail account's messages hang off its folders:
940
+ * `SELECT id FROM mail_folders WHERE account_id = ?`).
941
+ *
942
+ * Interpolated into the query, so it must be a literal written in your
943
+ * module, exactly like `table` and `column`. Never build it from input.
944
+ */
945
+ ownerScope?: string;
946
+ }
947
+
948
+ /** `WHERE` fragment tying a cell's rows to the item, subquery included. */
949
+ function ownerFilter(cell: MovableCell): string {
950
+ return cell.ownerScope
951
+ ? `${cell.ownerColumn} IN (${cell.ownerScope})`
952
+ : `${cell.ownerColumn} = ?`;
953
+ }
954
+
955
+ /** How many cells {@link resealCells} would convert: a `plan`'s `rows`. */
956
+ export async function countMovableCells(
957
+ q: SdkQueryable,
958
+ cells: readonly MovableCell[],
959
+ ownerId: string | number
960
+ ): Promise<number> {
961
+ let total = 0;
962
+ for (const cell of cells) {
963
+ const rows = await q.query<{ n: number }>(
964
+ `SELECT COUNT(*) AS n FROM ${cell.table}
965
+ WHERE ${ownerFilter(cell)} AND ${cell.column} IS NOT NULL AND ${cell.column} <> ''`,
966
+ [ownerId]
967
+ );
968
+ total += Number(rows[0]?.n ?? 0);
969
+ }
970
+ return total;
971
+ }
972
+
973
+ /**
974
+ * Re-seals every encrypted cell of an item from one workspace's key to
975
+ * another's, for a `move`'s `apply`.
976
+ *
977
+ * Reads and converts EVERYTHING before the first write, and throws before
978
+ * writing anything if one cell resists: half a converted tree is unreadable
979
+ * forever. Call it before you change the item's `workspace_id`, so a failure
980
+ * leaves the item where it was.
981
+ */
982
+ export async function resealCells(
983
+ q: SdkQueryable,
984
+ cells: readonly MovableCell[],
985
+ ownerId: string | number,
986
+ ciphers: { from: SdkCipher; to: SdkCipher }
987
+ ): Promise<number> {
988
+ const pending: { cell: MovableCell; id: string | number; value: string }[] = [];
989
+ for (const cell of cells) {
990
+ // A cell that is empty has nothing to convert, and that is the common
991
+ // case for an error message or an optional body.
992
+ const rows = await q.query<{ row_id: string | number; value: string }>(
993
+ `SELECT ${cell.idColumn} AS row_id, ${cell.column} AS value FROM ${cell.table}
994
+ WHERE ${ownerFilter(cell)} AND ${cell.column} IS NOT NULL AND ${cell.column} <> ''`,
995
+ [ownerId]
996
+ );
997
+ for (const row of rows) {
998
+ const plain = await ciphers.from.tryDecrypt(String(row.value));
999
+ if (plain === null) {
1000
+ throw new FeatureError(
1001
+ 'internal',
1002
+ `Une ligne de ${cell.table} est illisible : déplacement annulé, rien n’a été modifié.`
1003
+ );
1004
+ }
1005
+ pending.push({ cell, id: row.row_id, value: await ciphers.to.encrypt(plain) });
1006
+ }
1007
+ }
1008
+
1009
+ for (const { cell, id, value } of pending) {
1010
+ // La garde du propriétaire dans le `WHERE` même quand l'identifiant
1011
+ // suffit : une conversion ne peut alors pas déborder sur un voisin.
1012
+ await q.execute(
1013
+ `UPDATE ${cell.table} SET ${cell.column} = ? WHERE ${cell.idColumn} = ? AND ${ownerFilter(cell)}`,
1014
+ [value, id, ownerId]
1015
+ );
1016
+ }
1017
+ return pending.length;
827
1018
  }
828
1019
 
829
1020
  // Le conteneur chiffré que CloudSync et Backup partagent (voir `devb.ts`).