massimo 0.0.1 → 0.1.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.
package/.c8rc ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "exclude": [
3
+ "fixtures/*",
4
+ "test/*"
5
+ ]
6
+ }
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2025 Platformatic
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # @platformatic/massimo
2
+
3
+ Check out the full documentation for Massimo on [massimohttp.dev](https://massimohttp.dev).
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @platformatic/massimo
9
+ ```
10
+
11
+ ## License
12
+
13
+ Apache 2.0
@@ -0,0 +1,3 @@
1
+ import neostandard from 'neostandard'
2
+
3
+ export default neostandard()
@@ -0,0 +1,38 @@
1
+ import { FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify'
2
+ import { Dispatcher } from 'undici'
3
+
4
+ interface Headers {
5
+ [key: string]: string
6
+ }
7
+
8
+ export interface GetHeadersOptions {
9
+ url: URL
10
+ method: string
11
+ body: object
12
+ headers: Headers
13
+ telemetryHeaders?: Headers
14
+ }
15
+
16
+ interface PlatformaticClientOptions {
17
+ url: string
18
+ path?: string
19
+ fullResponse: boolean
20
+ fullRequest: boolean
21
+ throwOnError: boolean
22
+ headers?: Headers
23
+ bodyTimeout?: number
24
+ headersTimeout?: number
25
+ validateResponse?: boolean
26
+ queryParser?: (query: URLSearchParams) => string
27
+ dispatcher?: Dispatcher
28
+ }
29
+
30
+ export type PlatformaticClientPluginOptions = PlatformaticClientOptions & {
31
+ type: 'openapi' | 'graphql'
32
+ name?: string
33
+ applicationId?: string
34
+ getHeaders?: (request: FastifyRequest, reply: FastifyReply, options: GetHeadersOptions) => Promise<Headers>
35
+ }
36
+
37
+ export const plugin: FastifyPluginAsync<PlatformaticClientPluginOptions>
38
+ export default plugin
@@ -0,0 +1,63 @@
1
+ import { buildGraphQLClient, buildOpenAPIClient } from './index.js'
2
+ import { WrongOptsTypeError } from './lib/errors.js'
3
+ import { kGetHeaders, kTelemetryContext } from './lib/symbols.js'
4
+
5
+ function capitalize (str) {
6
+ return str.charAt(0).toUpperCase() + str.slice(1)
7
+ }
8
+
9
+ export async function plugin (app, opts) {
10
+ let client = null
11
+ let getHeaders = null
12
+
13
+ if (typeof opts.getHeaders === 'function') {
14
+ getHeaders = opts.getHeaders
15
+ opts = { ...opts }
16
+ opts.getHeaders = undefined
17
+ }
18
+
19
+ if (opts.applicationId && !opts.url) {
20
+ opts.url = `http://${opts.applicationId}.plt.local`
21
+ }
22
+
23
+ if (opts.type === 'openapi') {
24
+ client = await buildOpenAPIClient(opts, app.openTelemetry)
25
+ } else if (opts.type === 'graphql') {
26
+ if (!opts.url.endsWith('/graphql')) {
27
+ opts.url += '/graphql'
28
+ }
29
+ client = await buildGraphQLClient(opts, app.openTelemetry, app.log)
30
+ } else {
31
+ throw new WrongOptsTypeError()
32
+ }
33
+
34
+ let name = opts.name
35
+ if (!name) {
36
+ name = 'client'
37
+ }
38
+
39
+ app.decorateRequest(name, null)
40
+
41
+ app.decorate('configure' + capitalize(name), function (opts) {
42
+ getHeaders = opts.getHeaders
43
+ })
44
+
45
+ app.addHook('onRequest', async (req, reply) => {
46
+ const newClient = Object.create(client)
47
+
48
+ if (getHeaders) {
49
+ newClient[kGetHeaders] = getHeaders.bind(newClient, req, reply)
50
+ }
51
+ if (req.span) {
52
+ newClient[kTelemetryContext] = req.span.context
53
+ }
54
+ req[name] = newClient
55
+ })
56
+ }
57
+
58
+ plugin[Symbol.for('skip-override')] = true
59
+ plugin[Symbol.for('plugin-meta')] = {
60
+ name: '@platformatic/client'
61
+ }
62
+
63
+ export default plugin
package/index.d.ts ADDED
@@ -0,0 +1,93 @@
1
+ import { FastifyError } from '@fastify/error'
2
+ import { Dispatcher } from 'undici';
3
+
4
+ type CodeClasses = 1 | 2 | 3 | 4 | 5;
5
+ type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
6
+ type StringAsNumber<T extends string> = T extends `${infer N extends number}` ? N : never;
7
+ type StatusCodes<T extends CodeClasses> = StringAsNumber<`${T}${Digit}${Digit}`>;
8
+ export type StatusCode1xx = StatusCodes<1>;
9
+ export type StatusCode2xx = StatusCodes<2>;
10
+ export type StatusCode3xx = StatusCodes<3>;
11
+ export type StatusCode4xx = StatusCodes<4>;
12
+ export type StatusCode5xx = StatusCodes<5>;
13
+
14
+ interface Headers {
15
+ [key: string]: string
16
+ }
17
+
18
+ export interface GetHeadersOptions {
19
+ url: URL;
20
+ method: string;
21
+ body: object;
22
+ headers: Headers;
23
+ telemetryHeaders?: Headers;
24
+ }
25
+
26
+ interface PlatformaticClientOptions {
27
+ url: string;
28
+ path?: string;
29
+ fullResponse?: boolean;
30
+ fullRequest?: boolean;
31
+ throwOnError?: boolean;
32
+ headers?: Headers;
33
+ bodyTimeout?: number;
34
+ headersTimeout?: number;
35
+ validateResponse?: boolean;
36
+ queryParser?: (query: URLSearchParams) => string;
37
+ dispatcher?: Dispatcher;
38
+ }
39
+
40
+ type BuildOpenAPIClientOptions = PlatformaticClientOptions & {
41
+ getHeaders?: (options: GetHeadersOptions) => Promise<Headers>;
42
+ }
43
+
44
+ interface AbstractLogger {
45
+ fatal: () => void;
46
+ error: () => void;
47
+ warn: () => void;
48
+ info: () => void;
49
+ debug: () => void;
50
+ trace: () => void;
51
+ }
52
+
53
+ interface BuildGraphQLClientOptions {
54
+ url: string;
55
+ headers?: Headers;
56
+ }
57
+
58
+ interface Parameter {
59
+ in: string;
60
+ name: string;
61
+ }
62
+
63
+ interface MethodMetaInterface {
64
+ operationId?: string,
65
+ parameters: Parameter[]
66
+ }
67
+
68
+ interface BuildGraphQLClientOutput {
69
+ graphql: <T>() => Promise<T>;
70
+ }
71
+
72
+ type OpenTelemetry = {
73
+ startSpanClient?: (urlToCall: URL, method: string, telemetryContext: any) => object
74
+ endSpanClient?: (span: any, res: any) => void
75
+ setErrorInSpanClient?: (span: any, err: unknown) => void
76
+ }
77
+
78
+ export function generateOperationId(path: string, method: string, methodMeta: MethodMetaInterface, all: string[]): string
79
+ export function buildOpenAPIClient<T>(options: BuildOpenAPIClientOptions, openTelemetry?: OpenTelemetry): Promise<T>
80
+ export function buildGraphQLClient(options: BuildGraphQLClientOptions, openTelemetry?: OpenTelemetry, logger?: AbstractLogger): Promise<BuildGraphQLClientOutput>
81
+ export function hasDuplicatedParameters(methodMeta: MethodMetaInterface): boolean
82
+
83
+ export module errors {
84
+ export const OptionsUrlRequiredError: () => FastifyError
85
+ export const FormDataRequiredError: (value: string) => FastifyError
86
+ export const MissingParamsRequiredError: (value: string) => FastifyError
87
+ export const WrongOptsTypeError: () => FastifyError
88
+ export const InvalidResponseSchemaError: (value: string) => FastifyError
89
+ export const InvalidContentTypeError: (value: string) => FastifyError
90
+ export const InvalidResponseFormatError: () => FastifyError
91
+ export const UnexpectedCallFailureError: (value: string) => FastifyError
92
+ }
93
+
package/index.js ADDED
@@ -0,0 +1,505 @@
1
+ import $RefParser from '@apidevtools/json-schema-ref-parser'
2
+ import Ajv from 'ajv'
3
+ import camelCase from 'camelcase'
4
+ import fs from 'fs/promises'
5
+ import { createHash } from 'node:crypto'
6
+ import { join } from 'path'
7
+ import * as undici from 'undici'
8
+ import * as errors from './lib/errors.js'
9
+ import { kGetHeaders, kHeaders, kTelemetryContext } from './lib/symbols.js'
10
+
11
+ const {
12
+ FormData,
13
+ errors: { UndiciError },
14
+ getGlobalDispatcher,
15
+ request,
16
+ interceptors
17
+ } = undici
18
+
19
+ const validateFunctionCache = {}
20
+
21
+ function noop () {}
22
+
23
+ const abstractLogger = {
24
+ fatal: noop,
25
+ error: noop,
26
+ warn: noop,
27
+ info: noop,
28
+ debug: noop,
29
+ trace: noop,
30
+ done: noop,
31
+ child () {
32
+ return abstractLogger
33
+ }
34
+ }
35
+
36
+ function computeURLWithoutPath (url) {
37
+ url = new URL(url)
38
+ url.pathname = ''
39
+ return url.toString()
40
+ }
41
+
42
+ async function buildCallFunction (
43
+ spec,
44
+ baseUrl,
45
+ path,
46
+ method,
47
+ methodMeta,
48
+ openTelemetry,
49
+ fullRequest,
50
+ fullResponse,
51
+ validateResponse,
52
+ queryParser,
53
+ bodyTimeout,
54
+ headersTimeout,
55
+ dispatcher
56
+ ) {
57
+ if (validateResponse) {
58
+ await $RefParser.dereference(spec)
59
+ }
60
+ const ajv = new Ajv()
61
+ const url = new URL(baseUrl)
62
+ method = method.toUpperCase()
63
+ path = join(url.pathname, path)
64
+
65
+ const canHaveBody = method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'OPTIONS'
66
+ const pathParams = methodMeta.parameters?.filter(p => p.in === 'path') || []
67
+ const queryParams = methodMeta.parameters?.filter(p => p.in === 'query') || []
68
+ const headerParams = methodMeta.parameters?.filter(p => p.in === 'header') || []
69
+ const forceFullRequest = fullRequest || hasDuplicatedParameters(methodMeta)
70
+
71
+ const responses = methodMeta.responses
72
+ return async function (args) {
73
+ let headers = this[kHeaders]
74
+ let telemetryContext = null
75
+ if (this[kTelemetryContext]) {
76
+ telemetryContext = this[kTelemetryContext]
77
+ }
78
+ let body
79
+ const query = new URLSearchParams()
80
+ let pathToCall = path
81
+ const urlToCall = new URL(url)
82
+ if (forceFullRequest) {
83
+ headers = args?.headers
84
+ body = args?.body || ''
85
+ for (const param of pathParams) {
86
+ if (args?.path[param.name] === undefined) {
87
+ throw new errors.MissingParamsRequiredError(param.name)
88
+ }
89
+ pathToCall = pathToCall.replace(`{${param.name}}`, args.path[param.name])
90
+ }
91
+
92
+ for (const param of queryParams) {
93
+ if (args?.query?.[param.name] !== undefined) {
94
+ if (isArrayQueryParam(param)) {
95
+ args.query[param.name].forEach(p => query.append(param.name, p))
96
+ } else {
97
+ query.append(param.name, args.query[param.name])
98
+ }
99
+ }
100
+ }
101
+ } else {
102
+ body = args instanceof FormData ? args : { ...args } || '' // shallow copy
103
+ for (const param of pathParams) {
104
+ if (body[param.name] === undefined) {
105
+ throw new errors.MissingParamsRequiredError(param.name)
106
+ }
107
+ pathToCall = pathToCall.replace(`{${param.name}}`, body[param.name])
108
+ body[param.name] = undefined
109
+ }
110
+
111
+ for (const param of queryParams) {
112
+ if (body[param.name] !== undefined) {
113
+ if (isArrayQueryParam(param)) {
114
+ body[param.name].forEach(p => query.append(param.name, p))
115
+ } else {
116
+ query.append(param.name, body[param.name])
117
+ }
118
+ body[param.name] = undefined
119
+ }
120
+ }
121
+
122
+ for (const param of headerParams) {
123
+ if (body[param.name] !== undefined) {
124
+ headers[param.name] = body[param.name]
125
+ body[param.name] = undefined
126
+ }
127
+ }
128
+ }
129
+
130
+ urlToCall.search = queryParser ? queryParser(query) : query.toString()
131
+ urlToCall.pathname = pathToCall
132
+
133
+ const { span, telemetryHeaders } = openTelemetry?.startHTTPSpanClient(
134
+ urlToCall.toString(),
135
+ method,
136
+ telemetryContext
137
+ ) || { span: null, telemetryHeaders: {} }
138
+
139
+ if (this[kGetHeaders]) {
140
+ const options = { url: urlToCall, method, headers, telemetryHeaders, body }
141
+ headers = { ...headers, ...(await this[kGetHeaders](options)) }
142
+ }
143
+
144
+ let res
145
+ try {
146
+ const requestOptions = {
147
+ method,
148
+ headers: {
149
+ ...headers,
150
+ ...telemetryHeaders
151
+ },
152
+ bodyTimeout,
153
+ headersTimeout,
154
+ dispatcher
155
+ }
156
+ if (canHaveBody) {
157
+ const bodyType = getRequestBodyContentType(methodMeta)
158
+ if (bodyType === 'multipart/form-data') {
159
+ if (body instanceof FormData) {
160
+ requestOptions.body = body
161
+ } else {
162
+ throw new errors.FormDataRequiredError(`${method} ${path}`)
163
+ }
164
+ } else {
165
+ requestOptions.headers['content-type'] = bodyType
166
+ requestOptions.body = JSON.stringify(body)
167
+ }
168
+ }
169
+ res = await request(urlToCall, requestOptions)
170
+ let responseBody
171
+ const contentType = sanitizeContentType(res.headers['content-type']) || 'application/json'
172
+ try {
173
+ if (res.statusCode === 204) {
174
+ await res.body.dump()
175
+ } else if (contentType === 'application/json') {
176
+ responseBody = await res.body.json()
177
+ } else {
178
+ responseBody = await res.body.text()
179
+ }
180
+ } catch (err) {
181
+ // maybe the response is a 302, 301, or anything with empty payload
182
+ responseBody = {}
183
+ }
184
+ if (validateResponse) {
185
+ try {
186
+ // validate response first
187
+ const matchingResponse = responses[res.statusCode]
188
+
189
+ if (matchingResponse === undefined) {
190
+ throw new errors.InvalidResponseSchemaError(res.statusCode)
191
+ }
192
+ const matchingContentSchema = matchingResponse.content[contentType]
193
+
194
+ if (matchingContentSchema === undefined) {
195
+ throw new errors.InvalidContentTypeError(contentType)
196
+ }
197
+ const bodyIsValid = checkResponseAgainstSchema(responseBody, matchingContentSchema.schema, ajv)
198
+
199
+ if (!bodyIsValid) {
200
+ throw new errors.InvalidResponseFormatError()
201
+ }
202
+ } catch (err) {
203
+ responseBody = createErrorResponse(err.message)
204
+ }
205
+ }
206
+ if (fullResponse) {
207
+ return {
208
+ statusCode: res.statusCode,
209
+ headers: res.headers,
210
+ body: responseBody
211
+ }
212
+ }
213
+ return responseBody
214
+ } catch (err) {
215
+ openTelemetry?.setErrorInSpanClient(span, err)
216
+ const requestError = new errors.UnexpectedCallFailureError(err.toString())
217
+ if (err instanceof UndiciError) {
218
+ requestError.status = err.statusCode
219
+ requestError.statusCode = err.statusCode
220
+ requestError.headers = err.headers
221
+ requestError.body = err.body
222
+ requestError.data = err.data
223
+ requestError.socket = err.socket
224
+ }
225
+ throw requestError
226
+ } finally {
227
+ openTelemetry?.endHTTPSpanClient(span, res)
228
+ }
229
+ }
230
+ }
231
+
232
+ function getRequestBodyContentType (methodMetadata) {
233
+ let output = null
234
+ if (!methodMetadata.requestBody) {
235
+ return 'application/json'
236
+ }
237
+ if (methodMetadata.requestBody && methodMetadata.requestBody.content) {
238
+ if (methodMetadata.requestBody.content['multipart/form-data']) {
239
+ output = 'multipart/form-data'
240
+ }
241
+
242
+ if (methodMetadata.requestBody.content['application/json']) {
243
+ output = 'application/json'
244
+ }
245
+ }
246
+ return output
247
+ }
248
+
249
+ function createErrorResponse (message) {
250
+ return {
251
+ statusCode: 500,
252
+ message
253
+ }
254
+ }
255
+
256
+ function sanitizeContentType (contentType) {
257
+ if (!contentType) {
258
+ return false
259
+ }
260
+ const split = contentType.split(';')
261
+ return split[0]
262
+ }
263
+
264
+ function checkResponseAgainstSchema (body, schema, ajv) {
265
+ const validate = getValidateFunction(schema, ajv)
266
+ const valid = validate(body)
267
+ return valid
268
+ }
269
+
270
+ function getValidateFunction (schema, ajvInstance) {
271
+ const hash = createHash('md5').update(JSON.stringify(schema)).digest('hex')
272
+ if (!validateFunctionCache[hash]) {
273
+ validateFunctionCache[hash] = ajvInstance.compile(schema)
274
+ }
275
+ return validateFunctionCache[hash]
276
+ }
277
+
278
+ function capitalize (str) {
279
+ return str.charAt(0).toUpperCase() + str.slice(1)
280
+ }
281
+
282
+ function isArrayQueryParam ({ schema }) {
283
+ return schema?.type === 'array' || schema?.anyOf?.some(({ type }) => type === 'array')
284
+ }
285
+
286
+ // TODO: For some unknown reason c8 is not picking up the coverage for this function
287
+ async function graphql (url, log, headers, query, variables, openTelemetry, telemetryContext) {
288
+ const { span, telemetryHeaders } = openTelemetry?.startHTTPSpanClient(url.toString(), 'POST', telemetryContext) || {
289
+ span: null,
290
+ telemetryHeaders: {}
291
+ }
292
+
293
+ headers = {
294
+ ...headers,
295
+ ...telemetryHeaders,
296
+ 'content-type': 'application/json; charset=utf-8'
297
+ }
298
+
299
+ let res
300
+ try {
301
+ res = await request(url, {
302
+ method: 'POST',
303
+ headers,
304
+ body: JSON.stringify({
305
+ query,
306
+ variables
307
+ })
308
+ })
309
+
310
+ const json = await res.body.json()
311
+
312
+ if (res.statusCode !== 200) {
313
+ log.warn({ statusCode: res.statusCode, json }, 'request to client failed')
314
+ throw new Error('request to client failed')
315
+ }
316
+
317
+ if (json.errors) {
318
+ log.warn({ errors: json.errors }, 'errors in graphql response')
319
+ const e = new Error(json.errors.map(e => e.message).join(''))
320
+ e.errors = json.errors
321
+ throw e
322
+ }
323
+
324
+ const keys = Object.keys(json.data)
325
+ if (keys.length !== 1) {
326
+ return json.data
327
+ } else {
328
+ return json.data[keys[0]]
329
+ }
330
+ } catch (err) {
331
+ openTelemetry?.setErrorInSpanClient(span, err)
332
+ throw err
333
+ } finally {
334
+ openTelemetry?.endHTTPSpanClient(span, res)
335
+ }
336
+ }
337
+
338
+ function wrapGraphQLClient (url, openTelemetry, logger) {
339
+ return async function ({ query, variables }) {
340
+ let headers = this[kHeaders]
341
+ const telemetryContext = this[kTelemetryContext]
342
+ if (typeof this[kGetHeaders] === 'function') {
343
+ headers = { ...headers, ...(await this[kGetHeaders]()) }
344
+ }
345
+ const log = this.log || logger
346
+
347
+ return graphql(url, log, headers, query, variables, openTelemetry, telemetryContext)
348
+ }
349
+ }
350
+
351
+ export function generateOperationId (path, method, methodMeta, all) {
352
+ let operationId = null
353
+ // use methodMeta.operationId only if it's present AND it is a valid string that can be
354
+ // concatenated without converting it
355
+ // i.e
356
+ // operationId = "MyOperationId123" is valid
357
+ // operationId = "/v3/accounts/{id}" is NOT valid and sholuld be converted in "V3AccountsId"
358
+ if (methodMeta.operationId && methodMeta.operationId.match(/^[a-zA-z0-9]+$/)) {
359
+ operationId = methodMeta.operationId
360
+ }
361
+ if (!operationId) {
362
+ const pathParams = methodMeta.parameters?.filter(p => p.in === 'path') || []
363
+ let stringToUpdate = path
364
+ for (const param of pathParams) {
365
+ stringToUpdate = stringToUpdate.replace(`{${param.name}}`, capitalize(param.name))
366
+ }
367
+ operationId =
368
+ method.toLowerCase() +
369
+ stringToUpdate
370
+ .split(/[/-]+/)
371
+ .map(token => {
372
+ const sanitized = token.replace(/[^a-zA-z0-9]/g, '')
373
+ return capitalize(sanitized)
374
+ })
375
+ .join('')
376
+ } else {
377
+ let count = 0
378
+ let candidate = operationId
379
+ while (all.includes(candidate)) {
380
+ if (count === 0) {
381
+ // first try with method name
382
+ candidate = `${method}${capitalize(operationId)}`
383
+ } else {
384
+ candidate = `${method}${capitalize(operationId)}${count}`
385
+ }
386
+ count++
387
+ }
388
+ operationId = candidate
389
+ }
390
+ operationId = camelCase(operationId)
391
+ all.push(operationId)
392
+ return operationId
393
+ }
394
+
395
+ export async function buildOpenAPIClient (options, openTelemetry) {
396
+ const client = {}
397
+ let spec
398
+ let baseUrl
399
+
400
+ if (typeof options.getHeaders === 'function') {
401
+ const getHeaders = options.getHeaders
402
+ options = { ...options }
403
+ client[kGetHeaders] = getHeaders
404
+ options.getHeaders = undefined
405
+ }
406
+
407
+ const { validateResponse, queryParser } = options
408
+
409
+ // this is tested, not sure why c8 is not picking it up
410
+ if (!options.url) {
411
+ throw new errors.OptionsUrlRequiredError()
412
+ }
413
+ if (options.path) {
414
+ spec = JSON.parse(await fs.readFile(options.path, 'utf8'))
415
+ baseUrl = options.url.replace(/\/$/, '')
416
+ } else {
417
+ const res = await request(options.url)
418
+ spec = await res.body.json()
419
+ baseUrl = computeURLWithoutPath(options.url)
420
+ }
421
+
422
+ const kOperationIdMap = Symbol.for('plt.operationIdMap')
423
+ client[kOperationIdMap] = {}
424
+ client[kHeaders] = options.headers || {}
425
+
426
+ let { fullRequest = true, fullResponse = true, bodyTimeout, headersTimeout, dispatcher } = options
427
+
428
+ if (options.throwOnError) {
429
+ if (!dispatcher) {
430
+ dispatcher = getGlobalDispatcher()
431
+ }
432
+ dispatcher = dispatcher.compose(interceptors.responseError())
433
+ }
434
+
435
+ const generatedOperationIds = []
436
+ for (const path of Object.keys(spec.paths)) {
437
+ const pathMeta = spec.paths[path]
438
+ let commonParameters = []
439
+ if (pathMeta.parameters) {
440
+ commonParameters = pathMeta.parameters
441
+ delete pathMeta.parameters
442
+ }
443
+ for (const method of Object.keys(pathMeta)) {
444
+ const methodMeta = pathMeta[method]
445
+ if (methodMeta.parameters) {
446
+ methodMeta.parameters = [...methodMeta.parameters, ...commonParameters]
447
+ } else {
448
+ methodMeta.parameters = commonParameters
449
+ }
450
+ const operationId = generateOperationId(path, method, methodMeta, generatedOperationIds)
451
+ const responses = pathMeta[method].responses
452
+ const successResponses = Object.entries(responses).filter(([s]) => s.startsWith('2'))
453
+ if (successResponses.length !== 1) {
454
+ // force fullResponse = true if
455
+ // - there is more than 1 responses with 2XX code
456
+ // - there is no responses with 2XX code
457
+ fullResponse = true
458
+ }
459
+
460
+ client[kOperationIdMap][operationId] = { path, method }
461
+ client[operationId] = await buildCallFunction(
462
+ spec,
463
+ baseUrl,
464
+ path,
465
+ method,
466
+ methodMeta,
467
+ openTelemetry,
468
+ fullRequest,
469
+ fullResponse,
470
+ validateResponse,
471
+ queryParser,
472
+ bodyTimeout,
473
+ headersTimeout,
474
+ dispatcher
475
+ )
476
+ }
477
+ }
478
+ return client
479
+ }
480
+
481
+ export function hasDuplicatedParameters (methodMeta) {
482
+ if (!methodMeta.parameters) return false
483
+ if (methodMeta.parameters.length === 0) {
484
+ return false
485
+ }
486
+ const s = new Set()
487
+ methodMeta.parameters.forEach(param => {
488
+ s.add(param.name)
489
+ })
490
+ return s.size !== methodMeta.parameters.length
491
+ }
492
+
493
+ export async function buildGraphQLClient (options, openTelemetry, logger = abstractLogger) {
494
+ options = options || {}
495
+ if (!options.url) {
496
+ throw new Error('options.url is required')
497
+ }
498
+
499
+ return {
500
+ graphql: wrapGraphQLClient(options.url, openTelemetry, logger),
501
+ [kHeaders]: options.headers || {}
502
+ }
503
+ }
504
+
505
+ export * as errors from './lib/errors.js'
@@ -0,0 +1,158 @@
1
+ import { FastifyError } from '@fastify/error'
2
+ import fastify from 'fastify'
3
+ import { expectAssignable, expectError, expectNotAssignable, expectType } from 'tsd'
4
+ import { Agent } from 'undici'
5
+ import {
6
+ buildOpenAPIClient,
7
+ errors,
8
+ type GetHeadersOptions,
9
+ type StatusCode1xx,
10
+ type StatusCode2xx,
11
+ type StatusCode3xx,
12
+ type StatusCode4xx,
13
+ type StatusCode5xx
14
+ } from '.'
15
+ import pltClient, { type PlatformaticClientPluginOptions } from './fastify-plugin.js'
16
+
17
+ const server = await fastify()
18
+
19
+ expectError<PlatformaticClientPluginOptions>({})
20
+
21
+ expectError<PlatformaticClientPluginOptions>({
22
+ fullRequest: true,
23
+ fullResponse: true,
24
+ throwOnError: true,
25
+ url: 'localhost'
26
+ })
27
+
28
+ expectError<PlatformaticClientPluginOptions>({
29
+ fullRequest: true,
30
+ fullResponse: true,
31
+ throwOnError: true,
32
+ type: 'WRONG',
33
+ url: 'localhost'
34
+ })
35
+
36
+ server.register(pltClient, {
37
+ fullRequest: true,
38
+ fullResponse: true,
39
+ throwOnError: true,
40
+ type: 'graphql',
41
+ url: 'localhost'
42
+ })
43
+
44
+ server.register(pltClient, {
45
+ fullRequest: false,
46
+ fullResponse: false,
47
+ validateResponse: false,
48
+ throwOnError: false,
49
+ type: 'openapi',
50
+ url: 'http://127.0.0.1/path/42',
51
+ getHeaders: async ({ url }, { sent }, options) => ({
52
+ foo: 'bar',
53
+ url,
54
+ baz: sent.toString(),
55
+ opt: JSON.stringify(options)
56
+ }),
57
+ headers: { foo: 'bar' },
58
+ name: 'Frassica',
59
+ path: 'Fracchia',
60
+ applicationId: 'Fantozzi'
61
+ })
62
+
63
+ const key = Symbol.for('plt.operationIdMap')
64
+ type MyType = {
65
+ getFoo: Function
66
+ } & Record<typeof key, { path: string; method: string }>
67
+
68
+ const dispatcher = new Agent({ allowH2: true, connections: 10 })
69
+ const openTelemetry = {}
70
+ const client = await buildOpenAPIClient<MyType>(
71
+ {
72
+ url: 'http://foo.bar',
73
+ path: 'foobar',
74
+ fullRequest: true,
75
+ fullResponse: false,
76
+ throwOnError: false,
77
+ validateResponse: false,
78
+ headers: { foo: 'bar' },
79
+ bodyTimeout: 900000,
80
+ headersTimeout: 900000,
81
+ getHeaders: async (options: GetHeadersOptions) => {
82
+ const { url } = options
83
+ return { href: url.href }
84
+ },
85
+ queryParser: query => `${query.toString()}[]`,
86
+ dispatcher
87
+ },
88
+ openTelemetry
89
+ )
90
+
91
+ const isSuccessfulResponse = (status: number): status is StatusCode2xx => status >= 200 && status <= 299
92
+
93
+ async function _exampleUsageOfStatusCodeType (status: number) {
94
+ if (isSuccessfulResponse(status)) {
95
+ expectType<StatusCode2xx>(status)
96
+ } else {
97
+ expectError<StatusCode2xx>(status)
98
+ }
99
+ }
100
+
101
+ expectNotAssignable<StatusCode1xx>(99)
102
+ expectAssignable<StatusCode1xx>(100)
103
+ expectAssignable<StatusCode1xx>(101)
104
+ expectAssignable<StatusCode1xx>(150)
105
+ expectAssignable<StatusCode1xx>(199)
106
+ expectNotAssignable<StatusCode1xx>(200)
107
+
108
+ expectNotAssignable<StatusCode2xx>(199)
109
+ expectAssignable<StatusCode2xx>(200)
110
+ expectAssignable<StatusCode2xx>(201)
111
+ expectAssignable<StatusCode2xx>(250)
112
+ expectAssignable<StatusCode2xx>(299)
113
+ expectNotAssignable<StatusCode2xx>(300)
114
+
115
+ expectNotAssignable<StatusCode3xx>(299)
116
+ expectAssignable<StatusCode3xx>(300)
117
+ expectAssignable<StatusCode3xx>(301)
118
+ expectAssignable<StatusCode3xx>(350)
119
+ expectAssignable<StatusCode3xx>(399)
120
+ expectNotAssignable<StatusCode3xx>(400)
121
+
122
+ expectNotAssignable<StatusCode4xx>(399)
123
+ expectAssignable<StatusCode4xx>(400)
124
+ expectAssignable<StatusCode4xx>(401)
125
+ expectAssignable<StatusCode4xx>(450)
126
+ expectAssignable<StatusCode4xx>(499)
127
+ expectNotAssignable<StatusCode4xx>(500)
128
+
129
+ expectNotAssignable<StatusCode5xx>(399)
130
+ expectAssignable<StatusCode5xx>(500)
131
+ expectAssignable<StatusCode5xx>(501)
132
+ expectAssignable<StatusCode5xx>(550)
133
+ expectAssignable<StatusCode5xx>(599)
134
+ expectNotAssignable<StatusCode5xx>(600)
135
+
136
+ // All params and generic passed
137
+ expectType<MyType>(client)
138
+ expectType<Function>(client.getFoo)
139
+ expectType<{ path: string; method: string }>(client[key])
140
+
141
+ // Only required params and no generics
142
+ expectType<Promise<unknown>>(
143
+ buildOpenAPIClient({
144
+ url: 'https://undici.com/piscina',
145
+ fullRequest: true,
146
+ fullResponse: false,
147
+ throwOnError: false
148
+ })
149
+ )
150
+
151
+ expectType<() => FastifyError>(errors.OptionsUrlRequiredError)
152
+ expectType<(_: string) => FastifyError>(errors.FormDataRequiredError)
153
+ expectType<(_: string) => FastifyError>(errors.MissingParamsRequiredError)
154
+ expectType<() => FastifyError>(errors.WrongOptsTypeError)
155
+ expectType<(_: string) => FastifyError>(errors.InvalidResponseSchemaError)
156
+ expectType<(_: string) => FastifyError>(errors.InvalidContentTypeError)
157
+ expectType<() => FastifyError>(errors.InvalidResponseFormatError)
158
+ expectType<(_: string) => FastifyError>(errors.UnexpectedCallFailureError)
package/lib/errors.js ADDED
@@ -0,0 +1,33 @@
1
+ import createError from '@fastify/error'
2
+
3
+ export const ERROR_PREFIX = 'PLT_MASSIMO'
4
+
5
+ export const OptionsUrlRequiredError = createError(`${ERROR_PREFIX}_OPTIONS_URL_REQUIRED`, 'options.url is required')
6
+ export const FormDataRequiredError = createError(
7
+ `${ERROR_PREFIX}_FORM_DATA_REQUIRED`,
8
+ 'Operation %s should be called with a undici.FormData as payload'
9
+ )
10
+ export const MissingParamsRequiredError = createError(
11
+ `${ERROR_PREFIX}_MISSING_PARAMS_REQUIRED`,
12
+ "Param %s is missing, and it's required"
13
+ )
14
+ export const WrongOptsTypeError = createError(
15
+ `${ERROR_PREFIX}_WRONG_OPTS_TYPE`,
16
+ 'opts.type must be either "openapi" or "graphql"'
17
+ )
18
+ export const InvalidResponseSchemaError = createError(
19
+ `${ERROR_PREFIX}_INVALID_RESPONSE_SCHEMA`,
20
+ 'No matching response schema found for status code %s'
21
+ )
22
+ export const InvalidContentTypeError = createError(
23
+ `${ERROR_PREFIX}_INVALID_CONTENT_TYPE`,
24
+ 'No matching content type schema found for %s'
25
+ )
26
+ export const InvalidResponseFormatError = createError(
27
+ `${ERROR_PREFIX}_INVALID_RESPONSE_FORMAT`,
28
+ 'Invalid response format'
29
+ )
30
+ export const UnexpectedCallFailureError = createError(
31
+ `${ERROR_PREFIX}_UNEXPECTED_CALL_FAILURE`,
32
+ 'Unexpected failure calling the client: %s'
33
+ )
package/lib/symbols.js ADDED
@@ -0,0 +1,3 @@
1
+ export const kHeaders = Symbol('headers')
2
+ export const kGetHeaders = Symbol('getHeaders')
3
+ export const kTelemetryContext = Symbol('telemetry-context')
package/package.json CHANGED
@@ -1,12 +1,47 @@
1
1
  {
2
2
  "name": "massimo",
3
- "version": "0.0.1",
3
+ "version": "0.1.1",
4
+ "description": "A client for HTTP services.",
4
5
  "main": "index.js",
5
- "scripts": {
6
- "test": "echo \"Error: no test specified\" && exit 1"
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/platformatic/massimo.git"
10
+ },
11
+ "author": "Platformatic Inc. <oss@platformatic.dev> (https://platformatic.dev)",
12
+ "license": "Apache-2.0",
13
+ "bugs": {
14
+ "url": "https://github.com/platformatic/massimo/issues"
15
+ },
16
+ "homepage": "https://github.com/platformatic/massimo#readme",
17
+ "devDependencies": {
18
+ "@fastify/multipart": "^9.0.1",
19
+ "@platformatic/db": "3.0.0-alpha.6",
20
+ "@platformatic/foundation": "3.0.0-alpha.6",
21
+ "@platformatic/service": "3.0.0-alpha.6",
22
+ "@platformatic/telemetry": "3.0.0-alpha.6",
23
+ "c8": "^10.0.0",
24
+ "cleaner-spec-reporter": "^0.5.0",
25
+ "eslint": "9",
26
+ "execa": "^9.0.0",
27
+ "fastify": "^5.0.0",
28
+ "neostandard": "^0.12.0",
29
+ "tsd": "^0.32.0",
30
+ "typescript": "^5.4.2"
7
31
  },
8
- "keywords": [],
9
- "author": "Matteo Collina <hello@matteocollina.com>",
10
- "license": "MIT",
11
- "description": ""
12
- }
32
+ "dependencies": {
33
+ "@apidevtools/json-schema-ref-parser": "^11.5.4",
34
+ "@fastify/error": "^4.0.0",
35
+ "ajv": "^8.12.0",
36
+ "camelcase": "^6.3.0",
37
+ "undici": "^7.0.0"
38
+ },
39
+ "engines": {
40
+ "node": ">=22.18.0"
41
+ },
42
+ "scripts": {
43
+ "lint": "eslint",
44
+ "test": "node --test --test-reporter=cleaner-spec-reporter --test-concurrency=1 --test-timeout=2000000 test/*.test.js test/**/*.test.js",
45
+ "posttest": "tsd"
46
+ }
47
+ }