zeti-framework-backend 0.2.4

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,34 @@
1
+ import { a as ZetiConfigInternal } from '../config-VWgz0Iq_.js';
2
+ import 'hono';
3
+ import 'ioredis';
4
+ import 'hono/http-exception';
5
+
6
+ interface GenerateRegistryOptions {
7
+ controllersPath: string;
8
+ indexPath: string;
9
+ startMarker?: string;
10
+ endMarker?: string;
11
+ /** Se true, escreve apenas os imports no arquivo (para .zeti/registry.ts) */
12
+ outputMode?: 'inject' | 'standalone';
13
+ }
14
+ declare function generateRegistry(options: GenerateRegistryOptions): Promise<void>;
15
+
16
+ interface GenerateSwaggerTypesOptions {
17
+ controllersPath: string;
18
+ outputPath: string;
19
+ }
20
+ declare function generateSwaggerTypes(options: GenerateSwaggerTypesOptions): Promise<void>;
21
+
22
+ interface RunPrebuildOptions {
23
+ projectRoot?: string;
24
+ zetiConfig?: ZetiConfigInternal;
25
+ controllersPath?: string;
26
+ registryPath?: string;
27
+ swaggerOutputPath?: string;
28
+ prismaImport?: string;
29
+ /** Forçar regeneração mesmo se não houver mudanças */
30
+ force?: boolean;
31
+ }
32
+ declare function runPrebuild(options?: RunPrebuildOptions): Promise<void>;
33
+
34
+ export { type GenerateRegistryOptions, type GenerateSwaggerTypesOptions, type RunPrebuildOptions, generateRegistry, generateSwaggerTypes, runPrebuild };
@@ -0,0 +1,12 @@
1
+ import {
2
+ generateRegistry,
3
+ generateSwaggerTypes,
4
+ runPrebuild
5
+ } from "../chunk-KIOZSPU2.js";
6
+ import "../chunk-7D4SUZUM.js";
7
+ export {
8
+ generateRegistry,
9
+ generateSwaggerTypes,
10
+ runPrebuild
11
+ };
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,10 @@
1
+ export { S as SwaggerGeneratorOptions, a as SwaggerRegistry, g as generateSwagger } from '../generator-CK-ZmWQj.js';
2
+ import { ZodTypeAny } from 'zod';
3
+ import 'hono';
4
+ import '../config-VWgz0Iq_.js';
5
+ import 'ioredis';
6
+ import 'hono/http-exception';
7
+
8
+ declare function zodToJsonSchema(schema: ZodTypeAny): any;
9
+
10
+ export { zodToJsonSchema };
@@ -0,0 +1,14 @@
1
+ import {
2
+ SwaggerRegistry
3
+ } from "../chunk-K2E6XKVB.js";
4
+ import {
5
+ generateSwagger,
6
+ zodToJsonSchema
7
+ } from "../chunk-TTILJJ3O.js";
8
+ import "../chunk-7D4SUZUM.js";
9
+ export {
10
+ SwaggerRegistry,
11
+ generateSwagger,
12
+ zodToJsonSchema
13
+ };
14
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,146 @@
1
+ import { Context } from 'hono';
2
+ import { h as ZetiDatabaseConfig, m as ZetiPrismaConfig, b as ZetiPrismaConnectionConfig, T as TenantSelection, C as ConnectionStrategy } from '../config-VWgz0Iq_.js';
3
+ import 'ioredis';
4
+ import 'hono/http-exception';
5
+
6
+ interface TenantMetrics {
7
+ totalTenants: number;
8
+ activeConnections: number;
9
+ cachedConnections: number;
10
+ connectionPoolSize: number;
11
+ cacheHits: number;
12
+ cacheMisses: number;
13
+ errors: number;
14
+ lastCleanup?: Date;
15
+ uptime: number;
16
+ }
17
+ declare class MetricsCollector {
18
+ private metrics;
19
+ private startTime;
20
+ private cacheHitCount;
21
+ private cacheMissCount;
22
+ private errorCount;
23
+ incrementCacheHit(): void;
24
+ incrementCacheMiss(): void;
25
+ incrementError(): void;
26
+ updateMetrics(data: {
27
+ totalTenants?: number;
28
+ activeConnections?: number;
29
+ cachedConnections?: number;
30
+ connectionPoolSize?: number;
31
+ lastCleanup?: Date;
32
+ }): void;
33
+ getMetrics(): TenantMetrics;
34
+ reset(): void;
35
+ }
36
+
37
+ /**
38
+ * TenantManager com suporte a Modos de Operação (single/dynamic)
39
+ *
40
+ * Características:
41
+ * - Cache por URL (hash MD5) para reutilizar instâncias base
42
+ * - Detecção automática de models com tenantId via DMMF
43
+ * - $extends leve aplicado por request (sem cache)
44
+ * - Suporte a workers (sem Context do Hono)
45
+ */
46
+ declare class TenantManager {
47
+ private readonly MAX_RECOMMENDED_DATABASES;
48
+ private databaseConnections;
49
+ private specialDatabases;
50
+ private baseClients;
51
+ private clients;
52
+ private modelFieldsCache;
53
+ private config;
54
+ private databaseConfig;
55
+ private prismaConnectionConfig?;
56
+ private metrics;
57
+ private cleanupInterval?;
58
+ constructor(databaseConfig: ZetiDatabaseConfig, prismaConfig: ZetiPrismaConfig, specialDatabases?: Record<string, string>, prismaConnectionConfig?: ZetiPrismaConnectionConfig);
59
+ /**
60
+ * Obtém cliente contextual baseado na estratégia de conexão.
61
+ *
62
+ * Suporta duas formas de definir escopo de segurança:
63
+ * 1. Via `tenantSelector` no config (modo dynamic)
64
+ * 2. Via `context.set('securityScope', scope)` no middleware
65
+ *
66
+ * O securityScope do middleware tem PRIORIDADE sobre o tenantSelector.
67
+ *
68
+ * @param context - Context do Hono (request)
69
+ * @returns PrismaClient com ou sem $extends de segurança
70
+ */
71
+ getContextualClient(context: Context): Promise<any>;
72
+ /**
73
+ * Obtém cliente para workers (sem Context do Hono).
74
+ *
75
+ * @param selection - TenantSelection manual
76
+ * @returns PrismaClient com ou sem $extends de tenant
77
+ */
78
+ getClientForWorker(selection?: TenantSelection): any;
79
+ /**
80
+ * Obtém cliente base (sem extensões de segurança).
81
+ * Usado pelo middleware global para disponibilizar db aos middlewares do usuário.
82
+ *
83
+ * @returns PrismaClient base
84
+ */
85
+ getBaseClient(): Promise<any>;
86
+ /**
87
+ * Obtém ou cria cliente base cacheado por URL.
88
+ *
89
+ * @param url - Connection string do banco
90
+ * @returns PrismaClient base (sem extensions)
91
+ */
92
+ getOrCreateBaseClient(url: string): any;
93
+ /**
94
+ * Aplica $extends com VALIDAÇÃO de campos de segurança.
95
+ *
96
+ * Esta abordagem:
97
+ * - VALIDA que o campo passado é igual ao do escopo de segurança
98
+ * - Adiciona o campo ao WHERE em queries de leitura (filtro de segurança)
99
+ * - FALHA se o campo não for passado ou for diferente em create/update
100
+ *
101
+ * Isso garante que:
102
+ * 1. O desenvolvedor sempre passa explicitamente o campo
103
+ * 2. Não é possível acessar/modificar dados de outro contexto
104
+ *
105
+ * @param baseClient - Cliente Prisma base
106
+ * @param scopeFields - Campos do escopo de segurança (ex: { tenantId: 'abc', productId: 'xyz' })
107
+ * @param urlHash - Hash da URL do banco para cache de campos
108
+ */
109
+ private applySecurityExtension;
110
+ /**
111
+ * Detecta todos os campos de cada model via DMMF.
112
+ * Resultado é cacheado por URL hash.
113
+ *
114
+ * Isso permite validação genérica de qualquer campo retornado pelo tenantSelector.
115
+ */
116
+ private detectModelFields;
117
+ /**
118
+ * Gera hash MD5 da URL para usar como chave de cache.
119
+ * Isso evita expor credenciais em logs.
120
+ */
121
+ private hashUrl;
122
+ /**
123
+ * Modo legado - usa lógica antiga baseada em databaseId.
124
+ */
125
+ private getLegacyClient;
126
+ private startCleanupInterval;
127
+ private cleanupExpiredConnections;
128
+ private cleanupCache;
129
+ getMetrics(): TenantMetrics;
130
+ getTenantDatabase(databaseId: string): Promise<any>;
131
+ getSpecialDatabase(key: string): any;
132
+ private getOrCreateClient;
133
+ isValidDatabase(databaseId: string): boolean;
134
+ getAllDatabases(): string[];
135
+ /**
136
+ * Retorna a estratégia de conexão configurada.
137
+ */
138
+ getConnectionStrategy(): ConnectionStrategy;
139
+ /**
140
+ * Verifica se está usando o novo modo de operação.
141
+ */
142
+ isUsingConnectionConfig(): boolean;
143
+ shutdown(): Promise<void>;
144
+ }
145
+
146
+ export { MetricsCollector, TenantManager, type TenantMetrics };
@@ -0,0 +1,10 @@
1
+ import {
2
+ MetricsCollector,
3
+ TenantManager
4
+ } from "../chunk-LCNZVWVO.js";
5
+ import "../chunk-7D4SUZUM.js";
6
+ export {
7
+ MetricsCollector,
8
+ TenantManager
9
+ };
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/package.json ADDED
@@ -0,0 +1,83 @@
1
+ {
2
+ "name": "zeti-framework-backend",
3
+ "version": "0.2.4",
4
+ "description": "Framework Hono com suporte a multi-tenancy, Prisma e Swagger automático",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "bin": {
9
+ "zeti": "./dist/cli/index.js"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "import": "./dist/index.js",
14
+ "types": "./dist/index.d.ts"
15
+ },
16
+ "./swagger": {
17
+ "import": "./dist/swagger/index.js",
18
+ "types": "./dist/swagger/index.d.ts"
19
+ },
20
+ "./tenants": {
21
+ "import": "./dist/tenants/index.js",
22
+ "types": "./dist/tenants/index.d.ts"
23
+ },
24
+ "./scripts": {
25
+ "import": "./dist/scripts/index.js",
26
+ "types": "./dist/scripts/index.d.ts"
27
+ },
28
+ "./cli": {
29
+ "import": "./dist/cli/index.js",
30
+ "types": "./dist/cli/index.d.ts"
31
+ }
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "README.md"
36
+ ],
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "dev": "tsup --watch",
40
+ "clean": "rm -rf dist",
41
+ "test:types": "tsc -p tsconfig.typing-tests.json"
42
+ },
43
+ "keywords": [
44
+ "hono",
45
+ "prisma",
46
+ "multi-tenant",
47
+ "swagger",
48
+ "typescript",
49
+ "framework"
50
+ ],
51
+ "author": "",
52
+ "license": "MIT",
53
+ "dependencies": {
54
+ "@hono/node-server": "^1.12.0",
55
+ "@hono/swagger-ui": "^0.4.0",
56
+ "@hono/zod-openapi": "^1.2.0",
57
+ "@prisma/adapter-pg": "^7.2.0",
58
+ "@hono/zod-validator": "^0.4.0",
59
+ "dotenv": "^16.4.5",
60
+ "zod": "^3.23.0",
61
+ "pg": "^8.17.1",
62
+ "fast-glob": "^3.3.2"
63
+ },
64
+ "devDependencies": {
65
+ "@types/bun": "latest",
66
+ "@types/node": "^25.0.9",
67
+ "@types/pg": "^8.16.0",
68
+ "tsup": "^8.5.1",
69
+ "typescript": "^5.9.3"
70
+ },
71
+ "peerDependencies": {
72
+ "@prisma/client": "^7.0.0",
73
+ "hono": "^4.0.0"
74
+ },
75
+ "peerDependenciesMeta": {
76
+ "@prisma/client": {
77
+ "optional": false
78
+ },
79
+ "hono": {
80
+ "optional": false
81
+ }
82
+ }
83
+ }