rajt 0.0.18 → 0.0.20

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "rajt",
3
3
  "description": "A serverless bundler layer, fully typed for AWS Lambda (Node.js and LLRT) and Cloudflare Workers.",
4
- "version": "0.0.18",
4
+ "version": "0.0.20",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "exports": {
package/src/auth/token.ts CHANGED
@@ -7,14 +7,7 @@ export class Token {
7
7
  static #prefix: string = 'bearer'
8
8
 
9
9
  static fromRequest(c: Context) {
10
- // const token = this.fromHeader(c.req)
11
- // Mock user
12
- const token = this.create(c.req, {
13
- name: 'Nicolau',
14
- email: 'nicolau@zunq.com',
15
- role: 'user',
16
- }).get()
17
-
10
+ const token = this.fromHeader(c.req)
18
11
  return token ? this.parse(c.req, token) : null
19
12
  }
20
13
 
package/src/create-app.ts CHANGED
@@ -9,7 +9,7 @@ import { Routes } from './types'
9
9
  import { BadRequest, Unauthorized } from './exceptions'
10
10
  import response from './response'
11
11
  import { resolve, resolveMiddleware } from './utils/resolve'
12
- import { getGlobalMiddlewares, getHandler } from './register'
12
+ import { getMiddlewares, getHandler } from './register'
13
13
  import env from './utils/environment'
14
14
 
15
15
  type InitFunction<E extends Env = Env> = (app: Hono<E>) => void
@@ -90,13 +90,13 @@ export const createApp = <E extends Env>(options?: ServerOptions<E>) => {
90
90
  response.setContext(c)
91
91
  await next()
92
92
  },
93
- ...getGlobalMiddlewares()
93
+ ...getMiddlewares()
94
94
  ]
95
95
  middlewares.forEach(mw => {
96
96
  // @ts-ignore
97
97
  const h = resolveMiddleware(mw)
98
98
  // @ts-ignore
99
- mw?.p ? app.use(String(mw.p), h) : app.use(h)
99
+ mw?.path ? app.use(String(mw.path), h) : app.use(h)
100
100
  })
101
101
 
102
102
  app.onError(options?.onError || EHandler)
package/src/dev.ts CHANGED
@@ -1,14 +1,21 @@
1
1
  import { config } from 'dotenv'
2
2
  import { serve } from '@hono/node-server'
3
3
  import createApp from './create-app'
4
- import getRoutes from './routes'
4
+ import { getRoutes, getMiddlewares } from './routes'
5
+ import { registerHandler, registerMiddleware } from './register'
5
6
  import { Ability } from './auth'
6
7
  import { getAvailablePort } from './utils/port'
7
8
  import jsonImport from './utils/json-import'
8
9
 
9
10
  config({ path: '../../.env.dev' })
10
11
 
11
- const routes = await getRoutes()
12
+ let routes = await getRoutes()
13
+ routes.forEach(r => registerHandler(r.name, r.handle))
14
+ routes = routes.filter(r => r?.path)
15
+
16
+ const middlewares = await getMiddlewares()
17
+ middlewares.forEach(mw => registerMiddleware(mw.handle))
18
+
12
19
  Ability.fromRoutes(routes)
13
20
  Ability.roles = jsonImport('../../../../.rolefile')
14
21
 
package/src/http.ts CHANGED
@@ -2,7 +2,6 @@ import type { Context, Next } from 'hono'
2
2
  import { MiddlewareType } from './middleware'
3
3
  import JsonResponse from './response'
4
4
  import { Ability, Authnz, Token } from './auth'
5
- import { registerGlobalMiddleware } from './register'
6
5
  import mergeMiddleware from './utils/merge-middleware'
7
6
 
8
7
  function method(method: string, path = '/') {
@@ -42,17 +41,6 @@ export function Middlewares(...handlers: MiddlewareType[]) {
42
41
  return Middleware(...handlers)
43
42
  }
44
43
 
45
- type MiddlewareOpt = string | RegExp
46
- export function GlobalMiddleware(): ClassDecorator
47
- export function GlobalMiddleware(target: Function): void
48
- export function GlobalMiddleware(opt?: MiddlewareOpt): ClassDecorator
49
- export function GlobalMiddleware(...args: any[]): void | ClassDecorator {
50
- if (typeof args[0] === 'function')
51
- return _globalmw(args[0])
52
-
53
- return (target: any) => _globalmw(target, ...args)
54
- }
55
-
56
44
  export function Auth(target: Function): void
57
45
  export function Auth(): ClassDecorator
58
46
  export function Auth(...args: any[]): void | ClassDecorator {
@@ -76,9 +64,3 @@ function _auth(target: Function | any) {
76
64
  await next()
77
65
  })
78
66
  }
79
-
80
- function _globalmw(target: Function | any, path?: string) {
81
- target.gmw = true
82
- target.p = path
83
- registerGlobalMiddleware(target)
84
- }
package/src/middleware.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  import type { Context, MiddlewareHandler, Next } from 'hono'
2
2
 
3
- export type IMiddleware = {
4
- handle(c: Context, next: Next): Promise<void> | void
5
- }
6
-
7
- export default abstract class Middleware implements IMiddleware {
8
- abstract handle(c: Context, next: Next): Promise<void> | void
9
- }
10
-
11
- // export type MiddlewareHandler = (c: Context, next: Next) => Promise<void> | void
12
3
  export type MiddlewareType = MiddlewareHandler | Middleware | (new () => Middleware)
4
+ export default abstract class Middleware {
5
+ static factory?: Function
6
+ static opts?: object | any[]
7
+ static path: string = '*'
8
+ static async handle(c: Context, next: Next): Promise<void> {
9
+ await next()
10
+ }
11
+ }
package/src/register.ts CHANGED
@@ -25,7 +25,7 @@ export function getHandler(id: string): Function {
25
25
  }
26
26
 
27
27
  export const _mw: Function[] = []
28
- export const getGlobalMiddlewares = () => _mw
29
- export function registerGlobalMiddleware(handler: any) {
28
+ export const getMiddlewares = () => _mw
29
+ export function registerMiddleware(handler: any) {
30
30
  _mw.push(handler)
31
31
  }
package/src/routes.ts CHANGED
@@ -2,67 +2,86 @@ import { existsSync, readdirSync, statSync } from 'node:fs'
2
2
  import { dirname, join, resolve } from 'node:path'
3
3
  import { fileURLToPath } from 'node:url'
4
4
  import { Route } from './types'
5
- import { registerHandler } from './register'
6
5
  import { isAnonFn } from './utils/func'
7
6
 
8
7
  const __filename = fileURLToPath(import.meta.url)
9
8
  const __dirname = dirname(__filename)
10
9
 
11
- export default async function getRoutes(
12
- all: boolean = false,
13
- dirs: string[] = ['actions', 'features', 'errors', 'middlewares']
14
- ): Promise<Route[]> {
15
- const routes: Route[] = []
10
+ const importName = (name?: string) => (name || 'Fn'+ Math.random().toString(36).substring(2)).replace(/\.ts$/, '')
11
+ const walk = async (dir: string, baseDir: string, fn: Function, parentMw: string[] = []): Promise<void> => {
12
+ if (!existsSync(dir)) return
13
+ const files = readdirSync(dir)
16
14
 
17
- const walk = async (dir: string, baseDir: string, middlewares: Function[] = []): Promise<void> => {
18
- if (!existsSync(dir)) return
19
- const files = readdirSync(dir)
15
+ const currentMw = [...parentMw]
16
+ const indexFile = join(dir, 'index.ts')
20
17
 
21
- for (const file of files) {
22
- const fullPath = join(dir, file)
23
- const stat = statSync(fullPath)
18
+ if (existsSync(indexFile)) {
19
+ const mod = await import(indexFile)
20
+ const group = mod.default
21
+
22
+ !isAnonFn(group) && group?.mw?.length && currentMw.push(group?.name)
23
+ fn(indexFile, baseDir, group, currentMw)
24
+ }
24
25
 
25
- if (stat.isDirectory()) {
26
- const indexFile = join(fullPath, 'index.ts')
26
+ for (const file of files) {
27
+ const fullPath = join(dir, file)
28
+ const stat = statSync(fullPath)
27
29
 
28
- if (existsSync(indexFile)) {
29
- const mod = await import(indexFile)
30
- const group = mod.default
31
- registerHandler(group.name, group)
32
- !isAnonFn(group) && middlewares.push(group.name)
30
+ if (stat.isDirectory()) {
31
+ await walk(fullPath, baseDir, fn, currentMw)
32
+ } else if (file !== 'index.ts' && file.endsWith('.ts') && !file.endsWith('.d.ts')) {
33
+ const mod = await import(fullPath)
34
+ fn(fullPath, baseDir, mod.default, currentMw)
35
+ }
36
+ }
37
+ }
33
38
 
34
- all && routes.push({
35
- method: '',
36
- path: '',
37
- name: group.name.replace(/\.ts$/, ''),
38
- file: baseDir + indexFile.split(baseDir)[1],
39
- middlewares,
40
- handle: group,
41
- })
42
- }
43
39
 
44
- await walk(fullPath, baseDir, middlewares)
45
- } else if (file.endsWith('.ts')) {
46
- const mod = await import(fullPath)
47
- const handle = mod.default
40
+ export async function getRoutes(
41
+ dirs: string[] = ['actions', 'features']
42
+ ): Promise<Route[]> {
43
+ const routes: Route[] = []
44
+ let mw: string[] = []
48
45
 
49
- if (handle?.gmw) return
50
- if (handle?.m) {
51
- registerHandler(handle.name, handle)
46
+ await Promise.all(dirs.map(dir => walk(
47
+ resolve(__dirname, '../../..', dir),
48
+ dir,
49
+ (fullPath: string, baseDir: string, handle: any, middlewares: string[]) => {
50
+ const name = importName(handle?.name)
51
+ const file = baseDir + fullPath.split(baseDir)[1]
52
52
 
53
- routes.push({
54
- method: handle.m.toLowerCase(),
55
- path: handle.p,
56
- name: handle.name.replace(/\.ts$/, ''),
57
- file: baseDir + fullPath.split(baseDir)[1],
58
- middlewares,
59
- handle,
60
- })
61
- }
62
- }
53
+ routes.push({
54
+ method: handle?.m?.toLowerCase() || '',
55
+ path: handle?.p || '',
56
+ name,
57
+ file,
58
+ // @ts-ignore
59
+ middlewares,
60
+ handle,
61
+ })
63
62
  }
64
- }
63
+ )))
65
64
 
66
- await Promise.all(dirs.map(dir => walk(resolve(__dirname, '../../..', dir), dir)))
67
65
  return routes
68
66
  }
67
+
68
+ export async function getMiddlewares(
69
+ dirs: string[] = ['middlewares']
70
+ ): Promise<Route[]> {
71
+ const mw: Route[] = []
72
+
73
+ await Promise.all(dirs.map(dir => walk(
74
+ resolve(__dirname, '../../..', dir),
75
+ dir,
76
+ (fullPath: string, baseDir: string, handle: any) => {
77
+ // @ts-ignore
78
+ mw.push({
79
+ name: importName(handle?.name),
80
+ file: baseDir + fullPath.split(baseDir)[1],
81
+ handle,
82
+ })
83
+ }
84
+ )))
85
+
86
+ return mw
87
+ }
@@ -1,6 +1,6 @@
1
1
  import { existsSync, writeFileSync } from 'node:fs'
2
2
  import { config } from 'dotenv'
3
- import getRoutes from '../routes'
3
+ import { getRoutes, getMiddlewares } from '../routes'
4
4
  import ensureDir from '../utils/ensuredir'
5
5
 
6
6
  config({ path: '../../.env.dev' })
@@ -10,14 +10,16 @@ async function cacheRoutes() {
10
10
  if (!existsSync(rolePath))
11
11
  writeFileSync(rolePath, '{}')
12
12
 
13
- const routes = await getRoutes(true)
13
+ const routes = await getRoutes()
14
+ const middlewares = await getMiddlewares()
14
15
 
15
16
  const iPath = '../../tmp/import-routes.mjs'
16
17
  ensureDir(iPath)
17
18
  writeFileSync(iPath, `// AUTO-GENERATED FILE - DO NOT EDIT
18
- import { registerHandler } from '../node_modules/rajt/src/register'
19
+ import { registerHandler, registerMiddleware } from '../node_modules/rajt/src/register'
19
20
 
20
21
  ${routes.map(r => `import ${r.name} from '../${normalizePath(r.file)}'`).join('\n')}
22
+ ${middlewares.map(r => `import ${r.name} from '../${normalizePath(r.file)}'`).join('\n')}
21
23
 
22
24
  try {
23
25
  const handlers = {${routes.map(r => r.name).join()}}
@@ -27,6 +29,12 @@ try {
27
29
  registerHandler(name, handler)
28
30
  }
29
31
  }
32
+
33
+ const middlewares = {${middlewares.map(r => r.name).join()}}
34
+
35
+ for (const [name, mw] of Object.entries(handlers)) {
36
+ registerMiddleware(mw)
37
+ }
30
38
  } catch (e) {
31
39
  console.error('Failed to register handlers:', e)
32
40
  }
@@ -1,22 +1,15 @@
1
1
  export default function getEnvironment() {
2
- if (process.env?.npm_lifecycle_event === 'dev')
3
- return 'dev'
4
-
5
- if (
6
- process.argv?.includes('--dev')
7
- || process.execArgv?.includes('--watch')
8
- || import.meta.url?.includes('localhost')
9
- )
10
- return 'dev'
11
-
12
- // @ts-ignore
13
- if (typeof Bun === 'undefined') return 'prod'
14
-
15
- // @ts-ignore
16
- if (Bun.argv.includes('--prod')) return 'prod'
17
- // @ts-ignore
18
- if (Bun.argv.includes('--dev') || Bun.main.endsWith('.ts')) return 'dev'
19
-
2
+ try {
3
+ if (
4
+ process.env?.npm_lifecycle_event === 'dev'
5
+ || process.env?.AWS_SAM_LOCAL
6
+ || process?.argv?.includes('--dev')
7
+ || process?.execArgv?.includes('--watch')
8
+ || import.meta.url?.includes('localhost')
9
+ ) {
10
+ return 'dev'
11
+ }
12
+ } catch (e) { }
20
13
 
21
14
  return 'prod'
22
15
  }
@@ -22,19 +22,14 @@ export function resolveMiddleware(obj: MiddlewareType) {
22
22
  if (typeof obj === 'function' && obj.length === 2)
23
23
  return obj
24
24
 
25
+ if (obj?.factory)
26
+ return obj?.opts ? obj.factory(...Array.isArray(obj.opts) ? obj.opts : [obj.opts]) : obj.factory()
27
+
25
28
  if (obj?.handle)
26
29
  return obj.handle
27
30
 
28
31
  if (obj.prototype?.handle)
29
32
  return (new obj()).handle
30
33
 
31
- // if (obj instanceof BaseMiddleware)
32
- // return obj.handle
33
-
34
- // if (BaseMiddleware.isPrototypeOf(obj)) {
35
- // const instance = new (obj as new () => BaseMiddleware)()
36
- // return instance.handle
37
- // }
38
-
39
34
  throw new Error('Invalid middleware provided. Must be a Hono middleware function or MiddlewareClass instance/constructor')
40
35
  }