@igorchugurov/public-api-sdk 1.0.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.
@@ -0,0 +1,1175 @@
1
+ import { SupabaseClient } from '@supabase/supabase-js';
2
+
3
+ /**
4
+ * Типы для UI конфигурации сущностей
5
+ * Единый источник истины для UI типов в SDK
6
+ *
7
+ * Эти типы используются для автоматической генерации:
8
+ * - Страниц списков (list pages)
9
+ * - Страниц редактирования/создания (form pages)
10
+ * - UI элементов (кнопки, сообщения, модалки)
11
+ */
12
+ interface ListPageConfig {
13
+ pageTitle: string;
14
+ searchPlaceholder?: string;
15
+ emptyStateTitle: string;
16
+ emptyStateMessages: string[];
17
+ showCreateButton: boolean;
18
+ createButtonText: string;
19
+ showSearch: boolean;
20
+ enablePagination: boolean;
21
+ pageSize?: number;
22
+ enableFilters: boolean;
23
+ searchableFields?: string[];
24
+ columns: ColumnConfig[];
25
+ }
26
+ interface ColumnConfig {
27
+ field: string;
28
+ headerName: string;
29
+ width?: number;
30
+ flex?: number;
31
+ type?: "text" | "date" | "number" | "boolean" | "naigateToDetails" | "openEditPage" | "actions" | "relation";
32
+ sortable?: boolean;
33
+ relationDbType?: "manyToOne" | "oneToOne" | "manyToMany" | "oneToMany";
34
+ actions?: ActionConfig[];
35
+ additionalUrl?: string;
36
+ }
37
+ interface ActionConfig {
38
+ action: "edit" | "delete" | "view" | "clone" | "copy" | "link";
39
+ icon?: string;
40
+ link?: boolean;
41
+ additionalUrl?: string;
42
+ label?: string;
43
+ /**
44
+ * Условие для скрытия action на основе данных строки
45
+ * Если значение поля `field` равно `value`, action скрывается
46
+ */
47
+ hideIf?: {
48
+ field: string;
49
+ value: string | number | boolean;
50
+ };
51
+ }
52
+ interface FormPageConfig {
53
+ createPageTitle: string;
54
+ editPageTitle: string;
55
+ pageHeader?: string;
56
+ createButtonLabel: string;
57
+ updateButtonLabel: string;
58
+ cancelButtonLabel?: string;
59
+ sectionTitles?: {
60
+ 0?: string;
61
+ 1?: string;
62
+ 2?: string;
63
+ 3?: string;
64
+ };
65
+ }
66
+ interface MessagesConfig {
67
+ afterCreate: string;
68
+ afterUpdate: string;
69
+ afterDelete: string;
70
+ errorCreate?: string;
71
+ errorUpdate?: string;
72
+ deleteModalTitle: string;
73
+ deleteModalText: string;
74
+ deleteModalConfirmWord?: string;
75
+ deleteModalConfirmText?: string;
76
+ deleteModalButtonText: string;
77
+ reloadEvents: {
78
+ create: string;
79
+ update: string;
80
+ delete: string;
81
+ };
82
+ }
83
+ interface EntityUIConfig {
84
+ list: ListPageConfig;
85
+ form: FormPageConfig;
86
+ messages: MessagesConfig;
87
+ apiUrl: string;
88
+ apiUrlAll?: string;
89
+ }
90
+ /**
91
+ * Partial UI конфиг для хранения в БД (uiConfig JSONB поле)
92
+ * Позволяет переопределить только нужные значения
93
+ */
94
+ type PartialUIConfig = {
95
+ list?: Partial<Omit<ListPageConfig, "columns">> & {
96
+ columns?: Partial<ColumnConfig>[];
97
+ };
98
+ form?: Partial<FormPageConfig>;
99
+ messages?: Partial<MessagesConfig>;
100
+ apiUrl?: string;
101
+ apiUrlAll?: string;
102
+ };
103
+
104
+ /**
105
+ * Типы для универсальной системы сущностей
106
+ * Единый источник истины для типов сущностей в SDK
107
+ */
108
+
109
+ interface EntityDefinition {
110
+ id: string;
111
+ name: string;
112
+ description?: string | null;
113
+ tableName: string;
114
+ type: "primary" | "secondary" | "tertiary";
115
+ projectId: string;
116
+ createPermission: "ALL" | "User" | "Admin" | "Admin|User" | "Owner" | "Owner|Admin" | "Owner|User";
117
+ readPermission: "ALL" | "User" | "Admin" | "Admin|User" | "Owner" | "Owner|Admin" | "Owner|User";
118
+ updatePermission: "ALL" | "User" | "Admin" | "Admin|User" | "Owner" | "Owner|Admin" | "Owner|User";
119
+ deletePermission: "ALL" | "User" | "Admin" | "Admin|User" | "Owner" | "Owner|Admin" | "Owner|User";
120
+ titleSection0?: string | null;
121
+ titleSection1?: string | null;
122
+ titleSection2?: string | null;
123
+ titleSection3?: string | null;
124
+ uiConfig?: PartialUIConfig | null;
125
+ enablePagination?: boolean | null;
126
+ pageSize?: number | null;
127
+ enableFilters?: boolean | null;
128
+ maxFileSizeMb?: number | null;
129
+ maxFilesCount?: number | null;
130
+ createdAt: string;
131
+ updatedAt: string;
132
+ }
133
+ type FieldType = "select" | "text" | "textarea" | "number" | "date" | "boolean" | "radio" | "multipleSelect" | "array" | "dynamicValue" | "files" | "images";
134
+ type DbType = "varchar" | "float" | "boolean" | "timestamptz" | "manyToOne" | "oneToMany" | "manyToMany" | "oneToOne" | "files";
135
+ interface FieldOption {
136
+ id: string;
137
+ name: string;
138
+ }
139
+ interface Field {
140
+ id: string;
141
+ entityDefinitionId: string;
142
+ name: string;
143
+ dbType: DbType;
144
+ type: FieldType;
145
+ label: string;
146
+ placeholder?: string | null;
147
+ description?: string | null;
148
+ forEditPage: boolean;
149
+ forCreatePage: boolean;
150
+ required: boolean;
151
+ requiredText?: string | null;
152
+ forEditPageDisabled: boolean;
153
+ displayIndex: number;
154
+ displayInTable: boolean;
155
+ sectionIndex: number;
156
+ isOptionTitleField: boolean;
157
+ searchable: boolean;
158
+ filterableInList?: boolean;
159
+ options?: FieldOption[];
160
+ relatedEntityDefinitionId?: string | null;
161
+ relationFieldId?: string | null;
162
+ isRelationSource: boolean;
163
+ selectorRelationId?: string | null;
164
+ relationFieldName?: string | null;
165
+ relationFieldLabel?: string | null;
166
+ defaultStringValue?: string | null;
167
+ defaultNumberValue?: number | null;
168
+ defaultBooleanValue?: boolean | null;
169
+ defaultDateValue?: string | null;
170
+ autoPopulate: boolean;
171
+ includeInSinglePma: boolean;
172
+ includeInListPma: boolean;
173
+ includeInSingleSa: boolean;
174
+ includeInListSa: boolean;
175
+ foreignKey?: string | null;
176
+ foreignKeyValue?: string | null;
177
+ typeFieldName?: string | null;
178
+ optionsFieldName?: string | null;
179
+ acceptFileTypes?: string | null;
180
+ maxFileSize?: number | null;
181
+ maxFiles?: number | null;
182
+ storageBucket?: string | null;
183
+ createdAt: string;
184
+ updatedAt: string;
185
+ }
186
+ /**
187
+ * Возможные типы значений полей в зависимости от DbType
188
+ */
189
+ type FieldValue = string | number | boolean | Date | string[] | null | undefined;
190
+ /**
191
+ * Маппинг DbType на TypeScript типы
192
+ */
193
+ type DbTypeToTSType = {
194
+ varchar: string;
195
+ float: number;
196
+ boolean: boolean;
197
+ timestamptz: string | Date;
198
+ manyToOne: string;
199
+ oneToMany: string[];
200
+ manyToMany: string[];
201
+ oneToOne: string;
202
+ files: string[];
203
+ };
204
+ /**
205
+ * Generic тип для данных сущности с типобезопасностью
206
+ */
207
+ type EntityData<T extends Record<string, FieldValue> = Record<string, FieldValue>> = T;
208
+ interface EntityInstance<TData extends Record<string, FieldValue> = Record<string, FieldValue>> {
209
+ id: string;
210
+ entityDefinitionId: string;
211
+ projectId: string;
212
+ data: EntityData<TData>;
213
+ createdBy?: string | null;
214
+ createdAt: string;
215
+ updatedAt: string;
216
+ }
217
+ type RelationType = "manyToMany" | "manyToOne" | "oneToMany" | "oneToOne";
218
+ interface EntityRelation {
219
+ id: string;
220
+ sourceInstanceId: string;
221
+ targetInstanceId: string;
222
+ relationFieldId: string;
223
+ reverseFieldId?: string | null;
224
+ relationType: RelationType;
225
+ createdAt: string;
226
+ }
227
+ /**
228
+ * Экземпляр сущности с полями и связями (плоская структура)
229
+ * Все поля размещены на верхнем уровне, без data и relations
230
+ */
231
+ type EntityInstanceWithFields<TFields extends Record<string, FieldValue> = Record<string, FieldValue>> = {
232
+ id: string;
233
+ entityDefinitionId: string;
234
+ projectId: string;
235
+ createdAt: string;
236
+ updatedAt: string;
237
+ } & TFields;
238
+ /**
239
+ * Тип фильтра для поля
240
+ */
241
+ type FilterValue = FieldValue | FieldValue[];
242
+ /**
243
+ * Конфигурация для получения списка экземпляров
244
+ */
245
+ interface GetInstancesOptions<TFilters extends Record<string, FilterValue> = Record<string, FilterValue>> {
246
+ includeRelations?: string[];
247
+ relationsAsIds?: boolean;
248
+ filters?: TFilters;
249
+ limit?: number;
250
+ offset?: number;
251
+ sortBy?: string;
252
+ sortOrder?: "asc" | "desc";
253
+ }
254
+ /**
255
+ * Данные для создания/обновления экземпляра
256
+ */
257
+ type InstanceData<TData extends Record<string, FieldValue> = Record<string, FieldValue>> = TData;
258
+ /**
259
+ * Связи для создания/обновления
260
+ */
261
+ interface RelationsData {
262
+ [fieldName: string]: string[];
263
+ }
264
+ /**
265
+ * Type guard для проверки, что значение является валидным FieldValue
266
+ */
267
+ declare function isFieldValue(value: unknown): value is FieldValue;
268
+ /**
269
+ * Type guard для проверки EntityData
270
+ */
271
+ declare function isEntityData(value: unknown): value is Record<string, FieldValue>;
272
+ /**
273
+ * Безопасное извлечение значения поля с типом
274
+ */
275
+ declare function getFieldValue<T extends FieldValue>(data: Record<string, FieldValue>, fieldName: string, defaultValue?: T): T | undefined;
276
+ /**
277
+ * Partial тип для обновления данных сущности
278
+ */
279
+ type PartialInstanceData<T extends Record<string, FieldValue>> = Partial<T>;
280
+ /**
281
+ * Файл, привязанный к экземпляру сущности
282
+ */
283
+ interface EntityFile {
284
+ id: string;
285
+ entityInstanceId: string;
286
+ fieldId?: string | null;
287
+ fileUrl: string;
288
+ filePath: string;
289
+ fileName: string;
290
+ fileSize: number;
291
+ fileType: string;
292
+ storageBucket: string;
293
+ uploadedBy?: string | null;
294
+ createdAt: string;
295
+ updatedAt: string;
296
+ }
297
+
298
+ /**
299
+ * Типы для публичного API SDK
300
+ */
301
+
302
+ /**
303
+ * Конфигурация проекта с entityDefinitions и fields
304
+ */
305
+ interface ProjectConfig {
306
+ project: {
307
+ id: string;
308
+ name: string;
309
+ enableSignIn: boolean;
310
+ enableSignUp: boolean;
311
+ };
312
+ entityDefinitions: EntityDefinitionConfig[];
313
+ }
314
+ /**
315
+ * Конфигурация entityDefinition с полями
316
+ * Расширенная версия со всеми полями для админки и публичного API
317
+ */
318
+ interface EntityDefinitionConfig {
319
+ id: string;
320
+ name: string;
321
+ description?: string | null;
322
+ tableName: string;
323
+ type: "primary" | "secondary" | "tertiary";
324
+ projectId: string;
325
+ readPermission: string;
326
+ createPermission: string;
327
+ updatePermission: string;
328
+ deletePermission: string;
329
+ titleSection0?: string | null;
330
+ titleSection1?: string | null;
331
+ titleSection2?: string | null;
332
+ titleSection3?: string | null;
333
+ uiConfig?: PartialUIConfig | null;
334
+ enablePagination?: boolean | null;
335
+ pageSize?: number | null;
336
+ enableFilters?: boolean | null;
337
+ maxFileSizeMb?: number | null;
338
+ maxFilesCount?: number | null;
339
+ createdAt: string;
340
+ updatedAt: string;
341
+ fields: FieldConfig[];
342
+ }
343
+ /**
344
+ * Конфигурация поля
345
+ * Расширенная версия со всеми полями для админки и публичного API
346
+ */
347
+ interface FieldConfig {
348
+ id: string;
349
+ entityDefinitionId: string;
350
+ name: string;
351
+ dbType: DbType;
352
+ type: FieldType;
353
+ label: string;
354
+ placeholder?: string | null;
355
+ description?: string | null;
356
+ forEditPage: boolean;
357
+ forCreatePage: boolean;
358
+ required: boolean;
359
+ requiredText?: string | null;
360
+ forEditPageDisabled: boolean;
361
+ displayIndex: number;
362
+ displayInTable: boolean;
363
+ sectionIndex: number;
364
+ isOptionTitleField: boolean;
365
+ searchable: boolean;
366
+ filterableInList?: boolean;
367
+ options?: FieldOption[];
368
+ relatedEntityDefinitionId?: string | null;
369
+ relationFieldId?: string | null;
370
+ isRelationSource: boolean;
371
+ selectorRelationId?: string | null;
372
+ relationFieldName?: string | null;
373
+ relationFieldLabel?: string | null;
374
+ defaultStringValue?: string | null;
375
+ defaultNumberValue?: number | null;
376
+ defaultBooleanValue?: boolean | null;
377
+ defaultDateValue?: string | null;
378
+ autoPopulate: boolean;
379
+ includeInSinglePma: boolean;
380
+ includeInListPma: boolean;
381
+ includeInSingleSa: boolean;
382
+ includeInListSa: boolean;
383
+ foreignKey?: string | null;
384
+ foreignKeyValue?: string | null;
385
+ typeFieldName?: string | null;
386
+ optionsFieldName?: string | null;
387
+ acceptFileTypes?: string | null;
388
+ maxFileSize?: number | null;
389
+ maxFiles?: number | null;
390
+ storageBucket?: string | null;
391
+ createdAt: string;
392
+ updatedAt: string;
393
+ }
394
+ /**
395
+ * Информация о фильтре для relation-поля
396
+ */
397
+ interface RelationFilterInfo {
398
+ fieldName: string;
399
+ fieldId: string;
400
+ }
401
+ /**
402
+ * Режим фильтрации для relation полей
403
+ * - 'any': хотя бы одно из выбранных значений (OR) - по умолчанию
404
+ * - 'all': все выбранные значения (AND)
405
+ */
406
+ type RelationFilterMode = "any" | "all";
407
+ /**
408
+ * Параметры запроса для получения списка экземпляров
409
+ */
410
+ interface QueryParams {
411
+ page?: number;
412
+ limit?: number;
413
+ search?: string;
414
+ filters?: Record<string, string[]>;
415
+ relationFilterModes?: Record<string, RelationFilterMode>;
416
+ sortBy?: string;
417
+ sortOrder?: "asc" | "desc";
418
+ relationsAsIds?: boolean;
419
+ }
420
+ /**
421
+ * Данные для создания экземпляра
422
+ */
423
+ interface CreateInstanceData {
424
+ data: Record<string, unknown>;
425
+ relations?: Record<string, string[]>;
426
+ }
427
+ /**
428
+ * Данные для обновления экземпляра
429
+ */
430
+ interface UpdateInstanceData {
431
+ data: Record<string, unknown>;
432
+ relations?: Record<string, string[]>;
433
+ }
434
+ /**
435
+ * Результат пагинации
436
+ */
437
+ interface PaginationResult {
438
+ page: number;
439
+ limit: number;
440
+ total: number;
441
+ totalPages: number;
442
+ hasPreviousPage: boolean;
443
+ hasNextPage: boolean;
444
+ }
445
+ /**
446
+ * Результат авторизации
447
+ */
448
+ interface AuthResult {
449
+ accessToken: string;
450
+ refreshToken: string;
451
+ expiresAt: number;
452
+ expiresIn: number;
453
+ user: {
454
+ id: string;
455
+ email: string;
456
+ firstName?: string;
457
+ lastName?: string;
458
+ role: string;
459
+ };
460
+ }
461
+ /**
462
+ * Данные для регистрации
463
+ */
464
+ interface SignUpData {
465
+ email: string;
466
+ password: string;
467
+ firstName?: string;
468
+ lastName?: string;
469
+ }
470
+ /**
471
+ * Опции для создания SDK клиента
472
+ */
473
+ interface SDKOptions {
474
+ enableCache?: boolean;
475
+ cacheTTL?: number;
476
+ }
477
+
478
+ /**
479
+ * Типы для Supabase Database
480
+ * Автономные типы для SDK - не зависят от внешних модулей
481
+ */
482
+ type Json = string | number | boolean | null | {
483
+ [key: string]: Json | undefined;
484
+ } | Json[];
485
+ interface Database {
486
+ public: {
487
+ Tables: {
488
+ profiles: {
489
+ Row: {
490
+ id: string;
491
+ email: string | null;
492
+ first_name: string | null;
493
+ last_name: string | null;
494
+ avatar_url: string | null;
495
+ role: string | null;
496
+ created_at: string;
497
+ updated_at: string;
498
+ };
499
+ Insert: {
500
+ id: string;
501
+ email?: string | null;
502
+ first_name?: string | null;
503
+ last_name?: string | null;
504
+ avatar_url?: string | null;
505
+ role?: string | null;
506
+ created_at?: string;
507
+ updated_at?: string;
508
+ };
509
+ Update: {
510
+ id?: string;
511
+ email?: string | null;
512
+ first_name?: string | null;
513
+ last_name?: string | null;
514
+ avatar_url?: string | null;
515
+ role?: string | null;
516
+ created_at?: string;
517
+ updated_at?: string;
518
+ };
519
+ };
520
+ admin_roles: {
521
+ Row: {
522
+ id: string;
523
+ name: string;
524
+ description: string | null;
525
+ created_at: string;
526
+ };
527
+ Insert: {
528
+ id?: string;
529
+ name: string;
530
+ description?: string | null;
531
+ created_at?: string;
532
+ };
533
+ Update: {
534
+ id?: string;
535
+ name?: string;
536
+ description?: string | null;
537
+ created_at?: string;
538
+ };
539
+ };
540
+ admins: {
541
+ Row: {
542
+ id: string;
543
+ user_id: string;
544
+ role_id: string;
545
+ created_at: string;
546
+ updated_at: string;
547
+ };
548
+ Insert: {
549
+ id?: string;
550
+ user_id: string;
551
+ role_id: string;
552
+ created_at?: string;
553
+ updated_at?: string;
554
+ };
555
+ Update: {
556
+ id?: string;
557
+ user_id?: string;
558
+ role_id?: string;
559
+ created_at?: string;
560
+ updated_at?: string;
561
+ };
562
+ };
563
+ projects: {
564
+ Row: {
565
+ id: string;
566
+ name: string;
567
+ description: string | null;
568
+ status: string;
569
+ created_by: string | null;
570
+ enable_sign_in: boolean;
571
+ enable_sign_up: boolean;
572
+ created_at: string;
573
+ updated_at: string;
574
+ };
575
+ Insert: {
576
+ id?: string;
577
+ name: string;
578
+ description?: string | null;
579
+ status?: string;
580
+ created_by?: string | null;
581
+ enable_sign_in?: boolean;
582
+ enable_sign_up?: boolean;
583
+ created_at?: string;
584
+ updated_at?: string;
585
+ };
586
+ Update: {
587
+ id?: string;
588
+ name?: string;
589
+ description?: string | null;
590
+ status?: string;
591
+ created_by?: string | null;
592
+ enable_sign_in?: boolean;
593
+ enable_sign_up?: boolean;
594
+ created_at?: string;
595
+ updated_at?: string;
596
+ };
597
+ };
598
+ entity_definition: {
599
+ Row: {
600
+ id: string;
601
+ name: string;
602
+ url: string;
603
+ description: string | null;
604
+ table_name: string;
605
+ type: string;
606
+ project_id: string;
607
+ create_permission: string;
608
+ read_permission: string;
609
+ update_permission: string;
610
+ delete_permission: string;
611
+ title_section_0: string | null;
612
+ title_section_1: string | null;
613
+ title_section_2: string | null;
614
+ title_section_3: string | null;
615
+ ui_config: Json | null;
616
+ enable_pagination: boolean;
617
+ page_size: number;
618
+ enable_filters: boolean;
619
+ max_file_size_mb: number | null;
620
+ max_files_count: number | null;
621
+ created_at: string;
622
+ updated_at: string;
623
+ };
624
+ Insert: {
625
+ id?: string;
626
+ name: string;
627
+ url: string;
628
+ description?: string | null;
629
+ table_name: string;
630
+ type: string;
631
+ project_id: string;
632
+ create_permission?: string;
633
+ read_permission?: string;
634
+ update_permission?: string;
635
+ delete_permission?: string;
636
+ title_section_0?: string | null;
637
+ title_section_1?: string | null;
638
+ title_section_2?: string | null;
639
+ title_section_3?: string | null;
640
+ ui_config?: Json | null;
641
+ enable_pagination?: boolean;
642
+ page_size?: number;
643
+ enable_filters?: boolean;
644
+ max_file_size_mb?: number | null;
645
+ max_files_count?: number | null;
646
+ created_at?: string;
647
+ updated_at?: string;
648
+ };
649
+ Update: {
650
+ id?: string;
651
+ name?: string;
652
+ url?: string;
653
+ description?: string | null;
654
+ table_name?: string;
655
+ type?: string;
656
+ project_id?: string;
657
+ create_permission?: string;
658
+ read_permission?: string;
659
+ update_permission?: string;
660
+ delete_permission?: string;
661
+ title_section_0?: string | null;
662
+ title_section_1?: string | null;
663
+ title_section_2?: string | null;
664
+ title_section_3?: string | null;
665
+ ui_config?: Json | null;
666
+ enable_pagination?: boolean;
667
+ page_size?: number;
668
+ enable_filters?: boolean;
669
+ max_file_size_mb?: number | null;
670
+ max_files_count?: number | null;
671
+ created_at?: string;
672
+ updated_at?: string;
673
+ };
674
+ };
675
+ field: {
676
+ Row: {
677
+ id: string;
678
+ entity_definition_id: string;
679
+ name: string;
680
+ db_type: string;
681
+ type: string;
682
+ label: string;
683
+ placeholder: string | null;
684
+ description: string | null;
685
+ for_edit_page: boolean;
686
+ for_create_page: boolean;
687
+ required: boolean;
688
+ required_text: string | null;
689
+ for_edit_page_disabled: boolean;
690
+ display_index: number;
691
+ display_in_table: boolean;
692
+ section_index: number | null;
693
+ is_option_title_field: boolean;
694
+ searchable: boolean;
695
+ filterable_in_list: boolean;
696
+ options: Json | null;
697
+ related_entity_definition_id: string | null;
698
+ relation_field_id: string | null;
699
+ is_relation_source: boolean;
700
+ selector_relation_id: string | null;
701
+ default_string_value: string | null;
702
+ default_number_value: number | null;
703
+ default_boolean_value: boolean | null;
704
+ default_date_value: string | null;
705
+ auto_populate: boolean;
706
+ include_in_single_pma: boolean;
707
+ include_in_list_pma: boolean;
708
+ include_in_single_sa: boolean;
709
+ include_in_list_sa: boolean;
710
+ relation_field_name: string | null;
711
+ relation_field_label: string | null;
712
+ foreign_key: string | null;
713
+ foreign_key_value: string | null;
714
+ type_field_name: string | null;
715
+ options_field_name: string | null;
716
+ accept_file_types: string | null;
717
+ max_file_size: number | null;
718
+ max_files: number | null;
719
+ storage_bucket: string | null;
720
+ created_at: string;
721
+ updated_at: string;
722
+ };
723
+ Insert: {
724
+ id?: string;
725
+ entity_definition_id: string;
726
+ name: string;
727
+ db_type: string;
728
+ type: string;
729
+ label: string;
730
+ placeholder?: string | null;
731
+ description?: string | null;
732
+ for_edit_page?: boolean;
733
+ for_create_page?: boolean;
734
+ required?: boolean;
735
+ required_text?: string | null;
736
+ for_edit_page_disabled?: boolean;
737
+ display_index?: number;
738
+ display_in_table?: boolean;
739
+ section_index?: number | null;
740
+ is_option_title_field?: boolean;
741
+ searchable?: boolean;
742
+ filterable_in_list?: boolean;
743
+ options?: Json | null;
744
+ related_entity_definition_id?: string | null;
745
+ relation_field_id?: string | null;
746
+ is_relation_source?: boolean;
747
+ selector_relation_id?: string | null;
748
+ default_string_value?: string | null;
749
+ default_number_value?: number | null;
750
+ default_boolean_value?: boolean | null;
751
+ default_date_value?: string | null;
752
+ auto_populate?: boolean;
753
+ include_in_single_pma?: boolean;
754
+ include_in_list_pma?: boolean;
755
+ include_in_single_sa?: boolean;
756
+ include_in_list_sa?: boolean;
757
+ relation_field_name?: string | null;
758
+ relation_field_label?: string | null;
759
+ foreign_key?: string | null;
760
+ foreign_key_value?: string | null;
761
+ type_field_name?: string | null;
762
+ options_field_name?: string | null;
763
+ accept_file_types?: string | null;
764
+ max_file_size?: number | null;
765
+ max_files?: number | null;
766
+ storage_bucket?: string | null;
767
+ created_at?: string;
768
+ updated_at?: string;
769
+ };
770
+ Update: {
771
+ id?: string;
772
+ entity_definition_id?: string;
773
+ name?: string;
774
+ db_type?: string;
775
+ type?: string;
776
+ label?: string;
777
+ placeholder?: string | null;
778
+ description?: string | null;
779
+ for_edit_page?: boolean;
780
+ for_create_page?: boolean;
781
+ required?: boolean;
782
+ required_text?: string | null;
783
+ for_edit_page_disabled?: boolean;
784
+ display_index?: number;
785
+ display_in_table?: boolean;
786
+ section_index?: number | null;
787
+ is_option_title_field?: boolean;
788
+ searchable?: boolean;
789
+ filterable_in_list?: boolean;
790
+ options?: Json | null;
791
+ related_entity_definition_id?: string | null;
792
+ relation_field_id?: string | null;
793
+ is_relation_source?: boolean;
794
+ selector_relation_id?: string | null;
795
+ default_string_value?: string | null;
796
+ default_number_value?: number | null;
797
+ default_boolean_value?: boolean | null;
798
+ default_date_value?: string | null;
799
+ auto_populate?: boolean;
800
+ include_in_single_pma?: boolean;
801
+ include_in_list_pma?: boolean;
802
+ include_in_single_sa?: boolean;
803
+ include_in_list_sa?: boolean;
804
+ relation_field_name?: string | null;
805
+ relation_field_label?: string | null;
806
+ foreign_key?: string | null;
807
+ foreign_key_value?: string | null;
808
+ type_field_name?: string | null;
809
+ options_field_name?: string | null;
810
+ accept_file_types?: string | null;
811
+ max_file_size?: number | null;
812
+ max_files?: number | null;
813
+ storage_bucket?: string | null;
814
+ created_at?: string;
815
+ updated_at?: string;
816
+ };
817
+ };
818
+ entity_instance: {
819
+ Row: {
820
+ id: string;
821
+ entity_definition_id: string;
822
+ project_id: string;
823
+ data: Json;
824
+ created_by: string | null;
825
+ created_at: string;
826
+ updated_at: string;
827
+ };
828
+ Insert: {
829
+ id?: string;
830
+ entity_definition_id: string;
831
+ project_id: string;
832
+ data?: Json;
833
+ created_by?: string | null;
834
+ created_at?: string;
835
+ updated_at?: string;
836
+ };
837
+ Update: {
838
+ id?: string;
839
+ entity_definition_id?: string;
840
+ project_id?: string;
841
+ data?: Json;
842
+ created_by?: string | null;
843
+ created_at?: string;
844
+ updated_at?: string;
845
+ };
846
+ };
847
+ entity_file: {
848
+ Row: {
849
+ id: string;
850
+ entity_instance_id: string;
851
+ field_id: string | null;
852
+ file_url: string;
853
+ file_path: string;
854
+ file_name: string;
855
+ file_size: number;
856
+ file_type: string;
857
+ storage_bucket: string;
858
+ uploaded_by: string | null;
859
+ created_at: string;
860
+ updated_at: string;
861
+ };
862
+ Insert: {
863
+ id?: string;
864
+ entity_instance_id: string;
865
+ field_id?: string | null;
866
+ file_url: string;
867
+ file_path: string;
868
+ file_name: string;
869
+ file_size: number;
870
+ file_type: string;
871
+ storage_bucket?: string;
872
+ uploaded_by?: string | null;
873
+ created_at?: string;
874
+ updated_at?: string;
875
+ };
876
+ Update: {
877
+ id?: string;
878
+ entity_instance_id?: string;
879
+ field_id?: string | null;
880
+ file_url?: string;
881
+ file_path?: string;
882
+ file_name?: string;
883
+ file_size?: number;
884
+ file_type?: string;
885
+ storage_bucket?: string;
886
+ uploaded_by?: string | null;
887
+ created_at?: string;
888
+ updated_at?: string;
889
+ };
890
+ };
891
+ entity_relation: {
892
+ Row: {
893
+ id: string;
894
+ source_instance_id: string;
895
+ target_instance_id: string;
896
+ relation_field_id: string;
897
+ reverse_field_id: string | null;
898
+ relation_type: string;
899
+ created_at: string;
900
+ };
901
+ Insert: {
902
+ id?: string;
903
+ source_instance_id: string;
904
+ target_instance_id: string;
905
+ relation_field_id: string;
906
+ reverse_field_id?: string | null;
907
+ relation_type: string;
908
+ created_at?: string;
909
+ };
910
+ Update: {
911
+ id?: string;
912
+ source_instance_id?: string;
913
+ target_instance_id?: string;
914
+ relation_field_id?: string;
915
+ reverse_field_id?: string | null;
916
+ relation_type?: string;
917
+ created_at?: string;
918
+ };
919
+ };
920
+ environments: {
921
+ Row: {
922
+ id: string;
923
+ project_id: string;
924
+ key: string;
925
+ type: "string" | "number" | "boolean" | "select";
926
+ value: Json | null;
927
+ options: Json;
928
+ created_at: string;
929
+ updated_at: string;
930
+ };
931
+ Insert: {
932
+ id?: string;
933
+ project_id: string;
934
+ key: string;
935
+ type: "string" | "number" | "boolean" | "select";
936
+ value?: Json | null;
937
+ options?: Json;
938
+ created_at?: string;
939
+ updated_at?: string;
940
+ };
941
+ Update: {
942
+ id?: string;
943
+ project_id?: string;
944
+ key?: string;
945
+ type?: "string" | "number" | "boolean" | "select";
946
+ value?: Json | null;
947
+ options?: Json;
948
+ created_at?: string;
949
+ updated_at?: string;
950
+ };
951
+ };
952
+ };
953
+ Views: {
954
+ [_ in never]: never;
955
+ };
956
+ Functions: {
957
+ get_user_role: {
958
+ Args: {
959
+ user_uuid: string;
960
+ };
961
+ Returns: string;
962
+ };
963
+ is_super_admin: {
964
+ Args: {
965
+ user_uuid: string;
966
+ };
967
+ Returns: boolean;
968
+ };
969
+ is_admin: {
970
+ Args: {
971
+ user_uuid: string;
972
+ };
973
+ Returns: boolean;
974
+ };
975
+ search_entity_instances: {
976
+ Args: {
977
+ p_entity_definition_id: string;
978
+ p_project_id: string;
979
+ p_search_term: string;
980
+ p_search_fields?: string[];
981
+ p_limit?: number;
982
+ p_offset?: number;
983
+ };
984
+ Returns: Array<{
985
+ id: string;
986
+ entity_definition_id: string;
987
+ project_id: string;
988
+ data: Json;
989
+ created_at: string;
990
+ updated_at: string;
991
+ total_count: number;
992
+ }>;
993
+ };
994
+ get_related_instances: {
995
+ Args: {
996
+ p_source_instance_ids: string[];
997
+ p_relation_field_ids: string[];
998
+ };
999
+ Returns: Array<{
1000
+ source_instance_id: string;
1001
+ relation_field_id: string;
1002
+ target_instance_id: string;
1003
+ target_entity_definition_id: string;
1004
+ target_project_id: string;
1005
+ target_data: Json;
1006
+ target_created_at: string;
1007
+ target_updated_at: string;
1008
+ }>;
1009
+ };
1010
+ };
1011
+ Enums: {
1012
+ [_ in never]: never;
1013
+ };
1014
+ };
1015
+ }
1016
+
1017
+ /**
1018
+ * Базовый класс для публичного API SDK
1019
+ * Содержит общую логику: кэширование, загрузка конфигурации
1020
+ */
1021
+
1022
+ /**
1023
+ * Базовый класс для публичного API клиента
1024
+ */
1025
+ declare abstract class BasePublicAPIClient {
1026
+ protected supabase: SupabaseClient<Database>;
1027
+ protected projectId: string;
1028
+ private enableCache;
1029
+ private cacheTTL;
1030
+ private configCache;
1031
+ constructor(supabase: SupabaseClient<Database>, projectId: string, options?: SDKOptions);
1032
+ /**
1033
+ * Загрузить fields для entityDefinition (с кэшированием)
1034
+ *
1035
+ * Флоу работы с кэшем:
1036
+ *
1037
+ * 1. Если enableCache === true (публичный API):
1038
+ * - Проверяет кэш по entityDefinitionId
1039
+ * - Если есть в кэше и не истек → возвращает из кэша (0 запросов к БД)
1040
+ * - Если нет в кэше или истек → загружает из БД и кэширует (1 запрос к БД)
1041
+ *
1042
+ * 2. Если enableCache === false (админка):
1043
+ * - Пропускает проверку кэша (эквивалент forceRefresh: true)
1044
+ * - Всегда загружает из БД (1 запрос к БД)
1045
+ * - Не сохраняет в кэш (всегда свежие данные)
1046
+ *
1047
+ * Используется внутри SDK для получения fields перед операциями с instances.
1048
+ * Fields нужны для определения типов полей, relations, и уплощения данных.
1049
+ */
1050
+ protected getFields(entityDefinitionId: string): Promise<FieldConfig[]>;
1051
+ /**
1052
+ * Преобразование данных entity_definition из БД в EntityDefinitionConfig
1053
+ */
1054
+ private transformEntityDefinitionFromDB;
1055
+ /**
1056
+ * Преобразование данных field из БД в FieldConfig
1057
+ */
1058
+ private transformFieldFromDB;
1059
+ /**
1060
+ * Загрузить entityDefinition с полями одним запросом (JOIN)
1061
+ * Кэширует всю конфигурацию целиком (entityDefinition + fields)
1062
+ *
1063
+ * Логика кэширования:
1064
+ * - enableCache: true → использует кэш, сохраняет в кэш (TTL: 5 минут по умолчанию)
1065
+ * - enableCache: false → всегда загружает из БД, не использует кэш (эквивалент forceRefresh: true)
1066
+ *
1067
+ * @returns EntityDefinitionConfig с полями, отсортированными по display_index
1068
+ */
1069
+ getEntityDefinitionConfig(entityDefinitionId: string): Promise<EntityDefinitionConfig>;
1070
+ /**
1071
+ * Преобразование EntityDefinitionConfig в EntityDefinition
1072
+ */
1073
+ private convertToEntityDefinition;
1074
+ /**
1075
+ * Преобразование FieldConfig в Field
1076
+ */
1077
+ private convertToField;
1078
+ /**
1079
+ * Получить entity definition с полями и сгенерированным UI конфигом
1080
+ * Использует кэш SDK для оптимизации (если дефиниция уже загружена, не делает повторный запрос)
1081
+ *
1082
+ * @param entityDefinitionId - ID entity definition
1083
+ * @returns EntityDefinition, Fields и UI конфиг, или null если не найдено
1084
+ */
1085
+ getEntityDefinitionWithUIConfig(entityDefinitionId: string): Promise<{
1086
+ entityDefinition: EntityDefinition;
1087
+ fields: Field[];
1088
+ uiConfig: EntityUIConfig;
1089
+ } | null>;
1090
+ /**
1091
+ * Очистить кэш
1092
+ */
1093
+ clearCache(): void;
1094
+ abstract getInstances(entityDefinitionId: string, params?: QueryParams): Promise<{
1095
+ data: EntityInstanceWithFields[];
1096
+ pagination: PaginationResult;
1097
+ }>;
1098
+ abstract getInstance(entityDefinitionId: string, id: string, params?: {
1099
+ relationsAsIds?: boolean;
1100
+ }): Promise<EntityInstanceWithFields>;
1101
+ abstract createInstance(entityDefinitionId: string, data: CreateInstanceData): Promise<EntityInstanceWithFields>;
1102
+ abstract updateInstance(entityDefinitionId: string, id: string, data: UpdateInstanceData): Promise<EntityInstanceWithFields>;
1103
+ abstract deleteInstance(entityDefinitionId: string, id: string): Promise<void>;
1104
+ abstract signIn(email: string, password: string): Promise<AuthResult>;
1105
+ abstract signUp(data: SignUpData): Promise<AuthResult>;
1106
+ abstract signOut(): Promise<void>;
1107
+ abstract getCurrentUser(): Promise<AuthResult["user"] | null>;
1108
+ }
1109
+
1110
+ /**
1111
+ * Унифицированный SDK клиент для работы с экземплярами сущностей
1112
+ * Поддерживает как Server Components (SSR), так и Client Components
1113
+ * Использует динамические импорты для изоляции server/client кода
1114
+ */
1115
+
1116
+ /**
1117
+ * Унифицированный публичный API клиент
1118
+ * Работает как в server, так и в client режиме
1119
+ */
1120
+ declare class PublicAPIClient extends BasePublicAPIClient {
1121
+ private static instances;
1122
+ private mode;
1123
+ private constructor();
1124
+ /**
1125
+ * Создать SDK клиент напрямую с Supabase инстансом
1126
+ * Используется для создания через фабричные функции createServerSDK/createClientSDK
1127
+ *
1128
+ * @param supabase - Supabase клиент
1129
+ * @param projectId - ID проекта
1130
+ * @param mode - Режим работы: 'server' для SSR, 'client' для браузера
1131
+ * @param options - Опции SDK (кэширование и т.д.)
1132
+ */
1133
+ static create(supabase: SupabaseClient<Database>, projectId: string, mode: "server" | "client", options?: SDKOptions): PublicAPIClient;
1134
+ /**
1135
+ * Получить режим работы клиента (для отладки)
1136
+ */
1137
+ getMode(): "server" | "client";
1138
+ /**
1139
+ * Получить один экземпляр
1140
+ */
1141
+ getInstance(entityDefinitionId: string, id: string, params?: {
1142
+ relationsAsIds?: boolean;
1143
+ }): Promise<EntityInstanceWithFields>;
1144
+ /**
1145
+ * Получить список экземпляров
1146
+ * Поддерживает поиск, фильтры (JSONB и relation), пагинацию
1147
+ */
1148
+ getInstances(entityDefinitionId: string, params?: QueryParams): Promise<{
1149
+ data: EntityInstanceWithFields[];
1150
+ pagination: PaginationResult;
1151
+ }>;
1152
+ /**
1153
+ * Создать экземпляр сущности
1154
+ * Поддерживает создание с relations и автоматически устанавливает created_by
1155
+ */
1156
+ createInstance(entityDefinitionId: string, data: CreateInstanceData): Promise<EntityInstanceWithFields>;
1157
+ updateInstance(entityDefinitionId: string, id: string, data: UpdateInstanceData): Promise<EntityInstanceWithFields>;
1158
+ /**
1159
+ * Формирует обновленный экземпляр из уже обновленных данных без повторной загрузки
1160
+ * Оптимизация: избегает лишних запросов после updateInstance
1161
+ * Загружает полные объекты relations для совместимости с форматом списка
1162
+ */
1163
+ private buildUpdatedInstance;
1164
+ /**
1165
+ * Удалить экземпляр сущности
1166
+ * Связи удалятся автоматически через ON DELETE CASCADE
1167
+ */
1168
+ deleteInstance(entityDefinitionId: string, id: string): Promise<void>;
1169
+ signIn(email: string, password: string): Promise<AuthResult>;
1170
+ signUp(data: SignUpData): Promise<AuthResult>;
1171
+ signOut(): Promise<void>;
1172
+ getCurrentUser(): Promise<AuthResult["user"] | null>;
1173
+ }
1174
+
1175
+ export { type AuthResult as A, type PartialUIConfig as B, type ColumnConfig as C, type DbType as D, type EntityDefinition as E, type FieldConfig as F, type GetInstancesOptions as G, type InstanceData as I, type ListPageConfig as L, type MessagesConfig as M, PublicAPIClient as P, type QueryParams as Q, type RelationFilterInfo as R, type SDKOptions as S, type UpdateInstanceData as U, type FieldValue as a, type Field as b, type EntityUIConfig as c, type ProjectConfig as d, type EntityDefinitionConfig as e, type RelationFilterMode as f, type CreateInstanceData as g, type PaginationResult as h, type SignUpData as i, type FieldType as j, type FieldOption as k, type DbTypeToTSType as l, type EntityData as m, type EntityInstance as n, type RelationType as o, type EntityRelation as p, type EntityInstanceWithFields as q, type FilterValue as r, type RelationsData as s, isFieldValue as t, isEntityData as u, getFieldValue as v, type PartialInstanceData as w, type EntityFile as x, type ActionConfig as y, type FormPageConfig as z };