@plyaz/types 1.31.0 → 1.31.1

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,6 @@
1
+ /**
2
+ * Files Domain Types
3
+ *
4
+ * Core domain types for files/media service.
5
+ */
6
+ export { FileTypeSchema, type FileType, type FilesEntity, type FilesFrontendServiceConfig, type FilesDomainServiceConfig, type FilesDatabaseRow, type FilesCreateInput, type MediaVariantsDatabaseRow, type MediaVariantsCreateInput, type SingleUploadEventPayload, type BulkUploadEventPayload, } from './types';
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Files Domain Types
3
+ *
4
+ * Domain entity, service config, and database row types for files/media.
5
+ * Store types are in @plyaz/types/store/files.
6
+ * API types are in @plyaz/types/api/endpoints/files.
7
+ */
8
+ import type { FileVariant } from '../../../api/endpoints/files/schemas';
9
+ import type { CoreServiceInitConfig } from '../../init';
10
+ import type { CoreInjectedServices } from '../types';
11
+ import type { CoreBaseFrontendServiceConfig } from '../../frontend';
12
+ import type { FilesFrontendStoreData, FilesFrontendStoreSlice } from '../../../store/files';
13
+ import { z } from 'zod';
14
+ /**
15
+ * File type enum - for categorization in domain
16
+ */
17
+ export declare const FileTypeSchema: z.ZodEnum<{
18
+ IMAGE: "IMAGE";
19
+ VIDEO: "VIDEO";
20
+ DOCUMENT: "DOCUMENT";
21
+ AUDIO: "AUDIO";
22
+ OTHER: "OTHER";
23
+ }>;
24
+ export type FileType = z.infer<typeof FileTypeSchema>;
25
+ /**
26
+ * Files domain entity - maps from API response + additional domain properties
27
+ */
28
+ export interface FilesEntity {
29
+ id: string;
30
+ key: string;
31
+ filename: string;
32
+ mimeType: string;
33
+ size: number;
34
+ checksum?: string;
35
+ url?: string;
36
+ publicUrl?: string;
37
+ signedUrl?: string;
38
+ bucket: string;
39
+ entityType?: string;
40
+ entityId?: string;
41
+ category?: string;
42
+ uploadedAt: Date;
43
+ expiresAt?: Date;
44
+ variants?: Record<string, FileVariant>;
45
+ type: FileType;
46
+ isImage: boolean;
47
+ isVideo: boolean;
48
+ isDocument: boolean;
49
+ isAudio: boolean;
50
+ }
51
+ /**
52
+ * Frontend files service configuration
53
+ *
54
+ * Extends both CoreBaseFrontendServiceConfig (for fetchers, storeHandlers)
55
+ * and CoreServiceInitConfig (for base service options).
56
+ * Same pattern as ExampleFrontendServiceConfig.
57
+ */
58
+ export interface FilesFrontendServiceConfig extends CoreBaseFrontendServiceConfig<FilesFrontendStoreData, FilesFrontendStoreSlice>, CoreServiceInitConfig {
59
+ /** API base path for file endpoints */
60
+ apiBasePath?: string;
61
+ /** Auto-fetch files on initialization */
62
+ autoFetch?: boolean;
63
+ /** Maximum uploads to track in store */
64
+ maxUploads?: number;
65
+ /** Maximum generated files to track in store */
66
+ maxGenerated?: number;
67
+ /** Injected services (for testing/manual store injection) */
68
+ injected?: CoreInjectedServices;
69
+ }
70
+ /**
71
+ * Backend files service configuration
72
+ */
73
+ export interface FilesDomainServiceConfig extends CoreServiceInitConfig {
74
+ enabled?: boolean;
75
+ throwOnValidationError?: boolean;
76
+ throwOnRepositoryError?: boolean;
77
+ emitEvents?: boolean;
78
+ }
79
+ /**
80
+ * Database row from media table
81
+ * Used by FilesRepository, mapped to FilesEntity by FilesMapper
82
+ */
83
+ export interface FilesDatabaseRow {
84
+ id: string;
85
+ user_id: string;
86
+ type: string;
87
+ filename: string;
88
+ original_filename: string;
89
+ mime_type: string;
90
+ file_size: bigint | number;
91
+ storage_path: string;
92
+ cdn_url: string | null;
93
+ width: number | null;
94
+ height: number | null;
95
+ duration: number | null;
96
+ is_virus_scanned: boolean;
97
+ virus_scan_result: string | null;
98
+ metadata: Record<string, unknown> | null;
99
+ variants: Record<string, unknown> | null;
100
+ entity_type: string | null;
101
+ entity_id: string | null;
102
+ access_level: string | null;
103
+ created_at: string;
104
+ updated_at: string;
105
+ deleted_at: string | null;
106
+ }
107
+ /**
108
+ * Create input for Files entity (excludes auto-generated fields)
109
+ * Used internally by repository when creating records from upload responses
110
+ */
111
+ export type FilesCreateInput = Omit<FilesDatabaseRow, 'id' | 'created_at' | 'updated_at' | 'deleted_at'>;
112
+ /**
113
+ * Database row from media_variants table
114
+ * Used by MediaVariantsRepository for normalized variant storage
115
+ *
116
+ * Variant names: 'thumbnail', 'mobile', 'desktop', '4k'
117
+ */
118
+ export interface MediaVariantsDatabaseRow {
119
+ id: string;
120
+ media_id: string;
121
+ variant_name: string;
122
+ file_path: string;
123
+ cdn_url: string | null;
124
+ width: number | null;
125
+ height: number | null;
126
+ file_size: number | null;
127
+ created_at: string;
128
+ }
129
+ /**
130
+ * Create input for media variant (excludes auto-generated fields)
131
+ */
132
+ export type MediaVariantsCreateInput = Omit<MediaVariantsDatabaseRow, 'id' | 'created_at'>;
133
+ /**
134
+ * Event payload for single file upload
135
+ * Used by files:upload:uploaded event
136
+ */
137
+ export interface SingleUploadEventPayload {
138
+ result?: {
139
+ metadata: {
140
+ fileId: string;
141
+ filename: string;
142
+ mimeType: string;
143
+ size: number;
144
+ path: string;
145
+ entityType?: string;
146
+ entityId?: string;
147
+ accessLevel?: string;
148
+ url?: string;
149
+ extractedMetadata?: {
150
+ width?: number;
151
+ height?: number;
152
+ duration?: number;
153
+ };
154
+ customMetadata?: Record<string, unknown>;
155
+ };
156
+ variants?: Record<string, unknown>;
157
+ };
158
+ }
159
+ /**
160
+ * Event payload for bulk file upload
161
+ * Used by files:upload:bulk:uploaded event
162
+ */
163
+ export interface BulkUploadEventPayload {
164
+ result?: {
165
+ results?: SingleUploadEventPayload['result'][];
166
+ };
167
+ }
@@ -2,5 +2,6 @@
2
2
  * Core Domain Types
3
3
  * Type definitions for @plyaz/core domain services
4
4
  */
5
- export type { CoreBaseDomainServiceInterface, CoreEventSubscribable, CoreProviderSubscribable, CoreValidationResult, CoreValidatorConfig, CoreBaseValidatorInstance, CoreBaseMapperInstance, CoreBaseDomainServiceConfig, CoreBaseBackendServiceConfig, CoreMapperClass, CoreValidatorClass, CoreBaseServiceConfig, CoreInjectedServices, } from './types';
5
+ export type { EmptyDTO, CoreDeleteOptions, CoreBaseDomainServiceInterface, CoreEventSubscribable, CoreProviderSubscribable, CoreValidationResult, CoreValidatorConfig, CoreBaseValidatorInstance, CoreBaseMapperInstance, CoreBaseDomainServiceConfig, CoreBaseBackendServiceConfig, CoreMapperClass, CoreValidatorClass, CoreBaseServiceConfig, CoreInjectedServices, } from './types';
6
6
  export type { CrudCacheOptions, CrudTransactionOptions, CrudOperationOptions, } from './crud';
7
+ export * from './files';
@@ -8,6 +8,20 @@ import type { ValidationIssue, InternalValidationSchema } from '../../errors';
8
8
  import type { FeatureFlagValue } from '../../features';
9
9
  import type { CoreServiceRuntime } from '../modules';
10
10
  import type { ApiClientOptions } from '../../api';
11
+ /**
12
+ * Empty DTO type for operations that don't require validation.
13
+ * Use when a service/validator doesn't need a specific DTO for an operation.
14
+ */
15
+ export interface EmptyDTO {
16
+ }
17
+ /**
18
+ * Standard delete options for domain services.
19
+ * Supports soft delete (mark as deleted) or hard delete (permanent removal).
20
+ */
21
+ export interface CoreDeleteOptions {
22
+ /** If true, performs soft delete (sets deleted_at). If false, permanently removes. */
23
+ soft?: boolean;
24
+ }
11
25
  /**
12
26
  * Base interface for all domain services.
13
27
  *
@@ -19,4 +19,4 @@
19
19
  */
20
20
  export { CoreEventScope, SystemEventAction, EntityEventAction, ValidationEventAction, SanitizationEventAction, ApiEventAction, CacheEventAction, AuthEventAction, DatabaseEventAction, FeatureFlagEventAction, StoreEventAction, StorageEventAction, NotificationEventAction, CORE_EVENTS, } from './enums';
21
21
  export type { CoreEventScopeType, SystemEventType, EntityEventType, ValidationEventType, SanitizationEventType, ApiEventType, CacheEventType, AuthEventType, DatabaseEventType, FeatureFlagEventType, StoreEventType, CoreEventType, } from './enums';
22
- export type { CoreEvent, CoreCrudOperation, CoreValidationStartedPayload, CoreValidationSuccessPayload, CoreValidationFailedPayload, CoreSanitizationStartedPayload, CoreSanitizationSuccessPayload, CoreSanitizationFailedPayload, CoreEntityCreatedPayload, CoreEntityUpdatedPayload, CoreEntityPatchedPayload, CoreEntityDeletedPayload, CoreEntityCreatingPayload, CoreEntityUpdatingPayload, CoreEntityPatchingPayload, CoreEntityDeletingPayload, CoreEntityErrorPayload, CoreEntityCompletePayload, CoreBulkCreatedPayload, CoreBulkDeletedPayload, CoreSystemInitializedPayload, CoreSystemReadyPayload, CoreSystemShutdownPayload, CoreSystemErrorPayload, CoreSystemWarningPayload, CoreApiRequestStartPayload, CoreApiRequestSuccessPayload, CoreApiRequestErrorPayload, CoreApiRetryPayload, CoreApiTimeoutPayload, CoreCacheHitPayload, CoreCacheMissPayload, CoreCacheSetPayload, CoreCacheDeletePayload, CoreCacheClearPayload, CoreCacheExpiredPayload, CoreCacheErrorPayload, CoreDatabaseConnectedPayload, CoreDatabaseDisconnectedPayload, CoreDatabaseQueryPayload, CoreDatabaseErrorPayload, CoreDatabaseTransactionStartPayload, CoreDatabaseTransactionCommitPayload, CoreDatabaseTransactionRollbackPayload, CoreAuthLoginPayload, CoreAuthLogoutPayload, CoreAuthTokenRefreshPayload, CoreAuthSessionExpiredPayload, CoreAuthUnauthorizedPayload, CoreFeatureFlagChangedPayload, CoreFeatureFlagEvaluatedPayload, CoreFeatureFlagRefreshedPayload, CoreStoreUpdatedPayload, CoreStoreResetPayload, CoreStoreHydratedPayload, CoreStorageUploadedPayload, CoreStorageDownloadedPayload, CoreStorageDeletedPayload, CoreStorageErrorPayload, CoreStorageHealthCheckPayload, CoreNotificationSentPayload, CoreNotificationFailedPayload, CoreNotificationDeliveredPayload, CoreNotificationOpenedPayload, CoreNotificationClickedPayload, CoreNotificationErrorPayload, CoreNotificationHealthCheckPayload, CoreEventPayloadMap, } from './payloads';
22
+ export type { CoreEvent, CoreCrudOperation, CoreValidationStartedPayload, CoreValidationSuccessPayload, CoreValidationFailedPayload, CoreSanitizationStartedPayload, CoreSanitizationSuccessPayload, CoreSanitizationFailedPayload, CoreEntityCreatedPayload, CoreEntityUpdatedPayload, CoreEntityPatchedPayload, CoreEntityDeletedPayload, CoreEntityCreatingPayload, CoreEntityUpdatingPayload, CoreEntityPatchingPayload, CoreEntityDeletingPayload, CoreEntityErrorPayload, CoreEntityCompletePayload, CoreBulkCreatedPayload, CoreBulkDeletedPayload, CoreSystemInitializedPayload, CoreSystemReadyPayload, CoreSystemShutdownPayload, CoreSystemErrorPayload, CoreSystemWarningPayload, CoreApiRequestStartPayload, CoreApiRequestSuccessPayload, CoreApiRequestErrorPayload, CoreApiRetryPayload, CoreApiTimeoutPayload, CoreCacheHitPayload, CoreCacheMissPayload, CoreCacheSetPayload, CoreCacheDeletePayload, CoreCacheClearPayload, CoreCacheExpiredPayload, CoreCacheErrorPayload, CoreDatabaseConnectedPayload, CoreDatabaseDisconnectedPayload, CoreDatabaseQueryPayload, CoreDatabaseErrorPayload, CoreDatabaseTransactionStartPayload, CoreDatabaseTransactionCommitPayload, CoreDatabaseTransactionRollbackPayload, CoreAuthLoginPayload, CoreAuthLogoutPayload, CoreAuthTokenRefreshPayload, CoreAuthSessionExpiredPayload, CoreAuthUnauthorizedPayload, CoreFeatureFlagChangedPayload, CoreFeatureFlagEvaluatedPayload, CoreFeatureFlagRefreshedPayload, CoreStoreUpdatedPayload, CoreStoreResetPayload, CoreStoreHydratedPayload, CoreOperationRequestPayload, CoreOperationResultPayload, CoreOperationErrorPayload, CoreStorageUploadedPayload, CoreStorageDownloadedPayload, CoreStorageDeletedPayload, CoreStorageErrorPayload, CoreStorageHealthCheckPayload, CoreNotificationSentPayload, CoreNotificationFailedPayload, CoreNotificationDeliveredPayload, CoreNotificationOpenedPayload, CoreNotificationClickedPayload, CoreNotificationErrorPayload, CoreNotificationHealthCheckPayload, CoreEventPayloadMap, EventPersistenceConfig, DomainPersistenceConfig, } from './payloads';
@@ -505,6 +505,27 @@ export interface CoreStorageHealthCheckPayload {
505
505
  healthy: boolean;
506
506
  }[];
507
507
  }
508
+ /**
509
+ * Generic payload for operation request events (e.g., upload:uploading, email:sending)
510
+ * Used by domain services for storage/notification operations.
511
+ */
512
+ export interface CoreOperationRequestPayload<TRequest = unknown> {
513
+ request: TRequest;
514
+ }
515
+ /**
516
+ * Generic payload for operation result events (e.g., upload:uploaded, email:sent)
517
+ * Used by domain services for storage/notification operations.
518
+ */
519
+ export interface CoreOperationResultPayload<TResult = unknown> {
520
+ result: TResult;
521
+ }
522
+ /**
523
+ * Generic payload for operation error events (e.g., upload:error, email:error)
524
+ * Used by domain services for storage/notification operations.
525
+ */
526
+ export interface CoreOperationErrorPayload {
527
+ error: unknown;
528
+ }
508
529
  /**
509
530
  * Payload for notification:sent events
510
531
  */
@@ -658,3 +679,62 @@ export interface CoreEventPayloadMap {
658
679
  [CORE_EVENTS.NOTIFICATION.ERROR]: CoreNotificationErrorPayload;
659
680
  [CORE_EVENTS.NOTIFICATION.HEALTH_CHECK]: CoreNotificationHealthCheckPayload;
660
681
  }
682
+ /**
683
+ * Event configuration for persistence
684
+ * Defines how to extract and validate items from event payloads
685
+ *
686
+ * @typeParam TPayload - Event payload type
687
+ * @typeParam TItem - Item type extracted from payload
688
+ */
689
+ export interface EventPersistenceConfig<TPayload = unknown, TItem = unknown> {
690
+ /** Extract item(s) from event payload */
691
+ extractPayload: (payload: TPayload) => TItem | TItem[] | undefined;
692
+ /** Whether this event contains multiple items */
693
+ isBulk: boolean;
694
+ /** Optional: validate item before persisting */
695
+ validate?: (item: TItem) => boolean;
696
+ }
697
+ /**
698
+ * Domain persistence handler configuration
699
+ * Used by BackendEventPersistenceHandler to register event-to-DB persistence
700
+ *
701
+ * @typeParam TRepository - Repository type for database operations
702
+ * @typeParam TMapper - Mapper type for transforming items to DB rows
703
+ * @typeParam TItem - Item type extracted from event payload
704
+ * @typeParam TDbRow - Database row type
705
+ *
706
+ * @example
707
+ * ```typescript
708
+ * BackendEventPersistenceHandler.register<
709
+ * FilesRepository,
710
+ * FilesMapper,
711
+ * UploadResultItem,
712
+ * Partial<FilesDatabaseRow>
713
+ * >({
714
+ * domain: 'files',
715
+ * events: { ... },
716
+ * loadDependencies: async () => ({ repository, mapper }),
717
+ * mapToDbRow: (mapper, item) => mapper.eventPayloadToDbRow(item),
718
+ * createRecord: async (repo, row) => repo.create(row),
719
+ * });
720
+ * ```
721
+ */
722
+ export interface DomainPersistenceConfig<TRepository = unknown, TMapper = unknown, TItem = unknown, TDbRow = unknown> {
723
+ /** Domain name (e.g., 'files', 'notifications') */
724
+ domain: string;
725
+ /** Event configurations keyed by event name */
726
+ events: Record<string, EventPersistenceConfig<unknown, TItem>>;
727
+ /** Load repository and mapper (async to avoid circular deps) */
728
+ loadDependencies: () => Promise<{
729
+ repository: TRepository;
730
+ mapper: TMapper;
731
+ }>;
732
+ /** Map item to database row using mapper */
733
+ mapToDbRow: (mapper: TMapper, item: TItem) => TDbRow;
734
+ /** Create record in repository */
735
+ createRecord: (repository: TRepository, dbRow: TDbRow) => Promise<unknown>;
736
+ /** Optional: get unique key for deduplication logging */
737
+ getUniqueKey?: (item: TItem) => string;
738
+ /** Enable verbose logging */
739
+ verbose?: boolean;
740
+ }
@@ -5,8 +5,8 @@
5
5
  import type { DrizzleConfig, SupabaseConfig, SqlConfig, SoftDeleteConfig, DBCacheConfig, AuditConfig, DBEncryptionConfig } from '../../db';
6
6
  import type { ReactNode } from 'react';
7
7
  import type { ApiClientOptions } from '../../api/client';
8
- import type { StorageServiceConfig } from '../../storage';
9
- import type { NotificationServiceConfig } from '../../notifications';
8
+ import type { StorageServiceConfig, StorageServiceInstance } from '../../storage';
9
+ import type { NotificationServiceConfig, NotificationServiceInstance } from '../../notifications';
10
10
  import type { CacheStrategyType } from '../../features';
11
11
  import type { BackendErrorStore, BackendErrorStoreConfig, HttpErrorHandlerConfig } from '../../errors/middleware';
12
12
  export interface CoreCacheConfig {
@@ -575,16 +575,26 @@ export interface CoreCacheManagerInstance {
575
575
  /**
576
576
  * Core's StorageService instance interface
577
577
  * Returned by Core.storage and StorageService.getInstance()
578
+ *
579
+ * This is a wrapper around the actual StorageServiceInstance.
580
+ * Use getStorage() to access the underlying storage service with all methods.
578
581
  */
579
582
  export interface CoreStorageServiceInstance {
583
+ /** Get the underlying storage service (Proxy-based method forwarding) */
584
+ getStorage(): StorageServiceInstance;
580
585
  /** Close/cleanup the storage service */
581
586
  close(): Promise<void>;
582
587
  }
583
588
  /**
584
589
  * Core's NotificationService instance interface
585
590
  * Returned by Core.notifications - wraps the actual @plyaz/notifications service
591
+ *
592
+ * This is a wrapper around the actual NotificationServiceInstance.
593
+ * Use getNotifications() to access the underlying notification service with all methods.
586
594
  */
587
595
  export interface CoreNotificationServiceInstance {
596
+ /** Get the underlying notification service (Proxy-based method forwarding) */
597
+ getNotifications(): NotificationServiceInstance;
588
598
  /** Close/cleanup the notification service */
589
599
  close(): Promise<void>;
590
600
  }
@@ -137,14 +137,14 @@ export interface DatabaseAdapterType {
137
137
  * @param options - Query options including filters, sorting, and pagination
138
138
  * @returns Promise resolving to DatabaseResult containing paginated data
139
139
  */
140
- findMany<T extends Record<string, unknown>>(table: string, options?: QueryOptions<T>): Promise<DatabaseResult<PaginatedResult<T>>>;
140
+ findMany<T extends object>(table: string, options?: QueryOptions<T>): Promise<DatabaseResult<PaginatedResult<T>>>;
141
141
  /**
142
142
  * Create a new record
143
143
  * @param table - Table name
144
144
  * @param data - Record data to create
145
145
  * @returns Promise resolving to DatabaseResult containing the created record
146
146
  */
147
- create<T extends Record<string, unknown>>(table: string, data: T): Promise<DatabaseResult<T>>;
147
+ create<T extends object>(table: string, data: T): Promise<DatabaseResult<T>>;
148
148
  /**
149
149
  * Update an existing record
150
150
  * @param table - Table name
@@ -179,7 +179,7 @@ export interface DatabaseAdapterType {
179
179
  * @param filter - Filter conditions
180
180
  * @returns Promise resolving to DatabaseResult containing the count
181
181
  */
182
- count<T extends Record<string, unknown> = Record<string, unknown>>(table: string, filter?: Filter<T>): Promise<DatabaseResult<number>>;
182
+ count<T extends object = object>(table: string, filter?: Filter<T>): Promise<DatabaseResult<number>>;
183
183
  /**
184
184
  * Perform health check on the database connection
185
185
  * @returns Promise resolving to DatabaseResult containing health status
@@ -91,7 +91,7 @@ export interface DatabaseServiceInterface {
91
91
  * @param config - Optional per-operation configuration overrides
92
92
  * @returns Promise resolving to the record or null
93
93
  */
94
- get<T extends Record<string, unknown>>(table: TableName, id: string, config?: OperationConfig): Promise<DatabaseResult<T | null>>;
94
+ get<T extends object>(table: TableName, id: string, config?: OperationConfig): Promise<DatabaseResult<T | null>>;
95
95
  /**
96
96
  * List records with optional filtering, sorting, and pagination
97
97
  * @param table - Table name
@@ -99,7 +99,7 @@ export interface DatabaseServiceInterface {
99
99
  * @param config - Optional per-operation configuration overrides
100
100
  * @returns Promise resolving to paginated results
101
101
  */
102
- list<T extends Record<string, unknown>>(table: TableName, options?: QueryOptions<T>, config?: OperationConfig): Promise<DatabaseResult<PaginatedResult<T>>>;
102
+ list<T extends object>(table: TableName, options?: QueryOptions<T>, config?: OperationConfig): Promise<DatabaseResult<PaginatedResult<T>>>;
103
103
  /**
104
104
  * Create a new record
105
105
  * @param table - Table name
@@ -107,7 +107,7 @@ export interface DatabaseServiceInterface {
107
107
  * @param config - Optional per-operation configuration overrides
108
108
  * @returns Promise resolving to the created record
109
109
  */
110
- create<T extends Record<string, unknown>>(table: TableName, input: CreateInput<T>, config?: OperationConfig): Promise<DatabaseResult<T>>;
110
+ create<T extends object>(table: TableName, input: CreateInput<T>, config?: OperationConfig): Promise<DatabaseResult<T>>;
111
111
  /**
112
112
  * Update an existing record
113
113
  * @param table - Table name
@@ -116,7 +116,7 @@ export interface DatabaseServiceInterface {
116
116
  * @param config - Optional per-operation configuration overrides
117
117
  * @returns Promise resolving to the updated record
118
118
  */
119
- update<T extends Record<string, unknown>>(table: TableName, id: string, input: UpdateInput<T>, config?: OperationConfig): Promise<DatabaseResult<T>>;
119
+ update<T extends object>(table: TableName, id: string, input: UpdateInput<T>, config?: OperationConfig): Promise<DatabaseResult<T>>;
120
120
  /**
121
121
  * Delete a record
122
122
  * @param table - Table name
@@ -132,7 +132,7 @@ export interface DatabaseServiceInterface {
132
132
  * @param config - Optional per-operation configuration overrides
133
133
  * @returns Promise resolving to array of created records
134
134
  */
135
- batchCreate<T extends Record<string, unknown>>(table: TableName, inputs: CreateInput<T>[], config?: OperationConfig): Promise<DatabaseResult<T[]>>;
135
+ batchCreate<T extends object>(table: TableName, inputs: CreateInput<T>[], config?: OperationConfig): Promise<DatabaseResult<T[]>>;
136
136
  /**
137
137
  * Update multiple records in a batch
138
138
  * @param table - Table name
@@ -140,7 +140,7 @@ export interface DatabaseServiceInterface {
140
140
  * @param config - Optional per-operation configuration overrides
141
141
  * @returns Promise resolving to array of updated records
142
142
  */
143
- batchUpdate<T extends Record<string, unknown>>(table: TableName, updates: BatchUpdate<T>[], config?: OperationConfig): Promise<DatabaseResult<T[]>>;
143
+ batchUpdate<T extends object>(table: TableName, updates: BatchUpdate<T>[], config?: OperationConfig): Promise<DatabaseResult<T[]>>;
144
144
  /**
145
145
  * Delete multiple records in a batch
146
146
  * @param table - Table name
@@ -156,7 +156,7 @@ export interface DatabaseServiceInterface {
156
156
  * @param config - Optional per-operation configuration overrides
157
157
  * @returns Promise resolving to paginated results
158
158
  */
159
- query<T extends Record<string, unknown>>(table: TableName, query: QueryOptions<T>, config?: OperationConfig): Promise<DatabaseResult<PaginatedResult<T>>>;
159
+ query<T extends object>(table: TableName, query: QueryOptions<T>, config?: OperationConfig): Promise<DatabaseResult<PaginatedResult<T>>>;
160
160
  /**
161
161
  * Count records matching a filter
162
162
  * @param table - Table name
@@ -164,7 +164,7 @@ export interface DatabaseServiceInterface {
164
164
  * @param config - Optional per-operation configuration overrides
165
165
  * @returns Promise resolving to the count
166
166
  */
167
- count<T extends Record<string, unknown> = Record<string, unknown>>(table: TableName, filter?: Filter<T>, config?: OperationConfig): Promise<DatabaseResult<number>>;
167
+ count<T extends object = object>(table: TableName, filter?: Filter<T>, config?: OperationConfig): Promise<DatabaseResult<number>>;
168
168
  /**
169
169
  * Find a single record by filter conditions
170
170
  * @param table - Table name
@@ -172,7 +172,7 @@ export interface DatabaseServiceInterface {
172
172
  * @param config - Optional per-operation configuration overrides
173
173
  * @returns Promise resolving to the first matching record or null
174
174
  */
175
- findOne<T extends Record<string, unknown>>(table: TableName, filter: Filter<T>, config?: OperationConfig): Promise<DatabaseResult<T | null>>;
175
+ findOne<T extends object>(table: TableName, filter: Filter<T>, config?: OperationConfig): Promise<DatabaseResult<T | null>>;
176
176
  /**
177
177
  * Soft delete a record (logical deletion)
178
178
  * @param table - Table name
@@ -14,4 +14,4 @@
14
14
  * ```
15
15
  */
16
16
  export { CreateExampleSchema, UpdateExampleSchema, PatchExampleSchema, QueryExampleSchema, DeleteExampleSchema, ExampleResponseSchema, ExampleListResponseSchema, } from './schemas';
17
- export type { CreateExampleDTO, UpdateExampleDTO, PatchExampleDTO, QueryExampleDTO, DeleteExampleDTO, ExampleResponseDTO, ExampleListResponseDTO, ExampleEntity, ExampleStoreItem, ExampleStoreState, ExampleCreatedPayload, ExampleUpdatedPayload, ExampleDeletedPayload, ExampleValidationFailedPayload, ExampleFrontendStoreData, ExampleFrontendStoreState, ExampleFrontendStoreActions, ExampleFrontendStoreSlice, ExampleFrontendServiceConfig, ExampleFrontendEventType, ExampleUser, ExampleDomainServiceConfig, } from './types';
17
+ export type { CreateExampleDTO, UpdateExampleDTO, PatchExampleDTO, QueryExampleDTO, DeleteExampleDTO, ExampleResponseDTO, ExampleListResponseDTO, ExampleEntity, ExampleStoreItem, ExampleStoreState, ExampleCreatedPayload, ExampleUpdatedPayload, ExampleDeletedPayload, ExampleValidationFailedPayload, ExampleFrontendStoreData, ExampleFrontendStoreState, ExampleFrontendStoreActions, ExampleFrontendStoreSlice, ExampleFrontendServiceConfig, ExampleFrontendEventType, ExampleUser, ExampleDomainServiceConfig, ExampleGenerateDocumentDTO, ExampleGenerateDocumentResult, ExampleUploadFileDTO, ExampleUploadFileResult, ExampleSendEmailDTO, ExampleSendEmailResult, } from './types';
@@ -165,6 +165,69 @@ export interface ExampleUser extends Record<string, unknown> {
165
165
  updated_at?: string;
166
166
  deleted_at?: string | null;
167
167
  }
168
+ import type { GenerateFileParams, UploadParams, UploadResult } from '../storage';
169
+ import type { SendEmailParams, NotificationResult, NotificationResponse } from '../notifications';
170
+ /**
171
+ * DTO for generating a document (NO upload) using storage template engine.
172
+ * Re-exports GenerateFileParams from @plyaz/types/storage.
173
+ *
174
+ * Uses storage.generateFile() which:
175
+ * 1. Loads template from templates/{locale}/{category}/{templateId}.md
176
+ * 2. Renders with Handlebars + templateData
177
+ * 3. Converts to PDF/DOCX/XLSX
178
+ * 4. Returns Buffer (caller handles the buffer)
179
+ */
180
+ export type ExampleGenerateDocumentDTO = GenerateFileParams;
181
+ /**
182
+ * Result of document generation (Buffer-based, no URL).
183
+ * This is specific to the example service's JSON response format.
184
+ */
185
+ export interface ExampleGenerateDocumentResult {
186
+ /** Generated document buffer (base64 encoded for JSON transport) */
187
+ buffer: string;
188
+ /** File size in bytes */
189
+ size: number;
190
+ }
191
+ /**
192
+ * DTO for generating AND uploading a document using storage template engine.
193
+ * Re-exports UploadParams from @plyaz/types/storage.
194
+ *
195
+ * Uses storage.uploadFile() with templateId which:
196
+ * 1. Loads template from templates/{locale}/{category}/{templateId}.md
197
+ * 2. Renders with Handlebars + templateData
198
+ * 3. Converts to PDF/DOCX/XLSX
199
+ * 4. Uploads to storage (R2/Supabase)
200
+ * 5. Returns URL
201
+ *
202
+ * NOTE: In production, generated documents should be linked to entities via
203
+ * a media table with foreign keys (e.g., campaign_id -> media.entity_id).
204
+ */
205
+ export type ExampleUploadFileDTO = UploadParams;
206
+ /**
207
+ * Result of file upload (with URL).
208
+ * Re-exports UploadResult from @plyaz/types/storage.
209
+ */
210
+ export type ExampleUploadFileResult = UploadResult;
211
+ /**
212
+ * DTO for sending an email using notification templates.
213
+ * Re-exports SendEmailParams from @plyaz/types/notifications.
214
+ *
215
+ * Uses notifications.sendEmail() which:
216
+ * 1. Loads template from templates/{locale}/email/{templateId}.md
217
+ * 2. Parses frontmatter (subject, layout, etc.)
218
+ * 3. Renders Markdown to HTML with templateData
219
+ * 4. Inlines CSS for email clients
220
+ * 5. Sends via configured provider (Infobip/SendGrid)
221
+ *
222
+ * NOTE: In production, sent emails should be tracked in a notifications
223
+ * table with foreign keys (e.g., campaign_id -> notifications.entity_id).
224
+ */
225
+ export type ExampleSendEmailDTO = SendEmailParams;
226
+ /**
227
+ * Result of sending an email.
228
+ * Uses NotificationResult<NotificationResponse> from @plyaz/types/notifications.
229
+ */
230
+ export type ExampleSendEmailResult = NotificationResult<NotificationResponse>;
168
231
  /**
169
232
  * Example Domain Service Configuration
170
233
  */
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  export * from './auth';
2
2
  export type * from './common';
3
3
  export * from './core';
4
+ export type * from './store';
4
5
  export type * from './entities';
5
6
  export * from './errors';
6
7
  export * from './events';
7
8
  export * from './http/constants';
8
9
  export * from './locale/types';
9
- export type * from './store';
10
10
  export type * from './ui';
11
11
  export * from './web3';
12
12
  export type * from './translations';
@@ -3,7 +3,7 @@
3
3
  * @module @plyaz/types/storage
4
4
  */
5
5
  export { ADAPTER_HEALTH_STATUS, ENTITY_TYPE, FILE_ACCESS_LEVEL, FILE_CATEGORY, FILE_VALIDATION_ERROR, MEDIA_VARIANT_TYPE, OUTPUT_FORMAT, PATH_GENERATION_STRATEGY, STORAGE_RENDERER_TYPE, RETRY_STRATEGY, STORAGE_ADAPTER_TYPE, STORAGE_EVENT_TYPE, STORAGE_QUEUE_PRIORITY, TEMPLATE_OUTPUT_FORMAT, DOCUMENT_TYPE, MEDIA_ENTITY, STORAGE_VISIBILITY, STORAGE_ENVIRONMENT, BUSINESS_MODEL, ORGANIZATION_TIER, BUCKET_PURPOSE, PATH_STRATEGY, UPLOAD_STATUS, STORAGE_JURISDICTION, STORAGE_REGULATORY_FRAMEWORK, STORAGE_PLUGIN_TYPE, STORAGE_WEBHOOK_EVENT_TYPE, STORAGE_OPERATION, STORAGE_SIGNATURE_METHOD, STORAGE_DEVICE_TYPE, STORAGE_VARIANT_NAME, TEMPLATE_VARIABLE_TYPE, TEMPLATE_DOCUMENT_TYPE, } from './enums';
6
- export type { AdapterHealthCheck, BaseStorageAdapterConfig, BucketConfiguration, BucketRouterConfig, CompliancePathOptions, CloudflareR2Config, CorsConfig, CustomAdapterConfig, DeleteParams, DownloadParams, DownloadResult, FileDeleteResult, FileMetadata, FileValidationResult, GeneralPathOptions, MediaPathOptions, MediaProcessingOptions, MockAdapterConfig, PathGenerationConfig, PDFRenderOptions, PresignedUrlOptions, PresignedUrlResult, StorageExcelRenderOptions, StorageWordRenderOptions, StorageFileOperationType, StorageQueueProcessFunction, StorageQueuedOperation, QueueItem, StorageQueueStatistics, RetentionPolicy, RoutingCondition, RoutingDecision, RoutingRule, ShareLinkConfig, StorageApiClientConfig, StorageCategory, StorageComplianceRule, StorageEventPayload, StorageEventHandlers, StorageLayoutConfig, StorageRenderOptions, StorageRendererAdapterConfig, StorageRendererHealthCheck, StorageRenderResult, StorageResult, StorageQueueConfig, StorageRetryConfig, StorageServiceConfig, StorageTemplateCacheEntry, StorageTemplateEngineConfig, StorageTemplateFrontmatter, StorageTemplateRenderResult, StorageTranslationService, SupabaseStorageConfig, TemplateConfig, TemplateService, UploadParams, UploadProgressEvent, UploadResult, ValidationRule, MultipartUploadPart, BucketDeletionResult, BucketPurposeValidationRules, StorageValidationConfig, StorageAdapterRegistryConfig, StorageEventManagerConfig, StorageQueueProcessorConfig, StorageComplianceManagerConfig, StorageRendererRegistryConfig, StorageLayoutEngineConfig, StorageAppliedLayout, StorageTranslationServiceConfig, FileSystemTemplateServiceConfig, StorageDocxTemplaterRendererConfig, StorageWordDocumentData, StoragePlaywrightRendererConfig, StoragePDFKitRendererConfig, StoragePDFKitDocumentData, StorageExcelJSRendererConfig, StorageExcelData, StoragePuppeteerRendererConfig, StorageMediaProcessingWebhookConfig, StorageRetryOptions, StorageHashPathOptions, StorageEntityPathOptions, StorageDatePathOptions, StorageCategoryPathOptions, StorageFlatPathOptions, StorageTemplateVariables, StorageSignedUrlOptions, StorageVerificationResult, StorageEventCallback, StoragePathHashAlgorithm, StorageHashAlgorithm, StorageSignedUrlPermission, StorageAdapterCapability, StorageVariantConfig, StoragePresetConfig, StorageResolvedVariant, StoragePresetManagerConfig, StorageResolveVariantsOptions, StorageBucketDeletionResult, StorageChunkExtractionResult, StorageChunkUploadPartResult, StorageBucketInfo, StorageCopyFileParams, StorageListBucketsResult, StorageListFilesParams, StorageListFilesResult, StorageMoveFileParams, StoragePublicUrlParams, StorageReplaceFileParams, StorageSignedUploadUrlParams, StorageSignedUploadUrlResult, StorageUpdateBucketParams, GenerateFileParams, GenerateFileToPathParams, GenerateFileToPathResult, UpdateFileParams, TemplateVariableValidation, TemplateVariableDefinition, TemplateVariableValidationResult, TemplateVariablesFrontmatter, CustomValidationSchema, TemplateValidationOptions, StorageTemplateRenderResultWithValidation, StorageTemplateValidationDataResult, StorageTemplateRenderToHtmlOptions, StorageTemplateBuildMetadataOptions, StorageTemplateTypeCoercionResult, StorageTemplateInvoiceLineItem, StorageTemplateInvoiceTotalOptions, StorageTemplateInvoiceTotalArgs, } from './interfaces';
6
+ export type { AdapterHealthCheck, BaseStorageAdapterConfig, BucketConfiguration, BucketRouterConfig, CompliancePathOptions, CloudflareR2Config, CorsConfig, CustomAdapterConfig, DeleteParams, DownloadParams, DownloadResult, FileDeleteResult, FileMetadata, FileValidationResult, GeneralPathOptions, MediaPathOptions, MediaProcessingOptions, MockAdapterConfig, PathGenerationConfig, PDFRenderOptions, PresignedUrlOptions, PresignedUrlResult, StorageExcelRenderOptions, StorageWordRenderOptions, StorageFileOperationType, StorageQueueProcessFunction, StorageQueuedOperation, QueueItem, StorageQueueStatistics, RetentionPolicy, RoutingCondition, RoutingDecision, RoutingRule, ShareLinkConfig, StorageApiClientConfig, StorageCategory, StorageComplianceRule, StorageEventPayload, StorageEventHandlers, StorageLayoutConfig, StorageRenderOptions, StorageRendererAdapterConfig, StorageRendererHealthCheck, StorageRenderResult, StorageResult, StorageQueueConfig, StorageRetryConfig, StorageServiceConfig, StorageTemplateCacheEntry, StorageTemplateEngineConfig, StorageTemplateFrontmatter, StorageTemplateRenderResult, StorageTranslationService, SupabaseStorageConfig, TemplateConfig, TemplateService, UploadParams, UploadProgressEvent, UploadResult, ValidationRule, MultipartUploadPart, BucketDeletionResult, BucketPurposeValidationRules, StorageValidationConfig, StorageAdapterRegistryConfig, StorageEventManagerConfig, StorageQueueProcessorConfig, StorageComplianceManagerConfig, StorageRendererRegistryConfig, StorageLayoutEngineConfig, StorageAppliedLayout, StorageTranslationServiceConfig, FileSystemTemplateServiceConfig, StorageDocxTemplaterRendererConfig, StorageWordDocumentData, StoragePlaywrightRendererConfig, StoragePDFKitRendererConfig, StoragePDFKitDocumentData, StorageExcelJSRendererConfig, StorageExcelData, StoragePuppeteerRendererConfig, StorageMediaProcessingWebhookConfig, StorageRetryOptions, StorageHashPathOptions, StorageEntityPathOptions, StorageDatePathOptions, StorageCategoryPathOptions, StorageFlatPathOptions, StorageTemplateVariables, StorageSignedUrlOptions, StorageVerificationResult, StorageEventCallback, StoragePathHashAlgorithm, StorageHashAlgorithm, StorageSignedUrlPermission, StorageAdapterCapability, StorageVariantConfig, StoragePresetConfig, StorageResolvedVariant, StoragePresetManagerConfig, StorageResolveVariantsOptions, StorageBucketDeletionResult, StorageChunkExtractionResult, StorageChunkUploadPartResult, StorageBucketInfo, StorageCopyFileParams, StorageListBucketsResult, StorageListFilesParams, StorageListFilesResult, StorageMoveFileParams, StoragePublicUrlParams, StorageReplaceFileParams, StorageSignedUploadUrlParams, StorageSignedUploadUrlResult, StorageUpdateBucketParams, GenerateFileParams, GenerateFileToPathParams, GenerateFileToPathResult, UpdateFileParams, TemplateVariableValidation, TemplateVariableDefinition, TemplateVariableValidationResult, TemplateVariablesFrontmatter, CustomValidationSchema, TemplateValidationOptions, StorageTemplateRenderResultWithValidation, StorageTemplateValidationDataResult, StorageTemplateRenderToHtmlOptions, StorageTemplateBuildMetadataOptions, StorageTemplateTypeCoercionResult, StorageTemplateInvoiceLineItem, StorageTemplateInvoiceTotalOptions, StorageTemplateInvoiceTotalArgs, StorageServiceInstance, } from './interfaces';
7
7
  export { STORAGE_EVENT_HANDLER_MAPPING, STORAGE_EVENT_TYPE_TO_HANDLER_NAME, WEBHOOK_EVENT_TYPE_MAPPING, } from './event-handler-mapping';
8
8
  export type { StorageEventHandlerName, MappedStorageEventType } from './event-handler-mapping';
9
9
  export type { StorageRetentionPolicyType, StorageRetentionStrategy, StorageImmutabilityStrategy, StorageDeletionReason, StorageRetentionPolicy, StorageComplianceConfig, StorageComplianceCheckResult, StorageDeleteComplianceOptions, StorageBulkDeleteResult, StorageComplianceEventMetadata, StorageSoftDeleteMetadata, StorageJurisdictionContext, } from './compliance';