@donotdev/crud 0.1.1 → 0.1.43
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.
- package/LICENSE.md +21 -242
- package/README.md +0 -0
- package/dist/CrudService.bulk.d.ts +57 -0
- package/dist/CrudService.bulk.d.ts.map +1 -0
- package/dist/CrudService.bulk.js +1 -0
- package/dist/CrudService.bulkAcross.d.ts +23 -0
- package/dist/CrudService.bulkAcross.d.ts.map +1 -0
- package/dist/CrudService.bulkAcross.js +1 -0
- package/dist/CrudService.cache.d.ts +45 -0
- package/dist/CrudService.cache.d.ts.map +1 -0
- package/dist/CrudService.cache.js +1 -0
- package/dist/CrudService.d.ts +133 -98
- package/dist/CrudService.d.ts.map +1 -1
- package/dist/CrudService.internal.d.ts +80 -0
- package/dist/CrudService.internal.d.ts.map +1 -0
- package/dist/CrudService.internal.js +9 -0
- package/dist/CrudService.js +1 -9
- package/dist/CrudService.mutations.d.ts +7 -0
- package/dist/CrudService.mutations.d.ts.map +1 -0
- package/dist/CrudService.mutations.js +1 -0
- package/dist/CrudService.optimistic.d.ts +10 -0
- package/dist/CrudService.optimistic.d.ts.map +1 -0
- package/dist/CrudService.optimistic.js +1 -0
- package/dist/CrudService.queries.d.ts +27 -0
- package/dist/CrudService.queries.d.ts.map +1 -0
- package/dist/CrudService.queries.js +1 -0
- package/dist/CrudService.subscriptions.d.ts +17 -0
- package/dist/CrudService.subscriptions.d.ts.map +1 -0
- package/dist/CrudService.subscriptions.js +1 -0
- package/dist/CrudStore.d.ts.map +1 -1
- package/dist/CrudStore.js +1 -1
- package/dist/FieldRegistry.js +1 -1
- package/dist/adapters/FunctionsAdapter.d.ts +54 -17
- package/dist/adapters/FunctionsAdapter.d.ts.map +1 -1
- package/dist/adapters/FunctionsAdapter.js +1 -1
- package/dist/components/CrudButton.js +1 -1
- package/dist/components/CrudCard.d.ts.map +1 -1
- package/dist/components/CrudCard.js +1 -1
- package/dist/components/DateFilter.d.ts +1 -1
- package/dist/components/DateFilter.d.ts.map +1 -1
- package/dist/components/DateFilter.js +1 -1
- package/dist/components/DisplayFieldRenderer.d.ts +1 -1
- package/dist/components/DisplayFieldRenderer.js +1 -1
- package/dist/components/DisplayThumbnail.js +1 -1
- package/dist/components/EntityFilters.d.ts +6 -4
- package/dist/components/EntityFilters.d.ts.map +1 -1
- package/dist/components/EntityFilters.js +1 -1
- package/dist/components/FormFieldRenderer.d.ts.map +1 -1
- package/dist/components/FormFieldRenderer.js +1 -1
- package/dist/components/FormLayout.js +1 -1
- package/dist/components/YearFilter.d.ts +26 -0
- package/dist/components/YearFilter.d.ts.map +1 -0
- package/dist/components/YearFilter.js +1 -0
- package/dist/components/controlled/complex/ControlledAddressField.js +1 -1
- package/dist/components/controlled/complex/ControlledDateField.js +1 -1
- package/dist/components/controlled/complex/ControlledFieldArrayField.js +1 -1
- package/dist/components/controlled/complex/ControlledGeoPointField.js +1 -1
- package/dist/components/controlled/complex/ControlledMapField.js +1 -1
- package/dist/components/controlled/complex/ControlledMultiInputField.js +1 -1
- package/dist/components/controlled/complex/ControlledRichTextField.js +1 -1
- package/dist/components/controlled/complex/ControlledTimestampField.js +1 -1
- package/dist/components/controlled/complex/index.js +1 -1
- package/dist/components/controlled/file/ControlledDocumentField.js +1 -1
- package/dist/components/controlled/file/ControlledFileField.js +1 -1
- package/dist/components/controlled/file/ControlledImageField.js +1 -1
- package/dist/components/controlled/file/ControlledMultiDocumentField.js +1 -1
- package/dist/components/controlled/file/ControlledMultiFileField.js +1 -1
- package/dist/components/controlled/file/ControlledMultiImageField.js +1 -1
- package/dist/components/controlled/file/index.js +1 -1
- package/dist/components/controlled/index.js +1 -1
- package/dist/components/controlled/input/ControlledCheckboxField.js +1 -1
- package/dist/components/controlled/input/ControlledCurrencyField.js +1 -1
- package/dist/components/controlled/input/ControlledDurationField.js +1 -1
- package/dist/components/controlled/input/ControlledGdprConsentField.js +1 -1
- package/dist/components/controlled/input/ControlledNumberField.js +1 -1
- package/dist/components/controlled/input/ControlledPasswordField.js +1 -1
- package/dist/components/controlled/input/ControlledPhoneField.js +1 -1
- package/dist/components/controlled/input/ControlledPriceField.js +1 -1
- package/dist/components/controlled/input/ControlledRangeField.js +1 -1
- package/dist/components/controlled/input/ControlledRatingField.js +1 -1
- package/dist/components/controlled/input/ControlledSwitchField.js +1 -1
- package/dist/components/controlled/input/ControlledTextField.js +1 -1
- package/dist/components/controlled/input/ControlledTextareaField.js +1 -1
- package/dist/components/controlled/input/index.js +1 -1
- package/dist/components/controlled/select/ControlledComboboxField.d.ts.map +1 -1
- package/dist/components/controlled/select/ControlledComboboxField.js +1 -1
- package/dist/components/controlled/select/ControlledDropdownField.d.ts.map +1 -1
- package/dist/components/controlled/select/ControlledDropdownField.js +1 -1
- package/dist/components/controlled/select/ControlledMultiDropdownField.d.ts.map +1 -1
- package/dist/components/controlled/select/ControlledMultiDropdownField.js +1 -1
- package/dist/components/controlled/select/ControlledRadioField.d.ts.map +1 -1
- package/dist/components/controlled/select/ControlledRadioField.js +1 -1
- package/dist/components/controlled/select/ControlledReferenceField.js +1 -1
- package/dist/components/controlled/select/ControlledYearField.js +1 -1
- package/dist/components/controlled/select/index.js +1 -1
- package/dist/components/controlled/types.d.ts +2 -0
- package/dist/components/controlled/types.d.ts.map +1 -1
- package/dist/components/controlled/types.js +1 -1
- package/dist/components/fields/display/AvatarFieldDisplay.js +1 -1
- package/dist/components/fields/display/BadgeFieldDisplay.js +1 -1
- package/dist/components/fields/display/ButtonFieldDisplay.js +1 -1
- package/dist/components/fields/display/CheckboxFieldDisplay.js +1 -1
- package/dist/components/fields/display/DateFieldDisplay.js +1 -1
- package/dist/components/fields/display/DropdownDisplay.js +1 -1
- package/dist/components/fields/display/FileFieldDisplay.js +1 -1
- package/dist/components/fields/display/GeoPointFieldDisplay.js +1 -1
- package/dist/components/fields/display/HiddenFieldDisplay.js +1 -1
- package/dist/components/fields/display/ImageFieldDisplay.js +1 -1
- package/dist/components/fields/display/LinkFieldDisplay.js +1 -1
- package/dist/components/fields/display/MapFieldDisplay.js +1 -1
- package/dist/components/fields/display/MultiDropdownDisplay.js +1 -1
- package/dist/components/fields/display/MultiInputTextFieldDisplay.js +1 -1
- package/dist/components/fields/display/NumberFieldDisplay.js +1 -1
- package/dist/components/fields/display/PasswordFieldDisplay.js +1 -1
- package/dist/components/fields/display/PhoneNumberDisplay.js +1 -1
- package/dist/components/fields/display/RadioFieldDisplay.js +1 -1
- package/dist/components/fields/display/RangeFieldDisplay.js +1 -1
- package/dist/components/fields/display/ReferenceFieldDisplay.js +1 -1
- package/dist/components/fields/display/RichTextDisplay.js +2 -2
- package/dist/components/fields/display/TextAreaDisplay.js +1 -1
- package/dist/components/fields/display/TextFieldDisplay.d.ts.map +1 -1
- package/dist/components/fields/display/TextFieldDisplay.js +1 -1
- package/dist/components/fields/display/TimestampFieldDisplay.js +1 -1
- package/dist/components/fields/display/index.js +1 -1
- package/dist/components/form/fields/AddressFieldComponent.js +1 -1
- package/dist/components/form/fields/AvatarFieldComponent.js +1 -1
- package/dist/components/form/fields/BadgeFieldComponent.js +1 -1
- package/dist/components/form/fields/ButtonFieldComponent.js +1 -1
- package/dist/components/form/fields/CheckboxFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/CheckboxFieldComponent.js +1 -1
- package/dist/components/form/fields/ComboboxComponent.js +1 -1
- package/dist/components/form/fields/CurrencyFieldComponent.js +1 -1
- package/dist/components/form/fields/DateFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/DateFieldComponent.js +1 -1
- package/dist/components/form/fields/DocumentFieldComponent.d.ts +5 -11
- package/dist/components/form/fields/DocumentFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/DocumentFieldComponent.js +1 -1
- package/dist/components/form/fields/DropdownComponent.js +1 -1
- package/dist/components/form/fields/DurationFieldComponent.js +1 -1
- package/dist/components/form/fields/FileFieldComponent.d.ts +5 -11
- package/dist/components/form/fields/FileFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/FileFieldComponent.js +1 -1
- package/dist/components/form/fields/GdprConsentFieldComponent.js +1 -1
- package/dist/components/form/fields/GeoPointFieldComponent.js +1 -1
- package/dist/components/form/fields/HiddenFieldComponent.js +1 -1
- package/dist/components/form/fields/ImageFieldComponent.d.ts +1 -1
- package/dist/components/form/fields/ImageFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/ImageFieldComponent.js +1 -1
- package/dist/components/form/fields/MapFieldComponent.js +1 -1
- package/dist/components/form/fields/MultiDropdownComponent.js +1 -1
- package/dist/components/form/fields/MultiInputTextFieldComponent.js +1 -1
- package/dist/components/form/fields/NumberFieldComponent.js +1 -1
- package/dist/components/form/fields/PasswordFieldComponent.js +1 -1
- package/dist/components/form/fields/PhoneNumberComponent.d.ts.map +1 -1
- package/dist/components/form/fields/PhoneNumberComponent.js +1 -1
- package/dist/components/form/fields/PriceFieldComponent.d.ts +1 -1
- package/dist/components/form/fields/PriceFieldComponent.d.ts.map +1 -1
- package/dist/components/form/fields/PriceFieldComponent.js +1 -1
- package/dist/components/form/fields/RadioFieldComponent.js +1 -1
- package/dist/components/form/fields/RangeFieldComponent.js +1 -1
- package/dist/components/form/fields/RatingFieldComponent.js +1 -1
- package/dist/components/form/fields/ReferenceFieldComponent.js +1 -1
- package/dist/components/form/fields/RichTextComponent.js +1 -1
- package/dist/components/form/fields/SwitchFieldComponent.js +1 -1
- package/dist/components/form/fields/TextAreaComponent.js +1 -1
- package/dist/components/form/fields/TextFieldComponent.js +1 -1
- package/dist/components/form/fields/TimestampFieldComponent.js +1 -1
- package/dist/components/form/fields/index.js +1 -1
- package/dist/components/form/fields/internal/TiptapEditor.js +2 -2
- package/dist/components/form/internal/ImageViewerDialog.js +1 -1
- package/dist/components/index.d.ts +2 -0
- package/dist/components/index.d.ts.map +1 -1
- package/dist/components/index.js +1 -1
- package/dist/contexts/UploadContext.js +1 -1
- package/dist/contexts/index.js +1 -1
- package/dist/fieldTypeRegistry.js +1 -1
- package/dist/fieldTypeRegistry.store.js +1 -1
- package/dist/forms/hooks/index.js +1 -1
- package/dist/forms/hooks/useController.js +1 -1
- package/dist/forms/hooks/useEntityField.d.ts +2 -2
- package/dist/forms/hooks/useEntityField.d.ts.map +1 -1
- package/dist/forms/hooks/useEntityField.js +1 -1
- package/dist/forms/hooks/useEntityForm.d.ts +4 -4
- package/dist/forms/hooks/useEntityForm.d.ts.map +1 -1
- package/dist/forms/hooks/useEntityForm.js +1 -1
- package/dist/forms/index.d.ts +1 -1
- package/dist/forms/index.d.ts.map +1 -1
- package/dist/forms/index.js +1 -1
- package/dist/forms/types.d.ts +26 -14
- package/dist/forms/types.d.ts.map +1 -1
- package/dist/forms/utils/buildInitialValues.d.ts +3 -3
- package/dist/forms/utils/buildInitialValues.d.ts.map +1 -1
- package/dist/forms/utils/buildInitialValues.js +1 -1
- package/dist/forms/utils/getFieldsForOperation.d.ts +3 -3
- package/dist/forms/utils/getFieldsForOperation.d.ts.map +1 -1
- package/dist/forms/utils/getFieldsForOperation.js +1 -1
- package/dist/forms/utils/index.js +1 -1
- package/dist/forms/utils/isFieldEditable.d.ts +6 -6
- package/dist/forms/utils/isFieldEditable.d.ts.map +1 -1
- package/dist/forms/utils/isFieldEditable.js +1 -1
- package/dist/forms/utils/translateFieldLabel.js +1 -1
- package/dist/forms/utils/validateEntity.d.ts +2 -2
- package/dist/forms/utils/validateEntity.d.ts.map +1 -1
- package/dist/forms/utils/validateEntity.js +1 -1
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.d.ts.map +1 -1
- package/dist/hooks/index.js +1 -1
- package/dist/hooks/useCrudFilters.d.ts.map +1 -1
- package/dist/hooks/useCrudFilters.js +1 -1
- package/dist/hooks/useCrudPageSize.d.ts.map +1 -1
- package/dist/hooks/useCrudPageSize.js +1 -1
- package/dist/hooks/useEntityFavorites.js +1 -1
- package/dist/hooks/useFieldConditions.js +1 -1
- package/dist/hooks/useFileUpload.d.ts +18 -33
- package/dist/hooks/useFileUpload.d.ts.map +1 -1
- package/dist/hooks/useFileUpload.js +1 -1
- package/dist/hooks/useReferenceResolver.d.ts +2 -2
- package/dist/hooks/useReferenceResolver.d.ts.map +1 -1
- package/dist/hooks/useReferenceResolver.js +1 -1
- package/dist/hooks/useRelatedItems.d.ts +2 -2
- package/dist/hooks/useRelatedItems.d.ts.map +1 -1
- package/dist/hooks/useRelatedItems.js +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/registerBuiltinFieldTypes.d.ts.map +1 -1
- package/dist/registerBuiltinFieldTypes.js +1 -1
- package/dist/stores/FormStore.d.ts +32 -3
- package/dist/stores/FormStore.d.ts.map +1 -1
- package/dist/stores/FormStore.js +1 -1
- package/dist/stores/UploadStore.d.ts +65 -0
- package/dist/stores/UploadStore.d.ts.map +1 -1
- package/dist/stores/UploadStore.js +1 -1
- package/dist/stores/index.d.ts +1 -1
- package/dist/stores/index.d.ts.map +1 -1
- package/dist/stores/index.js +1 -1
- package/dist/symbol-index.json +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types.d.ts +40 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -1
- package/dist/useBaseCrudList.d.ts +2 -2
- package/dist/useBaseCrudList.d.ts.map +1 -1
- package/dist/useBaseCrudList.js +1 -1
- package/dist/useCrud.d.ts +54 -7
- package/dist/useCrud.d.ts.map +1 -1
- package/dist/useCrud.js +1 -1
- package/dist/useCrudCardList.d.ts +4 -3
- package/dist/useCrudCardList.d.ts.map +1 -1
- package/dist/useCrudCardList.js +1 -1
- package/dist/useCrudList.d.ts +4 -3
- package/dist/useCrudList.d.ts.map +1 -1
- package/dist/useCrudList.js +1 -1
- package/dist/utils/clientListProcessing.d.ts +4 -4
- package/dist/utils/clientListProcessing.d.ts.map +1 -1
- package/dist/utils/clientListProcessing.js +1 -1
- package/dist/utils/collections.d.ts +4 -4
- package/dist/utils/collections.d.ts.map +1 -1
- package/dist/utils/collections.js +1 -1
- package/dist/utils/fileStorage.d.ts +1 -1
- package/dist/utils/fileStorage.d.ts.map +1 -1
- package/dist/utils/fileStorage.js +1 -1
- package/dist/utils/imageProcessing.d.ts.map +1 -1
- package/dist/utils/imageProcessing.js +1 -1
- package/dist/utils/imageStorage.d.ts +1 -1
- package/dist/utils/imageStorage.d.ts.map +1 -1
- package/dist/utils/imageStorage.js +1 -1
- package/dist/utils/imageUtils.js +1 -1
- package/dist/utils/matchesFilter.js +1 -1
- package/dist/utils/mergeWithOptimistic.js +1 -1
- package/dist/utils/sanitizeHtml.d.ts.map +1 -1
- package/dist/utils/sanitizeHtml.js +1 -1
- package/dist/utils/scopeUtils.js +1 -1
- package/dist/utils/uploadValidation.js +1 -1
- package/dist/workflows/WorkflowPersistence.js +1 -1
- package/dist/workflows/defineWorkflow.d.ts +2 -2
- package/dist/workflows/defineWorkflow.d.ts.map +1 -1
- package/dist/workflows/index.js +1 -1
- package/dist/workflows/useEntityWorkflow.js +1 -1
- package/guidelines/COMPONENTS.md +0 -0
- package/guidelines/CRUD.md +64 -1
- package/guidelines/GOTCHAS.md +0 -0
- package/package.json +7 -6
- package/dist/hooks/useUnsavedChangesWarning.d.ts +0 -29
- package/dist/hooks/useUnsavedChangesWarning.d.ts.map +0 -1
- package/dist/hooks/useUnsavedChangesWarning.js +0 -1
package/dist/CrudService.d.ts
CHANGED
|
@@ -1,31 +1,94 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview CrudService - Complete CRUD Orchestrator with Caching
|
|
3
|
+
* @description Complete CRUD orchestrator with TanStack Query as single source of truth.
|
|
4
|
+
* Validation is handled by Valibot schemas in adapters.
|
|
5
|
+
*
|
|
6
|
+
* **Architecture (4 layers):**
|
|
7
|
+
* - useCrud (thin React wrapper, pass-through)
|
|
8
|
+
* - CrudService (orchestration + caching) ← THIS FILE
|
|
9
|
+
* - Backend Adapter (FirestoreAdapter | FunctionsAdapter | SupabaseCrudAdapter | custom ICrudAdapter)
|
|
10
|
+
* - Backend SDK (Firestore | Firebase Functions | Supabase PostgREST | ...)
|
|
11
|
+
*
|
|
12
|
+
* Adapters are registered via `configureProviders({ crud: adapter })` at app startup.
|
|
13
|
+
* Firebase adapters (firestore / functions) are also lazy-loaded by name for backwards compat.
|
|
14
|
+
*
|
|
15
|
+
* **File layout (refactored from a 1949-LOC monolith):**
|
|
16
|
+
* - `CrudService.ts` ← thin facade: DI + delegators (this file)
|
|
17
|
+
* - `CrudService.internal.ts` ← toast/audit/resilience/init helpers
|
|
18
|
+
* - `CrudService.cache.ts` ← TanStack cache read/update helpers
|
|
19
|
+
* - `CrudService.queries.ts` ← get / query / *QueryOptions impls
|
|
20
|
+
* - `CrudService.mutations.ts` ← set / update / delete / add impls
|
|
21
|
+
* - `CrudService.optimistic.ts` ← *Optimistic impls
|
|
22
|
+
* - `CrudService.subscriptions.ts` ← subscribe / subscribeToCollection impls
|
|
23
|
+
*
|
|
24
|
+
* **Responsibilities:**
|
|
25
|
+
* - All CRUD operations (via adapter)
|
|
26
|
+
* - TanStack Query caching (single source of truth for data)
|
|
27
|
+
* - Error wrapping with `handleError()`
|
|
28
|
+
* - Optimistic metadata updates (CrudStore tracks pending ops only)
|
|
29
|
+
* - Loading state management
|
|
30
|
+
* - Toast notifications
|
|
31
|
+
*
|
|
32
|
+
* **Caching strategy (aggressive / optimal):**
|
|
33
|
+
* - One cache key per (collection, queryOptions): `['crud', collection, 'query', JSON.stringify(queryOptions)]`.
|
|
34
|
+
* list and listCard share that same key — one network read, both views get data.
|
|
35
|
+
* - Create/Update/Delete update both the GET cache `['crud', collection, 'get', id]` and all
|
|
36
|
+
* list caches via `updateListCaches` so the UI stays in sync without any refetch.
|
|
37
|
+
* - `subscribeToCollection` writes to the same list cache key; real-time updates and mutations
|
|
38
|
+
* share one source of truth. The updater preserves `total`/`hasMore`/`lastVisible` and
|
|
39
|
+
* only replaces `items`.
|
|
40
|
+
*
|
|
41
|
+
* **Optimistic Flow:**
|
|
42
|
+
* 1. Store optimisticData + originalData in CrudStore
|
|
43
|
+
* 2. mergeWithOptimistic shows optimisticData instantly
|
|
44
|
+
* 3. On success: update TanStack cache, then remove optimistic flag
|
|
45
|
+
* 4. On error: restore originalData to cache, then remove optimistic flag
|
|
46
|
+
*
|
|
47
|
+
* **Key:** Cache updated BEFORE flag removed = no race condition
|
|
48
|
+
*
|
|
49
|
+
* @version 0.1.0
|
|
50
|
+
* @since 0.0.1
|
|
51
|
+
* @author AMBROISE PARK Consulting
|
|
52
|
+
*/
|
|
53
|
+
import type { BulkAcrossBatch, BulkAcrossResult, BulkOperations, BulkResult, CrudCreateInput, CrudDocQuery, CrudListQuery, dndevSchema, QueryClient, ICrudAdapter, QueryOptions, PaginatedQueryResult, ListSchemaType, SecurityContext } from '@donotdev/core';
|
|
54
|
+
import type { BulkSchemas } from './CrudService.bulk';
|
|
55
|
+
import type { CacheOptions, CrudServiceInternal, CrudStoreApi, MutationOptions } from './types';
|
|
3
56
|
export type { CacheOptions };
|
|
4
57
|
/**
|
|
5
|
-
* Complete CRUD orchestrator with TanStack Query caching
|
|
58
|
+
* Complete CRUD orchestrator with TanStack Query caching.
|
|
59
|
+
*
|
|
60
|
+
* **Field visibility:** fields below are marked `@internal` rather than TS
|
|
61
|
+
* `private` because impl functions in sibling files (`CrudService.*.ts`) must
|
|
62
|
+
* access them via `self.field`. TypeScript's `private` modifier blocks that
|
|
63
|
+
* cross-file access even within the same package. Consumers must not touch
|
|
64
|
+
* these fields directly — they're part of the class's internal surface only.
|
|
6
65
|
*
|
|
7
66
|
* @version 0.1.0
|
|
8
67
|
* @since 0.0.1
|
|
9
68
|
* @author AMBROISE PARK Consulting
|
|
10
69
|
*/
|
|
11
|
-
declare class CrudService implements
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
|
|
70
|
+
export declare class CrudService implements CrudServiceInternal {
|
|
71
|
+
/** @internal */
|
|
72
|
+
adapter: ICrudAdapter | null;
|
|
73
|
+
/** @internal */
|
|
74
|
+
store: CrudStoreApi | null;
|
|
75
|
+
/**
|
|
76
|
+
* Optional security context (SOC2 audit logging, rate limiting, PII encryption)
|
|
77
|
+
* @internal
|
|
78
|
+
*/
|
|
79
|
+
security: SecurityContext | null;
|
|
16
80
|
/**
|
|
17
81
|
* Current authenticated user ID — used as rate limit key prefix and audit actor.
|
|
18
82
|
* Call `setCurrentUser(userId)` after auth state changes so CRUD operations are
|
|
19
83
|
* scoped per-user rather than per-collection.
|
|
84
|
+
* @internal
|
|
20
85
|
*/
|
|
21
|
-
|
|
86
|
+
currentUserId: string | null;
|
|
22
87
|
/**
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* - options.showSuccessToast=false → never show
|
|
26
|
-
* - options.showSuccessToast=undefined → use global !hideSuccessToasts
|
|
88
|
+
* Tracks in-flight mutations to prevent concurrent writes to the same document.
|
|
89
|
+
* @internal
|
|
27
90
|
*/
|
|
28
|
-
|
|
91
|
+
_inflightMutations: Map<string, Promise<unknown>>;
|
|
29
92
|
setStore(store: CrudStoreApi): void;
|
|
30
93
|
/**
|
|
31
94
|
* Inject a security context for SOC2-compliant audit logging, rate limiting, and PII encryption.
|
|
@@ -50,43 +113,6 @@ declare class CrudService implements CrudServiceInterface {
|
|
|
50
113
|
* @since 0.0.1
|
|
51
114
|
*/
|
|
52
115
|
setCurrentUser(userId: string | null): void;
|
|
53
|
-
/**
|
|
54
|
-
* Resolve PII fields for a collection from the schema metadata (if available).
|
|
55
|
-
* Returns empty array when no security config or piiFields defined.
|
|
56
|
-
*/
|
|
57
|
-
private _getPiiFields;
|
|
58
|
-
/**
|
|
59
|
-
* Emit a CRUD audit event when security context is present.
|
|
60
|
-
* Skips silently if auditLog is explicitly false on the schema.
|
|
61
|
-
*/
|
|
62
|
-
private _auditCrud;
|
|
63
|
-
/**
|
|
64
|
-
* Build the rate limit key for a write/read operation.
|
|
65
|
-
* Uses `<userId>:<collection>` when a current user is set, ensuring per-user
|
|
66
|
-
* isolation.
|
|
67
|
-
*
|
|
68
|
-
* **Warning:** Falls back to `<collection>` when no user is set, which means all
|
|
69
|
-
* unauthenticated callers share one rate-limit bucket per collection. A single
|
|
70
|
-
* anonymous client can exhaust the limit for all others. Call `setCurrentUser()`
|
|
71
|
-
* after auth state changes to enable per-user isolation.
|
|
72
|
-
*/
|
|
73
|
-
private _rateLimitKey;
|
|
74
|
-
/** Tracks in-flight mutations to prevent concurrent writes to the same document */
|
|
75
|
-
private _inflightMutations;
|
|
76
|
-
private _mutationKey;
|
|
77
|
-
/**
|
|
78
|
-
* Execute an adapter call with timeout and 1 retry on transient errors.
|
|
79
|
-
* Transient errors: network errors, timeouts, 5xx status codes.
|
|
80
|
-
*/
|
|
81
|
-
private _withResilience;
|
|
82
|
-
private _isTransientError;
|
|
83
|
-
/** Ensure adapter is initialized from provider registry. */
|
|
84
|
-
private _ensureAdapter;
|
|
85
|
-
/**
|
|
86
|
-
* Throws if the active adapter is direct (not server-side) and the entity schema
|
|
87
|
-
* has any field with restricted visibility. Call before any adapter read or write.
|
|
88
|
-
*/
|
|
89
|
-
private _assertCanAccess;
|
|
90
116
|
/**
|
|
91
117
|
* Initialize the CRUD adapter from the provider registry.
|
|
92
118
|
* Apps must call `configureProviders({ crud: adapter })` at startup before any CRUD.
|
|
@@ -104,69 +130,78 @@ declare class CrudService implements CrudServiceInterface {
|
|
|
104
130
|
* Returns reactive loading states via TanStack Query.
|
|
105
131
|
* @param schema - Accepts dndevSchema<unknown> since OperationSchemas uses unknown. T is for return type.
|
|
106
132
|
*/
|
|
107
|
-
getListQueryOptions<T>(collection: string, queryOptions: QueryOptions, schema: dndevSchema<unknown>, cacheOptions?: CacheOptions, schemaType?: ListSchemaType):
|
|
108
|
-
queryKey: readonly ["crud", string, "query", string];
|
|
109
|
-
queryFn: () => Promise<PaginatedQueryResult<T>>;
|
|
110
|
-
staleTime: number;
|
|
111
|
-
};
|
|
133
|
+
getListQueryOptions<T>(collection: string, queryOptions: QueryOptions, schema: dndevSchema<unknown>, cacheOptions?: CacheOptions, schemaType?: ListSchemaType): CrudListQuery<T>;
|
|
112
134
|
/**
|
|
113
135
|
* Get query options for single document queries. Use with useQuery() in hooks.
|
|
114
136
|
* Returns reactive loading states via TanStack Query.
|
|
115
137
|
* @param schema - Accepts dndevSchema<unknown> since OperationSchemas uses unknown. T is for return type.
|
|
116
138
|
*/
|
|
117
|
-
getDocQueryOptions<T>(collection: string, id: string, schema: dndevSchema<unknown>, cacheOptions?: CacheOptions):
|
|
118
|
-
queryKey: readonly ["crud", string, "get", string];
|
|
119
|
-
queryFn: () => Promise<T | null>;
|
|
120
|
-
staleTime: number;
|
|
121
|
-
};
|
|
122
|
-
/**
|
|
123
|
-
* Update single document GET cache after mutation.
|
|
124
|
-
* Key format: ['crud', collection, 'get', id]
|
|
125
|
-
*/
|
|
126
|
-
private _updateGetCache;
|
|
127
|
-
/**
|
|
128
|
-
* Update all caches after mutation (list queries + single document GET cache).
|
|
129
|
-
* Automatically syncs both list and document caches for consistency.
|
|
130
|
-
*/
|
|
131
|
-
private _updateListCaches;
|
|
132
|
-
/**
|
|
133
|
-
* Check uniqueness constraints against cached data (list/listCard queries).
|
|
134
|
-
* For findOrCreate: returns existing item's ID without server call.
|
|
135
|
-
* For strict uniqueness: throws error to block the operation.
|
|
136
|
-
* Returns null if no match found or no cache available.
|
|
137
|
-
*/
|
|
138
|
-
private _checkUniquenessFromCache;
|
|
139
|
-
/**
|
|
140
|
-
* Get an item from any list cache for this collection.
|
|
141
|
-
* Used to get previous data for optimistic operations when individual GET cache is empty.
|
|
142
|
-
*/
|
|
143
|
-
private _getItemFromListCache;
|
|
139
|
+
getDocQueryOptions<T>(collection: string, id: string, schema: dndevSchema<unknown>, cacheOptions?: CacheOptions): CrudDocQuery<T>;
|
|
144
140
|
/**
|
|
145
141
|
* Invalidate all cached queries for a collection
|
|
146
142
|
*/
|
|
147
143
|
invalidateCollection(collection: string): Promise<void>;
|
|
148
144
|
get<T>(collection: string, id: string, schema: dndevSchema<T>, options?: CacheOptions): Promise<T | null>;
|
|
149
|
-
/** Internal: fetch from adapter with store updates */
|
|
150
|
-
private _getFromAdapter;
|
|
151
145
|
query<T>(collection: string, options: QueryOptions, schema: dndevSchema<T>, cacheOptions?: CacheOptions, schemaType?: ListSchemaType): Promise<PaginatedQueryResult<T>>;
|
|
152
|
-
/** Internal: query from adapter with store updates */
|
|
153
|
-
private _queryFromAdapter;
|
|
154
|
-
/**
|
|
155
|
-
* Helper to get translated entity name from collection
|
|
156
|
-
* Tries entity-{collection}:name and entity-{singular}:name patterns
|
|
157
|
-
* Falls back to collection name if translation not found
|
|
158
|
-
*/
|
|
159
|
-
private _getEntityName;
|
|
160
146
|
set<T>(collection: string, id: string, data: T, schema: dndevSchema<T>, options?: MutationOptions): Promise<void>;
|
|
161
147
|
update<T>(collection: string, id: string, data: Partial<T>, schema?: dndevSchema<T>, options?: MutationOptions): Promise<void>;
|
|
162
148
|
delete(collection: string, id: string, options?: MutationOptions): Promise<void>;
|
|
163
|
-
add<T
|
|
149
|
+
add<T extends Record<string, unknown>>(collection: string, data: CrudCreateInput<T>, schema: dndevSchema<T>, options?: MutationOptions): Promise<string>;
|
|
150
|
+
/**
|
|
151
|
+
* Execute a transactional bulk CRUD operation.
|
|
152
|
+
*
|
|
153
|
+
* All three buckets commit atomically in one adapter round-trip. Emits one
|
|
154
|
+
* audit entry, one rate-limit hit, one toast. Collisions (same id in two
|
|
155
|
+
* mutually-exclusive buckets) reject up-front with `BulkCollisionError`
|
|
156
|
+
* before any optimistic mutation. Empty payloads short-circuit without
|
|
157
|
+
* hitting the adapter.
|
|
158
|
+
*
|
|
159
|
+
* @param schemas - `create` schema validates inserts; `update` resolves PII
|
|
160
|
+
* fields on patches. Either may be omitted when the matching bucket is empty.
|
|
161
|
+
*
|
|
162
|
+
* @example
|
|
163
|
+
* ```typescript
|
|
164
|
+
* const result = await crud.bulk<Event>('events', {
|
|
165
|
+
* inserts: [{ title: 'A' }, { title: 'B' }],
|
|
166
|
+
* updates: [{ id: 'e1', patch: { title: 'renamed' } }],
|
|
167
|
+
* deletes: ['e2', 'e3'],
|
|
168
|
+
* }, { create: createSchema, update: updateSchema });
|
|
169
|
+
* ```
|
|
170
|
+
*/
|
|
171
|
+
bulk<T extends Record<string, unknown>>(collection: string, ops: BulkOperations<T>, schemas: BulkSchemas<T>, options?: MutationOptions): Promise<BulkResult>;
|
|
172
|
+
/**
|
|
173
|
+
* Cross-collection atomic bulk write.
|
|
174
|
+
*
|
|
175
|
+
* One optimistic pass across all collections, adapter writes in topological
|
|
176
|
+
* order (parallel within each wave), one toast, coordinated rollback.
|
|
177
|
+
* Batches with `dependsOn` run after their dependencies complete.
|
|
178
|
+
*
|
|
179
|
+
* @throws {BulkCollisionError} Same id in two mutually-exclusive buckets
|
|
180
|
+
* within one batch — thrown before any side effect.
|
|
181
|
+
* @throws {BulkAcrossCycleError} `dependsOn` contains a cycle — thrown
|
|
182
|
+
* before any side effect.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```typescript
|
|
186
|
+
* const customerId = generateUUID();
|
|
187
|
+
* await crud.bulkAcross([
|
|
188
|
+
* {
|
|
189
|
+
* collection: 'customers',
|
|
190
|
+
* inserts: [{ id: customerId, ...customerData }],
|
|
191
|
+
* schemas: { create: customerCreateSchema },
|
|
192
|
+
* },
|
|
193
|
+
* {
|
|
194
|
+
* collection: 'inquiries',
|
|
195
|
+
* inserts: [{ customerId, ...inquiryData }],
|
|
196
|
+
* schemas: { create: inquiryCreateSchema },
|
|
197
|
+
* dependsOn: ['customers'],
|
|
198
|
+
* },
|
|
199
|
+
* ]);
|
|
200
|
+
* ```
|
|
201
|
+
*/
|
|
202
|
+
bulkAcross(batches: BulkAcrossBatch[], options?: MutationOptions): Promise<BulkAcrossResult>;
|
|
164
203
|
subscribe<T>(collection: string, id: string, callback: (data: T | null, error?: Error) => void, schema: dndevSchema<T>): () => void;
|
|
165
|
-
/** Synchronous subscribe — only called once adapter is confirmed ready. */
|
|
166
|
-
private _subscribeSync;
|
|
167
204
|
subscribeToCollection<T>(collection: string, options: QueryOptions, callback: (data: T[], error?: Error) => void, schema: dndevSchema<T>): () => void;
|
|
168
|
-
/** Synchronous subscribeToCollection — only called once adapter is confirmed ready. */
|
|
169
|
-
private _subscribeToCollectionSync;
|
|
170
205
|
addOptimistic<T extends {
|
|
171
206
|
id?: string;
|
|
172
207
|
}>(collection: string, data: T, schema: dndevSchema<T>, options?: MutationOptions): Promise<T & {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CrudService.d.ts","sourceRoot":"","sources":["../src/CrudService.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"CrudService.d.ts","sourceRoot":"","sources":["../src/CrudService.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH,OAAO,KAAK,EACV,eAAe,EACf,gBAAgB,EAChB,cAAc,EACd,UAAU,EACV,eAAe,EACf,YAAY,EACZ,aAAa,EACb,WAAW,EACX,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,oBAAoB,EACpB,cAAc,EACd,eAAe,EAChB,MAAM,gBAAgB,CAAC;AAIxB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AA0BtD,OAAO,KAAK,EACV,YAAY,EACZ,mBAAmB,EACnB,YAAY,EACZ,eAAe,EAChB,MAAM,SAAS,CAAC;AAGjB,YAAY,EAAE,YAAY,EAAE,CAAC;AAE7B;;;;;;;;;;;;GAYG;AACH,qBAAa,WAAY,YAAW,mBAAmB;IACrD,gBAAgB;IAChB,OAAO,EAAE,YAAY,GAAG,IAAI,CAAQ;IACpC,gBAAgB;IAChB,KAAK,EAAE,YAAY,GAAG,IAAI,CAAQ;IAClC;;;OAGG;IACH,QAAQ,EAAE,eAAe,GAAG,IAAI,CAAQ;IACxC;;;;;OAKG;IACH,aAAa,EAAE,MAAM,GAAG,IAAI,CAAQ;IAEpC;;;OAGG;IACH,kBAAkB,gCAAuC;IAMzD,QAAQ,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI;IAInC;;;;;;;;;OASG;IACH,WAAW,CAAC,QAAQ,EAAE,eAAe,GAAG,IAAI;IAI5C;;;;;;;;;;OAUG;IACH,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;IAI3C;;;;;OAKG;IACH,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAQ3B;;;OAGG;IACH,cAAc,IAAI,WAAW;IAI7B;;;;OAIG;IACH,mBAAmB,CAAC,CAAC,EACnB,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,YAAY,EAC1B,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,EAC5B,YAAY,CAAC,EAAE,YAAY,EAC3B,UAAU,CAAC,EAAE,cAAc,GAC1B,aAAa,CAAC,CAAC,CAAC;IAWnB;;;;OAIG;IACH,kBAAkB,CAAC,CAAC,EAClB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,EAC5B,YAAY,CAAC,EAAE,YAAY,GAC1B,YAAY,CAAC,CAAC,CAAC;IAUlB;;OAEG;IACH,oBAAoB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQvD,GAAG,CAAC,CAAC,EACH,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,OAAO,CAAC,EAAE,YAAY,GACrB,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;IAIpB,KAAK,CAAC,CAAC,EACL,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,YAAY,CAAC,EAAE,YAAY,EAC3B,UAAU,CAAC,EAAE,cAAc,GAC1B,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;IAenC,GAAG,CAAC,CAAC,EACH,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,CAAC,EACP,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,IAAI,CAAC;IAIhB,MAAM,CAAC,CAAC,EACN,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,MAAM,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,EACvB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,IAAI,CAAC;IAIhB,MAAM,CACJ,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,IAAI,CAAC;IAIhB,GAAG,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACnC,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,eAAe,CAAC,CAAC,CAAC,EACxB,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,MAAM,CAAC;IAIlB;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,IAAI,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACpC,UAAU,EAAE,MAAM,EAClB,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC,EACtB,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC,EACvB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,UAAU,CAAC;IAItB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6BG;IACH,UAAU,CACR,OAAO,EAAE,eAAe,EAAE,EAC1B,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,gBAAgB,CAAC;IAY5B,SAAS,CAAC,CAAC,EACT,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,EACjD,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,GACrB,MAAM,IAAI;IAIb,qBAAqB,CAAC,CAAC,EACrB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,YAAY,EACrB,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,EAC5C,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,GACrB,MAAM,IAAI;IAcb,aAAa,CAAC,CAAC,SAAS;QAAE,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE,EACrC,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,CAAC,EACP,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,CAAC,GAAG;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;IAI9B,gBAAgB,CAAC,CAAC,EAChB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,CAAC,CAAC;IAIb,gBAAgB,CACd,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,IAAI,CAAC;CAGjB;AAED;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,mBAE1B,CAAC"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview CrudService internal helpers
|
|
3
|
+
* @description Toast/audit/rate-limit/resilience helpers used by the CrudService
|
|
4
|
+
* facade and its impl siblings (mutations, queries, subscriptions, optimistic).
|
|
5
|
+
*
|
|
6
|
+
* **Why this split exists:**
|
|
7
|
+
* The monolithic CrudService.ts exceeded the 500-LOC cap. These helpers are
|
|
8
|
+
* pure, stateless where possible, and take the service instance explicitly so
|
|
9
|
+
* they can live in a sibling file without mixins/proxies. Shared mutable state
|
|
10
|
+
* (`_inflightMutations`, adapter, store, security context) stays on the class.
|
|
11
|
+
*
|
|
12
|
+
* @version 0.1.0
|
|
13
|
+
* @since 0.0.1
|
|
14
|
+
* @author AMBROISE PARK Consulting
|
|
15
|
+
*/
|
|
16
|
+
import type { dndevSchema } from '@donotdev/core';
|
|
17
|
+
import type { CrudServiceInternal, MutationOptions } from './types';
|
|
18
|
+
/**
|
|
19
|
+
* Determine if success toast should be shown based on per-call options and global setting
|
|
20
|
+
* - options.showSuccessToast=true → always show
|
|
21
|
+
* - options.showSuccessToast=false → never show
|
|
22
|
+
* - options.showSuccessToast=undefined → use global !hideSuccessToasts
|
|
23
|
+
*/
|
|
24
|
+
export declare function shouldShowSuccessToast(self: CrudServiceInternal, options?: MutationOptions): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Resolve PII fields for a collection from the schema metadata (if available).
|
|
27
|
+
* Returns empty array when no security config or piiFields defined.
|
|
28
|
+
*/
|
|
29
|
+
export declare function getPiiFields(schema?: dndevSchema<unknown>): string[];
|
|
30
|
+
/**
|
|
31
|
+
* Emit a CRUD audit event when security context is present.
|
|
32
|
+
* Skips silently if auditLog is explicitly false on the schema.
|
|
33
|
+
*/
|
|
34
|
+
export declare function auditCrud(self: CrudServiceInternal, type: 'crud.create' | 'crud.read' | 'crud.update' | 'crud.delete', collection: string, docId?: string, userId?: string): void;
|
|
35
|
+
/**
|
|
36
|
+
* Build the rate limit key for a write/read operation.
|
|
37
|
+
* Uses `<userId>:<collection>` when a current user is set, ensuring per-user
|
|
38
|
+
* isolation.
|
|
39
|
+
*
|
|
40
|
+
* **Warning:** Falls back to `<collection>` when no user is set, which means all
|
|
41
|
+
* unauthenticated callers share one rate-limit bucket per collection. A single
|
|
42
|
+
* anonymous client can exhaust the limit for all others. Call `setCurrentUser()`
|
|
43
|
+
* after auth state changes to enable per-user isolation.
|
|
44
|
+
*/
|
|
45
|
+
export declare function rateLimitKey(self: CrudServiceInternal, collection: string): string;
|
|
46
|
+
/** Compose the in-flight mutation key for a given (collection, id). */
|
|
47
|
+
export declare function mutationKey(collection: string, id: string): string;
|
|
48
|
+
/**
|
|
49
|
+
* Execute an adapter call with timeout and 1 retry on transient errors.
|
|
50
|
+
* Transient errors: network errors, timeouts, 5xx status codes.
|
|
51
|
+
*/
|
|
52
|
+
export declare function withResilience<T>(operation: () => Promise<T>, timeoutMs?: number): Promise<T>;
|
|
53
|
+
export declare function isTransientError(error: unknown): boolean;
|
|
54
|
+
/** Ensure adapter is initialized from provider registry. */
|
|
55
|
+
export declare function ensureAdapter(self: CrudServiceInternal): Promise<void>;
|
|
56
|
+
/**
|
|
57
|
+
* Throws if the active adapter is direct (not server-side) and the entity schema
|
|
58
|
+
* has any field with restricted visibility. Call before any adapter read or write.
|
|
59
|
+
*/
|
|
60
|
+
export declare function assertCanAccess(self: CrudServiceInternal, collection: string, schema?: dndevSchema<unknown>): void;
|
|
61
|
+
/**
|
|
62
|
+
* Initialize the CRUD adapter from the provider registry.
|
|
63
|
+
* Apps must call `configureProviders({ crud: adapter })` at startup before any CRUD.
|
|
64
|
+
*
|
|
65
|
+
* @throws If no CRUD provider is configured
|
|
66
|
+
*/
|
|
67
|
+
export declare function initializeImpl(self: CrudServiceInternal): Promise<void>;
|
|
68
|
+
/**
|
|
69
|
+
* Helper to get translated entity name from collection
|
|
70
|
+
* Tries entity-{collection}:name and entity-{singular}:name patterns
|
|
71
|
+
* Falls back to collection name if translation not found
|
|
72
|
+
*/
|
|
73
|
+
export declare function getEntityName(collection: string): string;
|
|
74
|
+
/**
|
|
75
|
+
* Run a mutation with concurrent-mutation serialization per (collection, id).
|
|
76
|
+
* Ensures sequential writes to the same document while allowing concurrent
|
|
77
|
+
* writes across different documents.
|
|
78
|
+
*/
|
|
79
|
+
export declare function runSerializedMutation<T>(self: CrudServiceInternal, collection: string, id: string, run: () => Promise<T>): Promise<T>;
|
|
80
|
+
//# sourceMappingURL=CrudService.internal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CrudService.internal.d.ts","sourceRoot":"","sources":["../src/CrudService.internal.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAUlD,OAAO,KAAK,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAEpE;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,mBAAmB,EACzB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAKT;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,MAAM,EAAE,CAIpE;AAED;;;GAGG;AACH,wBAAgB,SAAS,CACvB,IAAI,EAAE,mBAAmB,EACzB,IAAI,EAAE,aAAa,GAAG,WAAW,GAAG,aAAa,GAAG,aAAa,EACjE,UAAU,EAAE,MAAM,EAClB,KAAK,CAAC,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,MAAM,GACd,IAAI,CAQN;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAIlF;AAED,uEAAuE;AACvE,wBAAgB,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAElE;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAAC,CAAC,EACpC,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAC3B,SAAS,GAAE,MAA6B,GACvC,OAAO,CAAC,CAAC,CAAC,CAWZ;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAgBxD;AAED,4DAA4D;AAC5D,wBAAsB,aAAa,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAG5E;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,MAAM,CAAC,EAAE,WAAW,CAAC,OAAO,CAAC,GAC5B,IAAI,CAiBN;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAsB7E;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAmCxD;AAED;;;;GAIG;AACH,wBAAsB,qBAAqB,CAAC,CAAC,EAC3C,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,GAAG,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GACpB,OAAO,CAAC,CAAC,CAAC,CAeZ"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{getI18nInstance as c,hasProvider as l,getProvider as f,hasRestrictedVisibility as p,withTimeout as o,DEFAULT_CRUD_TIMEOUT as m}from"@donotdev/core";function y(e,t){return t?.showSuccessToast===!0?!0:t?.showSuccessToast===!1?!1:!e.store?.getState().hideSuccessToasts}function h(e){return e?.security?.piiFields??[]}function w(e,t,r,a,i){e.security&&e.security.audit({type:t,collection:r,docId:a,userId:i??e.currentUserId??void 0})}function g(e,t){return e.currentUserId?`${e.currentUserId}:${t}`:t}function u(e,t){return`${e}:${t}`}async function v(e,t=m){try{return await o(e(),t)}catch(r){if(d(r))return await new Promise(a=>setTimeout(a,2e3)),await o(e(),t);throw r}}function d(e){if(e instanceof Error){if(e.name==="TimeoutError"||e.message.includes("Failed to fetch")||e.message.includes("NetworkError")||e.message.includes("network"))return!0;const t=e.message.match(/(?:status|code)\s*:?\s*(\d{3})/i);if(t?.[1]&&parseInt(t[1])>=500)return!0}return!1}async function S(e){e.adapter||await e.initialize()}function b(e,t,r){if(e.adapter&&r&&p(r)&&!e.adapter.serverSideOnly&&!e.adapter.dbLevelSecurity)throw new Error(`[dndev] Direct adapter cannot access "${t}": entity has restricted field visibility. Use a server-side adapter (FunctionsAdapter for Firebase, or SupabaseCrudAdapter with RLS enabled) to enforce field-level security (serverSideOnly = true | dbLevelSecurity = true).`)}async function A(e){if(!e.adapter){if(!l("crud"))throw new Error(`[dndev] No CRUD adapter configured. Call configureProviders({ crud: yourAdapter }) at app startup.
|
|
2
|
+
Examples:
|
|
3
|
+
import { FirestoreAdapter } from "@donotdev/firebase";
|
|
4
|
+
import { FunctionsAdapter } from "@donotdev/crud";
|
|
5
|
+
import { SupabaseCrudAdapter } from "@donotdev/supabase";
|
|
6
|
+
|
|
7
|
+
configureProviders({ crud: new FirestoreAdapter() }) // Firebase direct
|
|
8
|
+
configureProviders({ crud: new FunctionsAdapter() }) // via callable functions
|
|
9
|
+
configureProviders({ crud: new SupabaseCrudAdapter(sb) }) // Supabase direct (RLS)`);e.adapter=f("crud"),e.store&&e.store.getState().setCrudService(e)}}function F(e){const t=c();let r=`entity-${e}`,a=t.t("name",{ns:r,defaultValue:null});return a&&a!=="name"&&a!==`${r}:name`||e.endsWith("s")&&e.length>1&&(r=`entity-${e.slice(0,-1)}`,a=t.t("name",{ns:r,defaultValue:null}),a&&a!=="name"&&a!==`${r}:name`)?a:e}async function T(e,t,r,a){const i=u(t,r),n=e._inflightMutations.get(i);n&&await n.catch(()=>{});const s=a();e._inflightMutations.set(i,s);try{return await s}finally{e._inflightMutations.get(i)===s&&e._inflightMutations.delete(i)}}export{b as assertCanAccess,w as auditCrud,S as ensureAdapter,F as getEntityName,h as getPiiFields,A as initializeImpl,d as isTransientError,u as mutationKey,g as rateLimitKey,T as runSerializedMutation,y as shouldShowSuccessToast,v as withResilience};
|
package/dist/CrudService.js
CHANGED
|
@@ -1,9 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
Examples:
|
|
3
|
-
import { FirestoreAdapter } from "@donotdev/firebase";
|
|
4
|
-
import { FunctionsAdapter } from "@donotdev/crud";
|
|
5
|
-
import { SupabaseCrudAdapter } from "@donotdev/supabase";
|
|
6
|
-
|
|
7
|
-
configureProviders({ crud: new FirestoreAdapter() }) // Firebase direct
|
|
8
|
-
configureProviders({ crud: new FunctionsAdapter() }) // via callable functions
|
|
9
|
-
configureProviders({ crud: new SupabaseCrudAdapter(sb) }) // Supabase direct (RLS)`);this.adapter=F("crud"),this.store&&this.store.getState().setCrudService(this)}}getQueryClient(){return D()}getListQueryOptions(t,e,s,a,n=C.LIST){const r=this.adapter,i=()=>this._ensureAdapter();return{queryKey:["crud",t,"query",JSON.stringify(e)],queryFn:async()=>{if(r||await i(),!this.adapter)throw new Error("Adapter not initialized");const u=this.adapter;return this._withResilience(()=>u.query(t,e,s,n))},staleTime:a?.staleTime??S}}getDocQueryOptions(t,e,s,a){const n=this.adapter,r=()=>this._ensureAdapter();return{queryKey:["crud",t,"get",e],queryFn:async()=>{if(n||await r(),!this.adapter)throw new Error("Adapter not initialized");const i=this.adapter;return this._withResilience(()=>i.get(t,e,s))},staleTime:a?.staleTime??S}}_updateGetCache(t,e,s,a){const n=this.getQueryClient(),r=["crud",t,"get",e];a===o.DELETE?n.removeQueries({queryKey:r}):a===o.SET&&s?n.setQueryData(r,s):(a===o.UPDATE||a===o.ADD)&&s&&n.setQueryData(r,i=>i?{...i,...s}:s)}_updateListCaches(t,e,s,a){const n=this.getQueryClient();this._updateGetCache(t,e,s,a),n.setQueriesData({queryKey:["crud",t]},r=>{if(r&&typeof r=="object"&&"items"in r){const i=r;let u=i.items;return a===o.DELETE?(u=i.items.filter(d=>d!=null&&typeof d=="object"&&d.id!==e),{...i,items:u,total:Math.max(0,(i.total??u.length)-1)}):a===o.ADD&&s?(u=[...i.items,{...s,id:e}],{...i,items:u,total:(i.total??i.items.length)+1}):(a===o.UPDATE||a===o.SET)&&s&&i.items.some(h=>h!=null&&typeof h=="object"&&h.id===e)?(u=i.items.map(h=>h==null||typeof h!="object"||h.id!==e?h:a===o.SET?{...s,id:e}:{...h,...s}),{...i,items:u}):r}if(Array.isArray(r)){if(a===o.DELETE)return r.filter(i=>i.id!==e);if(a===o.ADD&&s)return[...r,{...s,id:e}];if((a===o.UPDATE||a===o.SET)&&s)return r.some(u=>u!=null&&typeof u=="object"&&u.id===e)?r.map(u=>u==null||typeof u!="object"||u.id!==e?u:a===o.SET?{...s,id:e}:{...u,...s}):r}return r})}_checkUniquenessFromCache(t,e,s){const n=s.metadata?.uniqueKeys;if(!n||n.length===0)return null;const i=this.getQueryClient().getQueriesData({queryKey:["crud",t]}),u=[];for(const[,h]of i)h&&typeof h=="object"&&"items"in h?u.push(...h.items):Array.isArray(h)&&u.push(...h);if(u.length===0)return null;const d=e;for(const h of n){if(!h.fields.every(g=>d[g]!=null&&d[g]!==""))continue;const f=u.find(g=>h.fields.every(c=>{const w=typeof d[c]=="string"?d[c].toLowerCase():d[c],E=typeof g[c]=="string"?g[c].toLowerCase():g[c];return w===E}));if(f){if(h.findOrCreate)return f.id;const g=h.fields.join(" + ");throw p(new Error(h.errorMessage||`Duplicate ${g}`),{userMessage:h.errorMessage||`A record with this ${g} already exists`,showNotification:!0})}}return null}_getItemFromListCache(t,e){const a=this.getQueryClient().getQueriesData({queryKey:["crud",t]});for(const[,n]of a)if(n?.items){const r=n.items.find(i=>i.id===e);if(r)return r}return null}async invalidateCollection(t){await this.getQueryClient().invalidateQueries({queryKey:["crud",t]})}async get(t,e,s,a){if(await this._ensureAdapter(),a?.noCache)return this._getFromAdapter(t,e,s);this.store&&(this.store.getState().setLoading(t,!0),this.store.getState().setError(t,null));try{return await this.getQueryClient().fetchQuery({queryKey:["crud",t,"get",e],queryFn:()=>this._getFromAdapter(t,e,s,!1),staleTime:a?.staleTime??S})}catch(n){const r=p(n,{userMessage:`Failed to fetch ${t}`,showNotification:!0});throw this.store&&this.store.getState().setError(t,r),r}finally{this.store&&this.store.getState().setLoading(t,!1)}}async _getFromAdapter(t,e,s,a=!0){this.store&&a&&(this.store.getState().setLoading(t,!0),this.store.getState().setError(t,null));try{if(!this.adapter)throw new Error("Adapter not initialized");this._assertCanAccess(t,s);const n=this.adapter,r=await this._withResilience(()=>n.get(t,e,s));if(r&&this.security){const i=this._getPiiFields(s);if(i.length>0)return this.security.decryptPii(r,i)}return r}catch(n){const r=p(n,{userMessage:`Failed to fetch ${t}`,showNotification:!0});throw this.store&&this.store.getState().setError(t,r),r}finally{this.store&&a&&this.store.getState().setLoading(t,!1)}}async query(t,e,s,a,n=C.LIST){if(await this._ensureAdapter(),a?.noCache)return this._queryFromAdapter(t,e,s,!0,n);this.store&&(this.store.getState().setLoading(t,!0),this.store.getState().setError(t,null));try{return await this.getQueryClient().fetchQuery({queryKey:["crud",t,"query",JSON.stringify(e)],queryFn:()=>this._queryFromAdapter(t,e,s,!1,n),staleTime:a?.staleTime??S})}catch(r){const i=p(r,{userMessage:`Failed to query ${t}`,showNotification:!0});throw this.store&&this.store.getState().setError(t,i),i}finally{this.store&&this.store.getState().setLoading(t,!1)}}async _queryFromAdapter(t,e,s,a=!0,n=C.LIST){this.store&&a&&(this.store.getState().setLoading(t,!0),this.store.getState().setError(t,null));try{if(!this.adapter)throw new Error("Adapter not initialized");this._assertCanAccess(t,s);const r=this.adapter,i=await this._withResilience(()=>r.query(t,e,s,n));if(this.security&&i.items.length>0){const u=this._getPiiFields(s);u.length>0&&(i.items=i.items.map(d=>this.security.decryptPii(d,u)))}return i}catch(r){const i=p(r,{userMessage:`Failed to query ${t}`,showNotification:!0});throw this.store&&this.store.getState().setError(t,i),i}finally{this.store&&a&&this.store.getState().setLoading(t,!1)}}_getEntityName(t){const e=m();let s=`entity-${t}`,a=e.t("name",{ns:s,defaultValue:null});return a&&a!=="name"&&a!==`${s}:name`||t.endsWith("s")&&t.length>1&&(s=`entity-${t.slice(0,-1)}`,a=e.t("name",{ns:s,defaultValue:null}),a&&a!=="name"&&a!==`${s}:name`)?a:t}async set(t,e,s,a,n){await this._ensureAdapter(),this.store&&(this.store.getState().setLoading(t,!0),this.store.getState().setError(t,null));const i=this.getQueryClient().getQueryData(["crud",t,"get",e])??null;this.store&&this.store.getState().updateOptimistic(t,e,s,i);try{if(!this.adapter)throw new Error("Adapter not initialized");this._assertCanAccess(t,a),this.security&&await this.security.checkRateLimit(this._rateLimitKey(t),"write");const u=this._getPiiFields(a),d=u.length>0&&this.security?this.security.encryptPii(s,u):s,h=this._mutationKey(t,e),y=this._inflightMutations.get(h);y&&await y.catch(()=>{});const f=this.adapter,g=(async()=>{await this._withResilience(()=>f.set(t,e,d,a))})();this._inflightMutations.set(h,g);try{await g}finally{this._inflightMutations.get(h)===g&&this._inflightMutations.delete(h)}if(this._updateListCaches(t,e,s,o.SET),this.store&&this.store.getState().confirmUpdate(t,e),this._auditCrud("crud.update",t,e),this._shouldShowSuccessToast(n)){const c=m(),w=this._getEntityName(t);_("success",c.t("messages.updateSuccess",{ns:"crud",entity:w}))}}catch(u){i&&this._updateListCaches(t,e,i,o.SET),this.store&&this.store.getState().rejectUpdate(t,e);const d=p(u,{userMessage:`Failed to save ${t}`,showNotification:!0}),h=m(),y=this._getEntityName(t);throw _("error",h.t("messages.updateError",{ns:"crud",entity:y})),this.store&&this.store.getState().setError(t,d),d}finally{this.store&&this.store.getState().setLoading(t,!1)}}async update(t,e,s,a,n){await this._ensureAdapter(),this.store&&(this.store.getState().setLoading(t,!0),this.store.getState().setError(t,null));const i=this.getQueryClient().getQueryData(["crud",t,"get",e])??this._getItemFromListCache(t,e),u=i?{...i,...s}:{...s,id:e};this.store&&this.store.getState().updateOptimistic(t,e,u,i??null);try{if(!this.adapter)throw new Error("Adapter not initialized");a&&this._assertCanAccess(t,a),this.security&&await this.security.checkRateLimit(this._rateLimitKey(t),"write");const d=a?this._getPiiFields(a):[],h=d.length>0&&this.security?this.security.encryptPii(s,d):s,y=this._mutationKey(t,e),f=this._inflightMutations.get(y);f&&await f.catch(()=>{});const g=this.adapter,c=(async()=>{await this._withResilience(()=>g.update(t,e,h))})();this._inflightMutations.set(y,c);try{await c}finally{this._inflightMutations.get(y)===c&&this._inflightMutations.delete(y)}if(this._updateListCaches(t,e,u,o.UPDATE),this.store&&this.store.getState().confirmUpdate(t,e),this._auditCrud("crud.update",t,e),this._shouldShowSuccessToast(n)){const w=m(),E=this._getEntityName(t);_("success",w.t("messages.updateSuccess",{ns:"crud",entity:E}))}}catch(d){i?this._updateListCaches(t,e,i,o.UPDATE):this.invalidateCollection(t),this.store&&this.store.getState().rejectUpdate(t,e);const h=p(d,{userMessage:`Failed to update ${t}`,showNotification:!0}),y=m(),f=this._getEntityName(t);throw _("error",y.t("messages.updateError",{ns:"crud",entity:f})),this.store&&this.store.getState().setError(t,h),h}finally{this.store&&this.store.getState().setLoading(t,!1)}}async delete(t,e,s){await this._ensureAdapter(),this.store&&(this.store.getState().setLoading(t,!0),this.store.getState().setError(t,null));const n=this.getQueryClient().getQueryData(["crud",t,"get",e])??this._getItemFromListCache(t,e);this.store&&n&&this.store.getState().deleteOptimistic(t,e,n);try{if(!this.adapter)throw new Error("Adapter not initialized");this.security&&await this.security.checkRateLimit(this._rateLimitKey(t),"write");const r=this._mutationKey(t,e),i=this._inflightMutations.get(r);i&&await i.catch(()=>{});const u=this.adapter,d=(async()=>{await this._withResilience(()=>u.delete(t,e))})();this._inflightMutations.set(r,d);try{await d}finally{this._inflightMutations.get(r)===d&&this._inflightMutations.delete(r)}if(this._updateListCaches(t,e,null,o.DELETE),this.store&&this.store.getState().confirmDelete(t,e),this._auditCrud("crud.delete",t,e),this.security?.recordAnomaly?.("bulk.deletes",this.currentUserId??void 0),this._shouldShowSuccessToast(s)){const h=m(),y=this._getEntityName(t);_("success",h.t("messages.deleteSuccess",{ns:"crud",entity:y}))}}catch(r){n&&this._updateListCaches(t,e,n,o.ADD),this.store&&this.store.getState().rejectDelete(t,e);const i=p(r,{userMessage:`Failed to delete ${t}`,showNotification:!0}),u=m(),d=this._getEntityName(t);throw _("error",u.t("messages.deleteError",{ns:"crud",entity:d})),this.store&&this.store.getState().setError(t,i),i}finally{this.store&&this.store.getState().setLoading(t,!1)}}async add(t,e,s,a){await this._ensureAdapter();const n=this._checkUniquenessFromCache(t,e,s);if(n)return n;this.store&&(this.store.getState().setLoading(t,!0),this.store.getState().setError(t,null));const r=`temp_${A()}`;this.store&&this.store.getState().addOptimistic(t,r,{...e,id:r});try{if(!this.adapter)throw new Error("Adapter not initialized");this._assertCanAccess(t,s),this.security&&await this.security.checkRateLimit(this._rateLimitKey(t),"write");const i=this._getPiiFields(s),u=i.length>0&&this.security?this.security.encryptPii(e,i):e,d=u;(d.status===void 0||d.status===null)&&(d.status=N);const h=this.adapter,y=await this._withResilience(()=>h.add(t,u,s)),f=y.id,g=y.data;if(this._updateListCaches(t,r,null,o.DELETE),this._updateListCaches(t,f,g,o.ADD),this.store&&this.store.getState().confirmOptimistic(t,r,f,g),this._auditCrud("crud.create",t,f),this._shouldShowSuccessToast(a)){const c=m(),w=this._getEntityName(t);_("success",c.t("messages.createSuccess",{ns:"crud",entity:w}))}return f}catch(i){this._updateListCaches(t,r,null,o.DELETE),this.store&&this.store.getState().rejectOptimistic(t,r);const u=p(i,{userMessage:`Failed to create ${t}`,showNotification:!0}),d=m(),h=this._getEntityName(t);throw _("error",d.t("messages.createError",{ns:"crud",entity:h})),this.store&&this.store.getState().setError(t,u),u}finally{this.store&&this.store.getState().setLoading(t,!1)}}subscribe(t,e,s,a){if(!this.adapter){let n=!1,r=null;return this._ensureAdapter().then(()=>{n||(r=this._subscribeSync(t,e,s,a))}).catch(i=>{n||s(null,p(i))}),()=>{n=!0,r?.()}}return this._subscribeSync(t,e,s,a)}_subscribeSync(t,e,s,a){try{const n=this.adapter;return n?n.subscribe?(this._assertCanAccess(t,a),n.subscribe(t,e,(r,i)=>{r&&this.getQueryClient().setQueryData(["crud",t,"get",e],r),s(r,i)},a)):()=>{}:(s(null,new Error("Adapter not initialized")),()=>{})}catch(n){return s(null,p(n)),()=>{}}}subscribeToCollection(t,e,s,a){if(!this.adapter){let n=!1,r=null;return this._ensureAdapter().then(()=>{n||(r=this._subscribeToCollectionSync(t,e,s,a))}).catch(i=>{n||s([],p(i))}),()=>{n=!0,r?.()}}return this._subscribeToCollectionSync(t,e,s,a)}_subscribeToCollectionSync(t,e,s,a){try{const n=this.adapter;return n?n.subscribeToCollection?(this._assertCanAccess(t,a),n.subscribeToCollection(t,e,(r,i)=>{r&&this.getQueryClient().setQueryData(["crud",t,"query",JSON.stringify(e)],u=>u?{...u,items:r}:{items:r}),s(r,i)},a)):()=>{}:(s([],new Error("Adapter not initialized")),()=>{})}catch(n){return s([],p(n)),()=>{}}}async addOptimistic(t,e,s,a){await this._ensureAdapter();const n=this._checkUniquenessFromCache(t,e,s);if(n)return{...e,id:n};this.security&&await this.security.checkRateLimit(this._rateLimitKey(t),"write");const r=`temp_${A()}`,i={...e,id:r,_optimistic:!0};this.store&&this.store.getState().addOptimistic(t,r,i);try{if(!this.adapter)throw new Error("Adapter not initialized");const u=this.adapter,d=await this._withResilience(()=>u.add(t,e,s)),h=d.id,y=d.data;if(this._updateListCaches(t,r,null,o.DELETE),this._updateListCaches(t,h,y,o.ADD),this.store&&this.store.getState().confirmOptimistic(t,r,h,y),this._auditCrud("crud.create",t,h),this._shouldShowSuccessToast(a)){const f=m(),g=this._getEntityName(t);_("success",f.t("messages.createSuccess",{ns:"crud",entity:g}))}return y}catch(u){this._updateListCaches(t,r,null,o.DELETE),this.store&&this.store.getState().rejectOptimistic(t,r);const d=p(u,{userMessage:`Failed to create ${t}`,showNotification:!0}),h=m(),y=this._getEntityName(t);throw _("error",h.t("messages.createError",{ns:"crud",entity:y})),d}}async updateOptimistic(t,e,s,a,n){await this._ensureAdapter(),this.security&&await this.security.checkRateLimit(this._rateLimitKey(t),"write");const i=this.getQueryClient().getQueryData(["crud",t,"get",e])??this._getItemFromListCache(t,e),u=i?{...i,...s,_optimistic:!0}:{...s,id:e,_optimistic:!0};this.store&&i&&this.store.getState().updateOptimistic(t,e,u,i);try{if(!this.adapter)throw new Error("Adapter not initialized");const d=this._mutationKey(t,e),h=this._inflightMutations.get(d);h&&await h.catch(()=>{});const y=this.adapter,f=(async()=>{await this._withResilience(()=>y.update(t,e,s))})();this._inflightMutations.set(d,f);try{await f}finally{this._inflightMutations.get(d)===f&&this._inflightMutations.delete(d)}const{_optimistic:g,...c}=u;if(this._updateListCaches(t,e,c,o.UPDATE),this.store&&this.store.getState().confirmUpdate(t,e),this._auditCrud("crud.update",t,e),this._shouldShowSuccessToast(n)){const w=m(),E=this._getEntityName(t);_("success",w.t("messages.updateSuccess",{ns:"crud",entity:E}))}return c}catch(d){i&&this._updateListCaches(t,e,i,o.UPDATE),this.store&&this.store.getState().rejectUpdate(t,e);const h=p(d,{userMessage:`Failed to update ${t}`,showNotification:!0}),y=m(),f=this._getEntityName(t);throw _("error",y.t("messages.updateError",{ns:"crud",entity:f})),h}}async deleteOptimistic(t,e,s){await this._ensureAdapter(),this.security&&await this.security.checkRateLimit(this._rateLimitKey(t),"write");const n=this.getQueryClient().getQueryData(["crud",t,"get",e])??this._getItemFromListCache(t,e);this.store&&n&&this.store.getState().deleteOptimistic(t,e,n);try{if(!this.adapter)throw new Error("Adapter not initialized");const r=this._mutationKey(t,e),i=this._inflightMutations.get(r);i&&await i.catch(()=>{});const u=this.adapter,d=(async()=>{await this._withResilience(()=>u.delete(t,e))})();this._inflightMutations.set(r,d);try{await d}finally{this._inflightMutations.get(r)===d&&this._inflightMutations.delete(r)}if(this._updateListCaches(t,e,null,o.DELETE),this.store&&this.store.getState().confirmDelete(t,e),this._auditCrud("crud.delete",t,e),this.security?.recordAnomaly?.("bulk.deletes",this.currentUserId??void 0),this._shouldShowSuccessToast(s)){const h=m(),y=this._getEntityName(t);_("success",h.t("messages.deleteSuccess",{ns:"crud",entity:y}))}}catch(r){n&&this._updateListCaches(t,e,n,o.ADD),this.store&&this.store.getState().rejectDelete(t,e);const i=p(r,{userMessage:`Failed to delete ${t}`,showNotification:!0}),u=m(),d=this._getEntityName(t);throw _("error",u.t("messages.deleteError",{ns:"crud",entity:d})),i}}}const R=T(()=>new b);export{R as getCrudService};
|
|
1
|
+
import{createSingleton as l,getQueryClient as n}from"@donotdev/core";import{bulkImpl as o}from"./CrudService.bulk";import{bulkAcrossImpl as p}from"./CrudService.bulkAcross";import{invalidateCollectionImpl as a}from"./CrudService.cache";import{initializeImpl as m}from"./CrudService.internal";import{addImpl as c,deleteImpl as d,setImpl as h,updateImpl as I}from"./CrudService.mutations";import{addOptimisticImpl as b,deleteOptimisticImpl as g,updateOptimisticImpl as y}from"./CrudService.optimistic";import{getDocQueryOptionsImpl as f,getImpl as O,getListQueryOptionsImpl as C,queryImpl as Q}from"./CrudService.queries";import{subscribeImpl as S,subscribeToCollectionImpl as k}from"./CrudService.subscriptions";class u{adapter=null;store=null;security=null;currentUserId=null;_inflightMutations=new Map;setStore(t){this.store=t}setSecurity(t){this.security=t}setCurrentUser(t){this.currentUserId=t}initialize(){return m(this)}getQueryClient(){return n()}getListQueryOptions(t,e,r,i,s){return C(this,t,e,r,i,s)}getDocQueryOptions(t,e,r,i){return f(this,t,e,r,i)}invalidateCollection(t){return a(this,t)}get(t,e,r,i){return O(this,t,e,r,i)}query(t,e,r,i,s){return Q(this,t,e,r,i,s)}set(t,e,r,i,s){return h(this,t,e,r,i,s)}update(t,e,r,i,s){return I(this,t,e,r,i,s)}delete(t,e,r){return d(this,t,e,r)}add(t,e,r,i){return c(this,t,e,r,i)}bulk(t,e,r,i){return o(this,t,e,r,i)}bulkAcross(t,e){return p(this,t,e)}subscribe(t,e,r,i){return S(this,t,e,r,i)}subscribeToCollection(t,e,r,i){return k(this,t,e,r,i)}addOptimistic(t,e,r,i){return b(this,t,e,r,i)}updateOptimistic(t,e,r,i,s){return y(this,t,e,r,i,s)}deleteOptimistic(t,e,r){return g(this,t,e,r)}}const v=l(()=>new u);export{u as CrudService,v as getCrudService};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { CrudCreateInput, dndevSchema } from '@donotdev/core';
|
|
2
|
+
import type { CrudServiceInternal, MutationOptions } from './types';
|
|
3
|
+
export declare function setImpl<T>(self: CrudServiceInternal, collection: string, id: string, data: T, schema: dndevSchema<T>, options?: MutationOptions): Promise<void>;
|
|
4
|
+
export declare function updateImpl<T>(self: CrudServiceInternal, collection: string, id: string, data: Partial<T>, schema?: dndevSchema<T>, options?: MutationOptions): Promise<void>;
|
|
5
|
+
export declare function deleteImpl(self: CrudServiceInternal, collection: string, id: string, options?: MutationOptions): Promise<void>;
|
|
6
|
+
export declare function addImpl<T extends Record<string, unknown>>(self: CrudServiceInternal, collection: string, data: CrudCreateInput<T>, schema: dndevSchema<T>, options?: MutationOptions): Promise<string>;
|
|
7
|
+
//# sourceMappingURL=CrudService.mutations.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CrudService.mutations.d.ts","sourceRoot":"","sources":["../src/CrudService.mutations.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAoBnE,OAAO,KAAK,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAEpE,wBAAsB,OAAO,CAAC,CAAC,EAC7B,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,CAAC,EACP,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,IAAI,CAAC,CA0Gf;AAED,wBAAsB,UAAU,CAAC,CAAC,EAChC,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,MAAM,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,EACvB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,IAAI,CAAC,CA6Hf;AAED,wBAAsB,UAAU,CAC9B,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,IAAI,CAAC,CA6Ff;AAED,wBAAsB,OAAO,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7D,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,eAAe,CAAC,CAAC,CAAC,EACxB,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,MAAM,CAAC,CAsHjB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toast as p}from"@donotdev/components";import{generateUUID as R,getI18nInstance as m,handleError as E}from"@donotdev/core";import{checkUniquenessFromCache as k,getItemFromListCache as O,updateListCaches as l}from"./CrudService.cache";import{assertCanAccess as U,auditCrud as f,ensureAdapter as h,getEntityName as S,getPiiFields as C,rateLimitKey as L,runSerializedMutation as I,shouldShowSuccessToast as D,withResilience as A}from"./CrudService.internal";import{CRUD_OPERATION as g}from"./types";async function N(t,e,r,i,c,u){await h(t),t.store&&(t.store.getState().setLoading(e,!0),t.store.getState().setError(e,null));const a=t.getQueryClient().getQueryData(["crud",e,"get",r])??null;t.store&&t.store.getState().updateOptimistic(e,r,i,a);try{if(!t.adapter)throw new Error("Adapter not initialized");U(t,e,c),t.security&&await t.security.checkRateLimit(L(t,e),"write");const o=C(c),s=o.length>0&&t.security?t.security.encryptPii(i,o):i,n=t.adapter;if(await I(t,e,r,async()=>{await A(()=>n.set(e,r,s,c))}),l(t,e,r,i,g.SET),t.store&&t.store.getState().confirmUpdate(e,r),f(t,"crud.update",e,r),D(t,u)){const d=m(),y=S(e);p("success",d.t("messages.updateSuccess",{ns:"crud",entity:y}))}}catch(o){a&&l(t,e,r,a,g.SET),t.store&&t.store.getState().rejectUpdate(e,r);const s=E(o,{userMessage:`Failed to save ${e}`,showNotification:!0}),n=m(),d=S(e);throw p("error",n.t("messages.updateError",{ns:"crud",entity:d})),t.store&&t.store.getState().setError(e,s),s}finally{t.store&&t.store.getState().setLoading(e,!1)}}async function Q(t,e,r,i,c,u){await h(t),t.store&&(t.store.getState().setLoading(e,!0),t.store.getState().setError(e,null));const a=t.getQueryClient().getQueryData(["crud",e,"get",r])??O(t,e,r),o=a?{...a,...i}:{...i,id:r};t.store&&t.store.getState().updateOptimistic(e,r,o,a??null);try{if(!t.adapter)throw new Error("Adapter not initialized");c&&U(t,e,c),t.security&&await t.security.checkRateLimit(L(t,e),"write");const s=c?C(c):[],n=s.length>0&&t.security?t.security.encryptPii(i,s):i,d=t.adapter;if(await I(t,e,r,async()=>{await A(()=>d.update(e,r,n))}),l(t,e,r,o,g.UPDATE),t.store&&t.store.getState().confirmUpdate(e,r),f(t,"crud.update",e,r),D(t,u)){const y=m(),w=S(e);p("success",y.t("messages.updateSuccess",{ns:"crud",entity:w}))}}catch(s){a?l(t,e,r,a,g.UPDATE):t.invalidateCollection(e),t.store&&t.store.getState().rejectUpdate(e,r);const n=E(s,{userMessage:`Failed to update ${e}`,showNotification:!0}),d=m(),y=S(e);throw p("error",d.t("messages.updateError",{ns:"crud",entity:y})),t.store&&t.store.getState().setError(e,n),n}finally{t.store&&t.store.getState().setLoading(e,!1)}}async function j(t,e,r,i){await h(t),t.store&&(t.store.getState().setLoading(e,!0),t.store.getState().setError(e,null));const c=t.getQueryClient().getQueryData(["crud",e,"get",r])??O(t,e,r);t.store&&c&&t.store.getState().deleteOptimistic(e,r,c);try{if(!t.adapter)throw new Error("Adapter not initialized");t.security&&await t.security.checkRateLimit(L(t,e),"write");const u=t.adapter;if(await I(t,e,r,async()=>{await A(()=>u.delete(e,r))}),l(t,e,r,null,g.DELETE),t.store&&t.store.getState().confirmDelete(e,r),f(t,"crud.delete",e,r),t.security?.recordAnomaly?.("bulk.deletes",t.currentUserId??void 0),D(t,i)){const a=m(),o=S(e);p("success",a.t("messages.deleteSuccess",{ns:"crud",entity:o}))}}catch(u){c&&l(t,e,r,c,g.ADD),t.store&&t.store.getState().rejectDelete(e,r);const a=E(u,{userMessage:`Failed to delete ${e}`,showNotification:!0}),o=m(),s=S(e);throw p("error",o.t("messages.deleteError",{ns:"crud",entity:s})),t.store&&t.store.getState().setError(e,a),a}finally{t.store&&t.store.getState().setLoading(e,!1)}}async function v(t,e,r,i,c){await h(t);const u=k(t,e,r,i);if(u)return u;t.store&&(t.store.getState().setLoading(e,!0),t.store.getState().setError(e,null));const a=`temp_${R()}`;t.store&&t.store.getState().addOptimistic(e,a,{...r,id:a});try{if(!t.adapter)throw new Error("Adapter not initialized");U(t,e,i),t.security&&await t.security.checkRateLimit(L(t,e),"write");const o=C(i),s=o.length>0&&t.security?t.security.encryptPii(r,o):r,n=s;(n.status===void 0||n.status===null)&&(n.status="draft");const d=t.adapter,y=await A(()=>d.add(e,s,i)),w=y.id,T=y.data;if(l(t,e,a,null,g.DELETE),l(t,e,w,T,g.ADD),t.store&&t.store.getState().confirmOptimistic(e,a,w,T),f(t,"crud.create",e,w),D(t,c)){const F=m(),P=S(e);p("success",F.t("messages.createSuccess",{ns:"crud",entity:P}))}return w}catch(o){l(t,e,a,null,g.DELETE),t.store&&t.store.getState().rejectOptimistic(e,a);const s=E(o,{userMessage:`Failed to create ${e}`,showNotification:!0}),n=m(),d=S(e);throw p("error",n.t("messages.createError",{ns:"crud",entity:d})),t.store&&t.store.getState().setError(e,s),s}finally{t.store&&t.store.getState().setLoading(e,!1)}}export{v as addImpl,j as deleteImpl,N as setImpl,Q as updateImpl};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { dndevSchema } from '@donotdev/core';
|
|
2
|
+
import type { CrudServiceInternal, MutationOptions } from './types';
|
|
3
|
+
export declare function addOptimisticImpl<T extends {
|
|
4
|
+
id?: string;
|
|
5
|
+
}>(self: CrudServiceInternal, collection: string, data: T, schema: dndevSchema<T>, options?: MutationOptions): Promise<T & {
|
|
6
|
+
id: string;
|
|
7
|
+
}>;
|
|
8
|
+
export declare function updateOptimisticImpl<T>(self: CrudServiceInternal, collection: string, id: string, data: Partial<T>, schema: dndevSchema<T>, options?: MutationOptions): Promise<T>;
|
|
9
|
+
export declare function deleteOptimisticImpl(self: CrudServiceInternal, collection: string, id: string, options?: MutationOptions): Promise<void>;
|
|
10
|
+
//# sourceMappingURL=CrudService.optimistic.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CrudService.optimistic.d.ts","sourceRoot":"","sources":["../src/CrudService.optimistic.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAkBlD,OAAO,KAAK,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAEpE,wBAAsB,iBAAiB,CAAC,CAAC,SAAS;IAAE,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,EAC/D,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,CAAC,EACP,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,CAAC,GAAG;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC,CAiG7B;AAED,wBAAsB,oBAAoB,CAAC,CAAC,EAC1C,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,CAAC,CAAC,CAmGZ;AAED,wBAAsB,oBAAoB,CACxC,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,OAAO,CAAC,EAAE,eAAe,GACxB,OAAO,CAAC,IAAI,CAAC,CA8Ef"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toast as g}from"@donotdev/components";import{generateUUID as C,getI18nInstance as w,handleError as f}from"@donotdev/core";import{checkUniquenessFromCache as T,getItemFromListCache as I,updateListCaches as m}from"./CrudService.cache";import{auditCrud as E,ensureAdapter as D,getEntityName as y,rateLimitKey as S,runSerializedMutation as L,shouldShowSuccessToast as A,withResilience as O}from"./CrudService.internal";import{CRUD_OPERATION as l}from"./types";async function R(t,e,r,o,u){await D(t);const n=T(t,e,r,o);if(n)return{...r,id:n};t.security&&await t.security.checkRateLimit(S(t,e),"write");const a=`temp_${C()}`,d={...r,id:a,_optimistic:!0};t.store&&t.store.getState().addOptimistic(e,a,d);try{if(!t.adapter)throw new Error("Adapter not initialized");const s=t.adapter,p=await O(()=>s.add(e,r,o)),i=p.id,c=p.data;if(m(t,e,a,null,l.DELETE),m(t,e,i,c,l.ADD),t.store&&t.store.getState().confirmOptimistic(e,a,i,c),E(t,"crud.create",e,i),A(t,u)){const h=w(),U=y(e);g("success",h.t("messages.createSuccess",{ns:"crud",entity:U}))}return c}catch(s){m(t,e,a,null,l.DELETE),t.store&&t.store.getState().rejectOptimistic(e,a);const p=f(s,{userMessage:`Failed to create ${e}`,showNotification:!0}),i=w(),c=y(e);throw g("error",i.t("messages.createError",{ns:"crud",entity:c})),p}}async function _(t,e,r,o,u,n){await D(t),t.security&&await t.security.checkRateLimit(S(t,e),"write");const a=t.getQueryClient().getQueryData(["crud",e,"get",r])??I(t,e,r),d=a?{...a,...o,_optimistic:!0}:{...o,id:r,_optimistic:!0};t.store&&a&&t.store.getState().updateOptimistic(e,r,d,a);try{if(!t.adapter)throw new Error("Adapter not initialized");const s=t.adapter;await L(t,e,r,async()=>{await O(()=>s.update(e,r,o))});const{_optimistic:p,...i}=d;if(m(t,e,r,i,l.UPDATE),t.store&&t.store.getState().confirmUpdate(e,r),E(t,"crud.update",e,r),A(t,n)){const c=w(),h=y(e);g("success",c.t("messages.updateSuccess",{ns:"crud",entity:h}))}return i}catch(s){a&&m(t,e,r,a,l.UPDATE),t.store&&t.store.getState().rejectUpdate(e,r);const p=f(s,{userMessage:`Failed to update ${e}`,showNotification:!0}),i=w(),c=y(e);throw g("error",i.t("messages.updateError",{ns:"crud",entity:c})),p}}async function N(t,e,r,o){await D(t),t.security&&await t.security.checkRateLimit(S(t,e),"write");const u=t.getQueryClient().getQueryData(["crud",e,"get",r])??I(t,e,r);t.store&&u&&t.store.getState().deleteOptimistic(e,r,u);try{if(!t.adapter)throw new Error("Adapter not initialized");const n=t.adapter;if(await L(t,e,r,async()=>{await O(()=>n.delete(e,r))}),m(t,e,r,null,l.DELETE),t.store&&t.store.getState().confirmDelete(e,r),E(t,"crud.delete",e,r),t.security?.recordAnomaly?.("bulk.deletes",t.currentUserId??void 0),A(t,o)){const a=w(),d=y(e);g("success",a.t("messages.deleteSuccess",{ns:"crud",entity:d}))}}catch(n){u&&m(t,e,r,u,l.ADD),t.store&&t.store.getState().rejectDelete(e,r);const a=f(n,{userMessage:`Failed to delete ${e}`,showNotification:!0}),d=w(),s=y(e);throw g("error",d.t("messages.deleteError",{ns:"crud",entity:s})),a}}export{R as addOptimisticImpl,N as deleteOptimisticImpl,_ as updateOptimisticImpl};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview CrudService read operations
|
|
3
|
+
* @description get / query / getListQueryOptions / getDocQueryOptions impl
|
|
4
|
+
* functions. Extracted from CrudService.ts to keep each file under the 500-LOC
|
|
5
|
+
* cap. The class methods are thin thunks — all logic lives here.
|
|
6
|
+
*
|
|
7
|
+
* @version 0.1.0
|
|
8
|
+
* @since 0.0.1
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
10
|
+
*/
|
|
11
|
+
import type { CrudDocQuery, CrudListQuery, dndevSchema, QueryOptions, PaginatedQueryResult, ListSchemaType } from '@donotdev/core';
|
|
12
|
+
import type { CacheOptions, CrudServiceInternal } from './types';
|
|
13
|
+
/**
|
|
14
|
+
* Get query options for list queries. Use with useQuery() in hooks.
|
|
15
|
+
* Returns reactive loading states via TanStack Query.
|
|
16
|
+
* @param schema - Accepts dndevSchema<unknown> since OperationSchemas uses unknown. T is for return type.
|
|
17
|
+
*/
|
|
18
|
+
export declare function getListQueryOptionsImpl<T>(self: CrudServiceInternal, collection: string, queryOptions: QueryOptions, schema: dndevSchema<unknown>, cacheOptions?: CacheOptions, schemaType?: ListSchemaType): CrudListQuery<T>;
|
|
19
|
+
/**
|
|
20
|
+
* Get query options for single document queries. Use with useQuery() in hooks.
|
|
21
|
+
* Returns reactive loading states via TanStack Query.
|
|
22
|
+
* @param schema - Accepts dndevSchema<unknown> since OperationSchemas uses unknown. T is for return type.
|
|
23
|
+
*/
|
|
24
|
+
export declare function getDocQueryOptionsImpl<T>(self: CrudServiceInternal, collection: string, id: string, schema: dndevSchema<unknown>, cacheOptions?: CacheOptions): CrudDocQuery<T>;
|
|
25
|
+
export declare function getImpl<T>(self: CrudServiceInternal, collection: string, id: string, schema: dndevSchema<T>, options?: CacheOptions): Promise<T | null>;
|
|
26
|
+
export declare function queryImpl<T>(self: CrudServiceInternal, collection: string, options: QueryOptions, schema: dndevSchema<T>, cacheOptions?: CacheOptions, schemaType?: ListSchemaType): Promise<PaginatedQueryResult<T>>;
|
|
27
|
+
//# sourceMappingURL=CrudService.queries.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CrudService.queries.d.ts","sourceRoot":"","sources":["../src/CrudService.queries.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EACV,YAAY,EACZ,aAAa,EACb,WAAW,EACX,YAAY,EACZ,oBAAoB,EACpB,cAAc,EACf,MAAM,gBAAgB,CAAC;AASxB,OAAO,KAAK,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAKjE;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,EACvC,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,YAAY,EAC1B,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,EAC5B,YAAY,CAAC,EAAE,YAAY,EAC3B,UAAU,GAAE,cAAsC,GACjD,aAAa,CAAC,CAAC,CAAC,CAsBlB;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,CAAC,EACtC,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,EAC5B,YAAY,CAAC,EAAE,YAAY,GAC1B,YAAY,CAAC,CAAC,CAAC,CAgBjB;AAED,wBAAsB,OAAO,CAAC,CAAC,EAC7B,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,OAAO,CAAC,EAAE,YAAY,GACrB,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAwCnB;AAuDD,wBAAsB,SAAS,CAAC,CAAC,EAC/B,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,EACtB,YAAY,CAAC,EAAE,YAAY,EAC3B,UAAU,GAAE,cAAsC,GACjD,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAkDlC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LIST_SCHEMA_TYPE as d,handleError as u}from"@donotdev/core";import{assertCanAccess as f,ensureAdapter as y,getPiiFields as h,withResilience as l}from"./CrudService.internal";const g=1/0;function m(t,r,a,o,i,n=d.LIST){const e=t.adapter,s=()=>y(t);return{queryKey:["crud",r,"query",JSON.stringify(a)],queryFn:async()=>{if(e||await s(),!t.adapter)throw new Error("Adapter not initialized");const c=t.adapter;return l(()=>c.query(r,a,o,n))},staleTime:i?.staleTime??g}}function q(t,r,a,o,i){const n=t.adapter,e=()=>y(t);return{queryKey:["crud",r,"get",a],queryFn:async()=>{if(n||await e(),!t.adapter)throw new Error("Adapter not initialized");const s=t.adapter;return l(()=>s.get(r,a,o))},staleTime:i?.staleTime??g}}async function E(t,r,a,o,i){if(await y(t),i?.noCache)return p(t,r,a,o);t.store&&(t.store.getState().setLoading(r,!0),t.store.getState().setError(r,null));try{return await t.getQueryClient().fetchQuery({queryKey:["crud",r,"get",a],queryFn:()=>p(t,r,a,o,!1),staleTime:i?.staleTime??g})}catch(n){const e=u(n,{userMessage:`Failed to fetch ${r}`,showNotification:!0});throw t.store&&t.store.getState().setError(r,e),e}finally{t.store&&t.store.getState().setLoading(r,!1)}}async function p(t,r,a,o,i=!0){t.store&&i&&(t.store.getState().setLoading(r,!0),t.store.getState().setError(r,null));try{if(!t.adapter)throw new Error("Adapter not initialized");f(t,r,o);const n=t.adapter,e=await l(()=>n.get(r,a,o));if(e&&t.security){const s=h(o);if(s.length>0)return t.security.decryptPii(e,s)}return e}catch(n){const e=u(n,{userMessage:`Failed to fetch ${r}`,showNotification:!0});throw t.store&&t.store.getState().setError(r,e),e}finally{t.store&&i&&t.store.getState().setLoading(r,!1)}}async function L(t,r,a,o,i,n=d.LIST){if(await y(t),i?.noCache)return w(t,r,a,o,!0,n);t.store&&(t.store.getState().setLoading(r,!0),t.store.getState().setError(r,null));try{return await t.getQueryClient().fetchQuery({queryKey:["crud",r,"query",JSON.stringify(a)],queryFn:()=>w(t,r,a,o,!1,n),staleTime:i?.staleTime??g})}catch(e){const s=u(e,{userMessage:`Failed to query ${r}`,showNotification:!0});throw t.store&&t.store.getState().setError(r,s),s}finally{t.store&&t.store.getState().setLoading(r,!1)}}async function w(t,r,a,o,i=!0,n=d.LIST){t.store&&i&&(t.store.getState().setLoading(r,!0),t.store.getState().setError(r,null));try{if(!t.adapter)throw new Error("Adapter not initialized");f(t,r,o);const e=t.adapter,s=await l(()=>e.query(r,a,o,n));if(t.security&&s.items.length>0){const c=h(o);c.length>0&&(s.items=s.items.map(S=>t.security.decryptPii(S,c)))}return s}catch(e){const s=u(e,{userMessage:`Failed to query ${r}`,showNotification:!0});throw t.store&&t.store.getState().setError(r,s),s}finally{t.store&&i&&t.store.getState().setLoading(r,!1)}}export{q as getDocQueryOptionsImpl,E as getImpl,m as getListQueryOptionsImpl,L as queryImpl};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview CrudService real-time subscriptions
|
|
3
|
+
* @description subscribe / subscribeToCollection impl functions. Syncs adapter
|
|
4
|
+
* real-time events to the same TanStack Query cache keys used by get/query, so
|
|
5
|
+
* mutations and subscriptions share one source of truth.
|
|
6
|
+
*
|
|
7
|
+
* Extracted from CrudService.ts to keep each file under the 500-LOC cap.
|
|
8
|
+
*
|
|
9
|
+
* @version 0.1.0
|
|
10
|
+
* @since 0.0.1
|
|
11
|
+
* @author AMBROISE PARK Consulting
|
|
12
|
+
*/
|
|
13
|
+
import type { dndevSchema, QueryOptions } from '@donotdev/core';
|
|
14
|
+
import type { CrudServiceInternal } from './types';
|
|
15
|
+
export declare function subscribeImpl<T>(self: CrudServiceInternal, collection: string, id: string, callback: (data: T | null, error?: Error) => void, schema: dndevSchema<T>): () => void;
|
|
16
|
+
export declare function subscribeToCollectionImpl<T>(self: CrudServiceInternal, collection: string, options: QueryOptions, callback: (data: T[], error?: Error) => void, schema: dndevSchema<T>): () => void;
|
|
17
|
+
//# sourceMappingURL=CrudService.subscriptions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CrudService.subscriptions.d.ts","sourceRoot":"","sources":["../src/CrudService.subscriptions.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EAEb,MAAM,gBAAgB,CAAC;AAIxB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAEnD,wBAAgB,aAAa,CAAC,CAAC,EAC7B,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,MAAM,EACV,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,EACjD,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,GACrB,MAAM,IAAI,CAwBZ;AAwCD,wBAAgB,yBAAyB,CAAC,CAAC,EACzC,IAAI,EAAE,mBAAmB,EACzB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,YAAY,EACrB,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,EAC5C,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,GACrB,MAAM,IAAI,CA4BZ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{handleError as l}from"@donotdev/core";import{assertCanAccess as c,ensureAdapter as b}from"./CrudService.internal";function f(e,u,s,t,i){if(!e.adapter){let r=!1,n=null;return b(e).then(()=>{r||(n=d(e,u,s,t,i))}).catch(o=>{r||t(null,l(o))}),()=>{r=!0,n?.()}}return d(e,u,s,t,i)}function d(e,u,s,t,i){try{const r=e.adapter;return r?r.subscribe?(c(e,u,i),r.subscribe(u,s,(n,o)=>{n&&e.getQueryClient().setQueryData(["crud",u,"get",s],n),t(n,o)},i)):()=>{}:(t(null,new Error("Adapter not initialized")),()=>{})}catch(r){return t(null,l(r)),()=>{}}}function m(e,u,s,t,i){if(!e.adapter){let r=!1,n=null;return b(e).then(()=>{r||(n=p(e,u,s,t,i))}).catch(o=>{r||t([],l(o))}),()=>{r=!0,n?.()}}return p(e,u,s,t,i)}function p(e,u,s,t,i){try{const r=e.adapter;return r?r.subscribeToCollection?(c(e,u,i),r.subscribeToCollection(u,s,(n,o)=>{n&&e.getQueryClient().setQueryData(["crud",u,"query",JSON.stringify(s)],a=>a?{...a,items:n}:{items:n}),t(n,o)},i)):()=>{}:(t([],new Error("Adapter not initialized")),()=>{})}catch(r){return t([],l(r)),()=>{}}}export{f as subscribeImpl,m as subscribeToCollectionImpl};
|
package/dist/CrudStore.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CrudStore.d.ts","sourceRoot":"","sources":["../src/CrudStore.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAEV,SAAS,EACT,WAAW,EAIZ,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"CrudStore.d.ts","sourceRoot":"","sources":["../src/CrudStore.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAEV,SAAS,EACT,WAAW,EAIZ,MAAM,SAAS,CAAC;AA8FjB;;;;;;GAMG;AACH,eAAO,MAAM,YAAY,iIA0cvB,CAAC"}
|