@astro-spec/openapi 0.0.0-0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +86 -0
- package/dist/action-metadata-CVcuvF_u.mjs +11 -0
- package/dist/actions.d.mts +2 -0
- package/dist/actions.mjs +33 -0
- package/dist/artifact-route.d.mts +2 -0
- package/dist/artifact-route.mjs +1 -0
- package/dist/create-openapi-document-DoxXS2mJ.mjs +205 -0
- package/dist/index-fRyZ0DqZ.d.mts +39 -0
- package/dist/index.d.mts +305 -0
- package/dist/index.mjs +201 -0
- package/dist/route-D3knsMZ-.mjs +152 -0
- package/dist/route.d.mts +2 -0
- package/dist/route.mjs +1 -0
- package/package.json +55 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 otoneko.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# @astro-spec/openapi
|
|
2
|
+
|
|
3
|
+
> Generate and serve an OpenAPI 3.1 document for Astro Actions and API routes
|
|
4
|
+
|
|
5
|
+
Describe your [Astro Actions](https://docs.astro.build/en/guides/actions/) with OpenAPI, so mobile apps, other frontends and external services can call them. The Zod schemas you already wrote are the source of truth.
|
|
6
|
+
|
|
7
|
+
Supports Astro 4.15 to 7.x and Node.js 22.12 or newer.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install @astro-spec/openapi
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
// astro.config.mjs
|
|
19
|
+
import astroSpec from '@astro-spec/openapi'
|
|
20
|
+
import { defineConfig } from 'astro/config'
|
|
21
|
+
|
|
22
|
+
export default defineConfig({
|
|
23
|
+
integrations: [
|
|
24
|
+
astroSpec({
|
|
25
|
+
info: { title: 'My API', version: '1.0.0' },
|
|
26
|
+
exclude: ['internal.*'],
|
|
27
|
+
}),
|
|
28
|
+
],
|
|
29
|
+
})
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Run `astro dev` and open `/openapi.json`.
|
|
33
|
+
|
|
34
|
+
Every action is a `POST` operation on `/_actions/<name>`. Its input schema, `accept` type, tag and errors are filled in from your code. Actions defined with plain `defineAction` get their input schema too; nothing in `src/actions` needs to change.
|
|
35
|
+
|
|
36
|
+
To document the result type and add a summary, wrap the action with `defineSpecAction` from `@astro-spec/openapi/actions`. It takes the documentation first and then the usual `defineAction` options:
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
// src/actions/index.ts
|
|
40
|
+
import { defineSpecAction } from '@astro-spec/openapi/actions'
|
|
41
|
+
import { ActionError } from 'astro:actions'
|
|
42
|
+
import { z } from 'astro/zod' // or 'astro:schema' on Astro 4
|
|
43
|
+
|
|
44
|
+
export const server = {
|
|
45
|
+
user: {
|
|
46
|
+
get: defineSpecAction({
|
|
47
|
+
summary: 'Get a user by id',
|
|
48
|
+
output: z.object({ id: z.string(), name: z.string() }),
|
|
49
|
+
errors: ['NOT_FOUND'],
|
|
50
|
+
})({
|
|
51
|
+
input: z.object({ id: z.string() }),
|
|
52
|
+
handler: async ({ id }) => {
|
|
53
|
+
const user = await db.user.find(id)
|
|
54
|
+
if (!user) throw new ActionError({ code: 'NOT_FOUND' })
|
|
55
|
+
return user
|
|
56
|
+
},
|
|
57
|
+
}),
|
|
58
|
+
},
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Besides `summary`, `output` and `errors`, it takes `description` (Markdown), `deprecated` and `tags`. The output schema is documentation only: it is not checked against what the handler returns. Import it from `@astro-spec/openapi/actions`, not the package root: that entry has no Node.js dependencies, so actions still run on runtimes such as Cloudflare Workers.
|
|
63
|
+
|
|
64
|
+
API routes written with `defineEndpoint` from [`@astro-spec/endpoints`](../endpoints#readme) are added to the same document, after the actions.
|
|
65
|
+
|
|
66
|
+
## Options
|
|
67
|
+
|
|
68
|
+
| Option | Default | Description |
|
|
69
|
+
| --- | --- | --- |
|
|
70
|
+
| `path` | `'/openapi.json'` | Where the document is served. |
|
|
71
|
+
| `info` | `{ title: 'API', version: '1.0.0' }` | The OpenAPI `info` object. |
|
|
72
|
+
| `servers` | — | The OpenAPI `servers` array. |
|
|
73
|
+
| `exclude` | `[]` | Action names and endpoint paths to leave out. `*` matches any characters, so `internal.*` excludes every action under `internal` and `/api/internal/*` every endpoint under that path. |
|
|
74
|
+
| `production` | `false` | Whether the built site serves the document: `false`, `'prerender'` (a static file written at build time) or `'runtime'` (generated per request; needs an adapter). `astro dev` always serves it. |
|
|
75
|
+
| `outputFile` | — | A path relative to the project root to write the document to on `astro build`, for example to commit it or compare it in CI. It is written outside `dist`, so it is not deployed. In `astro dev`, `path` still serves the live document, even when this file sits at the same path in the project root. |
|
|
76
|
+
|
|
77
|
+
## Calling actions from outside Astro
|
|
78
|
+
|
|
79
|
+
- Send JSON for actions with the default `accept: 'json'`, and `multipart/form-data` or `application/x-www-form-urlencoded` for `accept: 'form'`.
|
|
80
|
+
- Successful responses are serialized with [devalue](https://github.com/sveltejs/devalue) and use the `application/json+devalue` media type, so dates, sets and maps survive the trip. Decode them with `devalue.parse`. The schema in the document describes the decoded value.
|
|
81
|
+
- Errors are plain JSON, described by the `ActionError` and `ActionInputError` schemas.
|
|
82
|
+
- Astro 5 and 6 reject form submissions without a matching `Origin` header unless `security.checkOrigin` is turned off.
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
[MIT](https://github.com/betterlib/astro-spec/blob/main/LICENSE)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// ../core/src/action-metadata.ts
|
|
2
|
+
/**
|
|
3
|
+
* The key under which an action carries its astro-spec metadata.
|
|
4
|
+
*
|
|
5
|
+
* It comes from the global symbol registry because the Vite plugin attaches metadata from
|
|
6
|
+
* generated code that cannot import this module.
|
|
7
|
+
*/
|
|
8
|
+
const ACTION_METADATA = Symbol.for("astro-spec.action");
|
|
9
|
+
const attachActionMetadata = (action, metadata) => Object.assign(action, { [ACTION_METADATA]: metadata });
|
|
10
|
+
const readActionMetadata = (action) => action[ACTION_METADATA];
|
|
11
|
+
export { readActionMetadata as n, attachActionMetadata as t };
|
package/dist/actions.mjs
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { defineAction } from "astro:actions";
|
|
2
|
+
import { t as attachActionMetadata } from "./action-metadata-CVcuvF_u.mjs";
|
|
3
|
+
// ../core/src/define-spec-action.ts
|
|
4
|
+
/**
|
|
5
|
+
* Documents an action for the OpenAPI document and returns Astro's own `defineAction`, so the
|
|
6
|
+
* action is typed and behaves exactly as without astro-spec.
|
|
7
|
+
*
|
|
8
|
+
* The input schema and `accept` are read from the `defineAction` options. The output schema is
|
|
9
|
+
* not checked against the handler's return type.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { defineSpecAction } from '@astro-spec/openapi/actions'
|
|
14
|
+
* import { z } from 'astro/zod'
|
|
15
|
+
*
|
|
16
|
+
* export const server = {
|
|
17
|
+
* getUser: defineSpecAction({
|
|
18
|
+
* summary: 'Get a user by id',
|
|
19
|
+
* output: z.object({ id: z.string(), name: z.string() }),
|
|
20
|
+
* errors: ['NOT_FOUND'],
|
|
21
|
+
* })({
|
|
22
|
+
* input: z.object({ id: z.string() }),
|
|
23
|
+
* handler: async ({ id }) => db.user.find(id),
|
|
24
|
+
* }),
|
|
25
|
+
* }
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
const defineSpecAction = (details) => ((options) => attachActionMetadata(defineAction(options), {
|
|
29
|
+
...details,
|
|
30
|
+
accept: options.accept,
|
|
31
|
+
input: options.input
|
|
32
|
+
}));
|
|
33
|
+
export { defineSpecAction };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as GET } from "./route-D3knsMZ-.mjs";
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// src/matches-action-pattern.ts
|
|
2
|
+
/**
|
|
3
|
+
* Matches an action name such as `internal.users.list` against a pattern where `*` stands for
|
|
4
|
+
* any run of characters, dots included, so `internal.*` matches every nested action.
|
|
5
|
+
*/
|
|
6
|
+
const matchesActionPattern = (name, pattern) => {
|
|
7
|
+
const source = pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
8
|
+
return new RegExp(`^${source}$`).test(name);
|
|
9
|
+
};
|
|
10
|
+
// src/create-openapi-document.ts
|
|
11
|
+
const ACTION_ERROR_REF = { $ref: "#/components/schemas/ActionError" };
|
|
12
|
+
const ACTION_INPUT_ERROR_REF = { $ref: "#/components/schemas/ActionInputError" };
|
|
13
|
+
const ENDPOINT_INPUT_ERROR_REF = { $ref: "#/components/schemas/EndpointInputError" };
|
|
14
|
+
const components = { schemas: {
|
|
15
|
+
ActionError: {
|
|
16
|
+
type: "object",
|
|
17
|
+
properties: {
|
|
18
|
+
type: { const: "AstroActionError" },
|
|
19
|
+
code: { type: "string" },
|
|
20
|
+
status: { type: "integer" },
|
|
21
|
+
message: { type: "string" }
|
|
22
|
+
},
|
|
23
|
+
required: [
|
|
24
|
+
"type",
|
|
25
|
+
"code",
|
|
26
|
+
"status"
|
|
27
|
+
]
|
|
28
|
+
},
|
|
29
|
+
ActionInputError: {
|
|
30
|
+
type: "object",
|
|
31
|
+
properties: {
|
|
32
|
+
type: { const: "AstroActionInputError" },
|
|
33
|
+
issues: {
|
|
34
|
+
type: "array",
|
|
35
|
+
items: { type: "object" }
|
|
36
|
+
},
|
|
37
|
+
fields: {
|
|
38
|
+
type: "object",
|
|
39
|
+
additionalProperties: {
|
|
40
|
+
type: "array",
|
|
41
|
+
items: { type: "string" }
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
required: [
|
|
46
|
+
"type",
|
|
47
|
+
"issues",
|
|
48
|
+
"fields"
|
|
49
|
+
]
|
|
50
|
+
},
|
|
51
|
+
EndpointInputError: {
|
|
52
|
+
type: "object",
|
|
53
|
+
properties: {
|
|
54
|
+
type: { const: "EndpointInputError" },
|
|
55
|
+
in: { enum: [
|
|
56
|
+
"params",
|
|
57
|
+
"query",
|
|
58
|
+
"body"
|
|
59
|
+
] },
|
|
60
|
+
issues: {
|
|
61
|
+
type: "array",
|
|
62
|
+
items: { type: "object" }
|
|
63
|
+
},
|
|
64
|
+
fields: {
|
|
65
|
+
type: "object",
|
|
66
|
+
additionalProperties: {
|
|
67
|
+
type: "array",
|
|
68
|
+
items: { type: "string" }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
required: [
|
|
73
|
+
"type",
|
|
74
|
+
"in",
|
|
75
|
+
"issues",
|
|
76
|
+
"fields"
|
|
77
|
+
]
|
|
78
|
+
}
|
|
79
|
+
} };
|
|
80
|
+
const withBase = (path, { base, trailingSlash }, hasExtension = false) => {
|
|
81
|
+
const slash = trailingSlash === "always" && !path.endsWith("/") && !hasExtension;
|
|
82
|
+
return `${base.replace(/\/$/, "")}${path}${slash ? "/" : ""}`;
|
|
83
|
+
};
|
|
84
|
+
const actionPath = (name, options) => withBase(`/_actions/${name}`, options);
|
|
85
|
+
const isExcluded = (nameOrPath, { exclude }) => exclude.some((pattern) => matchesActionPattern(nameOrPath, pattern));
|
|
86
|
+
const formMedia = (schema) => ({
|
|
87
|
+
"multipart/form-data": { schema },
|
|
88
|
+
"application/x-www-form-urlencoded": { schema }
|
|
89
|
+
});
|
|
90
|
+
const requestBody = ({ accept, input }) => {
|
|
91
|
+
if (accept === "form") return {
|
|
92
|
+
required: true,
|
|
93
|
+
content: formMedia(input ?? { type: "object" })
|
|
94
|
+
};
|
|
95
|
+
return input && {
|
|
96
|
+
required: true,
|
|
97
|
+
content: { "application/json": { schema: input } }
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
const errorResponses = (errors) => {
|
|
101
|
+
const codesByStatus = Map.groupBy(errors, ({ status }) => status);
|
|
102
|
+
return Object.fromEntries(Array.from(codesByStatus, ([status, entries]) => {
|
|
103
|
+
const codes = [...new Set(entries.map(({ code }) => code))];
|
|
104
|
+
return [String(status), {
|
|
105
|
+
description: codes.join(", "),
|
|
106
|
+
content: { "application/json": { schema: { allOf: [ACTION_ERROR_REF, { properties: { code: { enum: codes } } }] } } }
|
|
107
|
+
}];
|
|
108
|
+
}));
|
|
109
|
+
};
|
|
110
|
+
const operation = (spec) => ({
|
|
111
|
+
operationId: spec.name,
|
|
112
|
+
summary: spec.summary,
|
|
113
|
+
description: spec.description,
|
|
114
|
+
deprecated: spec.deprecated || void 0,
|
|
115
|
+
tags: spec.tags ?? (spec.name.includes(".") ? [spec.name.split(".")[0]] : void 0),
|
|
116
|
+
requestBody: requestBody(spec),
|
|
117
|
+
responses: {
|
|
118
|
+
"200": {
|
|
119
|
+
description: "The value the action returned, serialized with devalue.",
|
|
120
|
+
content: { "application/json+devalue": { schema: spec.output ?? {} } }
|
|
121
|
+
},
|
|
122
|
+
...spec.input && { "400": {
|
|
123
|
+
description: "The input did not match the schema.",
|
|
124
|
+
content: { "application/json": { schema: ACTION_INPUT_ERROR_REF } }
|
|
125
|
+
} },
|
|
126
|
+
...errorResponses(spec.errors),
|
|
127
|
+
default: {
|
|
128
|
+
description: "An error the action did not declare.",
|
|
129
|
+
content: { "application/json": { schema: ACTION_ERROR_REF } }
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
const endpointParameters = ({ path, params, query }) => {
|
|
134
|
+
const paramsSchema = params;
|
|
135
|
+
const querySchema = query;
|
|
136
|
+
const pathParameters = Array.from(path.matchAll(/\{([^}]+)\}/g), ([, name]) => ({
|
|
137
|
+
name,
|
|
138
|
+
in: "path",
|
|
139
|
+
required: true,
|
|
140
|
+
schema: paramsSchema?.properties?.[name] ?? { type: "string" }
|
|
141
|
+
}));
|
|
142
|
+
const queryParameters = Object.entries(querySchema?.properties ?? {}).map(([name, schema]) => ({
|
|
143
|
+
name,
|
|
144
|
+
in: "query",
|
|
145
|
+
required: querySchema?.required?.includes(name) || void 0,
|
|
146
|
+
schema
|
|
147
|
+
}));
|
|
148
|
+
const parameters = [...pathParameters, ...queryParameters];
|
|
149
|
+
return parameters.length > 0 ? parameters : void 0;
|
|
150
|
+
};
|
|
151
|
+
const endpointOperation = (spec) => ({
|
|
152
|
+
operationId: spec.operationId,
|
|
153
|
+
summary: spec.summary,
|
|
154
|
+
description: spec.description,
|
|
155
|
+
deprecated: spec.deprecated || void 0,
|
|
156
|
+
tags: spec.tags,
|
|
157
|
+
parameters: endpointParameters(spec),
|
|
158
|
+
requestBody: spec.input && {
|
|
159
|
+
required: true,
|
|
160
|
+
content: spec.accept === "form" ? formMedia(spec.input) : { "application/json": { schema: spec.input } }
|
|
161
|
+
},
|
|
162
|
+
responses: {
|
|
163
|
+
"200": {
|
|
164
|
+
description: "The value the handler returned.",
|
|
165
|
+
...spec.output && { content: { "application/json": { schema: spec.output } } }
|
|
166
|
+
},
|
|
167
|
+
...(spec.params || spec.query || spec.input) && { "400": {
|
|
168
|
+
description: "The params, query or body did not match the schema.",
|
|
169
|
+
content: { "application/json": { schema: ENDPOINT_INPUT_ERROR_REF } }
|
|
170
|
+
} },
|
|
171
|
+
...Object.fromEntries(spec.errors.map(({ status, description }) => [String(status), { description }]))
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
const endpointPaths = (specs, options) => {
|
|
175
|
+
const paths = {};
|
|
176
|
+
for (const spec of specs) {
|
|
177
|
+
if (isExcluded(spec.path, options)) continue;
|
|
178
|
+
const hasExtension = spec.path.split("/").at(-1)?.includes(".") ?? false;
|
|
179
|
+
const path = withBase(spec.path, options, hasExtension);
|
|
180
|
+
paths[path] = {
|
|
181
|
+
...paths[path],
|
|
182
|
+
[spec.method.toLowerCase()]: endpointOperation(spec)
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
return paths;
|
|
186
|
+
};
|
|
187
|
+
const withoutUndefined = (value) => JSON.parse(JSON.stringify(value));
|
|
188
|
+
/**
|
|
189
|
+
* Builds an OpenAPI 3.1 document in which every action is a `POST` operation on its
|
|
190
|
+
* `/_actions/<name>` URL, followed by the endpoints made with `defineEndpoint`.
|
|
191
|
+
*
|
|
192
|
+
* Successful action responses use the `application/json+devalue` media type, because Astro
|
|
193
|
+
* serializes action results with devalue; the schema describes the value after decoding.
|
|
194
|
+
*/
|
|
195
|
+
const createOpenApiDocument = (specs, options, endpoints = []) => withoutUndefined({
|
|
196
|
+
openapi: "3.1.0",
|
|
197
|
+
info: options.info,
|
|
198
|
+
servers: options.servers,
|
|
199
|
+
paths: {
|
|
200
|
+
...Object.fromEntries(specs.filter(({ name }) => !isExcluded(name, options)).map((spec) => [actionPath(spec.name, options), { post: operation(spec) }])),
|
|
201
|
+
...endpointPaths(endpoints, options)
|
|
202
|
+
},
|
|
203
|
+
components
|
|
204
|
+
});
|
|
205
|
+
export { createOpenApiDocument as t };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ActionErrorCode, defineAction } from "astro:actions";
|
|
2
|
+
/** Documentation for one action, passed to `defineSpecAction`. */
|
|
3
|
+
type ActionSpecDetails = {
|
|
4
|
+
summary?: string;
|
|
5
|
+
description?: string;
|
|
6
|
+
deprecated?: boolean;
|
|
7
|
+
/** Overrides the tag, which defaults to the first segment of a nested action's name. */
|
|
8
|
+
tags?: string[];
|
|
9
|
+
/** A Zod schema for the value the handler returns. */
|
|
10
|
+
output?: object;
|
|
11
|
+
/** The `ActionError` codes the handler can throw. */
|
|
12
|
+
errors?: ActionErrorCode[];
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Documents an action for the OpenAPI document and returns Astro's own `defineAction`, so the
|
|
16
|
+
* action is typed and behaves exactly as without astro-spec.
|
|
17
|
+
*
|
|
18
|
+
* The input schema and `accept` are read from the `defineAction` options. The output schema is
|
|
19
|
+
* not checked against the handler's return type.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* import { defineSpecAction } from '@astro-spec/openapi/actions'
|
|
24
|
+
* import { z } from 'astro/zod'
|
|
25
|
+
*
|
|
26
|
+
* export const server = {
|
|
27
|
+
* getUser: defineSpecAction({
|
|
28
|
+
* summary: 'Get a user by id',
|
|
29
|
+
* output: z.object({ id: z.string(), name: z.string() }),
|
|
30
|
+
* errors: ['NOT_FOUND'],
|
|
31
|
+
* })({
|
|
32
|
+
* input: z.object({ id: z.string() }),
|
|
33
|
+
* handler: async ({ id }) => db.user.find(id),
|
|
34
|
+
* }),
|
|
35
|
+
* }
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
declare const defineSpecAction: (details: ActionSpecDetails) => typeof defineAction;
|
|
39
|
+
export { ActionSpecDetails as n, defineSpecAction as t };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import "./index-fRyZ0DqZ.mjs";
|
|
2
|
+
import { AstroIntegration } from "astro";
|
|
3
|
+
type JsonSchema = {
|
|
4
|
+
[key: string]: unknown;
|
|
5
|
+
};
|
|
6
|
+
/** Zod 4's `toJSONSchema`, taken from the `astro/zod` the project uses. */
|
|
7
|
+
type Zod4ToJsonSchema = (schema: never, params: Zod4ToJsonSchemaParams) => JsonSchema;
|
|
8
|
+
type Zod4ToJsonSchemaParams = {
|
|
9
|
+
target: 'draft-2020-12';
|
|
10
|
+
io: 'input' | 'output';
|
|
11
|
+
unrepresentable: 'any';
|
|
12
|
+
override: (context: {
|
|
13
|
+
zodSchema: {
|
|
14
|
+
_zod: {
|
|
15
|
+
def: {
|
|
16
|
+
type: string;
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
jsonSchema: JsonSchema;
|
|
21
|
+
}) => void;
|
|
22
|
+
};
|
|
23
|
+
/** What the project's Astro version provides, read inside Vite by `virtual:astro-spec/actions`. */
|
|
24
|
+
type AstroRuntime = {
|
|
25
|
+
zod4ToJsonSchema: Zod4ToJsonSchema | undefined;
|
|
26
|
+
/** `ActionError.codeToStatus`; the codes and their statuses differ between Astro versions. */
|
|
27
|
+
codeToStatus: (code: string) => number;
|
|
28
|
+
};
|
|
29
|
+
type ActionSpec = ReturnType<typeof createActionSpecs>[number];
|
|
30
|
+
/**
|
|
31
|
+
* Describes every action in the `server` export of `src/actions`.
|
|
32
|
+
*
|
|
33
|
+
* Actions made with `defineSpecAction`, or with `defineAction` while the astro-spec Vite plugin
|
|
34
|
+
* runs, have schemas. Others are listed with their name only.
|
|
35
|
+
*/
|
|
36
|
+
declare const createActionSpecs: (server: Record<string, unknown>, runtime: AstroRuntime) => {
|
|
37
|
+
name: string;
|
|
38
|
+
accept: "json" | "form";
|
|
39
|
+
input: {
|
|
40
|
+
[key: string]: unknown;
|
|
41
|
+
} | undefined;
|
|
42
|
+
output: {
|
|
43
|
+
[key: string]: unknown;
|
|
44
|
+
} | undefined;
|
|
45
|
+
summary: string | undefined;
|
|
46
|
+
description: string | undefined;
|
|
47
|
+
deprecated: boolean;
|
|
48
|
+
tags: string[] | undefined;
|
|
49
|
+
errors: {
|
|
50
|
+
code: "BAD_REQUEST" | "UNAUTHORIZED" | "PAYMENT_REQUIRED" | "FORBIDDEN" | "NOT_FOUND" | "METHOD_NOT_ALLOWED" | "NOT_ACCEPTABLE" | "PROXY_AUTHENTICATION_REQUIRED" | "REQUEST_TIMEOUT" | "CONFLICT" | "GONE" | "LENGTH_REQUIRED" | "PRECONDITION_FAILED" | "CONTENT_TOO_LARGE" | "URI_TOO_LONG" | "UNSUPPORTED_MEDIA_TYPE" | "RANGE_NOT_SATISFIABLE" | "EXPECTATION_FAILED" | "MISDIRECTED_REQUEST" | "UNPROCESSABLE_CONTENT" | "LOCKED" | "FAILED_DEPENDENCY" | "TOO_EARLY" | "UPGRADE_REQUIRED" | "PRECONDITION_REQUIRED" | "TOO_MANY_REQUESTS" | "REQUEST_HEADER_FIELDS_TOO_LARGE" | "UNAVAILABLE_FOR_LEGAL_REASONS" | "INTERNAL_SERVER_ERROR" | "NOT_IMPLEMENTED" | "BAD_GATEWAY" | "SERVICE_UNAVAILABLE" | "GATEWAY_TIMEOUT" | "HTTP_VERSION_NOT_SUPPORTED" | "VARIANT_ALSO_NEGOTIATES" | "INSUFFICIENT_STORAGE" | "LOOP_DETECTED" | "NETWORK_AUTHENTICATION_REQUIRED";
|
|
51
|
+
status: number;
|
|
52
|
+
}[];
|
|
53
|
+
}[];
|
|
54
|
+
/** A script in `src/pages` and the OpenAPI path it serves, from `virtual:astro-spec/endpoints`. */
|
|
55
|
+
type PageModule = {
|
|
56
|
+
path: string;
|
|
57
|
+
module: Record<string, unknown>;
|
|
58
|
+
};
|
|
59
|
+
type EndpointSpec = ReturnType<typeof createEndpointSpecs>[number];
|
|
60
|
+
/**
|
|
61
|
+
* Describes every endpoint handler made with `defineEndpoint` in the given page modules. Other
|
|
62
|
+
* handlers, such as a plain `export const GET`, are left out.
|
|
63
|
+
*/
|
|
64
|
+
declare const createEndpointSpecs: (pages: PageModule[], runtime: Pick<AstroRuntime, "zod4ToJsonSchema">) => {
|
|
65
|
+
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" | "HEAD";
|
|
66
|
+
path: string;
|
|
67
|
+
operationId: string;
|
|
68
|
+
summary: string | undefined;
|
|
69
|
+
description: string | undefined;
|
|
70
|
+
deprecated: boolean;
|
|
71
|
+
tags: string[] | undefined;
|
|
72
|
+
accept: "json" | "form";
|
|
73
|
+
params: {
|
|
74
|
+
[key: string]: unknown;
|
|
75
|
+
} | undefined;
|
|
76
|
+
query: {
|
|
77
|
+
[key: string]: unknown;
|
|
78
|
+
} | undefined;
|
|
79
|
+
input: {
|
|
80
|
+
[key: string]: unknown;
|
|
81
|
+
} | undefined;
|
|
82
|
+
output: {
|
|
83
|
+
[key: string]: unknown;
|
|
84
|
+
} | undefined;
|
|
85
|
+
errors: {
|
|
86
|
+
status: number;
|
|
87
|
+
description: string;
|
|
88
|
+
}[];
|
|
89
|
+
}[];
|
|
90
|
+
type OpenApiInfo = {
|
|
91
|
+
title: string;
|
|
92
|
+
version: string;
|
|
93
|
+
description?: string;
|
|
94
|
+
};
|
|
95
|
+
type OpenApiServer = {
|
|
96
|
+
url: string;
|
|
97
|
+
description?: string;
|
|
98
|
+
};
|
|
99
|
+
type DocumentOptions = {
|
|
100
|
+
info: OpenApiInfo;
|
|
101
|
+
servers: OpenApiServer[] | undefined;
|
|
102
|
+
/**
|
|
103
|
+
* Patterns to leave out: action names such as `internal.*`, and endpoint paths such as
|
|
104
|
+
* `/api/internal/*`.
|
|
105
|
+
*/
|
|
106
|
+
exclude: string[];
|
|
107
|
+
/** Astro's `base`. */
|
|
108
|
+
base: string;
|
|
109
|
+
/** Astro's `trailingSlash`; URLs end with a slash only for `always`. */
|
|
110
|
+
trailingSlash: 'always' | 'never' | 'ignore';
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Builds an OpenAPI 3.1 document in which every action is a `POST` operation on its
|
|
114
|
+
* `/_actions/<name>` URL, followed by the endpoints made with `defineEndpoint`.
|
|
115
|
+
*
|
|
116
|
+
* Successful action responses use the `application/json+devalue` media type, because Astro
|
|
117
|
+
* serializes action results with devalue; the schema describes the value after decoding.
|
|
118
|
+
*/
|
|
119
|
+
export declare const createOpenApiDocument: (specs: ActionSpec[], options: DocumentOptions, endpoints?: EndpointSpec[]) => {
|
|
120
|
+
openapi: string;
|
|
121
|
+
info: OpenApiInfo;
|
|
122
|
+
servers: OpenApiServer[] | undefined;
|
|
123
|
+
paths: {
|
|
124
|
+
[x: string]: Record<string, unknown> | {
|
|
125
|
+
post: {
|
|
126
|
+
operationId: string;
|
|
127
|
+
summary: string | undefined;
|
|
128
|
+
description: string | undefined;
|
|
129
|
+
deprecated: true | undefined;
|
|
130
|
+
tags: string[] | undefined;
|
|
131
|
+
requestBody: {
|
|
132
|
+
required: boolean;
|
|
133
|
+
content: {
|
|
134
|
+
'multipart/form-data': {
|
|
135
|
+
schema: object;
|
|
136
|
+
};
|
|
137
|
+
'application/x-www-form-urlencoded': {
|
|
138
|
+
schema: object;
|
|
139
|
+
};
|
|
140
|
+
};
|
|
141
|
+
} | {
|
|
142
|
+
required: boolean;
|
|
143
|
+
content: {
|
|
144
|
+
'application/json': {
|
|
145
|
+
schema: {
|
|
146
|
+
[key: string]: unknown;
|
|
147
|
+
};
|
|
148
|
+
};
|
|
149
|
+
};
|
|
150
|
+
} | undefined;
|
|
151
|
+
responses: {
|
|
152
|
+
default: {
|
|
153
|
+
description: string;
|
|
154
|
+
content: {
|
|
155
|
+
'application/json': {
|
|
156
|
+
schema: {
|
|
157
|
+
$ref: string;
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
'400'?: {
|
|
163
|
+
description: string;
|
|
164
|
+
content: {
|
|
165
|
+
'application/json': {
|
|
166
|
+
schema: {
|
|
167
|
+
$ref: string;
|
|
168
|
+
};
|
|
169
|
+
};
|
|
170
|
+
};
|
|
171
|
+
} | undefined;
|
|
172
|
+
'200': {
|
|
173
|
+
description: string;
|
|
174
|
+
content: {
|
|
175
|
+
'application/json+devalue': {
|
|
176
|
+
schema: {
|
|
177
|
+
[key: string]: unknown;
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
};
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
};
|
|
185
|
+
};
|
|
186
|
+
components: {
|
|
187
|
+
schemas: {
|
|
188
|
+
ActionError: {
|
|
189
|
+
type: string;
|
|
190
|
+
properties: {
|
|
191
|
+
type: {
|
|
192
|
+
const: string;
|
|
193
|
+
};
|
|
194
|
+
code: {
|
|
195
|
+
type: string;
|
|
196
|
+
};
|
|
197
|
+
status: {
|
|
198
|
+
type: string;
|
|
199
|
+
};
|
|
200
|
+
message: {
|
|
201
|
+
type: string;
|
|
202
|
+
};
|
|
203
|
+
};
|
|
204
|
+
required: string[];
|
|
205
|
+
};
|
|
206
|
+
ActionInputError: {
|
|
207
|
+
type: string;
|
|
208
|
+
properties: {
|
|
209
|
+
type: {
|
|
210
|
+
const: string;
|
|
211
|
+
};
|
|
212
|
+
issues: {
|
|
213
|
+
type: string;
|
|
214
|
+
items: {
|
|
215
|
+
type: string;
|
|
216
|
+
};
|
|
217
|
+
};
|
|
218
|
+
fields: {
|
|
219
|
+
type: string;
|
|
220
|
+
additionalProperties: {
|
|
221
|
+
type: string;
|
|
222
|
+
items: {
|
|
223
|
+
type: string;
|
|
224
|
+
};
|
|
225
|
+
};
|
|
226
|
+
};
|
|
227
|
+
};
|
|
228
|
+
required: string[];
|
|
229
|
+
};
|
|
230
|
+
EndpointInputError: {
|
|
231
|
+
type: string;
|
|
232
|
+
properties: {
|
|
233
|
+
type: {
|
|
234
|
+
const: string;
|
|
235
|
+
};
|
|
236
|
+
in: {
|
|
237
|
+
enum: string[];
|
|
238
|
+
};
|
|
239
|
+
issues: {
|
|
240
|
+
type: string;
|
|
241
|
+
items: {
|
|
242
|
+
type: string;
|
|
243
|
+
};
|
|
244
|
+
};
|
|
245
|
+
fields: {
|
|
246
|
+
type: string;
|
|
247
|
+
additionalProperties: {
|
|
248
|
+
type: string;
|
|
249
|
+
items: {
|
|
250
|
+
type: string;
|
|
251
|
+
};
|
|
252
|
+
};
|
|
253
|
+
};
|
|
254
|
+
};
|
|
255
|
+
required: string[];
|
|
256
|
+
};
|
|
257
|
+
};
|
|
258
|
+
};
|
|
259
|
+
};
|
|
260
|
+
type AstroSpecOptions = {
|
|
261
|
+
/** Where the document is served. Defaults to `/openapi.json`. */
|
|
262
|
+
path?: string;
|
|
263
|
+
/** Defaults to `{ title: 'API', version: '1.0.0' }`. */
|
|
264
|
+
info?: OpenApiInfo;
|
|
265
|
+
servers?: OpenApiServer[];
|
|
266
|
+
/**
|
|
267
|
+
* Patterns to leave out of the document: action names such as `internal.*`, and endpoint
|
|
268
|
+
* paths such as `/api/internal/*`.
|
|
269
|
+
*/
|
|
270
|
+
exclude?: string[];
|
|
271
|
+
/**
|
|
272
|
+
* Whether the built site serves the document. `astro dev` always serves it.
|
|
273
|
+
*
|
|
274
|
+
* - `false` (default): not served.
|
|
275
|
+
* - `'prerender'`: written as a static file at build time.
|
|
276
|
+
* - `'runtime'`: generated on each request; needs an adapter.
|
|
277
|
+
*/
|
|
278
|
+
production?: false | 'prerender' | 'runtime';
|
|
279
|
+
/**
|
|
280
|
+
* A path relative to the project root to write the document to on `astro build`, such as
|
|
281
|
+
* `openapi.json`, for checking it into the repository or comparing it in CI.
|
|
282
|
+
*/
|
|
283
|
+
outputFile?: string;
|
|
284
|
+
};
|
|
285
|
+
/**
|
|
286
|
+
* Serves an OpenAPI 3.1 document describing the project's Astro Actions.
|
|
287
|
+
*
|
|
288
|
+
* @example
|
|
289
|
+
* ```ts
|
|
290
|
+
* // astro.config.mjs
|
|
291
|
+
* import astroSpec from '@astro-spec/openapi'
|
|
292
|
+
*
|
|
293
|
+
* export default defineConfig({
|
|
294
|
+
* integrations: [
|
|
295
|
+
* astroSpec({
|
|
296
|
+
* info: { title: 'My API', version: '1.0.0' },
|
|
297
|
+
* exclude: ['internal.*'],
|
|
298
|
+
* production: 'prerender',
|
|
299
|
+
* }),
|
|
300
|
+
* ],
|
|
301
|
+
* })
|
|
302
|
+
* ```
|
|
303
|
+
*/
|
|
304
|
+
declare const astroSpec: ({ path, info, servers, exclude, production, outputFile }?: AstroSpecOptions) => AstroIntegration;
|
|
305
|
+
export { type AstroSpecOptions, type DocumentOptions, type OpenApiInfo, type OpenApiServer, astroSpec as default };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { t as createOpenApiDocument } from "./create-openapi-document-DoxXS2mJ.mjs";
|
|
2
|
+
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, relative } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { existsSync } from "node:fs";
|
|
6
|
+
// ../core/src/vite-plugin.ts
|
|
7
|
+
const ACTIONS_MODULE_ID = "virtual:astro-spec/actions";
|
|
8
|
+
const SHIM_MODULE_ID = "virtual:astro-spec/actions-shim";
|
|
9
|
+
const ENDPOINTS_MODULE_ID = "virtual:astro-spec/endpoints";
|
|
10
|
+
const VIRTUAL_MODULE_IDS = [
|
|
11
|
+
ACTIONS_MODULE_ID,
|
|
12
|
+
SHIM_MODULE_ID,
|
|
13
|
+
ENDPOINTS_MODULE_ID
|
|
14
|
+
];
|
|
15
|
+
const ACTION_FILE_CANDIDATES = [
|
|
16
|
+
"ts",
|
|
17
|
+
"mts",
|
|
18
|
+
"js",
|
|
19
|
+
"mjs"
|
|
20
|
+
].flatMap((extension) => [`actions.${extension}`, `actions/index.${extension}`]);
|
|
21
|
+
const SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
|
|
22
|
+
const ASTRO_ACTIONS_SPECIFIER = /(\bfrom\s*|\bimport\s*\(\s*)(['"])astro:actions\2/g;
|
|
23
|
+
const toVitePath = (path) => (path instanceof URL ? fileURLToPath(path) : path).replaceAll("\\", "/");
|
|
24
|
+
const actionsModuleCode = (actionsFile) => `
|
|
25
|
+
import { ActionError } from 'astro:actions'
|
|
26
|
+
import * as zod from 'astro/zod'
|
|
27
|
+
${actionsFile ? `export { server } from ${JSON.stringify(toVitePath(actionsFile))}` : "export const server = {}"}
|
|
28
|
+
export const runtime = {
|
|
29
|
+
zod4ToJsonSchema: zod.toJSONSchema,
|
|
30
|
+
codeToStatus: (code) => ActionError.codeToStatus(code),
|
|
31
|
+
}
|
|
32
|
+
`;
|
|
33
|
+
const shimModuleCode = `
|
|
34
|
+
import { defineAction as defineAstroAction } from 'astro:actions'
|
|
35
|
+
export * from 'astro:actions'
|
|
36
|
+
export const defineAction = (options) =>
|
|
37
|
+
Object.assign(defineAstroAction(options), {
|
|
38
|
+
[Symbol.for('astro-spec.action')]: { accept: options.accept, input: options.input },
|
|
39
|
+
})
|
|
40
|
+
`;
|
|
41
|
+
const endpointsModuleCode = (pagesDirectory) => `
|
|
42
|
+
export const pagesDirectory = ${JSON.stringify(pagesDirectory)}
|
|
43
|
+
export const modules = import.meta.glob(
|
|
44
|
+
${JSON.stringify([
|
|
45
|
+
`${pagesDirectory}/**/*.{ts,mts,js,mjs}`,
|
|
46
|
+
"!**/*.d.ts",
|
|
47
|
+
"!**/_*",
|
|
48
|
+
"!**/_*/**"
|
|
49
|
+
])},
|
|
50
|
+
{ eager: true },
|
|
51
|
+
)
|
|
52
|
+
`;
|
|
53
|
+
/**
|
|
54
|
+
* The Vite plugin every astro-spec integration adds. It provides `virtual:astro-spec/actions`,
|
|
55
|
+
* which exports the project's `server` actions and an `AstroRuntime` for `createActionSpecs`,
|
|
56
|
+
* and `virtual:astro-spec/endpoints`, which imports the script pages for `collectPages`.
|
|
57
|
+
*
|
|
58
|
+
* It also makes `defineAction` from `astro:actions` record `accept` and `input` in every script
|
|
59
|
+
* outside `node_modules`, so actions documented without `defineSpecAction` still get their input
|
|
60
|
+
* schema. The action behaves the same. Scripts outside `srcDir` count too, so actions written in
|
|
61
|
+
* another workspace package are covered.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```ts
|
|
65
|
+
* updateConfig({ vite: { plugins: [astroSpecVitePlugin({ srcDir: config.srcDir })] } })
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
const astroSpecVitePlugin = ({ srcDir }) => {
|
|
69
|
+
const pagesUrl = new URL("pages", srcDir);
|
|
70
|
+
let pagesDirectory = "/src/pages";
|
|
71
|
+
return {
|
|
72
|
+
name: "astro-spec:actions",
|
|
73
|
+
enforce: "pre",
|
|
74
|
+
configResolved({ root }) {
|
|
75
|
+
pagesDirectory = `/${toVitePath(relative(root, fileURLToPath(pagesUrl)))}`;
|
|
76
|
+
},
|
|
77
|
+
resolveId(id) {
|
|
78
|
+
return VIRTUAL_MODULE_IDS.includes(id) ? `\0${id}` : void 0;
|
|
79
|
+
},
|
|
80
|
+
configureServer(server) {
|
|
81
|
+
const invalidate = () => {
|
|
82
|
+
const graphs = server.environments ? Object.values(server.environments).map(({ moduleGraph }) => moduleGraph) : [server.moduleGraph];
|
|
83
|
+
for (const graph of graphs) {
|
|
84
|
+
const module = graph?.getModuleById(`\0${ENDPOINTS_MODULE_ID}`);
|
|
85
|
+
if (module) graph?.invalidateModule(module);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
server.watcher.on("add", invalidate);
|
|
89
|
+
server.watcher.on("unlink", invalidate);
|
|
90
|
+
},
|
|
91
|
+
load(id) {
|
|
92
|
+
if (id === `\0${ACTIONS_MODULE_ID}`) {
|
|
93
|
+
const actionsFile = ACTION_FILE_CANDIDATES.map((file) => new URL(file, srcDir)).find((url) => existsSync(url));
|
|
94
|
+
return actionsModuleCode(actionsFile);
|
|
95
|
+
}
|
|
96
|
+
if (id === `\0${SHIM_MODULE_ID}`) return shimModuleCode;
|
|
97
|
+
if (id === `\0${ENDPOINTS_MODULE_ID}`) return endpointsModuleCode(pagesDirectory);
|
|
98
|
+
},
|
|
99
|
+
transform(code, id) {
|
|
100
|
+
const [path] = id.split("?");
|
|
101
|
+
if (id.startsWith("\0") || path.includes("/node_modules/") || !SCRIPT_FILE.test(path)) return;
|
|
102
|
+
if (!code.includes("astro:actions")) return void 0;
|
|
103
|
+
return {
|
|
104
|
+
code: code.replace(ASTRO_ACTIONS_SPECIFIER, `$1$2${SHIM_MODULE_ID}$2`),
|
|
105
|
+
map: null
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
// src/integration.ts
|
|
111
|
+
const OPTIONS_MODULE_ID = "virtual:astro-spec/openapi-options";
|
|
112
|
+
const ARTIFACT_PATH = "_astro-spec/openapi.json";
|
|
113
|
+
const optionsVitePlugin = (options) => ({
|
|
114
|
+
name: "astro-spec:openapi-options",
|
|
115
|
+
resolveId: (id) => id === OPTIONS_MODULE_ID ? `\0${OPTIONS_MODULE_ID}` : void 0,
|
|
116
|
+
load: (id) => id === `\0${OPTIONS_MODULE_ID}` ? `export default ${JSON.stringify(options)}` : void 0
|
|
117
|
+
});
|
|
118
|
+
const devPathPlugin = (from, to) => ({
|
|
119
|
+
name: "astro-spec:openapi-dev-path",
|
|
120
|
+
configureServer(server) {
|
|
121
|
+
server.middlewares.use((req, _res, next) => {
|
|
122
|
+
const [pathname, query] = (req.url ?? "").split("?");
|
|
123
|
+
if (pathname === from) req.url = query === void 0 ? to : `${to}?${query}`;
|
|
124
|
+
next();
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
/**
|
|
129
|
+
* Serves an OpenAPI 3.1 document describing the project's Astro Actions.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```ts
|
|
133
|
+
* // astro.config.mjs
|
|
134
|
+
* import astroSpec from '@astro-spec/openapi'
|
|
135
|
+
*
|
|
136
|
+
* export default defineConfig({
|
|
137
|
+
* integrations: [
|
|
138
|
+
* astroSpec({
|
|
139
|
+
* info: { title: 'My API', version: '1.0.0' },
|
|
140
|
+
* exclude: ['internal.*'],
|
|
141
|
+
* production: 'prerender',
|
|
142
|
+
* }),
|
|
143
|
+
* ],
|
|
144
|
+
* })
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
const astroSpec = ({ path = "/openapi.json", info = {
|
|
148
|
+
title: "API",
|
|
149
|
+
version: "1.0.0"
|
|
150
|
+
}, servers, exclude = [], production = false, outputFile } = {}) => {
|
|
151
|
+
const outputUrl = { current: void 0 };
|
|
152
|
+
return {
|
|
153
|
+
name: "@astro-spec/openapi",
|
|
154
|
+
hooks: {
|
|
155
|
+
"astro:config:setup": ({ config, command, injectRoute, updateConfig }) => {
|
|
156
|
+
updateConfig({ vite: {
|
|
157
|
+
plugins: [astroSpecVitePlugin({ srcDir: config.srcDir }), optionsVitePlugin({
|
|
158
|
+
info,
|
|
159
|
+
servers,
|
|
160
|
+
exclude,
|
|
161
|
+
base: config.base,
|
|
162
|
+
trailingSlash: config.trailingSlash
|
|
163
|
+
})],
|
|
164
|
+
ssr: { noExternal: ["@astro-spec/openapi"] }
|
|
165
|
+
} });
|
|
166
|
+
if (command === "dev") {
|
|
167
|
+
const base = config.base.replace(/\/$/, "");
|
|
168
|
+
updateConfig({ vite: { plugins: [devPathPlugin(`${base}${path}`, `${base}/${ARTIFACT_PATH}`)] } });
|
|
169
|
+
injectRoute({
|
|
170
|
+
pattern: `/${ARTIFACT_PATH}`,
|
|
171
|
+
entrypoint: "@astro-spec/openapi/route",
|
|
172
|
+
prerender: false
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
if (command !== "build") return;
|
|
176
|
+
if (production) injectRoute({
|
|
177
|
+
pattern: path,
|
|
178
|
+
entrypoint: "@astro-spec/openapi/route",
|
|
179
|
+
prerender: production === "prerender"
|
|
180
|
+
});
|
|
181
|
+
if (outputFile) {
|
|
182
|
+
outputUrl.current = new URL(outputFile, config.root);
|
|
183
|
+
injectRoute({
|
|
184
|
+
pattern: `/${ARTIFACT_PATH}`,
|
|
185
|
+
entrypoint: "@astro-spec/openapi/artifact-route",
|
|
186
|
+
prerender: true
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
"astro:build:done": async ({ dir }) => {
|
|
191
|
+
if (!outputUrl.current) return;
|
|
192
|
+
const artifact = new URL(ARTIFACT_PATH, dir);
|
|
193
|
+
const document = JSON.parse(await readFile(artifact, "utf8"));
|
|
194
|
+
await mkdir(dirname(fileURLToPath(outputUrl.current)), { recursive: true });
|
|
195
|
+
await writeFile(outputUrl.current, `${JSON.stringify(document, null, 2)}\n`);
|
|
196
|
+
await rm(new URL(".", artifact), { recursive: true });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
};
|
|
201
|
+
export { createOpenApiDocument, astroSpec as default };
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { runtime, server } from "virtual:astro-spec/actions";
|
|
2
|
+
import { modules, pagesDirectory } from "virtual:astro-spec/endpoints";
|
|
3
|
+
import options from "virtual:astro-spec/openapi-options";
|
|
4
|
+
import { n as readActionMetadata } from "./action-metadata-CVcuvF_u.mjs";
|
|
5
|
+
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
6
|
+
import { t as createOpenApiDocument } from "./create-openapi-document-DoxXS2mJ.mjs";
|
|
7
|
+
// ../core/src/page-path.ts
|
|
8
|
+
const SCRIPT_EXTENSION = /\.[cm]?[jt]s$/;
|
|
9
|
+
const DYNAMIC_SEGMENT = /\[(?:\.\.\.)?([^\]]+)\]/g;
|
|
10
|
+
/**
|
|
11
|
+
* Turns the path of a script in `src/pages`, relative to that directory and with forward
|
|
12
|
+
* slashes, into the OpenAPI path it serves: `api/users/[id].ts` becomes `/api/users/{id}`.
|
|
13
|
+
* Returns `undefined` for files Astro does not route, such as `_helpers.ts`.
|
|
14
|
+
*/
|
|
15
|
+
const pagePath = (file) => {
|
|
16
|
+
const segments = file.replace(SCRIPT_EXTENSION, "").split("/");
|
|
17
|
+
if (segments.some((segment) => segment.startsWith("_"))) return void 0;
|
|
18
|
+
if (segments.at(-1) === "index") segments.pop();
|
|
19
|
+
return `/${segments.map((segment) => segment.replace(DYNAMIC_SEGMENT, "{$1}")).join("/")}`;
|
|
20
|
+
};
|
|
21
|
+
// ../core/src/collect-pages.ts
|
|
22
|
+
/**
|
|
23
|
+
* Pairs each module from `virtual:astro-spec/endpoints` with the OpenAPI path it serves, sorted
|
|
24
|
+
* by path. The module keys are file paths that start with `pagesDirectory`.
|
|
25
|
+
*/
|
|
26
|
+
const collectPages = (modules, pagesDirectory) => Object.entries(modules).flatMap(([file, module]) => {
|
|
27
|
+
const path = pagePath(file.slice(pagesDirectory.length + 1));
|
|
28
|
+
return path ? [{
|
|
29
|
+
path,
|
|
30
|
+
module
|
|
31
|
+
}] : [];
|
|
32
|
+
}).sort((a, b) => a.path.localeCompare(b.path));
|
|
33
|
+
// ../core/src/collect-actions.ts
|
|
34
|
+
const isAction = (value) => typeof value === "function" && "orThrow" in value;
|
|
35
|
+
const isNamespace = (value) => typeof value === "object" && value !== null;
|
|
36
|
+
/** Walks the `server` export of `src/actions` and yields every action, nested ones included. */
|
|
37
|
+
function* collectActions(server, prefix = "") {
|
|
38
|
+
for (const [key, value] of Object.entries(server)) {
|
|
39
|
+
const name = `${prefix}${key}`;
|
|
40
|
+
if (isAction(value)) yield {
|
|
41
|
+
name,
|
|
42
|
+
action: value
|
|
43
|
+
};
|
|
44
|
+
else if (isNamespace(value)) yield* collectActions(value, `${name}.`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
// ../core/src/to-json-schema.ts
|
|
48
|
+
/**
|
|
49
|
+
* Converts a Zod 3 or Zod 4 schema to a JSON Schema for OpenAPI 3.1, without the `$schema` key.
|
|
50
|
+
*
|
|
51
|
+
* `io` picks which side of transforms, pipes and defaults to describe: `input` for what a client
|
|
52
|
+
* sends, `output` for what a handler returns. Dates become `date-time` strings with both Zod
|
|
53
|
+
* versions; other types JSON Schema cannot express become `{}`.
|
|
54
|
+
*/
|
|
55
|
+
const toJsonSchema = (schema, io, zod4ToJsonSchema) => {
|
|
56
|
+
if ("_zod" in schema) {
|
|
57
|
+
if (!zod4ToJsonSchema) throw new Error("Found a Zod 4 schema, but `astro/zod` has no `toJSONSchema`. Import `z` from `astro/zod`.");
|
|
58
|
+
const { $schema: _, ...jsonSchema } = zod4ToJsonSchema(schema, {
|
|
59
|
+
target: "draft-2020-12",
|
|
60
|
+
io,
|
|
61
|
+
unrepresentable: "any",
|
|
62
|
+
override: ({ zodSchema, jsonSchema }) => {
|
|
63
|
+
if (zodSchema._zod.def.type === "date") {
|
|
64
|
+
jsonSchema.type = "string";
|
|
65
|
+
jsonSchema.format = "date-time";
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
return jsonSchema;
|
|
70
|
+
}
|
|
71
|
+
if ("_def" in schema) {
|
|
72
|
+
const { $schema: _, ...jsonSchema } = zodToJsonSchema(schema, {
|
|
73
|
+
target: "jsonSchema2019-09",
|
|
74
|
+
$refStrategy: "none",
|
|
75
|
+
pipeStrategy: io,
|
|
76
|
+
effectStrategy: io === "input" ? "input" : "any"
|
|
77
|
+
});
|
|
78
|
+
return jsonSchema;
|
|
79
|
+
}
|
|
80
|
+
throw new Error("Expected a Zod 3 or Zod 4 schema.");
|
|
81
|
+
};
|
|
82
|
+
// ../core/src/create-action-specs.ts
|
|
83
|
+
/**
|
|
84
|
+
* Describes every action in the `server` export of `src/actions`.
|
|
85
|
+
*
|
|
86
|
+
* Actions made with `defineSpecAction`, or with `defineAction` while the astro-spec Vite plugin
|
|
87
|
+
* runs, have schemas. Others are listed with their name only.
|
|
88
|
+
*/
|
|
89
|
+
const createActionSpecs = (server, runtime) => Array.from(collectActions(server), ({ name, action }) => {
|
|
90
|
+
const metadata = readActionMetadata(action);
|
|
91
|
+
return {
|
|
92
|
+
name,
|
|
93
|
+
accept: metadata?.accept ?? "json",
|
|
94
|
+
input: metadata?.input && toJsonSchema(metadata.input, "input", runtime.zod4ToJsonSchema),
|
|
95
|
+
output: metadata?.output && toJsonSchema(metadata.output, "output", runtime.zod4ToJsonSchema),
|
|
96
|
+
summary: metadata?.summary,
|
|
97
|
+
description: metadata?.description,
|
|
98
|
+
deprecated: metadata?.deprecated ?? false,
|
|
99
|
+
tags: metadata?.tags,
|
|
100
|
+
errors: (metadata?.errors ?? []).map((code) => ({
|
|
101
|
+
code,
|
|
102
|
+
status: runtime.codeToStatus(code)
|
|
103
|
+
}))
|
|
104
|
+
};
|
|
105
|
+
});
|
|
106
|
+
// ../core/src/endpoint-metadata.ts
|
|
107
|
+
/**
|
|
108
|
+
* The key under which an endpoint handler carries its astro-spec metadata. It comes from the
|
|
109
|
+
* global symbol registry so that copies of the packages in different bundles agree on it.
|
|
110
|
+
*/
|
|
111
|
+
const ENDPOINT_METADATA = Symbol.for("astro-spec.endpoint");
|
|
112
|
+
const readEndpointMetadata = (value) => value?.[ENDPOINT_METADATA];
|
|
113
|
+
// ../core/src/create-endpoint-specs.ts
|
|
114
|
+
const METHODS = [
|
|
115
|
+
"GET",
|
|
116
|
+
"POST",
|
|
117
|
+
"PUT",
|
|
118
|
+
"PATCH",
|
|
119
|
+
"DELETE",
|
|
120
|
+
"OPTIONS",
|
|
121
|
+
"HEAD"
|
|
122
|
+
];
|
|
123
|
+
/**
|
|
124
|
+
* Describes every endpoint handler made with `defineEndpoint` in the given page modules. Other
|
|
125
|
+
* handlers, such as a plain `export const GET`, are left out.
|
|
126
|
+
*/
|
|
127
|
+
const createEndpointSpecs = (pages, runtime) => pages.flatMap(({ path, module }) => METHODS.flatMap((method) => {
|
|
128
|
+
const metadata = readEndpointMetadata(module[method]);
|
|
129
|
+
if (!metadata) return [];
|
|
130
|
+
const schema = (value, io) => value && toJsonSchema(value, io, runtime.zod4ToJsonSchema);
|
|
131
|
+
return [{
|
|
132
|
+
method,
|
|
133
|
+
path,
|
|
134
|
+
operationId: metadata.operationId ?? `${method} ${path}`,
|
|
135
|
+
summary: metadata.summary,
|
|
136
|
+
description: metadata.description,
|
|
137
|
+
deprecated: metadata.deprecated ?? false,
|
|
138
|
+
tags: metadata.tags,
|
|
139
|
+
accept: metadata.accept ?? "json",
|
|
140
|
+
params: schema(metadata.params, "input"),
|
|
141
|
+
query: schema(metadata.query, "input"),
|
|
142
|
+
input: schema(metadata.input, "input"),
|
|
143
|
+
output: schema(metadata.output, "output"),
|
|
144
|
+
errors: Object.entries(metadata.errors ?? {}).map(([status, description]) => ({
|
|
145
|
+
status: Number(status),
|
|
146
|
+
description
|
|
147
|
+
}))
|
|
148
|
+
}];
|
|
149
|
+
}));
|
|
150
|
+
// src/route.ts
|
|
151
|
+
const GET = () => Response.json(createOpenApiDocument(createActionSpecs(server, runtime), options, createEndpointSpecs(collectPages(modules, pagesDirectory), runtime)));
|
|
152
|
+
export { GET as t };
|
package/dist/route.d.mts
ADDED
package/dist/route.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as GET } from "./route-D3knsMZ-.mjs";
|
package/package.json
CHANGED
|
@@ -1,10 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astro-spec/openapi",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Generate and serve an OpenAPI 3.1 document for Astro Actions",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"astro",
|
|
7
|
+
"astro-integration",
|
|
8
|
+
"withastro",
|
|
9
|
+
"openapi",
|
|
10
|
+
"astro-actions"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/betterlib/astro-spec/tree/main/packages/openapi#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/betterlib/astro-spec/issues"
|
|
15
|
+
},
|
|
5
16
|
"repository": {
|
|
6
17
|
"type": "git",
|
|
7
18
|
"url": "git+https://github.com/betterlib/astro-spec.git",
|
|
8
19
|
"directory": "packages/openapi"
|
|
20
|
+
},
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"author": "otoneko.",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.mts",
|
|
27
|
+
"default": "./dist/index.mjs"
|
|
28
|
+
},
|
|
29
|
+
"./actions": {
|
|
30
|
+
"types": "./dist/actions.d.mts",
|
|
31
|
+
"default": "./dist/actions.mjs"
|
|
32
|
+
},
|
|
33
|
+
"./route": "./dist/route.mjs",
|
|
34
|
+
"./artifact-route": "./dist/artifact-route.mjs",
|
|
35
|
+
"./package.json": "./package.json"
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist"
|
|
39
|
+
],
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=22.12.0"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"zod-to-json-schema": "^3.25.2"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"astro": "^4.15.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public",
|
|
51
|
+
"provenance": true
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"astro": "^7.4.14",
|
|
55
|
+
"zod": "^4.6.7",
|
|
56
|
+
"@astro-spec/core": "1.0.0"
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"build": "tsdown",
|
|
60
|
+
"typecheck": "tsc --noEmit"
|
|
9
61
|
}
|
|
10
|
-
}
|
|
62
|
+
}
|