@owlmeans/api 0.1.18-rc.9 → 0.1.18

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 (101) hide show
  1. package/README.md +12 -4
  2. package/agent-meta/manifest.json +3 -3
  3. package/agent-meta/skills/api/SKILL.md +117 -11
  4. package/build/consts.d.ts +7 -0
  5. package/build/consts.d.ts.map +1 -1
  6. package/build/consts.js +7 -0
  7. package/build/consts.js.map +1 -1
  8. package/build/errors.d.ts +30 -2
  9. package/build/errors.d.ts.map +1 -1
  10. package/build/errors.js +46 -4
  11. package/build/errors.js.map +1 -1
  12. package/build/index.d.ts +3 -0
  13. package/build/index.d.ts.map +1 -1
  14. package/build/index.js +1 -0
  15. package/build/index.js.map +1 -1
  16. package/build/service.d.ts +1 -6
  17. package/build/service.d.ts.map +1 -1
  18. package/build/service.js +39 -27
  19. package/build/service.js.map +1 -1
  20. package/build/status/consts.d.ts +5 -0
  21. package/build/status/consts.d.ts.map +1 -0
  22. package/build/status/consts.js +5 -0
  23. package/build/status/consts.js.map +1 -0
  24. package/build/status/consts.local.d.ts +10 -0
  25. package/build/status/consts.local.d.ts.map +1 -0
  26. package/build/status/consts.local.js +10 -0
  27. package/build/status/consts.local.js.map +1 -0
  28. package/build/status/helper.d.ts +4 -0
  29. package/build/status/helper.d.ts.map +1 -0
  30. package/build/status/helper.js +49 -0
  31. package/build/status/helper.js.map +1 -0
  32. package/build/status/index.d.ts +9 -0
  33. package/build/status/index.d.ts.map +1 -0
  34. package/build/status/index.js +9 -0
  35. package/build/status/index.js.map +1 -0
  36. package/build/status/marker.d.ts +3 -0
  37. package/build/status/marker.d.ts.map +1 -0
  38. package/build/status/marker.js +16 -0
  39. package/build/status/marker.js.map +1 -0
  40. package/build/status/types.d.ts +35 -0
  41. package/build/status/types.d.ts.map +1 -0
  42. package/build/status/types.js +2 -0
  43. package/build/status/types.js.map +1 -0
  44. package/build/types.local.d.ts +6 -0
  45. package/build/types.local.d.ts.map +1 -0
  46. package/build/types.local.js +2 -0
  47. package/build/types.local.js.map +1 -0
  48. package/build/utils/body/types.d.ts +36 -0
  49. package/build/utils/body/types.d.ts.map +1 -0
  50. package/build/utils/body/types.js +2 -0
  51. package/build/utils/body/types.js.map +1 -0
  52. package/build/utils/body.d.ts +4 -0
  53. package/build/utils/body.d.ts.map +1 -0
  54. package/build/utils/body.js +56 -0
  55. package/build/utils/body.js.map +1 -0
  56. package/build/utils/consts.d.ts +2 -0
  57. package/build/utils/consts.d.ts.map +1 -0
  58. package/build/utils/consts.js +2 -0
  59. package/build/utils/consts.js.map +1 -0
  60. package/build/utils/consts.local.d.ts +2 -0
  61. package/build/utils/consts.local.d.ts.map +1 -0
  62. package/build/utils/consts.local.js +2 -0
  63. package/build/utils/consts.local.js.map +1 -0
  64. package/build/utils/handler.d.ts.map +1 -1
  65. package/build/utils/index.d.ts +2 -1
  66. package/build/utils/index.d.ts.map +1 -1
  67. package/build/utils/index.js +1 -1
  68. package/build/utils/index.js.map +1 -1
  69. package/build/utils/response/types.d.ts +15 -0
  70. package/build/utils/response/types.d.ts.map +1 -0
  71. package/build/utils/response/types.js +2 -0
  72. package/build/utils/response/types.js.map +1 -0
  73. package/build/utils/response.d.ts +4 -0
  74. package/build/utils/response.d.ts.map +1 -0
  75. package/build/utils/response.js +99 -0
  76. package/build/utils/response.js.map +1 -0
  77. package/package.json +24 -14
  78. package/src/consts.ts +8 -0
  79. package/src/errors.ts +55 -4
  80. package/src/index.ts +5 -1
  81. package/src/service.ts +48 -40
  82. package/src/status/consts.local.ts +11 -0
  83. package/src/status/consts.ts +5 -0
  84. package/src/status/helper.ts +63 -0
  85. package/src/status/index.ts +11 -0
  86. package/src/status/marker.ts +19 -0
  87. package/src/status/types.ts +36 -0
  88. package/src/types.local.ts +7 -0
  89. package/src/utils/body/types.ts +37 -0
  90. package/src/utils/body.ts +70 -0
  91. package/src/utils/consts.local.ts +1 -0
  92. package/src/utils/consts.ts +1 -0
  93. package/src/utils/index.ts +2 -1
  94. package/src/utils/response/types.ts +15 -0
  95. package/src/utils/response.ts +117 -0
  96. package/tests/body.spec.ts +124 -0
  97. package/tests/handler.spec.ts +229 -0
  98. package/tests/tsconfig.json +11 -0
  99. package/tsconfig.json +1 -1
  100. package/build/.gitkeep +0 -0
  101. package/src/utils/handler.ts +0 -61
package/src/errors.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ResilientError } from '@owlmeans/error'
2
+ import { parseClientMarker } from './status/marker.js'
2
3
 
3
4
  export class ApiError extends ResilientError {
4
5
  public static override typeName = 'ApiError'
@@ -8,34 +9,84 @@ export class ApiError extends ResilientError {
8
9
  }
9
10
  }
10
11
 
12
+ /**
13
+ * A request the peer answered with a failure.
14
+ *
15
+ * `status` is the HTTP status the marker in the message states (`api:client:crashed:<id>` is 500,
16
+ * `api:client:auth:<id>` 401, `api:client:forbidden[:<id>]` 403, `api:client:status:<n>[:<id>]`
17
+ * any other); `incidentId` is the server's correlation id when the marker carries one. Only
18
+ * `type` and `message` survive a marshal, so both are rebuilt from the message in
19
+ * `finalizeUnmarshal()`. No class of this family declares a static `httpStatus`: a server that
20
+ * rethrows one answers 500, as before.
21
+ */
11
22
  export class ApiClientError extends ApiError {
12
23
  public static override typeName = 'ApiClientError'
13
24
 
25
+ /** The HTTP status the peer answered with, when the message states one. */
26
+ public status?: number
27
+
14
28
  constructor(message: string = 'error') {
15
29
  super(`client:${message}`)
16
30
  this.type = ApiClientError.typeName
31
+ this.applyStatus()
32
+ }
33
+
34
+ protected applyStatus(): void {
35
+ const marker = parseClientMarker(this.message)
36
+ this.status = marker?.status
37
+ if (marker?.incidentId != null) {
38
+ this.incidentId ??= marker.incidentId
39
+ }
40
+ }
41
+
42
+ override finalizeUnmarshal(): void {
43
+ this.applyStatus()
17
44
  }
18
45
  }
19
46
 
47
+ /** The peer answered 500. Marker `api:client:crashed:<incident id | error>`. */
20
48
  export class ServerCrashedError extends ApiClientError {
21
49
  public static override typeName = `${ApiClientError.typeName}ServerCrashed`
22
50
 
23
- constructor(message: string = 'error') {
24
- super(`crashed:${message}`)
51
+ constructor(incidentId?: string) {
52
+ super(`crashed:${incidentId ?? 'error'}`)
25
53
  this.type = ServerCrashedError.typeName
26
54
  }
27
55
  }
28
56
 
57
+ /** The peer answered 401. Marker `api:client:auth:<incident id | error>`. */
29
58
  export class ServerAuthError extends ApiClientError {
30
59
  public static override typeName = `${ApiClientError.typeName}ServerAuth`
31
60
 
32
- constructor(message: string = 'error') {
33
- super(`auth:${message}`)
61
+ constructor(incidentId?: string) {
62
+ super(`auth:${incidentId ?? 'error'}`)
34
63
  this.type = ServerAuthError.typeName
35
64
  }
36
65
  }
37
66
 
67
+ /**
68
+ * The peer answered any other non-2xx status with no typed error in the body — a production
69
+ * incident id, a proxy's HTML page, a framework's JSON. Marker `api:client:status:<n>[:<id>]`.
70
+ */
71
+ export class ApiStatusError extends ApiClientError {
72
+ public static override typeName = `${ApiClientError.typeName}Status`
73
+
74
+ /** The marker body: `<status>[:<incident id>]`. */
75
+ static encode(status: number, incidentId?: string): string {
76
+ return incidentId != null && incidentId !== '' ? `${status}:${incidentId}` : `${status}`
77
+ }
78
+
79
+ constructor(status: number, incidentId?: string)
80
+ /** A marker body (`ApiStatusError.encode`) or a marshaled message — the error registry's path. */
81
+ constructor(message: string)
82
+ constructor(status: number | string = 'error', incidentId?: string) {
83
+ super(`status:${typeof status === 'number' ? ApiStatusError.encode(status, incidentId) : status}`)
84
+ this.type = ApiStatusError.typeName
85
+ }
86
+ }
87
+
38
88
  ResilientError.registerErrorClass(ApiError)
39
89
  ResilientError.registerErrorClass(ApiClientError)
40
90
  ResilientError.registerErrorClass(ServerCrashedError)
41
91
  ResilientError.registerErrorClass(ServerAuthError)
92
+ ResilientError.registerErrorClass(ApiStatusError)
package/src/index.ts CHANGED
@@ -1,5 +1,9 @@
1
-
2
1
  export * from './errors.js'
3
2
  export * from './consts.js'
4
3
  export * from './service.js'
5
4
  export type * from './types.js'
5
+ export {
6
+ httpStatusOf, apiStatusHelper, createApiStatusHelper, parseClientMarker, API_CLIENT_MARKER, API_STATUS_MARKER,
7
+ } from './status/index.js'
8
+ export type { ClientMarker, ApiStatusHelper } from './status/index.js'
9
+ export type { ResponseStatusCarrier } from './status/types.js'
package/src/service.ts CHANGED
@@ -1,23 +1,21 @@
1
1
  import { assertContext, createService } from '@owlmeans/context'
2
- import type { BasicContext } from '@owlmeans/context'
3
- import { extractParams } from '@owlmeans/client-route'
2
+ import { clientRouteHelper } from '@owlmeans/client-route'
4
3
  import type { ApiClient } from './types.js'
5
4
  import axios, { AxiosHeaders } from 'axios'
6
5
  import type { AxiosRequestTransformer } from 'axios'
7
6
  import type { CommonEntrypoint } from '@owlmeans/entrypoint'
8
- import { DEFAULT_ALIAS } from './consts.js'
9
- import { processResponse } from './utils/handler.js'
10
- import { BasicClientConfig } from '@owlmeans/client-config'
11
- import qs from 'qs'
7
+ import { DEFAULT_ALIAS, UNAUTHORIZED_ERROR } from './consts.js'
8
+ import { responseUtils } from './utils/response.js'
12
9
  import { makeSecurityHelper } from '@owlmeans/config'
13
- import { RouteMethod } from '@owlmeans/route'
14
- import { DEF_AUTH_SRV, TOKEN_UPDATE } from '@owlmeans/auth-common'
15
- import type { AuthService } from '@owlmeans/auth-common'
10
+ import { AUTH_HEADER, DEF_AUTH_SRV, TOKEN_UPDATE, type AuthService } from '@owlmeans/auth-common'
11
+ import type { Config, Context } from './types.local.js'
12
+ import { bodyUtils } from './utils/body.js'
16
13
 
17
- type Config = BasicClientConfig
18
-
19
- interface Context<C extends Config = Config> extends BasicContext<C> {
20
- }
14
+ /** Whether a request carried an authentication header of its own. */
15
+ const presented = (headers?: Record<string, unknown>): boolean =>
16
+ headers != null && Object.entries(headers).some(
17
+ ([key, value]) => key.toLowerCase() === AUTH_HEADER && value != null && value !== ''
18
+ )
21
19
 
22
20
  export const createApiService = (alias: string = DEFAULT_ALIAS): ApiClient => {
23
21
  const location = `api.service:${alias}`
@@ -28,10 +26,9 @@ export const createApiService = (alias: string = DEFAULT_ALIAS): ApiClient => {
28
26
  }
29
27
  const context = assertContext<Config, Context>(client.ctx, location)
30
28
  const module = context.entrypoint<CommonEntrypoint>(request.alias)
31
- await module.resolve()
32
29
  const route = module.route.route
33
- let path = module.getPath()
34
- const params = extractParams(path)
30
+ let path = module.path()
31
+ const params = clientRouteHelper.extractParams(path)
35
32
  path = params.reduce((path, param) => {
36
33
  type Key = keyof typeof request.params
37
34
  if (request.params[param as Key] == null) {
@@ -39,36 +36,29 @@ export const createApiService = (alias: string = DEFAULT_ALIAS): ApiClient => {
39
36
  }
40
37
  return path.replace(`:${param}`, `${request.params[param as Key]}`)
41
38
  }, path)
42
- if (route.host == null && request.host == null) {
43
- throw new SyntaxError(`No host provided in ${module.alias} route`)
44
- }
45
39
 
46
40
  const helper = makeSecurityHelper(context)
47
41
 
48
- const url = helper.makeUrl(route, path, { host: request.host, base: request.base, forceUnsecure: request.unsecure })
49
-
50
- let transformer: AxiosRequestTransformer | undefined = undefined
51
-
52
- let body = request.body != null && Object.entries((request.headers ?? {})).find(
53
- ([key, value]) =>
54
- key.toLowerCase() === 'content-type' && value?.includes('application/x-www-form-urlencoded')
55
- ) ? qs.stringify(request.body) : request.body
56
-
57
- // @TODO Probably this hack needs to be made a little bit less dirty
58
- if (typeof body === 'string' && route.method === RouteMethod.POST) {
59
- if (Object.keys(request.headers).every(key => key.toLowerCase() !== 'content-type')) {
60
- request.headers['content-type'] = 'application/json'
61
- // It fixes the case when final rest api under application/json can't
62
- // properly accept canonized jsoned string value (put into quotes)
63
- transformer = data => data
64
- }
65
- }
42
+ // The entrypoint answers where it lives — host, port, base, protocol and whether the hop is
43
+ // TLS — from its declaration and the service it names. A per-request host still overrides it.
44
+ const url = helper.makeUrl(
45
+ module.address(), path,
46
+ { host: request.host, base: request.base, forceUnsecure: request.unsecure }
47
+ )
48
+
49
+ // A scalar JSON body (a string, a number, a boolean) is serialized here, so the server parses
50
+ // back the value the caller sent; objects and arrays are left to axios.
51
+ const body = bodyUtils.requestBodyOf(request.body, request.headers, route.method, module.filter?.body)
52
+ const transformer: AxiosRequestTransformer | undefined = body.verbatim ? data => data : undefined
53
+ const requestHeaders = body.contentType != null
54
+ ? { ...request.headers, 'content-type': body.contentType }
55
+ : request.headers
66
56
 
67
57
  const response = await axios.request({
68
58
  url, method: route.method,
69
59
  params: request.query,
70
- data: body,
71
- headers: request.headers,
60
+ data: body.data,
61
+ headers: requestHeaders,
72
62
  transformRequest: transformer,
73
63
  validateStatus: () => true,
74
64
  // Per-request timeout (ms); axios aborts the request and rejects on expiry.
@@ -84,9 +74,27 @@ export const createApiService = (alias: string = DEFAULT_ALIAS): ApiClient => {
84
74
  const auth = context.service<AuthService>(DEF_AUTH_SRV)
85
75
  const update = headers.get(TOKEN_UPDATE) as string
86
76
  await auth.update(update == null || update === '' ? undefined : update)
77
+ } else if (
78
+ response.status === UNAUTHORIZED_ERROR
79
+ && presented(request.headers)
80
+ && context.hasService(DEF_AUTH_SRV)
81
+ ) {
82
+ /**
83
+ * A session the server has refused is not a session, and keeping it is worse than having
84
+ * none: the application goes on rendering its signed-in tree over a credential that fails
85
+ * every call it makes, and nothing on the client ever asks again — `authenticated()` reads
86
+ * storage and decodes an envelope, it does not consult the server. What that leaves is an
87
+ * app that looks signed in, works at nothing, and offers "Log out" where the control that
88
+ * would fix it should be.
89
+ *
90
+ * Narrow on purpose. Only a request that actually PRESENTED this context's bearer counts,
91
+ * so a 401 from an authentication attempt — bad code, wrong password, an expired challenge
92
+ * — never clears the session of whoever is already signed in.
93
+ */
94
+ await context.service<AuthService>(DEF_AUTH_SRV).update(undefined)
87
95
  }
88
96
 
89
- processResponse(response, reply)
97
+ responseUtils.processResponse(response, reply)
90
98
 
91
99
  return [reply.error ?? reply.value, reply.outcome] as any
92
100
  }
@@ -0,0 +1,11 @@
1
+ export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
2
+
3
+ /**
4
+ * `crashed` / `auth` / `forbidden` / `status:<n>` / the legacy bare `<n>`, then an optional
5
+ * `:<incident id>`. The look-ahead refuses a match that runs on into more marker text, so a
6
+ * doubled prefix (a subclass constructor handed a whole marshaled message) resolves to the inner,
7
+ * complete marker.
8
+ */
9
+ export const MARKER = /api:client:(?:(crashed|auth|forbidden)|status:(\d{3})|(\d{3}))(?::([\w.-]{1,128}))?(?![\w.:-])/
10
+
11
+ export const NAMED_STATUS: Record<string, number> = { crashed: 500, auth: 401, forbidden: 403 }
@@ -0,0 +1,5 @@
1
+ /** The prefix every `ApiClientError` message carries. */
2
+ export const API_CLIENT_MARKER = 'api:client:'
3
+
4
+ /** The marker of an `ApiStatusError`: `api:client:status:<n>[:<incident id>]`. */
5
+ export const API_STATUS_MARKER = `${API_CLIENT_MARKER}status:`
@@ -0,0 +1,63 @@
1
+ import { ResilientError } from '@owlmeans/error'
2
+ import { ApiClientError } from '../errors.js'
3
+ import { parseClientMarker } from './marker.js'
4
+ import { ACCESS_DENIED_KIND } from '../consts.js'
5
+ import { UUID } from './consts.local.js'
6
+ import type { ApiStatusHelper, ClientMarker, ResponseStatusCarrier } from './types.js'
7
+
8
+ export const createApiStatusHelper = (): ApiStatusHelper => {
9
+ const isAccessDenied = (error: unknown): boolean =>
10
+ httpStatusOf(error) === 403
11
+ && typeof error === 'object' && error != null
12
+ && (error as ResponseStatusCarrier).denialKind === ACCESS_DENIED_KIND
13
+
14
+ const httpStatus = (value: unknown): number | null =>
15
+ typeof value === 'number' && Number.isInteger(value) && value >= 100 && value <= 599 ? value : null
16
+
17
+ /** The first `api:client:*` marker in an error's `message`, else in its `type`. */
18
+ const markerOf = (error: object): ClientMarker | null => {
19
+ const { message, type } = error as { message?: unknown, type?: unknown }
20
+
21
+ return (typeof message === 'string' ? parseClientMarker(message) : null)
22
+ ?? (typeof type === 'string' ? parseClientMarker(type) : null)
23
+ }
24
+
25
+ const httpStatusOf = (error: unknown): number | null => {
26
+ if (error == null || typeof error !== 'object') {
27
+ return null
28
+ }
29
+ const stamped = httpStatus((error as ResponseStatusCarrier).responseStatus)
30
+ if (stamped != null) {
31
+ return stamped
32
+ }
33
+ if (error instanceof ApiClientError && httpStatus(error.status) != null) {
34
+ return error.status!
35
+ }
36
+ const declaration = error.constructor as { httpStatus?: unknown, allowServerErrorStatus?: unknown } | undefined
37
+ const declared = httpStatus(declaration?.httpStatus)
38
+ if (declared != null && (declared < 500 || declaration?.allowServerErrorStatus === true)) {
39
+ return declared
40
+ }
41
+
42
+ return markerOf(error)?.status ?? null
43
+ }
44
+
45
+ const incidentIdOf = (error: unknown): string | null => {
46
+ if (error == null || typeof error !== 'object') {
47
+ return null
48
+ }
49
+ const own = (error as { incidentId?: unknown }).incidentId
50
+ if (typeof own === 'string' && own !== '') {
51
+ return own
52
+ }
53
+
54
+ return markerOf(error)?.incidentId ?? null
55
+ }
56
+
57
+ const isIncidentBody = (data: unknown): data is string =>
58
+ typeof data === 'string' && !data.includes(ResilientError.separator) && UUID.test(data.trim())
59
+
60
+ return { isAccessDenied, httpStatusOf, incidentIdOf, isIncidentBody }
61
+ }
62
+
63
+ export const apiStatusHelper = createApiStatusHelper()
@@ -0,0 +1,11 @@
1
+ import { apiStatusHelper } from './helper.js'
2
+
3
+ export { INCIDENT_ID_HEADER } from '../consts.js'
4
+ export { DENIAL_KIND_HEADER, ACCESS_DENIED_KIND } from '../consts.js'
5
+ export { parseClientMarker } from './marker.js'
6
+ export { API_CLIENT_MARKER, API_STATUS_MARKER } from './consts.js'
7
+ export type { ClientMarker, ResponseStatusCarrier, ApiStatusHelper } from './types.js'
8
+ export { apiStatusHelper, createApiStatusHelper } from './helper.js'
9
+
10
+ /** @deprecated compat:factory-refactor — use `apiStatusHelper.httpStatusOf(…)` */
11
+ export const httpStatusOf = (error: unknown): number | null => apiStatusHelper.httpStatusOf(error)
@@ -0,0 +1,19 @@
1
+
2
+ /** Read the first `api:client:*` marker in a text, or `null` when it carries none. */
3
+ import { MARKER, NAMED_STATUS } from './consts.local.js'
4
+ import type { ClientMarker } from './types.js'
5
+
6
+ export const parseClientMarker = (text: string): ClientMarker | null => {
7
+ const match = MARKER.exec(text)
8
+ if (match == null) {
9
+ return null
10
+ }
11
+ const [, named, coded, legacy, id] = match
12
+ const code = named != null ? NAMED_STATUS[named] : Number(coded ?? legacy)
13
+
14
+ return {
15
+ status: code >= 100 && code <= 599 ? code : undefined,
16
+ // `error` is the placeholder a marker gets when no incident id was known.
17
+ incidentId: id != null && id !== 'error' ? id : undefined,
18
+ }
19
+ }
@@ -0,0 +1,36 @@
1
+ /** The HTTP status the API client stamps on an error it rebuilt from a response body. */
2
+ export interface ResponseStatusCarrier {
3
+ responseStatus?: number
4
+ denialKind?: string
5
+ }
6
+
7
+ /** What an `api:client:*` marker states. */
8
+ export interface ClientMarker {
9
+ status?: number
10
+ incidentId?: string
11
+ }
12
+
13
+ /** Reads the HTTP status, the incident id and the denial kind a failed call carries. */
14
+ export interface ApiStatusHelper {
15
+ /** True only for a server-labelled auth/IAM refusal, never an unrelated 403. */
16
+ isAccessDenied: (error: unknown) => boolean
17
+ /**
18
+ * The HTTP status an error answers to, or `null` when nothing states one.
19
+ *
20
+ * Read in order: the status the API client stamped on the error it rebuilt from a response
21
+ * (`responseStatus`); the status an `ApiClientError` parsed from its marker; the `httpStatus` its
22
+ * class declares — a 4xx always, a 5xx only with `allowServerErrorStatus`, exactly what an
23
+ * `@owlmeans/server-api` boundary answers with; finally an `api:client:*` marker in the message or
24
+ * the type of anything else. This is what lets a browser recognise a refusal from its status
25
+ * alone when a production body carries nothing but an incident id.
26
+ */
27
+ httpStatusOf: (error: unknown) => number | null
28
+ /** The server's incident id carried by an error — its own field, else its marker — or `null`. */
29
+ incidentIdOf: (error: unknown) => string | null
30
+ /**
31
+ * Whether a response body is a production incident body — the bare incident UUID an
32
+ * `@owlmeans/server-api` boundary sends instead of the marshaled error. A development body
33
+ * carries the `ResilientError` separator and is never one.
34
+ */
35
+ isIncidentBody: (data: unknown) => data is string
36
+ }
@@ -0,0 +1,7 @@
1
+ import { BasicClientConfig } from '@owlmeans/client-config'
2
+ import type { BasicContext } from '@owlmeans/context'
3
+
4
+ export type Config = BasicClientConfig
5
+
6
+ export interface Context<C extends Config = Config> extends BasicContext<C> {
7
+ }
@@ -0,0 +1,37 @@
1
+ import type { RouteMethod } from '@owlmeans/route'
2
+
3
+ export interface RequestBody {
4
+ /** What axios is handed as `data`. */
5
+ data: unknown
6
+ /** A `content-type` the request lacked and must carry. */
7
+ contentType?: string
8
+ /** `data` is final text — axios must not transform it again. */
9
+ verbatim: boolean
10
+ }
11
+
12
+ /** How a request's body travels: its content type and the text a scalar body becomes. */
13
+ export interface BodyUtils {
14
+ /** The request's own `content-type`, whatever case its key is written in. */
15
+ contentTypeOf: (headers?: Record<string, unknown>) => string | undefined
16
+ /** `application/json` or a `+json` suffix type, with or without parameters. */
17
+ isJsonContentType: (type?: string) => boolean
18
+ /**
19
+ * The JSON text a scalar body travels as, so the server parses it back to the same value.
20
+ *
21
+ * A number or a boolean is `JSON.stringify`'d. A string is a value unless it is already JSON text:
22
+ * one that does not parse is quoted; one that parses is sent as it is (the caller serialized it
23
+ * itself) — except under a body schema of `type: 'string'`, where only a JSON string literal
24
+ * counts as serialized and `123`, `true` or `{…}` are the text the caller means.
25
+ */
26
+ jsonScalarBody: (body: string | number | boolean, schema?: object) => string
27
+ /**
28
+ * What a request's body becomes on the wire.
29
+ *
30
+ * - A `x-www-form-urlencoded` request: the body through `qs`.
31
+ * - A string, number or boolean under a JSON `content-type` — the caller's, or `application/json`
32
+ * supplied for a `POST` that names none — becomes JSON text ({@link BodyUtils.jsonScalarBody}).
33
+ * - Anything else — objects, arrays, a scalar under another content type — goes to axios as it is,
34
+ * which serializes an object or an array as JSON.
35
+ */
36
+ requestBodyOf: (body: unknown, headers: Record<string, unknown> | undefined, method?: RouteMethod, schema?: object) => RequestBody
37
+ }
@@ -0,0 +1,70 @@
1
+ import qs from 'qs'
2
+ import { RouteMethod } from '@owlmeans/route'
3
+ import { FORM_CONTENT_TYPE } from './consts.local.js'
4
+ import { JSON_CONTENT_TYPE } from './consts.js'
5
+ import type { BodyUtils, RequestBody } from './body/types.js'
6
+
7
+ export const createBodyUtils = (): BodyUtils => {
8
+ const contentTypeOf = (headers?: Record<string, unknown>): string | undefined => {
9
+ const value = Object.entries(headers ?? {}).find(([key]) => key.toLowerCase() === 'content-type')?.[1]
10
+ if (value == null || value === '') {
11
+ return undefined
12
+ }
13
+ return Array.isArray(value) ? value.join(', ') : `${value}`
14
+ }
15
+
16
+ const isJsonContentType = (type?: string): boolean =>
17
+ type != null && /^application\/(?:[^\s;]+\+)?json\s*(?:;|$)/i.test(type.trim())
18
+
19
+ /** A JSON value no serializer quotes for us: a string, a number or a boolean. */
20
+ const isScalar = (value: unknown): value is string | number | boolean =>
21
+ typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
22
+
23
+ /** Does the entrypoint's body schema declare a string? */
24
+ const stringContract = (schema?: object): boolean => {
25
+ const type = (schema as { type?: unknown } | undefined)?.type
26
+ return (Array.isArray(type) ? type : [type]).includes('string')
27
+ }
28
+
29
+ const parse = (text: string): { json: true, value: unknown } | { json: false } => {
30
+ try {
31
+ return { json: true, value: JSON.parse(text) }
32
+ } catch {
33
+ return { json: false }
34
+ }
35
+ }
36
+
37
+ const jsonScalarBody = (body: string | number | boolean, schema?: object): string => {
38
+ if (typeof body !== 'string') {
39
+ return JSON.stringify(body)
40
+ }
41
+ const parsed = parse(body)
42
+ const serialized = parsed.json && (!stringContract(schema) || typeof parsed.value === 'string')
43
+
44
+ return serialized ? body : JSON.stringify(body)
45
+ }
46
+
47
+ const requestBodyOf = (
48
+ body: unknown, headers: Record<string, unknown> | undefined, method?: RouteMethod, schema?: object
49
+ ): RequestBody => {
50
+ const type = contentTypeOf(headers)
51
+ if (body != null && type?.includes(FORM_CONTENT_TYPE) === true) {
52
+ return { data: qs.stringify(body), verbatim: false }
53
+ }
54
+ if (!isScalar(body)) {
55
+ return { data: body, verbatim: false }
56
+ }
57
+ if (type == null && method === RouteMethod.POST) {
58
+ return { data: jsonScalarBody(body, schema), contentType: JSON_CONTENT_TYPE, verbatim: true }
59
+ }
60
+ if (isJsonContentType(type)) {
61
+ return { data: jsonScalarBody(body, schema), verbatim: true }
62
+ }
63
+
64
+ return { data: body, verbatim: false }
65
+ }
66
+
67
+ return { contentTypeOf, isJsonContentType, jsonScalarBody, requestBodyOf }
68
+ }
69
+
70
+ export const bodyUtils = createBodyUtils()
@@ -0,0 +1 @@
1
+ export const FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded'
@@ -0,0 +1 @@
1
+ export const JSON_CONTENT_TYPE = 'application/json'
@@ -1,2 +1,3 @@
1
1
 
2
- export * from './handler.js'
2
+ export type * from './response/types.js'
3
+ export * from './response.js'
@@ -0,0 +1,15 @@
1
+ import type { AbstractResponse } from '@owlmeans/entrypoint'
2
+ import type { AxiosResponse } from 'axios'
3
+ import type { ApiClientError } from '../../errors.js'
4
+
5
+ /** Turns an axios answer into the entrypoint reply: a resolved value or a typed failure. */
6
+ export interface ResponseUtils {
7
+ /** Resolves `reply` with a 2xx answer's value, or rejects it with the failure of any other status. */
8
+ processResponse: (response: AxiosResponse, reply: AbstractResponse<any>) => void
9
+ /**
10
+ * The typed error of a bare status: `ServerCrashedError` (500), `ServerAuthError` (401),
11
+ * `ApiClientError('forbidden[:<id>]')` (403), `ApiStatusError` (`api:client:status:<n>[:<id>]`)
12
+ * for every other one.
13
+ */
14
+ statusError: (status: number, incidentId?: string) => ApiClientError
15
+ }
@@ -0,0 +1,117 @@
1
+ import { type AbstractResponse, EntrypointOutcome } from '@owlmeans/entrypoint'
2
+ import type { AxiosResponse } from 'axios'
3
+ import {
4
+ ACCEPTED, CREATED, FINISHED, FORBIDDEN_ERROR, INCIDENT_ID_HEADER, DENIAL_KIND_HEADER,
5
+ ACCESS_DENIED_KIND, OK, SERVER_ERROR, UNAUTHORIZED_ERROR,
6
+ } from '../consts.js'
7
+ import { ResilientError } from '@owlmeans/error'
8
+ import { ApiClientError, ApiStatusError, ServerAuthError, ServerCrashedError } from '../errors.js'
9
+ import { apiStatusHelper } from '../status/helper.js'
10
+ import type { ResponseStatusCarrier } from '../status/types.js'
11
+ import { logger } from '@owlmeans/log'
12
+ import type { ResponseUtils } from './response/types.js'
13
+
14
+ export const createResponseUtils = (): ResponseUtils => {
15
+ const log = logger('api')
16
+
17
+ const processResponse = (response: AxiosResponse, reply: AbstractResponse<any>): void => {
18
+ switch (response.status) {
19
+ case OK:
20
+ reply.resolve(response.data, EntrypointOutcome.Ok)
21
+ return
22
+ case ACCEPTED:
23
+ reply.resolve(response.data, EntrypointOutcome.Accepted)
24
+ return
25
+ case CREATED:
26
+ return processEmptyResponse(response, reply, EntrypointOutcome.Created)
27
+ case FINISHED:
28
+ return processEmptyResponse(response, reply, EntrypointOutcome.Finished)
29
+ default:
30
+ // A refusal is ordinary traffic (401, 403, 409, 428): debug, and never the headers.
31
+ log.debug('Request answered with a failure', {
32
+ status: response.status, statusText: response.statusText, url: response.config?.url,
33
+ incidentId: headerOf(response.headers, INCIDENT_ID_HEADER),
34
+ })
35
+
36
+ reply.reject(failureOf(response))
37
+ }
38
+ }
39
+
40
+ /**
41
+ * The error a non-2xx answer rejects with — always carrying the HTTP status and, when the server
42
+ * sent one, its incident id.
43
+ *
44
+ * A development body is the marshaled `ResilientError`: it is rebuilt into its own class and
45
+ * stamped with `responseStatus`. Anything else — the bare incident id of a production body, a
46
+ * proxy's HTML, a framework's JSON — becomes the status error of {@link statusError}.
47
+ */
48
+ const failureOf = (response: AxiosResponse): Error => {
49
+ const incidentId = headerOf(response.headers, INCIDENT_ID_HEADER)
50
+ ?? (apiStatusHelper.isIncidentBody(response.data) ? response.data.trim() : undefined)
51
+ const denialKind = response.status === FORBIDDEN_ERROR
52
+ && headerOf(response.headers, DENIAL_KIND_HEADER) === ACCESS_DENIED_KIND
53
+ ? ACCESS_DENIED_KIND : undefined
54
+
55
+ if (typeof response.data === 'string' && response.data.includes(ResilientError.separator)) {
56
+ try {
57
+ const error = ResilientError.ensure(response.data, true)
58
+ error.incidentId ??= incidentId
59
+ Object.assign(error, {
60
+ responseStatus: response.status, denialKind,
61
+ } satisfies ResponseStatusCarrier)
62
+
63
+ return error
64
+ } catch {
65
+ log.warn('Server returned an unrecognizable text error', { status: response.status, body: response.data })
66
+ }
67
+ }
68
+
69
+ return Object.assign(statusError(response.status, incidentId), { denialKind })
70
+ }
71
+
72
+ /**
73
+ * The typed error of a bare status: `ServerCrashedError` (500), `ServerAuthError` (401),
74
+ * `ApiClientError('forbidden[:<id>]')` (403), `ApiStatusError` (`api:client:status:<n>[:<id>]`)
75
+ * for every other one.
76
+ */
77
+ const statusError = (status: number, incidentId?: string): ApiClientError => {
78
+ const error = status === SERVER_ERROR ? new ServerCrashedError(incidentId)
79
+ : status === UNAUTHORIZED_ERROR ? new ServerAuthError(incidentId)
80
+ : status === FORBIDDEN_ERROR ? new ApiClientError(incidentId != null ? `forbidden:${incidentId}` : 'forbidden')
81
+ : new ApiStatusError(status, incidentId)
82
+ if (incidentId != null) {
83
+ error.incidentId = incidentId
84
+ }
85
+
86
+ return Object.assign(error, { responseStatus: status } satisfies ResponseStatusCarrier)
87
+ }
88
+
89
+ /** One response header, from an `AxiosHeaders` instance or a plain header object alike. */
90
+ const headerOf = (headers: unknown, name: string): string | undefined => {
91
+ if (headers == null || typeof headers !== 'object') {
92
+ return undefined
93
+ }
94
+ const get = (headers as { get?: unknown }).get
95
+ const viaGet = typeof get === 'function' ? get.call(headers, name) : undefined
96
+ const value = viaGet ?? Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1]
97
+ const first = Array.isArray(value) ? value[0] : value
98
+
99
+ return typeof first === 'string' && first.trim() !== '' ? first.trim() : undefined
100
+ }
101
+
102
+ const processEmptyResponse = (response: AxiosResponse, reply: AbstractResponse<any>, outcome: EntrypointOutcome): void => {
103
+ if (response.data != null && response.data != '') {
104
+ reply.resolve(response.data, outcome)
105
+ return
106
+ }
107
+ if (response.headers.toJSON != null && typeof response.headers.toJSON === 'function') {
108
+ reply.resolve(response.headers.toJSON(), outcome)
109
+ return
110
+ }
111
+ reply.resolve(response.headers, outcome)
112
+ }
113
+
114
+ return { processResponse, statusError }
115
+ }
116
+
117
+ export const responseUtils = createResponseUtils()