@deveye/types 0.20.0 → 0.20.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.
package/src/sdk/env.ts ADDED
@@ -0,0 +1,191 @@
1
+ /**
2
+ * A module's environment variables, declared once as plain data.
3
+ *
4
+ * A module reads its own variables (never through the host), and each one has
5
+ * a default that works: an install without any of these lines must run. But a
6
+ * default applied in silence is a trap when it guesses at the operator's world
7
+ * (a site address, a storage path). So the same spec is handed to the host
8
+ * (`FeatureServer.env`), which reads it again at boot and warns, once per
9
+ * module, about every variable left to its default.
10
+ *
11
+ * Pure: a spec is data and `readModuleEnv` reads only the source it is given,
12
+ * so the host's copy of this package and a module's copy agree.
13
+ */
14
+
15
+ interface ModuleEnvCommon {
16
+ /**
17
+ * Absent without a warning: a credential or an opt-in the install may well
18
+ * not use (an OAuth client, a certificate supplied by the operator).
19
+ */
20
+ optional?: boolean;
21
+ }
22
+
23
+ /** An integer, `min` or more (1 when omitted). */
24
+ export interface ModuleEnvInt extends ModuleEnvCommon {
25
+ kind: 'int';
26
+ default: number;
27
+ min?: number;
28
+ }
29
+
30
+ export interface ModuleEnvText extends ModuleEnvCommon {
31
+ kind: 'text';
32
+ default: string;
33
+ }
34
+
35
+ export interface ModuleEnvPath extends ModuleEnvCommon {
36
+ kind: 'path';
37
+ default: string;
38
+ }
39
+
40
+ /** An http(s) address. Set to an empty string, it means "none", never the default. */
41
+ export interface ModuleEnvUrl extends ModuleEnvCommon {
42
+ kind: 'url';
43
+ default: string;
44
+ }
45
+
46
+ /** `true`/`1` or `false`/`0`, in any case. */
47
+ export interface ModuleEnvFlag extends ModuleEnvCommon {
48
+ kind: 'flag';
49
+ default: boolean;
50
+ }
51
+
52
+ export interface ModuleEnvChoice<C extends string = string> extends ModuleEnvCommon {
53
+ kind: 'choice';
54
+ default: C;
55
+ choices: readonly C[];
56
+ }
57
+
58
+ /** Never printed. Its default is the empty string. */
59
+ export interface ModuleEnvSecret extends ModuleEnvCommon {
60
+ kind: 'secret';
61
+ }
62
+
63
+ export type ModuleEnvVar =
64
+ | ModuleEnvInt
65
+ | ModuleEnvText
66
+ | ModuleEnvPath
67
+ | ModuleEnvUrl
68
+ | ModuleEnvFlag
69
+ | ModuleEnvChoice
70
+ | ModuleEnvSecret;
71
+
72
+ export type ModuleEnvSpec = Readonly<Record<string, ModuleEnvVar>>;
73
+
74
+ type ModuleEnvValue<V> = V extends ModuleEnvInt
75
+ ? number
76
+ : V extends ModuleEnvFlag
77
+ ? boolean
78
+ : V extends ModuleEnvChoice<infer C>
79
+ ? C
80
+ : string;
81
+
82
+ /** Writable on purpose: tests point a module at a scratch directory by assignment. */
83
+ export type ModuleEnvValues<S extends ModuleEnvSpec> = {
84
+ -readonly [K in keyof S]: ModuleEnvValue<S[K]>;
85
+ };
86
+
87
+ /** A variable that fell back to its default, as the host reports it at boot. */
88
+ export interface ModuleEnvDefault {
89
+ name: string;
90
+ /** `unset`: absent from the environment. `invalid`: present, but unreadable as its kind. */
91
+ reason: 'unset' | 'invalid';
92
+ /** The value applied. A secret has no default: it is always the empty string here. */
93
+ value: string | number | boolean;
94
+ }
95
+
96
+ export const MODULE_ENV_NAME_PATTERN = /^[A-Z][A-Z0-9_]*$/;
97
+
98
+ const KINDS = new Set<string>(['int', 'text', 'path', 'url', 'flag', 'choice', 'secret']);
99
+
100
+ /** Identity, for inference: `choices` keep their literal types, values their kinds. */
101
+ export function defineModuleEnv<const S extends ModuleEnvSpec>(spec: S): S {
102
+ return spec;
103
+ }
104
+
105
+ /** What is wrong with a spec, or `null`. The host refuses to boot a module whose spec has a problem. */
106
+ export function moduleEnvProblem(spec: unknown): string | null {
107
+ if (typeof spec !== 'object' || spec === null) return 'the spec is not an object';
108
+ for (const [name, raw] of Object.entries(spec)) {
109
+ if (!MODULE_ENV_NAME_PATTERN.test(name)) return `${name}: not an environment variable name`;
110
+ const variable = raw as Partial<ModuleEnvVar> | null;
111
+ if (
112
+ typeof variable !== 'object' ||
113
+ variable === null ||
114
+ !KINDS.has(String(variable.kind))
115
+ ) {
116
+ return `${name}: unknown kind`;
117
+ }
118
+ if (
119
+ variable.kind === 'choice' &&
120
+ !(variable.choices ?? []).includes(variable.default as string)
121
+ ) {
122
+ return `${name}: the default is not one of the choices`;
123
+ }
124
+ }
125
+ return null;
126
+ }
127
+
128
+ /**
129
+ * One variable, read. `null` stands for "unreadable": the caller applies the
130
+ * default and reports it. An empty string is an explicit setting (the template
131
+ * ships blanks): it falls back to the default without a word, except for an
132
+ * address, where it means "none".
133
+ */
134
+ function parse(variable: ModuleEnvVar, raw: string): string | number | boolean | null {
135
+ const value = raw.trim();
136
+ switch (variable.kind) {
137
+ case 'int': {
138
+ if (value === '') return variable.default;
139
+ const n = Number(value);
140
+ return Number.isInteger(n) && n >= (variable.min ?? 1) ? n : null;
141
+ }
142
+ case 'text':
143
+ case 'path':
144
+ return value === '' ? variable.default : value;
145
+ case 'url':
146
+ if (value === '') return '';
147
+ return /^https?:\/\/\S+$/.test(value) ? value : null;
148
+ case 'flag': {
149
+ const word = value.toLowerCase();
150
+ if (word === '') return variable.default;
151
+ if (word === 'true' || word === '1') return true;
152
+ if (word === 'false' || word === '0') return false;
153
+ return null;
154
+ }
155
+ case 'choice':
156
+ if (value === '') return variable.default;
157
+ return variable.choices.includes(value) ? value : null;
158
+ case 'secret':
159
+ return value;
160
+ }
161
+ }
162
+
163
+ function fallbackOf(variable: ModuleEnvVar): string | number | boolean {
164
+ return variable.kind === 'secret' ? '' : variable.default;
165
+ }
166
+
167
+ /**
168
+ * Read a spec from `source` (the process environment by default). Every
169
+ * variable gets a value; `defaulted` lists those that fell back, except an
170
+ * `optional` one left unset.
171
+ */
172
+ export function readModuleEnv<S extends ModuleEnvSpec>(
173
+ spec: S,
174
+ source: Readonly<Record<string, string | undefined>> = process.env
175
+ ): { values: ModuleEnvValues<S>; defaulted: ModuleEnvDefault[] } {
176
+ const values: Record<string, string | number | boolean> = {};
177
+ const defaulted: ModuleEnvDefault[] = [];
178
+ for (const [name, variable] of Object.entries(spec)) {
179
+ const raw = source[name];
180
+ const parsed = raw === undefined ? null : parse(variable, raw);
181
+ if (parsed !== null) {
182
+ values[name] = parsed;
183
+ continue;
184
+ }
185
+ const fallback = fallbackOf(variable);
186
+ values[name] = fallback;
187
+ if (raw === undefined && variable.optional) continue;
188
+ defaulted.push({ name, reason: raw === undefined ? 'unset' : 'invalid', value: fallback });
189
+ }
190
+ return { values: values as ModuleEnvValues<S>, defaulted };
191
+ }
package/src/sdk/index.ts CHANGED
@@ -8,4 +8,5 @@
8
8
  */
9
9
  export * from './ids';
10
10
  export * from './manifest';
11
+ export * from './pageLook';
11
12
  export * from './providers';
@@ -159,6 +159,13 @@ test('validateManifest checks quotas and the account entry', () => {
159
159
  'duplicate quota key'
160
160
  );
161
161
  rejects({ quotas: [{ key: 'monitors', label: ' ' }] }, 'empty label');
162
+ assert.doesNotThrow(() =>
163
+ validateManifest({ ...base, quotas: [{ key: 'monitors', label: 'm', stock: true }] })
164
+ );
165
+ rejects(
166
+ { quotas: [{ key: 'storage', label: 'of storage', unit: 'bytes', stock: true }] },
167
+ 'a stock counts things'
168
+ );
162
169
  rejects({ accountOnly: true }, 'accountOnly requires accountEntry');
163
170
  rejects({ accountOnly: true, accountEntry: { label: 'S' }, tile: {} }, 'no tile');
164
171
  rejects({ accountEntry: { label: ' ' } }, 'requires a label');
@@ -74,6 +74,15 @@ export interface FeatureQuotaSpec {
74
74
  label: string;
75
75
  /** What the number counts. `bytes`: the host writes the limit as a size ("1 GB"). Default: things. */
76
76
  unit?: 'bytes';
77
+ /**
78
+ * Things that exist and cost while they exist (a probed monitor, a paired
79
+ * agent), as opposed to a flow checked at each use (events per month, the
80
+ * size of one file). When the limit drops below what exists, the host
81
+ * pauses the most recently created ones, never deletes them, and resumes
82
+ * them once the limit rises or a slot frees: see `SdkPlanPauses`. Requires
83
+ * `server.quotas[key]`; never with `unit: 'bytes'`.
84
+ */
85
+ stock?: true;
77
86
  }
78
87
 
79
88
  /** Hard cap on `extraPermissions`: keeps role editors legible. */
@@ -241,8 +250,10 @@ export interface FeatureManifest<Id extends FeatureId = FeatureId> {
241
250
  * WHEN the feature notifies, as the lead sentence of its Notifications tab.
242
251
  * Required with `notifies`: a tab that lists channels without saying what
243
252
  * reaches them leaves the user guessing why they would set one up.
253
+ * `perItem: false` when nothing is ever sent on behalf of an item: the
254
+ * item's settings then carry no Notifications tab that nothing would reach.
244
255
  */
245
- notifications?: { hint: string };
256
+ notifications?: { hint: string; perItem?: boolean };
246
257
  /**
247
258
  * The feature serves something under domain names the workspace owns (a
248
259
  * public page, a mailbox). Opens the Domains tab, which DevEye renders:
@@ -258,6 +269,14 @@ export interface FeatureManifest<Id extends FeatureId = FeatureId> {
258
269
  placeholder?: string;
259
270
  /** Warning of the removal confirm when items designate the domain. */
260
271
  removal?: string;
272
+ /**
273
+ * The names serve your public routes over HTTPS (a CNAME to
274
+ * `origins.public`). DevEye then checks by itself that a name points
275
+ * here and answers in HTTPS before calling your probe, hands it to its
276
+ * proxy for a certificate when the instance is wired for it, and
277
+ * counts it against the `domains.hosts` plan limit.
278
+ */
279
+ web?: boolean;
261
280
  };
262
281
  /**
263
282
  * Whether an item can be projected into another workspace. Decided by
@@ -443,6 +462,9 @@ export function validateManifest(m: FeatureManifest): void {
443
462
  if (quotaKeys.has(quota.key)) fail(m.id, `duplicate quota key « ${quota.key} »`);
444
463
  quotaKeys.add(quota.key);
445
464
  if (!quota.label.trim()) fail(m.id, `quota « ${quota.key} »: empty label`);
465
+ if (quota.stock && quota.unit === 'bytes') {
466
+ fail(m.id, `quota « ${quota.key} »: a stock counts things`);
467
+ }
446
468
  }
447
469
 
448
470
  if (m.accountEntry && !m.accountEntry.label.trim()) fail(m.id, 'accountEntry requires a label');
@@ -0,0 +1,26 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+
4
+ import { accentInk, accentSoft, pageAccentSchema, resolvePageAccent } from './pageLook';
5
+
6
+ test('an accent is an account colour, a #rrggbb, or none', () => {
7
+ assert.equal(resolvePageAccent('blue'), '#4da8ff');
8
+ assert.equal(resolvePageAccent(' #ABCDEF '), '#abcdef');
9
+ assert.equal(resolvePageAccent(''), null);
10
+ assert.equal(resolvePageAccent('#fff'), null);
11
+ assert.equal(resolvePageAccent('#000;}body{display:none'), null);
12
+ });
13
+
14
+ test('the schema keeps only what resolves, normalised', () => {
15
+ assert.equal(pageAccentSchema.parse(' Purple '), 'purple');
16
+ assert.equal(pageAccentSchema.parse('#A1B2C3'), '#a1b2c3');
17
+ assert.equal(pageAccentSchema.parse(''), '');
18
+ assert.equal(pageAccentSchema.safeParse('javascript:alert(1)').success, false);
19
+ });
20
+
21
+ test('the ink on an accent follows its luminance, its soft tone the theme', () => {
22
+ assert.equal(accentInk('#ffd54a'), '#10202e');
23
+ assert.equal(accentInk('#0f172a'), '#ffffff');
24
+ assert.equal(accentSoft('#b088ff', 'dark'), 'rgba(176, 136, 255, 0.22)');
25
+ assert.equal(accentSoft('#b088ff', 'light'), 'rgba(176, 136, 255, 0.14)');
26
+ });
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The look of a public page a module serves (a booking page, a public board): a
3
+ * theme and an accent colour. The pure half, shared by the server that renders
4
+ * the page and the settings that choose it. The page lives outside the app,
5
+ * often on a customer's domain, with none of the app's tokens: the colours are
6
+ * spelled out here.
7
+ */
8
+ import { z } from 'zod';
9
+
10
+ import type { UserColor } from '../domain/user';
11
+
12
+ /**
13
+ * DevEye's icon, a 64 px PNG the host serves at this path on every listener,
14
+ * so under every customer domain too: the tab icon of a public page that has
15
+ * none of its own (`<link rel="icon" href={DEVEYE_ICON_PATH}>`). A real address
16
+ * and not a data URL: link previews and crawlers fetch the icon, they never
17
+ * read one inlined. Allow `img-src 'self'` if your page sets a policy.
18
+ */
19
+ export const DEVEYE_ICON_PATH = '/deveye-icon.png';
20
+
21
+ export const PAGE_THEMES = ['light', 'dark'] as const;
22
+ export type PageTheme = (typeof PAGE_THEMES)[number];
23
+ /** `auto` follows the visitor's own light or dark setting. */
24
+ export type PageThemeChoice = PageTheme | 'auto';
25
+ export const pageThemeChoiceSchema = z.enum(['auto', ...PAGE_THEMES]);
26
+
27
+ /** The eight account colours, as the app's `--user-*` tokens spell them. */
28
+ export const PAGE_ACCENTS: Readonly<Record<UserColor, string>> = {
29
+ red: '#ff6b81',
30
+ orange: '#ff9f43',
31
+ yellow: '#ffd54a',
32
+ green: '#5ed17c',
33
+ blue: '#4da8ff',
34
+ indigo: '#7c8cff',
35
+ purple: '#b088ff',
36
+ pink: '#ff7ac6'
37
+ };
38
+
39
+ const HEX = /^#[0-9a-f]{6}$/;
40
+
41
+ /**
42
+ * An accent as a module stores it: an account colour's name, a `#rrggbb`, or
43
+ * the empty string for the page's own accent. Trimmed and lowercased.
44
+ */
45
+ export const pageAccentSchema = z
46
+ .string()
47
+ .trim()
48
+ .toLowerCase()
49
+ .refine((value) => value === '' || value in PAGE_ACCENTS || HEX.test(value), {
50
+ message: 'Une couleur de profil, un #rrggbb, ou rien.'
51
+ });
52
+
53
+ /** The `#rrggbb` an accent stands for, or `null` for the page's own. Anything unreadable counts as none. */
54
+ export function resolvePageAccent(raw: string): string | null {
55
+ const value = raw.trim().toLowerCase();
56
+ if (value in PAGE_ACCENTS) return PAGE_ACCENTS[value as UserColor];
57
+ return HEX.test(value) ? value : null;
58
+ }
59
+
60
+ function channels(hex: string): [number, number, number] {
61
+ return [
62
+ Number.parseInt(hex.slice(1, 3), 16),
63
+ Number.parseInt(hex.slice(3, 5), 16),
64
+ Number.parseInt(hex.slice(5, 7), 16)
65
+ ];
66
+ }
67
+
68
+ /**
69
+ * Dark or white text on this accent, by perceived luminance (the Rec. 709
70
+ * weights WCAG uses for contrast).
71
+ */
72
+ export function accentInk(hex: string): string {
73
+ const [r, g, b] = channels(hex);
74
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b > 140 ? '#10202e' : '#ffffff';
75
+ }
76
+
77
+ /** The quiet background of an accented surface: the same hue, almost transparent. */
78
+ export function accentSoft(hex: string, theme: PageTheme): string {
79
+ const [r, g, b] = channels(hex);
80
+ return `rgba(${r}, ${g}, ${b}, ${theme === 'dark' ? '0.22' : '0.14'})`;
81
+ }
@@ -447,6 +447,77 @@ export const UPTIME_CLIENT_PROVIDER = 'uptime.client' as const;
447
447
  */
448
448
  export const DEVICES_CLIENT_PROVIDER = 'devices.client' as const;
449
449
 
450
+ /**
451
+ * Key under `FeatureService.providers` for the money Invoicing already knows:
452
+ * the payments it recorded and the invoices still waiting for one. Offered by
453
+ * the Invoicing module, read by Finances, which mirrors the payments into its
454
+ * ledger instead of asking the user to type them twice. Absent module: the
455
+ * ledger stays manual.
456
+ */
457
+ export const INVOICING_LEDGER_PROVIDER = 'invoicing.ledger' as const;
458
+
459
+ /** One recorded payment. A payment is never edited, only removed: its fields are stable for its whole life. */
460
+ export interface InvoicingLedgerPayment {
461
+ paymentId: number;
462
+ docId: number;
463
+ /** `YYYY-MM-DD`. */
464
+ paidOn: string;
465
+ amountCents: number;
466
+ /** The payment's share of the invoice VAT, rounded like Invoicing's own dashboard. 0 under VAT exemption. */
467
+ vatCents: number;
468
+ method: 'transfer' | 'card' | 'cash' | 'check' | 'other';
469
+ /** The invoice's currency, ISO 4217. */
470
+ currency: string;
471
+ docNumber: string;
472
+ /** What `openFeature('invoicing', segment)` opens: the invoice's sheet. */
473
+ segment: string;
474
+ }
475
+
476
+ /** An issued invoice still waiting for money. */
477
+ export interface InvoicingLedgerReceivable {
478
+ docId: number;
479
+ docNumber: string;
480
+ /** From the client snapshot frozen at issue; empty when unreadable. */
481
+ clientName: string;
482
+ currency: string;
483
+ /** `YYYY-MM-DD`. */
484
+ issuedOn: string;
485
+ /** `YYYY-MM-DD`, or null when the invoice states no due date. */
486
+ dueOn: string | null;
487
+ remainingCents: number;
488
+ /** The VAT the remaining amount carries, pro rata of the invoice. 0 under VAT exemption. */
489
+ remainingVatCents: number;
490
+ overdue: boolean;
491
+ segment: string;
492
+ }
493
+
494
+ export interface InvoicingLedgerProvider {
495
+ /**
496
+ * An opaque value that changes whenever a payment of the workspace appears
497
+ * or disappears. One indexed query, no decryption: a consumer may call it
498
+ * on every read and skip the rest while it holds still.
499
+ */
500
+ version(workspaceId: number): Promise<string>;
501
+ /** Payments received on or after `from` (every payment when null), oldest first. No decryption. */
502
+ payments(workspaceId: number, from: string | null): Promise<readonly InvoicingLedgerPayment[]>;
503
+ /** Client names from the invoices' frozen snapshots, `''` when unreadable. Decrypts: ask only for what you store. */
504
+ clientNames(
505
+ workspaceId: number,
506
+ docIds: readonly number[]
507
+ ): Promise<ReadonlyMap<number, string>>;
508
+ /** Issued invoices still waiting for money, earliest due first. */
509
+ receivables(workspaceId: number): Promise<readonly InvoicingLedgerReceivable[]>;
510
+ /** What Invoicing settles for the workspace; a consumer follows it rather than keeping a copy. */
511
+ profile(workspaceId: number): Promise<{ currency: string; vatRegime: 'standard' | 'exempt' }>;
512
+ }
513
+
514
+ /**
515
+ * Key under `FeatureClient.providers` for what Invoicing lets another screen
516
+ * do in the user's name: record a payment the user recognised elsewhere (a
517
+ * bank line in Finances). The contract type lives in `@deveye/types/sdk/client`.
518
+ */
519
+ export const INVOICING_CLIENT_PROVIDER = 'invoicing.client' as const;
520
+
450
521
  /**
451
522
  * Key under `FeatureService.providers` for what Sentinel contributes to the
452
523
  * collection config the app pushes to an agent (`agent.config`): whether the
@@ -480,6 +551,11 @@ export interface SentinelAgentConfigProvider {
480
551
  * The plan of an account: what bounds the quotas modules declare
481
552
  * (`manifest.quotas`). Offered by a billing module. WITHOUT it every quota is
482
553
  * unlimited, which is what a self-hosted DevEye is.
554
+ *
555
+ * The provider calls `live.accountChanged(userId)` after every change it
556
+ * learns of by an event (a payment, a grant): that is when the host re-applies
557
+ * the `stock` limits. A change that comes with time alone is announced by
558
+ * `changesAt` instead.
483
559
  */
484
560
  export const ACCOUNT_PLAN_PROVIDER = 'account.plan';
485
561
 
@@ -490,8 +566,14 @@ export interface AccountPlan {
490
566
  limits: Readonly<Record<string, number>>;
491
567
  /** The plan is a trial ending then (ms since the epoch). */
492
568
  trialEndsAt?: number;
569
+ /**
570
+ * This answer changes by itself then, with no event to announce it (a
571
+ * trial or a grant ending), in ms since the epoch: the host asks again.
572
+ */
573
+ changesAt?: number;
493
574
  }
494
575
 
495
576
  export interface AccountPlanProvider {
496
- planFor(userId: number): Promise<AccountPlan>;
577
+ /** `fresh`: never from a cache, the host is about to pause or resume on the answer. */
578
+ planFor(userId: number, opts?: { fresh?: boolean }): Promise<AccountPlan>;
497
579
  }