@open-apiary/nuxt 0.0.0-stage → 0.0.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.
@@ -0,0 +1,11 @@
1
+ /** The virtual module that holds the options of the module for the runtime. */
2
+ export declare const OPTIONS = "#open-apiary/options";
3
+ /** The virtual module that holds the OpenAPI document of the package. */
4
+ export declare const OPENAPI = "#open-apiary/openapi";
5
+ /** The prefix of the virtual modules of the routes. Each holds the handler of one endpoint. */
6
+ export declare const ROUTES = "#open-apiary/routes";
7
+ /**
8
+ * The virtual module that holds the service of the API. Every route imports
9
+ * it, so the server has one service.
10
+ */
11
+ export declare const ENGINE = "#open-apiary/engine";
@@ -0,0 +1,5 @@
1
+ const OPTIONS = "#open-apiary/options";
2
+ const OPENAPI = "#open-apiary/openapi";
3
+ const ROUTES = "#open-apiary/routes";
4
+ const ENGINE = "#open-apiary/engine";
5
+ export { ENGINE, OPENAPI, OPTIONS, ROUTES };
@@ -0,0 +1,111 @@
1
+ import { NuxtModule } from "@nuxt/schema";
2
+ import { Manifest, ManifestEntry } from "open-apiary";
3
+ /**
4
+ * The options of the Nuxt module.
5
+ *
6
+ * - `package` names the package that `apiary build` produced. The module
7
+ * reads its `manifest.json` at build time and makes one service over its
8
+ * route modules.
9
+ * - `base` is the path that the API mounts at. Defaults to `/api`.
10
+ * - `services` is the file that registers the service classes of the API,
11
+ * relative to the root of the app. Its default export takes the service,
12
+ * and the module calls it once, when the server makes the service.
13
+ *
14
+ * ```ts
15
+ * export default defineNuxtConfig({
16
+ * modules: ["@open-apiary/nuxt"],
17
+ * openApiary: {
18
+ * package: "@acme/api",
19
+ * base: "/api",
20
+ * services: "./server/services.ts",
21
+ * },
22
+ * });
23
+ * ```
24
+ *
25
+ * ```ts
26
+ * // server/services.ts
27
+ * import type { Apiary } from "open-apiary";
28
+ * import { Users } from "@acme/api/contracts";
29
+ *
30
+ * export default (apiary: Apiary) => {
31
+ * apiary.register(Users, PostgresUsers);
32
+ * };
33
+ * ```
34
+ */
35
+ export interface ModuleOptions {
36
+ package?: string;
37
+ base?: string;
38
+ services?: string;
39
+ }
40
+ /** One server handler that the module registers for an endpoint. */
41
+ export interface RouteHandler {
42
+ /** The operation id of the endpoint. */
43
+ id: string;
44
+ /** The route of the Nitro router, under the base. */
45
+ route: string;
46
+ /** The method, in lower case. */
47
+ method: Lowercase<ManifestEntry["method"]>;
48
+ /** The name of the virtual module that holds the handler. */
49
+ handler: string;
50
+ /** The import specifier of the route module of the package. */
51
+ module: string;
52
+ }
53
+ /** Normalizes a base path: one leading slash, no trailing slash, `""` for the root. */
54
+ export declare const normalizeBase: (base: string) => string;
55
+ /**
56
+ * Makes the server handlers of a manifest: one for each endpoint, in the
57
+ * order of the manifest. The route of an endpoint becomes a route of the
58
+ * Nitro router under the base, so `/users/{id}` under `/api` is
59
+ * `/api/users/:id`.
60
+ *
61
+ * @param manifest - The manifest of the package.
62
+ * @param pkg - The name of the package.
63
+ * @param base - The normalized base.
64
+ */
65
+ export declare const routesOf: (manifest: Manifest, pkg: string, base: string) => RouteHandler[];
66
+ /**
67
+ * Makes the source of the virtual module of the service. The module makes
68
+ * one `Apiary` service over a bundle that it writes from the manifest: the
69
+ * data of each endpoint, and a `load` that imports the route module of the
70
+ * package. Each import is dynamic and names one route module, so Nitro
71
+ * makes a chunk for each endpoint, and the service loads a chunk at the
72
+ * first request to its route. The module does not import the entry of the
73
+ * package. When the manifest lists services, the module imports the
74
+ * services module of the package and hands it over in the bundle, so the
75
+ * service holds the classes that the package and its presets ship. With a
76
+ * services file, the module imports its default export and calls it with
77
+ * the service, so the classes are registered before the first call.
78
+ *
79
+ * @param manifest - The manifest of the package.
80
+ * @param pkg - The name of the package.
81
+ * @param runtime - The path of the runtime module that makes the service.
82
+ * @param services - The path of the file that registers the service classes.
83
+ */
84
+ export declare const engineSource: (manifest: Manifest, pkg: string, runtime: string, services?: string) => string;
85
+ /**
86
+ * Makes the source of the virtual module of one route. The module takes the
87
+ * service and makes the handler of one endpoint of it.
88
+ *
89
+ * @param id - The operation id of the endpoint.
90
+ * @param runtime - The path of the runtime module that makes the handler.
91
+ */
92
+ export declare const routeSource: (id: string, runtime: string) => string;
93
+ /**
94
+ * The Nuxt module for open-apiary. The module mounts a package that
95
+ * `apiary build` produced under `base`. It reads the manifest of the package
96
+ * at build time, makes one `Apiary` service over its route modules, and
97
+ * registers one lazy server handler for each endpoint, under its method and
98
+ * its route. Nitro routes a request to the handler, and the service loads
99
+ * the chunk of the endpoint at the first request, so a route loads its own
100
+ * endpoint and no other. Three more handlers complete the API:
101
+ *
102
+ * - `GET <base>/openapi.json` is the OpenAPI document of the package.
103
+ * - `GET <base>/docs` is a Scalar page over the document.
104
+ * - `<base>/**` answers 404 for a request that no endpoint takes. The module
105
+ * leaves it out when the base is the root.
106
+ *
107
+ * The caller comes from `event.context.apiary.caller`. A server middleware
108
+ * sets it from the request. Without one, the caller has no scopes.
109
+ */
110
+ declare const module: NuxtModule<ModuleOptions>;
111
+ export { module as default };
@@ -0,0 +1,126 @@
1
+ import { ENGINE, OPENAPI, OPTIONS, ROUTES } from "./constant.mjs";
2
+ import { createRequire } from "node:module";
3
+ import { readFileSync } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ import { addServerHandler, addServerTemplate, createResolver, defineNuxtModule } from "@nuxt/kit";
6
+ import { normalize, toH3Route } from "@open-apiary/h3";
7
+ const normalizeBase = (base) => normalize(base);
8
+ const routesOf = (manifest, pkg, base) => manifest.endpoints.map((entry) => ({
9
+ id: entry.id,
10
+ route: toH3Route(entry.route, base),
11
+ method: entry.method.toLowerCase(),
12
+ handler: `${ROUTES}/${entry.id}.mjs`,
13
+ module: `${pkg}/routes/${entry.id}`
14
+ }));
15
+ const engineSource = (manifest, pkg, runtime, services) => {
16
+ const lines = [
17
+ `import { makeApiary } from ${JSON.stringify(runtime)};`,
18
+ ...services === void 0 ? [] : [`import services from ${JSON.stringify(services)};`],
19
+ ...manifest.services === void 0 ? [] : [`import shipped from ${JSON.stringify(`${pkg}/services`)};`],
20
+ "",
21
+ "export const apiary = makeApiary({",
22
+ " endpoints: {"
23
+ ];
24
+ for (const entry of manifest.endpoints) {
25
+ const { id, method, route, status, scopes, tags } = entry;
26
+ const data = {
27
+ id,
28
+ method,
29
+ route,
30
+ status,
31
+ scopes,
32
+ tags
33
+ };
34
+ lines.push(` ${JSON.stringify(id)}: {`);
35
+ for (const [key, value] of Object.entries(data)) lines.push(` ${key}: ${JSON.stringify(value)},`);
36
+ lines.push(` load: () => import(${JSON.stringify(`${pkg}/routes/${id}`)}),`);
37
+ lines.push(" },");
38
+ }
39
+ lines.push(" },");
40
+ if (manifest.services !== void 0) lines.push(" services: shipped,");
41
+ lines.push("});", "");
42
+ if (services !== void 0) lines.push("services(apiary);", "");
43
+ return lines.join("\n");
44
+ };
45
+ const routeSource = (id, runtime) => [
46
+ `import { defineApiaryRoute } from ${JSON.stringify(runtime)};`,
47
+ `import { apiary } from ${JSON.stringify(ENGINE)};`,
48
+ "",
49
+ `export default defineApiaryRoute(apiary, ${JSON.stringify(id)});`,
50
+ ""
51
+ ].join("\n");
52
+ const resolveFile = (pkg, file, root) => {
53
+ const require = createRequire(join(root, "package.json"));
54
+ try {
55
+ return require.resolve(`${pkg}/${file}`);
56
+ } catch (cause) {
57
+ throw new Error(`@open-apiary/nuxt: cannot resolve \`${pkg}/${file}\` from ${root}. Run \`apiary build\` in the package, and list \`./${file}\` in its \`exports\`.`, { cause });
58
+ }
59
+ };
60
+ const readManifest = (path) => {
61
+ const manifest = JSON.parse(readFileSync(path, "utf8"));
62
+ if (typeof manifest !== "object" || manifest === null || !Array.isArray(manifest.endpoints)) throw new Error(`@open-apiary/nuxt: ${path} is not a manifest`);
63
+ return manifest;
64
+ };
65
+ const module = defineNuxtModule({
66
+ meta: {
67
+ name: "@open-apiary/nuxt",
68
+ configKey: "openApiary"
69
+ },
70
+ defaults: { base: "/api" },
71
+ setup: (options, nuxt) => {
72
+ if (typeof options.package !== "string" || options.package === "") throw new Error("@open-apiary/nuxt: `package` names the package that `apiary build` produced");
73
+ const resolver = createResolver(import.meta.url);
74
+ const base = normalizeBase(options.base ?? "/api");
75
+ const pkg = options.package;
76
+ const root = nuxt.options.rootDir;
77
+ const manifest = readManifest(resolveFile(pkg, "manifest.json", root));
78
+ const openapi = resolveFile(pkg, "openapi.json", root);
79
+ addServerTemplate({
80
+ filename: OPTIONS,
81
+ getContents: () => `export const base = ${JSON.stringify(base)};\n`
82
+ });
83
+ addServerTemplate({
84
+ filename: OPENAPI,
85
+ getContents: () => `export default ${readFileSync(openapi, "utf8")};\n`
86
+ });
87
+ addServerHandler({
88
+ route: `${base}/openapi.json`,
89
+ method: "get",
90
+ lazy: true,
91
+ handler: resolver.resolve("./runtime/openapi")
92
+ });
93
+ addServerHandler({
94
+ route: `${base}/docs`,
95
+ method: "get",
96
+ lazy: true,
97
+ handler: resolver.resolve("./runtime/docs")
98
+ });
99
+ if (options.services !== void 0 && (typeof options.services !== "string" || options.services === "")) throw new Error("@open-apiary/nuxt: `services` is the path of the file that registers the service classes");
100
+ const services = options.services === void 0 ? void 0 : resolve(root, options.services);
101
+ const engine = resolver.resolve("./runtime/engine");
102
+ addServerTemplate({
103
+ filename: ENGINE,
104
+ getContents: () => engineSource(manifest, pkg, engine, services)
105
+ });
106
+ const runtime = resolver.resolve("./runtime/route");
107
+ for (const route of routesOf(manifest, pkg, base)) {
108
+ addServerTemplate({
109
+ filename: route.handler,
110
+ getContents: () => routeSource(route.id, runtime)
111
+ });
112
+ addServerHandler({
113
+ route: route.route,
114
+ method: route.method,
115
+ lazy: true,
116
+ handler: route.handler
117
+ });
118
+ }
119
+ if (base !== "") addServerHandler({
120
+ route: `${base}/**`,
121
+ lazy: true,
122
+ handler: resolver.resolve("./runtime/missing")
123
+ });
124
+ }
125
+ });
126
+ export { module as default, engineSource, normalizeBase, routeSource, routesOf };
@@ -0,0 +1,4 @@
1
+ import type { EventHandler } from "h3";
2
+ /** Serves the Scalar page, pointed at the document under `base`. */
3
+ declare const handler: EventHandler;
4
+ export default handler;
@@ -0,0 +1 @@
1
+ export * from "./docs.mjs";
@@ -0,0 +1,9 @@
1
+ import { page } from "@open-apiary/h3";
2
+ import { defineEventHandler, setHeader } from "h3";
3
+ import { base } from "#open-apiary/options";
4
+
5
+ const handler = defineEventHandler((event) => {
6
+ setHeader(event, "content-type", "text/html; charset=utf-8");
7
+ return page(`${base}/openapi.json`);
8
+ });
9
+ export default handler;
@@ -0,0 +1 @@
1
+ export { makeApiary } from "open-apiary";
@@ -0,0 +1 @@
1
+ export * from "./engine.mjs";
@@ -0,0 +1,4 @@
1
+
2
+
3
+
4
+ export { makeApiary } from "open-apiary";
@@ -0,0 +1,8 @@
1
+ import type { EventHandler } from "h3";
2
+ /**
3
+ * Answers a request under the base that no endpoint takes: a path with no
4
+ * route, or a method that its route does not have. Without this handler,
5
+ * such a request would reach the page renderer of Nuxt and get an HTML page.
6
+ */
7
+ declare const handler: EventHandler;
8
+ export default handler;
@@ -0,0 +1 @@
1
+ export * from "./missing.mjs";
@@ -0,0 +1,9 @@
1
+ import { createError, defineEventHandler } from "h3";
2
+
3
+ const handler = defineEventHandler(() => {
4
+ throw createError({
5
+ statusCode: 404,
6
+ statusMessage: "Not Found"
7
+ });
8
+ });
9
+ export default handler;
@@ -0,0 +1,4 @@
1
+ import type { EventHandler } from "h3";
2
+ /** Serves the OpenAPI document of the package. */
3
+ declare const handler: EventHandler;
4
+ export default handler;
@@ -0,0 +1 @@
1
+ export * from "./openapi.mjs";
@@ -0,0 +1,5 @@
1
+ import { defineEventHandler } from "h3";
2
+ import document from "#open-apiary/openapi";
3
+
4
+ const handler = defineEventHandler(() => document);
5
+ export default handler;
@@ -0,0 +1 @@
1
+ export { defineApiaryRoute } from "@open-apiary/h3";
@@ -0,0 +1 @@
1
+ export * from "./route.mjs";
@@ -0,0 +1,4 @@
1
+
2
+
3
+
4
+ export { defineApiaryRoute } from "@open-apiary/h3";
package/README.md CHANGED
@@ -1,3 +1,80 @@
1
- # Temporary Holding Version
1
+ # @open-apiary/nuxt
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
+ The Nuxt module for open-apiary. It mounts a package that `apiary build`
4
+ produced, with one server route for each endpoint.
5
+
6
+ ## Install
7
+
8
+ ```sh
9
+ pnpm add @open-apiary/nuxt open-apiary @acme/api
10
+ ```
11
+
12
+ ## Setup
13
+
14
+ ```ts
15
+ // nuxt.config.ts
16
+ export default defineNuxtConfig({
17
+ modules: ["@open-apiary/nuxt"],
18
+ openApiary: { package: "@acme/api", base: "/api" },
19
+ });
20
+ ```
21
+
22
+ - `package` names the package that `apiary build` produced. It exports
23
+ `./manifest.json`, `./openapi.json`, and `./routes/*`.
24
+ - `base` is the path the API mounts at. The default is `/api`.
25
+ - `services` is the file that registers the service classes of the API,
26
+ relative to the root of the app. Its default export takes the service.
27
+ The module calls it once, when the server makes the service.
28
+
29
+ ```ts
30
+ // server/services.ts
31
+ import type { Apiary } from "open-apiary";
32
+ import { Users } from "@acme/api/contracts";
33
+
34
+ export default (apiary: Apiary) => {
35
+ apiary.register(Users, PostgresUsers);
36
+ };
37
+ ```
38
+
39
+ The module reads the manifest of the package at build time. It makes one
40
+ `Apiary` service for the server, in a virtual module, over the data of the
41
+ manifest and one dynamic import for each route module of the package. Then
42
+ it registers:
43
+
44
+ - One lazy server handler for each endpoint, under its method and its
45
+ route: `GET /users/{id}` is `GET <base>/users/:id`. The handler is the
46
+ `defineApiaryRoute` of `@open-apiary/h3` over the service. Nitro writes
47
+ one chunk for each endpoint, and the service loads it at the first
48
+ request to its route. The handler reads the path parameters, the query,
49
+ the headers, and the body, and the service runs the call. An
50
+ `ApiaryError` becomes a response with its status and body.
51
+ - `GET <base>/openapi.json`, the document of the package.
52
+ - `GET <base>/docs`, a Scalar page over it.
53
+ - `<base>/**`, which answers 404 for a request that no endpoint takes. The
54
+ module leaves it out when the base is the root, where it would take the
55
+ pages of the app.
56
+
57
+ When the manifest lists services, the module also imports `<package>/services`
58
+ and hands the list to the service, so the classes that the API and its
59
+ presets ship fill their contracts. The package then exports `./services`.
60
+
61
+ The module reads the built package, so run `apiary build` before the build
62
+ of the app, and again after a change of the API.
63
+
64
+ ## The caller
65
+
66
+ Each handler reads the caller from `event.context.apiary.caller`. A server
67
+ middleware sets it from the request:
68
+
69
+ ```ts
70
+ // server/middleware/auth.ts
71
+ export default defineEventHandler((event) => {
72
+ const token = getHeader(event, "authorization");
73
+ event.context.apiary = {
74
+ caller: { scopes: scopesOf(token), subject: subjectOf(token) },
75
+ };
76
+ });
77
+ ```
78
+
79
+ Without a middleware, the caller has no scopes, and an endpoint with scopes
80
+ answers 403.
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@open-apiary/nuxt",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/zoobzio/open-apiary.git",
7
+ "directory": "integrations/nuxt"
8
+ },
9
+ "type": "module",
10
+ "main": "./.dist/module.mjs",
11
+ "types": "./.dist/module.d.mts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./.dist/module.d.mts",
15
+ "import": "./.dist/module.mjs"
16
+ },
17
+ "./constant": {
18
+ "types": "./.dist/constant.d.mts",
19
+ "import": "./.dist/constant.mjs"
20
+ }
21
+ },
22
+ "files": [
23
+ ".dist"
24
+ ],
25
+ "dependencies": {
26
+ "@nuxt/kit": "^4.4.6",
27
+ "h3": "^1.15.0",
28
+ "@open-apiary/h3": "0.0.1",
29
+ "open-apiary": "0.0.1"
30
+ },
31
+ "devDependencies": {
32
+ "@nuxt/schema": "^4.4.6",
33
+ "@types/node": "^25.9.1",
34
+ "nitropack": "^2.13.0",
35
+ "nuxt": "^4.4.6",
36
+ "zod": "^4.3.0",
37
+ "@open-apiary/testing": "0.0.1"
38
+ },
39
+ "scripts": {
40
+ "build": "obuild",
41
+ "stub": "obuild --stub",
42
+ "lint": "oxlint",
43
+ "typecheck": "tsc --noEmit",
44
+ "test": "vitest run"
45
+ }
6
46
  }