command_tower 0.21.1 → 0.22.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 (65) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/concerns/command_tower/execution/http_boundary.rb +2 -1
  3. data/docs/api_reference.md +7 -3
  4. data/docs/bootstrap/11-auth-client-path.md +2 -0
  5. data/docs/extending.md +1 -1
  6. data/docs/messaging_integration_guide.md +2 -0
  7. data/docs/ui.md +138 -0
  8. data/docs/upgrades/0.22.0.md +29 -0
  9. data/docs/upgrades/README.md +1 -0
  10. data/lib/command_tower/configuration/config.rb +6 -0
  11. data/lib/command_tower/configuration/ui/config.rb +47 -0
  12. data/lib/command_tower/current.rb +1 -0
  13. data/lib/command_tower/execution.rb +2 -1
  14. data/lib/command_tower/ui/builder/frame.rb +19 -0
  15. data/lib/command_tower/ui/builder/item_builder.rb +27 -0
  16. data/lib/command_tower/ui/builder/token_resolver.rb +54 -0
  17. data/lib/command_tower/ui/builder.rb +157 -0
  18. data/lib/command_tower/ui/catalog.rb +18 -0
  19. data/lib/command_tower/ui/composer.rb +45 -0
  20. data/lib/command_tower/ui/document.rb +167 -0
  21. data/lib/command_tower/ui/email/layout.rb +95 -0
  22. data/lib/command_tower/ui/email/renderer/containers.rb +72 -0
  23. data/lib/command_tower/ui/email/renderer/inline_nodes.rb +70 -0
  24. data/lib/command_tower/ui/email/renderer/styling.rb +91 -0
  25. data/lib/command_tower/ui/email/renderer/text_nodes.rb +78 -0
  26. data/lib/command_tower/ui/email/renderer.rb +89 -0
  27. data/lib/command_tower/ui/email/styles.rb +77 -0
  28. data/lib/command_tower/ui/fragment.rb +54 -0
  29. data/lib/command_tower/ui/fragments/cta_group.rb +60 -0
  30. data/lib/command_tower/ui/fragments/fact_row.rb +20 -0
  31. data/lib/command_tower/ui/fragments/facts.rb +35 -0
  32. data/lib/command_tower/ui/fragments/header.rb +51 -0
  33. data/lib/command_tower/ui/fragments/notice_frame.rb +36 -0
  34. data/lib/command_tower/ui/hardening.rb +73 -0
  35. data/lib/command_tower/ui/hostname.rb +124 -0
  36. data/lib/command_tower/ui/legacy_mapping.rb +66 -0
  37. data/lib/command_tower/ui/limits.rb +19 -0
  38. data/lib/command_tower/ui/nodes/action.rb +53 -0
  39. data/lib/command_tower/ui/nodes/avatar.rb +35 -0
  40. data/lib/command_tower/ui/nodes/badge.rb +17 -0
  41. data/lib/command_tower/ui/nodes/banner.rb +17 -0
  42. data/lib/command_tower/ui/nodes/base.rb +125 -0
  43. data/lib/command_tower/ui/nodes/button.rb +34 -0
  44. data/lib/command_tower/ui/nodes/card.rb +19 -0
  45. data/lib/command_tower/ui/nodes/code.rb +28 -0
  46. data/lib/command_tower/ui/nodes/component.rb +39 -0
  47. data/lib/command_tower/ui/nodes/divider.rb +11 -0
  48. data/lib/command_tower/ui/nodes/facts.rb +14 -0
  49. data/lib/command_tower/ui/nodes/image.rb +41 -0
  50. data/lib/command_tower/ui/nodes/instant.rb +59 -0
  51. data/lib/command_tower/ui/nodes/key_value.rb +63 -0
  52. data/lib/command_tower/ui/nodes/span.rb +76 -0
  53. data/lib/command_tower/ui/nodes/stack.rb +24 -0
  54. data/lib/command_tower/ui/nodes/stat_tile.rb +20 -0
  55. data/lib/command_tower/ui/nodes/text.rb +24 -0
  56. data/lib/command_tower/ui/text_derivation.rb +89 -0
  57. data/lib/command_tower/ui/time_formatter.rb +59 -0
  58. data/lib/command_tower/ui/tokens/ui_token_mapping.json +277 -0
  59. data/lib/command_tower/ui/tokens.rb +56 -0
  60. data/lib/command_tower/ui/zone_abbreviation.rb +130 -0
  61. data/lib/command_tower/ui.rb +80 -0
  62. data/lib/command_tower/version.rb +1 -1
  63. data/lib/command_tower.rb +1 -0
  64. data/lib/tasks/ui.rake +16 -0
  65. metadata +67 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e1ec5ece1df40809d27f2276a4ed623358bef299302dc4b0e9fec217fb58e499
4
- data.tar.gz: 3b716c7813bd43b129339455b6651a8cce6f98e35e51e4f1665bbd482c3d9323
3
+ metadata.gz: 975edf68bda972a251cc1049d1c7fe3046f98cc3c2407cd2a9389742bff78f56
4
+ data.tar.gz: ad2fa525b22b80ab6a3d6ca061831cf301e59d849367ae3ef017845ce0112944
5
5
  SHA512:
6
- metadata.gz: a3d01feb54c9298ca4802a72c8db5e958622bc98e3558dda7814fba3f212fc655d8401931a5d1bf517d07ca8786b7bfe6f5fa4e8388510c337c914d49f8a7fce
7
- data.tar.gz: 4d2dd6b3f0a6d84e92526e00d77211cd3464e3fe86cf41f52bff46ce098638c7044b033fb3cdd0b3a8977bd5da89497563a5890a0001044eb614a9c18b8435ad
6
+ metadata.gz: 4eb44a6051918263a36b5a69fff6d9fa2d63a99e138d47a2c5a376eef6f167aff82d574eba032fa5f29a075482b846f781398afaeafe21359783780f49ab7613
7
+ data.tar.gz: '00880332ea7d67fb1b6f6f96f95304335f690df9d609416e0f8ca52338a6993296c442da936b83e270307d557b472da3b67b536c5c9739dc5bbab3d95e3dbcaf'
@@ -18,7 +18,8 @@ module CommandTower
18
18
  request_id:,
19
19
  correlation_id: request_id,
20
20
  remote_ip: request.remote_ip,
21
- user_agent: request.user_agent
21
+ user_agent: request.user_agent,
22
+ ui_catalog: CommandTower::UI::Catalog.from_header(request.headers["X-UI-Catalog"])
22
23
  ) do
23
24
  yield
24
25
  record_impersonation_activity_if_needed
@@ -353,10 +353,14 @@ Pagination for list: query `limit` (default **50**, max **100**), `offset` (defa
353
353
 
354
354
  | Block | Fields | Notes |
355
355
  |-------|--------|-------|
356
- | `paragraph` | `text` (string) | |
357
- | `cta` | `label` (string), `href` (string) | `href` must be `http(s)` or a custom scheme (e.g. `pickem://...`); `javascript:`/`data:`/`vbscript:`, schemeless, blank, and unparsable hrefs are rejected — the `cta` block is simply omitted, never an error |
356
+ | `paragraph` | `text` (string) | Blank text adds no block |
357
+ | `cta` | `label` (string), `destination` (object) | `destination` is `{ kind: "internal", path }` (starts with `/`, not `//`) or `{ kind: "external", href }` (any scheme except `javascript:`/`data:`/`vbscript:`; schemeless, blank, and unparsable hrefs are rejected). A `cta` with no valid destination is omitted, never an error. Blank `label` becomes `"Open"`. |
358
+ | `instant` | `at` (string) | ISO-8601 UTC. Input without an explicit offset adds no block. |
359
+ | `presentation` | `key` (string), `variant` (string or null) | Names a registered presentation capability; its data is composed after authoring. |
358
360
 
359
- Generic (default) rendering: one `paragraph` block from `communication.body` (omitted if blank — `blocks` can legitimately be `[]`), plus one `cta` block if `metadata.deep_link` is a safe href (label from `metadata.cta_label`, default `"Open"`).
361
+ Generic (default) rendering: one `paragraph` block from `communication.body` (omitted if blank — `blocks` can legitimately be `[]`), plus one `cta` block if `metadata.deep_link` is a safe destination (label from `metadata.cta_label`, default `"Open"`).
362
+
363
+ **`X-UI-Catalog` request header:** accepted on every request (CommandTower reads it in the HTTP boundary). Missing or invalid values mean `1`; it has no effect on any response yet, including Inbox bodies. See [ui.md](ui.md#catalog-header).
360
364
 
361
365
  Hosts may override the document per `notificationTypeKey` with an `inbox_document.json.erb` view at `app/views/command_tower/messaging/rendering/<notification_type_key>/inbox_document.json.erb` (same lookup convention as [`messaging_integration_guide.md`](messaging_integration_guide.md#rendering-template-overrides)). Any failure resolving or rendering that template (missing file, malformed JSON, wrong `schema`/`blocks` shape, or a raising template) fails open to the generic document — the Inbox read path never 500s on a bad type template. A valid envelope with one invalid/unknown block strips only that block; if stripping empties `blocks`, the generic document is used instead.
362
366
 
@@ -48,6 +48,8 @@ Rails.application.config.middleware.insert_before 0, Rack::Cors do
48
48
  end
49
49
  ```
50
50
 
51
+ `headers: :any` already covers the `X-UI-Catalog` request header. A host that lists allowed headers explicitly must add `X-UI-Catalog`.
52
+
51
53
  `credentials: true` requires an **explicit origin list**, not `*`. Compose already passes `CORS_ALLOWED_ORIGINS` from step 01. The sample origins `8081`, `8082`, and `19006` belong to one web product. Add the origin this Expo web app actually uses, and keep it aligned with `config.application.url` and the API’s published port.
52
54
 
53
55
  Attaching a Command Tower frontend: [Local FE↔BE join](../../../artifacts/COMMANDTOWER_LOCAL_JOIN.md).
data/docs/extending.md CHANGED
@@ -4,7 +4,7 @@ How hosts customize and integrate with CommandTower **without forking platform i
4
4
 
5
5
  **New host?** Start with [Bootstrap a new host](bootstrap/README.md).
6
6
 
7
- Layer map: [architecture.md](architecture.md). Install/configure/migrate/doctor: [initializing.md](initializing.md). Testing API: [testing.md](testing.md). HTTP catalog: [api_reference.md](api_reference.md).
7
+ Layer map: [architecture.md](architecture.md). Install/configure/migrate/doctor: [initializing.md](initializing.md). Testing API: [testing.md](testing.md). HTTP catalog: [api_reference.md](api_reference.md). Server-driven UI documents: [ui.md](ui.md).
8
8
 
9
9
  ## What hosts should extend
10
10
 
@@ -106,6 +106,8 @@ This override has **no generic ERB fallback file** — the generic Inbox documen
106
106
  | Bulk | `POST /me/inbox/bulk/{read,unread,archive,restore,delete}` with body `ids` |
107
107
  | Unread | `GET /me/inbox/unread-count` |
108
108
 
109
+ Detail `content` is `inbox_document_v1` with blocks `paragraph`, `cta` (typed `destination`: internal `path` or external `href`), `instant`, and `presentation`. The `X-UI-Catalog` request header is accepted and defaults to `1`; it has no effect on Inbox responses yet ([ui.md](ui.md#catalog-header)).
110
+
109
111
  Pagination detail: [pagination.md](pagination.md). Full catalog: [api_reference.md](api_reference.md#me-inbox).
110
112
 
111
113
  ## Host responsibilities
data/docs/ui.md ADDED
@@ -0,0 +1,138 @@
1
+ # Server-driven UI documents
2
+
3
+ `CommandTower::UI` builds and validates `ui_document` trees in pure Ruby (no DB, no Messaging dependency). A document is a closed catalog of primitives, token enums, and one `textFallback` string. Nothing in the engine renders a `ui_document` to an HTTP response yet: the Inbox `content` field is still `inbox_document_v1` (see [api_reference.md](api_reference.md#me-inbox)). This guide covers authoring, limits, the email renderer, and the catalog header.
4
+
5
+ ## Primitives
6
+
7
+ The Builder has one method per catalog primitive. Nodes live in `lib/command_tower/ui/nodes/`.
8
+
9
+ | Primitive | Purpose |
10
+ |-----------|---------|
11
+ | `stack` | Vertical container (`gap`, `align`). There is no row or direction. |
12
+ | `card` | Container with `surface`, `tone`, `padding`. |
13
+ | `facts` | Container for a fact block. |
14
+ | `divider` | Rule. |
15
+ | `text` | Spans (plain, `strong`, `link`) with `variant`, `textTone`, `maxLines`. |
16
+ | `time` (`instant`) | An instant rendered per viewer or by the server formatter. |
17
+ | `key_value` | Labelled items; `time` inside returns a node used as an item value. |
18
+ | `badge` | Short label with a `tone`. |
19
+ | `button` | Label plus a `navigate` action; `variant`: primary, secondary, ghost. |
20
+ | `image` | `https` only, host must be in `config.ui.image_hosts`; `alt` required unless `decorative`; `aspect` required. |
21
+ | `banner` | Spans with optional title and `tone`. |
22
+ | `avatar` | `src` or `initials`, size sm, md, lg. |
23
+ | `stat_tile` | Value and label. |
24
+ | `code` | Sensitive value (`qr` or `text`). Never reaches derived text, legacy mapping, email, `inspect` or validation errors. |
25
+ | `component` | Registered native component by `key`, with a required `fallback` tree. At most one per document. |
26
+
27
+ The `navigate` action takes exactly one destination: `path:` (internal, starts with `/`, not `//`) or `href:` (external: https, mailto, tel; no userinfo). Wire form: `{ type: "navigate", destination: { kind: "internal", path } | { kind: "external", href } }`.
28
+
29
+ ## Tokens
30
+
31
+ Enums are in `CommandTower::UI::Tokens`; the design mapping (spacing px, type steps, tone palette keys, tint alphas, avatar px, zone abbreviations) is runtime data in `lib/command_tower/ui/tokens/ui_token_mapping.json`.
32
+
33
+ | Token | Values |
34
+ |-------|--------|
35
+ | `gap` | none, xs, sm, md, lg, xl |
36
+ | `tone` | neutral, accent, success, warning, danger |
37
+ | `textTone` | primary, secondary, muted, accent |
38
+ | `variant` (text) | display, heading_xl, heading_l, heading_m, title, subtitle, body, caption, overline, mono |
39
+ | `surface` | raised, tinted, plain |
40
+ | `align` | start, center, end, between |
41
+ | `avatar size` | sm, md, lg |
42
+
43
+ Rules worth knowing:
44
+
45
+ - **`stack.align`:** absent stretches children across the cross axis; `start`, `center`, `end` set cross-axis alignment; `between` is main-axis space-between. `badge` and `avatar` children always hug their content.
46
+ - **No warning, success or danger text tones.** `textTone` is limited to the four above because those three fail contrast as text. They remain valid as container, badge and banner `tone`.
47
+ - **Badge contrast caveat.** Badges are solid: white text on a solid tone fill. White on the solid success (green) badge is about 4.1:1 in light and 3.2:1 in dark, below the 4.5:1 text threshold, and the dark danger badge is also low. Do not rely on a badge to carry meaning alone; pair it with text or an icon. See the design contrast notes (states.md 8 A3).
48
+ - **Unknown tokens.** They raise `InvalidTokenError` in development and test. In production they fall back to the default and log the path.
49
+
50
+ ## Composing
51
+
52
+ Three layers, all by constant (there is no registry):
53
+
54
+ ```ruby
55
+ class ClassCanceled < CommandTower::UI::Composer
56
+ def compose(d, starts_at:)
57
+ d.card { |c| c.text "Class canceled" }
58
+ end
59
+ end
60
+
61
+ ClassCanceled.call(starts_at: time) # => CommandTower::UI::Document, validated
62
+ ```
63
+
64
+ - `UI.document(text_fallback:) { |d| ... }` builds a `Document` with exactly one root. It is not validated; call `validate!`.
65
+ - `Composer` (`lib/command_tower/ui/composer.rb`): implement `compose(d, **inputs)`; `.call` validates the tree, derives `textFallback` with `TextDerivation`, and validates again. Override `text_fallback(root, **inputs)` to supply your own string.
66
+ - `Fragment` (`lib/command_tower/ui/fragment.rb`): declare inputs with `attribute` and `validates`; `compose(b)` emits primitives. Use with `d.fragment(MyFragment, **inputs)`. Invalid inputs raise `InvalidFragmentError` with attribute names and codes only.
67
+
68
+ Validation errors (`InvalidDocumentError#details`) carry node paths and codes only, never values.
69
+
70
+ ## Fragment library
71
+
72
+ `CommandTower::UI::Fragments`:
73
+
74
+ | Fragment | Emits |
75
+ |----------|-------|
76
+ | `Header` | Vertical header: optional avatar and badge, then title and subtitle. |
77
+ | `FactRow` | One `key_value` with a single labelled string value. |
78
+ | `Facts` | Base class for a host fact block. `Facts.call(builder, metadata:)` emits exactly one `facts` node; subclasses implement `compose(b, metadata:)`. |
79
+ | `CtaGroup` | Stacked buttons: the primary first, then up to two secondaries. |
80
+ | `NoticeFrame` | Tinted card with a title and body paragraphs. Informational only. |
81
+
82
+ ## Time formatter and abbreviation rule
83
+
84
+ `TimeFormatter.call(at:, zone:, format:, label: :auto)` renders an instant for an IANA zone: en-US, 12-hour clock, no leading zeros, uppercase AM/PM, plain U+0020 separators.
85
+
86
+ | Format | Example pattern |
87
+ |--------|-----------------|
88
+ | `short` | `Mon, Nov 23, 4:05 PM` |
89
+ | `long` | `Monday, November 23, 2026 at 4:05 PM` |
90
+ | `date` | `Mon, Nov 23` (never labelled) |
91
+ | `time` | `4:05 PM` |
92
+ | `countdown` | App-only; the server renders it as `short`. |
93
+
94
+ On the server the zone label is always shown for every format except `date`, unless `label: :never`. The label comes from `ZoneAbbreviation` and the `zoneAbbreviations` / `ambiguousAbbreviations` / `tzdataVersion` data in the token mapping. Regenerate it inside Docker with the engine task `app:command_tower:ui:zone_abbreviations` (`YEAR=` pins the generation year).
95
+
96
+ ## Limits
97
+
98
+ `CommandTower::UI::Limits`, mirrored by `spec/fixtures/ui/wire_hardening.json` for the frontend normalizer:
99
+
100
+ | Limit | Value |
101
+ |-------|-------|
102
+ | Nodes | 200 |
103
+ | Depth | 8 |
104
+ | Serialized bytes | 64 KiB |
105
+ | String length | 2,000 |
106
+ | `textFallback` length | 8,000 |
107
+ | Spans per text | 50 |
108
+ | `key_value` items | 50 |
109
+ | Nodes in `facts` | 100 |
110
+
111
+ Paths and links are hardened by `Hardening` (shared cases in `wire_hardening.json`); rejections return codes, never the rejected value.
112
+
113
+ ## Email renderer
114
+
115
+ `CommandTower::UI::Email::Renderer.call(document, palette:, origin:, **chrome)` returns `Output(html, text)`: table-based, inline-styled HTML plus a plain-text part. Chrome keywords: `footer_html:` (trusted, escaped HTML), `app_name:`, `preheader:`.
116
+
117
+ - Escaping uses ActionView's TagHelper; document values are never interpolated into markup.
118
+ - `code` nodes raise `InvalidDocumentError` (a check-in code never reaches an email).
119
+ - Conversions: `component` becomes its fallback tree; internal `navigate` becomes `origin + path`; `countdown` becomes `short`; icons are dropped; a ghost button becomes an underlined link; image width and height derive from `aspect`.
120
+ - Text colour comes from `textTone`.
121
+ - **Set 2 needs an `EmailTheme` adapter.** The renderer takes a `palette:` from the caller; nothing adapts `CommandTower::EmailTheme::Resolver` output into that palette yet. A second palette set (Set 2) needs that adapter before it can be used.
122
+
123
+ ## Legacy mapping
124
+
125
+ `UI::LegacyMapping.call(document, legacy_presentation_keys: [])` maps a catalog-2 document to `inbox_document_v1` blocks through `InboxDocument.compose`: text to `paragraph`, button to `cta` with a typed destination (https, mailto, tel only), time to `instant`, a `component` whose key is in `legacy_presentation_keys` to `presentation`, containers by mapping children, other nodes to a derived-text paragraph or dropped, `code` always dropped. No caller uses it yet.
126
+
127
+ ## Catalog header
128
+
129
+ Clients send `X-UI-Catalog: <n>`. `UI::Catalog.from_header` returns `1` for a missing, blank, non-integer or non-positive value and clamps higher numbers to `UI::CATALOG` (currently `2`). `HttpBoundary` passes the result into `with_execution`, and it is available as `CommandTower::Current.ui_catalog` (default `1`; nested `with_execution` keeps the outer value).
130
+
131
+ It has no effect yet: no response differs by catalog, and it is never read for authorization. See [api_reference.md](api_reference.md#me-inbox) and the CORS note in [bootstrap/11-auth-client-path.md](bootstrap/11-auth-client-path.md).
132
+
133
+ ## Producer contracts
134
+
135
+ - **`textFallback` excludes `code`.** Derived text never includes a `code` value; an overriding `text_fallback` must not either.
136
+ - **QR needs a text alternative.** A `code` node with format `qr` must be paired by the producer with a way to read the same information without scanning (a `text` code, or labelled instructions). The engine does not add one.
137
+ - **Link text versus host.** Link text is producer-controlled and is not checked against the destination host. Do not show a trusted-looking hostname as link text for a different destination.
138
+ - **Image hosts are enforced server-side.** `image` and `avatar` `src` must be https on an exact host in `config.ui.image_hosts` (lowercased, IDN-normalized); anything else fails validation. Clients should not treat the allowlist as their only line of defence, but they are not expected to re-implement it.
@@ -0,0 +1,29 @@
1
+ # Upgrade: CommandTower 0.22.0
2
+
3
+ **From:** `0.21.1`
4
+ **To:** `0.22.0`
5
+
6
+ Minor release: adds the server-driven UI document library (`CommandTower::UI`) and reads the `X-UI-Catalog` request header into execution context. No HTTP response, route, or Inbox contract changes. Authoring reference: [ui.md](../ui.md).
7
+
8
+ ## Host-visible changes
9
+
10
+ | Change | Host impact |
11
+ |--------|-------------|
12
+ | `CommandTower::UI` | New pure-Ruby library: primitives, tokens, Builder DSL, `Composer`, `Fragment`, five platform fragments, `TimeFormatter`, `Limits`, `Hardening`, `LegacyMapping`, and `Email::Renderer`. Nothing calls it from the engine yet. |
13
+ | `config.ui.image_hosts` | Image and avatar `src` must be https on an exact host in this list when a document is validated. Only matters if the host builds documents. |
14
+ | `X-UI-Catalog` header | Parsed by the HTTP boundary (missing or invalid is `1`, higher numbers clamp to the engine catalog) into `CommandTower::Current.ui_catalog`. Nothing reads it for authorization or response shape. |
15
+ | `tzinfo` | Runtime dependency (`~> 2.0`) used by the time formatter. |
16
+
17
+ ## Host actions
18
+
19
+ 1. Bump gem to `0.22.0` (or `>= 0.22.0`).
20
+ 2. **No new migration.**
21
+ 3. If a host lists CORS `headers:` explicitly, add `X-UI-Catalog`. `headers: :any` already covers it. See [bootstrap step 11](../bootstrap/11-auth-client-path.md).
22
+ 4. Set `config.ui.image_hosts` only if the host will compose documents with images.
23
+
24
+ ## Not in this release
25
+
26
+ - No new HTTP routes.
27
+ - No change to Inbox `content` (`inbox_document_v1`); `GET /me/inbox` bodies are identical with and without `X-UI-Catalog`.
28
+ - `LegacyMapping` and the email renderer are not wired into messaging or any response.
29
+ - No authorization or RBAC changes.
@@ -4,6 +4,7 @@ Host-facing upgrade / change summaries for CommandTower releases.
4
4
 
5
5
  | Version | Summary |
6
6
  |---------|---------|
7
+ | [0.22.0](0.22.0.md) | Server-driven UI document library (`CommandTower::UI`), legacy mapping, email renderer; `X-UI-Catalog` header read into `Current.ui_catalog` (no behavior change) |
7
8
  | [0.21.0](0.21.0.md) | Notification preference reads: channel catalog, destinations, settings rows; PATCH merges onto stored member state |
8
9
  | [0.20.0](0.20.0.md) | Push delivery certainty: JSON `provider_metadata` caster; duplicate-averse push recovery and Expo submission guards |
9
10
  | [0.19.0](0.19.0.md) | Push presentation: badge, urgency, sound, deep links; Expo ticket and receipt metadata; preference urgency and sound |
@@ -22,6 +22,7 @@ require "command_tower/configuration/pagination/config"
22
22
  require "command_tower/configuration/password_recovery_session/config"
23
23
  require "command_tower/configuration/registry/config"
24
24
  require "command_tower/configuration/signup_session/config"
25
+ require "command_tower/configuration/ui/config"
25
26
  require "command_tower/configuration/user/config"
26
27
  require "command_tower/configuration/username/config"
27
28
 
@@ -135,6 +136,11 @@ module CommandTower
135
136
  allowed: Configuration::PasswordRecoverySession::Config,
136
137
  default: Configuration::PasswordRecoverySession::Config.new
137
138
 
139
+ add_composer :ui,
140
+ desc: "Server-driven UI document settings (default time zone, image host allowlist)",
141
+ allowed: Configuration::UI::Config,
142
+ default: Configuration::UI::Config.new
143
+
138
144
  # To be Deleted
139
145
  add_composer :otp,
140
146
  desc: "One Time Password generation is used for ease in quickly validating a users actions. This is good for short term validation requirements as opposed to UserSecrets",
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "tzinfo"
4
+ require "command_tower/ui/hostname"
5
+
6
+ module CommandTower
7
+ module Configuration
8
+ module UI
9
+ class Config < ::CommandTower::Configuration::Base
10
+ include ClassComposer::Generator
11
+
12
+ # Reads return exact hosts, lowercased and IDN (punycode) normalized.
13
+ module NormalizedImageHosts
14
+ def image_hosts
15
+ super.map { |host| ::CommandTower::UI::Hostname.normalize(host) }.uniq
16
+ end
17
+ end
18
+
19
+ ZONE_HELP = "Expected a TZInfo identifier such as America/Los_Angeles"
20
+ HOSTS_DESC = "Exact image hosts allowed for document image nodes (https only). " \
21
+ "Fail closed: empty allows no images. Hosts are lowercased and " \
22
+ "IDN-normalized; no schemes, ports, paths or wildcards"
23
+
24
+ add_composer(
25
+ :default_zone,
26
+ desc: "Default IANA time zone identifier for time nodes that do not name a zone",
27
+ allowed: String,
28
+ default: "UTC",
29
+ validator: ->(val) { TZInfo::Timezone.all_identifiers.include?(val) },
30
+ invalid_message: ->(val) { "Provided #{val.inspect}. #{ZONE_HELP}" }
31
+ )
32
+
33
+ add_composer(
34
+ :image_hosts,
35
+ desc: HOSTS_DESC,
36
+ allowed: Array,
37
+ default: [],
38
+ default_shown: "[]",
39
+ validator: ->(val) { val.none? { |host| ::CommandTower::UI::Hostname.normalize(host).nil? } },
40
+ invalid_message: ->(_val) { "Expected an Array of bare host names (no scheme, port, path or wildcard)" }
41
+ )
42
+
43
+ prepend NormalizedImageHosts
44
+ end
45
+ end
46
+ end
47
+ end
@@ -16,5 +16,6 @@ module CommandTower
16
16
  attribute :remote_ip
17
17
  attribute :user_agent
18
18
  attribute :client_compatibility_recommendation
19
+ attribute :ui_catalog, default: 1
19
20
  end
20
21
  end
@@ -91,7 +91,8 @@ module CommandTower
91
91
  impersonation_session_id: attrs[:impersonation_session_id],
92
92
  impersonation_activity_recorded: attrs.key?(:impersonation_activity_recorded) ? attrs[:impersonation_activity_recorded] : false,
93
93
  remote_ip: attrs[:remote_ip],
94
- user_agent: attrs[:user_agent]
94
+ user_agent: attrs[:user_agent],
95
+ ui_catalog: attrs.fetch(:ui_catalog, 1)
95
96
  }
96
97
 
97
98
  run = -> { Current.set(assigned, &block) }
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ class Builder
6
+ # A collection of nodes under construction and where it sits in the document.
7
+ Frame = Struct.new(:path, :kind, :nodes) do
8
+ def next_path
9
+ case kind
10
+ when :root then "root"
11
+ when :fallback then "#{path}.fallback"
12
+ else "#{path}.children[#{nodes.length}]"
13
+ end
14
+ end
15
+ end
16
+ private_constant :Frame
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ class Builder
6
+ # Collects `key_value` rows. `time` returns an Instant for use as a row
7
+ # value instead of adding it as a child.
8
+ class ItemBuilder
9
+ attr_reader :items
10
+
11
+ def initialize(builder, path)
12
+ @builder = builder
13
+ @path = path
14
+ @items = []
15
+ end
16
+
17
+ def item(label, value, icon: nil)
18
+ @items << { icon:, label:, value: }.compact
19
+ end
20
+
21
+ def time(**)
22
+ @builder.build_time("#{@path}.items[#{@items.length}].value", **)
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ class Builder
6
+ # Validates token arguments for a primitive. Unknown tokens raise
7
+ # InvalidTokenError in development and test. In production they fall back
8
+ # to the field's default and log the node path and a code only, never the
9
+ # value.
10
+ module TokenResolver
11
+ # Token fields per primitive: field => [allowed values, default].
12
+ FIELDS = {
13
+ stack: { gap: [Tokens::GAP, "md"], align: [Tokens::ALIGN, nil] },
14
+ card: { surface: [Tokens::SURFACE, "raised"], tone: [Tokens::TONE, nil], padding: [Tokens::GAP, "md"] },
15
+ text: { variant: [Tokens::VARIANT, "body"], text_tone: [Tokens::TEXT_TONE, "primary"] },
16
+ time: {
17
+ variant: [Tokens::VARIANT, "body"], text_tone: [Tokens::TEXT_TONE, "primary"],
18
+ format: [Nodes::Instant::FORMAT, "short"], label: [Nodes::Instant::LABEL, "auto"]
19
+ },
20
+ badge: { tone: [Tokens::TONE, "neutral"] },
21
+ button: { variant: [Tokens::BUTTON_VARIANT, "secondary"] },
22
+ image: { fit: [Nodes::Image::FIT, "cover"] },
23
+ banner: { tone: [Tokens::TONE, "neutral"] },
24
+ avatar: { size: [Tokens::AVATAR_SIZE, "md"] },
25
+ stat_tile: { tone: [Tokens::TONE, nil] },
26
+ code: { format: [Nodes::Code::FORMAT, nil] }
27
+ }.freeze
28
+
29
+ module_function
30
+
31
+ # Returns attributes with token values normalized to strings.
32
+ def call(type, node_path, attributes)
33
+ FIELDS.fetch(type, {}).each do |field, (allowed, default)|
34
+ next if attributes[field].nil?
35
+
36
+ field_path = "#{node_path}.#{field.to_s.camelize(:lower)}"
37
+ attributes[field] = resolve(attributes[field], allowed, default, field_path)
38
+ end
39
+ attributes
40
+ end
41
+
42
+ def resolve(value, allowed, default, field_path)
43
+ token = value.to_s
44
+ return token if allowed.include?(token)
45
+
46
+ raise InvalidTokenError, "unknown token at #{field_path}" if Rails.env.local?
47
+
48
+ Rails.logger.warn { "[CommandTower::UI::Builder] #{field_path}: unknown_token, using default" }
49
+ default
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "command_tower/ui/builder/frame"
4
+ require "command_tower/ui/builder/token_resolver"
5
+ require "command_tower/ui/builder/item_builder"
6
+
7
+ module CommandTower
8
+ module UI
9
+ # Block DSL that builds node objects. One method per catalog primitive.
10
+ #
11
+ # UI.document(text_fallback: "Class canceled") do |d|
12
+ # d.stack(gap: :lg) do |s|
13
+ # s.text("Class ", d.strong("canceled"), variant: :heading_m)
14
+ # s.key_value { |kv| kv.item "When", kv.time(at: starts_at, zone: "America/Los_Angeles") }
15
+ # s.button "View classes", action: d.navigate(path: "/classes"), variant: :primary
16
+ # end
17
+ # end
18
+ #
19
+ # Block forms yield the builder itself; children are collected in order.
20
+ # `time` inside `key_value` returns the node for use as an item value
21
+ # instead of adding it as a child.
22
+ #
23
+ # Token arguments (gap, tone, variant, ...) accept symbols or strings; see
24
+ # TokenResolver for the unknown-token policy.
25
+ #
26
+ # Out of scope: markdown and any registry (design D3).
27
+ class Builder
28
+ def initialize
29
+ @frames = [Frame.new("root", :root, [])]
30
+ end
31
+
32
+ # Nodes added at the top level (a document wants exactly one).
33
+ def roots
34
+ @frames.first.nodes
35
+ end
36
+
37
+ def stack(gap: nil, align: nil, &)
38
+ container(:stack, Nodes::Stack, { gap:, align: }, &)
39
+ end
40
+
41
+ def card(surface: nil, tone: nil, padding: nil, &)
42
+ container(:card, Nodes::Card, { surface:, tone:, padding: }, &)
43
+ end
44
+
45
+ def facts(&)
46
+ container(:facts, Nodes::Facts, {}, &)
47
+ end
48
+
49
+ def divider
50
+ leaf(:divider, Nodes::Divider, {})
51
+ end
52
+
53
+ def text(*spans, variant: nil, text_tone: nil, max_lines: nil)
54
+ leaf(:text, Nodes::Text, { variant:, text_tone:, max_lines:, spans: spans.flatten })
55
+ end
56
+
57
+ def time(**)
58
+ place(build_time(@frames.last.next_path, **))
59
+ end
60
+
61
+ def key_value(&)
62
+ node_path = @frames.last.next_path
63
+ rows = ItemBuilder.new(self, node_path)
64
+ yield rows
65
+ place(build(:key_value, Nodes::KeyValue, node_path, { items: rows.items }))
66
+ end
67
+
68
+ def badge(label, tone: nil)
69
+ leaf(:badge, Nodes::Badge, { label:, tone: })
70
+ end
71
+
72
+ def button(label, action:, variant: nil)
73
+ leaf(:button, Nodes::Button, { label:, action:, variant: })
74
+ end
75
+
76
+ def image(src:, aspect:, **options)
77
+ leaf(:image, Nodes::Image, { src:, aspect: }.merge(options))
78
+ end
79
+
80
+ def banner(*spans, title: nil, tone: nil)
81
+ leaf(:banner, Nodes::Banner, { title:, tone:, spans: spans.flatten })
82
+ end
83
+
84
+ def avatar(src: nil, initials: nil, alt: nil, size: nil)
85
+ leaf(:avatar, Nodes::Avatar, { src:, initials:, alt:, size: })
86
+ end
87
+
88
+ def stat_tile(value:, label:, tone: nil, icon: nil)
89
+ leaf(:stat_tile, Nodes::StatTile, { value:, label:, tone:, icon: })
90
+ end
91
+
92
+ def code(value:, label:, format:)
93
+ leaf(:code, Nodes::Code, { value:, label:, format: })
94
+ end
95
+
96
+ # `fallback` is built by the block, which must add exactly one node.
97
+ def component(key:, variant: nil, data: {}, &)
98
+ node_path = @frames.last.next_path
99
+ fallback = collect(Frame.new(node_path, :fallback, []), &).first
100
+ place(build(:component, Nodes::Component, node_path, { key:, variant:, data:, fallback: }))
101
+ end
102
+
103
+ # Expands a fragment into primitives at this point. A fragment is any
104
+ # class whose instances respond to `compose(builder)`.
105
+ def fragment(klass, **args)
106
+ klass.new(**args).compose(self)
107
+ end
108
+
109
+ def navigate(path: nil, href: nil)
110
+ Nodes::Action::Navigate.new(path:, href:)
111
+ end
112
+
113
+ def strong(text)
114
+ Nodes::Span.new(text:, strong: true)
115
+ end
116
+
117
+ def link(text, action:)
118
+ Nodes::Span.link(text, action:)
119
+ end
120
+
121
+ # Builds an Instant without placing it (also used by ItemBuilder#time).
122
+ def build_time(node_path, **attributes)
123
+ attributes = { zone: CommandTower.config.ui.default_zone }.merge(attributes)
124
+ build(:time, Nodes::Instant, node_path, attributes)
125
+ end
126
+
127
+ private
128
+
129
+ def container(type, klass, attributes, &)
130
+ node_path = @frames.last.next_path
131
+ children = collect(Frame.new(node_path, :children, []), &)
132
+ place(build(type, klass, node_path, attributes.merge(children:)))
133
+ end
134
+
135
+ def leaf(type, klass, attributes)
136
+ place(build(type, klass, @frames.last.next_path, attributes))
137
+ end
138
+
139
+ def place(node)
140
+ @frames.last.nodes << node
141
+ node
142
+ end
143
+
144
+ def collect(frame)
145
+ @frames.push(frame)
146
+ yield self
147
+ frame.nodes
148
+ ensure
149
+ @frames.pop
150
+ end
151
+
152
+ def build(type, klass, node_path, attributes)
153
+ klass.new(**TokenResolver.call(type, node_path, attributes).compact)
154
+ end
155
+ end
156
+ end
157
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module UI
5
+ module Catalog
6
+ # Parses the X-UI-Catalog request header. Missing, blank, non-integer or
7
+ # non-positive gives 1; a higher number is clamped to CATALOG.
8
+ def self.from_header(value)
9
+ return 1 unless /\A\s*\d+\s*\z/.match?(value.to_s)
10
+
11
+ parsed = value.to_s.strip.to_i
12
+ return 1 if parsed <= 0
13
+
14
+ [parsed, CommandTower::UI::CATALOG].min
15
+ end
16
+ end
17
+ end
18
+ end