@open-norantec/utilities 2.4.4 → 2.6.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.
@@ -0,0 +1,51 @@
1
+ import { Context, ExecutionContext, Hono } from 'hono';
2
+ import { z } from './zod';
3
+ import { Bindings as BindingsType } from 'hono/types';
4
+ import { PartialDeep } from 'type-fest';
5
+ import { ContentfulStatusCode } from 'hono/utils/http-status';
6
+ import { OpenAPIObject } from 'openapi3-ts/oas31';
7
+ type HTTPBodyType = z.ZodType<any> | string;
8
+ export declare class StatusError extends Error {
9
+ readonly status: ContentfulStatusCode;
10
+ readonly statusText?: string | undefined;
11
+ constructor(status: ContentfulStatusCode, statusText?: string | undefined);
12
+ }
13
+ type BaseContext<Bindings extends BindingsType, SS extends z.ZodObject> = {
14
+ env: Bindings;
15
+ executionCtx: ExecutionContext;
16
+ headers: Record<string, string>;
17
+ storage: z.infer<SS>;
18
+ queries: Context['req']['queries'];
19
+ query: Context['req']['query'];
20
+ };
21
+ interface AuthenticationMethod<Bindings extends BindingsType, SS extends z.ZodObject> {
22
+ match(authorizationHeaderValue?: string): string | undefined;
23
+ authenticate(context: BaseContext<Bindings, SS>, authenticationValue?: string): string | false | Promise<string | false>;
24
+ }
25
+ type AuthenticationMethodMap<Bindings extends BindingsType, SS extends z.ZodObject> = Record<string, AuthenticationMethod<Bindings, SS>>;
26
+ type AuthKey<AMM extends AuthenticationMethodMap<{}, z.ZodObject>> = Extract<keyof AMM, string>;
27
+ type HandlerContext<IS extends HTTPBodyType, Bindings extends BindingsType, SS extends z.ZodObject, A extends Array<keyof AuthenticationMethodMap<Bindings, SS>>> = BaseContext<Bindings, SS> & {
28
+ authentication: A extends [] ? null : A[number];
29
+ authenticationValue: string | null;
30
+ input: IS extends string ? ReadableStreamDefaultReader<Uint8Array> : z.infer<IS>;
31
+ };
32
+ interface HookContext {
33
+ use: typeof Hono.prototype.use;
34
+ }
35
+ export declare class HonoUtil {
36
+ static createHelper<Bindings extends BindingsType>(): <SS extends z.ZodObject, AMM extends AuthenticationMethodMap<Bindings, SS>>({ storageSchema, openAPIObject, openAPIPath, openAPIPrefix, authenticationMethods, onAfterSetRoutes, onBeforeSetRoutes, }: {
37
+ storageSchema: SS;
38
+ authenticationMethods?: AMM;
39
+ openAPIObject?: PartialDeep<Omit<OpenAPIObject, "paths">>;
40
+ openAPIPath?: string;
41
+ openAPIPrefix?: string;
42
+ onAfterSetRoutes?: (context: HookContext) => void;
43
+ onBeforeSetRoutes?: (context: HookContext) => void;
44
+ }) => {
45
+ register: <IS extends HTTPBodyType, OS extends HTTPBodyType, const A extends Array<AuthKey<AMM>>>(pathname: string, inputSchema: IS, outputSchema: OS, authenticationTypes: A, handler: (context: HandlerContext<IS, Bindings, SS, A>) => Promise<z.infer<OS>>) => void;
46
+ getApp: () => Hono<{
47
+ Bindings: Bindings;
48
+ }, import("hono/types").BlankSchema, "/">;
49
+ };
50
+ }
51
+ export {};
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.HonoUtil = exports.StatusError = void 0;
46
+ const hono_1 = require("hono");
47
+ const zod_1 = require("./zod");
48
+ const attempt_util_class_1 = require("./attempt-util.class");
49
+ const _ = __importStar(require("lodash"));
50
+ class StatusError extends Error {
51
+ constructor(status, statusText) {
52
+ super();
53
+ this.status = status;
54
+ this.statusText = statusText;
55
+ }
56
+ }
57
+ exports.StatusError = StatusError;
58
+ class HonoUtil {
59
+ static createHelper() {
60
+ return function ({ storageSchema, openAPIObject = {}, openAPIPath = '/openapi', openAPIPrefix = '', authenticationMethods, onAfterSetRoutes, onBeforeSetRoutes, }) {
61
+ const config = {};
62
+ return {
63
+ register: function (pathname, inputSchema, outputSchema, authenticationTypes, handler) {
64
+ config[pathname] = {
65
+ inputSchema,
66
+ outputSchema,
67
+ authenticationTypes,
68
+ handler,
69
+ };
70
+ },
71
+ getApp: function () {
72
+ const app = new hono_1.Hono();
73
+ const hookContext = { use: app.use.bind(app) };
74
+ const openAPIDocument = _.merge({
75
+ openapi: '3.1.0',
76
+ info: {
77
+ title: 'API Documentation',
78
+ version: '1.0.0',
79
+ },
80
+ paths: {},
81
+ }, _.omit(openAPIObject, ['paths']));
82
+ onBeforeSetRoutes === null || onBeforeSetRoutes === void 0 ? void 0 : onBeforeSetRoutes(hookContext);
83
+ Object.entries(config).forEach(([pathname, { inputSchema, outputSchema, authenticationTypes, handler }]) => {
84
+ openAPIDocument.paths[`${openAPIPrefix}${pathname}`.replace(/^\/+/g, '/')] = {
85
+ post: {
86
+ requestBody: {
87
+ required: true,
88
+ content: typeof inputSchema === 'string'
89
+ ? {
90
+ [inputSchema]: {},
91
+ }
92
+ : {
93
+ 'application/json': { schema: inputSchema.toJSONSchema() },
94
+ },
95
+ },
96
+ responses: {
97
+ '200': {
98
+ content: typeof outputSchema === 'string'
99
+ ? {
100
+ [outputSchema]: {},
101
+ }
102
+ : {
103
+ 'application/json': {
104
+ schema: zod_1.z
105
+ .object({
106
+ data: outputSchema,
107
+ })
108
+ .toJSONSchema(),
109
+ },
110
+ },
111
+ },
112
+ },
113
+ },
114
+ };
115
+ app.post(pathname, (c) => __awaiter(this, void 0, void 0, function* () {
116
+ const input = typeof inputSchema === 'string' ? c.req.raw.body.getReader() : inputSchema.parse(yield c.req.json());
117
+ const headers = c.req.header();
118
+ const baseContext = {
119
+ headers,
120
+ env: c.env,
121
+ executionCtx: c.executionCtx,
122
+ storage: storageSchema.parse(Object.keys(storageSchema.shape).reduce((result, key) => {
123
+ result[key] = c.get(key);
124
+ return result;
125
+ }, {})),
126
+ query: c.req.query.bind(c.req),
127
+ queries: c.req.queries.bind(c.req),
128
+ };
129
+ const { authentication, authenticationValue } = yield (() => __awaiter(this, void 0, void 0, function* () {
130
+ let authenticationValue = null;
131
+ if (!Array.isArray(authenticationTypes) || authenticationTypes.length === 0) {
132
+ return {
133
+ authenticationValue,
134
+ authentication: null,
135
+ };
136
+ }
137
+ const authorizationHeaderValue = c.req.header('Authorization');
138
+ const finalResult = yield Promise.all(authenticationTypes.map((authenticationType) => {
139
+ var _a, _b;
140
+ const instance = authenticationMethods === null || authenticationMethods === void 0 ? void 0 : authenticationMethods[authenticationType];
141
+ const matched = (_a = instance === null || instance === void 0 ? void 0 : instance.match) === null || _a === void 0 ? void 0 : _a.call(instance, authorizationHeaderValue);
142
+ if (typeof matched !== 'string') {
143
+ return { type: authenticationType, result: false };
144
+ }
145
+ return Promise.resolve((_b = instance === null || instance === void 0 ? void 0 : instance.authenticate) === null || _b === void 0 ? void 0 : _b.call(instance, baseContext, matched)).then((result) => ({
146
+ type: authenticationType,
147
+ result,
148
+ }));
149
+ })).then((results) => results.find(({ result }) => typeof result === 'string'));
150
+ if (!(finalResult === null || finalResult === void 0 ? void 0 : finalResult.type))
151
+ throw new StatusError(401);
152
+ return { authenticationValue: finalResult.result, authentication: finalResult.type };
153
+ }))();
154
+ const rawOutput = yield attempt_util_class_1.AttemptUtil.execPromise(handler(Object.assign({ input, authentication: authentication, authenticationValue }, baseContext)));
155
+ if (rawOutput instanceof Error) {
156
+ console.log('Handler error', rawOutput, rawOutput === null || rawOutput === void 0 ? void 0 : rawOutput.message, rawOutput === null || rawOutput === void 0 ? void 0 : rawOutput.stack);
157
+ return c.json({ error: rawOutput.message }, rawOutput instanceof StatusError ? rawOutput.status : 400);
158
+ }
159
+ if (typeof outputSchema === 'string') {
160
+ return c.body(rawOutput, 200, { 'Content-Type': outputSchema });
161
+ }
162
+ else {
163
+ const output = attempt_util_class_1.AttemptUtil.exec(() => outputSchema.parse(rawOutput));
164
+ if (output instanceof Error) {
165
+ console.log('Return error', output, output === null || output === void 0 ? void 0 : output.message, output === null || output === void 0 ? void 0 : output.stack);
166
+ return c.json({ error: output.message }, 400);
167
+ }
168
+ return c.json({ data: output });
169
+ }
170
+ }));
171
+ });
172
+ app.get(openAPIPath, (c) => __awaiter(this, void 0, void 0, function* () { return c.json(openAPIDocument); }));
173
+ onAfterSetRoutes === null || onAfterSetRoutes === void 0 ? void 0 : onAfterSetRoutes(hookContext);
174
+ return app;
175
+ },
176
+ };
177
+ };
178
+ }
179
+ }
180
+ exports.HonoUtil = HonoUtil;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-norantec/utilities",
3
- "version": "2.4.4",
3
+ "version": "2.6.0",
4
4
  "description": "NoranTec Utilities",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -36,6 +36,7 @@
36
36
  "@types/node": "18.11.18",
37
37
  "cross-env": "^7.0.3",
38
38
  "eslint": "^10.3.0",
39
+ "hono": "^4.13.2",
39
40
  "octokit": "^5.0.5",
40
41
  "rimraf": "^6.0.1",
41
42
  "ts-node": "^10.0.0",
@@ -50,16 +51,21 @@
50
51
  "eslint-config-prettier": "^10.0.0",
51
52
  "eslint-plugin-prettier": "^5.0.0",
52
53
  "lodash": "^4.18.1",
54
+ "openapi3-ts": "^4.6.1",
53
55
  "prettier": "^3.0.0",
54
56
  "uuid": "^11.1.0",
55
57
  "zod": "^4.4.3"
56
58
  },
57
59
  "peerDependencies": {
58
- "octokit": ">=5.0.0"
60
+ "octokit": ">=5.0.0",
61
+ "hono": ">=4.0.0"
59
62
  },
60
63
  "peerDependenciesMeta": {
61
64
  "octokit": {
62
65
  "optional": true
66
+ },
67
+ "hono": {
68
+ "optional": true
63
69
  }
64
70
  }
65
71
  }