@astro-spec/client 0.0.0-stage → 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 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 CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # @astro-spec/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Generate a typed client for Astro Actions from an astro-spec OpenAPI document
4
+
5
+ Writes a TypeScript file with one function per action, typed from the OpenAPI document that [`@astro-spec/openapi`](../openapi#readme) serves. Use it to call your actions from another app, a script or a test, where `astro:actions` is not available.
6
+
7
+ The types come from [openapi-typescript](https://openapi-ts.dev). Results are decoded with [devalue](https://github.com/sveltejs/devalue) as Astro encodes them, so a date in a result is a `Date`.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install --save-dev @astro-spec/client
13
+ npm install devalue
14
+ ```
15
+
16
+ The generated file imports only `devalue`, so `@astro-spec/client` stays a development dependency.
17
+
18
+ ## Usage
19
+
20
+ Generate the client from a document file or from a running site:
21
+
22
+ ```sh
23
+ npx astro-spec-client openapi.json --out src/api-client.ts
24
+ npx astro-spec-client http://localhost:4321/openapi.json --out src/api-client.ts
25
+ ```
26
+
27
+ Then call the actions. Nested actions, such as `user.get`, become nested properties.
28
+
29
+ ```ts
30
+ import { createClient } from './api-client'
31
+
32
+ const client = createClient({ baseUrl: 'https://example.com' })
33
+
34
+ const { data, error } = await client.user.get({ id: '1' })
35
+ if (error) {
36
+ console.error(error.code, error.message)
37
+ } else {
38
+ console.log(data.createdAt.getFullYear())
39
+ }
40
+
41
+ // Or throw on error, like Astro's orThrow.
42
+ const user = await client.user.get.orThrow({ id: '1' })
43
+ ```
44
+
45
+ A form action (`accept: 'form'`) takes either `FormData` or an object, which is sent as form data the way a browser form would send it: `false`, `null` and `undefined` values are left out, arrays become repeated fields and dates become ISO strings.
46
+
47
+ Generate the client again whenever the actions change. You can run it in a `prebuild` script, or check in CI that the committed file is up to date.
48
+
49
+ ## Options
50
+
51
+ `createClient` takes these options:
52
+
53
+ | Option | Default | Description |
54
+ | --- | --- | --- |
55
+ | `baseUrl` | `''` | Prepended to each action path, such as `https://example.com`. Leave it empty to call the current origin from a browser. |
56
+ | `headers` | none | Headers for every call, or a function that returns them before each call, for example to send a fresh token. |
57
+ | `fetch` | global `fetch` | The fetch implementation to use. |
58
+
59
+ The action paths, including Astro's `base` and `trailingSlash`, come from the document.
60
+
61
+ ## Errors
62
+
63
+ When the action responds with an error, the call returns `{ data: undefined, error }`, and `orThrow` throws the same error. `error` is an `ActionClientError`:
64
+
65
+ | Property | Description |
66
+ | --- | --- |
67
+ | `status` | The HTTP status, such as `404`. |
68
+ | `code` | The action error code, such as `NOT_FOUND`, or `UNKNOWN` when the body has none. |
69
+ | `message` | The message the action threw. |
70
+ | `fields` | The messages for each invalid field, when the input did not match the schema. |
71
+ | `body` | The parsed JSON body, or the raw text when the body is not JSON. |
72
+
73
+ A network failure is not an action error: the call rejects with the error from `fetch`.
74
+
75
+ > [!NOTE]
76
+ >
77
+ > Astro's `security.checkOrigin` rejects form submissions whose `Origin` header does not match the site. Browsers send it, but a server calling a form action has to add it, for example with `headers: { Origin: 'https://example.com' }`.
78
+
79
+ ## API
80
+
81
+ `generateClient(document)` returns the source of the client for a parsed document, and `runClientCli(args)` runs the command with the given arguments. Both are exported from `@astro-spec/client`.
82
+
83
+ ## License
84
+
85
+ [MIT](https://github.com/betterlib/astro-spec/blob/main/LICENSE)
package/dist/bin.d.mts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/bin.mjs ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { t as runClientCli } from "./run-client-cli-Cn6KgmQ_.mjs";
3
+ // src/bin.ts
4
+ try {
5
+ await runClientCli(process.argv.slice(2));
6
+ } catch (error) {
7
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
8
+ process.exitCode = 1;
9
+ }
10
+ export {};
@@ -0,0 +1,22 @@
1
+ import { OpenAPI3 } from "openapi-typescript";
2
+ /**
3
+ * Generates the TypeScript source of a typed client for the actions in an OpenAPI document
4
+ * written by `@astro-spec/openapi`. The source needs only `devalue` at run time.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * const source = await generateClient(JSON.parse(await readFile('openapi.json', 'utf8')))
9
+ * await writeFile('src/api-client.ts', source)
10
+ * ```
11
+ */
12
+ export declare const generateClient: (document: OpenAPI3) => Promise<string>;
13
+ /**
14
+ * Runs the `astro-spec-client` command with the given arguments, without the node and script
15
+ * paths. Throws when the arguments are wrong or the document cannot be read.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * await runClientCli(['openapi.json', '--out', 'src/api-client.ts'])
20
+ * ```
21
+ */
22
+ export declare const runClientCli: (args: string[]) => Promise<void>;
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { n as generateClient, t as runClientCli } from "./run-client-cli-Cn6KgmQ_.mjs";
@@ -0,0 +1,138 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import openapiTS, { astToString } from "openapi-typescript";
5
+ import ts from "typescript";
6
+ // src/generate-client.ts
7
+ const DEVALUE = "application/json+devalue";
8
+ const collectRoutes = (document) => Object.entries(document.paths ?? {}).flatMap(([path, item]) => {
9
+ const operation = item.post;
10
+ if (!operation?.operationId || !operation.responses?.["200"]?.content?.[DEVALUE]) return [];
11
+ const accept = operation.requestBody?.content?.["multipart/form-data"] ? "form" : "json";
12
+ return [{
13
+ name: operation.operationId,
14
+ route: {
15
+ path,
16
+ accept
17
+ }
18
+ }];
19
+ });
20
+ const propertyKey = (key) => /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
21
+ const clientType = (tree, indent) => `{\n${Object.entries(tree).map(([key, node]) => `${indent} ${propertyKey(key)}: ${typeof node === "string" ? `ActionAt<${JSON.stringify(node)}>` : clientType(node, `${indent} `)}`).join("\n")}\n${indent}}`;
22
+ const toTree = (routes) => {
23
+ const tree = {};
24
+ for (const { name, route } of routes) {
25
+ const keys = name.split(".");
26
+ const parent = keys.slice(0, -1).reduce((node, key) => {
27
+ node[key] ??= {};
28
+ return node[key];
29
+ }, tree);
30
+ parent[keys.at(-1) ?? name] = route.path;
31
+ }
32
+ return tree;
33
+ };
34
+ const transform = (schema, { path = "" }) => schema.format === "date-time" && path.includes("/responses/") ? ts.factory.createTypeReferenceNode("Date") : void 0;
35
+ const HELPER_TYPES = `type Operation<P extends keyof paths> = NonNullable<paths[P]['post']>
36
+ type RequestBody<P extends keyof paths> = NonNullable<Operation<P>['requestBody']>
37
+ type Input<Body> = Body extends { content: { 'application/json': infer I } }
38
+ ? I
39
+ : Body extends { content: { 'multipart/form-data': infer I } }
40
+ ? I | FormData
41
+ : never
42
+ type Args<P extends keyof paths> = [RequestBody<P>] extends [never]
43
+ ? []
44
+ : undefined extends Operation<P>['requestBody']
45
+ ? [input?: Input<RequestBody<P>>]
46
+ : [input: Input<RequestBody<P>>]
47
+ type Output<P extends keyof paths> = Operation<P>['responses'] extends {
48
+ 200: { content: { '${DEVALUE}': infer O } }
49
+ }
50
+ ? O
51
+ : never
52
+ type ActionAt<P extends keyof paths> = Action<Args<P>, Output<P>>`;
53
+ /**
54
+ * Generates the TypeScript source of a typed client for the actions in an OpenAPI document
55
+ * written by `@astro-spec/openapi`. The source needs only `devalue` at run time.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * const source = await generateClient(JSON.parse(await readFile('openapi.json', 'utf8')))
60
+ * await writeFile('src/api-client.ts', source)
61
+ * ```
62
+ */
63
+ const generateClient = async (document) => {
64
+ const types = astToString(await openapiTS(document, { transform }));
65
+ const runtime = await readFile(new URL("./runtime.ts", import.meta.url), "utf8");
66
+ const routes = collectRoutes(document);
67
+ const routeMap = Object.fromEntries(routes.map(({ name, route }) => [name, route]));
68
+ return `// Generated by @astro-spec/client from the OpenAPI document. Do not edit it by hand.
69
+ /* eslint-disable */
70
+
71
+ ${runtime.trim()}
72
+
73
+ ${types.trim()}
74
+
75
+ ${HELPER_TYPES}
76
+
77
+ export type Client = ${clientType(toTree(routes), "")}
78
+
79
+ const routes: Record<string, ActionRoute> = ${JSON.stringify(routeMap, null, 2)}
80
+
81
+ /**
82
+ * Creates a client for the actions in the OpenAPI document.
83
+ *
84
+ * @example
85
+ * const client = createClient({ baseUrl: 'https://example.com' })
86
+ * const { data, error } = await client.user.get({ id: '1' })
87
+ */
88
+ export const createClient = (options: ClientOptions = {}) => createActionClient<Client>(routes, options)
89
+ `;
90
+ };
91
+ // src/run-client-cli.ts
92
+ const HELP = `Usage: astro-spec-client [INPUT] --out FILE
93
+
94
+ Generate a typed client for Astro Actions from an OpenAPI document.
95
+
96
+ INPUT Path or URL of the document (default: openapi.json)
97
+ -o, --out FILE Where to write the client, such as src/api-client.ts
98
+ -h, --help Show this help
99
+ `;
100
+ const readDocument = async (input) => /^https?:\/\//.test(input) ? await (await fetch(input)).text() : await readFile(resolve(input), "utf8");
101
+ /**
102
+ * Runs the `astro-spec-client` command with the given arguments, without the node and script
103
+ * paths. Throws when the arguments are wrong or the document cannot be read.
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * await runClientCli(['openapi.json', '--out', 'src/api-client.ts'])
108
+ * ```
109
+ */
110
+ const runClientCli = async (args) => {
111
+ const { values, positionals } = parseArgs({
112
+ args,
113
+ allowPositionals: true,
114
+ options: {
115
+ out: {
116
+ type: "string",
117
+ short: "o"
118
+ },
119
+ help: {
120
+ type: "boolean",
121
+ short: "h"
122
+ }
123
+ }
124
+ });
125
+ if (values.help) {
126
+ process.stdout.write(HELP);
127
+ return;
128
+ }
129
+ if (!values.out) throw new Error(`Missing --out.\n\n${HELP}`);
130
+ if (positionals.length > 1) throw new Error(`Expected one input, got ${positionals.length}.`);
131
+ const input = positionals[0] ?? "openapi.json";
132
+ const document = JSON.parse(await readDocument(input));
133
+ const out = resolve(values.out);
134
+ await mkdir(dirname(out), { recursive: true });
135
+ await writeFile(out, await generateClient(document));
136
+ process.stdout.write(`Wrote ${values.out} from ${input}\n`);
137
+ };
138
+ export { generateClient as n, runClientCli as t };
@@ -0,0 +1,135 @@
1
+ import { parse } from 'devalue'
2
+
3
+ type HeadersInit = ConstructorParameters<typeof Headers>[0]
4
+
5
+ export type ClientOptions = {
6
+ /** Prepended to each action path, such as `https://example.com`. Defaults to the current origin. */
7
+ baseUrl?: string
8
+ /** Headers sent with every call, or a function that returns them before each call. */
9
+ headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>)
10
+ /** The fetch implementation to use. Defaults to the global `fetch`. */
11
+ fetch?: typeof fetch
12
+ }
13
+
14
+ /** The error a call returns when the action responds with a status outside 200–299. */
15
+ export class ActionClientError extends Error {
16
+ readonly status: number
17
+ /** The action error code, such as `NOT_FOUND`, or `UNKNOWN` when the body has none. */
18
+ readonly code: string
19
+ /** The messages for each invalid field, when the input did not match the schema. */
20
+ readonly fields: Record<string, string[] | undefined> | undefined
21
+ /** The parsed JSON body, or the raw text when the body is not JSON. */
22
+ readonly body: unknown
23
+
24
+ constructor(status: number, body: unknown) {
25
+ const details = (typeof body === 'object' && body !== null ? body : {}) as {
26
+ code?: unknown
27
+ message?: unknown
28
+ fields?: Record<string, string[] | undefined>
29
+ }
30
+ super(
31
+ typeof details.message === 'string' ? details.message : `Action failed with status ${status}`,
32
+ )
33
+ this.name = 'ActionClientError'
34
+ this.status = status
35
+ this.code = typeof details.code === 'string' ? details.code : 'UNKNOWN'
36
+ this.fields = details.fields
37
+ this.body = body
38
+ }
39
+ }
40
+
41
+ export type SafeResult<Output> =
42
+ | { data: Output; error: undefined }
43
+ | { data: undefined; error: ActionClientError }
44
+
45
+ /**
46
+ * Calling an action returns `{ data, error }` like Astro's own client, and never throws for an
47
+ * error response. `orThrow` returns the data and throws the `ActionClientError` instead.
48
+ */
49
+ export type Action<Args extends unknown[], Output> = ((
50
+ ...args: Args
51
+ ) => Promise<SafeResult<Output>>) & {
52
+ orThrow: (...args: Args) => Promise<Output>
53
+ }
54
+
55
+ export type ActionRoute = { path: string; accept: 'json' | 'form' }
56
+
57
+ const formValue = (value: unknown) =>
58
+ value instanceof Blob ? value : value instanceof Date ? value.toISOString() : String(value)
59
+
60
+ // Mirrors a browser form: an unchecked box, like an empty optional field, is left out.
61
+ const toFormData = (input: Record<string, unknown>) => {
62
+ const formData = new FormData()
63
+ for (const [name, value] of Object.entries(input)) {
64
+ for (const item of Array.isArray(value) ? value : [value]) {
65
+ if (item === undefined || item === null || item === false) continue
66
+ formData.append(name, formValue(item))
67
+ }
68
+ }
69
+ return formData
70
+ }
71
+
72
+ const requestBody = (route: ActionRoute, input: unknown) => {
73
+ if (input === undefined) return undefined
74
+ if (route.accept === 'json') return JSON.stringify(input)
75
+ return input instanceof FormData ? input : toFormData(input as Record<string, unknown>)
76
+ }
77
+
78
+ const parseErrorBody = (text: string): unknown => {
79
+ try {
80
+ return JSON.parse(text)
81
+ } catch {
82
+ return text
83
+ }
84
+ }
85
+
86
+ const callAction = async (
87
+ route: ActionRoute,
88
+ input: unknown,
89
+ options: ClientOptions,
90
+ ): Promise<SafeResult<unknown>> => {
91
+ const headers = new Headers(
92
+ typeof options.headers === 'function' ? await options.headers() : options.headers,
93
+ )
94
+ const body = requestBody(route, input)
95
+ if (typeof body === 'string') headers.set('Content-Type', 'application/json')
96
+ const response = await (options.fetch ?? fetch)(`${options.baseUrl ?? ''}${route.path}`, {
97
+ method: 'POST',
98
+ headers,
99
+ ...(body === undefined ? {} : { body }),
100
+ })
101
+ const text = await response.text()
102
+ if (!response.ok) {
103
+ return { data: undefined, error: new ActionClientError(response.status, parseErrorBody(text)) }
104
+ }
105
+ // An action that returns nothing answers 204 with an empty body.
106
+ if (text === '') return { data: undefined, error: undefined }
107
+ const isDevalue = response.headers.get('Content-Type')?.includes('devalue') ?? false
108
+ return { data: isDevalue ? parse(text) : JSON.parse(text), error: undefined }
109
+ }
110
+
111
+ /**
112
+ * Builds a client with one function per action, nested by the dots in the action names. The
113
+ * generated `createClient` calls this with the routes from the OpenAPI document.
114
+ */
115
+ export const createActionClient = <Client>(
116
+ routes: Record<string, ActionRoute>,
117
+ options: ClientOptions = {},
118
+ ) => {
119
+ const client: Record<string, unknown> = {}
120
+ for (const [name, route] of Object.entries(routes)) {
121
+ const call = (input?: unknown) => callAction(route, input, options)
122
+ const orThrow = async (input?: unknown) => {
123
+ const result = await call(input)
124
+ if (result.error) throw result.error
125
+ return result.data
126
+ }
127
+ const keys = name.split('.')
128
+ const parent = keys.slice(0, -1).reduce((node, key) => {
129
+ node[key] ??= {}
130
+ return node[key] as Record<string, unknown>
131
+ }, client)
132
+ parent[keys.at(-1) ?? name] = Object.assign(call, { orThrow })
133
+ }
134
+ return client as Client
135
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@astro-spec/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Generate a typed client for Astro Actions from an astro-spec OpenAPI document",
5
+ "keywords": [
6
+ "astro",
7
+ "openapi",
8
+ "astro-actions",
9
+ "client",
10
+ "codegen"
11
+ ],
12
+ "homepage": "https://github.com/betterlib/astro-spec/tree/main/packages/client#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/betterlib/astro-spec/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/betterlib/astro-spec.git",
19
+ "directory": "packages/client"
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
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "engines": {
35
+ "node": ">=22.12.0"
36
+ },
37
+ "dependencies": {
38
+ "openapi-typescript": "^7.13.0",
39
+ "typescript": "^5.9.3"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public",
43
+ "provenance": true
44
+ },
45
+ "bin": {
46
+ "astro-spec-client": "./dist/bin.mjs"
47
+ },
48
+ "devDependencies": {
49
+ "devalue": "^6.0.4",
50
+ "@astro-spec/core": "1.0.0",
51
+ "@astro-spec/openapi": "1.0.0"
52
+ },
53
+ "scripts": {
54
+ "build": "tsdown",
55
+ "typecheck": "tsc --noEmit"
56
+ }
6
57
  }