@capybara-hq/kernel 0.1.0-rc.10 → 0.1.0-rc.12

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 (106) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/agents/agents.schemas.d.ts +3 -0
  3. package/dist/agents/agents.service.js +11 -1
  4. package/dist/agents/definition.d.ts +1 -0
  5. package/dist/agents/definition.js +7 -3
  6. package/dist/agents/org-templates.js +4 -0
  7. package/dist/agents/pending-connectors.service.js +1 -1
  8. package/dist/catalog/catalog-content.d.ts +33 -1
  9. package/dist/catalog/catalog-content.js +65 -2
  10. package/dist/catalog/catalog-items.js +1 -0
  11. package/dist/catalog/catalog-scope.service.d.ts +29 -3
  12. package/dist/catalog/catalog-scope.service.js +82 -10
  13. package/dist/catalog/catalog.service.d.ts +7 -5
  14. package/dist/catalog/catalog.service.js +26 -5
  15. package/dist/catalog/claude/translate.js +3 -0
  16. package/dist/catalog/component-scope.controller.d.ts +18 -6
  17. package/dist/catalog/component-scope.controller.js +36 -13
  18. package/dist/catalog/component-scope.schemas.d.ts +4 -0
  19. package/dist/catalog/component-scope.service.d.ts +59 -9
  20. package/dist/catalog/component-scope.service.js +156 -27
  21. package/dist/catalog/component-state.d.ts +20 -3
  22. package/dist/catalog/component-state.js +40 -14
  23. package/dist/catalog/marketplaces.service.d.ts +1 -1
  24. package/dist/catalog/org-catalog.service.js +3 -0
  25. package/dist/catalog/owned-items.js +7 -0
  26. package/dist/catalog/platform-components.d.ts +23 -3
  27. package/dist/catalog/platform-components.js +118 -9
  28. package/dist/catalog/platform-migration.js +2 -1
  29. package/dist/catalog/plugin-import.d.ts +24 -4
  30. package/dist/catalog/plugin-import.js +41 -7
  31. package/dist/catalog/plugin-install.d.ts +20 -1
  32. package/dist/catalog/plugin-install.js +71 -1
  33. package/dist/catalog/plugin-package.d.ts +41 -4
  34. package/dist/catalog/plugin-package.js +127 -7
  35. package/dist/catalog/plugin-upgrade.d.ts +13 -2
  36. package/dist/catalog/plugin-upgrade.js +124 -6
  37. package/dist/catalog/unshare.js +1 -0
  38. package/dist/conversations/conversations.service.d.ts +9 -0
  39. package/dist/conversations/conversations.service.js +9 -2
  40. package/dist/conversations/events.d.ts +1 -0
  41. package/dist/db/kernel-schema.d.ts +54 -4
  42. package/dist/errors.d.ts +27 -0
  43. package/dist/errors.js +27 -0
  44. package/dist/http/api.module.js +7 -0
  45. package/dist/identity/accounts.d.ts +11 -4
  46. package/dist/identity/accounts.js +23 -10
  47. package/dist/identity/me.controller.d.ts +10 -10
  48. package/dist/identity/me.controller.js +8 -6
  49. package/dist/identity/me.schemas.d.ts +13 -3
  50. package/dist/identity/me.schemas.js +10 -2
  51. package/dist/identity/settings.d.ts +27 -0
  52. package/dist/identity/settings.js +64 -0
  53. package/dist/orgs/settings.service.d.ts +31 -0
  54. package/dist/orgs/settings.service.js +31 -1
  55. package/dist/platform/exclusions.js +26 -0
  56. package/dist/platform/operation.js +6 -2
  57. package/dist/platform/ops/admin.ops.d.ts +3 -1
  58. package/dist/platform/ops/admin.ops.js +25 -7
  59. package/dist/platform/ops/agents.ops.js +19 -6
  60. package/dist/platform/ops/components.ops.js +1 -0
  61. package/dist/platform/ops/org-settings.ops.d.ts +3 -1
  62. package/dist/platform/ops/org-settings.ops.js +33 -8
  63. package/dist/platform/ops/orgs.ops.js +1 -0
  64. package/dist/platform/ops/platform.ops.d.ts +3 -1
  65. package/dist/platform/ops/platform.ops.js +43 -16
  66. package/dist/platform/ops/themes.ops.d.ts +14 -0
  67. package/dist/platform/ops/themes.ops.js +47 -0
  68. package/dist/platform/platform-ops.module.d.ts +2 -1
  69. package/dist/platform/platform-ops.module.js +5 -0
  70. package/dist/platform/route-schemas.js +3 -0
  71. package/dist/runtime/subagents/definition.d.ts +3 -2
  72. package/dist/runtime/subagents/definition.js +2 -1
  73. package/dist/themes/render-css.d.ts +12 -0
  74. package/dist/themes/render-css.js +132 -0
  75. package/dist/themes/theme-delivery.service.d.ts +34 -0
  76. package/dist/themes/theme-delivery.service.js +111 -0
  77. package/dist/themes/theme-state.d.ts +95 -0
  78. package/dist/themes/theme-state.js +203 -0
  79. package/dist/themes/theme-usage.d.ts +61 -0
  80. package/dist/themes/theme-usage.js +98 -0
  81. package/dist/themes/themes-public.controller.d.ts +28 -0
  82. package/dist/themes/themes-public.controller.js +92 -0
  83. package/dist/themes/themes.controller.d.ts +13 -0
  84. package/dist/themes/themes.controller.js +38 -0
  85. package/dist/themes/themes.module.d.ts +3 -0
  86. package/dist/themes/themes.module.js +21 -0
  87. package/dist/themes/themes.schemas.d.ts +3 -0
  88. package/dist/themes/themes.schemas.js +2 -0
  89. package/dist/themes/themes.service.d.ts +50 -0
  90. package/dist/themes/themes.service.js +99 -0
  91. package/dist/tools/connector-account-policies.d.ts +51 -0
  92. package/dist/tools/connector-account-policies.js +165 -0
  93. package/dist/tools/connectors.controller.d.ts +35 -4
  94. package/dist/tools/connectors.controller.js +66 -7
  95. package/dist/tools/connectors.schemas.d.ts +11 -0
  96. package/dist/tools/connectors.schemas.js +11 -0
  97. package/dist/tools/connectors.service.d.ts +2 -0
  98. package/dist/tools/connectors.service.js +1 -0
  99. package/dist/tools/pipeline.d.ts +1 -1
  100. package/dist/tools/policy.d.ts +23 -1
  101. package/dist/tools/policy.js +99 -24
  102. package/dist/tools/tools.module.js +3 -0
  103. package/package.json +3 -3
  104. package/src/migrations/0102_themes.sql +64 -0
  105. package/src/migrations/0103_ui_theme_setting.sql +7 -0
  106. package/src/migrations/0104_connector_tool_account_policies.sql +16 -0
@@ -0,0 +1,203 @@
1
+ // Which themes an org can use and which can be the platform default (themes spec §7), the theme
2
+ // references the web reads, and the delivery URLs (§8). Plain functions in the caller's context (a
3
+ // transaction's connection when there is one): the settings writers (deployment, org, person) and
4
+ // `ThemesService` decide with the same predicates.
5
+ import { mergeThemeSchemes, } from "@capybara-hq/plugin-sdk";
6
+ import { componentOn, listedIn, loadComponents, loadScopeState, pluginFactsOf, switchOf, } from "../catalog/component-state.js";
7
+ import { ApiError } from "../errors.js";
8
+ import { packagePath } from "../packages/tgz.js";
9
+ /** The schemes in the order they are listed. */
10
+ const SCHEMES = ["dark", "light"];
11
+ /**
12
+ * The delivery URL of a theme version (spec §8): its stylesheet, or with `asset` (a path inside the
13
+ * plugin as the theme file names it, e.g. `./fonts/MiSans.woff2`) that asset, as one path segment
14
+ * (`assets/fonts%2FMiSans.woff2`; the route decodes it back to the stored path `fonts/MiSans.woff2`).
15
+ * The one builder of these URLs: the listing, the stylesheet and the asset routes all use it.
16
+ */
17
+ export function themeUrl(id, version, asset) {
18
+ const base = `/api/v1/themes/${encodeURIComponent(id)}/${encodeURIComponent(version)}`;
19
+ return asset === undefined
20
+ ? `${base}/theme.css`
21
+ : `${base}/assets/${encodeURIComponent(packagePath(asset))}`;
22
+ }
23
+ /** The {@link ThemeRef} of version `version` of theme `id`. */
24
+ export function themeRefOf(id, version, def) {
25
+ const url = (ref) => (ref === undefined ? null : themeUrl(id, version, ref));
26
+ return {
27
+ id,
28
+ version,
29
+ name: def.name,
30
+ schemes: SCHEMES.filter((s) => def.schemes[s] !== undefined),
31
+ singleScheme: def.singleScheme,
32
+ logo: def.logo === undefined
33
+ ? null
34
+ : {
35
+ markUrl: url(def.logo.mark),
36
+ wordmark: def.logo.wordmark ?? null,
37
+ faviconUrl: url(def.logo.favicon),
38
+ },
39
+ cssUrl: themeUrl(id, version),
40
+ };
41
+ }
42
+ /**
43
+ * The swatches of each scheme the theme defines: its overrides merged onto the current built-in
44
+ * values (a stored definition holds only the theme file's own values, themes spec §6).
45
+ */
46
+ export function themeSwatches(def) {
47
+ const out = {};
48
+ const merged = mergeThemeSchemes(def);
49
+ for (const s of SCHEMES) {
50
+ const c = merged[s]?.color;
51
+ if (def.schemes[s] === undefined || c === undefined)
52
+ continue;
53
+ out[s] = { bg: c.bg ?? "", panel: c.panel ?? "", ink: c.ink ?? "", accent: c.accent ?? "" };
54
+ }
55
+ return out;
56
+ }
57
+ /** The current definitions of live themes `ids`, by id. */
58
+ export async function themeDefinitions(db, ids) {
59
+ const out = new Map();
60
+ if (ids.length === 0)
61
+ return out;
62
+ const rows = await db
63
+ .selectFrom("platform_themes as p")
64
+ .innerJoin("platform_theme_versions as v", (j) => j.onRef("v.theme_id", "=", "p.id").onRef("v.version", "=", "p.current_version"))
65
+ .select(["p.id", "p.current_version", "v.definition"])
66
+ .where("p.id", "in", [...ids])
67
+ .where("p.deleted_at", "is", null)
68
+ .execute();
69
+ for (const r of rows) {
70
+ out.set(r.id, { version: String(r.current_version), definition: r.definition });
71
+ }
72
+ return out;
73
+ }
74
+ /** Whether theme `c` is on in the org (offered in its pickers, spec §6), from `st`. */
75
+ const onIn = (st, c, orgId) => componentOn(c, pluginFactsOf(st, c.itemId, orgId), listedIn(st, c.id, orgId), switchOf(st, c.id, orgId));
76
+ /** The live themes on in the org, sorted by id. */
77
+ export async function themesOnIn(db, orgId) {
78
+ const comps = await loadComponents(db, "theme");
79
+ if (comps.length === 0)
80
+ return [];
81
+ const st = await loadScopeState(db, "theme", comps);
82
+ return comps.filter((c) => onIn(st, c, orgId));
83
+ }
84
+ /**
85
+ * Whether theme `c` can be the platform default (spec §7): platform-owned, not disabled, its
86
+ * plugin live and not disabled, and its effective scope `all` (its own, or its plugin's when it
87
+ * follows; a builtin plugin is `all`).
88
+ */
89
+ function platformDefaultEligible(st, c) {
90
+ if (c.ownerOrgId !== null || c.disabled)
91
+ return false;
92
+ const p = c.itemId === null ? undefined : st.plugins.get(c.itemId);
93
+ if (c.itemId !== null && (p === undefined || p.disabled))
94
+ return false;
95
+ if (c.scopeMode === "own")
96
+ return c.scope === "all";
97
+ return p !== undefined && (p.builtin || p.scope === "all");
98
+ }
99
+ /** The live theme `id` if it can be the platform default, else null. */
100
+ export async function eligiblePlatformDefault(db, id) {
101
+ const [c] = await loadComponents(db, "theme", { ids: [id] });
102
+ if (!c)
103
+ return null;
104
+ const st = await loadScopeState(db, "theme", [c]);
105
+ return platformDefaultEligible(st, c) ? c : null;
106
+ }
107
+ /**
108
+ * 400 `theme.not_available`: theme `id` cannot be chosen where it was set; `orgs`: the live orgs
109
+ * where it is off (a platform default must be on in every org).
110
+ */
111
+ export const themeNotAvailable = (id, where, orgs) => new ApiError("theme.not_available", orgs === undefined
112
+ ? `Theme ${id} is not available ${where}; choose one of the themes listed for it`
113
+ : `Theme ${id} is off in ${orgs.length} organization(s) (${orgs.map((o) => o.orgName).join(", ")}), so it cannot be the platform default; choose a theme that is on in every organization`, [{ theme: id, ...(orgs !== undefined && { orgs }) }]);
114
+ /**
115
+ * Locks theme `id`'s catalog item, then its `platform_themes` row, FOR SHARE (the one theme lock
116
+ * order: catalog item, then theme row, then the `uiTheme` setting row; the scope, disable, switch
117
+ * and removal writers hold the item or theme row FOR UPDATE before they read `uiTheme`), so the
118
+ * check that follows reads a state no such writer changes before the caller commits.
119
+ */
120
+ export async function lockThemeShared(db, id) {
121
+ const row = await db
122
+ .selectFrom("platform_themes")
123
+ .select("catalog_item_id")
124
+ .where("id", "=", id)
125
+ .executeTakeFirst();
126
+ if (!row)
127
+ return;
128
+ if (row.catalog_item_id !== null) {
129
+ await db
130
+ .selectFrom("catalog_items")
131
+ .select("id")
132
+ .where("id", "=", row.catalog_item_id)
133
+ .forShare()
134
+ .execute();
135
+ }
136
+ await db.selectFrom("platform_themes").select("id").where("id", "=", id).forShare().execute();
137
+ }
138
+ /**
139
+ * Refuses (400 `theme.not_available`) a platform default that is not a platform-owned theme with
140
+ * effective scope `all`, live and not disabled, or that is off in some live org (an org switched it
141
+ * off, or does not have the plugin a `follow` theme comes with; details list those orgs): the
142
+ * default is locked on in every org and every org falls back to it (spec §7). Call it in the
143
+ * setting's transaction after {@link lockThemeShared} and the `uiTheme` row lock.
144
+ */
145
+ export async function assertPlatformDefaultEligible(db, id) {
146
+ const [c] = await loadComponents(db, "theme", { ids: [id] });
147
+ const st = c && (await loadScopeState(db, "theme", [c]));
148
+ if (!c || !st || !platformDefaultEligible(st, c)) {
149
+ throw themeNotAvailable(id, "as the platform default (a platform theme whose scope is all)");
150
+ }
151
+ const orgs = await db
152
+ .selectFrom("orgs")
153
+ .select(["id", "name"])
154
+ .where("deleted_at", "is", null)
155
+ .orderBy("name")
156
+ .orderBy("id")
157
+ .execute();
158
+ const off = orgs.filter((o) => !onIn(st, c, o.id)).map((o) => ({ orgId: o.id, orgName: o.name }));
159
+ if (off.length > 0)
160
+ throw themeNotAvailable(id, "as the platform default", off);
161
+ }
162
+ /**
163
+ * Refuses (400 `theme.not_available`) an org default that is not on in the org. Call it in the
164
+ * setting's transaction after the org lock: it locks the theme's rows FOR SHARE before reading.
165
+ */
166
+ export async function assertThemeOnIn(db, orgId, id) {
167
+ await lockThemeShared(db, id);
168
+ const [c] = await loadComponents(db, "theme", { ids: [id] });
169
+ const st = c && (await loadScopeState(db, "theme", [c]));
170
+ if (!c || !st || !onIn(st, c, orgId))
171
+ throw themeNotAvailable(id, "in this organization");
172
+ }
173
+ /** Whether theme `id` is on in the org (no locks: a read for display). */
174
+ export async function themeOnIn(db, orgId, id) {
175
+ const [c] = await loadComponents(db, "theme", { ids: [id] });
176
+ if (!c)
177
+ return false;
178
+ return onIn(await loadScopeState(db, "theme", [c]), c, orgId);
179
+ }
180
+ /** Whether theme `id` is on in at least one of the person's live orgs. */
181
+ export async function themeOnForAccount(db, accountId, id) {
182
+ const orgs = await db
183
+ .selectFrom("memberships as m")
184
+ .innerJoin("orgs as o", "o.id", "m.org_id")
185
+ .select("m.org_id")
186
+ .where("m.account_id", "=", accountId)
187
+ .where("o.deleted_at", "is", null)
188
+ .execute();
189
+ const [c] = await loadComponents(db, "theme", { ids: [id] });
190
+ if (!c || orgs.length === 0)
191
+ return false;
192
+ const st = await loadScopeState(db, "theme", [c]);
193
+ return orgs.some((o) => onIn(st, c, o.org_id));
194
+ }
195
+ /**
196
+ * Refuses (400 `theme.not_available`) a person's pick that is on in none of their live orgs (the
197
+ * pick is one value across their orgs, spec §7; where it is off, the org's default applies).
198
+ */
199
+ export async function assertThemeOnForAccount(db, accountId, id) {
200
+ if (!(await themeOnForAccount(db, accountId, id))) {
201
+ throw themeNotAvailable(id, "in any of your organizations");
202
+ }
203
+ }
@@ -0,0 +1,61 @@
1
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
+ import { ApiError } from "../errors.js";
3
+ /** Where a theme is chosen (spec §7). */
4
+ export interface ThemeUsage {
5
+ /** It is the platform default (`uiTheme.id`). */
6
+ platformDefault: boolean;
7
+ /** The live orgs whose default it is, by name. */
8
+ orgDefaults: {
9
+ orgId: string;
10
+ orgName: string;
11
+ }[];
12
+ /** The accounts that picked it (`accounts.theme`). */
13
+ pickedBy: number;
14
+ }
15
+ /**
16
+ * One theme a change takes away from some orgs, as a preview lists it (`themes?` of the scope,
17
+ * disable, uninstall and update previews): the orgs among those losing it whose default it is, and
18
+ * the number of people who picked it among those orgs' members (a preview never counts people of
19
+ * orgs it does not name).
20
+ */
21
+ export interface ThemePreview {
22
+ id: string;
23
+ orgDefaults: {
24
+ orgId: string;
25
+ orgName: string;
26
+ }[];
27
+ pickedBy: number;
28
+ }
29
+ /** What a theme's availability is after a change: still `all`, narrower, or gone. */
30
+ export type ThemeAfter = "all" | "narrower" | "gone";
31
+ /**
32
+ * The platform default theme's id (null: the built-in theme, or not set), through the setting's
33
+ * typed reader; `lock`: the row is read FOR SHARE, so a concurrent write of the setting (which
34
+ * locks it FOR UPDATE first, see `SettingsService`) waits for the caller's transaction, and the
35
+ * reverse.
36
+ */
37
+ export declare function platformDefaultThemeId(db: KernelSchemaDb, opts?: {
38
+ lock?: boolean;
39
+ }): Promise<string | null>;
40
+ /** Where theme `themeId` (a `platform_themes` id) is chosen: see {@link ThemeUsage}. */
41
+ export declare function themeUsage(db: KernelSchemaDb, themeId: string): Promise<ThemeUsage>;
42
+ /**
43
+ * The `themes` block of a preview: for each theme of `lost` (theme id -> the orgs losing it) that
44
+ * some org loses, the orgs among those whose default it is and how many of their members picked
45
+ * it, by id.
46
+ * Undefined when no theme is lost, so a preview without themes keeps its shape and its hash.
47
+ */
48
+ export declare function themesPreview(db: KernelSchemaDb, lost: ReadonlyMap<string, ReadonlySet<string>>): Promise<ThemePreview[] | undefined>;
49
+ /** How many members of `orgs` (each counted once) picked theme `id`. */
50
+ export declare function pickedByIn(db: KernelSchemaDb, id: string, orgs: ReadonlySet<string>): Promise<number>;
51
+ /** 409 `theme.platform_default`: theme `theme` is the platform default (spec §7). */
52
+ export declare const platformDefaultError: (theme: string) => ApiError;
53
+ /**
54
+ * Refuses a change that takes the platform default theme away from any org (spec §7): when one of
55
+ * `themeIds` is the platform default and `after` says it would no longer be `all` (narrower, or
56
+ * gone), 409 `theme.platform_default`. Call it in the change's transaction before anything is
57
+ * written, after locking the catalog item or theme rows the change touches (the one theme lock
58
+ * order: catalog item, theme row, then the `uiTheme` row, which this reads FOR SHARE; the setting's
59
+ * write takes them in the same order).
60
+ */
61
+ export declare function assertNotPlatformDefault(db: KernelSchemaDb, themeIds: readonly string[], after: (id: string) => ThemeAfter): Promise<void>;
@@ -0,0 +1,98 @@
1
+ // Who uses a theme (themes spec §6 "Losing access", §7): the platform default (`deployment_settings`
2
+ // key `uiTheme`), the orgs whose default it is (`orgs.settings.theme.id`) and the people who picked
3
+ // it (`accounts.theme`); the previews of changes that take a theme away list them, and the guard
4
+ // refuses any change that takes the platform default away from an org. Plain reads in the caller's
5
+ // context (a transaction's connection when there is one). The settings are read through the same
6
+ // readers and schemas as their services (`readUiTheme`, `parseOrgSettings`), so the two never drift.
7
+ import { sql } from "kysely";
8
+ import { ApiError } from "../errors.js";
9
+ import { readUiTheme, UI_THEME_SETTING } from "../identity/settings.js";
10
+ import { parseOrgSettings } from "../orgs/settings.service.js";
11
+ /**
12
+ * The platform default theme's id (null: the built-in theme, or not set), through the setting's
13
+ * typed reader; `lock`: the row is read FOR SHARE, so a concurrent write of the setting (which
14
+ * locks it FOR UPDATE first, see `SettingsService`) waits for the caller's transaction, and the
15
+ * reverse.
16
+ */
17
+ export async function platformDefaultThemeId(db, opts = {}) {
18
+ return (await readUiTheme(db, opts)).id;
19
+ }
20
+ /** Where theme `themeId` (a `platform_themes` id) is chosen: see {@link ThemeUsage}. */
21
+ export async function themeUsage(db, themeId) {
22
+ const platformDefault = (await platformDefaultThemeId(db)) === themeId;
23
+ // the jsonb filter narrows the rows; the typed parse decides (an invalid stored value is no default)
24
+ const orgs = (await db
25
+ .selectFrom("orgs")
26
+ .select(["id", "name", "settings"])
27
+ .where("deleted_at", "is", null)
28
+ .where(sql `settings -> 'theme' ->> 'id'`, "=", themeId)
29
+ .orderBy("name")
30
+ .orderBy("id")
31
+ .execute()).filter((o) => parseOrgSettings(o.settings).theme?.id === themeId);
32
+ const picked = await db
33
+ .selectFrom("accounts")
34
+ .select((eb) => eb.fn.countAll().as("n"))
35
+ .where("theme", "=", themeId)
36
+ .executeTakeFirstOrThrow();
37
+ return {
38
+ platformDefault,
39
+ orgDefaults: orgs.map((o) => ({ orgId: o.id, orgName: o.name })),
40
+ pickedBy: Number(picked.n),
41
+ };
42
+ }
43
+ /**
44
+ * The `themes` block of a preview: for each theme of `lost` (theme id -> the orgs losing it) that
45
+ * some org loses, the orgs among those whose default it is and how many of their members picked
46
+ * it, by id.
47
+ * Undefined when no theme is lost, so a preview without themes keeps its shape and its hash.
48
+ */
49
+ export async function themesPreview(db, lost) {
50
+ const out = [];
51
+ for (const id of [...lost.keys()].sort()) {
52
+ const orgs = lost.get(id);
53
+ if (!orgs || orgs.size === 0)
54
+ continue;
55
+ const u = await themeUsage(db, id);
56
+ out.push({
57
+ id,
58
+ orgDefaults: u.orgDefaults.filter((o) => orgs.has(o.orgId)),
59
+ pickedBy: await pickedByIn(db, id, orgs),
60
+ });
61
+ }
62
+ return out.length > 0 ? out : undefined;
63
+ }
64
+ /** How many members of `orgs` (each counted once) picked theme `id`. */
65
+ export async function pickedByIn(db, id, orgs) {
66
+ if (orgs.size === 0)
67
+ return 0;
68
+ const picked = await db
69
+ .selectFrom("accounts as a")
70
+ .select((eb) => eb.fn.count("a.id").distinct().as("n"))
71
+ .where("a.theme", "=", id)
72
+ .where((eb) => eb.exists(eb
73
+ .selectFrom("memberships as m")
74
+ .select("m.account_id")
75
+ .whereRef("m.account_id", "=", "a.id")
76
+ .where("m.org_id", "in", [...orgs])))
77
+ .executeTakeFirstOrThrow();
78
+ return Number(picked.n);
79
+ }
80
+ /** 409 `theme.platform_default`: theme `theme` is the platform default (spec §7). */
81
+ export const platformDefaultError = (theme) => new ApiError("theme.platform_default", `Theme ${theme} is the platform default theme (setting ${UI_THEME_SETTING}): it must stay on in every organization. Choose another platform default theme first, then narrow, disable or remove this one`, [{ theme, setting: UI_THEME_SETTING }]);
82
+ /**
83
+ * Refuses a change that takes the platform default theme away from any org (spec §7): when one of
84
+ * `themeIds` is the platform default and `after` says it would no longer be `all` (narrower, or
85
+ * gone), 409 `theme.platform_default`. Call it in the change's transaction before anything is
86
+ * written, after locking the catalog item or theme rows the change touches (the one theme lock
87
+ * order: catalog item, theme row, then the `uiTheme` row, which this reads FOR SHARE; the setting's
88
+ * write takes them in the same order).
89
+ */
90
+ export async function assertNotPlatformDefault(db, themeIds, after) {
91
+ if (themeIds.length === 0)
92
+ return;
93
+ const id = await platformDefaultThemeId(db, { lock: true });
94
+ if (id === null || !themeIds.includes(id))
95
+ return;
96
+ if (after(id) !== "all")
97
+ throw platformDefaultError(id);
98
+ }
@@ -0,0 +1,28 @@
1
+ import type { FastifyReply } from "fastify";
2
+ import { ThemeDeliveryService } from "./theme-delivery.service.js";
3
+ import type { ThemeRef } from "./theme-state.js";
4
+ import { ThemesService } from "./themes.service.js";
5
+ /**
6
+ * Theme delivery (themes spec §8): every theme version's stylesheet and assets, public (styles are
7
+ * not sensitive; the URLs reveal only that the theme exists) and immutable. The URLs are the ones
8
+ * `themeUrl` builds; an unknown theme, version or file is 404 `theme.not_found`.
9
+ */
10
+ export declare class ThemeDeliveryController {
11
+ private readonly delivery;
12
+ constructor(delivery: ThemeDeliveryService);
13
+ /** The version's stylesheet: scheme overrides, `@font-face` rules and font stacks. */
14
+ css(id: string, version: string, reply: FastifyReply): Promise<void>;
15
+ /**
16
+ * A font (`font/woff2`) or logo (`image/svg+xml`, sanitized at import, served under a CSP
17
+ * sandbox; `image/png`) the version names; `file` is its plugin path as one segment
18
+ * (`fonts%2FMiSans.woff2`).
19
+ */
20
+ asset(id: string, version: string, file: string, reply: FastifyReply): Promise<void>;
21
+ }
22
+ /** The platform default theme for pages before sign-in (themes spec §8-§9), public. */
23
+ export declare class PlatformThemeController {
24
+ private readonly themes;
25
+ constructor(themes: ThemesService);
26
+ /** The platform default's reference while it is eligible; null: the built-in theme. */
27
+ platformTheme(): Promise<ThemeRef | null>;
28
+ }
@@ -0,0 +1,92 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Controller, Get, Header, Inject, Param, Res } from "@nestjs/common";
11
+ import { Public } from "../identity/principal.js";
12
+ import { ThemeDeliveryService } from "./theme-delivery.service.js";
13
+ import { ThemesService } from "./themes.service.js";
14
+ /** A theme version's stylesheet and assets never change (the version is in the URL). */
15
+ const IMMUTABLE = "public, max-age=31536000, immutable";
16
+ /**
17
+ * Theme delivery (themes spec §8): every theme version's stylesheet and assets, public (styles are
18
+ * not sensitive; the URLs reveal only that the theme exists) and immutable. The URLs are the ones
19
+ * `themeUrl` builds; an unknown theme, version or file is 404 `theme.not_found`.
20
+ */
21
+ let ThemeDeliveryController = class ThemeDeliveryController {
22
+ delivery;
23
+ constructor(delivery) {
24
+ this.delivery = delivery;
25
+ }
26
+ /** The version's stylesheet: scheme overrides, `@font-face` rules and font stacks. */
27
+ async css(id, version, reply) {
28
+ const css = await this.delivery.stylesheet(id, version);
29
+ await reply
30
+ .header("content-type", "text/css; charset=utf-8")
31
+ .header("x-content-type-options", "nosniff")
32
+ .header("cache-control", IMMUTABLE)
33
+ .send(css);
34
+ }
35
+ /**
36
+ * A font (`font/woff2`) or logo (`image/svg+xml`, sanitized at import, served under a CSP
37
+ * sandbox; `image/png`) the version names; `file` is its plugin path as one segment
38
+ * (`fonts%2FMiSans.woff2`).
39
+ */
40
+ async asset(id, version, file, reply) {
41
+ const a = await this.delivery.asset(id, version, file);
42
+ reply
43
+ .header("content-type", a.contentType)
44
+ .header("x-content-type-options", "nosniff")
45
+ .header("cache-control", IMMUTABLE);
46
+ if (a.contentType === "image/svg+xml") {
47
+ reply.header("content-security-policy", "default-src 'none'; sandbox");
48
+ }
49
+ await reply.send(Buffer.from(a.data.buffer, a.data.byteOffset, a.data.byteLength));
50
+ }
51
+ };
52
+ __decorate([
53
+ Public(),
54
+ Get("theme.css"),
55
+ __param(0, Param("id")),
56
+ __param(1, Param("version")),
57
+ __param(2, Res())
58
+ ], ThemeDeliveryController.prototype, "css", null);
59
+ __decorate([
60
+ Public(),
61
+ Get("assets/:file"),
62
+ __param(0, Param("id")),
63
+ __param(1, Param("version")),
64
+ __param(2, Param("file")),
65
+ __param(3, Res())
66
+ ], ThemeDeliveryController.prototype, "asset", null);
67
+ ThemeDeliveryController = __decorate([
68
+ Controller("api/v1/themes/:id/:version"),
69
+ __param(0, Inject(ThemeDeliveryService))
70
+ ], ThemeDeliveryController);
71
+ export { ThemeDeliveryController };
72
+ /** The platform default theme for pages before sign-in (themes spec §8-§9), public. */
73
+ let PlatformThemeController = class PlatformThemeController {
74
+ themes;
75
+ constructor(themes) {
76
+ this.themes = themes;
77
+ }
78
+ /** The platform default's reference while it is eligible; null: the built-in theme. */
79
+ platformTheme() {
80
+ return this.themes.platformDefault();
81
+ }
82
+ };
83
+ __decorate([
84
+ Public(),
85
+ Get(),
86
+ Header("cache-control", "no-store")
87
+ ], PlatformThemeController.prototype, "platformTheme", null);
88
+ PlatformThemeController = __decorate([
89
+ Controller("api/v1/platform/theme"),
90
+ __param(0, Inject(ThemesService))
91
+ ], PlatformThemeController);
92
+ export { PlatformThemeController };
@@ -0,0 +1,13 @@
1
+ import { type Principal } from "../identity/principal.js";
2
+ import { type OrgContext } from "../orgs/org.guard.js";
3
+ import { type OrgThemes, ThemesService } from "./themes.service.js";
4
+ /** The org's themes (`/api/v1/orgs/:orgId/themes`, themes spec §9): members only. */
5
+ export declare class OrgThemesController {
6
+ private readonly themes;
7
+ constructor(themes: ThemesService);
8
+ /**
9
+ * `{ themes, resolved, org }`: the themes on in the org (with swatches), the viewer's resolved
10
+ * theme (null: the built-in one) and the org's default and personal lock.
11
+ */
12
+ list(principal: Principal, org: OrgContext): Promise<OrgThemes>;
13
+ }
@@ -0,0 +1,38 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Controller, Get, Inject } from "@nestjs/common";
11
+ import { CurrentPrincipal } from "../identity/principal.js";
12
+ import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
13
+ import { ThemesService } from "./themes.service.js";
14
+ /** The org's themes (`/api/v1/orgs/:orgId/themes`, themes spec §9): members only. */
15
+ let OrgThemesController = class OrgThemesController {
16
+ themes;
17
+ constructor(themes) {
18
+ this.themes = themes;
19
+ }
20
+ /**
21
+ * `{ themes, resolved, org }`: the themes on in the org (with swatches), the viewer's resolved
22
+ * theme (null: the built-in one) and the org's default and personal lock.
23
+ */
24
+ async list(principal, org) {
25
+ return this.themes.forOrg(org.orgId, principal.kind === "user" ? principal.account.id : null);
26
+ }
27
+ };
28
+ __decorate([
29
+ Get(),
30
+ OrgAction("org.read"),
31
+ __param(0, CurrentPrincipal()),
32
+ __param(1, CurrentOrg())
33
+ ], OrgThemesController.prototype, "list", null);
34
+ OrgThemesController = __decorate([
35
+ Controller("api/v1/orgs/:orgId/themes"),
36
+ __param(0, Inject(ThemesService))
37
+ ], OrgThemesController);
38
+ export { OrgThemesController };
@@ -0,0 +1,3 @@
1
+ /** Themes (themes spec §7-§9): resolution, the org's theme listing and delivery. */
2
+ export declare class ThemesModule {
3
+ }
@@ -0,0 +1,21 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Module } from "@nestjs/common";
8
+ import { StorageModule } from "../storage/storage.module.js";
9
+ import { ThemeDeliveryService } from "./theme-delivery.service.js";
10
+ import { ThemesService } from "./themes.service.js";
11
+ /** Themes (themes spec §7-§9): resolution, the org's theme listing and delivery. */
12
+ let ThemesModule = class ThemesModule {
13
+ };
14
+ ThemesModule = __decorate([
15
+ Module({
16
+ imports: [StorageModule],
17
+ providers: [ThemesService, ThemeDeliveryService],
18
+ exports: [ThemesService, ThemeDeliveryService],
19
+ })
20
+ ], ThemesModule);
21
+ export { ThemesModule };
@@ -0,0 +1,3 @@
1
+ import type { RouteSchemas } from "../platform/route-schemas.js";
2
+ /** The theme routes the Platform operations mirror (`check:platform-ops` keys). */
3
+ export declare const THEME_ROUTES: readonly RouteSchemas[];
@@ -0,0 +1,2 @@
1
+ /** The theme routes the Platform operations mirror (`check:platform-ops` keys). */
2
+ export const THEME_ROUTES = [{ route: "GET /api/v1/orgs/:orgId/themes" }];
@@ -0,0 +1,50 @@
1
+ import type { LocalizedName } from "@capybara-hq/plugin-sdk";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import { type ListedTheme, type ThemeRef } from "./theme-state.js";
4
+ /** `GET /api/v1/orgs/:orgId/themes` (themes spec §9). */
5
+ export interface OrgThemes {
6
+ /** The themes on in the org, by English name. */
7
+ themes: ListedTheme[];
8
+ /** The viewer's theme ({@link ThemesService.resolve}); null: the built-in theme. */
9
+ resolved: ThemeRef | null;
10
+ /**
11
+ * The org's setting as stored: its default (null: follow the platform) and the personal lock.
12
+ * The stored id may name a theme absent from `themes` (it went off in the org after it was
13
+ * chosen; resolution skips it): the UI shows it as unavailable, not as selected.
14
+ */
15
+ org: {
16
+ id: string | null;
17
+ personal: "allowed" | "locked";
18
+ };
19
+ }
20
+ /**
21
+ * Which theme applies (themes spec §7) and the org's theme listing. Read-only; the levels are
22
+ * written by their settings services (deployment, org, person), which check availability with the
23
+ * same predicates (`theme-state.ts`).
24
+ */
25
+ export declare class ThemesService {
26
+ private readonly db;
27
+ constructor(db: KernelDb);
28
+ /** The themes on in the org with their references and swatches, by English name then id. */
29
+ listForOrg(orgId: string): Promise<ListedTheme[]>;
30
+ /**
31
+ * The theme of a signed-in page in the org (spec §7): the person's pick if it is on in the org
32
+ * and the org does not lock; else the org's default if on; else the platform default if on in
33
+ * the org; else null (the built-in theme). An unavailable choice is skipped, never an error.
34
+ * `accountId` null (a service token): no personal pick.
35
+ */
36
+ resolve(orgId: string, accountId: string | null): Promise<ThemeRef | null>;
37
+ /** The platform default for pages before sign-in, when it is still eligible (spec §7); else null. */
38
+ platformDefault(): Promise<ThemeRef | null>;
39
+ /**
40
+ * The listing, the viewer's resolved theme and the org's setting. Separate reads, not one
41
+ * snapshot: a change committed between them shows at the next read.
42
+ */
43
+ forOrg(orgId: string, accountId: string | null): Promise<OrgThemes>;
44
+ /** A live theme's name (the super admin's summaries); null when there is no such theme. */
45
+ nameOf(id: string): Promise<LocalizedName | null>;
46
+ /** Theme `id`'s name if it is on in the org, else null (a summary never names another org's theme). */
47
+ nameIn(orgId: string, id: string): Promise<LocalizedName | null>;
48
+ /** Theme `id`'s name if it is on in one of the person's orgs, else null (same reason). */
49
+ nameForAccount(accountId: string, id: string): Promise<LocalizedName | null>;
50
+ }