@adea-ai/app-framework 0.37.0 → 0.37.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/dist/appearance/appearance-host.js +2 -1
  2. package/dist/appearance/custom-theme-import.js +3 -1
  3. package/dist/appearance/custom-theme-library.d.ts +6 -185
  4. package/dist/appearance/custom-theme-library.js +3 -621
  5. package/dist/appearance/theme-library-mutation.d.ts +42 -0
  6. package/dist/appearance/theme-library-mutation.js +172 -0
  7. package/dist/appearance/theme-library-schema.d.ts +108 -0
  8. package/dist/appearance/theme-library-schema.js +189 -0
  9. package/dist/appearance/theme-library-store.d.ts +61 -0
  10. package/dist/appearance/theme-library-store.js +268 -0
  11. package/dist/appearance/theme-record-adapter.js +3 -1
  12. package/dist/appearance/theme-registry.js +2 -1
  13. package/dist/cli/update-helper-cli.js +1 -1
  14. package/dist/desktop/desktop-client.d.ts +1 -1
  15. package/dist/framework-source.json +1 -1
  16. package/dist/installer/installed-payload.js +2 -2
  17. package/dist/installer/{installer-archive.js → installer-archive-members.js} +2 -2
  18. package/dist/installer/installer-extraction.js +2 -2
  19. package/dist/installer/installer-fetch-guard.d.ts +1 -1
  20. package/dist/installer/installer-identity.js +2 -2
  21. package/dist/installer/installer-observation.d.ts +1 -1
  22. package/dist/installer/installer-observation.js +2 -2
  23. package/dist/installer/installer-upgrade-command.d.ts +2 -2
  24. package/dist/installer/installer-upgrade-command.js +5 -5
  25. package/dist/installer/linux-process-group.js +1 -1
  26. package/dist/installer/upgrade-asset-download.d.ts +1 -1
  27. package/dist/installer/upgrade-asset-download.js +2 -2
  28. package/dist/native/posix-tree-removal.d.ts +1 -1
  29. package/dist/release/feed-release-cut.d.ts +1 -1
  30. package/dist/release/feed-state.d.ts +2 -2
  31. package/dist/release/feed-state.js +3 -3
  32. package/dist/release/github-release-cut.js +1 -1
  33. package/dist/release/github-release-promotion.js +1 -1
  34. package/dist/release/github-release-publisher.js +1 -1
  35. package/dist/release/github-release-qualification.js +1 -1
  36. package/dist/release/local-release.d.ts +2 -2
  37. package/dist/release/local-release.js +3 -3
  38. package/dist/release/release-artifact.d.ts +1 -1
  39. package/dist/release/release-artifact.js +2 -2
  40. package/dist/release/release-assets-plan.js +1 -1
  41. package/dist/release/release-config.d.ts +1 -1
  42. package/dist/release/release-config.js +1 -1
  43. package/dist/release/release-descriptor-staging.js +3 -3
  44. package/dist/release/release-finalize.js +1 -1
  45. package/dist/release/release-promotion.js +1 -1
  46. package/dist/release/release-publication.d.ts +1 -1
  47. package/dist/release/release-publication.js +2 -2
  48. package/dist/release/release-publish-command.js +2 -2
  49. package/dist/update-helper.bundle.js +18 -18
  50. package/dist/updates/channel-update-manager.d.ts +3 -3
  51. package/dist/updates/channel-update-manager.js +2 -2
  52. package/dist/updates/desktop-updater.d.ts +10 -83
  53. package/dist/updates/desktop-updater.js +14 -217
  54. package/dist/updates/{packaged-release-config.js → feed/packaged-release-config.js} +5 -5
  55. package/dist/updates/{release-feed.js → feed/release-feed.js} +2 -2
  56. package/dist/updates/{release-location.js → feed/release-location.js} +2 -2
  57. package/dist/updates/{release-version.js → feed/release-version.js} +1 -1
  58. package/dist/updates/{signed-release.js → feed/signed-release.js} +2 -2
  59. package/dist/updates/{update-discovery.js → feed/update-discovery.js} +1 -1
  60. package/dist/updates/helper/launch-gate-recovery.d.ts +8 -0
  61. package/dist/updates/{update-resume.js → helper/launch-gate-recovery.js} +13 -423
  62. package/dist/updates/helper/resume-staging.d.ts +22 -0
  63. package/dist/updates/helper/resume-staging.js +180 -0
  64. package/dist/updates/{update-helper.d.ts → helper/update-helper.d.ts} +1 -1
  65. package/dist/updates/{update-helper.js → helper/update-helper.js} +9 -9
  66. package/dist/updates/{update-resume.d.ts → helper/update-resume.d.ts} +4 -10
  67. package/dist/updates/helper/update-resume.js +252 -0
  68. package/dist/updates/{update-shutdown.js → helper/update-shutdown.js} +2 -2
  69. package/dist/updates/{update-arm.d.ts → install/update-arm.d.ts} +2 -2
  70. package/dist/updates/{update-arm.js → install/update-arm.js} +9 -9
  71. package/dist/updates/{update-download-cleanup.d.ts → install/update-download-cleanup.d.ts} +1 -1
  72. package/dist/updates/{update-download-cleanup.js → install/update-download-cleanup.js} +3 -3
  73. package/dist/updates/{update-download.d.ts → install/update-download.d.ts} +2 -2
  74. package/dist/updates/{update-download.js → install/update-download.js} +3 -3
  75. package/dist/updates/{update-extraction.d.ts → install/update-extraction.d.ts} +2 -2
  76. package/dist/updates/{update-extraction.js → install/update-extraction.js} +6 -6
  77. package/dist/updates/{update-handoff-plan.d.ts → install/update-handoff-plan.d.ts} +2 -2
  78. package/dist/updates/{update-handoff-plan.js → install/update-handoff-plan.js} +5 -5
  79. package/dist/updates/{update-marker.js → install/update-marker.js} +2 -2
  80. package/dist/updates/{update-swap-stage.d.ts → install/update-swap-stage.d.ts} +2 -2
  81. package/dist/updates/{update-swap-stage.js → install/update-swap-stage.js} +7 -6
  82. package/dist/updates/{update-swap.d.ts → install/update-swap.d.ts} +1 -1
  83. package/dist/updates/{update-swap.js → install/update-swap.js} +5 -5
  84. package/dist/updates/install-target.d.ts +8 -0
  85. package/dist/updates/install-target.js +27 -0
  86. package/dist/updates/{launch-environment.js → launch/launch-environment.js} +1 -1
  87. package/dist/updates/{packaged-launch-admission.js → launch/packaged-launch-admission.js} +4 -4
  88. package/dist/updates/{packaged-update-startup.d.ts → launch/packaged-update-startup.d.ts} +3 -3
  89. package/dist/updates/{packaged-update-startup.js → launch/packaged-update-startup.js} +10 -7
  90. package/dist/updates/{update-launch-gate.d.ts → launch/update-launch-gate.d.ts} +1 -1
  91. package/dist/updates/{update-launch-gate.js → launch/update-launch-gate.js} +9 -9
  92. package/dist/updates/{update-launch.d.ts → launch/update-launch.d.ts} +1 -1
  93. package/dist/updates/{update-launch.js → launch/update-launch.js} +2 -2
  94. package/dist/updates/{linux-process-state.js → locks/linux-process-state.js} +1 -1
  95. package/dist/updates/{native-file-lock.js → locks/native-file-lock.js} +1 -1
  96. package/dist/updates/{stable-file.js → locks/stable-file.js} +2 -2
  97. package/dist/updates/{update-download-lock.js → locks/update-download-lock.js} +1 -1
  98. package/dist/updates/{update-generation-lease.js → locks/update-generation-lease.js} +3 -3
  99. package/dist/updates/{update-inherited-launch-lease.d.ts → locks/update-inherited-launch-lease.d.ts} +1 -1
  100. package/dist/updates/{update-inherited-launch-lease.js → locks/update-inherited-launch-lease.js} +2 -2
  101. package/dist/updates/{update-instance-lease.js → locks/update-instance-lease.js} +2 -2
  102. package/dist/updates/{update-lock.js → locks/update-lock.js} +2 -2
  103. package/dist/updates/{update-process-fence.js → locks/update-process-fence.js} +3 -3
  104. package/dist/updates/{update-process-liveness.js → locks/update-process-liveness.js} +2 -2
  105. package/dist/updates/retained-client-assets.d.ts +60 -0
  106. package/dist/updates/retained-client-assets.js +116 -0
  107. package/dist/updates/retention/retention-cleanup.d.ts +103 -0
  108. package/dist/updates/retention/retention-cleanup.js +439 -0
  109. package/dist/updates/retention/retention-prune-progress.d.ts +27 -0
  110. package/dist/updates/retention/retention-prune-progress.js +203 -0
  111. package/dist/updates/retention/retirement-inventory.d.ts +93 -0
  112. package/dist/updates/retention/retirement-inventory.js +373 -0
  113. package/dist/updates/retention/retirement-records.d.ts +75 -0
  114. package/dist/updates/retention/retirement-records.js +309 -0
  115. package/dist/updates/{update-retention-marker.d.ts → retention/update-retention-marker.d.ts} +1 -1
  116. package/dist/updates/{update-retention-marker.js → retention/update-retention-marker.js} +3 -3
  117. package/dist/updates/{update-retention-plan.d.ts → retention/update-retention-plan.d.ts} +1 -1
  118. package/dist/updates/{update-retention-plan.js → retention/update-retention-plan.js} +2 -2
  119. package/dist/updates/{update-retention-sync.d.ts → retention/update-retention-sync.d.ts} +1 -1
  120. package/dist/updates/{update-retention-sync.js → retention/update-retention-sync.js} +2 -2
  121. package/dist/updates/retention/update-retirement.d.ts +26 -0
  122. package/dist/updates/retention/update-retirement.js +205 -0
  123. package/dist/updates/update-adapter.js +1 -1
  124. package/dist/updates/update-channel-store.d.ts +1 -1
  125. package/dist/updates/update-channel-store.js +2 -2
  126. package/dist/updates/update-manager.d.ts +4 -4
  127. package/dist/updates/update-manager.js +5 -5
  128. package/dist/updates/update-services.d.ts +15 -0
  129. package/dist/updates/update-services.js +77 -0
  130. package/dist/updates/update-state-store.d.ts +2 -2
  131. package/dist/updates/update-state-store.js +2 -2
  132. package/dist/views/appearance-surface.js +3 -1
  133. package/package.json +29 -29
  134. package/src/appearance/custom-theme-library.ts +42 -956
  135. package/src/appearance/theme-library-mutation.ts +288 -0
  136. package/src/appearance/theme-library-schema.ts +347 -0
  137. package/src/appearance/theme-library-store.ts +379 -0
  138. package/src/updates/update-adapter.ts +1 -1
  139. package/dist/updates/update-retirement.d.ts +0 -205
  140. package/dist/updates/update-retirement.js +0 -1485
  141. /package/dist/installer/{installer-archive.d.ts → installer-archive-members.d.ts} +0 -0
  142. /package/dist/updates/{packaged-release-config.d.ts → feed/packaged-release-config.d.ts} +0 -0
  143. /package/dist/updates/{release-feed.d.ts → feed/release-feed.d.ts} +0 -0
  144. /package/dist/updates/{release-location.d.ts → feed/release-location.d.ts} +0 -0
  145. /package/dist/updates/{release-version.d.ts → feed/release-version.d.ts} +0 -0
  146. /package/dist/updates/{signed-release.d.ts → feed/signed-release.d.ts} +0 -0
  147. /package/dist/updates/{update-discovery.d.ts → feed/update-discovery.d.ts} +0 -0
  148. /package/dist/updates/{update-shutdown.d.ts → helper/update-shutdown.d.ts} +0 -0
  149. /package/dist/updates/{update-marker.d.ts → install/update-marker.d.ts} +0 -0
  150. /package/dist/updates/{launch-environment.d.ts → launch/launch-environment.d.ts} +0 -0
  151. /package/dist/updates/{packaged-launch-admission.d.ts → launch/packaged-launch-admission.d.ts} +0 -0
  152. /package/dist/updates/{linux-process-state.d.ts → locks/linux-process-state.d.ts} +0 -0
  153. /package/dist/updates/{native-file-lock.d.ts → locks/native-file-lock.d.ts} +0 -0
  154. /package/dist/updates/{stable-file.d.ts → locks/stable-file.d.ts} +0 -0
  155. /package/dist/updates/{update-download-lock.d.ts → locks/update-download-lock.d.ts} +0 -0
  156. /package/dist/updates/{update-generation-lease.d.ts → locks/update-generation-lease.d.ts} +0 -0
  157. /package/dist/updates/{update-instance-lease.d.ts → locks/update-instance-lease.d.ts} +0 -0
  158. /package/dist/updates/{update-lock.d.ts → locks/update-lock.d.ts} +0 -0
  159. /package/dist/updates/{update-process-fence.d.ts → locks/update-process-fence.d.ts} +0 -0
  160. /package/dist/updates/{update-process-liveness.d.ts → locks/update-process-liveness.d.ts} +0 -0
  161. /package/src/updates/{release-version.ts → feed/release-version.ts} +0 -0
@@ -8,16 +8,6 @@
8
8
  * theme); the shared ThemeProvider receives it as extra variants. See NOTICE and
9
9
  * the repository history for source and behavior provenance.
10
10
  */
11
- import type { AdeaTheme, AdeaThemeRecord } from '@adea-ai/ui/lib/theme-records'
12
-
13
- import { contrastRatio } from '@adea-ai/ui/lib/accent-roles'
14
- import { defaultPreferenceStorage, quarantineRecord } from '@adea-ai/ui/lib/preference-store'
15
- import { defaultVariantFor } from '@adea-ai/ui/lib/theme-defaults'
16
- import { variantFromRecord } from '@adea-ai/ui/lib/theme-records'
17
- import type { ThemeVariant as UiThemeVariant } from '@adea-ai/ui/lib/themes'
18
-
19
- import { LEGACY_IMPORTED_THEME_TOKEN_PROJECTION_FALLBACKS } from './legacy-imported-theme-token-projection'
20
-
21
11
  /**
22
12
  * The custom theme library: themes the user imported from a file, stored in
23
13
  * `localStorage` and handed to the provider as extra variants. Import and
@@ -31,949 +21,45 @@ import { LEGACY_IMPORTED_THEME_TOKEN_PROJECTION_FALLBACKS } from './legacy-impor
31
21
  * the sidebar projection recovers only absent source entries from `variant`.
32
22
  */
33
23
 
34
- export type StoredThemeAppearance = 'light' | 'dark'
35
-
36
- export type StoredThemeTerminal = Readonly<{
37
- background: string
38
- foreground: string
39
- cursor: string
40
- selection: string
41
- /** The 16 xterm ANSI slots, in protocol order. */
42
- ansi: readonly string[]
43
- }>
44
-
45
- export type StoredThemeEditorRoles = Readonly<{
46
- keyword: string
47
- string: string
48
- number: string
49
- comment: string
50
- function: string
51
- variable: string
52
- type: string
53
- tag: string
54
- attribute: string
55
- operator: string
56
- heading: string
57
- link: string
58
- diffAdd: string
59
- diffDelete: string
60
- diffHunk: string
61
- searchMatch: string
62
- }>
63
-
64
- export type StoredThemeChartRoles = Readonly<{
65
- chart1: string
66
- chart2: string
67
- chart3: string
68
- chart4: string
69
- chart5: string
70
- chart6: string
71
- }>
72
-
73
- export type StoredThemeColors = Readonly<{
74
- background: string
75
- foreground: string
76
- card: string
77
- cardForeground: string
78
- popover: string
79
- popoverForeground: string
80
- primary: string
81
- primaryForeground: string
82
- secondary: string
83
- secondaryForeground: string
84
- muted: string
85
- mutedForeground: string
86
- accent: string
87
- accentForeground: string
88
- destructive: string
89
- destructiveAction: string
90
- destructiveActionForeground: string
91
- success: string
92
- border: string
93
- input: string
94
- ring: string
95
- }>
96
-
97
- /** The variant shape the library has always stored for an imported theme. */
98
- export type StoredThemeVariant = Readonly<{
99
- id: string
100
- familyId: string
101
- familyName: string
102
- name: string
103
- appearance: StoredThemeAppearance
104
- colors: StoredThemeColors
105
- terminal: StoredThemeTerminal
106
- editor: StoredThemeEditorRoles
107
- charts: StoredThemeChartRoles
108
- }>
109
-
110
- export type CustomThemeStored = Readonly<{
111
- /** Stable id, namespaced so it can never collide with a catalogue id. */
112
- id: string
113
- name: string
114
- appearance: StoredThemeAppearance
115
- importedAt: string
116
- variant: StoredThemeVariant
117
- /** The verbatim imported map; projection may supply absent sources from `variant`. */
118
- flatTokens: Readonly<Record<string, string>>
119
- /** Non-fatal adjustments made while normalizing the file, for the UI. */
120
- notes: readonly string[]
121
- }>
122
-
123
- export type AppearanceStorage = Pick<Storage, 'getItem' | 'setItem'>
124
-
125
- /** A cross-context lock used to serialize theme-library read/modify/write operations. */
126
- export type ThemeLibraryAtomicLock = Readonly<{
127
- withExclusiveLock<T>(name: string, operation: () => T): Promise<T>
128
- }>
129
-
130
- export type ThemeLibraryMutationOptions = Readonly<{
131
- /** Override the browser lock provider in tests or embedder adapters. `null` means unavailable. */
132
- lock?: ThemeLibraryAtomicLock | null
133
- }>
134
-
135
- export type ThemeLibraryMutation<T> = Readonly<{
136
- themes: readonly CustomThemeStored[]
137
- value: T
138
- /** Leave storage and subscribers untouched for rejected or idempotent operations. */
139
- commit?: boolean
140
- }>
141
-
142
- export type ThemeLibraryMutationFailureReason =
143
- | 'atomic_unavailable'
144
- | 'storage_failed'
145
- | 'recovery_unavailable'
146
- | 'changed_during_mutation'
147
-
148
- export type ThemeLibraryMutationResult<T> =
149
- | { ok: true; committed: boolean; value: T }
150
- | { ok: false; reason: ThemeLibraryMutationFailureReason; error: string }
151
-
152
- export const CUSTOM_THEME_LIBRARY_STORAGE_KEY = 'appearance.library'
153
- /**
154
- * Where an unreadable library is quarantined. It is its own key: the library and
155
- * the appearance preference used to share `appearance.recovery`, so one could
156
- * overwrite the other's capture.
157
- */
158
- export const CUSTOM_THEME_LIBRARY_RECOVERY_KEY = 'appearance.library.recovery'
159
- const CUSTOM_THEME_LIBRARY_VERSION = 1
160
- const CUSTOM_THEME_ID_PREFIX = 'custom-'
161
- /** Origin-wide lock name shared by all cooperating framework builds. */
162
- export const CUSTOM_THEME_LIBRARY_LOCK_NAME = 'adea:appearance.library:mutation:v1'
163
- const CUSTOM_THEME_LIBRARY_LOCK_DB = 'adea:appearance-library-coordination:v1'
164
- const CUSTOM_THEME_LIBRARY_LOCK_STORE = 'locks'
165
- export const CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE =
166
- 'This app cannot safely save theme changes in this environment. Your library was not changed.'
167
- export const CUSTOM_THEME_LIBRARY_MUTATION_FAILED =
168
- 'The theme could not be saved. Check your storage and try again.'
169
-
170
- /*
171
- * Registry validation, ported from Zeron `ThemeRegistry::validate`: core text and
172
- * muted text must reach 4.5:1, the accent 3:1, on-accent 4.5:1, the terminal
173
- * foreground 4.5:1, and every chromatic ANSI slot 3:1 (slots 0 and 8 are
174
- * structural black/dim colors). Import runs it over the one variant it just built.
175
- */
176
-
177
- export type ValidationIssue = Readonly<{
178
- variantId: string
179
- severity: 'error' | 'warning'
180
- message: string
181
- }>
182
-
183
- export function validateThemeRegistry(registry: readonly StoredThemeVariant[]): ValidationIssue[] {
184
- const issues: ValidationIssue[] = []
185
- const seen = new Set<string>()
186
- for (const variant of registry) {
187
- if (variant.id.trim().length === 0 || seen.has(variant.id)) {
188
- issues.push({
189
- variantId: variant.id,
190
- severity: 'error',
191
- message: 'variant id must be unique',
192
- })
193
- }
194
- seen.add(variant.id)
195
- const check = (role: string, foreground: string, background: string, minimum: number) => {
196
- const actual = contrastRatio(foreground, background)
197
- if (actual < minimum) {
198
- issues.push({
199
- variantId: variant.id,
200
- severity: 'error',
201
- message: `${role} contrast is ${actual.toFixed(2)}:1; expected ${minimum.toFixed(1)}:1`,
202
- })
203
- }
204
- }
205
- check('text', variant.colors.foreground, variant.colors.background, 4.5)
206
- check('muted text', variant.colors.mutedForeground, variant.colors.background, 4.5)
207
- check('primary', variant.colors.primary, variant.colors.background, 3)
208
- check('on-primary', variant.colors.primaryForeground, variant.colors.primary, 4.5)
209
- check('terminal foreground', variant.terminal.foreground, variant.terminal.background, 4.5)
210
- for (const [index, color] of variant.terminal.ansi.entries()) {
211
- if (index % 8 === 0) continue
212
- const actual = contrastRatio(color, variant.terminal.background)
213
- if (actual < 3) {
214
- issues.push({
215
- variantId: variant.id,
216
- severity: 'warning',
217
- message: `terminal ANSI slot ${index} is below 3:1`,
218
- })
219
- }
220
- }
221
- check('editor comment', variant.editor.comment, variant.colors.background, 4.5)
222
- check('diff delete', variant.editor.diffDelete, variant.colors.background, 3)
223
- check('diff add', variant.editor.diffAdd, variant.colors.background, 3)
224
- }
225
- return issues
226
- }
227
-
228
- /*
229
- * The flat token map: the custom properties an imported theme owns. It is stored
230
- * with the theme (`flatTokens`) so the pre-paint script can apply it without the
231
- * library's code, and the provider writes it verbatim over everything it derives.
232
- */
233
-
234
- const ANSI_NAMES = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
235
-
236
- function kebabCase(value: string): string {
237
- return value.replaceAll(/[A-Z]/g, (character) => `-${character.toLocaleLowerCase()}`)
238
- }
239
-
240
- function terminalTokens(palette: StoredThemeTerminal): Record<string, string> {
241
- const tokens: Record<string, string> = {
242
- '--terminal-background': palette.background,
243
- '--terminal-foreground': palette.foreground,
244
- '--terminal-cursor': palette.cursor,
245
- '--terminal-selection': palette.selection,
246
- }
247
- for (const [index, color] of palette.ansi.entries()) {
248
- const name = ANSI_NAMES[index % 8]!
249
- tokens[index < 8 ? `--terminal-ansi-${name}` : `--terminal-ansi-bright-${name}`] = color
250
- }
251
- return tokens
252
- }
253
-
254
- /** The custom properties an imported variant owns, as a flat map. */
255
- export function flatVariantTokens(variant: StoredThemeVariant): Record<string, string> {
256
- const tokens: Record<string, string> = {}
257
- for (const [role, value] of Object.entries(variant.colors)) {
258
- tokens[`--${kebabCase(role)}`] = value
259
- }
260
- Object.assign(tokens, terminalTokens(variant.terminal))
261
- for (const [role, value] of Object.entries(variant.editor)) {
262
- tokens[`--editor-${kebabCase(role)}`] = value
263
- }
264
- for (const [index, value] of Object.values(variant.charts).entries()) {
265
- tokens[`--chart-${index + 1}`] = value
266
- }
267
- return tokens
268
- }
269
-
270
- /*
271
- * The shared variant for a stored theme.
272
- *
273
- * The stored variant is lossy against the catalogue's record shape (it has no
274
- * warning, info or hover roles), so the record is reconstructed from it, the same
275
- * reconstruction the appearance editor previews. The shared provider derives what
276
- * the import never stored (status hues, sidebar, hover) from that record, and then
277
- * writes `flatTokens` verbatim over the derivation: every stored key paints exactly
278
- * what the user imported.
279
- */
280
-
281
- const IMPORTED_PROVENANCE = {
282
- project: 'Adea themes catalogue',
283
- url: 'https://github.com/adea-ai/themes',
284
- license: 'Apache-2.0',
285
- } as const
286
-
287
- function ansiRamp(variant: StoredThemeVariant): AdeaTheme['ansi'] {
288
- const [
289
- black,
290
- red,
291
- green,
292
- yellow,
293
- blue,
294
- magenta,
295
- cyan,
296
- white,
297
- brightBlack,
298
- brightRed,
299
- brightGreen,
300
- brightYellow,
301
- brightBlue,
302
- brightMagenta,
303
- brightCyan,
304
- brightWhite,
305
- ] = variant.terminal.ansi
306
- return {
307
- black: black!,
308
- red: red!,
309
- green: green!,
310
- yellow: yellow!,
311
- blue: blue!,
312
- magenta: magenta!,
313
- cyan: cyan!,
314
- white: white!,
315
- brightBlack: brightBlack!,
316
- brightRed: brightRed!,
317
- brightGreen: brightGreen!,
318
- brightYellow: brightYellow!,
319
- brightBlue: brightBlue!,
320
- brightMagenta: brightMagenta!,
321
- brightCyan: brightCyan!,
322
- brightWhite: brightWhite!,
323
- }
324
- }
325
-
326
- /**
327
- * The catalogue-shaped record for an imported variant. The editor reads only its
328
- * surface, text, border and accent roles; warning and info are the ANSI yellow and
329
- * blue because the stored variant has no such roles.
330
- */
331
- export function storedVariantRecord(variant: StoredThemeVariant): AdeaThemeRecord {
332
- const colors = variant.colors
333
- const ansi = ansiRamp(variant)
334
- const theme: AdeaTheme = {
335
- id: variant.id,
336
- name: variant.name,
337
- appearance: variant.appearance,
338
- colors: {
339
- background: colors.background,
340
- foreground: colors.foreground,
341
- surface: colors.card,
342
- surfaceElevated: colors.popover,
343
- surfaceHover: colors.accent,
344
- surfaceActive: colors.border,
345
- border: colors.border,
346
- borderMuted: colors.border,
347
- text: colors.foreground,
348
- textMuted: colors.mutedForeground,
349
- textSubtle: colors.mutedForeground,
350
- accent: colors.primary,
351
- accentForeground: colors.primaryForeground,
352
- success: colors.success,
353
- warning: ansi.yellow,
354
- error: colors.destructive,
355
- info: ansi.blue,
356
- },
357
- ansi,
358
- cursor: variant.terminal.cursor,
359
- selection: variant.terminal.selection,
360
- }
361
- return {
362
- ...theme,
363
- family: variant.familyId,
364
- familyLabel: variant.familyName,
365
- label: variant.name,
366
- description: `${variant.name}, imported into your library.`,
367
- provenance: IMPORTED_PROVENANCE,
368
- tags: ['imported', variant.appearance],
369
- }
370
- }
371
-
372
- /**
373
- * The shared-provider variant for a stored theme: derived roles from the
374
- * reconstructed record, missing sidebar projection sources from the stored variant,
375
- * then every stored flat token verbatim.
376
- *
377
- * A record the shared projection cannot map falls back to the default theme of the
378
- * same appearance under the stored identity, so an import that the projection
379
- * rejects still paints from its tokens instead of vanishing.
380
- */
381
- export function toUiVariant(stored: CustomThemeStored): UiThemeVariant {
382
- const { variant } = stored
383
- let base: UiThemeVariant
384
- try {
385
- base = variantFromRecord(storedVariantRecord(variant))
386
- } catch {
387
- // The shipped default of the appearance: the provider's own start-up data, so the
388
- // shell never imports the themes catalogue to repair an import.
389
- base = {
390
- ...defaultVariantFor(variant.appearance),
391
- id: variant.id,
392
- family: variant.familyId,
393
- familyLabel: variant.familyName,
394
- label: variant.name,
395
- description: `${variant.name}, imported into your library.`,
396
- provenance: {
397
- source: IMPORTED_PROVENANCE.project,
398
- url: IMPORTED_PROVENANCE.url,
399
- license: IMPORTED_PROVENANCE.license,
400
- },
401
- }
402
- }
403
- const projectionSources: Record<string, string> = {}
404
- for (const fallback of LEGACY_IMPORTED_THEME_TOKEN_PROJECTION_FALLBACKS) {
405
- if (Object.hasOwn(stored.flatTokens, fallback.token)) continue
406
- // Read-only walk over own properties of the stored record.
407
- const value = fallback.path.reduce<unknown>(
408
- (node, key) =>
409
- node && typeof node === 'object' && Object.hasOwn(node, key)
410
- ? (node as Record<string, unknown>)[key]
411
- : undefined,
412
- stored
413
- )
414
- if (typeof value === 'string') projectionSources[fallback.token] = value
415
- }
416
- return { ...base, tokens: { ...projectionSources, ...stored.flatTokens } }
417
- }
418
-
419
- /*
420
- * The in-memory library.
421
- *
422
- * It lives on the host object, not in module state: the dev graph (and any consumer
423
- * graph) can legitimately load this module twice (a relative import and the
424
- * components subpath are distinct module records), and a singleton array would fork
425
- * the registry. The listeners live there too, so a change made through one instance
426
- * reaches a subscriber registered through the other.
427
- */
428
- type LibraryState = {
429
- themes: readonly CustomThemeStored[]
430
- /** Derived from `themes`; rebuilt on first read after each change. */
431
- uiVariants?: readonly UiThemeVariant[]
432
- listeners: Set<() => void>
433
- /** Blocks legacy synchronous writes while a coordinated mutation is committing. */
434
- atomicMutationDepth?: number
435
- /** One storage observer per shared host, even if source and package graphs load twice. */
436
- storageEventTarget?: Window
437
- storageEventListener?: (event: StorageEvent) => void
438
- }
439
- type LibraryHost = typeof globalThis & { __ADEA_THEME_LIBRARY__?: Partial<LibraryState> }
440
- const libraryHost = globalThis as LibraryHost
441
-
442
- function library(): LibraryState {
443
- const existing = libraryHost.__ADEA_THEME_LIBRARY__
444
- if (existing && Array.isArray(existing.themes) && existing.listeners) {
445
- return existing as LibraryState
446
- }
447
- // A host object written by an older module instance has another shape.
448
- const created: LibraryState = {
449
- themes: [],
450
- listeners: existing?.listeners ?? new Set(),
451
- atomicMutationDepth: 0,
452
- }
453
- libraryHost.__ADEA_THEME_LIBRARY__ = created
454
- return created
455
- }
456
-
457
- function replaceThemes(themes: readonly CustomThemeStored[]): void {
458
- const state = library()
459
- state.themes = Object.freeze([...themes])
460
- state.uiVariants = undefined
461
- }
462
-
463
- /** The imported themes' stored variants, in import order. */
464
- export function customThemeVariants(): readonly StoredThemeVariant[] {
465
- return library().themes.map((theme) => theme.variant)
466
- }
467
-
468
- /** Find one stored variant without projecting the rest of the imported library. */
469
- export function customThemeVariantById(id: string): StoredThemeVariant | undefined {
470
- return library().themes.find((theme) => theme.variant.id === id)?.variant
471
- }
472
-
473
- /** The imported themes as shared-provider variants: what the provider's `themes` takes. */
474
- export function customUiVariants(): readonly UiThemeVariant[] {
475
- const state = library()
476
- state.uiVariants ??= Object.freeze(state.themes.map(toUiVariant))
477
- return state.uiVariants
478
- }
479
-
480
- function handlePersistentLibraryChange(event: StorageEvent): void {
481
- if (event.key !== CUSTOM_THEME_LIBRARY_STORAGE_KEY && event.key !== null) return
482
- // This library uses the same localStorage returned by the preference store.
483
- // Ignore sessionStorage events and events from any other Storage object.
484
- const storage = defaultPreferenceStorage()
485
- if (!storage || event.storageArea !== storage) return
486
- readCustomThemeLibrary(storage)
487
- }
488
-
489
- function observePersistentLibraryChanges(): void {
490
- const state = library()
491
- if (state.storageEventTarget || typeof window === 'undefined') return
492
- const target = window
493
- const listener = handlePersistentLibraryChange
494
- state.storageEventTarget = target
495
- state.storageEventListener = listener
496
- target.addEventListener('storage', listener)
497
- }
498
-
499
- export function subscribeCustomThemes(listener: () => void): () => void {
500
- observePersistentLibraryChanges()
501
- const { listeners } = library()
502
- listeners.add(listener)
503
- return () => listeners.delete(listener)
504
- }
505
-
506
- function notifyCustomThemes(): void {
507
- const { listeners } = library()
508
- // Visit each start-of-notification listener at most once. Skip listeners no
509
- // longer subscribed at their turn; newly added functions wait until next time.
510
- // oxlint-disable-next-line unicorn/no-useless-spread
511
- for (const listener of [...listeners]) {
512
- if (!listeners.has(listener)) continue
513
- try {
514
- // Listeners are observers of an already committed library. A broken
515
- // observer must not turn a successful write into an import failure or
516
- // keep later observers from seeing it. There is no diagnostics sink here.
517
- void Promise.resolve(listener()).catch(() => {})
518
- } catch {
519
- // The committed library remains authoritative when a listener throws.
520
- }
521
- }
522
- }
523
-
524
- function isCustomThemeId(id: string): boolean {
525
- return id.startsWith(CUSTOM_THEME_ID_PREFIX)
526
- }
527
-
528
- /**
529
- * Replace the in-memory imported-theme set and tell subscribers. Durable mutations
530
- * must use `mutateCustomThemeLibrary`; this deprecated synchronous API fails closed
531
- * when a storage adapter is supplied because it cannot acquire the shared lock.
532
- *
533
- * @deprecated Use `mutateCustomThemeLibrary` for persisted read/modify/write operations.
534
- */
535
- export function setCustomThemes(
536
- themes: readonly CustomThemeStored[],
537
- storage: AppearanceStorage | undefined
538
- ): boolean {
539
- const state = library()
540
- // This synchronous compatibility API cannot acquire the shared lock. Reject it
541
- // during a coordinated write as well as for any durable storage, before it can
542
- // mutate the shared cache or overwrite a newer v1 record.
543
- if ((state.atomicMutationDepth ?? 0) > 0) return false
544
- if (storage) return false
545
- const safe = namespaceCustomThemes(themes)
546
- replaceThemes(safe)
547
- notifyCustomThemes()
548
- return true
549
- }
550
-
551
- function namespaceCustomThemes(themes: readonly CustomThemeStored[]): CustomThemeStored[] {
552
- return themes.map((theme) => {
553
- if (isCustomThemeId(theme.id)) return theme
554
- const id = `${CUSTOM_THEME_ID_PREFIX}${theme.id}`
555
- return { ...theme, id, variant: { ...theme.variant, id } }
556
- })
557
- }
558
-
559
- const object = (value: unknown): value is Record<string, unknown> =>
560
- typeof value === 'object' && value !== null && !Array.isArray(value)
561
- const fields = (value: unknown, names: readonly string[]) =>
562
- object(value) && names.every((name) => typeof value[name] === 'string')
563
-
564
- function isStoredTheme(entry: unknown): entry is CustomThemeStored {
565
- if (!object(entry) || !object(entry.variant)) return false
566
- const theme = entry
567
- const variant = entry.variant
568
- return (
569
- typeof theme.id === 'string' &&
570
- typeof theme.name === 'string' &&
571
- (theme.appearance === 'light' || theme.appearance === 'dark') &&
572
- typeof theme.importedAt === 'string' &&
573
- fields(variant, ['id', 'familyId', 'familyName', 'name']) &&
574
- (variant.appearance === 'light' || variant.appearance === 'dark') &&
575
- fields(variant.colors, [
576
- 'background',
577
- 'foreground',
578
- 'card',
579
- 'cardForeground',
580
- 'popover',
581
- 'popoverForeground',
582
- 'primary',
583
- 'primaryForeground',
584
- 'secondary',
585
- 'secondaryForeground',
586
- 'muted',
587
- 'mutedForeground',
588
- 'accent',
589
- 'accentForeground',
590
- 'destructive',
591
- 'destructiveAction',
592
- 'destructiveActionForeground',
593
- 'success',
594
- 'border',
595
- 'input',
596
- 'ring',
597
- ]) &&
598
- fields(variant.terminal, ['background', 'foreground', 'cursor', 'selection']) &&
599
- object(variant.terminal) &&
600
- Array.isArray(variant.terminal.ansi) &&
601
- variant.terminal.ansi.length === 16 &&
602
- variant.terminal.ansi.every((color) => typeof color === 'string') &&
603
- fields(variant.editor, [
604
- 'keyword',
605
- 'string',
606
- 'number',
607
- 'comment',
608
- 'function',
609
- 'variable',
610
- 'type',
611
- 'tag',
612
- 'attribute',
613
- 'operator',
614
- 'heading',
615
- 'link',
616
- 'diffAdd',
617
- 'diffDelete',
618
- 'diffHunk',
619
- 'searchMatch',
620
- ]) &&
621
- fields(variant.charts, ['chart1', 'chart2', 'chart3', 'chart4', 'chart5', 'chart6']) &&
622
- object(theme.flatTokens) &&
623
- Object.values(theme.flatTokens).every((value) => typeof value === 'string') &&
624
- Array.isArray(theme.notes) &&
625
- theme.notes.every((note) => typeof note === 'string')
626
- )
627
- }
628
-
629
- function parseLibrary(raw: string): {
630
- themes: CustomThemeStored[]
631
- reason?: 'corrupt_json' | 'unsupported_record'
632
- } {
633
- let value: unknown
634
- try {
635
- value = JSON.parse(raw)
636
- } catch {
637
- return { themes: [], reason: 'corrupt_json' }
638
- }
639
- if (
640
- !object(value) ||
641
- value.version !== CUSTOM_THEME_LIBRARY_VERSION ||
642
- !Array.isArray(value.themes)
643
- )
644
- return { themes: [], reason: 'unsupported_record' }
645
- const themes = value.themes.filter(isStoredTheme)
646
- return themes.length === value.themes.length
647
- ? { themes }
648
- : { themes, reason: 'unsupported_record' }
649
- }
650
-
651
- function preserveLibrary(
652
- storage: AppearanceStorage,
653
- raw: string,
654
- reason: 'corrupt_json' | 'unsupported_record'
655
- ): boolean {
656
- const existing = storage.getItem(CUSTOM_THEME_LIBRARY_RECOVERY_KEY)
657
- if (!existing) quarantineRecord(storage, CUSTOM_THEME_LIBRARY_RECOVERY_KEY, raw, reason)
658
- const saved = storage.getItem(CUSTOM_THEME_LIBRARY_RECOVERY_KEY)
659
- try {
660
- const capture: unknown = saved && JSON.parse(saved)
661
- return object(capture) && capture.schemaVersion === 1 && capture.raw === raw
662
- } catch {
663
- return false
664
- }
665
- }
666
-
667
- /**
668
- * Read the stored library. A malformed document starts an empty library and
669
- * quarantines the raw bytes into the library's own recovery key, mirroring the
670
- * appearance-preference recovery contract; individual invalid records are dropped,
671
- * not fatal.
672
- */
673
- export function readCustomThemeLibrary(
674
- storage: AppearanceStorage | undefined
675
- ): readonly CustomThemeStored[] {
676
- if (!storage) return []
677
- const result = tryReadCustomThemeLibrary(storage)
678
- if (result?.changed) notifyCustomThemes()
679
- return result?.themes ?? []
680
- }
681
-
682
- // Theme records are JSON data. Compare values without allocating serialized
683
- // copies or treating a different object-key order as a theme change.
684
- function sameThemeValue(left: unknown, right: unknown): boolean {
685
- if (Object.is(left, right)) return true
686
- if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false
687
- if (Array.isArray(left) || Array.isArray(right)) {
688
- if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false
689
- if (Object.getPrototypeOf(left) !== Array.prototype) return false
690
- if (Reflect.ownKeys(left).length !== left.length + 1) return false
691
- for (let index = 0; index < left.length; index++) {
692
- const entry = Object.getOwnPropertyDescriptor(left, index)
693
- if (!entry || !entry.enumerable || !('value' in entry)) return false
694
- if (!sameThemeValue(entry.value, right[index])) return false
695
- }
696
- return true
697
- }
698
- if (Object.getPrototypeOf(left) !== Object.prototype) return false
699
- const leftKeys = Object.keys(left)
700
- const rightKeys = Object.keys(right)
701
- if (leftKeys.length !== rightKeys.length || Reflect.ownKeys(left).length !== leftKeys.length)
702
- return false
703
- const rightRecord = right as Record<string, unknown>
704
- return leftKeys.every((key) => {
705
- const entry = Object.getOwnPropertyDescriptor(left, key)
706
- return (
707
- !!entry &&
708
- 'value' in entry &&
709
- Object.hasOwn(rightRecord, key) &&
710
- sameThemeValue(entry.value, rightRecord[key])
711
- )
712
- })
713
- }
714
-
715
- /** A failed read must not be confused with a successfully read empty library. */
716
- function tryReadCustomThemeLibrary(
717
- storage: AppearanceStorage
718
- ): { themes: readonly CustomThemeStored[]; changed: boolean } | undefined {
719
- const state = library()
720
- const previousThemes = state.themes
721
- try {
722
- // An empty value is no library, not a corrupt one.
723
- const raw = storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY)
724
- const { themes, reason } = raw ? parseLibrary(raw) : { themes: [] }
725
- if (raw && reason) preserveLibrary(storage, raw, reason)
726
- let changed = true
727
- try {
728
- changed = !sameThemeValue(previousThemes, themes)
729
- } catch {
730
- // Legacy in-memory values can be unserializable. Publish and notify
731
- // conservatively after checking that this read is still current.
732
- }
733
- // Detect storage or shared-cache changes observed during this read before
734
- // publishing its snapshot. This is not an atomic cross-context write.
735
- if (
736
- storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY) !== raw ||
737
- library() !== state ||
738
- state.themes !== previousThemes
739
- )
740
- return undefined
741
- if (changed) replaceThemes(themes)
742
- return { themes: changed ? themes : previousThemes, changed }
743
- } catch {
744
- return undefined
745
- }
746
- }
747
-
748
- function withIndexedDbMutationLock<T>(name: string, operation: () => T): Promise<T> {
749
- const factory = globalThis.indexedDB
750
- if (!factory) return Promise.reject(new Error('IndexedDB is unavailable'))
751
-
752
- return new Promise<T>((resolve, reject) => {
753
- const open = factory.open(CUSTOM_THEME_LIBRARY_LOCK_DB, 1)
754
- open.addEventListener('upgradeneeded', () => {
755
- if (!open.result.objectStoreNames.contains(CUSTOM_THEME_LIBRARY_LOCK_STORE))
756
- open.result.createObjectStore(CUSTOM_THEME_LIBRARY_LOCK_STORE)
757
- })
758
- open.addEventListener('error', () =>
759
- reject(open.error ?? new Error('Could not open theme coordination database'))
760
- )
761
- open.addEventListener('success', () => {
762
- const database = open.result
763
- database.addEventListener('versionchange', () => database.close())
764
- let transaction: IDBTransaction
765
- try {
766
- transaction = database.transaction(CUSTOM_THEME_LIBRARY_LOCK_STORE, 'readwrite')
767
- } catch (error) {
768
- database.close()
769
- reject(error)
770
- return
771
- }
772
-
773
- let result: T
774
- let ran = false
775
- let operationError: unknown
776
- const close = () => database.close()
777
- transaction.addEventListener('complete', () => {
778
- close()
779
- if (operationError !== undefined) reject(operationError)
780
- else if (ran) resolve(result)
781
- else reject(new Error('Theme library lock transaction did not run'))
782
- })
783
- transaction.addEventListener('abort', () => {
784
- close()
785
- // This transaction is only the cross-context mutex; it does not store
786
- // application data. If the synchronous critical section completed, it
787
- // already verified the localStorage result before the abort event could
788
- // run. Report that result rather than claiming the persisted mutation
789
- // failed after it and its notifications have already committed.
790
- if (ran) {
791
- resolve(result)
792
- return
793
- }
794
- reject(
795
- operationError ?? transaction.error ?? new Error('Theme library lock transaction aborted')
796
- )
797
- })
798
-
799
- try {
800
- const lockRequest = transaction.objectStore(CUSTOM_THEME_LIBRARY_LOCK_STORE).get(name)
801
- lockRequest.addEventListener('success', () => {
802
- try {
803
- // Keep the read/write transaction active while the synchronous localStorage
804
- // read/modify/write runs. IndexedDB serializes overlapping transactions
805
- // across WebViews even where their Web Lock managers are not shared.
806
- result = operation()
807
- ran = true
808
- } catch (error) {
809
- operationError = error
810
- transaction.abort()
811
- }
812
- })
813
- } catch (error) {
814
- operationError = error
815
- transaction.abort()
816
- }
817
- })
818
- })
819
- }
820
-
821
- function browserThemeLibraryAtomicLock(): ThemeLibraryAtomicLock | undefined {
822
- if (!globalThis.indexedDB) return undefined
823
- const locks = globalThis.navigator?.locks
824
- return {
825
- withExclusiveLock: (name, operation) =>
826
- locks && typeof locks.request === 'function'
827
- ? locks.request(name, { mode: 'exclusive' }, () =>
828
- withIndexedDbMutationLock(name, operation)
829
- )
830
- : withIndexedDbMutationLock(name, operation),
831
- }
832
- }
833
-
834
- function mutationFailure<T>(
835
- reason: ThemeLibraryMutationFailureReason,
836
- error: string
837
- ): ThemeLibraryMutationResult<T> {
838
- return { ok: false, reason, error }
839
- }
840
-
841
- /**
842
- * Coordinate a storage-backed library read/modify/write across cooperating contexts.
843
- * The callback reads the current v1 record while holding an origin-wide IndexedDB
844
- * read/write transaction (and a Web Lock where available), then writes and verifies
845
- * the v1 record before updating this tab's in-memory registry. Older builds and
846
- * direct `setCustomThemes` storage writes do not acquire these locks and can still
847
- * race; this API does not claim cross-version atomicity. If IndexedDB is unavailable,
848
- * durable mutations fail closed.
849
- */
850
- export async function mutateCustomThemeLibrary<T>(
851
- storage: AppearanceStorage | undefined,
852
- update: (themes: readonly CustomThemeStored[]) => ThemeLibraryMutation<T>,
853
- options: ThemeLibraryMutationOptions = {}
854
- ): Promise<ThemeLibraryMutationResult<T>> {
855
- if (!storage) {
856
- try {
857
- const mutation = update(library().themes)
858
- if (mutation.commit === false) return { ok: true, committed: false, value: mutation.value }
859
- const safe = namespaceCustomThemes(mutation.themes)
860
- if (!setCustomThemes(safe, undefined))
861
- return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
862
- return { ok: true, committed: true, value: mutation.value }
863
- } catch {
864
- return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
865
- }
866
- }
867
-
868
- const lock = options.lock === undefined ? browserThemeLibraryAtomicLock() : options.lock
869
- if (!lock) return mutationFailure('atomic_unavailable', CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE)
870
-
871
- let enteredLock = false
872
- try {
873
- return await lock.withExclusiveLock(CUSTOM_THEME_LIBRARY_LOCK_NAME, () => {
874
- enteredLock = true
875
- const state = library()
876
- state.atomicMutationDepth = (state.atomicMutationDepth ?? 0) + 1
877
- try {
878
- let raw: string | null
879
- let themes: readonly CustomThemeStored[]
880
- try {
881
- raw = storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY)
882
- const parsed = raw ? parseLibrary(raw) : { themes: [] as CustomThemeStored[] }
883
- themes = parsed.themes
884
- if (raw && parsed.reason && !preserveLibrary(storage, raw, parsed.reason))
885
- return mutationFailure(
886
- 'recovery_unavailable',
887
- 'The stored theme library could not be preserved, so this change was not saved.'
888
- )
889
- // Detect synchronous/reentrant adapters that change the record while it
890
- // is read. The shared lock covers current builds; this check also exposes
891
- // adapters and old clients that bypass it without claiming a CAS.
892
- if (storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY) !== raw)
893
- return mutationFailure(
894
- 'changed_during_mutation',
895
- 'The theme library changed while it was being read. Try again.'
896
- )
897
- } catch {
898
- return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
899
- }
900
-
901
- let mutation: ThemeLibraryMutation<T>
902
- try {
903
- mutation = update(themes)
904
- // The updater is synchronous, but an older build can still write
905
- // localStorage outside this lock while the callback runs. Recheck before
906
- // committing so a snapshot changed during update is not overwritten.
907
- if (storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY) !== raw)
908
- return mutationFailure(
909
- 'changed_during_mutation',
910
- 'The theme library changed while this change was being prepared. Try again.'
911
- )
912
- } catch {
913
- return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
914
- }
915
- if (mutation.commit === false) return { ok: true, committed: false, value: mutation.value }
916
-
917
- const safe = namespaceCustomThemes(mutation.themes)
918
- const serialized = JSON.stringify({ version: CUSTOM_THEME_LIBRARY_VERSION, themes: safe })
919
- try {
920
- storage.setItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY, serialized)
921
- if (storage.getItem(CUSTOM_THEME_LIBRARY_STORAGE_KEY) !== serialized)
922
- return mutationFailure(
923
- 'changed_during_mutation',
924
- 'The theme library changed while it was being saved. Try again.'
925
- )
926
- } catch {
927
- return mutationFailure('storage_failed', CUSTOM_THEME_LIBRARY_MUTATION_FAILED)
928
- }
929
-
930
- replaceThemes(safe)
931
- notifyCustomThemes()
932
- return { ok: true, committed: true, value: mutation.value }
933
- } finally {
934
- state.atomicMutationDepth = Math.max(0, (state.atomicMutationDepth ?? 1) - 1)
935
- }
936
- })
937
- } catch {
938
- return mutationFailure(
939
- enteredLock ? 'storage_failed' : 'atomic_unavailable',
940
- enteredLock ? CUSTOM_THEME_LIBRARY_MUTATION_FAILED : CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE
941
- )
942
- }
943
- }
944
-
945
- /** Remove from the latest persisted snapshot, not a possibly stale UI snapshot. */
946
- export async function removeCustomThemeAtomically(
947
- id: string,
948
- storage: AppearanceStorage | undefined,
949
- options: ThemeLibraryMutationOptions = {}
950
- ): Promise<ThemeLibraryMutationResult<boolean>> {
951
- return mutateCustomThemeLibrary(
952
- storage,
953
- (themes) => {
954
- const remaining = themes.filter((theme) => theme.id !== id)
955
- return {
956
- themes: remaining,
957
- value: true,
958
- // Removing an already-removed id is a successful idempotent operation.
959
- commit: remaining.length !== themes.length,
960
- }
961
- },
962
- options
963
- )
964
- }
965
-
966
- /**
967
- * Synchronous legacy removal for the in-memory library. Passing storage fails closed;
968
- * use `removeCustomThemeAtomically` for persisted removals.
969
- *
970
- * @deprecated Use `removeCustomThemeAtomically` for persisted removals.
971
- */
972
- export function removeCustomTheme(id: string, storage: AppearanceStorage | undefined): boolean {
973
- if (storage) return false
974
- const themes = library().themes
975
- return setCustomThemes(
976
- themes.filter((theme) => theme.id !== id),
977
- storage
978
- )
979
- }
24
+ export {
25
+ CUSTOM_THEME_LIBRARY_LOCK_NAME,
26
+ CUSTOM_THEME_ATOMIC_STORAGE_UNAVAILABLE,
27
+ CUSTOM_THEME_LIBRARY_MUTATION_FAILED,
28
+ mutateCustomThemeLibrary,
29
+ removeCustomThemeAtomically,
30
+ } from './theme-library-mutation'
31
+ export type {
32
+ ThemeLibraryAtomicLock,
33
+ ThemeLibraryMutationOptions,
34
+ ThemeLibraryMutation,
35
+ ThemeLibraryMutationFailureReason,
36
+ ThemeLibraryMutationResult,
37
+ } from './theme-library-mutation'
38
+ export {
39
+ validateThemeRegistry,
40
+ flatVariantTokens,
41
+ storedVariantRecord,
42
+ toUiVariant,
43
+ } from './theme-library-schema'
44
+ export type {
45
+ StoredThemeAppearance,
46
+ StoredThemeTerminal,
47
+ StoredThemeEditorRoles,
48
+ StoredThemeChartRoles,
49
+ StoredThemeColors,
50
+ StoredThemeVariant,
51
+ CustomThemeStored,
52
+ ValidationIssue,
53
+ } from './theme-library-schema'
54
+ export {
55
+ CUSTOM_THEME_LIBRARY_STORAGE_KEY,
56
+ CUSTOM_THEME_LIBRARY_RECOVERY_KEY,
57
+ customThemeVariants,
58
+ customThemeVariantById,
59
+ customUiVariants,
60
+ subscribeCustomThemes,
61
+ setCustomThemes,
62
+ readCustomThemeLibrary,
63
+ removeCustomTheme,
64
+ } from './theme-library-store'
65
+ export type { AppearanceStorage } from './theme-library-store'