@ai-pip/csl 0.1.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/LICENSE +21 -0
  2. package/README.md +349 -0
  3. package/index.ts +273 -0
  4. package/layers/csl/adapters/index.ts +9 -0
  5. package/layers/csl/adapters/input/DOMAdapter.ts +236 -0
  6. package/layers/csl/adapters/input/UIAdapter.ts +0 -0
  7. package/layers/csl/adapters/output/ConsoleLogger.ts +34 -0
  8. package/layers/csl/adapters/output/CryptoHashGenerator.ts +29 -0
  9. package/layers/csl/adapters/output/FilePolicyRepository.ts +0 -0
  10. package/layers/csl/adapters/output/InMemoryPolicyRepository.ts +135 -0
  11. package/layers/csl/adapters/output/SystemTimestampProvider.ts +9 -0
  12. package/layers/csl/domain/entities/CSLResult.ts +309 -0
  13. package/layers/csl/domain/entities/Segment.ts +338 -0
  14. package/layers/csl/domain/entities/index.ts +2 -0
  15. package/layers/csl/domain/exceptions/ClassificationError.ts +26 -0
  16. package/layers/csl/domain/exceptions/SegmentationError.ts +30 -0
  17. package/layers/csl/domain/exceptions/index.ts +2 -0
  18. package/layers/csl/domain/index.ts +4 -0
  19. package/layers/csl/domain/services/AnomalyService.ts +255 -0
  20. package/layers/csl/domain/services/LineageService.ts +224 -0
  21. package/layers/csl/domain/services/NormalizationService.ts +392 -0
  22. package/layers/csl/domain/services/OriginClassificationService.ts +69 -0
  23. package/layers/csl/domain/services/PiDetectionService.ts +475 -0
  24. package/layers/csl/domain/services/PolicyService.ts +296 -0
  25. package/layers/csl/domain/services/SegmentClassificationService.ts +105 -0
  26. package/layers/csl/domain/services/SerializationService.ts +229 -0
  27. package/layers/csl/domain/services/index.ts +7 -0
  28. package/layers/csl/domain/value-objects/AnomalyScore.ts +23 -0
  29. package/layers/csl/domain/value-objects/ContentHash.ts +54 -0
  30. package/layers/csl/domain/value-objects/LineageEntry.ts +42 -0
  31. package/layers/csl/domain/value-objects/Origin-map.ts +67 -0
  32. package/layers/csl/domain/value-objects/Origin.ts +99 -0
  33. package/layers/csl/domain/value-objects/Pattern.ts +221 -0
  34. package/layers/csl/domain/value-objects/PiDetection.ts +140 -0
  35. package/layers/csl/domain/value-objects/PiDetectionResult.ts +275 -0
  36. package/layers/csl/domain/value-objects/PolicyRule.ts +151 -0
  37. package/layers/csl/domain/value-objects/TrustLevel.ts +34 -0
  38. package/layers/csl/domain/value-objects/index.ts +10 -0
  39. package/layers/csl/index.ts +3 -0
  40. package/layers/csl/ports/index.ts +10 -0
  41. package/layers/csl/ports/input/ClassificationPort.ts +76 -0
  42. package/layers/csl/ports/input/SegmentationPort.ts +81 -0
  43. package/layers/csl/ports/output/DOMAdapter.ts +14 -0
  44. package/layers/csl/ports/output/HashGenerator.ts +18 -0
  45. package/layers/csl/ports/output/Logger.ts +17 -0
  46. package/layers/csl/ports/output/PolicyRepository.ts +29 -0
  47. package/layers/csl/ports/output/SegmentClassified.ts +8 -0
  48. package/layers/csl/ports/output/TimeStampProvider.ts +5 -0
  49. package/layers/csl/services/CSLService.ts +393 -0
  50. package/layers/csl/services/index.ts +1 -0
  51. package/layers/csl/types/entities-types.ts +37 -0
  52. package/layers/csl/types/index.ts +4 -0
  53. package/layers/csl/types/pi-types.ts +111 -0
  54. package/layers/csl/types/port-output-types.ts +17 -0
  55. package/layers/csl/types/value-objects-types.ts +213 -0
  56. package/layers/csl/utils/colors.ts +25 -0
  57. package/layers/csl/utils/pattern-helpers.ts +174 -0
  58. package/package.json +50 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Felipe Mv
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,349 @@
1
+ # @ai-pip/csl - SDK de Context Segmentation Layer
2
+
3
+ SDK oficial para la capa de segmentación de contexto (CSL) del protocolo AI-PIP. La CSL es responsable de clasificar, etiquetar y aislar el contenido según origen, confiabilidad y riesgo operacional.
4
+
5
+ ## ⚙️ Requisitos
6
+
7
+ Este SDK está escrito en **TypeScript puro** y requiere:
8
+
9
+ - **Node.js >= 22.6.0** (última versión LTS recomendada)
10
+ - TypeScript configurado en tu proyecto (si usas TypeScript)
11
+ - Un entorno que soporte módulos ES (ESM)
12
+
13
+ > **Nota:** Este paquete se distribuye como código TypeScript fuente, por lo que necesitas una versión moderna de Node.js que soporte las características de ES modules y TypeScript nativo, o un bundler/transpilador configurado en tu proyecto.
14
+
15
+ ## 📦 Instalación
16
+
17
+ ```bash
18
+ npm install @ai-pip/csl
19
+ # o
20
+ pnpm add @ai-pip/csl
21
+ # o
22
+ yarn add @ai-pip/csl
23
+ ```
24
+
25
+ ## 🚀 Uso Básico
26
+
27
+ ### Ejemplo Simple
28
+
29
+ ```typescript
30
+ import { createCSLService } from '@ai-pip/csl'
31
+
32
+ // Crear servicio con configuración por defecto
33
+ const cslService = createCSLService()
34
+
35
+ // Procesar contenido del DOM
36
+ const result = await cslService.segment(document.body)
37
+
38
+ // Acceder a los resultados
39
+ console.log(`Segmentos procesados: ${result.metadata.total_segments}`)
40
+ console.log(`Segmentos bloqueados: ${result.getBlockedCount()}`)
41
+
42
+ // Iterar sobre segmentos
43
+ result.segments.forEach(segment => {
44
+ console.log(`Segmento ${segment.id}:`)
45
+ console.log(` - Nivel de confianza: ${segment.trustLevel?.value}`)
46
+ console.log(` - Contenido: ${segment.content}`)
47
+ console.log(` - Score de anomalía: ${segment.anomalyScore?.score}`)
48
+
49
+ if (segment.shouldBlock()) {
50
+ console.log(` ⚠️ Este segmento debe ser bloqueado`)
51
+ }
52
+ })
53
+ ```
54
+
55
+ ## ⚙️ Configuración Avanzada
56
+
57
+ ### Con Opciones Personalizadas
58
+
59
+ ```typescript
60
+ import { createCSLService } from '@ai-pip/csl'
61
+
62
+ const cslService = createCSLService({
63
+ // Habilitar validación de políticas
64
+ enablePolicyValidation: true,
65
+
66
+ // Habilitar tracking de linaje
67
+ enableLineageTracking: true,
68
+
69
+ // Usar algoritmo SHA-512 para hashes
70
+ hashAlgorithm: 'sha512'
71
+ })
72
+
73
+ const result = await cslService.segment(document.body)
74
+ ```
75
+
76
+ ### Con Dependencias Personalizadas
77
+
78
+ ```typescript
79
+ import {
80
+ createCSLService,
81
+ ConsoleLogger,
82
+ InMemoryPolicyRepository,
83
+ PolicyRule,
84
+ SystemTimestamProvider
85
+ } from '@ai-pip/csl'
86
+
87
+ // Crear logger personalizado
88
+ class CustomLogger extends ConsoleLogger {
89
+ error(message: string) {
90
+ // Enviar a servicio de logging externo
91
+ super.error(message)
92
+ }
93
+ }
94
+
95
+ // Configurar políticas
96
+ const policyRepository = new InMemoryPolicyRepository()
97
+ const policy = new PolicyRule({
98
+ version: '1.0',
99
+ blockedIntents: ['delete_user_data', 'modify_system_settings'],
100
+ sensitiveScope: ['financial_transactions'],
101
+ // ... más configuración
102
+ })
103
+ await policyRepository.savePolicy(policy)
104
+
105
+ // Crear servicio con dependencias personalizadas
106
+ const cslService = createCSLService({
107
+ logger: new CustomLogger(),
108
+ policyRepository: policyRepository,
109
+ enablePolicyValidation: true
110
+ })
111
+
112
+ const result = await cslService.segment(document.body)
113
+ ```
114
+
115
+ ## 📚 API Reference
116
+
117
+ ### `createCSLService(options?)`
118
+
119
+ Función factory que crea una instancia de `CSLService` con todas sus dependencias configuradas.
120
+
121
+ **Parámetros:**
122
+ - `options` (opcional): Objeto de configuración
123
+ - `enablePolicyValidation?: boolean` - Habilita validación de políticas (default: `true`)
124
+ - `enableLineageTracking?: boolean` - Habilita tracking de linaje (default: `true`)
125
+ - `hashAlgorithm?: 'sha256' | 'sha512'` - Algoritmo de hash (default: `'sha256'`)
126
+ - `policyRepository?: PolicyRepositoryPort` - Repositorio de políticas personalizado
127
+ - `logger?: LoggerPort` - Logger personalizado
128
+ - `hashGenerator?: HashGeneratorPort` - Generador de hash personalizado
129
+ - `timestampProvider?: TimeStampProviderPort` - Proveedor de timestamps personalizado
130
+
131
+ **Retorna:** `CSLService`
132
+
133
+ ### `CSLService.segment(element)`
134
+
135
+ Procesa un elemento DOM o documento a través del pipeline completo de CSL.
136
+
137
+ **Parámetros:**
138
+ - `element: HTMLElement | Document` - El elemento DOM o documento a procesar
139
+
140
+ **Retorna:** `Promise<CSLResult>`
141
+
142
+ **Lanza:** `SegmentationError` si el procesamiento falla
143
+
144
+ ### `CSLResult`
145
+
146
+ Resultado del procesamiento de segmentación.
147
+
148
+ **Propiedades:**
149
+ - `segments: Segment[]` - Array de segmentos procesados
150
+ - `metadata: CSLResultMetadata` - Metadatos del procesamiento
151
+ - `lineage: LineageEntry[]` - Entradas de linaje para trazabilidad
152
+
153
+ **Métodos:**
154
+ - `getBlockedCount(): number` - Retorna el número de segmentos bloqueados
155
+ - `getTrustDistribution(): { TC: number, STC: number, UC: number }` - Distribución de niveles de confianza
156
+
157
+ ### `Segment`
158
+
159
+ Representa un segmento de contenido procesado.
160
+
161
+ **Propiedades:**
162
+ - `id: string` - Identificador único
163
+ - `content: string` - Contenido del segmento
164
+ - `origin: Origin` - Origen del contenido
165
+ - `trustLevel?: TrustLevel` - Nivel de confianza (TC, STC, UC)
166
+ - `anomalyScore?: AnomalyScore` - Score de anomalía
167
+ - `piDetection?: PiDetection` - Detección de prompt injection
168
+ - `hash?: ContentHash` - Hash del contenido
169
+ - `lineage?: LineageEntry[]` - Entradas de linaje
170
+
171
+ **Métodos:**
172
+ - `shouldBlock(): boolean` - Indica si el segmento debe ser bloqueado
173
+
174
+ ## 🔍 Ejemplos de Uso
175
+
176
+ ### Procesar un Formulario
177
+
178
+ ```typescript
179
+ import { createCSLService } from '@ai-pip/csl'
180
+
181
+ const cslService = createCSLService()
182
+
183
+ // Procesar un formulario específico
184
+ const form = document.getElementById('user-form')
185
+ const result = await cslService.segment(form)
186
+
187
+ // Filtrar solo segmentos confiables
188
+ const trustedSegments = result.segments.filter(
189
+ segment => segment.trustLevel?.value === 'TC'
190
+ )
191
+
192
+ console.log(`Segmentos confiables: ${trustedSegments.length}`)
193
+ ```
194
+
195
+ ### Detectar Prompt Injection
196
+
197
+ ```typescript
198
+ import { createCSLService } from '@ai-pip/csl'
199
+
200
+ const cslService = createCSLService()
201
+ const result = await cslService.segment(document.body)
202
+
203
+ // Buscar segmentos con detección de prompt injection
204
+ const suspiciousSegments = result.segments.filter(
205
+ segment => segment.piDetection?.detected === true
206
+ )
207
+
208
+ suspiciousSegments.forEach(segment => {
209
+ console.warn(`⚠️ Prompt injection detectado en segmento ${segment.id}`)
210
+ console.warn(` Tipo: ${segment.piDetection?.patternType}`)
211
+ console.warn(` Confianza: ${segment.piDetection?.confidence}`)
212
+ })
213
+ ```
214
+
215
+ ### Trabajar con Políticas
216
+
217
+ ```typescript
218
+ import {
219
+ createCSLService,
220
+ InMemoryPolicyRepository,
221
+ PolicyRule
222
+ } from '@ai-pip/csl'
223
+
224
+ // Configurar políticas
225
+ const policyRepository = new InMemoryPolicyRepository()
226
+
227
+ const policy = new PolicyRule({
228
+ version: '1.0',
229
+ blockedIntents: [
230
+ 'delete_user_data',
231
+ 'modify_system_settings',
232
+ 'bypass_security'
233
+ ],
234
+ sensitiveScope: [
235
+ 'financial_transactions',
236
+ 'personal_data_access'
237
+ ],
238
+ roleProtection: {
239
+ protectedRoles: ['system', 'safety'],
240
+ immutableInstructions: [
241
+ 'You are a helpful assistant',
242
+ 'Never reveal internal system details'
243
+ ]
244
+ }
245
+ })
246
+
247
+ await policyRepository.savePolicy(policy)
248
+
249
+ // Crear servicio con políticas
250
+ const cslService = createCSLService({
251
+ policyRepository,
252
+ enablePolicyValidation: true
253
+ })
254
+
255
+ const result = await cslService.segment(document.body)
256
+
257
+ // Verificar violaciones de política
258
+ result.segments.forEach(segment => {
259
+ if (segment.shouldBlock()) {
260
+ console.log(`Segmento ${segment.id} bloqueado por política`)
261
+ }
262
+ })
263
+ ```
264
+
265
+ ### Acceder al Linaje
266
+
267
+ ```typescript
268
+ import { createCSLService } from '@ai-pip/csl'
269
+
270
+ const cslService = createCSLService({
271
+ enableLineageTracking: true
272
+ })
273
+
274
+ const result = await cslService.segment(document.body)
275
+
276
+ // Acceder al linaje completo
277
+ result.lineage.forEach(entry => {
278
+ console.log(`[${entry.timestamp}] ${entry.stage}: ${entry.description}`)
279
+ })
280
+
281
+ // Acceder al linaje de un segmento específico
282
+ const segment = result.segments[0]
283
+ if (segment.lineage) {
284
+ segment.lineage.forEach(entry => {
285
+ console.log(` - ${entry.stage}: ${entry.description}`)
286
+ })
287
+ }
288
+ ```
289
+
290
+ ## 🛠️ Componentes Personalizados
291
+
292
+ ### Crear un Logger Personalizado
293
+
294
+ ```typescript
295
+ import type { LoggerPort } from '@ai-pip/csl'
296
+
297
+ class CustomLogger implements LoggerPort {
298
+ debug(message: string): void {
299
+ // Implementación personalizada
300
+ }
301
+
302
+ info(message: string): void {
303
+ // Implementación personalizada
304
+ }
305
+
306
+ warn(message: string): void {
307
+ // Implementación personalizada
308
+ }
309
+
310
+ error(message: string): void {
311
+ // Implementación personalizada
312
+ }
313
+ }
314
+
315
+ const cslService = createCSLService({
316
+ logger: new CustomLogger()
317
+ })
318
+ ```
319
+
320
+ ### Crear un Repositorio de Políticas Personalizado
321
+
322
+ ```typescript
323
+ import type { PolicyRepositoryPort } from '@ai-pip/csl'
324
+ import { PolicyRule } from '@ai-pip/csl'
325
+
326
+ class DatabasePolicyRepository implements PolicyRepositoryPort {
327
+ async savePolicy(policy: PolicyRule): Promise<void> {
328
+ // Guardar en base de datos
329
+ }
330
+
331
+ async getActivePolicy(): Promise<PolicyRule> {
332
+ // Obtener de base de datos
333
+ }
334
+
335
+ // ... implementar otros métodos
336
+ }
337
+
338
+ const cslService = createCSLService({
339
+ policyRepository: new DatabasePolicyRepository()
340
+ })
341
+ ```
342
+
343
+ ## 📖 Más Información
344
+
345
+ Para más detalles sobre la arquitectura y el funcionamiento de CSL, consulta la [documentación completa](../../docs/layer/csl.md).
346
+
347
+ ## 📄 Licencia
348
+
349
+ MIT
package/index.ts ADDED
@@ -0,0 +1,273 @@
1
+ /**
2
+ * @ai-pip/csl - SDK para la capa de segmentación de contexto (CSL)
3
+ *
4
+ * Este SDK proporciona una interfaz completa para usar la CSL (Context Segmentation Layer)
5
+ * del protocolo AI-PIP. La CSL es responsable de clasificar, etiquetar y aislar el contenido
6
+ * según origen, confiabilidad y riesgo operacional.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { createCSLService } from '@ai-pip/csl'
11
+ *
12
+ * // Crear servicio con configuración por defecto
13
+ * const cslService = createCSLService()
14
+ *
15
+ * // Procesar contenido del DOM
16
+ * const result = await cslService.segment(document.body)
17
+ *
18
+ * // Acceder a los resultados
19
+ * console.log(`Segmentos procesados: ${result.metadata.total_segments}`)
20
+ * console.log(`Segmentos bloqueados: ${result.getBlockedCount()}`)
21
+ * ```
22
+ *
23
+ * @packageDocumentation
24
+ */
25
+
26
+ // ============================================================================
27
+ // EXPORTACIONES PRINCIPALES
28
+ // ============================================================================
29
+
30
+ // Servicio principal
31
+ export { CSLService, type CSLServiceConfig } from './layers/csl/services/CSLService'
32
+
33
+ // ============================================================================
34
+ // PORTS (Interfaces públicas)
35
+ // ============================================================================
36
+
37
+ // Input ports (interfaces que CSL expone)
38
+ export type { SegmentationPort } from './layers/csl/ports/input/SegmentationPort'
39
+ export type { ClassificationPort } from './layers/csl/ports/input/ClassificationPort'
40
+
41
+ // Output ports (interfaces que CSL necesita)
42
+ export type { LoggerPort } from './layers/csl/ports/output/Logger'
43
+ export type { HashGeneratorPort } from './layers/csl/ports/output/HashGenerator'
44
+ export type { TimeStampProviderPort } from './layers/csl/ports/output/TimeStampProvider'
45
+ export type { PolicyRepositoryPort } from './layers/csl/ports/output/PolicyRepository'
46
+ export type { SegmentClassified } from './layers/csl/ports/output/SegmentClassified'
47
+
48
+ // ============================================================================
49
+ // ENTIDADES
50
+ // ============================================================================
51
+
52
+ export { CSLResult } from './layers/csl/domain/entities/CSLResult'
53
+ export { Segment } from './layers/csl/domain/entities/Segment'
54
+
55
+ // ============================================================================
56
+ // VALUE OBJECTS
57
+ // ============================================================================
58
+
59
+ export { Origin } from './layers/csl/domain/value-objects/Origin'
60
+ export { TrustLevel } from './layers/csl/domain/value-objects/TrustLevel'
61
+ export { AnomalyScore } from './layers/csl/domain/value-objects/AnomalyScore'
62
+ export { ContentHash } from './layers/csl/domain/value-objects/ContentHash'
63
+ export { LineageEntry } from './layers/csl/domain/value-objects/LineageEntry'
64
+ export { PiDetection } from './layers/csl/domain/value-objects/PiDetection'
65
+ export { PiDetectionResult } from './layers/csl/domain/value-objects/PiDetectionResult'
66
+ export { PolicyRule } from './layers/csl/domain/value-objects/PolicyRule'
67
+ export { Pattern } from './layers/csl/domain/value-objects/Pattern'
68
+
69
+ // ============================================================================
70
+ // SERVICIOS DE DOMINIO
71
+ // ============================================================================
72
+
73
+ export { NormalizationService } from './layers/csl/domain/services/NormalizationService'
74
+ export { OriginClassificationService } from './layers/csl/domain/services/OriginClassificationService'
75
+ export { PiDetectionService } from './layers/csl/domain/services/PiDetectionService'
76
+ export { AnomalyService } from './layers/csl/domain/services/AnomalyService'
77
+ export { PolicyService } from './layers/csl/domain/services/PolicyService'
78
+ export { LineageService } from './layers/csl/domain/services/LineageService'
79
+ export { SerializationService } from './layers/csl/domain/services/SerializationService'
80
+
81
+ // ============================================================================
82
+ // ADAPTERS (Implementaciones por defecto)
83
+ // ============================================================================
84
+
85
+ // Input adapters
86
+ export { DOMAdapter } from './layers/csl/adapters/input/DOMAdapter'
87
+
88
+ // Output adapters
89
+ export { ConsoleLogger } from './layers/csl/adapters/output/ConsoleLogger'
90
+ export { CryptoHashGenerator } from './layers/csl/adapters/output/CryptoHashGenerator'
91
+ export { SystemTimestamProvider } from './layers/csl/adapters/output/SystemTimestampProvider'
92
+ export { InMemoryPolicyRepository } from './layers/csl/adapters/output/InMemoryPolicyRepository'
93
+
94
+ // ============================================================================
95
+ // EXCEPCIONES
96
+ // ============================================================================
97
+
98
+ export { SegmentationError } from './layers/csl/domain/exceptions/SegmentationError'
99
+ export { ClassificationError } from './layers/csl/domain/exceptions/ClassificationError'
100
+
101
+ // ============================================================================
102
+ // TIPOS
103
+ // ============================================================================
104
+
105
+ export type * from './layers/csl/types'
106
+
107
+ // ============================================================================
108
+ // FACTORY FUNCTION - Creación fácil del servicio
109
+ // ============================================================================
110
+
111
+ import { CSLService, type CSLServiceConfig } from './layers/csl/services/CSLService'
112
+ import { DOMAdapter } from './layers/csl/adapters/input/DOMAdapter'
113
+ import { OriginClassificationService } from './layers/csl/domain/services/OriginClassificationService'
114
+ import { PiDetectionService } from './layers/csl/domain/services/PiDetectionService'
115
+ import { AnomalyService } from './layers/csl/domain/services/AnomalyService'
116
+ import { PolicyService } from './layers/csl/domain/services/PolicyService'
117
+ import { LineageService } from './layers/csl/domain/services/LineageService'
118
+ import { CryptoHashGenerator } from './layers/csl/adapters/output/CryptoHashGenerator'
119
+ import { ConsoleLogger } from './layers/csl/adapters/output/ConsoleLogger'
120
+ import { SystemTimestamProvider } from './layers/csl/adapters/output/SystemTimestampProvider'
121
+ import { InMemoryPolicyRepository } from './layers/csl/adapters/output/InMemoryPolicyRepository'
122
+ import type { PolicyRepositoryPort } from './layers/csl/ports/output/PolicyRepository'
123
+ import type { LoggerPort } from './layers/csl/ports/output/Logger'
124
+ import type { HashGeneratorPort } from './layers/csl/ports/output/HashGenerator'
125
+ import type { TimeStampProviderPort } from './layers/csl/ports/output/TimeStampProvider'
126
+
127
+ /**
128
+ * Opciones para crear el servicio CSL
129
+ * @props
130
+ * - enablePolicyValidation?: boolean
131
+ * - enableLineageTracking?: boolean
132
+ * - hashAlgorithm?: 'sha256' | 'sha512'
133
+ * - policyRepository?: PolicyRepositoryPort
134
+ * - logger?: LoggerPort
135
+ * - hashGenerator?: HashGeneratorPort
136
+ * - timestampProvider?: TimeStampProviderPort
137
+ * @example
138
+ * ```typescript
139
+ * const options: CreateCSLServiceOptions = {
140
+ * enablePolicyValidation: true,
141
+ * enableLineageTracking: true,
142
+ * hashAlgorithm: 'sha512'
143
+ * }
144
+
145
+ */
146
+ export interface CreateCSLServiceOptions extends Partial<CSLServiceConfig> {
147
+ /**
148
+ * Repositorio de políticas personalizado.
149
+ * Si no se proporciona, se usa InMemoryPolicyRepository por defecto.
150
+ */
151
+ policyRepository?: PolicyRepositoryPort
152
+
153
+ /**
154
+ * Logger personalizado.
155
+ * Si no se proporciona, se usa ConsoleLogger por defecto.
156
+ */
157
+ logger?: LoggerPort
158
+
159
+ /**
160
+ * Generador de hash personalizado.
161
+ * Si no se proporciona, se usa CryptoHashGenerator por defecto.
162
+ */
163
+ hashGenerator?: HashGeneratorPort
164
+
165
+ /**
166
+ * Proveedor de timestamps personalizado.
167
+ * Si no se proporciona, se usa SystemTimestampProvider por defecto.
168
+ */
169
+ timestampProvider?: TimeStampProviderPort
170
+ }
171
+
172
+ /**
173
+ * Crea una instancia de CSLService con todas sus dependencias configuradas.
174
+ *
175
+ * Esta función factory simplifica la creación del servicio CSL proporcionando
176
+ * implementaciones por defecto para todas las dependencias. Los usuarios pueden
177
+ * personalizar cualquier componente pasando opciones personalizadas.
178
+ *
179
+ * @param options - Opciones de configuración para el servicio y sus dependencias
180
+ *
181
+ * @returns Una instancia configurada de CSLService lista para usar
182
+ *
183
+ * @example
184
+ * ```typescript
185
+ * // Uso básico con configuración por defecto
186
+ * const cslService = createCSLService()
187
+ *
188
+ * // Con configuración personalizada
189
+ * const cslService = createCSLService({
190
+ * enablePolicyValidation: true,
191
+ * enableLineageTracking: true,
192
+ * hashAlgorithm: 'sha512'
193
+ * })
194
+ *
195
+ * // Con dependencias personalizadas
196
+ * const customLogger = new CustomLogger()
197
+ * const customPolicyRepo = new CustomPolicyRepository()
198
+ *
199
+ * const cslService = createCSLService({
200
+ * logger: customLogger,
201
+ * policyRepository: customPolicyRepo,
202
+ * enablePolicyValidation: true
203
+ * })
204
+ *
205
+ * // Procesar contenido
206
+ * const result = await cslService.segment(document.body)
207
+ * ```
208
+ */
209
+ export function createCSLService(options?: CreateCSLServiceOptions): CSLService {
210
+ // Crear adapters con implementaciones por defecto o personalizadas
211
+ const domAdapter = new DOMAdapter()
212
+
213
+ const logger: LoggerPort = options?.logger ?? new ConsoleLogger()
214
+ const hashGenerator: HashGeneratorPort = options?.hashGenerator ?? new CryptoHashGenerator()
215
+ const timestampProvider: TimeStampProviderPort = options?.timestampProvider ?? new SystemTimestamProvider()
216
+ const policyRepository: PolicyRepositoryPort = options?.policyRepository ?? new InMemoryPolicyRepository()
217
+
218
+ // Crear servicios de dominio
219
+ const originClassificationService = new OriginClassificationService()
220
+ const piDetectionService = new PiDetectionService()
221
+ const anomalyService = new AnomalyService()
222
+ const policyService = new PolicyService(policyRepository)
223
+ const lineageService = new LineageService()
224
+
225
+ // Crear configuración del servicio
226
+ const config: CSLServiceConfig | undefined = (() => {
227
+ const hasAnyConfig =
228
+ options?.enablePolicyValidation !== undefined ||
229
+ options?.enableLineageTracking !== undefined ||
230
+ options?.hashAlgorithm !== undefined
231
+
232
+ if (!hasAnyConfig) {
233
+ return undefined
234
+ }
235
+
236
+ // Construir objeto literal inmutable
237
+ const configObj: CSLServiceConfig = {
238
+ ...(options?.enablePolicyValidation !== undefined && {
239
+ enablePolicyValidation: options.enablePolicyValidation
240
+ }),
241
+ ...(options?.enableLineageTracking !== undefined && {
242
+ enableLineageTracking: options.enableLineageTracking
243
+ }),
244
+ ...(options?.hashAlgorithm !== undefined && {
245
+ hashAlgorithm: options.hashAlgorithm
246
+ }),
247
+ }
248
+ return configObj
249
+ })()
250
+
251
+ // Crear y retornar el servicio
252
+ return new CSLService(
253
+ domAdapter,
254
+ originClassificationService,
255
+ piDetectionService,
256
+ anomalyService,
257
+ policyService,
258
+ lineageService,
259
+ hashGenerator,
260
+ logger,
261
+ timestampProvider,
262
+ config
263
+ )
264
+ }
265
+
266
+ // ============================================================================
267
+ // EXPORTACIÓN POR DEFECTO
268
+ // ============================================================================
269
+
270
+ /**
271
+ * Exportación por defecto: función factory para crear el servicio
272
+ */
273
+ export default createCSLService
@@ -0,0 +1,9 @@
1
+ // input
2
+ export * from './input/DOMAdapter';
3
+
4
+
5
+
6
+ // output
7
+ export * from './output/ConsoleLogger'
8
+ export * from './output/SystemTimestampProvider'
9
+ export * from './output/CryptoHashGenerator'