emailengine-app 2.76.0 → 2.78.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 (165) hide show
  1. package/.github/workflows/release.yaml +24 -19
  2. package/.github/workflows/test.yml +80 -0
  3. package/.ncurc.js +14 -2
  4. package/.release-please-manifest.json +3 -0
  5. package/CHANGELOG.md +54 -0
  6. package/README.md +1 -1
  7. package/bin/emailengine.js +1 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +72 -5
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +75 -26
  12. package/lib/address-strategies.js +18 -0
  13. package/lib/api-reference/code-samples.js +194 -0
  14. package/lib/api-reference/format.js +193 -0
  15. package/lib/api-reference/index.js +222 -0
  16. package/lib/api-reference/model.js +338 -0
  17. package/lib/api-reference/schema-tree.js +366 -0
  18. package/lib/api-routes/account-routes.js +136 -39
  19. package/lib/api-routes/behavior-notes.js +57 -0
  20. package/lib/api-routes/blocklist-routes.js +9 -9
  21. package/lib/api-routes/changes-routes.js +6 -4
  22. package/lib/api-routes/chat-routes.js +3 -3
  23. package/lib/api-routes/delivery-test-routes.js +24 -6
  24. package/lib/api-routes/export-routes.js +14 -12
  25. package/lib/api-routes/gateway-routes.js +11 -11
  26. package/lib/api-routes/license-routes.js +7 -7
  27. package/lib/api-routes/mailbox-routes.js +18 -9
  28. package/lib/api-routes/message-routes.js +55 -35
  29. package/lib/api-routes/oauth2-app-routes.js +22 -16
  30. package/lib/api-routes/outbox-routes.js +7 -7
  31. package/lib/api-routes/pubsub-routes.js +3 -3
  32. package/lib/api-routes/settings-routes.js +10 -9
  33. package/lib/api-routes/stats-routes.js +3 -3
  34. package/lib/api-routes/submit-routes.js +58 -8
  35. package/lib/api-routes/template-routes.js +13 -13
  36. package/lib/api-routes/token-routes.js +15 -10
  37. package/lib/api-routes/webhook-route-routes.js +5 -5
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/autodetect-imap-settings.js +40 -16
  41. package/lib/base32.js +30 -0
  42. package/lib/bounce-detect.js +182 -62
  43. package/lib/consts.js +7 -0
  44. package/lib/egress-filter.js +89 -8
  45. package/lib/email-client/base-client.js +72 -82
  46. package/lib/email-client/gmail-client.js +3 -3
  47. package/lib/email-client/imap/listing-diff.js +3 -3
  48. package/lib/email-client/imap/mailbox.js +5 -69
  49. package/lib/email-client/imap-client.js +3 -2
  50. package/lib/email-client/message-builder.js +13 -13
  51. package/lib/email-client/outlook-client.js +1 -1
  52. package/lib/enum-descriptions.js +130 -0
  53. package/lib/export.js +1 -1
  54. package/lib/gateway.js +1 -1
  55. package/lib/get-raw-email.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-connection.js +2 -2
  57. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  58. package/lib/imapproxy/imap-server.js +42 -28
  59. package/lib/imapproxy/upstream-client.js +38 -0
  60. package/lib/license-beacon.js +1 -1
  61. package/lib/llm-pre-process.js +1 -1
  62. package/lib/msgpack.js +62 -0
  63. package/lib/oauth/decode-jwt-payload.js +39 -0
  64. package/lib/oauth/outlook-identity.js +61 -0
  65. package/lib/oauth/retry-setup.js +38 -0
  66. package/lib/oauth2-apps.js +10 -4
  67. package/lib/openapi/build-document.js +318 -0
  68. package/lib/openapi/index.js +95 -0
  69. package/lib/openapi/joi-schema.js +523 -0
  70. package/lib/outbox.js +66 -3
  71. package/lib/pre-process.js +1 -1
  72. package/lib/read-env-value.js +37 -0
  73. package/lib/routes-ui.js +5 -1
  74. package/lib/schemas.js +88 -17
  75. package/lib/swagger-options.js +173 -0
  76. package/lib/templates.js +1 -1
  77. package/lib/tokens.js +70 -6
  78. package/lib/tools.js +117 -48
  79. package/lib/totp.js +67 -0
  80. package/lib/ui-routes/account-routes.js +91 -15
  81. package/lib/ui-routes/admin-config-routes.js +2 -7
  82. package/lib/ui-routes/admin-entities-routes.js +3 -0
  83. package/lib/ui-routes/auth-routes.js +6 -24
  84. package/lib/ui-routes/dashboard-routes.js +2 -26
  85. package/lib/ui-routes/reference-routes.js +198 -0
  86. package/lib/ui-routes/route-helpers.js +39 -0
  87. package/lib/utils/is-email.js +34 -0
  88. package/lib/utils/to-camel-case.js +17 -0
  89. package/lib/webhook-egress.js +37 -0
  90. package/lib/webhooks.js +1 -1
  91. package/package.json +27 -31
  92. package/prepare-bundle-deps.sh +28 -0
  93. package/release-please-config.json +11 -0
  94. package/sbom.json +1 -1
  95. package/server.js +11 -3
  96. package/static/css/flyonui.css +1 -1
  97. package/static/css/public.css +3 -0
  98. package/static/css/src/app.tailwind.css +113 -0
  99. package/static/js/app.js +69 -0
  100. package/static/js/ee-client.js +238 -8
  101. package/static/js/reference.js +1021 -0
  102. package/static/js/ui.js +61 -33
  103. package/static/licenses.html +658 -1560
  104. package/translations/README.md +64 -0
  105. package/translations/de.mo +0 -0
  106. package/translations/de.po +164 -120
  107. package/translations/en.po +200 -161
  108. package/translations/et.mo +0 -0
  109. package/translations/et.po +163 -120
  110. package/translations/fr.mo +0 -0
  111. package/translations/fr.po +163 -120
  112. package/translations/ja.mo +0 -0
  113. package/translations/ja.po +163 -120
  114. package/translations/messages.pot +84 -54
  115. package/translations/nl.mo +0 -0
  116. package/translations/nl.po +164 -120
  117. package/translations/pl.mo +0 -0
  118. package/translations/pl.po +163 -120
  119. package/views/account-identity-error.hbs +34 -0
  120. package/views/accounts/edit.hbs +1 -0
  121. package/views/accounts/register/imap.hbs +12 -2
  122. package/views/config/ai.hbs +1 -1
  123. package/views/config/document-store/chat.hbs +5 -5
  124. package/views/config/document-store/index.hbs +2 -2
  125. package/views/config/document-store/pre-processing/index.hbs +1 -1
  126. package/views/config/email-processing.hbs +1 -1
  127. package/views/config/imap-proxy.hbs +1 -1
  128. package/views/config/license.hbs +1 -1
  129. package/views/config/oauth/index.hbs +3 -3
  130. package/views/config/security.hbs +1 -1
  131. package/views/config/smtp.hbs +2 -2
  132. package/views/dashboard.hbs +1 -1
  133. package/views/layout/app.hbs +43 -8
  134. package/views/oauth-scope-error.hbs +1 -1
  135. package/views/partials/oauth_form.hbs +4 -4
  136. package/views/partials/reference/anchor-link.hbs +20 -0
  137. package/views/partials/reference/disclosure.hbs +37 -0
  138. package/views/partials/reference/nav.hbs +120 -0
  139. package/views/partials/reference/operation.hbs +127 -0
  140. package/views/partials/reference/params.hbs +20 -0
  141. package/views/partials/reference/schema-node.hbs +99 -0
  142. package/views/partials/reference/schema.hbs +19 -0
  143. package/views/partials/reference/section-heading.hbs +16 -0
  144. package/views/partials/reference/token-alert.hbs +49 -0
  145. package/views/partials/reference/try-field.hbs +31 -0
  146. package/views/partials/reference/try-it.hbs +78 -0
  147. package/views/partials/side_menu.hbs +1 -1
  148. package/views/partials/ui/badge.hbs +4 -2
  149. package/views/partials/ui/page-header.hbs +1 -1
  150. package/views/partials/ui/search-input.hbs +31 -0
  151. package/views/partials/ui/setting-ref.hbs +1 -1
  152. package/views/partials/ui/stat-card.hbs +4 -2
  153. package/views/partials/ui/tab.hbs +6 -1
  154. package/views/partials/ui/tabs.hbs +2 -2
  155. package/views/reference/index.hbs +76 -0
  156. package/views/reference/redirect.hbs +49 -0
  157. package/views/reference/tag.hbs +28 -0
  158. package/views/reference/token.hbs +49 -0
  159. package/views/tokens/index.hbs +9 -1
  160. package/views/webhooks/index.hbs +3 -3
  161. package/workers/api.js +194 -302
  162. package/workers/imap.js +1 -1
  163. package/workers/submit.js +1 -1
  164. package/workers/webhooks.js +2 -13
  165. package/views/swagger/index.hbs +0 -82
@@ -0,0 +1,222 @@
1
+ 'use strict';
2
+
3
+ // Server-rendered API reference.
4
+ //
5
+ // The OpenAPI document is generated from the route joi schemas by lib/openapi/ - this
6
+ // module only reads it back (over server.inject, so there is no second source of truth)
7
+ // and turns it into a render model. The old /admin/swagger page shipped the same document
8
+ // to the browser and let swagger-ui build the DOM; here the whole page is HTML by the time
9
+ // it leaves the worker.
10
+ //
11
+ // The model is derived purely from the spec, so it is built once per API worker and
12
+ // shared. Only the code samples depend on the request, and those are applied per render.
13
+
14
+ const settings = require('../settings');
15
+ const { buildModel } = require('./model');
16
+ const { buildCodeSamples } = require('./code-samples');
17
+ const { operationUrl } = require('./format');
18
+
19
+ const SPEC_URL = '/swagger.json';
20
+
21
+ const FALLBACK_BASE_URL = 'https://your-emailengine-host';
22
+
23
+ // The in-flight or resolved model. Caching the promise itself means concurrent first
24
+ // requests share one load; a failed load clears the slot so the next request retries.
25
+ let modelPromise = null;
26
+
27
+ async function fetchSpec(server) {
28
+ const res = await server.inject({ method: 'get', url: SPEC_URL });
29
+
30
+ if (res.statusCode !== 200) {
31
+ throw new Error(`Failed to load the API specification (HTTP ${res.statusCode})`);
32
+ }
33
+
34
+ // hapi returns the handler's own object for an in-process inject, so the JSON parse
35
+ // is only the fallback for a serialized payload
36
+ if (res.result && typeof res.result === 'object') {
37
+ return res.result;
38
+ }
39
+
40
+ return JSON.parse(res.payload);
41
+ }
42
+
43
+ function getModel(server) {
44
+ if (!modelPromise) {
45
+ modelPromise = fetchSpec(server)
46
+ .then(buildModel)
47
+ .catch(err => {
48
+ modelPromise = null;
49
+ throw err;
50
+ });
51
+ }
52
+
53
+ return modelPromise;
54
+ }
55
+
56
+ // Base address used in the generated samples. The configured public URL wins, because
57
+ // that is the address callers actually use; otherwise the request's own origin is used,
58
+ // normalized through the URL parser so a malformed Host header cannot smuggle anything
59
+ // into the rendered snippet.
60
+ //
61
+ // serviceUrl is memoized because the shared view context already reads it for every
62
+ // admin page render, so an unmemoized read here would be a second Redis round trip for
63
+ // the same value. The worker's existing settings broadcast clears it.
64
+ let cachedServiceUrl;
65
+
66
+ function clearServiceUrlCache() {
67
+ cachedServiceUrl = undefined;
68
+ }
69
+
70
+ async function resolveBaseUrl(request) {
71
+ if (typeof cachedServiceUrl === 'undefined') {
72
+ cachedServiceUrl = (await settings.get('serviceUrl')) || null;
73
+ }
74
+
75
+ const serviceUrl = cachedServiceUrl;
76
+ if (serviceUrl) {
77
+ try {
78
+ return new URL(serviceUrl).origin;
79
+ } catch (err) {
80
+ // fall through to the request origin
81
+ }
82
+ }
83
+
84
+ try {
85
+ return new URL(`${request.server.info.protocol}://${request.info.host}`).origin;
86
+ } catch (err) {
87
+ return FALLBACK_BASE_URL;
88
+ }
89
+ }
90
+
91
+ // Per-request copy of an operation carrying its code samples. The cached model is never
92
+ // mutated - samples embed the base URL, which differs between callers.
93
+ function withSamples(operation, baseUrl) {
94
+ return Object.assign({}, operation, {
95
+ samples: buildCodeSamples(operation, baseUrl, operation.body && operation.body.exampleValue, operation.body && operation.body.exampleJson)
96
+ });
97
+ }
98
+
99
+ // Navigation model shared by every reference page: all tags, with the active one marked.
100
+ // activeSlug is null on the overview page, which the nav marks instead.
101
+ //
102
+ // Every tag carries its operations, not only the active one. Below the layout's lg breakpoint
103
+ // the nav is a disclosure, where tapping a group opens its list in place instead of loading
104
+ // its page (views/partials/reference/nav.hbs), so the rows of a group you are not on have to
105
+ // already be there. The active tag's entries are in-page anchors - the same links the scroll
106
+ // spy tracks - and every other tag's carry the page they live on.
107
+ function buildNav(model, activeSlug) {
108
+ return model.tags.map(tag => {
109
+ const active = tag.slug === activeSlug;
110
+
111
+ return {
112
+ name: tag.name,
113
+ slug: tag.slug,
114
+ url: tag.url,
115
+ operationCount: tag.operationCount,
116
+ active,
117
+ operations: tag.operations.map(operation => ({
118
+ summary: operation.summary || operation.path,
119
+ // The active tag's entries have to stay bare fragments: initScrollSpy matches
120
+ // them literally, as a[href="#<id>"], to mark the operation being read.
121
+ url: active ? `#${operation.id}` : operationUrl(tag.slug, operation.id)
122
+ }))
123
+ };
124
+ });
125
+ }
126
+
127
+ // Serializes a value for embedding in a <script> element. JSON.stringify escapes quotes but
128
+ // NOT `<`, so a string containing `</script` would close the element and everything after it
129
+ // would be parsed as HTML. Nothing in this map can contain one today - operation ids are
130
+ // [A-Za-z0-9_] and slugs are [a-z0-9-] - but that is a property of the inputs, and this makes
131
+ // it a property of the sink instead. U+2028/2029 are escaped too: legal in JSON, but line
132
+ // terminators in JavaScript source.
133
+ function jsonForScript(value) {
134
+ return JSON.stringify(value)
135
+ .replace(/</g, '\\u003c')
136
+ .replace(/\u2028/g, '\\u2028')
137
+ .replace(/\u2029/g, '\\u2029');
138
+ }
139
+
140
+ // Lookup tables for the /admin/swagger compatibility redirect. The old swagger-ui page deep
141
+ // linked as `#/Tag/operationId`, and a fragment never reaches the server, so the mapping has
142
+ // to be done in the browser.
143
+ //
144
+ // Operations map to their tag SLUG rather than a full URL: the shim composes the URL, which
145
+ // halves the payload since the operation id is already the key.
146
+ //
147
+ // The lookup is keyed on the operation id alone, deliberately ignoring the tag in the old
148
+ // hash - tags get renamed (the Chat endpoints now sit under "Deprecated endpoints (Document
149
+ // Store)"), which would strand every link that named the old one. The tag table is only a
150
+ // second chance for a link whose operation no longer exists but whose group still does.
151
+ let redirectMapJson;
152
+
153
+ async function getRedirectView(request) {
154
+ const model = await getModel(request.server);
155
+
156
+ if (!redirectMapJson) {
157
+ redirectMapJson = jsonForScript({
158
+ operations: Object.fromEntries(model.searchIndex.map(entry => [entry.id, entry.url.split('#')[0].split('/').pop()])),
159
+ tags: Object.fromEntries(model.tags.map(tag => [tag.name.toLowerCase(), tag.slug]))
160
+ });
161
+ }
162
+
163
+ return { redirectMap: redirectMapJson };
164
+ }
165
+
166
+ // Just the sidebar, for the reference pages that render no operations of their own
167
+ // (the access-token page).
168
+ async function getNavView(request) {
169
+ const model = await getModel(request.server);
170
+
171
+ return {
172
+ nav: buildNav(model, null),
173
+ // marks the nav's "Access token" entry as current
174
+ tokenActive: true,
175
+ searchIndex: model.searchIndex
176
+ };
177
+ }
178
+
179
+ // Landing page: the tag directory plus the counts shown on it.
180
+ async function getIndexView(request) {
181
+ const model = await getModel(request.server);
182
+
183
+ return {
184
+ version: model.version,
185
+ descriptionHtml: model.descriptionHtml,
186
+ operationCount: model.operationCount,
187
+ tags: model.tags,
188
+ nav: buildNav(model, null),
189
+ // marks the nav's "Overview" entry as current
190
+ overviewActive: true,
191
+ baseUrl: await resolveBaseUrl(request),
192
+ searchIndex: model.searchIndex
193
+ };
194
+ }
195
+
196
+ // Per-tag page. Returns null when the slug does not match a tag, so the route can 404.
197
+ async function getTagView(request, slug) {
198
+ const model = await getModel(request.server);
199
+
200
+ const tag = model.tagsBySlug.get(slug);
201
+ if (!tag) {
202
+ return null;
203
+ }
204
+
205
+ const baseUrl = await resolveBaseUrl(request);
206
+
207
+ return {
208
+ tag,
209
+ operations: tag.operations.map(operation => withSamples(operation, baseUrl)),
210
+ nav: buildNav(model, slug),
211
+ searchIndex: model.searchIndex
212
+ };
213
+ }
214
+
215
+ module.exports = {
216
+ getModel,
217
+ getRedirectView,
218
+ getNavView,
219
+ getIndexView,
220
+ getTagView,
221
+ clearServiceUrlCache
222
+ };
@@ -0,0 +1,338 @@
1
+ 'use strict';
2
+
3
+ // Builds the render model for the API reference from the OpenAPI document.
4
+ //
5
+ // Everything derived here depends only on the spec, so the result is built once per
6
+ // API worker and shared by every request. Anything that depends on the request (the
7
+ // base URL used in the code samples) is applied later, in lib/api-reference/index.js.
8
+
9
+ const { formatDescription, slugify, tagUrl, operationUrl, methodVariant, constraintList, stringifyExample } = require('./format');
10
+ const { buildSchemaTree, buildExample, typeLabel, enumInfo, requiredFirst } = require('./schema-tree');
11
+ const { readCodeSamples } = require('./code-samples');
12
+ const { NOTES_SEPARATOR } = require('../openapi');
13
+
14
+ const METHOD_ORDER = ['get', 'post', 'put', 'patch', 'delete', 'options', 'head'];
15
+
16
+ const JSON_CONTENT_TYPE = 'application/json';
17
+
18
+ function statusVariant(code) {
19
+ const numeric = Number(code);
20
+ if (numeric >= 200 && numeric < 300) {
21
+ return 'success';
22
+ }
23
+ if (numeric >= 400 && numeric < 500) {
24
+ return 'warning';
25
+ }
26
+ if (numeric >= 500) {
27
+ return 'error';
28
+ }
29
+ return 'neutral';
30
+ }
31
+
32
+ // Picks the media type to document. Every operation in the current document either
33
+ // speaks JSON or streams (text/event-stream, application/octet-stream); JSON is
34
+ // preferred so the schema tree and examples have something to render.
35
+ function pickContent(content) {
36
+ if (!content || typeof content !== 'object') {
37
+ return null;
38
+ }
39
+
40
+ const types = Object.keys(content);
41
+ if (!types.length) {
42
+ return null;
43
+ }
44
+
45
+ const contentType = types.includes(JSON_CONTENT_TYPE) ? JSON_CONTENT_TYPE : types[0];
46
+ return { contentType, media: content[contentType] };
47
+ }
48
+
49
+ function buildParameter(spec, parameter, operationId) {
50
+ const schema = parameter.schema || {};
51
+
52
+ const view = {
53
+ name: parameter.name,
54
+ anchor: `${operationId}.param.${parameter.name}`,
55
+ in: parameter.in,
56
+ required: !!parameter.required,
57
+ typeLabel: typeLabel(spec, schema),
58
+ descriptionHtml: formatDescription(parameter.description || schema.description),
59
+ constraints: constraintList(schema),
60
+ deprecated: !!parameter.deprecated,
61
+ // Booleans and enums render as a select in the try-it form, not a text field
62
+ isBoolean: schema.type === 'boolean'
63
+ };
64
+
65
+ const enums = enumInfo(schema);
66
+ if (enums) {
67
+ view.enumValues = enums.values;
68
+ view.enumDocumented = enums.documented;
69
+ }
70
+
71
+ if (typeof schema.default !== 'undefined') {
72
+ view.defaultValue = typeof schema.default === 'string' ? schema.default : JSON.stringify(schema.default);
73
+ }
74
+
75
+ if (typeof schema.example !== 'undefined') {
76
+ view.exampleValue = typeof schema.example === 'string' ? schema.example : JSON.stringify(schema.example);
77
+ }
78
+
79
+ // Prefilled value for the try-it form, so an operation can be executed after filling
80
+ // in only the values that are genuinely instance specific. Left undefined when the
81
+ // schema offers nothing, which renders as an empty field.
82
+ view.tryValue = view.exampleValue ?? view.defaultValue;
83
+
84
+ // Value substituted into the generated code samples. Unlike tryValue this always
85
+ // resolves, so a snippet shows `<account>` rather than an empty path segment.
86
+ view.sampleValue = view.tryValue ?? (view.enumValues && view.enumValues[0].value) ?? `<${parameter.name}>`;
87
+
88
+ return view;
89
+ }
90
+
91
+ function buildBody(spec, requestBody, operationId) {
92
+ if (!requestBody) {
93
+ return null;
94
+ }
95
+
96
+ const picked = pickContent(requestBody.content);
97
+ if (!picked) {
98
+ return null;
99
+ }
100
+
101
+ const schema = picked.media.schema;
102
+ const exampleValue = typeof picked.media.example !== 'undefined' ? picked.media.example : buildExample(spec, schema);
103
+
104
+ return {
105
+ contentType: picked.contentType,
106
+ descriptionHtml: formatDescription(requestBody.description),
107
+ tree: buildSchemaTree(spec, schema, `${operationId}.body`),
108
+ exampleValue,
109
+ exampleJson: stringifyExample(exampleValue)
110
+ };
111
+ }
112
+
113
+ // Tab ids are built here rather than in the template because ui/tabs neutralizes its own
114
+ // hash params inside the partial block, which puts the operation id out of reach for
115
+ // composing them there.
116
+ function buildResponses(spec, responses, operationId) {
117
+ if (!responses) {
118
+ return [];
119
+ }
120
+
121
+ const entries = Object.keys(responses).map(code => {
122
+ const response = responses[code] || {};
123
+ const variant = statusVariant(code);
124
+ const picked = pickContent(response.content);
125
+ const schema = picked && picked.media.schema;
126
+ const exampleValue = picked && typeof picked.media.example !== 'undefined' ? picked.media.example : buildExample(spec, schema);
127
+
128
+ return {
129
+ code,
130
+ variant,
131
+ descriptionHtml: formatDescription(response.description),
132
+ contentType: picked ? picked.contentType : null,
133
+ // Property trees are built for success responses only. The document has 474
134
+ // non-2xx responses sharing 8 distinct shapes - all variations on the
135
+ // {statusCode, error, message} envelope - so expanding them per operation
136
+ // added 2,400 of a tag page's 4,400 tree nodes and a quarter of its bytes to
137
+ // restate the same thing. The error envelope is documented once on the
138
+ // landing page, and each response still carries its own example.
139
+ tree: schema && variant === 'success' ? buildSchemaTree(spec, schema, `${operationId}.resp.${code}`) : null,
140
+ exampleJson: schema ? stringifyExample(exampleValue) : ''
141
+ };
142
+ });
143
+
144
+ return entries.map((entry, index) =>
145
+ Object.assign(entry, {
146
+ tabId: `${operationId}-resp-${entry.code}`,
147
+ active: index === 0
148
+ })
149
+ );
150
+ }
151
+
152
+ function buildOperation(spec, path, method, operation, tagName) {
153
+ // Resolved first because it is the anchor prefix every parameter, property and
154
+ // response node below hangs its own id off
155
+ const id = operation.operationId || slugify(`${method}-${path}`);
156
+
157
+ const parameters = (operation.parameters || []).map(parameter => buildParameter(spec, parameter, id));
158
+
159
+ const body = buildBody(spec, operation.requestBody, id);
160
+
161
+ // Behavior notes (lib/api-routes/behavior-notes.js): things the schemas cannot express,
162
+ // like "a 2xx means queued, not sent", or a provider that handles the call differently.
163
+ //
164
+ // Routes declare them twice on purpose. They are appended to the route's `notes` array,
165
+ // which the generator joins into the standard `description` - so every consumer of
166
+ // /swagger.json gets them, not just this page. They are ALSO listed under the
167
+ // x-ee-behavior extension so this renderer can tell them apart from the operation's own
168
+ // prose and pull them into their own callout. A test asserts the two stay in step.
169
+ const behaviorNotes = Array.isArray(operation['x-ee-behavior']) ? operation['x-ee-behavior'] : [];
170
+
171
+ // Split back on the separator the generator joined the route's `notes` array with, so the two
172
+ // halves of that contract cannot drift apart
173
+ const paragraphs = (operation.description || '').split(NOTES_SEPARATOR);
174
+ const prose = paragraphs.filter(paragraph => !behaviorNotes.includes(paragraph));
175
+
176
+ return {
177
+ id,
178
+ behavior: behaviorNotes.map(note => formatDescription(note)),
179
+ // Hand-written snippets the route declared; buildCodeSamples() puts them ahead of
180
+ // the generated ones
181
+ codeSamples: readCodeSamples(operation),
182
+ method: method.toLowerCase(),
183
+ methodLabel: method.toUpperCase(),
184
+ methodVariant: methodVariant(method),
185
+ path,
186
+ summary: operation.summary || '',
187
+ descriptionHtml: formatDescription(prose.join('\n\n')),
188
+ deprecated: !!operation.deprecated,
189
+ tag: tagName,
190
+ tagSlug: slugify(tagName),
191
+ // Path parameters keep their order in the path, which is the only order that makes
192
+ // sense for them. The other two are grouped required-first: GET /v1/settings carries
193
+ // 106 query parameters, and the handful that are mandatory should not be buried.
194
+ pathParams: parameters.filter(parameter => parameter.in === 'path'),
195
+ queryParams: requiredFirst(parameters.filter(parameter => parameter.in === 'query')),
196
+ headerParams: requiredFirst(parameters.filter(parameter => parameter.in === 'header')),
197
+ body,
198
+ responses: buildResponses(spec, operation.responses, id)
199
+ };
200
+ }
201
+
202
+ // Collects the property names in a schema tree, at every depth.
203
+ function collectNames(node, into) {
204
+ if (!node) {
205
+ return;
206
+ }
207
+
208
+ if (node.name) {
209
+ into.add(node.name);
210
+ }
211
+
212
+ for (const child of node.children) {
213
+ collectNames(child, into);
214
+ }
215
+ for (const variant of node.variants) {
216
+ collectNames(variant, into);
217
+ }
218
+ }
219
+
220
+ // The whole corpus the sidebar filter matches an operation against. Built here rather than
221
+ // interpolated in reference/nav.hbs so that what is searchable is decided in one place -
222
+ // the template just emits it.
223
+ //
224
+ // It is more than the hit row displays. The two questions the filter could not answer
225
+ // before are "which endpoint takes a `mailbox`" and "which one accepts `mailMerge`", so it
226
+ // also carries the operation id and every name a caller can SEND: query and header
227
+ // parameters, and request body properties at any depth. Path parameters are already covered
228
+ // by the path itself, which spells them out as `{account}`.
229
+ //
230
+ // Response property names are deliberately left out. The filter ANDs plain substrings, so
231
+ // every added term is also a chance to match something unrelated - and response shapes
232
+ // repeat the same envelope fields (`account`, `id`, `messages`) across most operations,
233
+ // which would blunt exactly the queries this is for. Descriptions are left out for the same
234
+ // reason, and because they are the bulk of the bytes.
235
+ function searchCorpus(operation) {
236
+ const terms = new Set([operation.methodLabel, operation.path, operation.summary, operation.tag, operation.id]);
237
+
238
+ for (const parameter of [...operation.queryParams, ...operation.headerParams]) {
239
+ terms.add(parameter.name);
240
+ }
241
+
242
+ if (operation.body) {
243
+ collectNames(operation.body.tree, terms);
244
+ }
245
+
246
+ terms.delete('');
247
+ return [...terms].join(' ');
248
+ }
249
+
250
+ // Sorts operations inside a tag the way the old swagger-ui page did (`sortEndpoints:
251
+ // 'method'`), so the ordering people are used to carries over.
252
+ function sortOperations(operations) {
253
+ return operations.sort((a, b) => {
254
+ const methodDiff = METHOD_ORDER.indexOf(a.method) - METHOD_ORDER.indexOf(b.method);
255
+ if (methodDiff) {
256
+ return methodDiff;
257
+ }
258
+ return a.path.localeCompare(b.path);
259
+ });
260
+ }
261
+
262
+ function buildModel(spec) {
263
+ const tagsByName = new Map();
264
+
265
+ // Seed from the spec's tag list first so the declared order (the `tags` array in
266
+ // lib/swagger-options.js) drives the navigation, not path iteration order
267
+ for (const tag of spec.tags || []) {
268
+ tagsByName.set(tag.name, {
269
+ name: tag.name,
270
+ slug: slugify(tag.name),
271
+ url: tagUrl(slugify(tag.name)),
272
+ descriptionHtml: formatDescription(tag.description),
273
+ externalDocs: tag.externalDocs && tag.externalDocs.url ? tag.externalDocs : null,
274
+ operations: []
275
+ });
276
+ }
277
+
278
+ const allOperations = [];
279
+
280
+ for (const path of Object.keys(spec.paths || {})) {
281
+ const pathItem = spec.paths[path] || {};
282
+ for (const method of Object.keys(pathItem)) {
283
+ if (!METHOD_ORDER.includes(method.toLowerCase())) {
284
+ continue;
285
+ }
286
+
287
+ const operation = pathItem[method];
288
+ const tagName = (operation.tags && operation.tags[0]) || 'Other';
289
+
290
+ if (!tagsByName.has(tagName)) {
291
+ tagsByName.set(tagName, {
292
+ name: tagName,
293
+ slug: slugify(tagName),
294
+ url: tagUrl(slugify(tagName)),
295
+ descriptionHtml: '',
296
+ externalDocs: null,
297
+ operations: []
298
+ });
299
+ }
300
+
301
+ const view = buildOperation(spec, path, method, operation, tagName);
302
+ tagsByName.get(tagName).operations.push(view);
303
+ allOperations.push(view);
304
+ }
305
+ }
306
+
307
+ const tags = [...tagsByName.values()].filter(tag => tag.operations.length);
308
+ for (const tag of tags) {
309
+ sortOperations(tag.operations);
310
+ tag.operationCount = tag.operations.length;
311
+ }
312
+
313
+ return {
314
+ version: (spec.info && spec.info.version) || '',
315
+ // The document's own introduction, rendered on the landing page rather than
316
+ // restated there. It is written as plain paragraphs for exactly this reason -
317
+ // see the `info` block in workers/api.js.
318
+ descriptionHtml: formatDescription(spec.info && spec.info.description),
319
+ tags,
320
+ tagsBySlug: new Map(tags.map(tag => [tag.slug, tag])),
321
+ operationCount: allOperations.length,
322
+ // Flat list backing the client-side filter on every page
323
+ searchIndex: allOperations.map(operation => ({
324
+ id: operation.id,
325
+ method: operation.methodLabel,
326
+ methodVariant: operation.methodVariant,
327
+ path: operation.path,
328
+ summary: operation.summary,
329
+ tag: operation.tag,
330
+ search: searchCorpus(operation),
331
+ url: operationUrl(operation.tagSlug, operation.id)
332
+ }))
333
+ };
334
+ }
335
+
336
+ module.exports = {
337
+ buildModel
338
+ };