@deveye/types 0.20.1 → 0.20.3

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.
@@ -1,9 +1,12 @@
1
1
  import type { ZodType } from 'zod';
2
2
  import type { ItemAccess } from '../domain/sharing';
3
+ import type { PathExclusion } from '../domain/pathExclusions';
3
4
  import { normaliseDomainHost } from './domains';
4
5
  import { resolveExtras, type FeatureManifest } from './manifest';
5
6
  import {
6
7
  FeatureError,
8
+ type AgentFolderArchive,
9
+ type AgentFolderArchiveSummary,
7
10
  type DevEyeFacade,
8
11
  type FeatureDomainsContext,
9
12
  type SdkDns,
@@ -15,6 +18,8 @@ import {
15
18
  type SdkDevice,
16
19
  type SdkFeatureContext,
17
20
  type SdkLogger,
21
+ type SdkOrigins,
22
+ type SdkPlanPauses,
18
23
  type SdkProviders,
19
24
  type SdkTelemetry,
20
25
  type SdkTelemetrySnapshot,
@@ -112,6 +117,13 @@ export interface RecordedCalls {
112
117
  audits: { action: string; description: string }[];
113
118
  /** Outbound agent frames, as `{ method, deviceId }` (payloads dropped for brevity). */
114
119
  agentRequests: { method: string; deviceId: string }[];
120
+ /** Folder archives asked through `agents.archiveFolder`, with what they cover. */
121
+ archiveRequests: {
122
+ deviceId: string;
123
+ path: string;
124
+ exclusions: readonly PathExclusion[];
125
+ oneFileSystem: boolean;
126
+ }[];
115
127
  /** Instants pinned through `telemetry.pinInstant`. */
116
128
  pinnedInstants: { deviceId: string; ts: number }[];
117
129
  /** Frames pushed through `live.publish`, in order. */
@@ -172,9 +184,22 @@ export function testDevice(over: Partial<SdkDevice> & { id: string }): SdkDevice
172
184
  };
173
185
  }
174
186
 
175
- function recordingDevices(devices: readonly SdkDevice[]): DevEyeFacade['devices'] {
187
+ function recordingDevices(
188
+ devices: readonly SdkDevice[],
189
+ refuseExtras: boolean | readonly string[] = false
190
+ ): DevEyeFacade['devices'] {
191
+ const refused = (id: string): boolean =>
192
+ refuseExtras === true || (Array.isArray(refuseExtras) && refuseExtras.includes(id));
176
193
  return {
177
- authorize: (id) => Promise.resolve(devices.find((d) => d.id === id) ?? testDevice({ id })),
194
+ authorize: (id, options) =>
195
+ refused(id) && (options?.extras?.length ?? 0) > 0
196
+ ? Promise.reject(
197
+ new FeatureError(
198
+ 'forbidden',
199
+ 'Cette permission ne vous est pas accordée sur cet élément'
200
+ )
201
+ )
202
+ : Promise.resolve(devices.find((d) => d.id === id) ?? testDevice({ id })),
178
203
  list: () => Promise.resolve([...devices]),
179
204
  isOnline: (id) => devices.find((d) => d.id === id)?.online ?? true
180
205
  };
@@ -194,7 +219,49 @@ function recordingTelemetry(
194
219
  };
195
220
  }
196
221
 
197
- function recordingAgents(recorded: RecordedCalls): DevEyeFacade['agents'] {
222
+ /** What a test says of a folder archive: its pieces, or the error its stream throws. */
223
+ export interface TestFolderArchive {
224
+ chunks: readonly Buffer[];
225
+ summary?: Partial<AgentFolderArchiveSummary>;
226
+ }
227
+
228
+ /** What a test says of its devices' agents: a deployment's verdict, an inventory, folder archives. */
229
+ interface TestAgents {
230
+ dockerRun?: DevEyeFacade['agents']['dockerRun'];
231
+ dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
232
+ /** By device id. A device without an entry answers nothing: its stream throws. */
233
+ archives?: Readonly<Record<string, TestFolderArchive | Error>>;
234
+ }
235
+
236
+ /** Replays the planned pieces; the summary appears once the last one is taken, as in the app. */
237
+ function replayedArchive(planned: TestFolderArchive | Error | undefined): AgentFolderArchive {
238
+ let summary: AgentFolderArchiveSummary | null = null;
239
+ return {
240
+ get summary() {
241
+ return summary;
242
+ },
243
+ async *[Symbol.asyncIterator]() {
244
+ if (!planned) throw new Error('No archive planned for this device');
245
+ if (planned instanceof Error) throw planned;
246
+ let bytesRead = 0;
247
+ for (const chunk of planned.chunks) {
248
+ bytesRead += chunk.length;
249
+ yield chunk;
250
+ }
251
+ summary = {
252
+ files: 1,
253
+ dirs: 0,
254
+ bytesRead,
255
+ skipped: 0,
256
+ changed: 0,
257
+ samples: [],
258
+ ...planned.summary
259
+ };
260
+ }
261
+ };
262
+ }
263
+
264
+ function recordingAgents(recorded: RecordedCalls, docker: TestAgents = {}): DevEyeFacade['agents'] {
198
265
  const req = (method: string) => (deviceId: string) => {
199
266
  recorded.agentRequests.push({ method, deviceId });
200
267
  return true;
@@ -216,7 +283,6 @@ function recordingAgents(recorded: RecordedCalls): DevEyeFacade['agents'] {
216
283
  publishSyncState: () => undefined,
217
284
  requestDestroy: req('requestDestroy'),
218
285
  disconnectAgent: req('disconnectAgent'),
219
- resetAgentSession: req('resetAgentSession'),
220
286
  // Nothing synced: a test of the self-update flag feeds a manifest to
221
287
  // the module's own pure helper.
222
288
  servedManifest: () => Promise.resolve(null),
@@ -226,7 +292,24 @@ function recordingAgents(recorded: RecordedCalls): DevEyeFacade['agents'] {
226
292
  // with a refusal injects its own facade through `deveye`.
227
293
  awaitFilesOp: () => Promise.resolve({ ok: true }),
228
294
  cancelFilesOp: () => undefined,
229
- buffered: () => 0
295
+ buffered: () => 0,
296
+ // Recorded, then answered as the test decides: success, and no
297
+ // inventory, by default.
298
+ dockerRun: (deviceId, order, options) => {
299
+ recorded.agentRequests.push({ method: 'dockerRun', deviceId });
300
+ return docker.dockerRun
301
+ ? docker.dockerRun(deviceId, order, options)
302
+ : Promise.resolve({ ok: true });
303
+ },
304
+ dockerInventory: (deviceId, timeoutMs) =>
305
+ docker.dockerInventory
306
+ ? docker.dockerInventory(deviceId, timeoutMs)
307
+ : Promise.resolve(null),
308
+ archiveFolder(deviceId, request) {
309
+ recorded.agentRequests.push({ method: 'archiveFolder', deviceId });
310
+ recorded.archiveRequests.push({ deviceId, ...request });
311
+ return replayedArchive(docker.archives?.[deviceId]);
312
+ }
230
313
  };
231
314
  }
232
315
 
@@ -243,6 +326,26 @@ function fakeDerive(salt: string, info: string, length: number): Uint8Array {
243
326
  return out;
244
327
  }
245
328
 
329
+ /** The plan pauses, from a fixed list by YOUR quota key: no key is checked against the manifest. */
330
+ function memoryPauses(
331
+ pausedItems: Readonly<Record<string, readonly string[]>> | undefined
332
+ ): SdkPlanPauses {
333
+ return {
334
+ isPaused: (key, itemId) => (pausedItems?.[key] ?? []).includes(itemId),
335
+ paused: (key) => pausedItems?.[key] ?? []
336
+ };
337
+ }
338
+
339
+ /** The app's refusal of a paused item run on demand. */
340
+ async function assertActiveIn(pauses: SdkPlanPauses, key: string, itemId: string): Promise<void> {
341
+ if (pauses.isPaused(key, itemId)) {
342
+ throw new FeatureError('quota_exceeded', `« ${key} » ${itemId} is paused by the plan`, {
343
+ key,
344
+ paused: true
345
+ });
346
+ }
347
+ }
348
+
246
349
  function memoryDomains(domains: readonly SdkDomain[]) {
247
350
  return {
248
351
  in: (workspaceId: number) => domains.filter((d) => d.workspaceId === workspaceId),
@@ -285,6 +388,8 @@ export interface TestContextOverrides<Repo> {
285
388
  quotaLimits?: Record<string, number>;
286
389
  /** The workspaces the owner account owns, handed to a quota counter. Default: the workspace of the call. */
287
390
  ownerWorkspaceIds?: readonly number[];
391
+ /** The items the plan holds paused, by YOUR `stock` quota key. Default none. */
392
+ pausedItems?: Record<string, readonly string[]>;
288
393
  canWrite?: boolean;
289
394
  /** Extra permissions the caller holds, as the grant would carry them. */
290
395
  extras?: Record<string, boolean | string>;
@@ -298,12 +403,23 @@ export interface TestContextOverrides<Repo> {
298
403
  hasRoute?: boolean;
299
404
  /** What `deveye.notify.send` resolves (no usable channel: false). Default true; recorded either way. */
300
405
  notifyAccepted?: boolean;
301
- /** What `ctx.origins` answers. Default `https://deveye.test` / `https://public.deveye.test`. */
302
- origins?: { app: string; public: string };
406
+ /** What `ctx.origins` answers. Default `https://deveye.test` / `https://public.deveye.test` / `https://site.deveye.test`. */
407
+ origins?: SdkOrigins;
303
408
  /** The channel ids `deveye.notify.liveChannels` lists. Default none. */
304
409
  liveChannels?: readonly number[];
305
410
  /** Devices `deveye.devices` reveals. Default none listed, any id authorized. */
306
411
  devices?: readonly SdkDevice[];
412
+ /**
413
+ * `deveye.devices.authorize` refuses any `extras`: the caller lacks them
414
+ * on every device (`true`) or on these ones. Default false.
415
+ */
416
+ refuseDeviceExtras?: boolean | readonly string[];
417
+ /** What `deveye.agents.dockerRun` resolves. Default success. */
418
+ dockerRun?: DevEyeFacade['agents']['dockerRun'];
419
+ /** What `deveye.agents.dockerInventory` resolves. Default null (no answer). */
420
+ dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
421
+ /** What `deveye.agents.archiveFolder` streams, by device id. Default none: the stream throws. */
422
+ archives?: Readonly<Record<string, TestFolderArchive | Error>>;
307
423
  /** Instants `deveye.telemetry.snapshot` answers (matched within a second). Default none. */
308
424
  snapshots?: readonly SdkTelemetrySnapshot[];
309
425
  /** Override facade members entirely when the defaults are not enough. */
@@ -342,6 +458,7 @@ export function createTestContext<Repo = undefined>(
342
458
  liveMessages: [],
343
459
  audits: [],
344
460
  agentRequests: [],
461
+ archiveRequests: [],
345
462
  pinnedInstants: [],
346
463
  livePublishes: [],
347
464
  accountChanges: []
@@ -349,6 +466,7 @@ export function createTestContext<Repo = undefined>(
349
466
  const isOwner = overrides.isOwner ?? true;
350
467
  const workspaceId = overrides.workspaceId ?? 1;
351
468
  const canWrite = overrides.canWrite ?? true;
469
+ const pauses = memoryPauses(overrides.pausedItems);
352
470
  const deveye: DevEyeFacade = {
353
471
  notify: recordingNotify(
354
472
  recorded,
@@ -364,9 +482,9 @@ export function createTestContext<Repo = undefined>(
364
482
  ])
365
483
  },
366
484
  workspaces: { list: () => Promise.resolve(overrides.workspaces ?? []) },
367
- devices: recordingDevices(overrides.devices ?? []),
485
+ devices: recordingDevices(overrides.devices ?? [], overrides.refuseDeviceExtras ?? false),
368
486
  telemetry: recordingTelemetry(recorded, overrides.snapshots ?? []),
369
- agents: recordingAgents(recorded),
487
+ agents: recordingAgents(recorded, overrides),
370
488
  accounts: {
371
489
  me: () =>
372
490
  Promise.resolve(
@@ -418,6 +536,7 @@ export function createTestContext<Repo = undefined>(
418
536
  }
419
537
  },
420
538
  quota: {
539
+ ...pauses,
421
540
  limit: (key) => Promise.resolve(overrides.quotaLimits?.[key] ?? null),
422
541
  // The exact rule of the app: never counted when unlimited, refused
423
542
  // once the count AFTER creation passes the limit.
@@ -431,7 +550,8 @@ export function createTestContext<Repo = undefined>(
431
550
  limit
432
551
  });
433
552
  }
434
- }
553
+ },
554
+ assertActive: (key, itemId) => assertActiveIn(pauses, key, itemId)
435
555
  },
436
556
  items: {
437
557
  restrictions: () => Promise.resolve(restrictions),
@@ -517,7 +637,8 @@ export function createTestContext<Repo = undefined>(
517
637
  requestId: 'test',
518
638
  origins: overrides.origins ?? {
519
639
  app: 'https://deveye.test',
520
- public: 'https://public.deveye.test'
640
+ public: 'https://public.deveye.test',
641
+ site: 'https://site.deveye.test'
521
642
  }
522
643
  };
523
644
  }
@@ -543,18 +664,30 @@ export interface TestServiceOverrides<Repo> {
543
664
  workspaceIds?: readonly number[];
544
665
  /** Devices every workspace reveals. Default none. */
545
666
  devices?: readonly SdkDevice[];
667
+ /** What `membersFor(workspaceId).list()` answers, by workspace id. Default none. */
668
+ members?: Readonly<Record<number, Awaited<ReturnType<DevEyeFacade['members']['list']>>>>;
669
+ /** What `deps.agents.dockerRun` resolves. Default success. */
670
+ dockerRun?: DevEyeFacade['agents']['dockerRun'];
671
+ /** What `deps.agents.dockerInventory` resolves. Default null (no answer). */
672
+ dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
673
+ /** What `deps.agents.archiveFolder` streams, by device id. Default none: the stream throws. */
674
+ archives?: Readonly<Record<string, TestFolderArchive | Error>>;
675
+ /** What `deps.access` answers. Default: every member holds every right. */
676
+ access?: Partial<FeatureServiceDeps['access']>;
546
677
  /** The accounts `deps.accounts` knows. Default none. */
547
678
  accounts?: readonly SdkAccount[];
548
679
  /** The plan's limits `deps.quotaFor` applies, by YOUR quota key. Default none (unlimited). */
549
680
  quotaLimits?: Record<string, number>;
681
+ /** The items the plan holds paused (`deps.pauses`), by YOUR `stock` quota key. Default none. */
682
+ pausedItems?: Record<string, readonly string[]>;
550
683
  /** What `deveyeFor(...).notify.hasRoute` answers. Default true. */
551
684
  hasRoute?: boolean;
552
685
  /** What `deveyeFor(...).notify.send` resolves. Default true; recorded either way. */
553
686
  notifyAccepted?: boolean;
554
687
  /** The channel ids `deveyeFor(...).notify.liveChannels` lists. Default none. */
555
688
  liveChannels?: readonly number[];
556
- /** What `deps.origins` answers. Default `https://deveye.test` / `https://public.deveye.test`. */
557
- origins?: { app: string; public: string };
689
+ /** What `deps.origins` answers. Default `https://deveye.test` / `https://public.deveye.test` / `https://site.deveye.test`. */
690
+ origins?: SdkOrigins;
558
691
  /** Instants `telemetry.snapshot` answers (matched within a second). Default none. */
559
692
  snapshots?: readonly SdkTelemetrySnapshot[];
560
693
  /** The feature's domains, every workspace mixed. Default none. */
@@ -576,6 +709,7 @@ export function createTestServiceDeps<Repo = undefined>(
576
709
  liveMessages: [],
577
710
  audits: [],
578
711
  agentRequests: [],
712
+ archiveRequests: [],
579
713
  pinnedInstants: [],
580
714
  livePublishes: [],
581
715
  accountChanges: [],
@@ -592,6 +726,7 @@ export function createTestServiceDeps<Repo = undefined>(
592
726
  overrides.liveChannels ?? []
593
727
  );
594
728
  const devices = recordingDevices(overrides.devices ?? []);
729
+ const pauses = memoryPauses(overrides.pausedItems);
595
730
  return {
596
731
  recorded,
597
732
  stores,
@@ -609,7 +744,8 @@ export function createTestServiceDeps<Repo = undefined>(
609
744
  deveyeFor: () => ({ notify }),
610
745
  origins: overrides.origins ?? {
611
746
  app: 'https://deveye.test',
612
- public: 'https://public.deveye.test'
747
+ public: 'https://public.deveye.test',
748
+ site: 'https://site.deveye.test'
613
749
  },
614
750
  secrecy: {
615
751
  redeem: (ticket) => {
@@ -632,6 +768,9 @@ export function createTestServiceDeps<Repo = undefined>(
632
768
  }
633
769
  },
634
770
  devicesFor: () => ({ list: devices.list, isOnline: devices.isOnline }),
771
+ membersFor: (workspaceId) => ({
772
+ list: () => Promise.resolve(overrides.members?.[workspaceId] ?? [])
773
+ }),
635
774
  devices: {
636
775
  find: (id) =>
637
776
  Promise.resolve((overrides.devices ?? []).find((d) => d.id === id) ?? null),
@@ -651,6 +790,7 @@ export function createTestServiceDeps<Repo = undefined>(
651
790
  }
652
791
  },
653
792
  quotaFor: () => ({
793
+ ...pauses,
654
794
  limit: (key) => Promise.resolve(overrides.quotaLimits?.[key] ?? null),
655
795
  async assert(key, countAfter) {
656
796
  const limit = overrides.quotaLimits?.[key];
@@ -661,8 +801,10 @@ export function createTestServiceDeps<Repo = undefined>(
661
801
  limit
662
802
  });
663
803
  }
664
- }
804
+ },
805
+ assertActive: (key, itemId) => assertActiveIn(pauses, key, itemId)
665
806
  }),
807
+ pauses,
666
808
  accounts: {
667
809
  find: (userId) =>
668
810
  Promise.resolve((overrides.accounts ?? []).find((a) => a.id === userId) ?? null),
@@ -698,7 +840,11 @@ export function createTestServiceDeps<Repo = undefined>(
698
840
  audit: (entry) => {
699
841
  recorded.audits.push({ action: entry.action, description: entry.description });
700
842
  },
701
- agents: recordingAgents(recorded),
843
+ agents: recordingAgents(recorded, overrides),
844
+ access: {
845
+ feature: overrides.access?.feature ?? (() => Promise.resolve({ ok: true })),
846
+ device: overrides.access?.device ?? (() => Promise.resolve({ ok: true }))
847
+ },
702
848
  // A fake wrapper: the sealed string is a handle to the bytes, and an
703
849
  // unknown handle opens to `null` exactly like a tampered blob would.
704
850
  keys: {
@@ -737,7 +883,14 @@ export function createTestServiceDeps<Repo = undefined>(
737
883
 
738
884
  /** A domain row for a test, verified by default. */
739
885
  export function testDomain(over: Partial<SdkDomain> & { id: number; host: string }): SdkDomain {
740
- return { workspaceId: 1, token: 'a'.repeat(32), verified: true, verifiedAt: 1, ...over };
886
+ return {
887
+ workspaceId: 1,
888
+ token: 'a'.repeat(32),
889
+ verified: true,
890
+ verifiedAt: 1,
891
+ planPaused: false,
892
+ ...over
893
+ };
741
894
  }
742
895
 
743
896
  /**
@@ -749,7 +902,7 @@ export function createTestDomainsContext<Repo = undefined>(
749
902
  overrides: {
750
903
  repo?: Repo;
751
904
  dns?: Partial<SdkDns>;
752
- origins?: { app: string; public: string };
905
+ origins?: SdkOrigins;
753
906
  } = {}
754
907
  ): FeatureDomainsContext<Repo> {
755
908
  const stores = new Map<number, TestFeatureStore>();
@@ -758,7 +911,8 @@ export function createTestDomainsContext<Repo = undefined>(
758
911
  repo: overrides.repo as Repo,
759
912
  origins: overrides.origins ?? {
760
913
  app: 'https://deveye.test',
761
- public: 'https://public.deveye.test'
914
+ public: 'https://public.deveye.test',
915
+ site: 'https://site.deveye.test'
762
916
  },
763
917
  cipherFor: () => identityCipher,
764
918
  storeFor(workspaceId) {