@antelopejs/dms-api 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +18 -6
  2. package/dist/automation/query-request-logs.js.map +1 -1
  3. package/dist/automation/route-unhealthy.js.map +1 -1
  4. package/dist/db/models/request_log.model.js.map +1 -1
  5. package/dist/db/models/request_log.search.js +3 -3
  6. package/dist/db/models/request_log.search.js.map +1 -1
  7. package/dist/db/tables/request_log.table.js.map +1 -1
  8. package/dist/guards.d.ts +22 -0
  9. package/dist/guards.js +57 -0
  10. package/dist/guards.js.map +1 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/pages/blocks.d.ts +2 -2
  13. package/dist/pages/blocks.js +2 -2
  14. package/dist/pages/blocks.js.map +1 -1
  15. package/dist/pages/index.js.map +1 -1
  16. package/dist/pages/logs.js.map +1 -1
  17. package/dist/pages/module.js +8 -2
  18. package/dist/pages/module.js.map +1 -1
  19. package/dist/pages/overview.js.map +1 -1
  20. package/dist/pages/request-table.js.map +1 -1
  21. package/dist/pages/routes.js.map +1 -1
  22. package/dist/pages/settings.js +1 -3
  23. package/dist/pages/settings.js.map +1 -1
  24. package/dist/routes/logs.js.map +1 -1
  25. package/dist/routes/routes.js.map +1 -1
  26. package/dist/routes/settings.d.ts +2 -1
  27. package/dist/routes/settings.js +1 -1
  28. package/dist/routes/settings.js.map +1 -1
  29. package/dist/services/activity.js.map +1 -1
  30. package/dist/services/attention.js +1 -1
  31. package/dist/services/attention.js.map +1 -1
  32. package/dist/services/health-rules.js.map +1 -1
  33. package/dist/services/introspection/auth.js +1 -2
  34. package/dist/services/introspection/auth.js.map +1 -1
  35. package/dist/services/introspection/decorators.d.ts +3 -1
  36. package/dist/services/introspection/decorators.js +28 -17
  37. package/dist/services/introspection/decorators.js.map +1 -1
  38. package/dist/services/introspection/errors.d.ts +1 -1
  39. package/dist/services/introspection/errors.js +0 -2
  40. package/dist/services/introspection/errors.js.map +1 -1
  41. package/dist/services/introspection/index.d.ts +1 -1
  42. package/dist/services/introspection/index.js +24 -18
  43. package/dist/services/introspection/index.js.map +1 -1
  44. package/dist/services/introspection/probe.js.map +1 -1
  45. package/dist/services/links.js +4 -4
  46. package/dist/services/links.js.map +1 -1
  47. package/dist/services/live.d.ts +3 -2
  48. package/dist/services/live.js.map +1 -1
  49. package/dist/services/overview-lists.d.ts +4 -4
  50. package/dist/services/overview-lists.js.map +1 -1
  51. package/dist/services/overview.d.ts +4 -4
  52. package/dist/services/overview.js.map +1 -1
  53. package/dist/services/request-log/capture.d.ts +5 -14
  54. package/dist/services/request-log/capture.js +28 -76
  55. package/dist/services/request-log/capture.js.map +1 -1
  56. package/dist/services/request-log/console-traffic.d.ts +12 -0
  57. package/dist/services/request-log/console-traffic.js +69 -0
  58. package/dist/services/request-log/console-traffic.js.map +1 -0
  59. package/dist/services/request-log/list.d.ts +1 -1
  60. package/dist/services/request-log/list.js.map +1 -1
  61. package/dist/services/request-log/read.js.map +1 -1
  62. package/dist/services/request-log/redaction.js +7 -6
  63. package/dist/services/request-log/redaction.js.map +1 -1
  64. package/dist/services/request-log/util.d.ts +6 -3
  65. package/dist/services/request-log/util.js +17 -30
  66. package/dist/services/request-log/util.js.map +1 -1
  67. package/dist/services/route-catalog.js +2 -2
  68. package/dist/services/route-catalog.js.map +1 -1
  69. package/dist/services/route-contract.d.ts +6 -1
  70. package/dist/services/route-contract.js +11 -12
  71. package/dist/services/route-contract.js.map +1 -1
  72. package/dist/services/route-health.d.ts +5 -1
  73. package/dist/services/route-health.js +4 -1
  74. package/dist/services/route-health.js.map +1 -1
  75. package/dist/services/route-statistics.d.ts +3 -4
  76. package/dist/services/route-statistics.js.map +1 -1
  77. package/dist/services/routes-sync.d.ts +2 -2
  78. package/dist/services/routes-sync.js +13 -4
  79. package/dist/services/routes-sync.js.map +1 -1
  80. package/dist/services/scope.js +1 -1
  81. package/dist/services/scope.js.map +1 -1
  82. package/dist/services/settings-form.d.ts +4 -3
  83. package/dist/services/settings-form.js +1 -1
  84. package/dist/services/settings-form.js.map +1 -1
  85. package/dist/services/settings.js.map +1 -1
  86. package/dist/services/statistics-write.js +4 -7
  87. package/dist/services/statistics-write.js.map +1 -1
  88. package/dist/services/traffic-samples.js.map +1 -1
  89. package/dist/services/traffic.js +2 -1
  90. package/dist/services/traffic.js.map +1 -1
  91. package/dist/services/window.js +1 -1
  92. package/dist/services/window.js.map +1 -1
  93. package/dist/types/constants.js.map +1 -1
  94. package/dist/types/index.d.ts +1 -0
  95. package/dist/types/index.js +1 -0
  96. package/dist/types/index.js.map +1 -1
  97. package/dist/types/json.d.ts +2 -0
  98. package/dist/types/json.js +3 -0
  99. package/dist/types/json.js.map +1 -0
  100. package/frontend-vue/app/components/blocks/HealthHero.vue +8 -117
  101. package/frontend-vue/app/components/blocks/RequestDetail.vue +18 -153
  102. package/frontend-vue/app/components/blocks/RouteDocumentation.vue +2 -151
  103. package/frontend-vue/app/components/blocks/RouteHeader.vue +7 -8
  104. package/frontend-vue/app/components/blocks/RouteTester.vue +58 -1682
  105. package/frontend-vue/app/components/blocks/RouteTree.vue +16 -81
  106. package/frontend-vue/app/components/internal/HealthHeroMetrics.vue +50 -0
  107. package/frontend-vue/app/components/internal/RequestGeneral.vue +32 -0
  108. package/frontend-vue/app/components/internal/RequestTiming.vue +85 -0
  109. package/frontend-vue/app/components/internal/RouteInternals.vue +159 -0
  110. package/frontend-vue/app/components/internal/RouteTesterRequest.vue +225 -0
  111. package/frontend-vue/app/components/internal/RouteTesterResponse.vue +272 -0
  112. package/frontend-vue/app/components/internal/RouteTreeFooter.vue +62 -0
  113. package/frontend-vue/app/components/internal/routeTester/context.ts +8 -0
  114. package/frontend-vue/app/components/internal/routeTester/useTesterExtras.ts +284 -0
  115. package/frontend-vue/app/components/internal/routeTester/useTesterFlow.ts +637 -0
  116. package/frontend-vue/app/components/internal/routeTester/useTesterState.ts +601 -0
  117. package/frontend-vue/app/utils/health.ts +73 -0
  118. package/frontend-vue/app/utils/requestDrawer.ts +49 -0
  119. package/frontend-vue/app/utils/routeExplorer.ts +34 -0
  120. package/frontend-vue/app/utils/testerMasks.ts +34 -0
  121. package/frontend-vue/app/utils/testerRequest.ts +14 -38
  122. package/frontend-vue/build/backend-boundary.ts +122 -0
  123. package/frontend-vue/dms.frontend.build.ts +2 -0
  124. package/frontend-vue/eslint.config.mjs +13 -0
  125. package/frontend-vue/package.json +6 -3
  126. package/frontend-vue/pnpm-lock.yaml +348 -153
  127. package/frontend-vue/tests/apiErrorPresentation.test.ts +115 -0
  128. package/frontend-vue/tests/backend-boundary.test.ts +180 -0
  129. package/frontend-vue/tests/dmsServer.test.ts +11 -23
  130. package/frontend-vue/tests/registration.test.ts +22 -6
  131. package/frontend-vue/tests/stubs/server.ts +19 -0
  132. package/frontend-vue/tests/testerRequest.test.ts +14 -0
  133. package/frontend-vue/vitest.config.ts +16 -0
  134. package/package.json +16 -4
  135. package/skills/dms-api/SKILL.md +1 -1
  136. package/skills/dms-api/cases.json +47 -0
@@ -1,90 +1,17 @@
1
1
  <script setup lang="ts">
2
- import {
3
- computed,
4
- onBeforeUnmount,
5
- onMounted,
6
- reactive,
7
- ref,
8
- shallowRef,
9
- useId,
10
- watch,
11
- } from 'vue'
12
- import {
13
- byteLength,
14
- formatBytes,
15
- formatClock,
16
- formatMs,
17
- prettyBody,
18
- } from '../../utils/format'
19
- import {
20
- acceptsRequestBody,
21
- errorStatus,
22
- isWritingMethod,
23
- pathSegments,
24
- statusText,
25
- } from '../../utils/http'
26
- import { fillPath, toCurl } from '../../utils/snippets'
27
- import {
28
- authModeOf,
29
- type AuthMode,
30
- type BodyMode,
31
- type CapturedRequest,
32
- capturedSummary,
33
- contentTypeFor,
34
- countRedacted,
35
- formatJson,
36
- hasRedacted,
37
- inputProblem,
38
- jsonProblem,
39
- type KeyValue,
40
- createSourceTokens,
41
- markedHeaders,
42
- mergeHeaders,
43
- neverSent,
44
- newRequestId,
45
- PROXY_BODY_LIMIT,
46
- PROXY_RESPONSE_LIMIT,
47
- PROXY_TIMEOUT_MS,
48
- redactedFields,
49
- replayFrom,
50
- revealBidi,
51
- sendTesterRequest,
52
- serializeBody,
53
- SIZE_PROBE_SOURCE,
54
- TesterError,
55
- type TesterSourceToken,
56
- TESTER_SOURCE_URL,
57
- type TesterErrorCode,
58
- type TesterRequest,
59
- type TesterResult,
60
- withQueryRows,
61
- } from '../../utils/testerRequest'
62
- import {
63
- type BodyOrigin,
64
- type DraftRequest,
65
- exampleRequest,
66
- hasConfirmedWrite,
67
- type HistoryEntry,
68
- HISTORY_MAX,
69
- historyEntry,
70
- isSecretHeader,
71
- loadCommonHeaders,
72
- loadDraft,
73
- loadHistory,
74
- lostSecrets,
75
- patchResult,
76
- rememberConfirmedWrite,
77
- type ReplayInfo,
78
- sameRequest,
79
- saveCommonHeaders,
80
- saveDraft,
81
- saveHistory,
82
- secretNames,
83
- type TesterDraft,
84
- } from '../../utils/testerHistory'
85
- import ApiKeyValues from '../internal/ApiKeyValues.vue'
2
+ import { formatBytes, formatClock, formatMs } from '../../utils/format'
3
+ import { hasRedacted } from '../../utils/testerRequest'
86
4
  import ApiMethodBadge from '../internal/ApiMethodBadge.vue'
87
5
  import ApiStatusBadge from '../internal/ApiStatusBadge.vue'
6
+ import RouteTesterRequest from '../internal/RouteTesterRequest.vue'
7
+ import RouteTesterResponse from '../internal/RouteTesterResponse.vue'
8
+ import type { TesterContext } from '../internal/routeTester/context'
9
+ import { useTesterExtras } from '../internal/routeTester/useTesterExtras'
10
+ import { useTesterFlow } from '../internal/routeTester/useTesterFlow'
11
+ import {
12
+ type RouteTesterProps,
13
+ useTesterState,
14
+ } from '../internal/routeTester/useTesterState'
88
15
 
89
16
  // Call the selected route from the dashboard. The URL bar holds the method,
90
17
  // the path with its parameters to fill in, and Send; the body starts from
@@ -98,1166 +25,58 @@ import ApiStatusBadge from '../internal/ApiStatusBadge.vue'
98
25
  // Typing in one of its fields holds the page's live mode ("Paused · typing in
99
26
  // the Tester"), so the route's figures do not move under the request being
100
27
  // written; leaving the Tester releases it.
101
- defineOptions({ inheritAttrs: false })
102
28
 
103
- const props = withDefaults(
104
- defineProps<{ fetchUrl: string; queryKey?: string }>(),
105
- {
106
- queryKey: 'route',
107
- },
108
- )
109
-
110
- interface Row extends KeyValue {
111
- id: number
112
- }
113
-
114
- /** A row of the logs list, as far as finding a captured call goes. */
115
- interface CapturedRow {
116
- _id: string
117
- route?: string
118
- timestamp: string
119
- requestId?: string
120
- }
121
-
122
- type CapturedState = 'idle' | 'loading' | 'found' | 'missing' | 'error'
123
-
124
- /** A backend read of the tester's own flows (a replay, a capture lookup). */
125
- type ReadJson = <R>(url: string) => Promise<R>
29
+ defineOptions({ inheritAttrs: false })
126
30
 
127
- /**
128
- * A read the tester runs when it needs it (a replay, a lookup after a call),
129
- * in the browser only and never again on the page's refreshes.
130
- */
131
- const ON_DEMAND = {
132
- immediate: false,
133
- server: false,
134
- watch: false,
135
- refreshOnPageRefresh: false,
136
- } as const
31
+ const props = withDefaults(defineProps<RouteTesterProps>(), {
32
+ queryKey: 'route',
33
+ })
137
34
 
138
- // The tester's own reads of the request logs: by its permission, not the
139
- // request logs page's.
140
- const LOGS_API = '/api/monitoring/logs/tester'
141
- const LOGS_PAGE = '/modules/api/logs'
142
- /**
143
- * Abort reason of a call left behind by a route change: filed under its
144
- * route as abandoned, since the API may have received it.
145
- */
146
- const ROUTE_CHANGED = 'route-changed'
147
- /** The capture is written once the answer is sent: looked for twice. */
148
- const CAPTURE_DELAYS_MS = [400, 1500]
149
- /** A captured call older than this is not the one just sent. */
150
- const CAPTURE_MATCH_MS = 60_000
151
- /** An id as long as a real one, to size the request before sending it. */
152
- const SIZE_PROBE_ID = '00000000-0000-0000-0000-000000000000'
153
- const DRAFT_SAVE_DELAY_MS = 250
154
- const BODY_MODES: BodyMode[] = ['json', 'text', 'form', 'none']
155
- const AUTH_ICONS: Record<AuthMode, string> = {
156
- session: 'i-ph-user-check',
157
- manual: 'i-ph-key',
158
- none: 'i-ph-lock-simple-open',
159
- }
160
- const ERROR_ICONS: Partial<Record<TesterErrorCode, string>> = {
161
- invalid_input: 'i-ph-prohibit',
162
- body_too_large: 'i-ph-file-x',
163
- not_authenticated: 'i-ph-sign-in',
164
- not_owner: 'i-ph-lock-simple',
165
- cross_origin: 'i-ph-shield-warning',
166
- response_too_large: 'i-ph-file-x',
167
- timeout: 'i-ph-timer',
168
- aborted: 'i-ph-x-circle',
35
+ const state = useTesterState(props)
36
+ const flow = useTesterFlow(state)
37
+ const tester: TesterContext = {
38
+ ...state,
39
+ ...flow,
40
+ ...useTesterExtras({ ...state, ...flow }),
169
41
  }
170
- /**
171
- * Error texts that send to the Captured tab: another text on a route the
172
- * module does not capture.
173
- */
174
- const POINTS_TO_CAPTURED: ReadonlySet<string> = new Set([
175
- 'proxy_failed',
176
- 'timeout',
177
- 'aborted',
178
- 'abandoned',
179
- ])
180
-
181
- const { t } = useI18n()
182
- const { formatLocale: locale } = useRegionalFormat({ locale: 'format' })
183
- const dateFormat = useDateFormat()
184
- const toast = useToast()
185
- const { confirm } = useConfirm()
186
- const { loggedIn } = useDmsUserSession()
187
- const currentRoute = useDmsRoute()
188
- const router = useDmsRouter()
189
- const { $authFetch } = useAuthFetch()
190
42
  const {
191
- data: route,
43
+ AUTH_ICONS,
44
+ auth,
45
+ authLabel,
46
+ blocker,
47
+ blockerId,
48
+ cancel,
49
+ clearHistory,
50
+ copyCurl,
51
+ dateFormat,
52
+ displayQuery,
53
+ filledRef,
54
+ history,
55
+ liveMessage,
56
+ locale,
57
+ loggedIn,
58
+ onFocusIn,
59
+ onFocusOut,
60
+ onKey,
61
+ path,
62
+ pathValues,
192
63
  pending,
64
+ readable,
65
+ recordLink,
66
+ replayDescription,
67
+ replayInfo,
68
+ replayTitle,
69
+ restore,
70
+ route,
71
+ segments,
193
72
  selection,
194
- } = useRouteDetail(props.fetchUrl, props.queryKey)
195
- const apiOrigin = useApiOrigin(() => route.value?.apiOrigin)
196
- const blockerId = useId()
197
- // Not a `useApiData` read: each call mints a short-lived token, which must
198
- // never be shared between calls, cached or handed over with the page.
199
- const sourceTokens = createSourceTokens(() =>
200
- $authFetch<TesterSourceToken>(TESTER_SOURCE_URL),
201
- )
202
- const bodyHintId = useId()
203
-
204
- let nextRowId = 0
205
- const row = (name = '', value = ''): Row => ({ id: nextRowId++, name, value })
206
- const rows = (list: Row[]): KeyValue[] =>
207
- list.map(({ name, value }) => ({ name, value }))
208
-
209
- const bodyMode = ref<BodyMode>('none')
210
- const body = ref('')
211
- const form = reactive<Row[]>([])
212
- const headers = reactive<Row[]>([])
213
- const query = reactive<Row[]>([])
214
- const pathValues = reactive<Record<string, string>>({})
215
- const useSession = ref(true)
216
- const origin = ref<BodyOrigin>('example')
217
- const replayInfo = ref<ReplayInfo | null>(null)
218
- const result = ref<TesterResult | null>(null)
219
- const commonHeaders = reactive<Row[]>(
220
- loadCommonHeaders().map((entry) => row(entry.name, entry.value)),
221
- )
222
- const history = ref<HistoryEntry[]>([])
223
- const tab = ref('body')
224
- const responseTab = ref('body')
225
- const sending = ref(false)
226
- const capturedState = ref<CapturedState>('idle')
227
- const capturedLog = ref<CapturedRequest | null>(null)
228
-
229
- // The route the fields belong to, the call in flight and its route.
230
- let activeRef: string | null = null
231
- // The route the fields were filled for: they come from this browser's drafts,
232
- // history and headers, so the tester shows once mounted, never on a server.
233
- const filledRef = ref<string | null>(null)
234
- let inFlight: { controller: AbortController; ref: string } | null = null
235
- let confirming = false
236
- let unmounted = false
237
-
238
- const method = computed(() => route.value?.method ?? 'GET')
239
- const bodyAllowed = computed(() => acceptsRequestBody(method.value))
240
- const writes = computed(() => isWritingMethod(method.value))
241
- const isDelete = computed(() => method.value.toUpperCase() === 'DELETE')
242
-
243
- const draftRequest = computed<DraftRequest>(() => ({
244
- bodyMode: bodyMode.value,
245
- body: body.value,
246
- form: rows(form),
247
- headers: rows(headers),
248
- query: rows(query),
249
- pathValues: { ...pathValues },
250
- useSession: useSession.value,
251
- }))
252
-
253
- const example = computed(() =>
254
- route.value
255
- ? exampleRequest(
256
- {
257
- method: route.value.method,
258
- pathParams: route.value.pathParams,
259
- exampleBody: route.value.contract.exampleBody,
260
- examplePath: route.value.contract.examplePath,
261
- authStatus: route.value.auth.status,
262
- },
263
- history.value,
264
- )
265
- : null,
266
- )
267
- const modified = computed(
268
- () => !!example.value && !sameRequest(draftRequest.value, example.value),
269
- )
270
-
271
- // --- The request as it leaves ---
272
-
273
- const segments = computed(() =>
274
- pathSegments(route.value?.path ?? '/').map((segment) => ({
275
- ...segment,
276
- name: segment.text.slice(1),
277
- })),
278
- )
279
- const path = computed(() =>
280
- withQueryRows(fillPath(route.value?.path ?? '/', pathValues), query),
281
- )
282
- const displayQuery = computed(() => {
283
- const named = query.filter((entry) => entry.name)
284
- return named.length
285
- ? revealBidi(
286
- `?${named.map((entry) => `${entry.name}=${entry.value}`).join('&')}`,
287
- )
288
- : ''
289
- })
290
- const missingPathParams = computed(() =>
291
- (route.value?.pathParams ?? []).filter((name) => !pathValues[name]),
292
- )
293
-
294
- const sentBody = computed(() =>
295
- bodyAllowed.value
296
- ? serializeBody(bodyMode.value, body.value, form)
297
- : undefined,
298
- )
299
- const impliedHeaders = computed(() => {
300
- const implied: Record<string, string> = {}
301
- const type = contentTypeFor(bodyMode.value)
302
- if (sentBody.value !== undefined && type) implied['content-type'] = type
303
- return implied
304
- })
305
- /** Headers as the API gets them, before the session and the tester's marks. */
306
- const effectiveHeaders = computed(() =>
307
- mergeHeaders(impliedHeaders.value, commonHeaders, headers),
308
- )
309
- const shownImpliedHeaders = computed(() =>
310
- Object.entries(impliedHeaders.value).filter(
311
- ([name]) =>
312
- ![...commonHeaders, ...headers].some(
313
- (entry) => entry.name.toLowerCase() === name,
314
- ),
315
- ),
316
- )
317
- const auth = computed(() =>
318
- authModeOf(effectiveHeaders.value, useSession.value && loggedIn.value),
319
- )
320
- /** Who the call goes as; an Authorization of the headers for all routes says so. */
321
- const authLabel = computed(() =>
322
- auth.value === 'manual' &&
323
- !headers.some((entry) => entry.name.toLowerCase() === 'authorization')
324
- ? t('api.tester.auth.manual_common')
325
- : t(`api.tester.auth.${auth.value}`),
326
- )
327
- const request = computed<TesterRequest>(() => ({
328
- method: method.value,
329
- headers: effectiveHeaders.value,
330
- useSession: useSession.value && loggedIn.value,
331
- ...(sentBody.value !== undefined ? { body: sentBody.value } : {}),
332
- }))
333
-
334
- const problem = computed(() =>
335
- route.value
336
- ? inputProblem(pathValues, path.value, {
337
- ...request.value,
338
- headers: markedHeaders(
339
- request.value.headers,
340
- SIZE_PROBE_ID,
341
- SIZE_PROBE_SOURCE,
342
- ),
343
- })
344
- : null,
345
- )
346
- /** Why Send is off, said next to it. */
347
- const blocker = computed<string | null>(() => {
348
- if (missingPathParams.value.length)
349
- return t('api.tester.blocked.path_missing', {
350
- names: missingPathParams.value.map((name) => `:${name}`).join(', '),
351
- })
352
- const value = problem.value
353
- if (!value) return null
354
- if (value.code === 'path_value')
355
- return t('api.tester.blocked.path_value', { name: `:${value.name}` })
356
- if (value.code === 'header')
357
- return t('api.tester.blocked.header', { name: value.name })
358
- return t('api.tester.blocked.too_large', {
359
- size: formatBytes(value.size, locale.value),
360
- limit: formatBytes(PROXY_BODY_LIMIT, locale.value),
361
- })
362
- })
363
-
364
- const jsonWarning = computed(() =>
365
- bodyAllowed.value && bodyMode.value === 'json'
366
- ? jsonProblem(body.value)
367
- : null,
368
- )
369
- const formattedBody = computed(() =>
370
- bodyMode.value === 'json' && body.value.trim() && !jsonWarning.value
371
- ? formatJson(body.value)
372
- : null,
373
- )
374
-
375
- /** Masked values ([REDACTED]) still in what would be sent. */
376
- const redactedCount = computed(() => {
377
- const text =
378
- bodyAllowed.value && ['json', 'text'].includes(bodyMode.value)
379
- ? body.value
380
- : ''
381
- const fields = bodyMode.value === 'form' ? form : []
382
- return (
383
- countRedacted(text) +
384
- [...headers, ...commonHeaders, ...query, ...fields].reduce(
385
- (count, entry) => count + countRedacted(entry.value),
386
- 0,
387
- ) +
388
- Object.values(pathValues).reduce(
389
- (count, value) => count + countRedacted(value),
390
- 0,
391
- )
392
- )
393
- })
394
- const redactedBodyFields = computed(() =>
395
- ['json', 'text'].includes(bodyMode.value) ? redactedFields(body.value) : [],
396
- )
397
-
398
- // --- Tabs ---
399
-
400
- const tabs = computed(() => [
401
- ...(bodyAllowed.value
402
- ? [{ label: t('api.tester.tabs.body'), value: 'body' }]
403
- : []),
404
- {
405
- label: t('api.tester.tabs.headers'),
406
- value: 'headers',
407
- badge:
408
- [...headers, ...commonHeaders].filter((entry) => entry.name).length ||
409
- undefined,
410
- },
411
- {
412
- label: t('api.tester.tabs.query'),
413
- value: 'query',
414
- badge: query.filter((entry) => entry.name).length || undefined,
415
- },
416
- ])
417
-
418
- const bodyModeItems = computed(() =>
419
- BODY_MODES.map((value) => ({
420
- label: t(`api.tester.body_modes.${value}`),
421
- value,
422
- })),
423
- )
424
-
425
- /** Credentials typed among the headers for all routes: every route gets them. */
426
- const commonSecrets = computed(() =>
427
- commonHeaders
428
- .filter((entry) => entry.value && isSecretHeader(entry.name))
429
- .map((entry) => entry.name),
430
- )
431
-
432
- /** The key / value lists the open tab edits. */
433
- const editors = computed(() => {
434
- if (tab.value === 'headers')
435
- return [
436
- { key: 'headers', list: headers, add: t('api.tester.add_header') },
437
- {
438
- key: 'common',
439
- list: commonHeaders,
440
- add: t('api.tester.add_header'),
441
- title: t('api.tester.common_headers'),
442
- hint: t('api.tester.common_headers_hint'),
443
- warning: commonSecrets.value.length
444
- ? t('api.tester.common_secret', {
445
- names: commonSecrets.value.join(', '),
446
- })
447
- : undefined,
448
- },
449
- ]
450
- if (tab.value === 'query')
451
- return [{ key: 'query', list: query, add: t('api.tester.add_query') }]
452
- return [{ key: 'form', list: form, add: t('api.tester.add_field') }]
453
- })
454
-
455
- /** False for a route the module leaves out of its logs (the console's own). */
456
- const routeCaptured = computed(() => route.value?.captured !== false)
457
- const capturedAvailable = computed(
458
- () =>
459
- routeCaptured.value &&
460
- !!result.value?.requestId &&
461
- !neverSent(result.value.error),
462
- )
463
- const responseTabs = computed(() => [
464
- ...(result.value?.error
465
- ? []
466
- : [
467
- { label: t('api.tester.response'), value: 'body' },
468
- {
469
- label: t('api.tester.tabs.headers'),
470
- value: 'headers',
471
- badge: Object.keys(result.value?.headers ?? {}).length || undefined,
472
- },
473
- ]),
474
- ...(capturedAvailable.value
475
- ? [{ label: t('api.tester.tabs.captured'), value: 'captured' }]
476
- : []),
477
- ])
478
-
479
- // --- What the line under the body says ---
480
-
481
- const bodyHint = computed<{ text: string; tone: 'dimmed' | 'warning' }>(() => {
482
- const contract = route.value?.contract
483
- if (bodyMode.value === 'none')
484
- return { text: t('api.tester.body_hint.none'), tone: 'dimmed' }
485
- if (origin.value === 'replay' && replayInfo.value) {
486
- const info = replayInfo.value
487
- if (info.bodyMissing)
488
- return {
489
- text: info.bodyOmitted
490
- ? t('api.tester.body_hint.replay_missing', {
491
- reason: t(`api.tester.body_omitted.${info.bodyOmitted}`),
492
- })
493
- : t('api.tester.body_hint.replay_missing_unknown'),
494
- tone: 'warning',
495
- }
496
- if (info.bodyTruncated)
497
- return {
498
- text:
499
- problem.value?.code === 'body_too_large'
500
- ? t('api.tester.body_hint.replay_truncated_too_large', {
501
- limit: formatBytes(PROXY_BODY_LIMIT, locale.value),
502
- })
503
- : t('api.tester.body_hint.replay_truncated'),
504
- tone: 'warning',
505
- }
506
- return {
507
- text: t('api.tester.body_hint.replay', { id: shortId(info.id) }),
508
- tone: 'dimmed',
509
- }
510
- }
511
- if (sentBody.value === undefined)
512
- return { text: t('api.tester.body_hint.empty'), tone: 'dimmed' }
513
- if (bodyMode.value === 'form')
514
- return { text: t('api.tester.body_hint.form'), tone: 'dimmed' }
515
- if (origin.value === 'history')
516
- return { text: t('api.tester.body_hint.history'), tone: 'dimmed' }
517
- if (origin.value === 'edited' || !contract)
518
- return { text: '', tone: 'dimmed' }
519
- if (contract.exampleBody !== null && contract.exampleBody !== undefined)
520
- return { text: t('api.tester.body_hint.example'), tone: 'dimmed' }
521
- const span = { days: contract.windowDays, count: contract.total }
522
- if (contract.total === 0)
523
- return { text: t('api.tester.body_hint.no_capture', span), tone: 'dimmed' }
524
- return {
525
- text: contract.sampled
526
- ? t(
527
- 'api.tester.body_hint.no_json',
528
- { ...span, count: contract.sampled },
529
- contract.sampled,
530
- )
531
- : t('api.tester.body_hint.no_success', span, contract.total),
532
- tone: 'dimmed',
533
- }
534
- })
535
-
536
- const queryHint = computed(() => {
537
- const contract = route.value?.contract
538
- if (!contract) return ''
539
- if (contract.queryParams.length)
540
- return t('api.tester.query_known', {
541
- names: contract.queryParams.join(', '),
542
- })
543
- const span = { days: contract.windowDays }
544
- return contract.total
545
- ? t('api.tester.query_none', span)
546
- : t('api.tester.query_no_capture', span)
547
- })
548
-
549
- function shortId(id: string): string {
550
- return id.slice(0, 8)
551
- }
552
-
553
- // --- Draft ---
554
-
555
- function fill(list: Row[], values: KeyValue[]) {
556
- list.splice(
557
- 0,
558
- list.length,
559
- ...values.map((entry) => row(entry.name, entry.value)),
560
- )
561
- }
562
-
563
- function applyRequest(next: DraftRequest) {
564
- bodyMode.value = bodyAllowed.value ? next.bodyMode : 'none'
565
- body.value = next.body
566
- fill(form, next.form)
567
- fill(headers, next.headers)
568
- fill(query, next.query)
569
- for (const key of Object.keys(pathValues)) delete pathValues[key]
570
- for (const name of route.value?.pathParams ?? [])
571
- pathValues[name] = next.pathValues[name] ?? ''
572
- useSession.value = next.useSession
573
- }
574
-
575
- function openFirstTab() {
576
- tab.value = bodyMode.value !== 'none' ? 'body' : 'headers'
577
- }
578
-
579
- /**
580
- * Says which credentials a restored answer was sent with that the fields no
581
- * longer hold: never stored, or forgotten on reload.
582
- */
583
- function warnLostSecrets(sent: string[]) {
584
- const lost = lostSecrets(sent, [...headers, ...commonHeaders])
585
- if (lost.length)
586
- toast.add({
587
- title: t('api.tester.secrets_not_kept', { names: lost.join(', ') }),
588
- color: 'warning',
589
- icon: 'i-ph-key',
590
- })
591
- }
592
-
593
- function resetToExample(clearResult = false) {
594
- if (!example.value) return
595
- applyRequest(example.value)
596
- origin.value = 'example'
597
- replayInfo.value = null
598
- if (clearResult) showResult(null)
599
- openFirstTab()
600
- }
601
-
602
- function currentDraft(): TesterDraft | null {
603
- if (!modified.value && !result.value && !replayInfo.value) return null
604
- return {
605
- request: draftRequest.value,
606
- origin: origin.value,
607
- replay: replayInfo.value,
608
- result: result.value,
609
- }
610
- }
611
-
612
- let saveTimer: ReturnType<typeof setTimeout> | undefined
613
- let saveRef: string | null = null
614
-
615
- function flushDraft() {
616
- if (saveTimer === undefined || !saveRef) return
617
- clearTimeout(saveTimer)
618
- saveTimer = undefined
619
- saveDraft(saveRef, currentDraft())
620
- }
621
-
622
- watch([draftRequest, origin, replayInfo, result], () => {
623
- if (!activeRef) return
624
- if (saveTimer !== undefined) clearTimeout(saveTimer)
625
- saveRef = activeRef
626
- saveTimer = setTimeout(() => {
627
- saveTimer = undefined
628
- if (activeRef && saveRef === activeRef) saveDraft(activeRef, currentDraft())
629
- }, DRAFT_SAVE_DELAY_MS)
630
- })
631
-
632
- watch(commonHeaders, () => saveCommonHeaders(rows(commonHeaders)), {
633
- deep: true,
634
- })
635
-
636
- function loadRoute(next: string) {
637
- flushDraft()
638
- if (inFlight && inFlight.ref !== next) {
639
- inFlight.controller.abort(ROUTE_CHANGED)
640
- inFlight = null
641
- sending.value = false
642
- }
643
- activeRef = next
644
- filledRef.value = next
645
- history.value = loadHistory(next)
646
- const draft = loadDraft(next)
647
- if (draft) {
648
- applyRequest(draft.request)
649
- origin.value = draft.origin
650
- replayInfo.value = draft.replay
651
- showResult(draft.result)
652
- openFirstTab()
653
- warnLostSecrets(draft.result?.secrets ?? [])
654
- } else resetToExample(true)
655
- const replayId = currentRoute.query.replay
656
- if (typeof replayId === 'string' && replayId) void replay(replayId, next)
657
- }
658
-
659
- onMounted(() =>
660
- watch(
661
- () => route.value?.ref,
662
- (next) => {
663
- if (next) loadRoute(next)
664
- },
665
- { immediate: true },
666
- ),
667
- )
668
-
669
- // --- Replay ---
670
-
671
- /** Takes `?replay=` off the URL: a replay is loaded once, on its own route. */
672
- function dropReplayParam() {
673
- const { replay: _replay, ...rest } = currentRoute.query
674
- return router.replace({ query: rest })
675
- }
676
-
677
- const replayedId = shallowRef<string | null>(null)
678
- const replayRead = useApiData<CapturedRequest>(
679
- () =>
680
- replayedId.value
681
- ? `${LOGS_API}/${encodeURIComponent(replayedId.value)}`
682
- : null,
683
- ON_DEMAND,
684
- )
685
-
686
- async function replay(id: string, ref: string) {
687
- void dropReplayParam()
688
- try {
689
- replayedId.value = id
690
- await replayRead.execute()
691
- if (replayRead.error.value) throw replayRead.error.value
692
- const log = replayRead.data.value
693
- if (activeRef !== ref || !log) return
694
- const capturedRef = log.route
695
- if (capturedRef !== ref) {
696
- toast.add({
697
- title: t('api.tester.replay_other_route', { route: capturedRef }),
698
- color: 'warning',
699
- icon: 'i-ph-warning',
700
- })
701
- return
702
- }
703
- const replayed = replayFrom(log)
704
- applyRequest({
705
- bodyMode: replayed.bodyMode,
706
- body: replayed.body,
707
- form: [],
708
- headers: replayed.headers,
709
- query: replayed.query,
710
- pathValues: replayed.pathValues,
711
- useSession: example.value?.useSession ?? true,
712
- })
713
- origin.value = 'replay'
714
- replayInfo.value = {
715
- id: log._id,
716
- at: log.timestamp,
717
- skippedHeaders: replayed.skippedHeaders,
718
- bodyMissing: replayed.bodyMissing,
719
- bodyOmitted: replayed.bodyOmitted,
720
- bodyTruncated: replayed.bodyTruncated,
721
- }
722
- showResult(null)
723
- openFirstTab()
724
- toast.add({
725
- title: t('api.tester.replayed'),
726
- color: 'info',
727
- icon: 'i-ph-arrow-counter-clockwise',
728
- })
729
- } catch (cause) {
730
- // A request pruned, outside the route scope or matching no route: the
731
- // logs do not open it.
732
- const missing = errorStatus(cause) === 404
733
- toast.add({
734
- title: t(
735
- missing ? 'api.tester.replay_not_found' : 'api.tester.replay_failed',
736
- ),
737
- color: missing ? 'warning' : 'error',
738
- icon: 'i-ph-warning',
739
- })
740
- }
741
- }
742
-
743
- const replayTitle = computed(() => {
744
- const info = replayInfo.value
745
- if (!info) return ''
746
- return [
747
- t('api.tester.replay_banner.title', {
748
- id: shortId(info.id),
749
- at: formatClock(info.at, dateFormat.value),
750
- }),
751
- ...(info.skippedHeaders.length
752
- ? [
753
- t(
754
- 'api.tester.replay_banner.headers',
755
- { count: info.skippedHeaders.length },
756
- info.skippedHeaders.length,
757
- ),
758
- ]
759
- : []),
760
- ...(redactedCount.value
761
- ? [
762
- t(
763
- 'api.tester.replay_banner.redacted',
764
- { count: redactedCount.value },
765
- redactedCount.value,
766
- ),
767
- ]
768
- : []),
769
- ...(info.bodyTruncated ? [t('api.tester.replay_banner.truncated')] : []),
770
- ].join(' · ')
771
- })
772
- const replayDescription = computed(() => {
773
- const info = replayInfo.value
774
- if (!info) return ''
775
- return info.skippedHeaders.length
776
- ? t('api.tester.replay_banner.skipped', {
777
- names: info.skippedHeaders.join(', '),
778
- })
779
- : t('api.tester.replay_banner.credentials')
780
- })
781
-
782
- // --- Sending ---
783
-
784
- async function confirmSend(ref: string): Promise<boolean> {
785
- const firstWrite = writes.value && !isDelete.value && !hasConfirmedWrite(ref)
786
- const reasons: string[] = []
787
- if (isDelete.value)
788
- reasons.push(t('api.tester.confirm.delete', { path: path.value }))
789
- else if (firstWrite)
790
- reasons.push(
791
- t('api.tester.confirm.write', { method: method.value, path: path.value }),
792
- )
793
- if (redactedCount.value)
794
- reasons.push(
795
- t(
796
- 'api.tester.confirm.redacted',
797
- { count: redactedCount.value },
798
- redactedCount.value,
799
- ),
800
- )
801
- // A body cut at capture, sent untouched: the API gets part of it.
802
- const truncated =
803
- origin.value === 'replay' &&
804
- !!replayInfo.value?.bodyTruncated &&
805
- sentBody.value !== undefined
806
- if (truncated) reasons.push(t('api.tester.confirm.truncated'))
807
- if (reasons.length === 0) return true
808
- confirming = true
809
- try {
810
- const confirmed = await confirm({
811
- title: isDelete.value
812
- ? t('api.tester.confirm.delete_title')
813
- : firstWrite
814
- ? t('api.tester.confirm.write_title')
815
- : redactedCount.value
816
- ? t('api.tester.confirm.redacted_title')
817
- : t('api.tester.confirm.truncated_title'),
818
- description: reasons.join(' '),
819
- color: isDelete.value ? 'error' : 'warning',
820
- confirmLabel: t('api.tester.send'),
821
- confirmIcon: 'i-ph-paper-plane-tilt',
822
- initialFocus: 'cancel',
823
- })
824
- if (confirmed && firstWrite) rememberConfirmedWrite(ref)
825
- return confirmed
826
- } finally {
827
- confirming = false
828
- }
829
- }
830
-
831
- async function send() {
832
- const value = route.value
833
- if (sending.value || confirming || !value || blocker.value) return
834
- const ref = value.ref
835
- if (!(await confirmSend(ref))) return
836
- if (activeRef !== ref || sending.value) return
837
- // The signed mark that keeps the call out of the statistics: without it,
838
- // the call would count as the API's own traffic, so it is not sent.
839
- let source: string
840
- try {
841
- source = (await sourceTokens.get()).value
842
- } catch {
843
- toast.add({
844
- title: t('api.tester.source_failed'),
845
- color: 'error',
846
- icon: 'i-ph-warning',
847
- })
848
- return
849
- }
850
- if (activeRef !== ref || sending.value) return
851
- const requestId = newRequestId()
852
- const sentPath = path.value
853
- const snapshot = draftRequest.value
854
- const sentAuth = auth.value
855
- const outgoing: TesterRequest = {
856
- ...request.value,
857
- headers: markedHeaders(request.value.headers, requestId, source),
858
- }
859
- const controller = new AbortController()
860
- inFlight = { controller, ref }
861
- sending.value = true
862
- const at = Date.now()
863
- const started = performance.now()
864
- const sentSecrets = secretNames(outgoing.headers)
865
- const common = {
866
- auth: sentAuth,
867
- ...(sentSecrets.length ? { secrets: sentSecrets } : {}),
868
- requestId,
869
- at,
870
- }
871
- let outcome: TesterResult
872
- try {
873
- const answer = await sendTesterRequest(
874
- sentPath,
875
- window.location.origin,
876
- outgoing,
877
- controller.signal,
878
- )
879
- outcome = {
880
- ...answer,
881
- bodySize: byteLength(answer.body),
882
- durationMs: Math.round(performance.now() - started),
883
- ...common,
884
- }
885
- } catch (cause) {
886
- outcome = {
887
- status: 0,
888
- durationMs: Math.round(performance.now() - started),
889
- headers: {},
890
- body: '',
891
- error: cause instanceof TesterError ? cause.code : 'unexpected',
892
- message: cause instanceof Error ? cause.message : String(cause),
893
- ...common,
894
- }
895
- }
896
- if (inFlight?.controller === controller) {
897
- inFlight = null
898
- sending.value = false
899
- }
900
- // An answer already in hand when the route changed is filed as it came.
901
- if (controller.signal.reason === ROUTE_CHANGED && outcome.error)
902
- outcome = { ...outcome, error: 'aborted', abandoned: true }
903
- commit(ref, value.method, sentPath, snapshot, outcome)
904
- }
905
-
906
- function cancel() {
907
- inFlight?.controller.abort()
908
- }
909
-
910
- /**
911
- * Files a finished call under the route that sent it: its history, and the
912
- * screen if it still shows that route, else its draft. A call cancelled from
913
- * the screen stays off the history; one abandoned by a route change is kept,
914
- * as the API may have received it.
915
- */
916
- function commit(
917
- ref: string,
918
- sentMethod: string,
919
- sentPath: string,
920
- snapshot: DraftRequest,
921
- outcome: TesterResult,
922
- ) {
923
- const shown = !unmounted && activeRef === ref
924
- if (outcome.error !== 'aborted' || outcome.abandoned) {
925
- const entry = historyEntry(sentMethod, sentPath, snapshot, outcome)
926
- const list = [entry, ...(shown ? history.value : loadHistory(ref))].slice(
927
- 0,
928
- HISTORY_MAX,
929
- )
930
- if (shown) history.value = list
931
- saveHistory(ref, list)
932
- }
933
- if (!shown) {
934
- const draft = loadDraft(ref)
935
- saveDraft(ref, {
936
- ...(draft ?? { request: snapshot, origin: 'example', replay: null }),
937
- result: outcome,
938
- })
939
- return
940
- }
941
- showResult(outcome, true)
942
- }
943
-
944
- // --- What the module captured of the call ---
945
-
946
- const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
947
-
948
- async function findCaptured(
949
- read: ReadJson,
950
- target: TesterResult,
951
- ): Promise<CapturedRequest | null> {
952
- const id = target.requestId as string
953
- const page = await read<{ results: CapturedRow[] }>(
954
- `${LOGS_API}?${new URLSearchParams({ requestId: id })}`,
955
- )
956
- // Only the call sent: a list that ignored the filter is no answer.
957
- const matches = page.results.filter((item) =>
958
- item.requestId === undefined
959
- ? page.results.length === 1
960
- : item.requestId === id,
961
- )
962
- const found = matches[0]
963
- if (
964
- !found ||
965
- Date.parse(found.timestamp) < target.at - CAPTURE_MATCH_MS ||
966
- (found.route && activeRef && found.route !== activeRef)
967
- )
968
- return null
969
- return read<CapturedRequest>(`${LOGS_API}/${encodeURIComponent(found._id)}`)
970
- }
971
-
972
- const capturedTarget = shallowRef<TesterResult | null>(null)
973
- const captured = useApiData<CapturedRequest | null>(
974
- () =>
975
- capturedTarget.value?.requestId
976
- ? `dms-api:tester-captured:${capturedTarget.value.requestId}`
977
- : null,
978
- ({ $authFetch, signal }) =>
979
- findCaptured(
980
- (url) => $authFetch(url, { signal }),
981
- capturedTarget.value as TesterResult,
982
- ),
983
- ON_DEMAND,
984
- )
985
-
986
- async function lookUpCaptured(target: TesterResult, retry: boolean) {
987
- const id = target.requestId
988
- if (!id) return
989
- capturedState.value = 'loading'
990
- const current = () =>
991
- result.value?.requestId === id && capturedTarget.value?.requestId === id
992
- for (const delay of retry ? CAPTURE_DELAYS_MS : [0]) {
993
- if (delay) await wait(delay)
994
- if (result.value?.requestId !== id) return
995
- capturedTarget.value = target
996
- await captured.execute()
997
- if (!current()) return
998
- if (captured.error.value) {
999
- capturedState.value = 'error'
1000
- return
1001
- }
1002
- const log = captured.data.value
1003
- if (log) {
1004
- capturedLog.value = log
1005
- capturedState.value = 'found'
1006
- keepCaptured(id, log)
1007
- return
1008
- }
1009
- }
1010
- capturedState.value = 'missing'
1011
- }
1012
-
1013
- /**
1014
- * Keeps what the module captured of a call with its answer, on screen, in
1015
- * the draft and in the history: its server time and its record survive a
1016
- * return to the route. A 502 of the proxy for a call the module captured is
1017
- * the API answering more than the proxy returns.
1018
- */
1019
- function keepCaptured(id: string, log: CapturedRequest) {
1020
- const value = result.value
1021
- if (value?.requestId !== id) return
1022
- if (value.captured && value.error !== 'proxy_failed') return
1023
- const patch: Partial<TesterResult> = {
1024
- captured: capturedSummary(log),
1025
- ...(value.error === 'proxy_failed'
1026
- ? { error: 'response_too_large' as const }
1027
- : {}),
1028
- }
1029
- result.value = { ...value, ...patch }
1030
- if (!activeRef) return
1031
- history.value = patchResult(history.value, id, patch)
1032
- saveHistory(activeRef, history.value)
1033
- }
1034
-
1035
- /**
1036
- * Shows an answer, on its Captured tab when it failed. What the module
1037
- * captured is looked up for a call just made, for an answer restored before
1038
- * it was found (its server time and record), and when that tab is open.
1039
- */
1040
- function showResult(value: TesterResult | null, fresh = false) {
1041
- result.value = value
1042
- capturedState.value = 'idle'
1043
- capturedLog.value = null
1044
- responseTab.value =
1045
- value?.error && capturedAvailable.value ? 'captured' : 'body'
1046
- if (
1047
- value &&
1048
- capturedAvailable.value &&
1049
- (fresh || responseTab.value === 'captured' || !value.captured)
1050
- )
1051
- void lookUpCaptured(value, fresh)
1052
- }
1053
-
1054
- watch(responseTab, (value) => {
1055
- if (value === 'captured' && capturedState.value === 'idle' && result.value)
1056
- void lookUpCaptured(result.value, false)
1057
- })
1058
-
1059
- const capturedSlow = computed(() => !!result.value?.captured?.slow)
1060
-
1061
- // --- History ---
1062
-
1063
- function restore(entry: HistoryEntry) {
1064
- applyRequest(entry.request)
1065
- origin.value = 'history'
1066
- replayInfo.value = null
1067
- showResult(entry.result)
1068
- warnLostSecrets([
1069
- ...(entry.secretsRemoved ?? []),
1070
- ...(entry.result.secrets ?? []),
1071
- ])
1072
- }
1073
-
1074
- function clearHistory() {
1075
- const ref = activeRef
1076
- if (!ref) return
1077
- const cleared = history.value
1078
- history.value = []
1079
- saveHistory(ref, [])
1080
- toast.add({
1081
- title: t(
1082
- 'api.tester.history_cleared',
1083
- { count: cleared.length },
1084
- cleared.length,
1085
- ),
1086
- color: 'neutral',
1087
- icon: 'i-ph-trash',
1088
- actions: [
1089
- {
1090
- label: t('api.tester.undo'),
1091
- color: 'neutral',
1092
- variant: 'outline',
1093
- onClick: () => {
1094
- const merged = [...loadHistory(ref), ...cleared].slice(0, HISTORY_MAX)
1095
- saveHistory(ref, merged)
1096
- if (activeRef === ref) history.value = merged
1097
- },
1098
- },
1099
- ],
1100
- })
1101
- }
1102
-
1103
- // --- Copy cURL ---
1104
-
1105
- function curl(): string {
1106
- const search: Record<string, string | string[]> = {}
1107
- for (const { name, value } of query) {
1108
- if (!name) continue
1109
- const known = search[name]
1110
- search[name] = known === undefined ? value : [...[known].flat(), value]
1111
- }
1112
- return toCurl({
1113
- method: method.value,
1114
- path: route.value?.path ?? '/',
1115
- origin: apiOrigin.value,
1116
- pathParams: { ...pathValues },
1117
- query: search,
1118
- headers: effectiveHeaders.value,
1119
- body: sentBody.value,
1120
- session: auth.value === 'session',
1121
- })
1122
- }
1123
-
1124
- async function copyCurl() {
1125
- try {
1126
- await navigator.clipboard.writeText(curl())
1127
- toast.add({
1128
- title: t('api.request.curl_copied'),
1129
- color: 'success',
1130
- icon: 'i-ph-check',
1131
- })
1132
- } catch {
1133
- toast.add({
1134
- title: t('api.request.copy_failed'),
1135
- color: 'error',
1136
- icon: 'i-ph-warning',
1137
- })
1138
- }
1139
- }
1140
-
1141
- /** What the user typed in the body editor (not a body loaded into it). */
1142
- function editBody(value: string | null | undefined) {
1143
- const next = value ?? ''
1144
- if (next === body.value) return
1145
- body.value = next
1146
- origin.value = 'edited'
1147
- }
1148
-
1149
- function formatBody() {
1150
- if (formattedBody.value === null) return
1151
- body.value = formattedBody.value
1152
- origin.value = 'edited'
1153
- }
1154
-
1155
- // --- Keyboard ---
1156
-
1157
- /**
1158
- * Ctrl/Cmd+Enter sends from a field of the tester only, never from the rest
1159
- * of the page (the route filter, the command palette); `send` still asks
1160
- * before a write it has not confirmed.
1161
- */
1162
- function onKey(event: KeyboardEvent) {
1163
- if (event.key !== 'Enter' || !(event.metaKey || event.ctrlKey)) return
1164
- if (event.isComposing) return
1165
- event.preventDefault()
1166
- void send()
1167
- }
1168
-
1169
- // --- Live hold ---
1170
-
1171
- const FIELD_SELECTOR = 'input, textarea, select, [contenteditable="true"]'
1172
- const live = usePageLive()
1173
-
1174
- function onFocusIn(event: FocusEvent) {
1175
- const target = event.target as HTMLElement | null
1176
- if (target?.closest(FIELD_SELECTOR))
1177
- live.hold('$api.live_mode.typing_in_tester')
1178
- }
1179
-
1180
- // Held while the focus stays in the Tester (a field, Send), released once it
1181
- // leaves; the DMS releases it with the component too.
1182
- function onFocusOut(event: FocusEvent) {
1183
- const root = event.currentTarget as HTMLElement
1184
- const next = event.relatedTarget as Node | null
1185
- if (next && root.contains(next)) return
1186
- live.release()
1187
- }
1188
-
1189
- onBeforeUnmount(() => {
1190
- flushDraft()
1191
- // A call in flight still lands in its route's history and draft.
1192
- unmounted = true
1193
- })
1194
-
1195
- // --- Answer ---
1196
-
1197
- const responseBody = computed(() => prettyBody(result.value?.body))
1198
- const responseSize = computed(() =>
1199
- result.value ? (result.value.bodySize ?? byteLength(result.value.body)) : 0,
1200
- )
1201
- function recordLink(id: string): string {
1202
- return `${LOGS_PAGE}?${new URLSearchParams({ record: id })}`
1203
- }
1204
-
1205
- /** A path as it reads: decoded, its bidirectional controls shown. */
1206
- function readable(value: string): string {
1207
- try {
1208
- return revealBidi(decodeURI(value))
1209
- } catch {
1210
- return revealBidi(value)
1211
- }
1212
- }
1213
-
1214
- /**
1215
- * The captured call, else the route's logs: only for a route the module
1216
- * captures and the active scope shows (the logs list is scoped).
1217
- */
1218
- const logsLink = computed(() => {
1219
- const id = result.value?.captured?.id
1220
- if (id) return recordLink(id)
1221
- return route.value && routeCaptured.value && route.value.inScope !== false
1222
- ? `${LOGS_PAGE}?${new URLSearchParams({ route: route.value.ref })}`
1223
- : ''
1224
- })
1225
- const errorCopy = computed(() => {
1226
- const value = result.value
1227
- if (!value?.error) return null
1228
- const code = value.abandoned ? 'abandoned' : value.error
1229
- const params = {
1230
- limit: formatBytes(PROXY_RESPONSE_LIMIT, locale.value),
1231
- seconds: PROXY_TIMEOUT_MS / 1000,
1232
- status: value.captured?.status ?? '',
1233
- message: value.message ?? '',
1234
- }
1235
- const description =
1236
- !routeCaptured.value && POINTS_TO_CAPTURED.has(code)
1237
- ? 'description_uncaptured'
1238
- : 'description'
1239
- return {
1240
- title: t(`api.tester.errors.${code}.title`, params),
1241
- description: t(`api.tester.errors.${code}.${description}`, params),
1242
- icon: ERROR_ICONS[value.error] ?? 'i-ph-plugs',
1243
- }
1244
- })
1245
- const liveMessage = computed(() => {
1246
- const value = result.value
1247
- if (sending.value || !value) return ''
1248
- if (errorCopy.value)
1249
- return t('api.tester.live.failed', { title: errorCopy.value.title })
1250
- return t('api.tester.live.sent', {
1251
- status: value.status,
1252
- text: statusText(value.status),
1253
- duration: formatMs(value.durationMs, locale.value),
1254
- })
1255
- })
1256
- const shortcut = computed(() =>
1257
- typeof navigator !== 'undefined' && /Mac|iP/.test(navigator.platform)
1258
- ? '⌘'
1259
- : 'Ctrl',
1260
- )
73
+ send,
74
+ sending,
75
+ shortcut,
76
+ t,
77
+ useSession,
78
+ writes,
79
+ } = tester
1261
80
  </script>
1262
81
 
1263
82
  <template>
@@ -1412,452 +231,9 @@ const shortcut = computed(() =>
1412
231
  </DmsCard>
1413
232
 
1414
233
  <div class="grid gap-4 xl:grid-cols-2 xl:items-start">
1415
- <DmsCard :padded="false" class="@container min-w-0">
1416
- <div
1417
- class="border-default flex flex-wrap items-center gap-x-2 border-b px-3"
1418
- >
1419
- <!-- overflow-x-auto alone turns overflow-y to auto: the active
1420
- tab's underline would show a scrollbar. -->
1421
- <UTabs
1422
- v-model="tab"
1423
- :items="tabs"
1424
- :content="false"
1425
- variant="link"
1426
- size="sm"
1427
- class="min-w-0 grow overflow-x-auto overflow-y-hidden"
1428
- />
1429
- <template v-if="modified">
1430
- <span class="text-dimmed inline-flex items-center gap-1.5 text-xs">
1431
- <span
1432
- class="bg-warning size-1.5 rounded-full"
1433
- aria-hidden="true"
1434
- />
1435
- {{ t('api.tester.draft_modified') }}
1436
- </span>
1437
- <UButton
1438
- size="xs"
1439
- color="neutral"
1440
- variant="ghost"
1441
- icon="i-ph-arrow-counter-clockwise"
1442
- :label="t('api.tester.reset')"
1443
- @click="resetToExample()"
1444
- />
1445
- </template>
1446
- </div>
1447
- <div class="p-3">
1448
- <div
1449
- v-if="tab === 'body' && bodyAllowed"
1450
- class="mb-2 flex flex-wrap items-center gap-2"
1451
- >
1452
- <USelect
1453
- v-model="bodyMode"
1454
- :items="bodyModeItems"
1455
- size="xs"
1456
- class="w-36"
1457
- :aria-label="t('api.tester.body_mode')"
1458
- />
1459
- <span class="grow" />
1460
- <UButton
1461
- v-if="bodyMode === 'json'"
1462
- size="xs"
1463
- color="neutral"
1464
- variant="outline"
1465
- icon="i-ph-brackets-curly"
1466
- :disabled="formattedBody === null || formattedBody === body"
1467
- :label="t('api.tester.format')"
1468
- @click="formatBody"
1469
- />
1470
- </div>
234
+ <RouteTesterRequest :tester="tester" />
1471
235
 
1472
- <template
1473
- v-if="
1474
- tab === 'body' &&
1475
- bodyAllowed &&
1476
- (bodyMode === 'json' || bodyMode === 'text')
1477
- "
1478
- >
1479
- <DmsInputCode
1480
- :key="bodyMode"
1481
- :model-value="body"
1482
- :language="bodyMode === 'json' ? 'json' : 'text'"
1483
- :min-lines="12"
1484
- :max-lines="24"
1485
- :aria-describedby="bodyHintId"
1486
- @update:model-value="editBody"
1487
- />
1488
- </template>
1489
-
1490
- <div
1491
- v-else-if="tab !== 'body' || (bodyAllowed && bodyMode === 'form')"
1492
- class="flex flex-col gap-4"
1493
- >
1494
- <div
1495
- v-if="tab === 'headers' && shownImpliedHeaders.length"
1496
- class="text-dimmed flex flex-col gap-1 font-mono text-xs"
1497
- >
1498
- <span v-for="[name, value] in shownImpliedHeaders" :key="name">
1499
- {{ name }}: {{ value }}
1500
- <span class="font-sans">
1501
- · {{ t('api.tester.implied_header') }}
1502
- </span>
1503
- </span>
1504
- </div>
1505
- <div
1506
- v-for="editor in editors"
1507
- :key="editor.key"
1508
- class="@sm:gap-2 flex flex-col gap-3"
1509
- >
1510
- <p
1511
- v-if="editor.title"
1512
- class="text-default border-default border-t pt-3 text-xs font-medium"
1513
- >
1514
- {{ editor.title }}
1515
- </p>
1516
- <!-- In a narrow card the name takes a line of its own, the
1517
- value and its button the next: a name is never cut. -->
1518
- <div
1519
- v-for="(entry, index) in editor.list"
1520
- :key="entry.id"
1521
- class="@sm:flex-nowrap flex flex-wrap gap-2"
1522
- >
1523
- <UInput
1524
- v-model="entry.name"
1525
- size="sm"
1526
- class="@sm:w-2/5 w-full font-mono"
1527
- :placeholder="t('dms.form.key_value.key')"
1528
- :aria-label="t('dms.form.key_value.key')"
1529
- />
1530
- <UInput
1531
- v-model="entry.value"
1532
- size="sm"
1533
- class="min-w-0 flex-1 font-mono"
1534
- :placeholder="t('dms.form.key_value.value')"
1535
- :aria-label="t('dms.form.key_value.value')"
1536
- :color="hasRedacted(entry.value) ? 'warning' : undefined"
1537
- :highlight="hasRedacted(entry.value)"
1538
- :title="
1539
- hasRedacted(entry.value)
1540
- ? t('api.tester.redacted_value')
1541
- : undefined
1542
- "
1543
- />
1544
- <UButton
1545
- size="sm"
1546
- color="neutral"
1547
- variant="ghost"
1548
- icon="i-ph-x"
1549
- :aria-label="t('api.tester.remove')"
1550
- @click="editor.list.splice(index, 1)"
1551
- />
1552
- </div>
1553
- <div>
1554
- <UButton
1555
- size="xs"
1556
- color="neutral"
1557
- variant="outline"
1558
- icon="i-ph-plus"
1559
- :label="editor.add"
1560
- @click="editor.list.push(row())"
1561
- />
1562
- </div>
1563
- <p v-if="editor.hint" class="text-dimmed text-xs">
1564
- {{ editor.hint }}
1565
- </p>
1566
- <p
1567
- v-if="editor.warning"
1568
- class="text-warning inline-flex items-start gap-1 text-xs"
1569
- >
1570
- <UIcon name="i-ph-key" class="mt-px size-3.5 shrink-0" />
1571
- {{ editor.warning }}
1572
- </p>
1573
- </div>
1574
- <p v-if="tab !== 'body'" class="text-dimmed text-xs">
1575
- <template v-if="tab === 'headers'">
1576
- {{ t('api.tester.headers_hint') }}
1577
- {{ t('api.tester.marks_hint') }}
1578
- </template>
1579
- <template v-else-if="tab === 'query'">{{ queryHint }}</template>
1580
- </p>
1581
- </div>
1582
-
1583
- <template v-if="tab === 'body' && bodyAllowed">
1584
- <p v-if="jsonWarning" class="text-warning mt-1.5 text-xs">
1585
- {{ t('api.tester.json_warning', { message: jsonWarning }) }}
1586
- </p>
1587
- <p
1588
- v-if="redactedBodyFields.length"
1589
- class="text-warning mt-1.5 text-xs"
1590
- >
1591
- {{
1592
- t(
1593
- 'api.tester.body_redacted',
1594
- {
1595
- count: redactedBodyFields.length,
1596
- names: redactedBodyFields.join(', '),
1597
- },
1598
- redactedBodyFields.length,
1599
- )
1600
- }}
1601
- </p>
1602
- <p
1603
- v-if="bodyHint.text"
1604
- :id="bodyHintId"
1605
- class="mt-1.5 text-xs"
1606
- :class="
1607
- bodyHint.tone === 'warning' ? 'text-warning' : 'text-dimmed'
1608
- "
1609
- >
1610
- {{ bodyHint.text }}
1611
- </p>
1612
- </template>
1613
- </div>
1614
- </DmsCard>
1615
-
1616
- <DmsCard :padded="false" class="min-w-0">
1617
- <div v-if="!result" class="px-4 py-10">
1618
- <DmsEmptyState
1619
- size="sm"
1620
- :icon="sending ? 'i-ph-hourglass-medium' : 'i-ph-paper-plane-tilt'"
1621
- :title="
1622
- sending
1623
- ? t('api.tester.waiting_title')
1624
- : t('api.tester.no_response_title')
1625
- "
1626
- :description="
1627
- sending
1628
- ? t('api.tester.waiting_description', {
1629
- seconds: PROXY_TIMEOUT_MS / 1000,
1630
- })
1631
- : t('api.tester.no_response_description', { shortcut })
1632
- "
1633
- />
1634
- </div>
1635
- <template v-else>
1636
- <div
1637
- class="border-default flex flex-wrap items-center gap-x-3 gap-y-1 border-b px-4 py-2.5"
1638
- >
1639
- <ApiStatusBadge v-if="result.status" :status="result.status" text />
1640
- <DmsStatusPill
1641
- v-else
1642
- :tone="result.error === 'aborted' ? 'neutral' : 'error'"
1643
- dot="none"
1644
- :label="
1645
- result.error === 'aborted'
1646
- ? t('api.tester.cancelled')
1647
- : t('api.tester.failed')
1648
- "
1649
- />
1650
- <UTooltip :text="t('api.tester.duration_tooltip')">
1651
- <span class="text-muted font-mono text-[12px]" tabindex="0">
1652
- {{
1653
- t('api.tester.duration_browser', {
1654
- duration: formatMs(result.durationMs, locale),
1655
- })
1656
- }}
1657
- <template
1658
- v-if="
1659
- result.captured && result.captured.responseTimeMs !== null
1660
- "
1661
- >
1662
- ·
1663
- <span
1664
- :class="capturedSlow ? 'text-warning font-semibold' : ''"
1665
- >
1666
- {{
1667
- t('api.tester.duration_server', {
1668
- duration: formatMs(
1669
- result.captured.responseTimeMs,
1670
- locale,
1671
- ),
1672
- })
1673
- }}
1674
- </span>
1675
- </template>
1676
- </span>
1677
- </UTooltip>
1678
- <span
1679
- v-if="result.body || result.bodySize"
1680
- class="text-muted font-mono text-[12px]"
1681
- >
1682
- {{ formatBytes(responseSize, locale) }}
1683
- </span>
1684
- <span class="grow" />
1685
- <UButton
1686
- v-if="!neverSent(result.error) && logsLink"
1687
- :to="logsLink"
1688
- size="xs"
1689
- variant="link"
1690
- trailing-icon="i-ph-arrow-right"
1691
- :label="
1692
- result.captured
1693
- ? t('api.tester.open_captured')
1694
- : t('api.tester.open_logs')
1695
- "
1696
- />
1697
- <UTooltip
1698
- v-else-if="!routeCaptured"
1699
- :text="t('api.tester.not_captured_hint')"
1700
- >
1701
- <span class="text-dimmed text-xs" tabindex="0">
1702
- {{ t('api.tester.not_captured') }}
1703
- </span>
1704
- </UTooltip>
1705
- </div>
1706
- <div class="flex flex-col gap-2 p-3">
1707
- <DmsBanner
1708
- v-if="errorCopy"
1709
- :tone="result.error === 'aborted' ? 'info' : 'error'"
1710
- size="sm"
1711
- :icon="errorCopy.icon"
1712
- :title="errorCopy.title"
1713
- :description="errorCopy.description"
1714
- />
1715
- <DmsBanner
1716
- v-else-if="result.status === 401"
1717
- tone="warning"
1718
- size="sm"
1719
- icon="i-ph-lock-simple"
1720
- :title="t('api.tester.unauthorized_title')"
1721
- :description="t(`api.tester.unauthorized.${result.auth}`)"
1722
- >
1723
- <template v-if="result.auth === 'none'" #actions>
1724
- <UButton
1725
- size="xs"
1726
- color="neutral"
1727
- variant="outline"
1728
- :label="t('api.tester.turn_on_session')"
1729
- @click="useSession = true"
1730
- />
1731
- </template>
1732
- </DmsBanner>
1733
- <UTabs
1734
- v-if="responseTabs.length"
1735
- v-model="responseTab"
1736
- :items="responseTabs"
1737
- :content="false"
1738
- variant="link"
1739
- size="sm"
1740
- />
1741
- <template v-if="responseTab === 'captured' && capturedAvailable">
1742
- <p
1743
- v-if="capturedState === 'loading' || capturedState === 'idle'"
1744
- class="text-dimmed text-sm"
1745
- >
1746
- {{ t('api.tester.captured.loading') }}
1747
- </p>
1748
- <p
1749
- v-else-if="capturedState === 'missing'"
1750
- class="text-dimmed text-sm"
1751
- >
1752
- {{
1753
- t('api.tester.captured.missing', {
1754
- id: shortId(result.requestId ?? ''),
1755
- })
1756
- }}
1757
- </p>
1758
- <p
1759
- v-else-if="capturedState === 'error'"
1760
- class="text-error text-sm"
1761
- >
1762
- {{ t('api.tester.captured.error') }}
1763
- </p>
1764
- <div v-else-if="capturedLog" class="flex flex-col gap-3">
1765
- <div
1766
- class="text-muted flex flex-wrap items-center gap-3 font-mono text-[12px]"
1767
- >
1768
- <ApiStatusBadge
1769
- :status="capturedLog.statusCode"
1770
- text
1771
- size="sm"
1772
- />
1773
- <span
1774
- v-if="capturedLog.responseTimeMs !== null"
1775
- :class="capturedSlow ? 'text-warning font-semibold' : ''"
1776
- >
1777
- {{
1778
- t('api.tester.duration_server', {
1779
- duration: formatMs(capturedLog.responseTimeMs, locale),
1780
- })
1781
- }}
1782
- </span>
1783
- <span>
1784
- {{ formatClock(capturedLog.timestamp, dateFormat) }}
1785
- </span>
1786
- <span>{{ shortId(capturedLog._id) }}</span>
1787
- </div>
1788
- <DmsBanner
1789
- v-if="capturedLog.error"
1790
- tone="error"
1791
- size="sm"
1792
- icon="i-ph-bug"
1793
- :title="capturedLog.error.message"
1794
- />
1795
- <DmsCodeSnippet
1796
- v-if="capturedLog.error?.stack"
1797
- :code="capturedLog.error.stack"
1798
- :title="t('api.tester.captured.stack')"
1799
- max-height="12rem"
1800
- wrap="anywhere"
1801
- />
1802
- <div class="flex flex-col gap-1.5">
1803
- <p class="text-default text-xs font-medium">
1804
- {{ t('api.tester.captured.headers') }}
1805
- </p>
1806
- <ApiKeyValues
1807
- :values="capturedLog.requestHeaders"
1808
- :empty="t('api.request.no_headers')"
1809
- />
1810
- </div>
1811
- <DmsCodeSnippet
1812
- v-if="capturedLog.requestBody"
1813
- :code="prettyBody(capturedLog.requestBody).text"
1814
- :title="t('api.tester.captured.body')"
1815
- max-height="16rem"
1816
- wrap="anywhere"
1817
- />
1818
- <p
1819
- v-else-if="capturedLog.requestBodyOmitted"
1820
- class="text-dimmed text-xs"
1821
- >
1822
- {{
1823
- t('api.tester.captured.body_omitted', {
1824
- reason: t(
1825
- `api.tester.body_omitted.${capturedLog.requestBodyOmitted}`,
1826
- ),
1827
- })
1828
- }}
1829
- </p>
1830
- </div>
1831
- </template>
1832
- <template v-else-if="!result.error">
1833
- <template v-if="responseTab === 'body'">
1834
- <DmsCodeSnippet
1835
- v-if="responseBody.text"
1836
- :code="responseBody.text"
1837
- max-height="24rem"
1838
- wrap="anywhere"
1839
- />
1840
- <p v-else class="text-dimmed text-sm">
1841
- {{ t('api.request.no_body') }}
1842
- </p>
1843
- <p v-if="result.bodyTruncated" class="text-warning text-xs">
1844
- {{
1845
- t('api.tester.truncated_in_history', {
1846
- shown: formatBytes(byteLength(result.body), locale),
1847
- size: formatBytes(responseSize, locale),
1848
- })
1849
- }}
1850
- </p>
1851
- </template>
1852
- <ApiKeyValues
1853
- v-else
1854
- :values="result.headers"
1855
- :empty="t('api.request.no_headers')"
1856
- />
1857
- </template>
1858
- </div>
1859
- </template>
1860
- </DmsCard>
236
+ <RouteTesterResponse :tester="tester" />
1861
237
  </div>
1862
238
 
1863
239
  <DmsCard :title="t('api.tester.history')" :padded="false">