emailengine-app 2.77.0 → 2.79.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 (189) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.ncurc.js +23 -13
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +60 -0
  5. package/bin/emailengine.js +1 -1
  6. package/config/e2e.toml +2 -1
  7. package/config/test.toml +2 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +1 -1
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +145 -61
  12. package/lib/api-reference/format.js +105 -4
  13. package/lib/api-reference/index.js +24 -7
  14. package/lib/api-reference/model.js +148 -21
  15. package/lib/api-reference/schema-tree.js +282 -28
  16. package/lib/api-routes/account-routes.js +99 -36
  17. package/lib/api-routes/behavior-notes.js +3 -0
  18. package/lib/api-routes/blocklist-routes.js +21 -47
  19. package/lib/api-routes/chat-routes.js +10 -12
  20. package/lib/api-routes/delivery-test-routes.js +6 -26
  21. package/lib/api-routes/export-routes.js +2 -0
  22. package/lib/api-routes/gateway-routes.js +52 -11
  23. package/lib/api-routes/license-routes.js +2 -0
  24. package/lib/api-routes/mailbox-routes.js +29 -26
  25. package/lib/api-routes/message-routes.js +27 -21
  26. package/lib/api-routes/oauth2-app-routes.js +11 -29
  27. package/lib/api-routes/operation-impact.js +80 -0
  28. package/lib/api-routes/outbox-routes.js +15 -5
  29. package/lib/api-routes/permission-map.js +397 -0
  30. package/lib/api-routes/route-helpers.js +223 -9
  31. package/lib/api-routes/route-metadata.js +28 -0
  32. package/lib/api-routes/settings-routes.js +30 -25
  33. package/lib/api-routes/stats-routes.js +2 -2
  34. package/lib/api-routes/submit-routes.js +53 -31
  35. package/lib/api-routes/template-routes.js +3 -0
  36. package/lib/api-routes/token-routes.js +319 -33
  37. package/lib/api-routes/webhook-route-routes.js +14 -4
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/auth-token.js +80 -8
  41. package/lib/autodetect-imap-settings.js +40 -16
  42. package/lib/base32.js +30 -0
  43. package/lib/bounce-detect.js +182 -62
  44. package/lib/consts.js +10 -0
  45. package/lib/db.js +20 -2
  46. package/lib/delivery-error.js +30 -1
  47. package/lib/egress-filter.js +89 -8
  48. package/lib/email-client/base-client.js +35 -113
  49. package/lib/email-client/gmail-client.js +22 -13
  50. package/lib/email-client/imap/listing-diff.js +3 -3
  51. package/lib/email-client/imap/mailbox.js +28 -93
  52. package/lib/email-client/imap/subconnection.js +10 -7
  53. package/lib/email-client/imap/sync-operations.js +46 -46
  54. package/lib/email-client/imap-client.js +39 -28
  55. package/lib/email-client/message-builder.js +15 -15
  56. package/lib/email-client/notification-handler.js +1 -1
  57. package/lib/email-client/outlook/graph-api.js +10 -4
  58. package/lib/email-client/outlook-client.js +54 -55
  59. package/lib/email-client/smtp-pool-manager.js +1 -1
  60. package/lib/enum-descriptions.js +92 -2
  61. package/lib/export.js +2 -2
  62. package/lib/field-usage.js +133 -0
  63. package/lib/gateway.js +2 -2
  64. package/lib/get-raw-email.js +1 -1
  65. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  66. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  67. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  68. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  69. package/lib/imapproxy/imap-core/lib/imap-connection.js +17 -7
  70. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  71. package/lib/imapproxy/imap-server.js +40 -10
  72. package/lib/license-beacon.js +5 -10
  73. package/lib/lists.js +49 -1
  74. package/lib/llm-pre-process.js +6 -6
  75. package/lib/logger.js +5 -1
  76. package/lib/metrics-collector.js +2 -2
  77. package/lib/msgpack.js +62 -0
  78. package/lib/oauth/decode-jwt-payload.js +39 -0
  79. package/lib/oauth/gmail.js +9 -12
  80. package/lib/oauth/mail-ru.js +5 -7
  81. package/lib/oauth/outlook-identity.js +61 -0
  82. package/lib/oauth/outlook.js +9 -9
  83. package/lib/oauth/pubsub/google.js +25 -10
  84. package/lib/oauth/retry-setup.js +38 -0
  85. package/lib/oauth/scope-checker.js +1 -1
  86. package/lib/oauth2-apps.js +224 -295
  87. package/lib/openapi/build-document.js +15 -7
  88. package/lib/openapi/joi-schema.js +20 -0
  89. package/lib/outbox.js +145 -14
  90. package/lib/pre-process.js +9 -9
  91. package/lib/queue-stats.js +49 -0
  92. package/lib/read-env-value.js +37 -0
  93. package/lib/reconnection-manager.js +2 -2
  94. package/lib/rewrite-text-nodes.js +4 -3
  95. package/lib/routes-ui.js +4 -0
  96. package/lib/schemas.js +223 -155
  97. package/lib/settings.js +84 -5
  98. package/lib/sub-script.js +2 -1
  99. package/lib/swagger-options.js +2 -1
  100. package/lib/templates.js +5 -5
  101. package/lib/threads.js +2 -2
  102. package/lib/token-audit-log.js +208 -0
  103. package/lib/token-permission-view.js +219 -0
  104. package/lib/token-permissions.js +172 -0
  105. package/lib/tokens.js +100 -16
  106. package/lib/tools.js +259 -85
  107. package/lib/totp.js +67 -0
  108. package/lib/ui-routes/account-routes.js +122 -26
  109. package/lib/ui-routes/admin-config-routes.js +20 -17
  110. package/lib/ui-routes/admin-entities-routes.js +66 -22
  111. package/lib/ui-routes/auth-routes.js +36 -48
  112. package/lib/ui-routes/export-routes.js +10 -4
  113. package/lib/ui-routes/oauth-config-routes.js +5 -5
  114. package/lib/ui-routes/reference-routes.js +11 -8
  115. package/lib/ui-routes/route-helpers.js +79 -2
  116. package/lib/ui-routes/settings-page.js +1 -1
  117. package/lib/ui-routes/smtp-test-routes.js +1 -1
  118. package/lib/ui-routes/suppression-list-routes.js +294 -0
  119. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  120. package/lib/utils/is-email.js +34 -0
  121. package/lib/utils/network.js +2 -2
  122. package/lib/utils/to-camel-case.js +17 -0
  123. package/lib/web-safe-html.js +1 -1
  124. package/lib/webhook-egress.js +37 -0
  125. package/lib/webhook-routing.js +80 -0
  126. package/lib/webhooks.js +21 -15
  127. package/package.json +26 -27
  128. package/sbom.json +1 -0
  129. package/server.js +81 -42
  130. package/static/css/flyonui.css +1 -1
  131. package/static/css/public.css +3 -0
  132. package/static/css/src/app.tailwind.css +159 -9
  133. package/static/js/app.js +69 -0
  134. package/static/js/reference.js +741 -10
  135. package/static/js/ui.js +43 -0
  136. package/static/licenses.html +698 -1590
  137. package/translations/README.md +64 -0
  138. package/translations/de.mo +0 -0
  139. package/translations/de.po +164 -120
  140. package/translations/en.po +200 -161
  141. package/translations/et.mo +0 -0
  142. package/translations/et.po +163 -120
  143. package/translations/fr.mo +0 -0
  144. package/translations/fr.po +163 -120
  145. package/translations/ja.mo +0 -0
  146. package/translations/ja.po +163 -120
  147. package/translations/messages.pot +94 -64
  148. package/translations/nl.mo +0 -0
  149. package/translations/nl.po +164 -120
  150. package/translations/pl.mo +0 -0
  151. package/translations/pl.po +163 -120
  152. package/views/account-identity-error.hbs +34 -0
  153. package/views/accounts/account.hbs +69 -7
  154. package/views/accounts/browse.hbs +18 -35
  155. package/views/accounts/edit.hbs +1 -0
  156. package/views/accounts/register/imap.hbs +12 -2
  157. package/views/config/logging.hbs +6 -0
  158. package/views/config/oauth/app.hbs +0 -2
  159. package/views/config/security.hbs +13 -0
  160. package/views/layout/app.hbs +29 -5
  161. package/views/oauth-scope-error.hbs +1 -1
  162. package/views/partials/oauth_form.hbs +0 -15
  163. package/views/partials/reference/disclosure.hbs +8 -2
  164. package/views/partials/reference/nav.hbs +36 -9
  165. package/views/partials/reference/operation.hbs +48 -14
  166. package/views/partials/reference/params.hbs +17 -1
  167. package/views/partials/reference/schema-node.hbs +112 -54
  168. package/views/partials/reference/schema-tools.hbs +25 -0
  169. package/views/partials/reference/token-alert.hbs +35 -10
  170. package/views/partials/reference/try-it.hbs +84 -11
  171. package/views/partials/side_menu.hbs +1 -0
  172. package/views/partials/ui/checkbox.hbs +2 -2
  173. package/views/partials/ui/tabs.hbs +7 -1
  174. package/views/reference/index.hbs +1 -1
  175. package/views/reference/token.hbs +4 -0
  176. package/views/suppression-lists/index.hbs +85 -0
  177. package/views/suppression-lists/list.hbs +87 -0
  178. package/views/templates/index.hbs +8 -2
  179. package/views/tokens/index.hbs +31 -4
  180. package/views/tokens/new.hbs +324 -2
  181. package/workers/api.js +299 -140
  182. package/workers/documents.js +46 -26
  183. package/workers/export.js +20 -8
  184. package/workers/imap-proxy.js +2 -2
  185. package/workers/imap.js +13 -7
  186. package/workers/smtp.js +13 -7
  187. package/workers/submit.js +41 -31
  188. package/workers/webhooks.js +60 -37
  189. package/lib/feature-flags.js +0 -48
@@ -74,19 +74,122 @@
74
74
  }
75
75
  };
76
76
 
77
- const minutesLeft = expires => Math.max(0, Math.round((expires - Date.now()) / 60000));
77
+ // Rounded up, so the label counts the minute that is still running rather than the one
78
+ // nearest: a token with 20 seconds of life left reads "1 min left", and "0" never shows
79
+ // for a token that still works.
80
+ const minutesLeft = expires => Math.max(0, Math.ceil((expires - Date.now()) / 60000));
81
+
82
+ // The "no token set" banner sticks below the topbar (reference/token-alert.hbs), so it
83
+ // adds to what a jump target has to clear. Its measured height is published to the
84
+ // stylesheet rather than hard-coded there, because the band wraps to two rows on a narrow
85
+ // viewport - the layout's scroll-padding (.ee-app-chrome) adds it to the scroller's top
86
+ // inset. Kept as a number too, for the scroll spy: that line moves with the same inset,
87
+ // and reading it back out of the cascade on every scrolled frame would force a style
88
+ // recalc to do it.
89
+ let alertHeight = 0;
90
+
91
+ // Written only when it actually changes. Setting an inherited custom property on the root
92
+ // element invalidates style for the whole document - measured at ~7ms on a tag page, and
93
+ // the same with no rule reading the property at all, so this is the cost of the write
94
+ // itself rather than of the 434 rows that resolve it. The observer below makes an
95
+ // unchanged republish easy to hit, since it fires on width too, which moves on every frame
96
+ // of a resize drag while the height sits still.
97
+ const publishAlertHeight = alert => {
98
+ // `hidden` is display: none, so a hidden band measures 0 without a special case
99
+ const height = alert.offsetHeight;
100
+ if (height === alertHeight) {
101
+ return;
102
+ }
103
+
104
+ alertHeight = height;
105
+ document.documentElement.style.setProperty('--ee-sticky-band-h', `${height}px`);
106
+ return true;
107
+ };
108
+
109
+ // A band that changes height after revealTarget has landed a deep link leaves the section
110
+ // under a band that is opaque, not merely offset - the web font swapping in and rewrapping
111
+ // the warning is the case that hits a cold load. Re-land it, but only while the reader is
112
+ // still exactly where the jump left them: past that they have scrolled on, and yanking the
113
+ // page back would be worse than the offset.
114
+ const relandIfUnmoved = () => {
115
+ if (landedAt !== null && Math.round(window.scrollY) === landedAt) {
116
+ revealTarget();
117
+ }
118
+ };
119
+
120
+ // Show and hide are published by paintTokenStatus rather than left to the observer below:
121
+ // both run at DOMContentLoaded, and revealTarget scrolls to the deep link at `load` with
122
+ // whatever margin is in effect by then. This covers the band changing height on its own,
123
+ // which it does when a viewport narrow enough to wrap it is resized.
124
+ const initAlertHeight = () => {
125
+ const alert = document.getElementById('ref-token-alert');
126
+ if (alert) {
127
+ new ResizeObserver(() => {
128
+ if (publishAlertHeight(alert)) {
129
+ relandIfUnmoved();
130
+ }
131
+ }).observe(alert);
132
+ }
133
+ };
134
+
135
+ // A minted token's hour runs down while the page stays open, so the countdown below is
136
+ // repainted on a timer as well as on every change to the token. Not a poll: the repaint
137
+ // is scheduled for the moment the displayed minute actually changes, so a page left open
138
+ // does nothing at all in between. The handle doubles as "a countdown is running".
139
+ let countdownTimer = null;
140
+
141
+ const scheduleCountdown = expires => {
142
+ window.clearTimeout(countdownTimer);
143
+ countdownTimer = null;
144
+
145
+ if (!expires) {
146
+ return;
147
+ }
148
+
149
+ // The label (a ceil) rolls over on the minute boundaries counted back from the
150
+ // expiry, not on wall-clock ones. A timeout can fire a hair early, which would
151
+ // repaint the same number and then schedule another full minute from just short of
152
+ // the boundary, so aim past it. The store drops an entry the moment it expires, so
153
+ // what arrives here is always still ahead.
154
+ const remaining = expires - Date.now();
155
+ countdownTimer = window.setTimeout(() => paintTokenStatus(), (remaining % 60000 || 60000) + 250);
156
+ };
157
+
158
+ // Whether the "no token set" banner was last painted as shown. Only a change in that
159
+ // pays for publishAlertHeight, which measures: a forced layout, and one that follows the
160
+ // label write below, so the timer would be flushing layout for the whole page every
161
+ // minute for a height a minute rollover cannot have moved. The ResizeObserver in
162
+ // initAlertHeight still covers the band changing height on its own.
163
+ let alertShown = null;
78
164
 
79
165
  // Repaints the always-visible status in the sidebar, and shows the Clear control on
80
166
  // the overview page only while there is something to clear.
81
167
  const paintTokenStatus = () => {
82
168
  const entry = tokenStore.read();
169
+ const expires = entry && entry.expires;
170
+ const label = entry ? (expires ? `${minutesLeft(expires)} min left` : 'Active') : 'Not set';
83
171
 
84
172
  const state = document.getElementById('ref-token-state');
85
- if (state) {
86
- state.textContent = entry ? (entry.expires ? `${minutesLeft(entry.expires)} min left` : 'Active') : 'Not set';
173
+ // One guard for both: the class only ever changes along with the text
174
+ if (state && state.textContent !== label) {
175
+ state.textContent = label;
87
176
  state.className = entry ? 'text-success text-2xs' : 'text-base-content/50 text-2xs';
88
177
  }
89
178
 
179
+ // The access-token page's own copy of the countdown. It is there because the
180
+ // sidebar's is collapsed behind a disclosure below lg, on the one page where the
181
+ // token is the subject, and it is shown only for a minted token - a pasted one has
182
+ // no expiry known here.
183
+ const expiry = document.getElementById('ref-token-expiry');
184
+ if (expiry) {
185
+ expiry.classList.toggle('hidden', !expires);
186
+ if (expires) {
187
+ expiry.textContent = label;
188
+ }
189
+ }
190
+
191
+ scheduleCountdown(expires);
192
+
90
193
  const clearWrap = document.getElementById('ref-token-clear-wrap');
91
194
  if (clearWrap) {
92
195
  clearWrap.classList.toggle('hidden', !entry);
@@ -98,15 +201,22 @@
98
201
  const alert = document.getElementById('ref-token-alert');
99
202
  if (alert) {
100
203
  alert.classList.toggle('hidden', !!entry);
101
- alert.classList.toggle('flex', !entry);
204
+ if (alertShown !== !entry) {
205
+ alertShown = !entry;
206
+ publishAlertHeight(alert);
207
+ }
102
208
  }
103
209
  };
104
210
 
105
211
  // A tag page carries up to ~150 code blocks, several of them tens of kilobytes,
106
212
  // so highlighting all of them up front stalls the page for seconds. Each block is
107
- // highlighted the first time it becomes visible instead. That also covers blocks
108
- // inside collapsed <details> and inactive tab panels for free: those have no
109
- // layout box until they open, so the observer fires exactly then.
213
+ // highlighted the first time it becomes visible instead - which for most of them is
214
+ // on scroll, since they are below the fold rather than hidden.
215
+ //
216
+ // Blocks with no layout box at all are covered for the same reason and for free: an
217
+ // inactive response tab panel, or a collapsed <details>, has none until it opens, so
218
+ // the observer fires exactly then. Example payloads used to be in that second group;
219
+ // they now render open, so only the non-active response tabs still are.
110
220
  const highlightBlock = block => {
111
221
  if (block.dataset.eeHighlighted) {
112
222
  return;
@@ -150,6 +260,10 @@
150
260
  window.addEventListener('load', fn);
151
261
  };
152
262
 
263
+ // Where the last deep-link jump left the page, so a band that grows afterwards can tell
264
+ // "the reader has not moved yet" from "they have scrolled on". Null until one happens.
265
+ let landedAt = null;
266
+
153
267
  // Deep links point at a single schema property ("#accountCreate.body.imap.tls"), which
154
268
  // can sit inside collapsed <details> groups and an inactive response tab - neither of
155
269
  // which the browser can scroll to, because they have no layout box. Everything on the
@@ -181,6 +295,83 @@
181
295
  }
182
296
 
183
297
  target.scrollIntoView({ block: 'start' });
298
+ landedAt = Math.round(window.scrollY);
299
+ };
300
+
301
+ // Group rows in the nav. As a column they are plain links to the group's page. Below the
302
+ // layout's lg breakpoint the whole nav is a disclosure, and a link there is a bad deal: the
303
+ // tap that was meant to look inside a group loads its page and takes the menu with it. So
304
+ // in that mode the row opens its own operation list instead, and the reader picks the
305
+ // endpoint they actually wanted - which is the only navigation that ends the menu.
306
+ //
307
+ // Which mode the column is in is the layout's own question, answered by the small API
308
+ // static/js/app.js publishes for it.
309
+ const initTagRows = () => {
310
+ const list = document.getElementById('ref-tag-list');
311
+ const nav = window.uiSecondaryNav;
312
+ if (!list || !nav) {
313
+ return;
314
+ }
315
+
316
+ list.addEventListener('click', event => {
317
+ // aria-controls is what a group row has and an operation row does not
318
+ const row = event.target.closest('a[aria-controls]');
319
+ if (!row || !nav.collapsible()) {
320
+ return;
321
+ }
322
+
323
+ // A modified click is asking for the group's page in a new tab or window, which is
324
+ // still what the href says. Swallowing it would make the row mean one thing to the
325
+ // left button and another to every other way of opening a link.
326
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
327
+ return;
328
+ }
329
+
330
+ // preventDefault is also what tells the layout's panel handler to leave the menu
331
+ // open: a link that did not navigate has not finished with the reader.
332
+ event.preventDefault();
333
+
334
+ const expand = row.getAttribute('aria-expanded') !== 'true';
335
+ const before = row.getBoundingClientRect().top;
336
+
337
+ // One group at a time, which is the state the page is served in and keeps the menu
338
+ // to a screen or two. Opening all nineteen would put 3000px of navigation above the
339
+ // page, with the control to put it away scrolled off the top.
340
+ for (const open of list.querySelectorAll('a[aria-expanded="true"]')) {
341
+ open.setAttribute('aria-expanded', 'false');
342
+ }
343
+
344
+ row.setAttribute('aria-expanded', String(expand));
345
+
346
+ // Closing a group above this one pulls the list out from under the finger that
347
+ // just tapped it - by the height of whatever was open, which is most of a screen.
348
+ // Put the row back where it was touched.
349
+ const drift = row.getBoundingClientRect().top - before;
350
+ if (drift) {
351
+ if (nav.panel.scrollHeight > nav.panel.clientHeight) {
352
+ nav.panel.scrollTop += drift;
353
+ } else {
354
+ window.scrollBy(0, drift);
355
+ }
356
+ }
357
+ });
358
+
359
+ // Crossing back into column mode resets the rows to what the server renders: there
360
+ // lg:block shows the group the page is on and hides every other, so a row still saying
361
+ // "expanded" from a narrow window would announce the opposite of what is on screen -
362
+ // and no click can reconcile it, because the rows are plain links at that width. The
363
+ // active group is the one carrying the spy hook. Watching the toggle's box is how this
364
+ // hears the mode change without naming the breakpoint.
365
+ new ResizeObserver(() => {
366
+ if (nav.collapsible()) {
367
+ return;
368
+ }
369
+
370
+ for (const row of list.querySelectorAll('a[aria-controls]')) {
371
+ const ops = document.getElementById(row.getAttribute('aria-controls'));
372
+ row.setAttribute('aria-expanded', String(!!ops && ops.classList.contains('ee-ref-op-nav')));
373
+ }
374
+ }).observe(nav.toggle);
184
375
  };
185
376
 
186
377
  // Resolved once - the platform cannot change, and the shortcut check runs on every
@@ -342,11 +533,300 @@
342
533
  }
343
534
 
344
535
  event.preventDefault();
536
+
537
+ // Below the layout's lg breakpoint this whole column is a disclosure, and focusing
538
+ // an input inside a display:none subtree does nothing at all - which is the width
539
+ // where a narrow window most needs the filter. Open it on the way to the field.
540
+ if (window.uiSecondaryNav && window.uiSecondaryNav.collapsible()) {
541
+ window.uiSecondaryNav.open();
542
+ }
543
+
345
544
  input.focus();
346
545
  input.select();
347
546
  });
348
547
  };
349
548
 
549
+ // Marks the operation you are currently reading in the sidebar.
550
+ //
551
+ // Slack between the line an operation has to cross and the point it parks at when linked
552
+ // to directly. Without it the two are equal and sub-pixel rounding decides which section
553
+ // a deep link marks; with it, landing on a section always marks that section.
554
+ const SPY_SLACK = 16;
555
+
556
+ const initScrollSpy = () => {
557
+ const list = document.querySelector('.ee-ref-op-nav');
558
+ const panel = list && list.closest('aside');
559
+ if (!panel) {
560
+ return;
561
+ }
562
+
563
+ // Walked in DOCUMENT order, from the sections rather than from the nav. The two happen
564
+ // to agree today - both come from tag.operations - but only this direction is true by
565
+ // construction, and the scan below is meaningless if the order is wrong. Sorting the
566
+ // nav some other way later would silently break a nav-ordered list.
567
+ //
568
+ // One array of pairs, not a Map plus a copy of its keys: every use wants both halves.
569
+ const entries = [];
570
+ for (const section of document.querySelectorAll('.ee-ref-op[id]')) {
571
+ const link = list.querySelector(`a[href="#${CSS.escape(section.id)}"]`);
572
+ if (link) {
573
+ entries.push({ link, section });
574
+ }
575
+ }
576
+
577
+ if (!entries.length) {
578
+ return;
579
+ }
580
+
581
+ const last = entries[entries.length - 1];
582
+
583
+ // Read from the cascade rather than restated as a number here: a linked section parks
584
+ // at the scroller's own top inset (the sticky chrome, html's scroll-padding-top) plus
585
+ // its scroll-margin, and a spy line that disagreed with the two would mark the wrong
586
+ // row on arrival. Whatever the banner contributes right now is taken back out and
587
+ // re-added per read: that makes this independent of whether the banner has been
588
+ // measured yet, and follows it disappearing when a token is minted, which shortens the
589
+ // inset without the page reloading.
590
+ const staticLine =
591
+ parseFloat(window.getComputedStyle(document.documentElement).scrollPaddingTop || '0') -
592
+ alertHeight +
593
+ parseFloat(window.getComputedStyle(entries[0].section).scrollMarginTop || '0') +
594
+ SPY_SLACK;
595
+
596
+ const current = () => {
597
+ // Recomputed from scratch every time rather than tracked incrementally, so it cannot
598
+ // drift out of step with the page
599
+ const line = staticLine + alertHeight;
600
+ const found = entries.findLast(entry => entry.section.getBoundingClientRect().top <= line) || entries[0];
601
+
602
+ // A final section shorter than the space below it never reaches the line, so it
603
+ // would never light up. Only the pick just before it can be wrong this way, which
604
+ // keeps the scrollHeight read - the one most likely to force layout, on a page whose
605
+ // height moves as code blocks highlight - off all but the last screenful.
606
+ if (found === entries[entries.length - 2] && window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2) {
607
+ return last;
608
+ }
609
+
610
+ return found;
611
+ };
612
+
613
+ // Scrolls the sidebar itself rather than calling scrollIntoView, which also scrolls the
614
+ // window - that would move the sections being measured and could oscillate. Returns the
615
+ // delta instead of applying it so paint() can finish measuring before it writes.
616
+ const panelDelta = link => {
617
+ // Only the full-height column scrolls on its own. Below the layout's lg breakpoint
618
+ // the same markup is a disclosure in normal page flow, with nothing to scroll -
619
+ // asking whether it overflows answers that without naming the breakpoint again.
620
+ if (panel.scrollHeight <= panel.clientHeight) {
621
+ return 0;
622
+ }
623
+
624
+ // While the filter has input the whole tag list is display:none, so these links
625
+ // have no box at all - and a zero rect against the panel's top reads as "scrolled
626
+ // far above", which would drag the sidebar up a row at a time behind the results.
627
+ if (!link.offsetParent) {
628
+ return 0;
629
+ }
630
+
631
+ const linkBox = link.getBoundingClientRect();
632
+ const panelBox = panel.getBoundingClientRect();
633
+
634
+ if (linkBox.top < panelBox.top) {
635
+ return linkBox.top - panelBox.top - 8;
636
+ }
637
+ if (linkBox.bottom > panelBox.bottom) {
638
+ return linkBox.bottom - panelBox.bottom + 8;
639
+ }
640
+ return 0;
641
+ };
642
+
643
+ let marked = null;
644
+
645
+ const paint = () => {
646
+ const entry = current();
647
+ if (entry === marked) {
648
+ return;
649
+ }
650
+
651
+ // Measured before anything is written: setting aria-current restyles the link, so
652
+ // reading its box afterwards would force a synchronous style and layout pass at the
653
+ // exact moment the marker moves.
654
+ const delta = panelDelta(entry.link);
655
+
656
+ if (marked) {
657
+ marked.link.removeAttribute('aria-current');
658
+ }
659
+
660
+ marked = entry;
661
+ // `location` rather than `page`: the tag entry above is the current page, this is a
662
+ // position within it
663
+ entry.link.setAttribute('aria-current', 'location');
664
+
665
+ if (delta) {
666
+ panel.scrollTop += delta;
667
+ }
668
+ };
669
+
670
+ let queued = false;
671
+ const schedule = () => {
672
+ if (queued) {
673
+ return;
674
+ }
675
+ queued = true;
676
+ // Reads happen inside the frame callback, before the browser's own style and layout
677
+ // phase, so the flush they force is work the frame was going to do anyway
678
+ window.requestAnimationFrame(() => {
679
+ queued = false;
680
+ paint();
681
+ });
682
+ };
683
+
684
+ window.addEventListener('scroll', schedule, { passive: true });
685
+ window.addEventListener('resize', schedule, { passive: true });
686
+ paint();
687
+ };
688
+
689
+ // Filter and expand/collapse for one large schema tree (reference/schema-tools).
690
+ //
691
+ // Separate from the sidebar filter above on purpose. That one searches operations and
692
+ // deliberately leaves response property names out of its corpus, because it ANDs plain
693
+ // substrings and the envelope fields repeat across most endpoints - adding them would
694
+ // blunt exactly the queries it exists for. The cost was that on a page rendering 418
695
+ // property rows there was no way to reach `oauth2.expires` except by scrolling and
696
+ // opening groups. This filter has its own corpus, its own control and its own scope, so
697
+ // that trade-off is untouched.
698
+ //
699
+ // Matching is on the property name alone, not the description: a name is what a caller
700
+ // has in hand when they come looking, and matching prose would light up most of a tree
701
+ // for a common word.
702
+ const SCHEMA_ROW = 'ee-ref-prop';
703
+ const SCHEMA_GROUP = 'details.ee-ref-disclosure';
704
+
705
+ // Everything about a schema tree that the filter needs and that never changes: the rows,
706
+ // their lowercased names, the parent row each one hangs off, and the disclosures on the
707
+ // way down to it. Walked once per tree, so a keystroke is a pass over arrays rather than
708
+ // ~130 selector queries and as many string allocations.
709
+ //
710
+ // querySelectorAll returns document order, and an ancestor row always precedes its
711
+ // descendants, so a parent's entry is already built by the time a child needs it.
712
+ const indexSchema = scope => {
713
+ const byElement = new Map();
714
+
715
+ return Array.from(scope.querySelectorAll(`.${SCHEMA_ROW}`)).map(element => {
716
+ const code = element.querySelector('.ee-ref-prop-rail code');
717
+ // The parent PROPERTY, not the closest ancestor carrying the class - that is the
718
+ // row itself, which is why the walk starts at parentElement.
719
+ const parentElement = element.parentElement ? element.parentElement.closest(`.${SCHEMA_ROW}`) : null;
720
+
721
+ const groups = [];
722
+ for (let details = element.closest(SCHEMA_GROUP); details && scope.contains(details); details = details.parentElement.closest(SCHEMA_GROUP)) {
723
+ groups.push(details);
724
+ }
725
+
726
+ const entry = { element, name: code ? code.textContent.toLowerCase() : '', parent: byElement.get(parentElement) || null, groups };
727
+ byElement.set(element, entry);
728
+ return entry;
729
+ });
730
+ };
731
+
732
+ const applySchemaFilter = (rows, disclosures, openOnLoad, term) => {
733
+ if (!term) {
734
+ for (const entry of rows) {
735
+ entry.element.classList.remove('hidden');
736
+ }
737
+ // Back to whatever the server decided, so clearing the box is a real undo rather
738
+ // than leaving the tree wherever the search happened to open it
739
+ for (const details of disclosures) {
740
+ details.open = openOnLoad.has(details);
741
+ }
742
+ return 0;
743
+ }
744
+
745
+ const matched = new Set(rows.filter(entry => entry.name.includes(term)));
746
+
747
+ // A row survives if it matches, contains a match, or sits inside one - so a hit on an
748
+ // object still shows the object's own children rather than an empty group.
749
+ const keep = new Set(matched);
750
+ for (const entry of matched) {
751
+ for (let parent = entry.parent; parent; parent = parent.parent) {
752
+ keep.add(parent);
753
+ }
754
+ }
755
+ for (const entry of rows) {
756
+ for (let parent = entry.parent; parent; parent = parent.parent) {
757
+ if (matched.has(parent)) {
758
+ keep.add(entry);
759
+ break;
760
+ }
761
+ }
762
+ }
763
+
764
+ // Only the groups on the way down to a surviving row stay open - otherwise the hits
765
+ // are inside a collapsed <details> and the filter looks like it found nothing, while
766
+ // unrelated groups the reader opened earlier stay in the way.
767
+ const open = new Set();
768
+ for (const entry of keep) {
769
+ entry.element.classList.remove('hidden');
770
+ for (const details of entry.groups) {
771
+ open.add(details);
772
+ }
773
+ }
774
+ for (const entry of rows) {
775
+ if (!keep.has(entry)) {
776
+ entry.element.classList.add('hidden');
777
+ }
778
+ }
779
+ for (const details of disclosures) {
780
+ details.open = open.has(details);
781
+ }
782
+
783
+ return matched.size;
784
+ };
785
+
786
+ const initSchemaTools = () => {
787
+ for (const tools of document.querySelectorAll('[data-schema-tools]')) {
788
+ const scope = document.getElementById(tools.getAttribute('data-schema-scope') || '');
789
+ if (!scope) {
790
+ continue;
791
+ }
792
+
793
+ const rows = indexSchema(scope);
794
+ const disclosures = Array.from(scope.querySelectorAll(SCHEMA_GROUP));
795
+ const openOnLoad = new Set(disclosures.filter(details => details.open));
796
+
797
+ // The input and the two buttons come from ui/search-input and ui/btn, so they
798
+ // carry no hooks of their own - reference/schema-tools renders exactly one
799
+ // input and exactly two buttons, in that order, and the container scopes both
800
+ // lookups.
801
+ const input = tools.querySelector('input');
802
+ const count = tools.querySelector('[data-schema-count]');
803
+ const [expand, collapse] = tools.querySelectorAll('button');
804
+
805
+ if (input) {
806
+ input.addEventListener('input', () => {
807
+ const term = input.value.trim().toLowerCase();
808
+ const hits = applySchemaFilter(rows, disclosures, openOnLoad, term);
809
+ if (count) {
810
+ count.textContent = term ? `${hits} ${hits === 1 ? 'match' : 'matches'}` : '';
811
+ }
812
+ });
813
+ }
814
+
815
+ const setAll = open => () => {
816
+ for (const details of disclosures) {
817
+ details.open = open;
818
+ }
819
+ };
820
+
821
+ if (expand) {
822
+ expand.addEventListener('click', setAll(true));
823
+ }
824
+ if (collapse) {
825
+ collapse.addEventListener('click', setAll(false));
826
+ }
827
+ }
828
+ };
829
+
350
830
  // Code sample language, remembered across operations and page loads.
351
831
  //
352
832
  // localStorage, not sessionStorage (which is what the try-it token uses): this is a
@@ -561,10 +1041,233 @@
561
1041
  }
562
1042
  };
563
1043
 
1044
+ // ---- Try it: JSON body editor ------------------------------------------------
1045
+ //
1046
+ // The request body textarea is upgraded to an ACE editor for JSON highlighting, the
1047
+ // gutter errors its worker reports as you type, and completion over the field names the
1048
+ // operation actually accepts. The textarea stays in the DOM and keeps holding the value,
1049
+ // so prepareRequest(), "Copy as curl" and the JSON validation are untouched and the
1050
+ // panel still works with no JS at all.
1051
+ //
1052
+ // Both halves are lazy. ace.js is 127 KB gzipped and nothing else on a reference page
1053
+ // wants it, so it is fetched the first time a Try it panel with a body is opened; and
1054
+ // each editor is mounted on its own panel's first open, because these disclosures start
1055
+ // closed and ACE cannot measure itself inside a container with no layout box. A tag page
1056
+ // has at most seven request bodies and in practice mounts one or two.
1057
+ const ACE_BASE = '/static/js/ace';
1058
+
1059
+ let acePromise = null;
1060
+
1061
+ const loadScript = src =>
1062
+ new Promise((resolve, reject) => {
1063
+ const element = document.createElement('script');
1064
+ element.src = src;
1065
+ element.onload = resolve;
1066
+ element.onerror = () => reject(new Error(`Failed to load ${src}`));
1067
+ document.head.appendChild(element);
1068
+ });
1069
+
1070
+ const loadAce = () => {
1071
+ if (!acePromise) {
1072
+ acePromise = loadScript(`${ACE_BASE}/ace.js`)
1073
+ .then(() => {
1074
+ // Modes, themes and the JSON worker are resolved against this. ACE infers
1075
+ // it from its own <script src> when the page carries one; injected at
1076
+ // runtime that inference is not worth relying on.
1077
+ window.ace.config.set('basePath', ACE_BASE);
1078
+ return loadScript(`${ACE_BASE}/ext-language_tools.js`);
1079
+ })
1080
+ .catch(err => {
1081
+ // Let a later open try again rather than leaving every panel stuck on a
1082
+ // one-off network failure
1083
+ acePromise = null;
1084
+ throw err;
1085
+ });
1086
+ }
1087
+ return acePromise;
1088
+ };
1089
+
1090
+ // Completion entries for one operation, read off the property tree already rendered on
1091
+ // the page rather than duplicated into the markup for the editor's benefit. Stock
1092
+ // language_tools completion is word-based - inside a JSON body that only ever suggests
1093
+ // words already typed - so this replaces the default completers rather than joining them.
1094
+ //
1095
+ // Deduped by name: the same field legitimately appears at several depths (`auth` under
1096
+ // both imap and smtp), and a completer needs the token, not where it came from.
1097
+ //
1098
+ // A row that carries an example completes to the whole pair, `"listId": "test-list"`,
1099
+ // rather than to a bare key. Completing a key alone left the reader with the harder half
1100
+ // of the problem still to solve, which is the same gap the rows themselves used to have.
1101
+ //
1102
+ // The value comes off the row's example chip, so it is the value documented right there.
1103
+ // A cut chip carries the whole value in data-example - reference/schema-node emits it for
1104
+ // exactly this - rather than the completion being reconstructed from the shortened text.
1105
+ const schemaCompleter = schemaId => {
1106
+ const scope = document.getElementById(schemaId || '');
1107
+ if (!scope) {
1108
+ return null;
1109
+ }
1110
+
1111
+ const fields = new Map();
1112
+ for (const row of scope.querySelectorAll('.ee-ref-prop')) {
1113
+ // The row's OWN rail. A row contains its nested rows, so an unanchored descendant
1114
+ // selector would read a child's name onto the parent.
1115
+ const rail = row.querySelector(':scope > .ee-ref-prop-row > .ee-ref-prop-rail');
1116
+ const name = rail && rail.querySelector('code');
1117
+ if (!name || !name.textContent || fields.has(name.textContent)) {
1118
+ continue;
1119
+ }
1120
+ const type = rail.querySelector('.text-primary');
1121
+ const example = row.querySelector(':scope > .ee-ref-prop-row > .ee-ref-prop-body .ee-ref-example-value');
1122
+ const value = example ? example.dataset.example || example.textContent : '';
1123
+
1124
+ fields.set(name.textContent, {
1125
+ caption: name.textContent,
1126
+ value: value ? `"${name.textContent}": ${value}` : name.textContent,
1127
+ meta: type ? type.textContent : '',
1128
+ score: 100
1129
+ });
1130
+ }
1131
+
1132
+ if (!fields.size) {
1133
+ return null;
1134
+ }
1135
+
1136
+ const list = [...fields.values()];
1137
+ return { getCompletions: (editor, session, pos, prefix, callback) => callback(null, list) };
1138
+ };
1139
+
1140
+ // Mounted editors, so the "Fill in every field" button can write into one. The editor is
1141
+ // created inside mountBodyEditor and nothing else needed a handle on it before.
1142
+ const bodyEditors = new WeakMap();
1143
+
1144
+ // Swaps the typical payload in the try-it field for the complete one, read back out of
1145
+ // the tab panel rendered above the form rather than from a second copy in the markup.
1146
+ const fillCompleteBody = field => {
1147
+ const source = document.getElementById(field.dataset.completeSource || '');
1148
+ const code = source && source.querySelector('code');
1149
+ const textarea = field.querySelector('[data-body]');
1150
+
1151
+ if (!code || !textarea) {
1152
+ return;
1153
+ }
1154
+
1155
+ textarea.value = code.textContent;
1156
+
1157
+ const editor = bodyEditors.get(field);
1158
+ if (editor) {
1159
+ editor.setValue(code.textContent, -1);
1160
+ }
1161
+ };
1162
+
1163
+ const mountBodyEditor = async field => {
1164
+ if (field.dataset.editorMounted) {
1165
+ return;
1166
+ }
1167
+ field.dataset.editorMounted = '1';
1168
+
1169
+ const textarea = field.querySelector('[data-body]');
1170
+ if (!textarea) {
1171
+ return;
1172
+ }
1173
+
1174
+ try {
1175
+ await loadAce();
1176
+ } catch (err) {
1177
+ // The textarea is still there and still holds the value, so the panel keeps
1178
+ // working exactly as it did before the upgrade existed
1179
+ delete field.dataset.editorMounted;
1180
+ return;
1181
+ }
1182
+
1183
+ const mount = document.createElement('div');
1184
+ mount.className = 'code-editor ee-ref-body-editor mt-1';
1185
+ textarea.after(mount);
1186
+ textarea.hidden = true;
1187
+
1188
+ const completer = schemaCompleter(field.dataset.schema);
1189
+ const editor = window.uiAceEditor(mount, 'json', textarea.value, {
1190
+ // Grows with the payload instead of scrolling inside a fixed box - a 62-property
1191
+ // account body is unreadable through an eight-line window - but stops before it
1192
+ // pushes the Send button off screen
1193
+ minLines: 8,
1194
+ maxLines: 24,
1195
+ // The 80-column rule means nothing in a JSON body
1196
+ showPrintMargin: false,
1197
+ // Only this operation's own field names, never the word-based default
1198
+ enableBasicAutocompletion: completer ? [completer] : false,
1199
+ enableLiveAutocompletion: completer ? [completer] : false
1200
+ });
1201
+
1202
+ bodyEditors.set(field, editor);
1203
+
1204
+ // The textarea remains what everything downstream reads
1205
+ editor.session.on('change', () => {
1206
+ textarea.value = editor.getValue();
1207
+ });
1208
+ };
1209
+
1210
+ const initTryItEditors = () => {
1211
+ for (const field of document.querySelectorAll('[data-body-field]')) {
1212
+ const details = field.closest('details');
1213
+ if (!details) {
1214
+ continue;
1215
+ }
1216
+
1217
+ if (details.open) {
1218
+ mountBodyEditor(field);
1219
+ continue;
1220
+ }
1221
+
1222
+ // Mounting is idempotent, so a panel opened and closed repeatedly still costs one
1223
+ details.addEventListener('toggle', () => {
1224
+ if (details.open) {
1225
+ mountBodyEditor(field);
1226
+ }
1227
+ });
1228
+ }
1229
+ };
1230
+
1231
+ // Confirmation step for the operations whose effect cannot be taken back (tryImpact.confirm
1232
+ // in lib/api-reference/model.js). The fields arrive prefilled from the schema example, so
1233
+ // Send on DELETE /v1/account/{account} is one click from a real deletion; this puts the
1234
+ // resolved request in front of the reader first - the actual method, path and body, with
1235
+ // the values currently in the form - and makes them press a second, differently labelled
1236
+ // button.
1237
+ //
1238
+ // The dialog mechanics are window.uiConfirmModal in static/js/ui.js, shared with the
1239
+ // message browser. All this adds is what to show.
1240
+ const confirmRequest = (form, request) => {
1241
+ const modal = document.getElementById(form.dataset.confirm);
1242
+ if (!modal) {
1243
+ return Promise.resolve(false);
1244
+ }
1245
+
1246
+ // Emitted unconditionally beside the button, by the same {{#if tryImpact.confirm}}
1247
+ // that sets the form's data-confirm, so these are there
1248
+ modal.querySelector('.ee-ref-confirm-request').textContent = `${request.method} ${request.url}`;
1249
+
1250
+ // Shown only when there is one, which among these operations means the bulk deletes
1251
+ // and the submits, where the body is what decides what actually happens
1252
+ modal.querySelector('.ee-ref-confirm-body').textContent = request.body || '';
1253
+ modal.querySelector('.ee-ref-confirm-body-wrap').classList.toggle('hidden', !request.body);
1254
+
1255
+ return window.uiConfirmModal(modal, '.ee-ref-confirm-run');
1256
+ };
1257
+
564
1258
  // One delegated listener for every try-it form on the page, matching how
565
1259
  // static/js/ui.js handles the copy buttons.
566
1260
  const initTryIt = () => {
567
1261
  document.addEventListener('click', event => {
1262
+ const fill = event.target.closest('.ee-ref-try-fill');
1263
+ if (fill) {
1264
+ const field = fill.closest('[data-body-field]');
1265
+ if (field) {
1266
+ fillCompleteBody(field);
1267
+ }
1268
+ return;
1269
+ }
1270
+
568
1271
  const button = event.target.closest('.ee-ref-try-curl');
569
1272
  if (!button) {
570
1273
  return;
@@ -592,10 +1295,22 @@
592
1295
  const status = form.querySelector('.ee-ref-try-status');
593
1296
  const button = form.querySelector('button[type="submit"]');
594
1297
 
1298
+ // Busy BEFORE the confirmation, not after it. uiButtonBusy disables the button,
1299
+ // which is what stops a second Send from queueing a second confirmation against
1300
+ // the same dialog - one "Run it" would then resolve both and delete twice.
595
1301
  window.uiButtonBusy(button, true);
596
- const started = performance.now();
597
1302
 
598
1303
  try {
1304
+ // Confirmed after prepareRequest, so a malformed body is reported rather than
1305
+ // confirmed, and the dialog can show the request that would actually run.
1306
+ // Inside the try so that however it ends, the finally re-enables the button.
1307
+ if (form.dataset.confirm && !(await confirmRequest(form, request))) {
1308
+ return;
1309
+ }
1310
+
1311
+ // Started after the dialog, so a reader thinking it over is not reported back
1312
+ // to them as request latency
1313
+ const started = performance.now();
599
1314
  const response = await fetch(request.url, {
600
1315
  method: request.method,
601
1316
  headers: request.headers,
@@ -682,10 +1397,11 @@
682
1397
  return;
683
1398
  }
684
1399
 
685
- // Reflect what is already held for this tab
1400
+ // Reflect what is already held for this tab. No minute count here - this line is
1401
+ // written once, and the badge beside the Clear button is the one that stays true.
686
1402
  const existing = tokenStore.read();
687
1403
  if (existing) {
688
- say(existing.expires ? `A temporary token is active, ${minutesLeft(existing.expires)} minutes left.` : 'A token is active.', true);
1404
+ say(existing.expires ? 'A temporary token is active.' : 'A token is active.', true);
689
1405
  }
690
1406
 
691
1407
  document.getElementById('ref-token-set').addEventListener('click', () => {
@@ -719,10 +1435,15 @@
719
1435
  document.addEventListener('DOMContentLoaded', () => {
720
1436
  initHighlighting();
721
1437
  initFilter();
1438
+ initTagRows();
1439
+ initScrollSpy();
1440
+ initSchemaTools();
722
1441
  initSampleTabs();
723
1442
  initTryIt();
1443
+ initTryItEditors();
724
1444
  initMint();
725
1445
  initTokenForm();
1446
+ initAlertHeight();
726
1447
  paintTokenStatus();
727
1448
 
728
1449
  // On load rather than here: a target inside an inactive response tab needs the tab
@@ -730,6 +1451,16 @@
730
1451
  whenComponentsReady(revealTarget);
731
1452
  });
732
1453
 
1454
+ // A background tab has its timers throttled to about one a minute, and a frozen one gets
1455
+ // none at all, so the countdown can be well behind by the time the reader comes back to
1456
+ // it. Repaint on the way back rather than trusting the schedule to have kept up - but
1457
+ // only with a countdown actually running, since nothing else here moves on its own.
1458
+ document.addEventListener('visibilitychange', () => {
1459
+ if (!document.hidden && countdownTimer) {
1460
+ paintTokenStatus();
1461
+ }
1462
+ });
1463
+
733
1464
  // Same-page property links only change the fragment, so the load-time pass does not
734
1465
  // run for them
735
1466
  window.addEventListener('hashchange', revealTarget);