@silkweave/fastify 1.3.1 → 1.4.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.
@@ -1,6 +1,6 @@
1
1
 
2
2
  
3
- > @silkweave/fastify@1.3.0 build /Users/atomic/projects/ai/silkweave/packages/fastify
3
+ > @silkweave/fastify@1.3.2 build /Users/atomic/projects/ai/silkweave/packages/fastify
4
4
  > tsup
5
5
 
6
6
  CLI Building entry: src/index.ts
@@ -10,9 +10,9 @@
10
10
  CLI Target: es2022
11
11
  CLI Cleaning output folder
12
12
  ESM Build start
13
- ESM build/index.js 5.54 KB
14
- ESM build/index.js.map 9.94 KB
15
- ESM ⚡️ Build success in 12ms
13
+ ESM build/index.js 5.35 KB
14
+ ESM build/index.js.map 10.13 KB
15
+ ESM ⚡️ Build success in 7ms
16
16
  DTS Build start
17
- DTS ⚡️ Build success in 1144ms
17
+ DTS ⚡️ Build success in 848ms
18
18
  DTS build/index.d.ts 455.00 B
@@ -1,9 +1,12 @@
1
1
 
2
- > @silkweave/fastify@1.3.0 check /Users/atomic/projects/ai/silkweave/packages/fastify
2
+ > @silkweave/fastify@1.3.2 check /Users/atomic/projects/ai/silkweave/packages/fastify
3
3
  > pnpm lint && pnpm typecheck
4
4
 
5
5
 
6
- > @silkweave/fastify@1.3.0 lint /Users/atomic/projects/ai/silkweave/packages/fastify
6
+ > @silkweave/fastify@1.3.2 lint /Users/atomic/projects/ai/silkweave/packages/fastify
7
7
  > eslint
8
8
 
9
-  ELIFECYCLE  Command failed.
9
+
10
+ > @silkweave/fastify@1.3.2 typecheck /Users/atomic/projects/ai/silkweave/packages/fastify
11
+ > tsc --noEmit
12
+
@@ -1,5 +1,5 @@
1
1
 
2
2
  
3
- > @silkweave/fastify@1.3.0 lint /Users/atomic/projects/ai/silkweave/packages/fastify
3
+ > @silkweave/fastify@1.3.2 lint /Users/atomic/projects/ai/silkweave/packages/fastify
4
4
  > eslint
5
5
 
@@ -1,14 +1,14 @@
1
1
 
2
2
  
3
- > @silkweave/fastify@1.3.0 prepack /Users/atomic/projects/ai/silkweave/packages/fastify
3
+ > @silkweave/fastify@1.4.0 prepack /Users/atomic/projects/ai/silkweave/packages/fastify
4
4
  > pnpm clean && pnpm build
5
5
 
6
6
 
7
- > @silkweave/fastify@1.3.0 clean /Users/atomic/projects/ai/silkweave/packages/fastify
7
+ > @silkweave/fastify@1.4.0 clean /Users/atomic/projects/ai/silkweave/packages/fastify
8
8
  > rimraf build
9
9
 
10
10
 
11
- > @silkweave/fastify@1.3.0 build /Users/atomic/projects/ai/silkweave/packages/fastify
11
+ > @silkweave/fastify@1.4.0 build /Users/atomic/projects/ai/silkweave/packages/fastify
12
12
  > tsup
13
13
 
14
14
  CLI Building entry: src/index.ts
@@ -18,9 +18,9 @@
18
18
  CLI Target: es2022
19
19
  CLI Cleaning output folder
20
20
  ESM Build start
21
- ESM build/index.js 5.54 KB
22
- ESM build/index.js.map 9.94 KB
23
- ESM ⚡️ Build success in 13ms
21
+ ESM build/index.js 5.35 KB
22
+ ESM build/index.js.map 10.13 KB
23
+ ESM ⚡️ Build success in 7ms
24
24
  DTS Build start
25
- DTS ⚡️ Build success in 984ms
25
+ DTS ⚡️ Build success in 847ms
26
26
  DTS build/index.d.ts 455.00 B
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @silkweave/fastify
2
2
 
3
- Fastify REST adapter for [Silkweave](https://github.com/silkweave/silkweave) expose your actions as a REST API with auto-generated OpenAPI/Swagger documentation.
3
+ Fastify REST adapter for [Silkweave](https://github.com/silkweave/silkweave) - expose your actions as a REST API with auto-generated OpenAPI/Swagger documentation.
4
4
 
5
5
  ## Install
6
6
 
@@ -56,5 +56,5 @@ fastify({
56
56
 
57
57
  ## See Also
58
58
 
59
- - [Silkweave README](https://github.com/silkweave/silkweave) Full documentation
60
- - [`@silkweave/core`](https://www.npmjs.com/package/@silkweave/core) Core library
59
+ - [Silkweave README](https://github.com/silkweave/silkweave) - Full documentation
60
+ - [`@silkweave/core`](https://www.npmjs.com/package/@silkweave/core) - Core library
package/build/index.js CHANGED
@@ -14,6 +14,75 @@ var PINO_LEVEL_MAP = {
14
14
  info: "info",
15
15
  debug: "debug"
16
16
  };
17
+ function toOAuthReq(request) {
18
+ return {
19
+ method: request.method,
20
+ url: new URL(request.url, `http://${request.hostname}`),
21
+ headers: Object.fromEntries(Object.entries(request.headers).map(([k, v]) => [k, Array.isArray(v) ? v[0] : v])),
22
+ body: request.body
23
+ };
24
+ }
25
+ function sendOAuth(reply, oauthRes) {
26
+ for (const [key, value] of Object.entries(oauthRes.headers)) {
27
+ reply.header(key, value);
28
+ }
29
+ return reply.status(oauthRes.status).send(oauthRes.body);
30
+ }
31
+ function mountOAuthRoutes(instance, auth) {
32
+ const provider = auth.provider;
33
+ const paths = /* @__PURE__ */ new Set([
34
+ "/.well-known/oauth-authorization-server",
35
+ "/authorize",
36
+ "/auth/callback",
37
+ "/token",
38
+ "/register"
39
+ ]);
40
+ instance.get("/.well-known/oauth-authorization-server", async (_req, reply) => {
41
+ return sendOAuth(reply, provider.metadata());
42
+ });
43
+ instance.get("/authorize", async (req, reply) => {
44
+ return sendOAuth(reply, await provider.authorize(toOAuthReq(req)));
45
+ });
46
+ instance.get("/auth/callback", async (req, reply) => {
47
+ return sendOAuth(reply, await provider.callback(toOAuthReq(req)));
48
+ });
49
+ instance.post("/token", async (req, reply) => {
50
+ return sendOAuth(reply, await provider.token(toOAuthReq(req)));
51
+ });
52
+ instance.post("/register", async (req, reply) => {
53
+ return sendOAuth(reply, await provider.register(toOAuthReq(req)));
54
+ });
55
+ return paths;
56
+ }
57
+ function mountAuthMiddleware(instance, auth, oauthPaths, context) {
58
+ instance.decorateRequest("__silkweave_auth", void 0);
59
+ instance.addHook("onRequest", async (request, reply) => {
60
+ if (request.url.startsWith("/.well-known/") || oauthPaths.has(request.url.split("?")[0])) {
61
+ return;
62
+ }
63
+ const result = await validateToken(request.headers.authorization, auth, context.fork({ request }));
64
+ if (result.error) {
65
+ for (const [key, value] of Object.entries(result.error.headers)) {
66
+ reply.header(key, value);
67
+ }
68
+ return reply.status(result.error.statusCode).send(result.error.body);
69
+ }
70
+ if (result.auth) {
71
+ request.__silkweave_auth = result.auth;
72
+ }
73
+ });
74
+ }
75
+ function createActionLogger(instance) {
76
+ return {
77
+ ...buildLogLevels((level, data) => {
78
+ const pinoLevel = PINO_LEVEL_MAP[level] ?? "info";
79
+ instance.log[pinoLevel](data);
80
+ }),
81
+ progress: ({ progress, total, message }) => {
82
+ instance.log.trace({ progress, total }, message);
83
+ }
84
+ };
85
+ }
17
86
  var fastify = ({ host, port, auth, ...fastifyOptions }) => {
18
87
  const instance = fastifyInstance(fastifyOptions);
19
88
  return (options, baseContext) => {
@@ -36,59 +105,9 @@ var fastify = ({ host, port, auth, ...fastifyOptions }) => {
36
105
  return generateProtectedResourceMetadata(auth.resourceUrl, auth.authorizationServers);
37
106
  });
38
107
  }
39
- const oauthPaths = /* @__PURE__ */ new Set();
40
- if (auth?.provider) {
41
- const provider = auth.provider;
42
- const toOAuthReq = (request) => ({
43
- method: request.method,
44
- url: new URL(request.url, `http://${request.hostname}`),
45
- headers: Object.fromEntries(Object.entries(request.headers).map(([k, v]) => [k, Array.isArray(v) ? v[0] : v])),
46
- body: request.body
47
- });
48
- const sendOAuth = (reply, oauthRes) => {
49
- for (const [key, value] of Object.entries(oauthRes.headers)) {
50
- reply.header(key, value);
51
- }
52
- return reply.status(oauthRes.status).send(oauthRes.body);
53
- };
54
- oauthPaths.add("/.well-known/oauth-authorization-server");
55
- oauthPaths.add("/authorize");
56
- oauthPaths.add("/auth/callback");
57
- oauthPaths.add("/token");
58
- oauthPaths.add("/register");
59
- instance.get("/.well-known/oauth-authorization-server", async (_req, reply) => {
60
- return sendOAuth(reply, provider.metadata());
61
- });
62
- instance.get("/authorize", async (req, reply) => {
63
- return sendOAuth(reply, await provider.authorize(toOAuthReq(req)));
64
- });
65
- instance.get("/auth/callback", async (req, reply) => {
66
- return sendOAuth(reply, await provider.callback(toOAuthReq(req)));
67
- });
68
- instance.post("/token", async (req, reply) => {
69
- return sendOAuth(reply, await provider.token(toOAuthReq(req)));
70
- });
71
- instance.post("/register", async (req, reply) => {
72
- return sendOAuth(reply, await provider.register(toOAuthReq(req)));
73
- });
74
- }
108
+ const oauthPaths = auth?.provider ? mountOAuthRoutes(instance, auth) : /* @__PURE__ */ new Set();
75
109
  if (auth) {
76
- instance.decorateRequest("__silkweave_auth", void 0);
77
- instance.addHook("onRequest", async (request, reply) => {
78
- if (request.url.startsWith("/.well-known/") || oauthPaths.has(request.url.split("?")[0])) {
79
- return;
80
- }
81
- const result = await validateToken(request.headers.authorization, auth);
82
- if (result.error) {
83
- for (const [key, value] of Object.entries(result.error.headers)) {
84
- reply.header(key, value);
85
- }
86
- return reply.status(result.error.statusCode).send(result.error.body);
87
- }
88
- if (result.auth) {
89
- request.__silkweave_auth = result.auth;
90
- }
91
- });
110
+ mountAuthMiddleware(instance, auth, oauthPaths, context);
92
111
  }
93
112
  instance.setErrorHandler((error, _request, reply) => {
94
113
  if (error instanceof SilkweaveError) {
@@ -100,6 +119,7 @@ var fastify = ({ host, port, auth, ...fastifyOptions }) => {
100
119
  instance.log.error(error);
101
120
  return reply.status(500).send({ error: "internal", message: "Internal server error" });
102
121
  });
122
+ const logger = createActionLogger(instance);
103
123
  for (const action of actions) {
104
124
  const schema = action.input.toJSONSchema();
105
125
  instance.post(`/${action.name}`, {
@@ -115,15 +135,6 @@ var fastify = ({ host, port, auth, ...fastifyOptions }) => {
115
135
  }
116
136
  }
117
137
  }, (request) => {
118
- const logger = {
119
- ...buildLogLevels((level, data) => {
120
- const pinoLevel = PINO_LEVEL_MAP[level] ?? "info";
121
- instance.log[pinoLevel](data);
122
- }),
123
- progress: ({ progress, total, message }) => {
124
- instance.log.trace({ progress, total }, message);
125
- }
126
- };
127
138
  const authInfo = auth ? request.__silkweave_auth : void 0;
128
139
  return action.run(request.body, context.fork({ logger, request, ...authInfo ? { auth: authInfo } : {} }));
129
140
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapter/fastify.ts"],"sourcesContent":["import { AuthConfig, AuthInfo, generateProtectedResourceMetadata, OAuthRequest, OAuthResponse, validateToken } from '@silkweave/auth'\nimport { AdapterFactory, SilkweaveError } from '@silkweave/core'\nimport { buildLogLevels, Logger, LogLevel } from '@silkweave/logger'\nimport { FastifyBaseLogger, FastifyHttpOptions, fastify as fastifyInstance, FastifyReply, FastifyRequest } from 'fastify'\nimport { Server } from 'http'\nimport z from 'zod'\n\ntype FastifyLogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'\n\nconst PINO_LEVEL_MAP: Record<LogLevel, FastifyLogLevel> = {\n emergency: 'fatal',\n alert: 'fatal',\n critical: 'fatal',\n error: 'error',\n warning: 'warn',\n notice: 'debug',\n info: 'info',\n debug: 'debug'\n}\n\nexport interface FastifyAdapterOptions extends FastifyHttpOptions<Server, FastifyBaseLogger> {\n host?: string\n port?: number\n auth?: AuthConfig\n}\n\nexport const fastify: AdapterFactory<FastifyAdapterOptions> = ({ host, port, auth, ...fastifyOptions }) => {\n const instance = fastifyInstance(fastifyOptions)\n return (options, baseContext) => {\n const context = baseContext.fork({ adapter: 'fastify' })\n return {\n context,\n start: async (actions) => {\n await instance.register(import('@fastify/swagger'), {\n openapi: {\n info: {\n title: options.name,\n description: options.description,\n version: options.version\n }\n }\n })\n await instance.register(import('@scalar/fastify-api-reference'), { routePrefix: '/' as `/${string}` })\n\n if (auth?.authorizationServers?.length && auth.resourceUrl) {\n instance.get('/.well-known/oauth-protected-resource', () => {\n return generateProtectedResourceMetadata(auth.resourceUrl!, auth.authorizationServers!)\n })\n }\n\n const oauthPaths = new Set<string>()\n if (auth?.provider) {\n const provider = auth.provider\n const toOAuthReq = (request: FastifyRequest): OAuthRequest => ({\n method: request.method,\n url: new URL(request.url, `http://${request.hostname}`),\n headers: Object.fromEntries(Object.entries(request.headers).map(([k, v]) => [k, Array.isArray(v) ? v[0] : v])),\n body: request.body as Record<string, string> | undefined\n })\n const sendOAuth = (reply: FastifyReply, oauthRes: OAuthResponse) => {\n for (const [key, value] of Object.entries(oauthRes.headers)) { reply.header(key, value) }\n return reply.status(oauthRes.status).send(oauthRes.body)\n }\n\n oauthPaths.add('/.well-known/oauth-authorization-server')\n oauthPaths.add('/authorize')\n oauthPaths.add('/auth/callback')\n oauthPaths.add('/token')\n oauthPaths.add('/register')\n\n instance.get('/.well-known/oauth-authorization-server', async (_req, reply) => {\n return sendOAuth(reply, provider.metadata())\n })\n instance.get('/authorize', async (req, reply) => {\n return sendOAuth(reply, await provider.authorize(toOAuthReq(req)))\n })\n instance.get('/auth/callback', async (req, reply) => {\n return sendOAuth(reply, await provider.callback(toOAuthReq(req)))\n })\n instance.post('/token', async (req, reply) => {\n return sendOAuth(reply, await provider.token(toOAuthReq(req)))\n })\n instance.post('/register', async (req, reply) => {\n return sendOAuth(reply, await provider.register(toOAuthReq(req)))\n })\n }\n\n if (auth) {\n instance.decorateRequest('__silkweave_auth', undefined)\n instance.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {\n if (request.url.startsWith('/.well-known/') || oauthPaths.has(request.url.split('?')[0])) { return }\n const result = await validateToken(request.headers.authorization, auth)\n if (result.error) {\n for (const [key, value] of Object.entries(result.error.headers)) {\n reply.header(key, value)\n }\n return reply.status(result.error.statusCode).send(result.error.body)\n }\n if (result.auth) {\n (request as FastifyRequest & { __silkweave_auth?: AuthInfo }).__silkweave_auth = result.auth\n }\n })\n }\n\n instance.setErrorHandler((error, _request, reply) => {\n if (error instanceof SilkweaveError) {\n return reply.status(error.statusCode).send({ error: error.code, message: error.message })\n }\n if (error instanceof z.ZodError) {\n return reply.status(400).send({ error: 'validation_error', issues: error.issues })\n }\n instance.log.error(error)\n return reply.status(500).send({ error: 'internal', message: 'Internal server error' })\n })\n\n for (const action of actions) {\n const schema = action.input.toJSONSchema()\n instance.post(`/${action.name}`, {\n schema: {\n description: action.description,\n body: {\n type: 'object',\n properties: schema.properties,\n required: schema.required\n },\n response: {\n 200: { description: 'Successful response' }\n }\n }\n }, (request) => {\n const logger: Logger = {\n ...buildLogLevels((level, data) => {\n const pinoLevel = PINO_LEVEL_MAP[level] ?? 'info'\n instance.log[pinoLevel](data)\n }),\n progress: ({ progress, total, message }) => { instance.log.trace({ progress, total }, message) }\n }\n const authInfo = auth ? (request as FastifyRequest & { __silkweave_auth?: AuthInfo }).__silkweave_auth : undefined\n return action.run(request.body, context.fork({ logger, request, ...(authInfo ? { auth: authInfo } : {}) }))\n })\n }\n await instance.listen({ host, port })\n },\n stop: async () => { await instance.close() }\n }\n }\n}\n"],"mappings":";AAAA,SAA+B,mCAAgE,qBAAqB;AACpH,SAAyB,sBAAsB;AAC/C,SAAS,sBAAwC;AACjD,SAAgD,WAAW,uBAAqD;AAEhH,OAAO,OAAO;AAId,IAAM,iBAAoD;AAAA,EACxD,WAAW;AAAA,EACX,OAAO;AAAA,EACP,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AACT;AAQO,IAAM,UAAiD,CAAC,EAAE,MAAM,MAAM,MAAM,GAAG,eAAe,MAAM;AACzG,QAAM,WAAW,gBAAgB,cAAc;AAC/C,SAAO,CAAC,SAAS,gBAAgB;AAC/B,UAAM,UAAU,YAAY,KAAK,EAAE,SAAS,UAAU,CAAC;AACvD,WAAO;AAAA,MACL;AAAA,MACA,OAAO,OAAO,YAAY;AACxB,cAAM,SAAS,SAAS,OAAO,kBAAkB,GAAG;AAAA,UAClD,SAAS;AAAA,YACP,MAAM;AAAA,cACJ,OAAO,QAAQ;AAAA,cACf,aAAa,QAAQ;AAAA,cACrB,SAAS,QAAQ;AAAA,YACnB;AAAA,UACF;AAAA,QACF,CAAC;AACD,cAAM,SAAS,SAAS,OAAO,+BAA+B,GAAG,EAAE,aAAa,IAAoB,CAAC;AAErG,YAAI,MAAM,sBAA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, OAuthRequest, OAuthResponse, validateToken } from '@silkweave/auth'\nimport { AdapterFactory, SilkweaveContext, SilkweaveError } from '@silkweave/core'\nimport { buildLogLevels, Logger, LogLevel } from '@silkweave/logger'\nimport { FastifyBaseLogger, FastifyHttpOptions, fastify as fastifyInstance, FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'\nimport { Server } from 'http'\nimport z from 'zod'\n\ntype FastifyLogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'\n\nconst PINO_LEVEL_MAP: Record<LogLevel, FastifyLogLevel> = {\n emergency: 'fatal',\n alert: 'fatal',\n critical: 'fatal',\n error: 'error',\n warning: 'warn',\n notice: 'debug',\n info: 'info',\n debug: 'debug'\n}\n\nexport interface FastifyAdapterOptions extends FastifyHttpOptions<Server, FastifyBaseLogger> {\n host?: string\n port?: number\n auth?: AuthConfig\n}\n\nfunction toOAuthReq(request: FastifyRequest): OAuthRequest {\n return {\n method: request.method,\n url: new URL(request.url, `http://${request.hostname}`),\n headers: Object.fromEntries(Object.entries(request.headers).map(([k, v]) => [k, Array.isArray(v) ? v[0] : v])),\n body: request.body as Record<string, string> | undefined\n }\n}\n\nfunction sendOAuth(reply: FastifyReply, oauthRes: OAuthResponse) {\n for (const [key, value] of Object.entries(oauthRes.headers)) { reply.header(key, value) }\n return reply.status(oauthRes.status).send(oauthRes.body)\n}\n\nfunction mountOAuthRoutes(instance: FastifyInstance, auth: AuthConfig): Set<string> {\n const provider = auth.provider!\n\n const paths = new Set([\n '/.well-known/oauth-authorization-server',\n '/authorize',\n '/auth/callback',\n '/token',\n '/register'\n ])\n\n instance.get('/.well-known/oauth-authorization-server', async (_req, reply) => {\n return sendOAuth(reply, provider.metadata())\n })\n instance.get('/authorize', async (req, reply) => {\n return sendOAuth(reply, await provider.authorize(toOAuthReq(req)))\n })\n instance.get('/auth/callback', async (req, reply) => {\n return sendOAuth(reply, await provider.callback(toOAuthReq(req)))\n })\n instance.post('/token', async (req, reply) => {\n return sendOAuth(reply, await provider.token(toOAuthReq(req)))\n })\n instance.post('/register', async (req, reply) => {\n return sendOAuth(reply, await provider.register(toOAuthReq(req)))\n })\n\n return paths\n}\n\nfunction mountAuthMiddleware(instance: FastifyInstance, auth: AuthConfig, oauthPaths: Set<string>, context: SilkweaveContext) {\n instance.decorateRequest('__silkweave_auth', undefined)\n instance.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {\n if (request.url.startsWith('/.well-known/') || oauthPaths.has(request.url.split('?')[0])) { return }\n const result = await validateToken(request.headers.authorization, auth, context.fork({ request }))\n if (result.error) {\n for (const [key, value] of Object.entries(result.error.headers)) {\n reply.header(key, value)\n }\n return reply.status(result.error.statusCode).send(result.error.body)\n }\n if (result.auth) {\n (request as FastifyRequest & { __silkweave_auth?: AuthInfo }).__silkweave_auth = result.auth\n }\n })\n}\n\nfunction createActionLogger(instance: FastifyInstance): Logger {\n return {\n ...buildLogLevels((level, data) => {\n const pinoLevel = PINO_LEVEL_MAP[level] ?? 'info'\n instance.log[pinoLevel](data)\n }),\n progress: ({ progress, total, message }) => { instance.log.trace({ progress, total }, message) }\n }\n}\n\nexport const fastify: AdapterFactory<FastifyAdapterOptions> = ({ host, port, auth, ...fastifyOptions }) => {\n const instance = fastifyInstance(fastifyOptions)\n return (options, baseContext) => {\n const context = baseContext.fork({ adapter: 'fastify' })\n return {\n context,\n start: async (actions) => {\n await instance.register(import('@fastify/swagger'), {\n openapi: {\n info: {\n title: options.name,\n description: options.description,\n version: options.version\n }\n }\n })\n await instance.register(import('@scalar/fastify-api-reference'), { routePrefix: '/' as `/${string}` })\n\n if (auth?.authorizationServers?.length && auth.resourceUrl) {\n instance.get('/.well-known/oauth-protected-resource', () => {\n return generateProtectedResourceMetadata(auth.resourceUrl!, auth.authorizationServers!)\n })\n }\n\n const oauthPaths = auth?.provider ? mountOAuthRoutes(instance, auth) : new Set<string>()\n\n if (auth) {\n mountAuthMiddleware(instance, auth, oauthPaths, context)\n }\n\n instance.setErrorHandler((error, _request, reply) => {\n if (error instanceof SilkweaveError) {\n return reply.status(error.statusCode).send({ error: error.code, message: error.message })\n }\n if (error instanceof z.ZodError) {\n return reply.status(400).send({ error: 'validation_error', issues: error.issues })\n }\n instance.log.error(error)\n return reply.status(500).send({ error: 'internal', message: 'Internal server error' })\n })\n\n const logger = createActionLogger(instance)\n\n for (const action of actions) {\n const schema = action.input.toJSONSchema()\n instance.post(`/${action.name}`, {\n schema: {\n description: action.description,\n body: {\n type: 'object',\n properties: schema.properties,\n required: schema.required\n },\n response: {\n 200: { description: 'Successful response' }\n }\n }\n }, (request) => {\n const authInfo = auth ? (request as FastifyRequest & { __silkweave_auth?: AuthInfo }).__silkweave_auth : undefined\n return action.run(request.body, context.fork({ logger, request, ...(authInfo ? { auth: authInfo } : {}) }))\n })\n }\n await instance.listen({ host, port })\n },\n stop: async () => { await instance.close() }\n }\n }\n}\n"],"mappings":";AAAA,SAA+B,mCAAgE,qBAAqB;AACpH,SAA2C,sBAAsB;AACjE,SAAS,sBAAwC;AACjD,SAAgD,WAAW,uBAAsE;AAEjI,OAAO,OAAO;AAId,IAAM,iBAAoD;AAAA,EACxD,WAAW;AAAA,EACX,OAAO;AAAA,EACP,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AACT;AAQA,SAAS,WAAW,SAAuC;AACzD,SAAO;AAAA,IACL,QAAQ,QAAQ;AAAA,IAChB,KAAK,IAAI,IAAI,QAAQ,KAAK,UAAU,QAAQ,QAAQ,EAAE;AAAA,IACtD,SAAS,OAAO,YAAY,OAAO,QAAQ,QAAQ,OAAO,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;AAAA,IAC7G,MAAM,QAAQ;AAAA,EAChB;AACF;AAEA,SAAS,UAAU,OAAqB,UAAyB;AAC/D,aAAW,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,EAAE,MAAM,SAAS,IAAI,CAAC,EAAG,CAAC,CAAC;AAAA,UAC5G,CAAC;AAAA,QACH;AACA,cAAM,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;AAAA,MACtC;AAAA,MACA,MAAM,YAAY;AAAE,cAAM,SAAS,MAAM;AAAA,MAAE;AAAA,IAC7C;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@silkweave/fastify",
3
- "version": "1.3.1",
3
+ "version": "1.4.0",
4
4
  "description": "Silkweave Fastify REST Adapter",
5
5
  "repository": {
6
6
  "type": "git",
@@ -15,9 +15,9 @@
15
15
  "@scalar/fastify-api-reference": "^1.49.0",
16
16
  "fastify": "^5.8.2",
17
17
  "zod": "^4.3.6",
18
- "@silkweave/auth": "1.3.1",
19
- "@silkweave/logger": "1.3.1",
20
- "@silkweave/core": "1.3.1"
18
+ "@silkweave/auth": "1.4.0",
19
+ "@silkweave/logger": "1.4.0",
20
+ "@silkweave/core": "1.4.0"
21
21
  },
22
22
  "devDependencies": {
23
23
  "@eslint/js": "^10.0.1",