adula 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +1 -1
  2. package/build/agent/capabilities.md +2 -3
  3. package/build/agent/skills/adula-frontend-design/SKILL.md +5 -3
  4. package/build/commands/adula_assistant_prune.d.ts +10 -0
  5. package/build/commands/adula_assistant_prune.js +12 -0
  6. package/build/commands/backup_open.d.ts +16 -0
  7. package/build/commands/backup_open.js +48 -0
  8. package/build/commands/backup_restore_test.js +3 -0
  9. package/build/commands/backup_seal.d.ts +12 -0
  10. package/build/commands/backup_seal.js +36 -0
  11. package/build/commands/backup_services.d.ts +3 -1
  12. package/build/commands/doctor.js +18 -1
  13. package/build/commands/install.js +6 -0
  14. package/build/commands/main.d.ts +2 -2
  15. package/build/commands/main.js +6 -0
  16. package/build/commands/resource_migration.js +12 -3
  17. package/build/commands/resource_snapshot.js +18 -4
  18. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  19. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  20. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  21. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  22. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  23. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  24. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  25. package/build/database/migrations/1770000000056_appearance.js +10 -0
  26. package/build/index.d.ts +36 -6
  27. package/build/index.js +18 -3
  28. package/build/src/admin/controller.js +18 -4
  29. package/build/src/admin/resource/editor.d.ts +1 -0
  30. package/build/src/admin/resource/editor.js +26 -4
  31. package/build/src/admin/resource/export.d.ts +21 -4
  32. package/build/src/admin/resource/export.js +117 -36
  33. package/build/src/admin/resource/lifecycle.d.ts +2 -0
  34. package/build/src/admin/resource/query.d.ts +14 -3
  35. package/build/src/admin/resource/query.js +98 -11
  36. package/build/src/admin/resource/read.d.ts +3 -0
  37. package/build/src/admin/resource/read.js +75 -14
  38. package/build/src/admin/resource/shared.d.ts +16 -0
  39. package/build/src/admin/resource/shared.js +47 -4
  40. package/build/src/admin/resource/write.js +37 -8
  41. package/build/src/admin/resource_service.d.ts +17 -3
  42. package/build/src/admin/resource_service.js +16 -2
  43. package/build/src/admin/resource_tools.d.ts +111 -0
  44. package/build/src/admin/resource_tools.js +139 -0
  45. package/build/src/ai/assistant.d.ts +100 -0
  46. package/build/src/ai/assistant.js +487 -0
  47. package/build/src/ai/client.d.ts +49 -0
  48. package/build/src/ai/client.js +85 -0
  49. package/build/src/ai/prompt.d.ts +23 -0
  50. package/build/src/ai/prompt.js +83 -0
  51. package/build/src/ai/settings.d.ts +56 -0
  52. package/build/src/ai/settings.js +214 -0
  53. package/build/src/ai/usage.d.ts +16 -0
  54. package/build/src/ai/usage.js +33 -0
  55. package/build/src/appearance/appearance.d.ts +134 -0
  56. package/build/src/appearance/appearance.js +461 -0
  57. package/build/src/appearance/colors.d.ts +43 -0
  58. package/build/src/appearance/colors.js +99 -0
  59. package/build/src/appearance/logo.d.ts +32 -0
  60. package/build/src/appearance/logo.js +112 -0
  61. package/build/src/auth/actor_store.d.ts +5 -1
  62. package/build/src/auth/actor_store.js +8 -4
  63. package/build/src/backups/archive.d.ts +52 -0
  64. package/build/src/backups/archive.js +362 -0
  65. package/build/src/backups/cloud_backups.d.ts +133 -0
  66. package/build/src/backups/cloud_backups.js +650 -0
  67. package/build/src/backups/doctor.d.ts +7 -0
  68. package/build/src/backups/doctor.js +55 -0
  69. package/build/src/backups/providers.d.ts +81 -0
  70. package/build/src/backups/providers.js +470 -0
  71. package/build/src/collaboration/assignments.d.ts +24 -2
  72. package/build/src/collaboration/assignments.js +88 -32
  73. package/build/src/collaboration/record_collaboration.d.ts +19 -1
  74. package/build/src/collaboration/record_collaboration.js +109 -37
  75. package/build/src/collaboration/shared.d.ts +10 -2
  76. package/build/src/collaboration/shared.js +14 -1
  77. package/build/src/commands/capabilities.js +1 -1
  78. package/build/src/commands/doctor.d.ts +10 -0
  79. package/build/src/commands/doctor.js +31 -1
  80. package/build/src/commands/snapshot.d.ts +14 -0
  81. package/build/src/commands/snapshot.js +23 -0
  82. package/build/src/core/administrators.js +19 -3
  83. package/build/src/core/avatar_image.d.ts +33 -0
  84. package/build/src/core/avatar_image.js +278 -0
  85. package/build/src/core/mail_settings.d.ts +83 -0
  86. package/build/src/core/mail_settings.js +274 -0
  87. package/build/src/core/mail_test.d.ts +16 -0
  88. package/build/src/core/mail_test.js +81 -6
  89. package/build/src/core/message_templates.d.ts +8 -0
  90. package/build/src/core/message_templates.js +12 -3
  91. package/build/src/core/roles.js +24 -7
  92. package/build/src/core/saved_views.js +55 -24
  93. package/build/src/core/settings.d.ts +2 -2
  94. package/build/src/core/settings.js +15 -4
  95. package/build/src/core/ui_preferences.d.ts +6 -0
  96. package/build/src/core/ui_preferences.js +12 -1
  97. package/build/src/core/user_avatars.d.ts +79 -0
  98. package/build/src/core/user_avatars.js +186 -0
  99. package/build/src/core/user_preferences.d.ts +36 -0
  100. package/build/src/core/user_preferences.js +125 -0
  101. package/build/src/core/users.d.ts +2 -0
  102. package/build/src/core/users.js +4 -2
  103. package/build/src/database/schema.d.ts +46 -0
  104. package/build/src/database/schema.js +182 -0
  105. package/build/src/database/schema_diff.d.ts +16 -2
  106. package/build/src/database/schema_diff.js +40 -7
  107. package/build/src/integrations/api_client.js +18 -3
  108. package/build/src/integrations/imports.d.ts +16 -4
  109. package/build/src/integrations/imports.js +36 -8
  110. package/build/src/integrations/openapi.js +15 -4
  111. package/build/src/integrations/outbound.d.ts +43 -0
  112. package/build/src/integrations/outbound.js +98 -17
  113. package/build/src/integrations/print.d.ts +2 -1
  114. package/build/src/integrations/print.js +7 -3
  115. package/build/src/integrations/print_templates.js +3 -1
  116. package/build/src/integrations/xlsx.d.ts +41 -0
  117. package/build/src/integrations/xlsx.js +519 -0
  118. package/build/src/languages/ar.js +22 -0
  119. package/build/src/languages/ar_ui.d.ts +143 -14
  120. package/build/src/languages/ar_ui.js +145 -14
  121. package/build/src/languages/en.js +22 -0
  122. package/build/src/languages/en_ui.js +144 -14
  123. package/build/src/lists/dashboards.d.ts +42 -0
  124. package/build/src/lists/dashboards.js +49 -0
  125. package/build/src/mcp/tools.js +9 -104
  126. package/build/src/resource/define_resource.js +7 -0
  127. package/build/src/resource/types.d.ts +9 -0
  128. package/build/src/workflows/delegations.d.ts +15 -1
  129. package/build/src/workflows/delegations.js +49 -10
  130. package/build/src/workflows/engine.d.ts +11 -0
  131. package/build/src/workflows/engine.js +29 -7
  132. package/package.json +5 -1
@@ -0,0 +1,461 @@
1
+ import { AdulaError } from '../admin/errors.js';
2
+ import { logActivity } from '../core/activity.js';
3
+ import { registerUpload, isAttachmentId } from '../attachments/attachment_service.js';
4
+ import { derivePrimaryTheme, normalizeColor } from './colors.js';
5
+ /**
6
+ * Appearance and occasion themes (ADR 053). The base identity is one system setting; dated
7
+ * occasions live in `appearance_occasions`; logos are `attachments` rows bound to this owner,
8
+ * so backups and storage migration carry them like profile pictures (ADR 050). Nothing is
9
+ * scheduled: `resolve()` picks the active occasion for today's date in the system time zone,
10
+ * so the base identity returns by itself the day after an occasion ends.
11
+ */
12
+ export const APPEARANCE_SETTING_KEY = 'appearance.identity';
13
+ export const APPEARANCE_LOGO_OWNER = Object.freeze({ resource: 'core_appearance', field: 'logo' });
14
+ /** The `record_id` of the base identity's logo; occasions use their own id. */
15
+ export const BASE_LOGO_RECORD = 0;
16
+ const RESOURCE = 'core.appearance';
17
+ const CACHE_MS = 30_000;
18
+ export const APPEARANCE_TEXT_LIMITS = Object.freeze({
19
+ company: 120,
20
+ loginTitle: 120,
21
+ loginDescription: 300,
22
+ guestTitle: 120,
23
+ guestDescription: 300,
24
+ name: 80,
25
+ banner: 160,
26
+ });
27
+ const EMPTY_IDENTITY = {
28
+ company: null,
29
+ logoId: null,
30
+ loginTitle: null,
31
+ loginDescription: null,
32
+ guestTitle: null,
33
+ guestDescription: null,
34
+ primaryColor: null,
35
+ };
36
+ const IDENTITY_TEXTS = [
37
+ 'company',
38
+ 'loginTitle',
39
+ 'loginDescription',
40
+ 'guestTitle',
41
+ 'guestDescription',
42
+ ];
43
+ const OCCASION_TEXTS = ['name', 'banner', 'loginTitle', 'loginDescription'];
44
+ const invalid = (message) => new AdulaError(422, 'E_APPEARANCE_INPUT', message);
45
+ /** Plain text on one line: trimmed, bounded, no control characters; empty is null. */
46
+ function plainText(value, limit, label) {
47
+ if (value === undefined || value === null)
48
+ return null;
49
+ if (typeof value !== 'string')
50
+ throw invalid(`${label} يجب أن يكون نصًا`);
51
+ const text = value.trim();
52
+ if (!text)
53
+ return null;
54
+ // C0/C1 controls, the line and paragraph separators and the bidi embeddings, overrides
55
+ // and isolates, which could reorder the text around them on a page.
56
+ // eslint-disable-next-line no-control-regex
57
+ if (/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/.test(text))
58
+ throw invalid(`${label} يجب أن يكون سطرًا واحدًا دون رموز تحكم`);
59
+ if ([...text].length > limit)
60
+ throw invalid(`${label} لا يتجاوز ${limit} حرفًا`);
61
+ return text;
62
+ }
63
+ const LABELS = {
64
+ company: 'اسم الشركة',
65
+ loginTitle: 'عنوان صفحة الدخول',
66
+ loginDescription: 'وصف صفحة الدخول',
67
+ guestTitle: 'عنوان الصفحة الرئيسية للزوار',
68
+ guestDescription: 'وصف الصفحة الرئيسية للزوار',
69
+ name: 'اسم المناسبة',
70
+ banner: 'رسالة المناسبة',
71
+ };
72
+ function colorOf(value) {
73
+ if (value === undefined || value === null || value === '')
74
+ return null;
75
+ const color = normalizeColor(value);
76
+ if (!color)
77
+ throw invalid('اكتب اللون بالصيغة ‎#RRGGBB‎');
78
+ // Refused here, with the Arabic reason, when either theme misses WCAG AA.
79
+ derivePrimaryTheme(color);
80
+ return color;
81
+ }
82
+ function logoIdOf(value) {
83
+ if (value === undefined || value === null || value === '')
84
+ return null;
85
+ const id = Number(value);
86
+ if (!isAttachmentId(id))
87
+ throw invalid('الشعار غير صالح');
88
+ return id;
89
+ }
90
+ /** A real calendar date written as YYYY-MM-DD. */
91
+ function dateOf(value, label) {
92
+ const text = typeof value === 'string' ? value.trim() : '';
93
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
94
+ const date = match ? new Date(Date.UTC(+match[1], +match[2] - 1, +match[3])) : null;
95
+ if (!date || date.toISOString().slice(0, 10) !== text)
96
+ throw invalid(`${label} غير صالح`);
97
+ return text;
98
+ }
99
+ function only(input, allowed) {
100
+ if (!input || typeof input !== 'object' || Array.isArray(input))
101
+ throw invalid('بيانات المظهر غير صالحة');
102
+ const data = input;
103
+ if (Object.keys(data).some((key) => !allowed.includes(key)))
104
+ throw invalid('حقل غير معروف في إعداد المظهر');
105
+ return data;
106
+ }
107
+ /** Today's date (YYYY-MM-DD) in a time zone. */
108
+ export function dateIn(timeZone, now) {
109
+ return new Intl.DateTimeFormat('en-CA', {
110
+ timeZone,
111
+ year: 'numeric',
112
+ month: '2-digit',
113
+ day: '2-digit',
114
+ }).format(now);
115
+ }
116
+ const OCCASION_COLUMNS = [
117
+ 'id',
118
+ 'name',
119
+ 'primary_color',
120
+ 'logo_id',
121
+ 'banner',
122
+ 'login_title',
123
+ 'login_description',
124
+ ];
125
+ function occasionOf(row) {
126
+ return {
127
+ id: Number(row.id),
128
+ name: String(row.name),
129
+ startsOn: String(row.starts_on),
130
+ endsOn: String(row.ends_on),
131
+ primaryColor: row.primary_color ?? null,
132
+ logoId: row.logo_id === null || row.logo_id === undefined ? null : Number(row.logo_id),
133
+ banner: row.banner ?? null,
134
+ loginTitle: row.login_title ?? null,
135
+ loginDescription: row.login_description ?? null,
136
+ };
137
+ }
138
+ export class Appearance {
139
+ db;
140
+ options;
141
+ /** The current time; tests replace it to move between and past occasions. */
142
+ clock;
143
+ #cache = null;
144
+ constructor(db, options) {
145
+ this.db = db;
146
+ this.options = options;
147
+ this.clock = options.now ?? (() => new Date());
148
+ }
149
+ /** Drops the cached result, for a change made outside this service (tests, restores). */
150
+ forget() {
151
+ this.#cache = null;
152
+ }
153
+ /** Today in the system time zone; an occasion's dates are read in the same zone. */
154
+ today() {
155
+ return dateIn(this.options.timeZone, this.clock());
156
+ }
157
+ async identity() {
158
+ const row = await this.db('settings')
159
+ .where({ key: APPEARANCE_SETTING_KEY, scope: 'system', scope_id: '0' })
160
+ .first('value');
161
+ const value = (row?.value ?? {});
162
+ const identity = { ...EMPTY_IDENTITY };
163
+ for (const key of IDENTITY_TEXTS)
164
+ identity[key] = typeof value[key] === 'string' ? value[key] : null;
165
+ identity.logoId = isAttachmentId(Number(value.logoId)) ? Number(value.logoId) : null;
166
+ identity.primaryColor = normalizeColor(value.primaryColor);
167
+ return identity;
168
+ }
169
+ /** Replaces the base identity. A changed logo retires the previous one. */
170
+ async saveIdentity(actor, input) {
171
+ const data = only(input, [...IDENTITY_TEXTS, 'logoId', 'primaryColor']);
172
+ const next = { ...EMPTY_IDENTITY };
173
+ for (const key of IDENTITY_TEXTS)
174
+ next[key] = plainText(data[key], APPEARANCE_TEXT_LIMITS[key], LABELS[key]);
175
+ next.primaryColor = colorOf(data.primaryColor);
176
+ next.logoId = logoIdOf(data.logoId);
177
+ const removed = await this.db.transaction(async (trx) => {
178
+ await this.#lockSettings(trx);
179
+ const previous = await this.identity();
180
+ const files = await this.#bindLogo(trx, next.logoId, BASE_LOGO_RECORD);
181
+ await trx('settings')
182
+ .insert({
183
+ key: APPEARANCE_SETTING_KEY,
184
+ scope: 'system',
185
+ scope_id: '0',
186
+ value: JSON.stringify(next),
187
+ })
188
+ .onConflict(['key', 'scope', 'scope_id'])
189
+ .merge(['value']);
190
+ await this.#log(trx, actor, BASE_LOGO_RECORD, 'identity.update', {
191
+ changed: Object.keys(next).filter((key) => next[key] !== previous[key]),
192
+ primaryColor: next.primaryColor,
193
+ logoId: next.logoId,
194
+ });
195
+ return files;
196
+ });
197
+ this.#cache = null;
198
+ return { identity: await this.identity(), removed };
199
+ }
200
+ /** «استعادة الافتراضي»: removes the saved identity and its logo; occasions stay. */
201
+ async resetIdentity(actor) {
202
+ const removed = await this.db.transaction(async (trx) => {
203
+ await this.#lockSettings(trx);
204
+ const files = await this.#bindLogo(trx, null, BASE_LOGO_RECORD);
205
+ await trx('settings')
206
+ .where({ key: APPEARANCE_SETTING_KEY, scope: 'system', scope_id: '0' })
207
+ .delete();
208
+ await this.#log(trx, actor, BASE_LOGO_RECORD, 'identity.reset', {});
209
+ return files;
210
+ });
211
+ this.#cache = null;
212
+ return removed;
213
+ }
214
+ async occasions() {
215
+ const rows = await this.#occasionQuery(this.db).orderBy('starts_on', 'desc');
216
+ return rows.map(occasionOf);
217
+ }
218
+ async occasion(id) {
219
+ if (!isAttachmentId(id))
220
+ return null;
221
+ const row = await this.#occasionQuery(this.db).where('id', id).first();
222
+ return row ? occasionOf(row) : null;
223
+ }
224
+ /** Creates (no id) or updates an occasion; a date range that overlaps another is refused. */
225
+ async saveOccasion(actor, input, id) {
226
+ const data = only(input, [...OCCASION_TEXTS, 'startsOn', 'endsOn', 'primaryColor', 'logoId']);
227
+ const name = plainText(data.name, APPEARANCE_TEXT_LIMITS.name, LABELS.name);
228
+ if (!name)
229
+ throw invalid('اكتب اسم المناسبة');
230
+ const startsOn = dateOf(data.startsOn, 'تاريخ البداية');
231
+ const endsOn = dateOf(data.endsOn, 'تاريخ النهاية');
232
+ if (endsOn < startsOn)
233
+ throw invalid('تاريخ النهاية يجب ألا يسبق تاريخ البداية');
234
+ const values = {
235
+ name,
236
+ starts_on: startsOn,
237
+ ends_on: endsOn,
238
+ primary_color: colorOf(data.primaryColor),
239
+ logo_id: logoIdOf(data.logoId),
240
+ banner: plainText(data.banner, APPEARANCE_TEXT_LIMITS.banner, LABELS.banner),
241
+ login_title: plainText(data.loginTitle, APPEARANCE_TEXT_LIMITS.loginTitle, LABELS.loginTitle),
242
+ login_description: plainText(data.loginDescription, APPEARANCE_TEXT_LIMITS.loginDescription, LABELS.loginDescription),
243
+ };
244
+ if (!values.primary_color &&
245
+ !values.logo_id &&
246
+ !values.banner &&
247
+ !values.login_title &&
248
+ !values.login_description)
249
+ throw invalid('اختر تغييرًا واحدًا على الأقل للمناسبة: اللون أو الشعار أو الرسالة أو نصوص الدخول');
250
+ const result = await this.db.transaction(async (trx) => {
251
+ // One writer at a time, so two overlapping occasions cannot both pass the check.
252
+ await trx.raw('LOCK TABLE appearance_occasions IN SHARE ROW EXCLUSIVE MODE');
253
+ if (id !== undefined) {
254
+ const existing = await trx('appearance_occasions').where('id', id).first('id');
255
+ if (!existing)
256
+ throw new AdulaError(404, 'E_NOT_FOUND', 'المناسبة غير موجودة');
257
+ }
258
+ const overlapping = await this.#occasionQuery(trx)
259
+ .where('starts_on', '<=', endsOn)
260
+ .where('ends_on', '>=', startsOn)
261
+ .modify((query) => {
262
+ if (id !== undefined)
263
+ query.whereNot('id', id);
264
+ })
265
+ .first();
266
+ if (overlapping) {
267
+ const other = occasionOf(overlapping);
268
+ throw new AdulaError(409, 'E_APPEARANCE_OVERLAP', `تتداخل الفترة مع مناسبة «${other.name}» (${other.startsOn} – ${other.endsOn}). لا تنشط إلا مناسبة واحدة في كل يوم.`);
269
+ }
270
+ let saved;
271
+ if (id === undefined) {
272
+ const [row] = await trx('appearance_occasions')
273
+ .insert({ ...values, created_by: actor.id, updated_by: actor.id })
274
+ .returning('id');
275
+ saved = Number(row.id ?? row);
276
+ }
277
+ else {
278
+ await trx('appearance_occasions')
279
+ .where('id', id)
280
+ .update({ ...values, updated_by: actor.id, updated_at: trx.fn.now() });
281
+ saved = id;
282
+ }
283
+ const files = await this.#bindLogo(trx, values.logo_id, saved);
284
+ await this.#log(trx, actor, saved, id === undefined ? 'occasion.create' : 'occasion.update', {
285
+ name,
286
+ startsOn,
287
+ endsOn,
288
+ primaryColor: values.primary_color,
289
+ logoId: values.logo_id,
290
+ banner: values.banner !== null,
291
+ });
292
+ return { id: saved, files };
293
+ });
294
+ this.#cache = null;
295
+ return { occasion: (await this.occasion(result.id)), removed: result.files };
296
+ }
297
+ async deleteOccasion(actor, id) {
298
+ if (!isAttachmentId(id))
299
+ throw new AdulaError(404, 'E_NOT_FOUND', 'المناسبة غير موجودة');
300
+ const removed = await this.db.transaction(async (trx) => {
301
+ const row = await trx('appearance_occasions').where('id', id).forUpdate().first('id', 'name');
302
+ if (!row)
303
+ throw new AdulaError(404, 'E_NOT_FOUND', 'المناسبة غير موجودة');
304
+ const files = await this.#bindLogo(trx, null, id);
305
+ await trx('appearance_occasions').where('id', id).delete();
306
+ await this.#log(trx, actor, id, 'occasion.delete', { name: row.name });
307
+ return files;
308
+ });
309
+ this.#cache = null;
310
+ return removed;
311
+ }
312
+ /**
313
+ * Records a stored, prepared logo as an unbound upload. It becomes the identity's or an
314
+ * occasion's logo only when that is saved; an abandoned upload is pruned like any other.
315
+ */
316
+ async registerLogo(actor, file) {
317
+ return this.db.transaction(async (trx) => {
318
+ const row = await registerUpload(trx, {
319
+ disk: file.disk,
320
+ path: file.path,
321
+ name: file.path.split('/').at(-1) ?? '',
322
+ originalName: `logo.${file.image.extname}`,
323
+ size: file.image.bytes.length,
324
+ mimeType: file.image.mimeType,
325
+ extname: file.image.extname,
326
+ data: { width: file.image.width, height: file.image.height },
327
+ uploadedBy: actor.id,
328
+ impersonatorId: actor.impersonatorId,
329
+ resource: APPEARANCE_LOGO_OWNER.resource,
330
+ field: APPEARANCE_LOGO_OWNER.field,
331
+ });
332
+ await this.#log(trx, actor, BASE_LOGO_RECORD, 'logo.upload', {
333
+ logoId: row.id,
334
+ width: file.image.width,
335
+ height: file.image.height,
336
+ });
337
+ return (await this.logo(row.id, trx));
338
+ });
339
+ }
340
+ /** A live appearance logo; any other attachment id is unknown here. */
341
+ async logo(id, db = this.db, lock = false) {
342
+ if (!isAttachmentId(id))
343
+ return null;
344
+ const query = db('attachments')
345
+ .where({
346
+ id,
347
+ resource: APPEARANCE_LOGO_OWNER.resource,
348
+ field: APPEARANCE_LOGO_OWNER.field,
349
+ })
350
+ .whereNull('deleted_at');
351
+ // Binding locks the row, so an identity save and an occasion save that race for the same
352
+ // upload see each other's binding instead of both claiming it.
353
+ if (lock)
354
+ query.forUpdate();
355
+ const row = await query.first('id', 'disk', 'path', 'mime_type', 'size', 'record_id');
356
+ if (!row)
357
+ return null;
358
+ return {
359
+ id: Number(row.id),
360
+ disk: String(row.disk),
361
+ path: String(row.path),
362
+ mimeType: String(row.mime_type),
363
+ size: Number(row.size),
364
+ recordId: row.record_id === null ? null : Number(row.record_id),
365
+ };
366
+ }
367
+ /**
368
+ * The appearance for this request: the base identity, overridden by the occasion whose
369
+ * dates include today. Cached for 30 seconds per date and cleared by every change here.
370
+ */
371
+ async resolve() {
372
+ const today = this.today();
373
+ const now = Date.now();
374
+ const ttl = this.options.cacheMs ?? CACHE_MS;
375
+ if (this.#cache && this.#cache.key === today && now - this.#cache.at < ttl)
376
+ return this.#cache.value;
377
+ const identity = await this.identity();
378
+ const row = await this.#occasionQuery(this.db)
379
+ .where('starts_on', '<=', today)
380
+ .where('ends_on', '>=', today)
381
+ .orderBy('starts_on', 'desc')
382
+ .first();
383
+ const occasion = row ? occasionOf(row) : null;
384
+ const color = occasion?.primaryColor ?? identity.primaryColor;
385
+ const value = {
386
+ company: identity.company,
387
+ logoId: occasion?.logoId ?? identity.logoId,
388
+ login: {
389
+ title: occasion?.loginTitle ?? identity.loginTitle,
390
+ description: occasion?.loginDescription ?? identity.loginDescription,
391
+ },
392
+ guestHome: { title: identity.guestTitle, description: identity.guestDescription },
393
+ banner: occasion?.banner ?? null,
394
+ occasion: occasion
395
+ ? {
396
+ id: occasion.id,
397
+ name: occasion.name,
398
+ startsOn: occasion.startsOn,
399
+ endsOn: occasion.endsOn,
400
+ }
401
+ : null,
402
+ // A stored colour passed the check when it was saved; a failing one is ignored.
403
+ theme: color ? safeTheme(color) : null,
404
+ };
405
+ this.#cache = { key: today, at: now, value };
406
+ return value;
407
+ }
408
+ #occasionQuery(db) {
409
+ return db('appearance_occasions').select(...OCCASION_COLUMNS, db.raw(`to_char(starts_on, 'YYYY-MM-DD') as starts_on`), db.raw(`to_char(ends_on, 'YYYY-MM-DD') as ends_on`));
410
+ }
411
+ async #lockSettings(trx) {
412
+ // Serialises identity changes; the advisory lock is released with the transaction.
413
+ await trx.raw('SELECT pg_advisory_xact_lock(hashtext(?))', [APPEARANCE_SETTING_KEY]);
414
+ }
415
+ /**
416
+ * Binds `logoId` to `recordId` and removes that record's other logos. The logo must be an
417
+ * appearance upload that is unbound or already bound to the same record.
418
+ */
419
+ async #bindLogo(trx, logoId, recordId) {
420
+ if (logoId !== null) {
421
+ const logo = await this.logo(logoId, trx, true);
422
+ if (!logo || (logo.recordId !== null && logo.recordId !== recordId))
423
+ throw invalid('الشعار غير موجود. ارفعه مرة أخرى.');
424
+ await trx('attachments').where('id', logoId).update({ record_id: recordId });
425
+ }
426
+ const previous = trx('attachments')
427
+ .where({
428
+ resource: APPEARANCE_LOGO_OWNER.resource,
429
+ field: APPEARANCE_LOGO_OWNER.field,
430
+ record_id: recordId,
431
+ })
432
+ .whereNull('deleted_at');
433
+ if (logoId !== null)
434
+ previous.whereNot('id', logoId);
435
+ const rows = await previous.select('id', 'disk', 'path');
436
+ if (!rows.length)
437
+ return [];
438
+ await trx('attachments')
439
+ .whereIn('id', rows.map((row) => Number(row.id)))
440
+ .delete();
441
+ return rows.map((row) => ({ disk: String(row.disk), path: String(row.path) }));
442
+ }
443
+ #log(trx, actor, recordId, action, changes) {
444
+ return logActivity(trx, {
445
+ resource: RESOURCE,
446
+ recordId,
447
+ actorId: actor.id,
448
+ impersonatorId: actor.impersonatorId,
449
+ action,
450
+ changes,
451
+ });
452
+ }
453
+ }
454
+ function safeTheme(color) {
455
+ try {
456
+ return derivePrimaryTheme(color);
457
+ }
458
+ catch {
459
+ return null;
460
+ }
461
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Primary colour checks for the appearance settings (ADR 053). An administrator picks one
3
+ * colour; the light theme uses it as is and the dark theme uses a lighter tint of it. Both
4
+ * must reach WCAG AA (4.5:1) for normal text: the colour as text on the page background
5
+ * (links, the active navigation item) and the foreground on the colour (primary buttons).
6
+ * Only `#rrggbb` values are accepted, so no CSS other than a colour ever reaches a page.
7
+ */
8
+ export declare const WCAG_AA = 4.5;
9
+ /** The shipped theme backgrounds (`--background`): white and oklch(0.145 0 0). */
10
+ export declare const LIGHT_BACKGROUND = "#ffffff";
11
+ export declare const DARK_BACKGROUND = "#0a0a0a";
12
+ export type ThemeColors = {
13
+ '--primary': string;
14
+ '--primary-foreground': string;
15
+ };
16
+ export type DerivedTheme = {
17
+ light: ThemeColors;
18
+ dark: ThemeColors;
19
+ };
20
+ /** `#RRGGBB` or `#rrggbb` as lowercase `#rrggbb`; anything else is null. */
21
+ export declare function normalizeColor(value: unknown): string | null;
22
+ /** WCAG 2.x relative luminance of an sRGB colour. */
23
+ export declare function luminance(hex: string): number;
24
+ /** The WCAG contrast ratio of two colours, from 1 to 21. */
25
+ export declare function contrast(first: string, second: string): number;
26
+ /** Rounds down to two decimals, so a ratio shown as 4.5 really reaches 4.5. */
27
+ export declare const ratio: (value: number) => number;
28
+ export type ContrastCheck = {
29
+ ok: true;
30
+ theme: DerivedTheme;
31
+ } | {
32
+ ok: false;
33
+ reason: string;
34
+ light: number;
35
+ dark: number;
36
+ };
37
+ /**
38
+ * Derives both themes from one colour and checks them. The dark tint is the colour mixed
39
+ * with white in 5% steps until it reaches AA on the dark background.
40
+ */
41
+ export declare function checkPrimaryColor(value: unknown): ContrastCheck;
42
+ /** The derived themes of a colour, or a 422 with the Arabic reason. */
43
+ export declare function derivePrimaryTheme(value: unknown): DerivedTheme;
@@ -0,0 +1,99 @@
1
+ import { AdulaError } from '../admin/errors.js';
2
+ /**
3
+ * Primary colour checks for the appearance settings (ADR 053). An administrator picks one
4
+ * colour; the light theme uses it as is and the dark theme uses a lighter tint of it. Both
5
+ * must reach WCAG AA (4.5:1) for normal text: the colour as text on the page background
6
+ * (links, the active navigation item) and the foreground on the colour (primary buttons).
7
+ * Only `#rrggbb` values are accepted, so no CSS other than a colour ever reaches a page.
8
+ */
9
+ export const WCAG_AA = 4.5;
10
+ /** The shipped theme backgrounds (`--background`): white and oklch(0.145 0 0). */
11
+ export const LIGHT_BACKGROUND = '#ffffff';
12
+ export const DARK_BACKGROUND = '#0a0a0a';
13
+ const LIGHT_TEXT = '#ffffff';
14
+ const DARK_TEXT = '#0a0a0a';
15
+ const HEX = /^#[0-9a-f]{6}$/;
16
+ /** `#RRGGBB` or `#rrggbb` as lowercase `#rrggbb`; anything else is null. */
17
+ export function normalizeColor(value) {
18
+ if (typeof value !== 'string')
19
+ return null;
20
+ const color = value.trim().toLowerCase();
21
+ return HEX.test(color) ? color : null;
22
+ }
23
+ function channels(hex) {
24
+ return [1, 3, 5].map((start) => Number.parseInt(hex.slice(start, start + 2), 16));
25
+ }
26
+ /** WCAG 2.x relative luminance of an sRGB colour. */
27
+ export function luminance(hex) {
28
+ const [r, g, b] = channels(hex).map((value) => {
29
+ const c = value / 255;
30
+ return c <= 0.040_45 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
31
+ });
32
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
33
+ }
34
+ /** The WCAG contrast ratio of two colours, from 1 to 21. */
35
+ export function contrast(first, second) {
36
+ const [high, low] = [luminance(first), luminance(second)].sort((a, b) => b - a);
37
+ return (high + 0.05) / (low + 0.05);
38
+ }
39
+ /** Rounds down to two decimals, so a ratio shown as 4.5 really reaches 4.5. */
40
+ export const ratio = (value) => Math.floor(value * 100) / 100;
41
+ function mix(hex, toward, amount) {
42
+ const from = channels(hex);
43
+ const to = channels(toward);
44
+ return `#${from
45
+ .map((value, index) => Math.round(value + (to[index] - value) * amount)
46
+ .toString(16)
47
+ .padStart(2, '0'))
48
+ .join('')}`;
49
+ }
50
+ /** White or near-black, whichever reads better on the colour. */
51
+ function foreground(primary) {
52
+ return contrast(primary, LIGHT_TEXT) >= contrast(primary, DARK_TEXT) ? LIGHT_TEXT : DARK_TEXT;
53
+ }
54
+ /**
55
+ * Derives both themes from one colour and checks them. The dark tint is the colour mixed
56
+ * with white in 5% steps until it reaches AA on the dark background.
57
+ */
58
+ export function checkPrimaryColor(value) {
59
+ const color = normalizeColor(value);
60
+ if (!color)
61
+ return { ok: false, reason: 'اكتب اللون بالصيغة ‎#RRGGBB‎، مثل ‎#006c35‎', light: 0, dark: 0 };
62
+ const lightText = contrast(color, LIGHT_BACKGROUND);
63
+ const lightForeground = foreground(color);
64
+ const onButton = contrast(color, lightForeground);
65
+ let dark = color;
66
+ for (let step = 1; contrast(dark, DARK_BACKGROUND) < WCAG_AA && step <= 20; step++)
67
+ dark = mix(color, LIGHT_TEXT, step * 0.05);
68
+ const darkText = contrast(dark, DARK_BACKGROUND);
69
+ const darkForeground = foreground(dark);
70
+ const darkButton = contrast(dark, darkForeground);
71
+ if (lightText < WCAG_AA)
72
+ return {
73
+ ok: false,
74
+ reason: `اللون فاتح على الخلفية الفاتحة: التباين ${ratio(lightText)}:1 والحد الأدنى ${WCAG_AA}:1. اختر درجة أغمق.`,
75
+ light: ratio(lightText),
76
+ dark: ratio(darkText),
77
+ };
78
+ if (onButton < WCAG_AA || darkText < WCAG_AA || darkButton < WCAG_AA)
79
+ return {
80
+ ok: false,
81
+ reason: `لا يبلغ اللون تباين ${WCAG_AA}:1 مع نص الأزرار في الوضعين الفاتح والداكن. اختر لونًا آخر.`,
82
+ light: ratio(Math.min(lightText, onButton)),
83
+ dark: ratio(Math.min(darkText, darkButton)),
84
+ };
85
+ return {
86
+ ok: true,
87
+ theme: {
88
+ light: { '--primary': color, '--primary-foreground': lightForeground },
89
+ dark: { '--primary': dark, '--primary-foreground': darkForeground },
90
+ },
91
+ };
92
+ }
93
+ /** The derived themes of a colour, or a 422 with the Arabic reason. */
94
+ export function derivePrimaryTheme(value) {
95
+ const check = checkPrimaryColor(value);
96
+ if (!check.ok)
97
+ throw new AdulaError(422, 'E_APPEARANCE_CONTRAST', check.reason);
98
+ return check.theme;
99
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Logos (ADR 053) are untrusted bytes shown on public pages. Only PNG, JPEG and still WebP
3
+ * are accepted, recognised by their first bytes; SVG is refused because it can carry script.
4
+ * libvips decodes one frame within a pixel budget and re-encodes it in the same format,
5
+ * fitted inside 1024×512 without enlarging, so the stored file carries no metadata and no
6
+ * payload hidden in the original. The result is checked again before it is stored.
7
+ */
8
+ export declare const LOGO_LIMITS: Readonly<{
9
+ maxBytes: number;
10
+ maxInputSide: 4096;
11
+ maxWidth: 1024;
12
+ maxHeight: 512;
13
+ minSide: 16;
14
+ }>;
15
+ export type LogoType = 'png' | 'jpeg' | 'webp';
16
+ export type LogoImage = {
17
+ type: LogoType;
18
+ mimeType: 'image/png' | 'image/jpeg' | 'image/webp';
19
+ extname: 'png' | 'jpg' | 'webp';
20
+ width: number;
21
+ height: number;
22
+ bytes: Buffer;
23
+ };
24
+ /** The format named by the file's first bytes; the name and declared type are never trusted. */
25
+ export declare function detectLogoType(bytes: Uint8Array): LogoType | null;
26
+ /** The headers a stored logo is served with: its allow-listed type, no sniffing, no script. */
27
+ export declare function logoHeaders(logo: {
28
+ mimeType: string;
29
+ size: number;
30
+ id: number;
31
+ }): Record<string, string>;
32
+ export declare function prepareLogoImage(input: Uint8Array): Promise<LogoImage>;