emailengine-app 2.76.0 → 2.77.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 (102) hide show
  1. package/.github/workflows/release.yaml +24 -19
  2. package/.ncurc.js +14 -2
  3. package/.release-please-manifest.json +3 -0
  4. package/CHANGELOG.md +23 -0
  5. package/README.md +1 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/encrypt.js +71 -4
  8. package/lib/address-strategies.js +18 -0
  9. package/lib/api-reference/code-samples.js +194 -0
  10. package/lib/api-reference/format.js +179 -0
  11. package/lib/api-reference/index.js +205 -0
  12. package/lib/api-reference/model.js +336 -0
  13. package/lib/api-reference/schema-tree.js +366 -0
  14. package/lib/api-routes/account-routes.js +117 -37
  15. package/lib/api-routes/behavior-notes.js +54 -0
  16. package/lib/api-routes/blocklist-routes.js +9 -9
  17. package/lib/api-routes/changes-routes.js +6 -4
  18. package/lib/api-routes/chat-routes.js +3 -3
  19. package/lib/api-routes/delivery-test-routes.js +24 -6
  20. package/lib/api-routes/export-routes.js +14 -12
  21. package/lib/api-routes/gateway-routes.js +11 -11
  22. package/lib/api-routes/license-routes.js +7 -7
  23. package/lib/api-routes/mailbox-routes.js +18 -9
  24. package/lib/api-routes/message-routes.js +55 -35
  25. package/lib/api-routes/oauth2-app-routes.js +22 -16
  26. package/lib/api-routes/outbox-routes.js +7 -7
  27. package/lib/api-routes/pubsub-routes.js +3 -3
  28. package/lib/api-routes/settings-routes.js +10 -9
  29. package/lib/api-routes/stats-routes.js +3 -3
  30. package/lib/api-routes/submit-routes.js +58 -8
  31. package/lib/api-routes/template-routes.js +13 -13
  32. package/lib/api-routes/token-routes.js +15 -10
  33. package/lib/api-routes/webhook-route-routes.js +5 -5
  34. package/lib/consts.js +7 -0
  35. package/lib/email-client/base-client.js +66 -12
  36. package/lib/enum-descriptions.js +130 -0
  37. package/lib/imapproxy/imap-server.js +30 -26
  38. package/lib/imapproxy/upstream-client.js +38 -0
  39. package/lib/oauth2-apps.js +9 -3
  40. package/lib/openapi/build-document.js +318 -0
  41. package/lib/openapi/index.js +95 -0
  42. package/lib/openapi/joi-schema.js +523 -0
  43. package/lib/routes-ui.js +5 -1
  44. package/lib/schemas.js +76 -17
  45. package/lib/swagger-options.js +173 -0
  46. package/lib/tokens.js +69 -5
  47. package/lib/ui-routes/admin-entities-routes.js +3 -0
  48. package/lib/ui-routes/dashboard-routes.js +2 -26
  49. package/lib/ui-routes/reference-routes.js +195 -0
  50. package/lib/ui-routes/route-helpers.js +11 -0
  51. package/package.json +9 -11
  52. package/prepare-bundle-deps.sh +28 -0
  53. package/release-please-config.json +11 -0
  54. package/sbom.json +0 -1
  55. package/server.js +10 -2
  56. package/static/css/flyonui.css +1 -1
  57. package/static/css/src/app.tailwind.css +90 -0
  58. package/static/js/ee-client.js +238 -8
  59. package/static/js/reference.js +736 -0
  60. package/static/js/ui.js +61 -33
  61. package/static/licenses.html +4 -4
  62. package/translations/messages.pot +27 -27
  63. package/views/config/ai.hbs +1 -1
  64. package/views/config/document-store/chat.hbs +5 -5
  65. package/views/config/document-store/index.hbs +2 -2
  66. package/views/config/document-store/pre-processing/index.hbs +1 -1
  67. package/views/config/email-processing.hbs +1 -1
  68. package/views/config/imap-proxy.hbs +1 -1
  69. package/views/config/license.hbs +1 -1
  70. package/views/config/oauth/index.hbs +3 -3
  71. package/views/config/security.hbs +1 -1
  72. package/views/config/smtp.hbs +2 -2
  73. package/views/dashboard.hbs +1 -1
  74. package/views/layout/app.hbs +18 -7
  75. package/views/partials/oauth_form.hbs +4 -4
  76. package/views/partials/reference/anchor-link.hbs +20 -0
  77. package/views/partials/reference/disclosure.hbs +37 -0
  78. package/views/partials/reference/nav.hbs +93 -0
  79. package/views/partials/reference/operation.hbs +127 -0
  80. package/views/partials/reference/params.hbs +20 -0
  81. package/views/partials/reference/schema-node.hbs +99 -0
  82. package/views/partials/reference/schema.hbs +19 -0
  83. package/views/partials/reference/section-heading.hbs +16 -0
  84. package/views/partials/reference/token-alert.hbs +24 -0
  85. package/views/partials/reference/try-field.hbs +31 -0
  86. package/views/partials/reference/try-it.hbs +78 -0
  87. package/views/partials/side_menu.hbs +1 -1
  88. package/views/partials/ui/badge.hbs +4 -2
  89. package/views/partials/ui/page-header.hbs +1 -1
  90. package/views/partials/ui/search-input.hbs +31 -0
  91. package/views/partials/ui/setting-ref.hbs +1 -1
  92. package/views/partials/ui/stat-card.hbs +4 -2
  93. package/views/partials/ui/tab.hbs +6 -1
  94. package/views/partials/ui/tabs.hbs +2 -2
  95. package/views/reference/index.hbs +76 -0
  96. package/views/reference/redirect.hbs +49 -0
  97. package/views/reference/tag.hbs +28 -0
  98. package/views/reference/token.hbs +49 -0
  99. package/views/tokens/index.hbs +9 -1
  100. package/views/webhooks/index.hbs +3 -3
  101. package/workers/api.js +37 -215
  102. package/views/swagger/index.hbs +0 -82
@@ -0,0 +1,205 @@
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
+
18
+ const SPEC_URL = '/swagger.json';
19
+
20
+ const FALLBACK_BASE_URL = 'https://your-emailengine-host';
21
+
22
+ // The in-flight or resolved model. Caching the promise itself means concurrent first
23
+ // requests share one load; a failed load clears the slot so the next request retries.
24
+ let modelPromise = null;
25
+
26
+ async function fetchSpec(server) {
27
+ const res = await server.inject({ method: 'get', url: SPEC_URL });
28
+
29
+ if (res.statusCode !== 200) {
30
+ throw new Error(`Failed to load the API specification (HTTP ${res.statusCode})`);
31
+ }
32
+
33
+ // hapi returns the handler's own object for an in-process inject, so the JSON parse
34
+ // is only the fallback for a serialized payload
35
+ if (res.result && typeof res.result === 'object') {
36
+ return res.result;
37
+ }
38
+
39
+ return JSON.parse(res.payload);
40
+ }
41
+
42
+ function getModel(server) {
43
+ if (!modelPromise) {
44
+ modelPromise = fetchSpec(server)
45
+ .then(buildModel)
46
+ .catch(err => {
47
+ modelPromise = null;
48
+ throw err;
49
+ });
50
+ }
51
+
52
+ return modelPromise;
53
+ }
54
+
55
+ // Base address used in the generated samples. The configured public URL wins, because
56
+ // that is the address callers actually use; otherwise the request's own origin is used,
57
+ // normalized through the URL parser so a malformed Host header cannot smuggle anything
58
+ // into the rendered snippet.
59
+ //
60
+ // serviceUrl is memoized because the shared view context already reads it for every
61
+ // admin page render, so an unmemoized read here would be a second Redis round trip for
62
+ // the same value. The worker's existing settings broadcast clears it.
63
+ let cachedServiceUrl;
64
+
65
+ function clearServiceUrlCache() {
66
+ cachedServiceUrl = undefined;
67
+ }
68
+
69
+ async function resolveBaseUrl(request) {
70
+ if (typeof cachedServiceUrl === 'undefined') {
71
+ cachedServiceUrl = (await settings.get('serviceUrl')) || null;
72
+ }
73
+
74
+ const serviceUrl = cachedServiceUrl;
75
+ if (serviceUrl) {
76
+ try {
77
+ return new URL(serviceUrl).origin;
78
+ } catch (err) {
79
+ // fall through to the request origin
80
+ }
81
+ }
82
+
83
+ try {
84
+ return new URL(`${request.server.info.protocol}://${request.info.host}`).origin;
85
+ } catch (err) {
86
+ return FALLBACK_BASE_URL;
87
+ }
88
+ }
89
+
90
+ // Per-request copy of an operation carrying its code samples. The cached model is never
91
+ // mutated - samples embed the base URL, which differs between callers.
92
+ function withSamples(operation, baseUrl) {
93
+ return Object.assign({}, operation, {
94
+ samples: buildCodeSamples(operation, baseUrl, operation.body && operation.body.exampleValue, operation.body && operation.body.exampleJson)
95
+ });
96
+ }
97
+
98
+ // Navigation model shared by every reference page: all tags, with the active one marked.
99
+ // activeSlug is null on the overview page, which the nav marks instead.
100
+ function buildNav(model, activeSlug) {
101
+ return model.tags.map(tag => ({
102
+ name: tag.name,
103
+ slug: tag.slug,
104
+ operationCount: tag.operationCount,
105
+ active: tag.slug === activeSlug,
106
+ operations: tag.slug === activeSlug ? tag.operations.map(operation => ({ id: operation.id, summary: operation.summary || operation.path })) : []
107
+ }));
108
+ }
109
+
110
+ // Serializes a value for embedding in a <script> element. JSON.stringify escapes quotes but
111
+ // NOT `<`, so a string containing `</script` would close the element and everything after it
112
+ // would be parsed as HTML. Nothing in this map can contain one today - operation ids are
113
+ // [A-Za-z0-9_] and slugs are [a-z0-9-] - but that is a property of the inputs, and this makes
114
+ // it a property of the sink instead. U+2028/2029 are escaped too: legal in JSON, but line
115
+ // terminators in JavaScript source.
116
+ function jsonForScript(value) {
117
+ return JSON.stringify(value)
118
+ .replace(/</g, '\\u003c')
119
+ .replace(/\u2028/g, '\\u2028')
120
+ .replace(/\u2029/g, '\\u2029');
121
+ }
122
+
123
+ // Lookup tables for the /admin/swagger compatibility redirect. The old swagger-ui page deep
124
+ // linked as `#/Tag/operationId`, and a fragment never reaches the server, so the mapping has
125
+ // to be done in the browser.
126
+ //
127
+ // Operations map to their tag SLUG rather than a full URL: the shim composes the URL, which
128
+ // halves the payload since the operation id is already the key.
129
+ //
130
+ // The lookup is keyed on the operation id alone, deliberately ignoring the tag in the old
131
+ // hash - tags get renamed (the Chat endpoints now sit under "Deprecated endpoints (Document
132
+ // Store)"), which would strand every link that named the old one. The tag table is only a
133
+ // second chance for a link whose operation no longer exists but whose group still does.
134
+ let redirectMapJson;
135
+
136
+ async function getRedirectView(request) {
137
+ const model = await getModel(request.server);
138
+
139
+ if (!redirectMapJson) {
140
+ redirectMapJson = jsonForScript({
141
+ operations: Object.fromEntries(model.searchIndex.map(entry => [entry.id, entry.url.split('#')[0].split('/').pop()])),
142
+ tags: Object.fromEntries(model.tags.map(tag => [tag.name.toLowerCase(), tag.slug]))
143
+ });
144
+ }
145
+
146
+ return { redirectMap: redirectMapJson };
147
+ }
148
+
149
+ // Just the sidebar, for the reference pages that render no operations of their own
150
+ // (the access-token page).
151
+ async function getNavView(request) {
152
+ const model = await getModel(request.server);
153
+
154
+ return {
155
+ nav: buildNav(model, null),
156
+ // marks the nav's "Access token" entry as current
157
+ tokenActive: true,
158
+ searchIndex: model.searchIndex
159
+ };
160
+ }
161
+
162
+ // Landing page: the tag directory plus the counts shown on it.
163
+ async function getIndexView(request) {
164
+ const model = await getModel(request.server);
165
+
166
+ return {
167
+ version: model.version,
168
+ descriptionHtml: model.descriptionHtml,
169
+ operationCount: model.operationCount,
170
+ tags: model.tags,
171
+ nav: buildNav(model, null),
172
+ // marks the nav's "Overview" entry as current
173
+ overviewActive: true,
174
+ baseUrl: await resolveBaseUrl(request),
175
+ searchIndex: model.searchIndex
176
+ };
177
+ }
178
+
179
+ // Per-tag page. Returns null when the slug does not match a tag, so the route can 404.
180
+ async function getTagView(request, slug) {
181
+ const model = await getModel(request.server);
182
+
183
+ const tag = model.tagsBySlug.get(slug);
184
+ if (!tag) {
185
+ return null;
186
+ }
187
+
188
+ const baseUrl = await resolveBaseUrl(request);
189
+
190
+ return {
191
+ tag,
192
+ operations: tag.operations.map(operation => withSamples(operation, baseUrl)),
193
+ nav: buildNav(model, slug),
194
+ searchIndex: model.searchIndex
195
+ };
196
+ }
197
+
198
+ module.exports = {
199
+ getModel,
200
+ getRedirectView,
201
+ getNavView,
202
+ getIndexView,
203
+ getTagView,
204
+ clearServiceUrlCache
205
+ };
@@ -0,0 +1,336 @@
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, 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
+ descriptionHtml: formatDescription(tag.description),
272
+ externalDocs: tag.externalDocs && tag.externalDocs.url ? tag.externalDocs : null,
273
+ operations: []
274
+ });
275
+ }
276
+
277
+ const allOperations = [];
278
+
279
+ for (const path of Object.keys(spec.paths || {})) {
280
+ const pathItem = spec.paths[path] || {};
281
+ for (const method of Object.keys(pathItem)) {
282
+ if (!METHOD_ORDER.includes(method.toLowerCase())) {
283
+ continue;
284
+ }
285
+
286
+ const operation = pathItem[method];
287
+ const tagName = (operation.tags && operation.tags[0]) || 'Other';
288
+
289
+ if (!tagsByName.has(tagName)) {
290
+ tagsByName.set(tagName, {
291
+ name: tagName,
292
+ slug: slugify(tagName),
293
+ descriptionHtml: '',
294
+ externalDocs: null,
295
+ operations: []
296
+ });
297
+ }
298
+
299
+ const view = buildOperation(spec, path, method, operation, tagName);
300
+ tagsByName.get(tagName).operations.push(view);
301
+ allOperations.push(view);
302
+ }
303
+ }
304
+
305
+ const tags = [...tagsByName.values()].filter(tag => tag.operations.length);
306
+ for (const tag of tags) {
307
+ sortOperations(tag.operations);
308
+ tag.operationCount = tag.operations.length;
309
+ }
310
+
311
+ return {
312
+ version: (spec.info && spec.info.version) || '',
313
+ // The document's own introduction, rendered on the landing page rather than
314
+ // restated there. It is written as plain paragraphs for exactly this reason -
315
+ // see the `info` block in workers/api.js.
316
+ descriptionHtml: formatDescription(spec.info && spec.info.description),
317
+ tags,
318
+ tagsBySlug: new Map(tags.map(tag => [tag.slug, tag])),
319
+ operationCount: allOperations.length,
320
+ // Flat list backing the client-side filter on every page
321
+ searchIndex: allOperations.map(operation => ({
322
+ id: operation.id,
323
+ method: operation.methodLabel,
324
+ methodVariant: operation.methodVariant,
325
+ path: operation.path,
326
+ summary: operation.summary,
327
+ tag: operation.tag,
328
+ search: searchCorpus(operation),
329
+ url: `/admin/reference/${operation.tagSlug}#${operation.id}`
330
+ }))
331
+ };
332
+ }
333
+
334
+ module.exports = {
335
+ buildModel
336
+ };