@gzl10/baserow 1.2.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +435 -0
  2. package/README.md +847 -0
  3. package/dist/index.d.ts +8749 -0
  4. package/dist/index.js +11167 -0
  5. package/dist/index.js.map +1 -0
  6. package/package.json +91 -0
  7. package/src/BaserowClient.ts +501 -0
  8. package/src/ClientWithCreds.ts +545 -0
  9. package/src/ClientWithCredsWs.ts +852 -0
  10. package/src/ClientWithToken.ts +171 -0
  11. package/src/contexts/DatabaseClientContext.ts +114 -0
  12. package/src/contexts/DatabaseContext.ts +870 -0
  13. package/src/contexts/DatabaseTokenContext.ts +331 -0
  14. package/src/contexts/FieldContext.ts +399 -0
  15. package/src/contexts/RowContext.ts +99 -0
  16. package/src/contexts/TableClientContext.ts +291 -0
  17. package/src/contexts/TableContext.ts +1247 -0
  18. package/src/contexts/TableOnlyContext.ts +74 -0
  19. package/src/contexts/WorkspaceContext.ts +490 -0
  20. package/src/express/errors.ts +260 -0
  21. package/src/express/index.ts +69 -0
  22. package/src/express/middleware.ts +225 -0
  23. package/src/express/serializers.ts +314 -0
  24. package/src/index.ts +247 -0
  25. package/src/presets/performance.ts +262 -0
  26. package/src/services/AuthService.ts +472 -0
  27. package/src/services/DatabaseService.ts +246 -0
  28. package/src/services/DatabaseTokenService.ts +186 -0
  29. package/src/services/FieldService.ts +1543 -0
  30. package/src/services/RowService.ts +982 -0
  31. package/src/services/SchemaControlService.ts +420 -0
  32. package/src/services/TableService.ts +781 -0
  33. package/src/services/WorkspaceService.ts +113 -0
  34. package/src/services/core/BaseAuthClient.ts +111 -0
  35. package/src/services/core/BaseClient.ts +107 -0
  36. package/src/services/core/BaseService.ts +71 -0
  37. package/src/services/core/HttpService.ts +115 -0
  38. package/src/services/core/ValidationService.ts +149 -0
  39. package/src/types/auth.ts +177 -0
  40. package/src/types/core.ts +91 -0
  41. package/src/types/errors.ts +105 -0
  42. package/src/types/fields.ts +456 -0
  43. package/src/types/index.ts +222 -0
  44. package/src/types/requests.ts +333 -0
  45. package/src/types/responses.ts +50 -0
  46. package/src/types/schema.ts +446 -0
  47. package/src/types/tokens.ts +36 -0
  48. package/src/types.ts +11 -0
  49. package/src/utils/auth.ts +174 -0
  50. package/src/utils/axios.ts +647 -0
  51. package/src/utils/field-cache.ts +164 -0
  52. package/src/utils/httpFactory.ts +66 -0
  53. package/src/utils/jwt-decoder.ts +188 -0
  54. package/src/utils/jwtTokens.ts +50 -0
  55. package/src/utils/performance.ts +105 -0
  56. package/src/utils/prisma-mapper.ts +961 -0
  57. package/src/utils/validation.ts +463 -0
  58. package/src/validators/schema.ts +419 -0
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Tipos relacionados con autenticación y configuración
3
+ */
4
+
5
+ import { Logger } from './core'
6
+
7
+ export interface BaserowCredentials {
8
+ email: string
9
+ password: string
10
+ }
11
+
12
+ /**
13
+ * Opciones de configuración de rendimiento (completamente opcionales)
14
+ *
15
+ * Permite personalizar el comportamiento del cliente HTTP para casos específicos:
16
+ * - Testing: timeouts largos, pocos reintentos
17
+ * - Batch operations: rate limiting alto, timeouts largos
18
+ * - Producción crítica: configuración conservadora
19
+ *
20
+ * @since 1.2.0
21
+ */
22
+ export interface BaserowPerformanceOptions {
23
+ /** Timeout por request en milisegundos (default: 30000) */
24
+ timeout?: number
25
+ /** Número de reintentos automáticos (default: 3) */
26
+ retries?: number
27
+ /** Máximo requests por segundo para rate limiting (default: 10) */
28
+ maxRequestsPerSecond?: number
29
+ /** Habilitar rate limiting automático (default: true) */
30
+ enableRateLimiting?: boolean
31
+ }
32
+
33
+ /**
34
+ * Configuración de keep-alive para evitar expiración de refresh token
35
+ *
36
+ * IMPORTANTE: El refresh token de Baserow expira 7 días después del login (fijo, NO se renueva con refresh).
37
+ * Keep-alive ejecuta RE-LOGIN completo periódicamente para obtener tokens frescos y mantener
38
+ * la sesión activa indefinidamente en aplicaciones backend de larga duración (24/7).
39
+ *
40
+ * ⚠️ SEGURIDAD: Las credenciales se almacenan en memoria del proceso.
41
+ * Solo habilitar en backends propios/confiables, NO en frontends o apps compartidas.
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * // Re-login cada 5 días (default recomendado, margen de 2 días)
46
+ * keepAlive: { enabled: true }
47
+ *
48
+ * // Re-login cada 3 días (más conservador, margen de 4 días)
49
+ * keepAlive: { enabled: true, intervalMinutes: 4320 }
50
+ * ```
51
+ *
52
+ * @since 1.3.0
53
+ */
54
+ export interface KeepAliveConfig {
55
+ /** Habilitar keep-alive automático (almacena credenciales en memoria) */
56
+ enabled: true
57
+ /** Intervalo en minutos para re-login (default: 7200 = 5 días) */
58
+ intervalMinutes?: number
59
+ }
60
+
61
+ export interface BaserowConfig {
62
+ url: string
63
+ token: string
64
+ logger?: Logger
65
+ /** Configuración opcional de rendimiento */
66
+ performance?: BaserowPerformanceOptions
67
+ }
68
+
69
+ export interface BaserowAdminConfig {
70
+ url: string
71
+ credentials: BaserowCredentials
72
+ workspace?: string
73
+ logger?: Logger
74
+ /** Configuración opcional de rendimiento */
75
+ performance?: BaserowPerformanceOptions
76
+ /** Configuración opcional de keep-alive para evitar expiración de refresh token */
77
+ keepAlive?: KeepAliveConfig
78
+ }
79
+
80
+ export interface LoginRequest {
81
+ username: string
82
+ password: string
83
+ }
84
+
85
+ export interface LoginResponse {
86
+ token: string
87
+ access_token: string
88
+ refresh_token: string
89
+ user_session: string
90
+ user: {
91
+ id: number
92
+ username: string
93
+ first_name: string
94
+ email_verified: boolean
95
+ is_staff: boolean
96
+ language: string
97
+ completed_onboarding: boolean
98
+ }
99
+ }
100
+
101
+ export interface RefreshTokenRequest {
102
+ refresh_token: string
103
+ }
104
+
105
+ export interface RefreshTokenResponse {
106
+ token: string
107
+ access_token: string
108
+ user: {
109
+ id: number
110
+ username: string
111
+ first_name: string
112
+ email_verified: boolean
113
+ is_staff: boolean
114
+ language: string
115
+ completed_onboarding: boolean
116
+ }
117
+ }
118
+
119
+ export interface ChangePasswordRequest {
120
+ old_password: string
121
+ new_password: string
122
+ }
123
+
124
+ // ===== Nuevos tipos para API unificada =====
125
+
126
+ /**
127
+ * Configuración para cliente con Database Token
128
+ */
129
+ export interface BaserowTokenConfig {
130
+ url: string
131
+ token: string
132
+ logger?: Logger
133
+ performance?: BaserowPerformanceOptions
134
+ }
135
+
136
+ /**
137
+ * Configuración para cliente con credenciales (sin workspace específico)
138
+ */
139
+ export interface BaserowCredentialsConfig {
140
+ url: string
141
+ credentials: BaserowCredentials
142
+ logger?: Logger
143
+ performance?: BaserowPerformanceOptions
144
+ keepAlive?: KeepAliveConfig
145
+ }
146
+
147
+ /**
148
+ * Configuración para cliente con credenciales y workspace específico
149
+ */
150
+ export interface BaserowCredentialsWorkspaceConfig extends BaserowCredentialsConfig {
151
+ workspace: string
152
+ }
153
+
154
+ /**
155
+ * Configuración unificada que puede ser cualquiera de los tipos anteriores
156
+ */
157
+ export type BaserowUnifiedConfig = BaserowTokenConfig | BaserowCredentialsConfig | BaserowCredentialsWorkspaceConfig
158
+
159
+ // ===== Aliases descriptivos para mejor DX =====
160
+
161
+ /**
162
+ * Alias: Configuración para cliente con Database Token
163
+ * @alias BaserowTokenConfig
164
+ */
165
+ export type TokenConfig = BaserowTokenConfig
166
+
167
+ /**
168
+ * Alias: Configuración para cliente con credenciales (sin workspace específico)
169
+ * @alias BaserowCredentialsConfig
170
+ */
171
+ export type CredentialsConfig = BaserowCredentialsConfig
172
+
173
+ /**
174
+ * Alias: Configuración para cliente con credenciales y workspace específico
175
+ * @alias BaserowCredentialsWorkspaceConfig
176
+ */
177
+ export type CredentialsWorkspaceConfig = BaserowCredentialsWorkspaceConfig
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Tipos fundamentales y entidades core de Baserow
3
+ */
4
+
5
+ export interface Logger {
6
+ info(message?: any, ...optionalParams: any[]): void
7
+ warn(message?: any, ...optionalParams: any[]): void
8
+ error(message?: any, ...optionalParams: any[]): void
9
+ debug?(message?: any, ...optionalParams: any[]): void
10
+ log?(message?: any, ...optionalParams: any[]): void
11
+ }
12
+
13
+ export interface UserReference {
14
+ id: number
15
+ email: string
16
+ name: string
17
+ permissions: string
18
+ to_be_deleted: boolean
19
+ user_id: number
20
+ workspace: number
21
+ created_on: Date
22
+ }
23
+
24
+ export interface Workspace {
25
+ id: number
26
+ name: string
27
+ order: number
28
+ permissions: string
29
+ users: UserReference[]
30
+ }
31
+
32
+ export interface Database {
33
+ id: number
34
+ name: string
35
+ order: number
36
+ type: string
37
+ workspace?: {
38
+ id: number
39
+ name: string
40
+ }
41
+ tables: Table[]
42
+ created_on?: string
43
+ }
44
+
45
+ export interface DatabaseLight {
46
+ id: number
47
+ name: string
48
+ order: number
49
+ database_id: number
50
+ }
51
+
52
+ /**
53
+ * Tabla tal como viene del endpoint /database/tables/all-tables/
54
+ * Usado para Database Tokens que pueden listar tablas directamente
55
+ */
56
+ export interface TableFromAllTables {
57
+ id: number
58
+ name: string
59
+ order: number
60
+ database_id: number
61
+ }
62
+
63
+ export interface Table {
64
+ id: number
65
+ name: string
66
+ order: number
67
+ database_id: number
68
+ }
69
+
70
+ export interface Row {
71
+ id: number
72
+ order: string
73
+ [fieldName: string]: any
74
+ }
75
+
76
+ export interface User {
77
+ id: number
78
+ username: string
79
+ first_name: string
80
+ last_name?: string
81
+ email_verified: boolean
82
+ is_staff: boolean
83
+ is_active: boolean
84
+ language: string
85
+ completed_onboarding: boolean
86
+ created_on: string
87
+ }
88
+
89
+ export interface UserProfile extends User {
90
+ email_notification_frequency: string
91
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Clases de error específicas para Baserow
3
+ */
4
+
5
+ export class BaserowError extends Error {
6
+ public config?: any // Axios request config para permitir retry en interceptores
7
+
8
+ constructor(
9
+ message: string,
10
+ public status?: number,
11
+ public code?: string,
12
+ public details?: any,
13
+ config?: any
14
+ ) {
15
+ super(message)
16
+ this.name = 'BaserowError'
17
+ this.config = config
18
+ }
19
+ }
20
+
21
+ export class BaserowValidationError extends BaserowError {
22
+ constructor(
23
+ message: string,
24
+ public fieldErrors: Record<string, string[]>
25
+ ) {
26
+ super(message, 400, 'VALIDATION_ERROR', fieldErrors)
27
+ this.name = 'BaserowValidationError'
28
+ }
29
+ }
30
+
31
+ export class BaserowNotFoundError extends BaserowError {
32
+ constructor(resource: string, id: number | string) {
33
+ super(`${resource} with id ${id} not found`, 404, 'NOT_FOUND')
34
+ this.name = 'BaserowNotFoundError'
35
+ }
36
+ }
37
+
38
+ export class BaserowRateLimitError extends BaserowError {
39
+ constructor(public retryAfter?: number) {
40
+ super('Rate limit exceeded', 429, 'RATE_LIMIT', { retryAfter })
41
+ this.name = 'BaserowRateLimitError'
42
+ }
43
+ }
44
+
45
+ export class BaserowNetworkError extends BaserowError {
46
+ constructor(message: string, originalError?: any) {
47
+ super(`Network error: ${message}`, 0, 'NETWORK_ERROR', { originalError })
48
+ this.name = 'BaserowNetworkError'
49
+ }
50
+ }
51
+
52
+ export class BaserowTimeoutError extends BaserowError {
53
+ constructor(timeoutMs: number) {
54
+ super(`Request timeout after ${timeoutMs}ms`, 0, 'TIMEOUT', { timeoutMs })
55
+ this.name = 'BaserowTimeoutError'
56
+ }
57
+ }
58
+
59
+ export class BaserowConfigError extends BaserowError {
60
+ constructor(message: string, configField?: string) {
61
+ super(`Configuration error: ${message}`, 0, 'CONFIG_ERROR', { configField })
62
+ this.name = 'BaserowConfigError'
63
+ }
64
+ }
65
+
66
+ export class BaserowWorkspaceError extends BaserowError {
67
+ constructor(message: string, workspaceId?: number) {
68
+ super(`Workspace error: ${message}`, 0, 'WORKSPACE_ERROR', { workspaceId })
69
+ this.name = 'BaserowWorkspaceError'
70
+ }
71
+ }
72
+
73
+ export class BaserowAuthTokenExpiredError extends BaserowError {
74
+ constructor(tokenType: 'access' | 'refresh' = 'refresh') {
75
+ super(
76
+ `${tokenType === 'access' ? 'Access' : 'Refresh'} token has expired. Please login again.`,
77
+ 401,
78
+ 'AUTH_TOKEN_EXPIRED',
79
+ { tokenType }
80
+ )
81
+ this.name = 'BaserowAuthTokenExpiredError'
82
+ }
83
+ }
84
+
85
+ export class BaserowAuthTokenInvalidError extends BaserowError {
86
+ constructor(message: string = 'Invalid or corrupted authentication token', details?: any) {
87
+ super(message, 401, 'AUTH_TOKEN_INVALID', details)
88
+ this.name = 'BaserowAuthTokenInvalidError'
89
+ }
90
+ }
91
+
92
+ export class BaserowReLoginRequiredError extends BaserowError {
93
+ constructor(
94
+ reason: 'refresh_token_expired' | 'session_expired' | 'tokens_lost' = 'refresh_token_expired',
95
+ details?: any
96
+ ) {
97
+ const messages = {
98
+ refresh_token_expired: 'Refresh token has expired after period of inactivity. Re-authentication required.',
99
+ session_expired: 'Session has expired. Please login again with your credentials.',
100
+ tokens_lost: 'Authentication tokens were lost (process restart or memory cleared). Re-authentication required.'
101
+ }
102
+ super(messages[reason], 401, 'RE_LOGIN_REQUIRED', { reason, ...details })
103
+ this.name = 'BaserowReLoginRequiredError'
104
+ }
105
+ }