@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,171 @@
1
+ import { BaserowConfig, TableFromAllTables } from './types'
2
+ import { createHttpClient } from './utils/httpFactory'
3
+ import { validateConfig } from './utils/validation'
4
+ import { PerformanceManager } from './utils/performance'
5
+ import { TableService } from './services/TableService'
6
+ import { FieldService } from './services/FieldService'
7
+ import { RowService } from './services/RowService'
8
+ import { TableOnlyContext } from './contexts/TableOnlyContext'
9
+ import { BaseClient } from './services/core/BaseClient'
10
+
11
+ /**
12
+ * Cliente interno para operaciones CRUD de datos con Database Token
13
+ *
14
+ * ⚠️ **USO INTERNO**: Esta clase no debe usarse directamente.
15
+ * Usar `BaserowClient.create()` en su lugar.
16
+ *
17
+ * Proporciona acceso de solo lectura/escritura a datos de Baserow sin capacidades administrativas.
18
+ * Ideal para aplicaciones cliente que necesitan acceder a datos específicos de una base de datos.
19
+ *
20
+ * **Características:**
21
+ * - Autenticación mediante Database Token (no requiere credenciales de usuario)
22
+ * - API directa: `client.tables.findMany()` y `client.table(id).rows.list()`
23
+ * - Solo operaciones de datos: CRUD de filas, lectura de esquemas
24
+ * - Sin capacidades administrativas: no puede crear/modificar estructura
25
+ * - Rate limiting automático y retry logic integrado
26
+ *
27
+ * @internal
28
+ * @since 1.0.0
29
+ */
30
+ export class ClientWithToken extends BaseClient<BaserowConfig> {
31
+ // Servicios para operaciones directas de tablas
32
+ private tableService: TableService
33
+ private fieldService: FieldService
34
+ private rowService: RowService
35
+
36
+ // API pública de tables (acceso directo para Database Token)
37
+ public tables: {
38
+ findMany(): Promise<TableFromAllTables[]>
39
+ findUnique(id: number): Promise<TableFromAllTables | null>
40
+ }
41
+
42
+ /**
43
+ * Crear una nueva instancia de ClientWithToken
44
+ *
45
+ * ⚠️ **USO INTERNO**: Usar `BaserowClient.create()` en su lugar.
46
+ *
47
+ * @param config - Configuración del cliente
48
+ * @param config.url - URL del servidor Baserow
49
+ * @param config.token - Database Token para autenticación
50
+ * @param config.logger - Logger opcional para debugging
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * // ❌ No usar directamente
55
+ * const client = new ClientWithToken(config)
56
+ *
57
+ * // ✅ Usar la API unificada
58
+ * const client = await BaserowClient.create({
59
+ * url: 'https://baserow.example.com',
60
+ * token: process.env.BASEROW_DB_TOKEN
61
+ * })
62
+ *
63
+ * // Nueva API simplificada para Database Tokens
64
+ * const tables = await client.tables.findMany()
65
+ * const rows = await client.table(123).rows.findMany()
66
+ * ```
67
+ *
68
+ * @internal
69
+ * @since 1.0.0
70
+ */
71
+ constructor(config: BaserowConfig) {
72
+ validateConfig(config)
73
+
74
+ // Procesar performance con defaults antes de guardar
75
+ const processedConfig = {
76
+ ...config,
77
+ performance: PerformanceManager.merge(config.performance)
78
+ }
79
+
80
+ const http = createHttpClient({
81
+ url: processedConfig.url,
82
+ token: processedConfig.token,
83
+ logger: processedConfig.logger,
84
+ performance: processedConfig.performance
85
+ })
86
+
87
+ super(processedConfig, http, processedConfig.logger)
88
+
89
+ // Inicializar servicios para operaciones directas de tablas
90
+ this.tableService = new TableService(this.http, this.logger)
91
+ this.fieldService = new FieldService(this.http, this.logger)
92
+ this.rowService = new RowService(this.http, this.logger)
93
+
94
+ // Inicializar API de tables (acceso directo para Database Token)
95
+ this.tables = {
96
+ /**
97
+ * Listar todas las tablas accesibles por el Database Token
98
+ * Usa el endpoint /database/tables/all-tables/ específico para tokens
99
+ */
100
+ findMany: async (): Promise<TableFromAllTables[]> => {
101
+ return await this.tableService.findAllTablesWithToken()
102
+ },
103
+
104
+ /**
105
+ * Buscar tabla específica por ID
106
+ * Busca en las tablas accesibles al Database Token
107
+ */
108
+ findUnique: async (id: number): Promise<TableFromAllTables | null> => {
109
+ const tables = await this.tableService.findAllTablesWithToken()
110
+ return tables.find(table => table.id === id) || null
111
+ }
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Campos que deben excluirse por defecto para cliente con token
117
+ * Para ClientWithToken no hay campos sensibles a excluir
118
+ */
119
+ protected getDefaultExcludeKeys(): string[] {
120
+ return []
121
+ }
122
+
123
+ /**
124
+ * Acceder a una tabla específica (API directa)
125
+ *
126
+ * Crea un contexto de tabla que permite operaciones en filas y campos.
127
+ * El Database Token debe tener permisos para la tabla especificada.
128
+ *
129
+ * @param tableId - ID numérico de la tabla
130
+ * @returns Contexto de tabla con acceso a filas y campos
131
+ *
132
+ * @example
133
+ * ```typescript
134
+ * // Acceso directo a operaciones de tabla
135
+ * const table = await client.table(456).get()
136
+ * const rows = await client.table(456).rows.findMany()
137
+ * const newRow = await client.table(456).rows.createMany([{
138
+ * name: 'John',
139
+ * active: true
140
+ * }])
141
+ *
142
+ * // Acceso a información de campos
143
+ * const fields = await client.table(456).fields.findMany()
144
+ * ```
145
+ *
146
+ * @since 1.0.0
147
+ */
148
+ table(tableId: number): TableOnlyContext {
149
+ return new TableOnlyContext(tableId, this.tableService, this.fieldService, this.rowService, this.logger)
150
+ }
151
+
152
+ /**
153
+ * Obtener la configuración actual del cliente
154
+ *
155
+ * Retorna una copia de solo lectura de la configuración para prevenir modificaciones accidentales.
156
+ *
157
+ * @returns Configuración actual del cliente (solo lectura)
158
+ *
159
+ * @example
160
+ * ```typescript
161
+ * const config = client.getConfig()
162
+ * console.log('URL servidor:', config.url)
163
+ * console.log('Token:', config.token.substring(0, 10) + '...')
164
+ * ```
165
+ *
166
+ * @since 1.0.0
167
+ */
168
+ getConfig(): Readonly<BaserowConfig> {
169
+ return this.getConfigBase()
170
+ }
171
+ }
@@ -0,0 +1,114 @@
1
+ import { Logger, Database } from '../types'
2
+ import { TableClientContext } from './TableClientContext'
3
+ import { DatabaseService } from '../services/DatabaseService'
4
+ import { TableService } from '../services/TableService'
5
+ import { FieldService } from '../services/FieldService'
6
+ import { RowService } from '../services/RowService'
7
+
8
+ /**
9
+ * Context para operaciones en una base de datos específica con BaserowClient
10
+ * Proporciona API jerárquica para Database Token operations
11
+ */
12
+ export class DatabaseClientContext {
13
+ private databaseId: number
14
+ private resolvedDatabase?: Database
15
+ private logger?: Logger
16
+
17
+ constructor(
18
+ databaseId: number,
19
+ private databaseService: DatabaseService,
20
+ private tableService: TableService,
21
+ private fieldService: FieldService,
22
+ private rowService: RowService,
23
+ logger?: Logger
24
+ ) {
25
+ this.databaseId = databaseId
26
+ this.logger = logger
27
+ }
28
+
29
+ /**
30
+ * Acceder a una tabla específica en esta database
31
+ */
32
+ table(tableId: number): TableClientContext {
33
+ return new TableClientContext(
34
+ this.databaseId,
35
+ tableId,
36
+ this.tableService,
37
+ this.fieldService,
38
+ this.rowService,
39
+ this.logger
40
+ )
41
+ }
42
+
43
+ /**
44
+ * Operaciones de tables en esta database
45
+ */
46
+ get tables() {
47
+ return {
48
+ /**
49
+ * Listar todas las tables de la database
50
+ */
51
+ findMany: async () => {
52
+ return await this.tableService.findMany(this.databaseId)
53
+ },
54
+
55
+ /**
56
+ * Buscar table por nombre en esta database
57
+ */
58
+ findUnique: async (name: string) => {
59
+ return await this.tableService.findUnique(this.databaseId, name)
60
+ }
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Obtener información de la database (lazy loading)
66
+ */
67
+ async get(): Promise<Database> {
68
+ if (this.resolvedDatabase) {
69
+ return this.resolvedDatabase
70
+ }
71
+
72
+ const database = await this.databaseService.findUnique(this.databaseId)
73
+ if (!database) {
74
+ throw new Error(`Database with ID ${this.databaseId} not found`)
75
+ }
76
+ this.resolvedDatabase = database
77
+
78
+ if (this.logger) {
79
+ this.logger.debug?.(`Resolved database: "${this.resolvedDatabase.name}" (ID: ${this.resolvedDatabase.id})`)
80
+ }
81
+
82
+ return this.resolvedDatabase
83
+ }
84
+
85
+ /**
86
+ * Verificar si la database existe
87
+ *
88
+ * Método de utilidad para verificar la existencia de la database
89
+ * sin cargar todos sus datos. Útil para validaciones previas.
90
+ *
91
+ * @returns Promise con true si existe, false si no
92
+ *
93
+ * @example
94
+ * ```typescript
95
+ * const exists = await client.database(123).exists()
96
+ * if (exists) {
97
+ * const database = await client.database(123).get()
98
+ * console.log(`Database: ${database.name}`)
99
+ * } else {
100
+ * console.log('Database no encontrada')
101
+ * }
102
+ * ```
103
+ *
104
+ * @since 1.1.0
105
+ */
106
+ async exists(): Promise<boolean> {
107
+ try {
108
+ await this.get()
109
+ return true
110
+ } catch {
111
+ return false
112
+ }
113
+ }
114
+ }