• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

supabase / storage / 30381503940

28 Jul 2026 05:07PM UTC coverage: 59.291% (-21.0%) from 80.307%
30381503940

Pull #1270

github

web-flow
Merge fa9a4947b into 20927735c
Pull Request #1270: fix(storage): document 200 responses for vector bucket CRUD endpoints

3677 of 7083 branches covered (51.91%)

Branch coverage included in aggregate %.

9 of 55 new or added lines in 3 files covered. (16.36%)

2445 existing lines in 105 files now uncovered.

7666 of 12048 relevant lines covered (63.63%)

363.67 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

3.33
/src/http/routes/openapi-transform.ts
1
import { SwaggerTransformObject } from '@fastify/swagger'
2
import { FastifySchema, RouteOptions } from 'fastify'
3
import { ROUTE_OPERATIONS } from './operations'
4

5
/**
6
 * @fastify/swagger names every de-duplicated component schema `def-0`, `def-1`, ... by
7
 * default, even for schemas registered with a meaningful `$id` (bucketSchema, errorSchema).
8
 * Use the `$id` as the component name instead, falling back to the default `def-N` for
9
 * anonymous schemas so unrelated inline schemas don't collide.
10
 */
11
export function nameSchemaByDollarId(
12
  json: { $id?: string },
13
  _baseUri: unknown,
14
  _fragment: unknown,
15
  i: number
16
) {
NEW
17
  return json.$id || `def-${i}`
×
18
}
19

20
const WILDCARD_PARAM = '*'
19✔
21
const WILDCARD_DOC_NAME = 'wildcard'
19✔
22

23
/**
24
 * Fastify's catch-all route segment is `*`, and its request params are keyed by the
25
 * literal `*` character (`request.params['*']`). @fastify/swagger mirrors that straight
26
 * into the OpenAPI doc as a path template `{*}` with a parameter named `*`, which isn't a
27
 * legal parameter/identifier name for any code generator. Rewrite it to a readable name for
28
 * docs only - the raw url string returned here still goes through Fastify's own `:name`
29
 * path-param formatting, and `route.schema` (the live validation schema) is never mutated.
30
 */
31
function renameWildcardParam(
32
  schema: FastifySchema,
33
  url: string
34
): { schema: FastifySchema; url: string } {
NEW
35
  if (!url.split('/').includes(WILDCARD_PARAM)) {
×
NEW
36
    return { schema, url }
×
37
  }
38

NEW
39
  const renamedUrl = url
×
40
    .split('/')
NEW
41
    .map((segment) => (segment === WILDCARD_PARAM ? `:${WILDCARD_DOC_NAME}` : segment))
×
42
    .join('/')
43

NEW
44
  const params = schema.params as
×
45
    | { properties?: Record<string, unknown>; required?: string[] }
46
    | undefined
NEW
47
  if (!params?.properties?.[WILDCARD_PARAM]) {
×
NEW
48
    return { schema, url: renamedUrl }
×
49
  }
50

NEW
51
  const { [WILDCARD_PARAM]: wildcardProperty, ...otherProperties } = params.properties
×
NEW
52
  const renamedParams = {
×
53
    ...params,
54
    properties: { ...otherProperties, [WILDCARD_DOC_NAME]: wildcardProperty },
NEW
55
    required: params.required?.map((name) => (name === WILDCARD_PARAM ? WILDCARD_DOC_NAME : name)),
×
56
  }
57

NEW
58
  return { schema: { ...schema, params: renamedParams }, url: renamedUrl }
×
59
}
60

61
/**
62
 * The S3-compatible surface dispatches ~18 real commands (PutObject, ListObjects,
63
 * CreateMultipartUpload, ...) from a handful of generic Fastify routes based on query
64
 * string/header matching done entirely inside the internal `s3/router.ts` Router - see
65
 * `s3/index.ts`. Fastify (and therefore @fastify/swagger) only ever sees the outer
66
 * catch-all route with no request/response schema, since OpenAPI has no way to express
67
 * "N distinct operations, same path and method, picked by a query parameter". Documenting
68
 * that catch-all as-is would give SDK generators a single method with an untyped body and
69
 * an untyped response for a request that's actually the whole S3 API - worse than nothing.
70
 * Hide it instead; the real per-command schemas remain the source of truth in s3/commands/*.
71
 */
72
function isS3ProtocolCatchAll(schema: FastifySchema | undefined, route: RouteOptions): boolean {
NEW
73
  const operation = (route.config as { operation?: string } | undefined)?.operation
×
NEW
74
  return (schema?.tags?.includes('s3') ?? false) && !operation
×
75
}
76

77
/**
78
 * Derives a stable, unique operationId from the route's `config.operation`
79
 * (see ROUTE_OPERATIONS in ./operations.ts), e.g. `storage.object.get_public` -> `objectGetPublic`.
80
 * Routes without a `config.operation` (protocol-level catch-alls like /s3 and /upload/resumable)
81
 * are left without an operationId.
82
 */
83
function operationToId(operation: string): string {
NEW
84
  const parts = operation.split('.').filter((part) => part !== 'storage')
×
NEW
85
  return parts
×
86
    .map((part) =>
NEW
87
      part
×
88
        .split('_')
89
        .filter(Boolean)
NEW
90
        .map((word, i) => (i === 0 ? word : word[0].toUpperCase() + word.slice(1)))
×
91
        .join('')
92
    )
NEW
93
    .map((part, i) => (i === 0 ? part : part[0].toUpperCase() + part.slice(1)))
×
94
    .join('')
95
}
96

97
/**
98
 * Every route can end up hitting setErrorHandler and getting back a {statusCode, error,
99
 * message, code} body (or, for a subtree with its own formatter, whatever that subtree
100
 * documents instead) - default the doc to that shape for any otherwise-undocumented 4xx.
101
 * Doc-only on purpose: several handlers reply with an ad-hoc, partial error body directly
102
 * (`reply.status(400).send({message: '...'})`, bypassing the formatter entirely), and an
103
 * earlier version of this defaulted via a real onRoute hook that made Fastify enforce
104
 * errorSchema's `required` fields during response *serialization* - which threw on exactly
105
 * those ad-hoc replies (fast-json-stringify errors on a missing required property rather
106
 * than dropping it). A transform can't affect request handling, so it can't cause that.
107
 */
108
function defaultErrorResponse(schema: FastifySchema | undefined): FastifySchema {
NEW
109
  const response = schema?.response as Record<string, unknown> | undefined
×
NEW
110
  if (schema && response && Object.keys(response).some((status) => /^4xx$/i.test(status))) {
×
NEW
111
    return schema
×
112
  }
113

NEW
114
  return {
×
115
    ...schema,
116
    response: {
117
      ...(response ? undefined : { 200: { description: 'Default Response' } }),
×
118
      '4xx': { description: 'Error response', $ref: 'errorSchema#' },
119
      ...response,
120
    },
121
  }
122
}
123

124
const MULTIPART_UPLOAD_OPERATIONS = new Set<string>([
19✔
125
  ROUTE_OPERATIONS.CREATE_OBJECT,
126
  ROUTE_OPERATIONS.UPDATE_OBJECT,
127
  ROUTE_OPERATIONS.UPLOAD_SIGN_OBJECT,
128
])
129

130
/**
131
 * createObject/updateObject/uploadSignedObject never set `schema.body` - they read the raw
132
 * multipart stream directly via `uploadFromRequest` -> `fileUploadFromRequest`
133
 * (see src/storage/object.ts), without registering `@fastify/multipart`'s
134
 * `attachFieldsToBody`. That means `request.body` is always `undefined` on these routes, so a
135
 * real `schema.body` would make Fastify validate that `undefined` (substituted as `null`)
136
 * against a required-fields schema on every real upload and fail it with a 400 - a production
137
 * regression, not a docs improvement. Document the multipart shape here instead, transform-only,
138
 * where - like `defaultErrorResponse` above - it can never reach live request validation.
139
 */
140
function documentMultipartUploadBody(schema: FastifySchema, route: RouteOptions): FastifySchema {
NEW
141
  const operation = (route.config as { operation?: string } | undefined)?.operation
×
NEW
142
  if (!operation || !MULTIPART_UPLOAD_OPERATIONS.has(operation)) {
×
NEW
143
    return schema
×
144
  }
145

NEW
146
  return {
×
147
    ...schema,
148
    consumes: ['multipart/form-data'],
149
    body: {
150
      type: 'object',
151
      properties: {
152
        cacheControl: { type: 'string', description: "Defaults to 'no-cache' if not set." },
153
        metadata: {
154
          type: 'string',
155
          description: 'JSON-encoded custom metadata. Alias: userMetadata.',
156
        },
157
        userMetadata: { type: 'string', description: 'Alias for metadata.' },
158
        contentType: { type: 'string', description: 'Overrides the auto-detected mime type.' },
159
        file: { type: 'string', format: 'binary' },
160
      },
161
      required: ['file'],
162
    },
163
  }
164
}
165

166
/**
167
 * OpenAPI requires operationId to be unique across the whole document. A route can set
168
 * `config.operationId` to pin its id explicitly (takes precedence over the derived
169
 * `config.operation` id) - do this for any route whose id must stay stable regardless of
170
 * where it's registered, since generated SDK method names key off of it.
171
 * `exposeHeadRoutes` auto-derives a HEAD operation from every GET route re-using the same
172
 * `config.operation`/`config.operationId` - give that specific, deterministic case a `Head`
173
 * suffix. Any other collision (two distinct routes resolving to the same id) is a mistake,
174
 * not something to paper over with a registration-order-dependent suffix - it fails loudly
175
 * so it gets fixed via an explicit `config.operationId` instead.
176
 * Returns a fresh transform bound to its own dedup state, so main/admin specs don't
177
 * leak collisions into each other when generated in the same process (see export-docs.ts).
178
 */
179
export function createOpenApiTransform() {
NEW
180
  const seenIds = new Set<string>()
×
181

NEW
182
  return function transformOpenApiSchema({
×
183
    schema,
184
    url,
185
    route,
186
  }: {
187
    schema: FastifySchema
188
    url: string
189
    route: RouteOptions
190
  }): { schema: FastifySchema; url: string } {
NEW
191
    if (isS3ProtocolCatchAll(schema, route)) {
×
NEW
192
      return { schema: { ...schema, hide: true }, url }
×
193
    }
194

NEW
195
    ;({ schema, url } = renameWildcardParam(schema, url))
×
NEW
196
    schema = defaultErrorResponse(schema)
×
NEW
197
    schema = documentMultipartUploadBody(schema, route)
×
198

199
    const baseId =
NEW
200
      route.config?.operationId ??
×
201
      (route.config?.operation && operationToId(route.config.operation))
202

NEW
203
    if (!baseId || (schema as { operationId?: string }).operationId) {
×
NEW
204
      return { schema, url }
×
205
    }
206

NEW
207
    const methods = Array.isArray(route.method) ? route.method : [route.method]
×
NEW
208
    const isAutoHeadRoute = methods.length === 1 && methods[0] === 'HEAD'
×
NEW
209
    const operationId = isAutoHeadRoute ? `${baseId}Head` : baseId
×
210

NEW
211
    if (seenIds.has(operationId)) {
×
NEW
212
      throw new Error(
×
213
        `Duplicate OpenAPI operationId "${operationId}" for ${methods.join(',')} ${url} - ` +
214
          `give this route (or its ROUTE_OPERATIONS entry) a distinct config.operationId.`
215
      )
216
    }
NEW
217
    seenIds.add(operationId)
×
218

NEW
219
    return {
×
220
      schema: { ...schema, operationId },
221
      url,
222
    }
223
  }
224
}
225

226
/**
227
 * A handful of paths are reachable both with and without a trailing slash - either because
228
 * Fastify's own `exposeHeadRoutes` derives a HEAD route from the un-prefixed path (e.g.
229
 * /health vs /health/) or because a route is explicitly registered both ways (the S3
230
 * protocol surface). Both forms genuinely work at runtime, but documenting them as two
231
 * unrelated paths just doubles the number of operations a generated SDK has to deal with
232
 * for the same endpoint. Keep the slash-less form and fold the other one's methods into it.
233
 */
234
export const dedupeTrailingSlashPaths: SwaggerTransformObject = (documentObject) => {
19✔
235
  if (!('openapiObject' in documentObject)) {
×
236
    return documentObject.swaggerObject
×
237
  }
238

239
  const { openapiObject } = documentObject
×
240
  const paths = openapiObject.paths as Record<string, Record<string, unknown>> | undefined
×
241
  if (!paths) {
×
242
    return openapiObject
×
243
  }
244

245
  for (const url of Object.keys(paths)) {
×
246
    if (url === '/' || !url.endsWith('/')) {
×
247
      continue
×
248
    }
249

250
    const canonicalUrl = url.slice(0, -1)
×
251
    const canonicalPathItem = paths[canonicalUrl]
×
252
    if (!canonicalPathItem) {
×
253
      continue
×
254
    }
255

256
    for (const [method, operation] of Object.entries(paths[url])) {
×
257
      canonicalPathItem[method] ??= operation
×
258
    }
259
    delete paths[url]
×
260
  }
261

262
  return openapiObject
×
263
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc