@contember/binding-legacy 2.1.0-beta.2 → 2.2.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/development/src/accessors/EntityAccessorImpl.cjs.map +1 -1
- package/dist/development/src/accessors/EntityAccessorImpl.js.map +1 -1
- package/dist/development/src/accessors/EntityListAccessorImpl.cjs.map +1 -1
- package/dist/development/src/accessors/EntityListAccessorImpl.js.map +1 -1
- package/dist/development/src/accessors/FieldAccessorImpl.cjs.map +1 -1
- package/dist/development/src/accessors/FieldAccessorImpl.js.map +1 -1
- package/dist/development/src/core/AccessorErrorManager.cjs.map +1 -1
- package/dist/development/src/core/AccessorErrorManager.js.map +1 -1
- package/dist/development/src/core/Config.cjs.map +1 -1
- package/dist/development/src/core/Config.js.map +1 -1
- package/dist/development/src/core/DataBinding.cjs.map +1 -1
- package/dist/development/src/core/DataBinding.js.map +1 -1
- package/dist/development/src/core/ErrorsPreprocessor.cjs.map +1 -1
- package/dist/development/src/core/ErrorsPreprocessor.js.map +1 -1
- package/dist/development/src/core/EventManager.cjs.map +1 -1
- package/dist/development/src/core/EventManager.js.map +1 -1
- package/dist/development/src/core/MutationGenerator.cjs.map +1 -1
- package/dist/development/src/core/MutationGenerator.js.map +1 -1
- package/dist/development/src/core/RealmKeyGenerator.cjs.map +1 -1
- package/dist/development/src/core/RealmKeyGenerator.js.map +1 -1
- package/dist/development/src/core/RequestResponseNormalizer.cjs.map +1 -1
- package/dist/development/src/core/RequestResponseNormalizer.js.map +1 -1
- package/dist/development/src/core/StateInitializer.cjs.map +1 -1
- package/dist/development/src/core/StateInitializer.js.map +1 -1
- package/dist/development/src/core/TreeAugmenter.cjs.map +1 -1
- package/dist/development/src/core/TreeAugmenter.js.map +1 -1
- package/dist/development/src/core/TreeStore.cjs.map +1 -1
- package/dist/development/src/core/TreeStore.js.map +1 -1
- package/dist/development/src/core/exceptions/ErrorLocator.cjs.map +1 -1
- package/dist/development/src/core/exceptions/ErrorLocator.js.map +1 -1
- package/dist/development/src/core/exceptions/MarkerSugarer.cjs.map +1 -1
- package/dist/development/src/core/exceptions/MarkerSugarer.js.map +1 -1
- package/dist/development/src/core/factories/createBatchUpdatesOptions.cjs.map +1 -1
- package/dist/development/src/core/factories/createBatchUpdatesOptions.js.map +1 -1
- package/dist/development/src/core/operations/EntityOperations.cjs.map +1 -1
- package/dist/development/src/core/operations/EntityOperations.js.map +1 -1
- package/dist/development/src/core/operations/FieldOperations.cjs.map +1 -1
- package/dist/development/src/core/operations/FieldOperations.js.map +1 -1
- package/dist/development/src/core/operations/ListOperations.cjs.map +1 -1
- package/dist/development/src/core/operations/ListOperations.js.map +1 -1
- package/dist/development/src/core/operations/OperationsHelpers.cjs.map +1 -1
- package/dist/development/src/core/operations/OperationsHelpers.js.map +1 -1
- package/dist/development/src/core/state/StateIterator.cjs.map +1 -1
- package/dist/development/src/core/state/StateIterator.js.map +1 -1
- package/dist/development/src/core/state/getEntityMarker.cjs.map +1 -1
- package/dist/development/src/core/state/getEntityMarker.js.map +1 -1
- package/dist/development/src/fieldHelpers/helpers/TemporalFieldHelper.cjs.map +1 -1
- package/dist/development/src/fieldHelpers/helpers/TemporalFieldHelper.js.map +1 -1
- package/dist/development/src/fieldHelpers/helpers/UuidFieldHelper.cjs.map +1 -1
- package/dist/development/src/fieldHelpers/helpers/UuidFieldHelper.js.map +1 -1
- package/dist/production/src/accessors/EntityAccessorImpl.cjs.map +1 -1
- package/dist/production/src/accessors/EntityAccessorImpl.js.map +1 -1
- package/dist/production/src/accessors/EntityListAccessorImpl.cjs.map +1 -1
- package/dist/production/src/accessors/EntityListAccessorImpl.js.map +1 -1
- package/dist/production/src/accessors/FieldAccessorImpl.cjs.map +1 -1
- package/dist/production/src/accessors/FieldAccessorImpl.js.map +1 -1
- package/dist/production/src/core/AccessorErrorManager.cjs.map +1 -1
- package/dist/production/src/core/AccessorErrorManager.js.map +1 -1
- package/dist/production/src/core/Config.cjs.map +1 -1
- package/dist/production/src/core/Config.js.map +1 -1
- package/dist/production/src/core/DataBinding.cjs.map +1 -1
- package/dist/production/src/core/DataBinding.js.map +1 -1
- package/dist/production/src/core/ErrorsPreprocessor.cjs.map +1 -1
- package/dist/production/src/core/ErrorsPreprocessor.js.map +1 -1
- package/dist/production/src/core/EventManager.cjs.map +1 -1
- package/dist/production/src/core/EventManager.js.map +1 -1
- package/dist/production/src/core/MutationGenerator.cjs.map +1 -1
- package/dist/production/src/core/MutationGenerator.js.map +1 -1
- package/dist/production/src/core/RealmKeyGenerator.cjs.map +1 -1
- package/dist/production/src/core/RealmKeyGenerator.js.map +1 -1
- package/dist/production/src/core/RequestResponseNormalizer.cjs.map +1 -1
- package/dist/production/src/core/RequestResponseNormalizer.js.map +1 -1
- package/dist/production/src/core/StateInitializer.cjs.map +1 -1
- package/dist/production/src/core/StateInitializer.js.map +1 -1
- package/dist/production/src/core/TreeAugmenter.cjs.map +1 -1
- package/dist/production/src/core/TreeAugmenter.js.map +1 -1
- package/dist/production/src/core/TreeStore.cjs.map +1 -1
- package/dist/production/src/core/TreeStore.js.map +1 -1
- package/dist/production/src/core/exceptions/ErrorLocator.cjs.map +1 -1
- package/dist/production/src/core/exceptions/ErrorLocator.js.map +1 -1
- package/dist/production/src/core/exceptions/MarkerSugarer.cjs.map +1 -1
- package/dist/production/src/core/exceptions/MarkerSugarer.js.map +1 -1
- package/dist/production/src/core/factories/createBatchUpdatesOptions.cjs.map +1 -1
- package/dist/production/src/core/factories/createBatchUpdatesOptions.js.map +1 -1
- package/dist/production/src/core/operations/EntityOperations.cjs.map +1 -1
- package/dist/production/src/core/operations/EntityOperations.js.map +1 -1
- package/dist/production/src/core/operations/FieldOperations.cjs.map +1 -1
- package/dist/production/src/core/operations/FieldOperations.js.map +1 -1
- package/dist/production/src/core/operations/ListOperations.cjs.map +1 -1
- package/dist/production/src/core/operations/ListOperations.js.map +1 -1
- package/dist/production/src/core/operations/OperationsHelpers.cjs.map +1 -1
- package/dist/production/src/core/operations/OperationsHelpers.js.map +1 -1
- package/dist/production/src/core/state/StateIterator.cjs.map +1 -1
- package/dist/production/src/core/state/StateIterator.js.map +1 -1
- package/dist/production/src/core/state/getEntityMarker.cjs.map +1 -1
- package/dist/production/src/core/state/getEntityMarker.js.map +1 -1
- package/dist/production/src/fieldHelpers/helpers/TemporalFieldHelper.cjs.map +1 -1
- package/dist/production/src/fieldHelpers/helpers/TemporalFieldHelper.js.map +1 -1
- package/dist/production/src/fieldHelpers/helpers/UuidFieldHelper.cjs.map +1 -1
- package/dist/production/src/fieldHelpers/helpers/UuidFieldHelper.js.map +1 -1
- package/dist/types/accessorTree/index.d.ts +1 -1
- package/dist/types/accessorTree/index.d.ts.map +1 -1
- package/dist/types/accessors/EntityAccessorImpl.d.ts +3 -3
- package/dist/types/accessors/EntityAccessorImpl.d.ts.map +1 -1
- package/dist/types/accessors/EntityListAccessorImpl.d.ts +2 -2
- package/dist/types/accessors/EntityListAccessorImpl.d.ts.map +1 -1
- package/dist/types/accessors/FieldAccessorImpl.d.ts +3 -3
- package/dist/types/accessors/FieldAccessorImpl.d.ts.map +1 -1
- package/dist/types/accessors/index.d.ts +4 -4
- package/dist/types/accessors/index.d.ts.map +1 -1
- package/dist/types/core/AccessorErrorManager.d.ts +4 -4
- package/dist/types/core/AccessorErrorManager.d.ts.map +1 -1
- package/dist/types/core/Config.d.ts +1 -1
- package/dist/types/core/Config.d.ts.map +1 -1
- package/dist/types/core/DataBinding.d.ts +1 -1
- package/dist/types/core/DataBinding.d.ts.map +1 -1
- package/dist/types/core/ErrorsPreprocessor.d.ts +1 -1
- package/dist/types/core/ErrorsPreprocessor.d.ts.map +1 -1
- package/dist/types/core/EventManager.d.ts +5 -5
- package/dist/types/core/EventManager.d.ts.map +1 -1
- package/dist/types/core/MutationGenerator.d.ts +1 -1
- package/dist/types/core/MutationGenerator.d.ts.map +1 -1
- package/dist/types/core/RealmKeyGenerator.d.ts +1 -1
- package/dist/types/core/RealmKeyGenerator.d.ts.map +1 -1
- package/dist/types/core/RequestResponseNormalizer.d.ts +2 -2
- package/dist/types/core/RequestResponseNormalizer.d.ts.map +1 -1
- package/dist/types/core/StateInitializer.d.ts +4 -4
- package/dist/types/core/StateInitializer.d.ts.map +1 -1
- package/dist/types/core/TreeAugmenter.d.ts +4 -4
- package/dist/types/core/TreeAugmenter.d.ts.map +1 -1
- package/dist/types/core/TreeStore.d.ts +3 -3
- package/dist/types/core/TreeStore.d.ts.map +1 -1
- package/dist/types/core/exceptions/ErrorLocator.d.ts +1 -1
- package/dist/types/core/exceptions/ErrorLocator.d.ts.map +1 -1
- package/dist/types/core/factories/createBatchUpdatesOptions.d.ts +1 -1
- package/dist/types/core/factories/createBatchUpdatesOptions.d.ts.map +1 -1
- package/dist/types/core/factories/index.d.ts +1 -1
- package/dist/types/core/factories/index.d.ts.map +1 -1
- package/dist/types/core/index.d.ts +8 -8
- package/dist/types/core/index.d.ts.map +1 -1
- package/dist/types/core/operations/EntityOperations.d.ts +5 -5
- package/dist/types/core/operations/EntityOperations.d.ts.map +1 -1
- package/dist/types/core/operations/FieldOperations.d.ts +5 -5
- package/dist/types/core/operations/FieldOperations.d.ts.map +1 -1
- package/dist/types/core/operations/ListOperations.d.ts +5 -5
- package/dist/types/core/operations/ListOperations.d.ts.map +1 -1
- package/dist/types/core/operations/OperationsHelpers.d.ts +4 -4
- package/dist/types/core/operations/OperationsHelpers.d.ts.map +1 -1
- package/dist/types/core/operations/index.d.ts +3 -3
- package/dist/types/core/operations/index.d.ts.map +1 -1
- package/dist/types/core/requestAliases/index.d.ts +1 -1
- package/dist/types/core/requestAliases/index.d.ts.map +1 -1
- package/dist/types/core/state/EntityListState.d.ts +1 -1
- package/dist/types/core/state/EntityListState.d.ts.map +1 -1
- package/dist/types/core/state/EntityRealmState.d.ts +3 -3
- package/dist/types/core/state/EntityRealmState.d.ts.map +1 -1
- package/dist/types/core/state/EntityState.d.ts +1 -1
- package/dist/types/core/state/EntityState.d.ts.map +1 -1
- package/dist/types/core/state/FieldState.d.ts +1 -1
- package/dist/types/core/state/FieldState.d.ts.map +1 -1
- package/dist/types/core/state/StateIterator.d.ts +5 -5
- package/dist/types/core/state/StateIterator.d.ts.map +1 -1
- package/dist/types/core/state/StateNode.d.ts +3 -3
- package/dist/types/core/state/StateNode.d.ts.map +1 -1
- package/dist/types/core/state/getEntityMarker.d.ts +1 -1
- package/dist/types/core/state/getEntityMarker.d.ts.map +1 -1
- package/dist/types/core/state/index.d.ts +7 -7
- package/dist/types/core/state/index.d.ts.map +1 -1
- package/dist/types/core/utils/index.d.ts +1 -1
- package/dist/types/core/utils/index.d.ts.map +1 -1
- package/dist/types/fieldHelpers/helpers/TemporalFieldHelper.d.ts +1 -1
- package/dist/types/fieldHelpers/helpers/TemporalFieldHelper.d.ts.map +1 -1
- package/dist/types/fieldHelpers/helpers/UuidFieldHelper.d.ts +1 -1
- package/dist/types/fieldHelpers/helpers/UuidFieldHelper.d.ts.map +1 -1
- package/dist/types/fieldHelpers/helpers/index.d.ts +2 -2
- package/dist/types/fieldHelpers/helpers/index.d.ts.map +1 -1
- package/dist/types/fieldHelpers/index.d.ts +1 -1
- package/dist/types/fieldHelpers/index.d.ts.map +1 -1
- package/dist/types/index.d.ts +3 -3
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/utils/index.d.ts +3 -3
- package/dist/types/utils/index.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/accessorTree/index.ts +1 -1
- package/src/accessors/EntityAccessorImpl.ts +3 -3
- package/src/accessors/EntityListAccessorImpl.ts +2 -2
- package/src/accessors/FieldAccessorImpl.ts +3 -3
- package/src/accessors/index.ts +4 -4
- package/src/core/AccessorErrorManager.ts +5 -5
- package/src/core/Config.ts +1 -1
- package/src/core/DataBinding.ts +14 -14
- package/src/core/ErrorsPreprocessor.ts +2 -2
- package/src/core/EventManager.ts +5 -5
- package/src/core/MutationGenerator.ts +6 -6
- package/src/core/RealmKeyGenerator.ts +1 -1
- package/src/core/RequestResponseNormalizer.ts +2 -2
- package/src/core/StateInitializer.ts +8 -8
- package/src/core/TreeAugmenter.ts +7 -7
- package/src/core/TreeStore.ts +4 -4
- package/src/core/exceptions/ErrorLocator.ts +3 -3
- package/src/core/exceptions/MarkerSugarer.ts +1 -1
- package/src/core/factories/createBatchUpdatesOptions.ts +1 -1
- package/src/core/factories/index.ts +1 -1
- package/src/core/index.ts +8 -8
- package/src/core/operations/EntityOperations.ts +7 -7
- package/src/core/operations/FieldOperations.ts +6 -6
- package/src/core/operations/ListOperations.ts +8 -8
- package/src/core/operations/OperationsHelpers.ts +5 -5
- package/src/core/operations/index.ts +3 -3
- package/src/core/requestAliases/index.ts +1 -1
- package/src/core/state/EntityListState.ts +1 -1
- package/src/core/state/EntityRealmState.ts +3 -3
- package/src/core/state/EntityState.ts +1 -1
- package/src/core/state/FieldState.ts +1 -1
- package/src/core/state/StateIterator.ts +6 -6
- package/src/core/state/StateNode.ts +3 -3
- package/src/core/state/getEntityMarker.ts +1 -1
- package/src/core/state/index.ts +7 -7
- package/src/core/utils/index.ts +1 -1
- package/src/fieldHelpers/helpers/TemporalFieldHelper.ts +1 -1
- package/src/fieldHelpers/helpers/UuidFieldHelper.ts +1 -1
- package/src/fieldHelpers/helpers/index.ts +2 -2
- package/src/fieldHelpers/index.ts +1 -1
- package/src/index.ts +3 -3
- package/src/utils/index.ts +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataBinding.js","sources":["../../../../../packages/binding-legacy/src/core/DataBinding.ts"],"sourcesContent":["import { ContentClient, ContentQueryBuilder, GraphQlClient, GraphQlClientError } from '@contember/client'\nimport type {\n\tDataBindingEventListenerMap,\n\tDataBindingTransactionResult,\n\tEntityId,\n\tEnvironment,\n\tMarkerTreeRoot,\n\tTreeRootId,\n} from '@contember/binding-common'\nimport {\n\tassertNever,\n\tAsyncBatchUpdatesOptions,\n\tBatchUpdatesOptions,\n\tBindingOperations,\n\tErrorPersistResult,\n\tEventListenersStore,\n\tExtendTreeOptions,\n\tMarkerMerger,\n\tPersistOptions,\n\tPersistSuccessOptions,\n\tReceivedDataTree,\n\tSuccessfulPersistResult,\n\tTreeRootAccessor,\n} from '@contember/binding-common'\nimport { generateEnumerabilityPreventingEntropy } from '../utils'\nimport { AccessorErrorManager } from './AccessorErrorManager'\nimport { Config } from './Config'\nimport { DirtinessTracker } from './DirtinessTracker'\nimport { EventManager } from './EventManager'\nimport { createBatchUpdatesOptions } from './factories'\nimport { MutationGenerator, SubMutationOperation } from './MutationGenerator'\nimport { QueryGenerator } from './QueryGenerator'\nimport { StateIterator } from './state'\nimport { StateInitializer } from './StateInitializer'\nimport { TreeAugmenter } from './TreeAugmenter'\nimport { TreeStore } from './TreeStore'\nimport type { UpdateMetadata } from './UpdateMetadata'\nimport { getCombinedSignal } from './utils'\nimport { createQueryBuilder } from '@contember/binding-common'\nimport { DataBindingExtendAborted } from '@contember/binding-common'\n\nexport class DataBinding<Node> {\n\tprivate readonly accessorErrorManager: AccessorErrorManager\n\tprivate readonly batchUpdatesOptions: BatchUpdatesOptions\n\tprivate readonly asyncBatchUpdatesOptions: AsyncBatchUpdatesOptions\n\tprivate readonly bindingOperations: BindingOperations<Node>\n\tprivate readonly config: Config\n\tprivate readonly dirtinessTracker: DirtinessTracker\n\tprivate readonly eventManager: EventManager\n\tprivate readonly stateInitializer: StateInitializer\n\tprivate readonly treeAugmenter: TreeAugmenter\n\tprivate readonly queryBuilder: ContentQueryBuilder\n\tprivate readonly contentClient: ContentClient\n\tprivate readonly eventListenerStore = new EventListenersStore<DataBindingEventListenerMap>()\n\n\t// private treeRootListeners: {\n\t// \teventListeners: {}\n\t// } = {\n\t// \teventListeners: {},\n\t// }\n\n\tpublic constructor(\n\t\tprivate readonly contentApiClient: GraphQlClient,\n\t\tprivate readonly systemApiClient: GraphQlClient,\n\t\tprivate readonly tenantApiClient: GraphQlClient,\n\t\tprivate readonly treeStore: TreeStore,\n\t\tprivate readonly environment: Environment,\n\t\tprivate readonly createMarkerTree: (node: Node, environment: Environment) => MarkerTreeRoot,\n\t\tprivate readonly batchedUpdates: (callback: () => any) => void,\n\t\tprivate readonly onUpdate: (newData: TreeRootAccessor<Node>, binding: DataBinding<Node>) => void,\n\t\tprivate readonly onError: (error: GraphQlClientError, binding: DataBinding<Node>) => void,\n\t\tprivate readonly onPersistSuccess: (result: SuccessfulPersistResult, binding: DataBinding<Node>) => void,\n\t\tprivate readonly options: {\n\t\t\tskipStateUpdateAfterPersist: boolean\n\t\t},\n\t) {\n\t\tthis.config = new Config()\n\t\tthis.batchUpdatesOptions = createBatchUpdatesOptions(environment, this.treeStore)\n\t\tthis.asyncBatchUpdatesOptions = {\n\t\t\t...this.batchUpdatesOptions,\n\t\t\tcontentClient: contentApiClient,\n\t\t\tsystemClient: systemApiClient,\n\t\t\ttenantClient: tenantApiClient,\n\t\t}\n\t\tthis.dirtinessTracker = new DirtinessTracker()\n\t\tthis.eventManager = new EventManager(\n\t\t\tthis.asyncBatchUpdatesOptions,\n\t\t\tthis.batchUpdatesOptions,\n\t\t\tthis.config,\n\t\t\tthis.dirtinessTracker,\n\t\t\tthis.resolvedOnUpdate,\n\t\t\tthis.treeStore,\n\t\t\tthis.batchedUpdates,\n\t\t)\n\t\tthis.accessorErrorManager = new AccessorErrorManager(this.eventManager, this.treeStore)\n\t\tthis.stateInitializer = new StateInitializer(\n\t\t\tthis.accessorErrorManager,\n\t\t\tthis.batchUpdatesOptions,\n\t\t\tthis.eventManager,\n\t\t\tthis.treeStore,\n\t\t)\n\t\tthis.treeAugmenter = new TreeAugmenter(this.eventManager, this.stateInitializer, this.treeStore, options.skipStateUpdateAfterPersist)\n\n\t\t// TODO move this elsewhere\n\t\tthis.bindingOperations = Object.freeze<BindingOperations<Node>>({\n\t\t\t...this.asyncBatchUpdatesOptions,\n\t\t\taddEventListener: (type, listener) => this.eventListenerStore.add({ type }, listener),\n\t\t\tbatchDeferredUpdates: performUpdates => {\n\t\t\t\tthis.eventManager.syncTransaction(() => performUpdates(this.bindingOperations))\n\t\t\t},\n\t\t\textendTree: async (...args) => await this.extendTree(...args),\n\t\t\tpersist: async options => await this.persist(options),\n\t\t\tfetchData: async (...args) => await this.fetchData(...args),\n\t\t})\n\t\tthis.queryBuilder = createQueryBuilder(this.environment.getSchema())\n\t\tthis.contentClient = new ContentClient(contentApiClient)\n\t}\n\n\tprivate async persist({ onPersistError, onPersistSuccess, signal }: PersistOptions = {}) {\n\t\treturn await this.eventManager.persistOperation(async () => {\n\t\t\t// TODO if the tree is in an inconsistent state, wait for lock releases\n\n\t\t\tthis.eventManager.syncTransaction(() => {\n\t\t\t\tthis.accessorErrorManager.clearErrors()\n\t\t\t})\n\t\t\tawait this.eventManager.triggerOnBeforePersist()\n\n\t\t\tawait this.checkErrorsBeforePersist(onPersistError)\n\n\t\t\tconst mutationResult = MutationGenerator.getPersistMutation(this.treeStore, this.queryBuilder)\n\n\t\t\tif (mutationResult.operations.length === 0) {\n\t\t\t\treturn await this.processEmptyPersistMutation(onPersistSuccess)\n\t\t\t}\n\n\t\t\tconst { mutations, operations } = mutationResult\n\n\t\t\tlet response: DataBindingTransactionResult\n\t\t\ttry {\n\t\t\t\tresponse = await this.contentClient.mutate(\n\t\t\t\t\tthis.queryBuilder.transaction(mutations, {\n\t\t\t\t\t\tdeferForeignKeyConstraints: true,\n\t\t\t\t\t}),\n\t\t\t\t\t{\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tonBeforeRequest: ({ query, variables }) => {\n\t\t\t\t\t\t\tconsole.debug(query, variables)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof GraphQlClientError) {\n\t\t\t\t\tthis.onError(e, this)\n\t\t\t\t\tthrow await this.persistFail({\n\t\t\t\t\t\terrors: [e],\n\t\t\t\t\t\ttype: 'invalidResponse',\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tthrow e\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (response.ok && Object.values(response.data).every(it => it.ok)) {\n\t\t\t\treturn await this.processSuccessfulPersistResult(response, operations, onPersistSuccess)\n\t\t\t} else {\n\t\t\t\tif (response.errorMessage) {\n\t\t\t\t\tconsole.debug(response.errorMessage)\n\t\t\t\t}\n\n\t\t\t\tthis.eventManager.syncTransaction(() => this.accessorErrorManager.replaceErrors(response, operations))\n\n\t\t\t\tawait this.eventManager.triggerOnPersistError(this.bindingOperations)\n\t\t\t\tawait onPersistError?.(this.bindingOperations)\n\t\t\t\tthrow await this.persistFail({\n\t\t\t\t\terrors: this.accessorErrorManager.getErrors(),\n\t\t\t\t\ttype: 'invalidInput',\n\t\t\t\t\tresponse,\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate async checkErrorsBeforePersist(onPersistError: PersistOptions['onPersistError']) {\n\t\tif (this.accessorErrorManager.hasErrors()) {\n\t\t\tawait this.eventManager.triggerOnPersistError(this.bindingOperations)\n\t\t\tawait onPersistError?.(this.bindingOperations)\n\t\t\tthrow await this.persistFail({\n\t\t\t\terrors: this.accessorErrorManager.getErrors(),\n\t\t\t\ttype: 'invalidInput',\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async processEmptyPersistMutation(onPersistSuccess: PersistOptions['onPersistSuccess']): Promise<SuccessfulPersistResult> {\n\t\tthis.dirtinessTracker.reset() // TODO This ideally shouldn't be necessary but given the current limitations, this makes for better UX.\n\t\tconst persistSuccessOptions: PersistSuccessOptions = {\n\t\t\t...this.bindingOperations,\n\t\t\tsuccessType: 'nothingToPersist',\n\t\t}\n\t\tawait this.eventManager.triggerOnPersistSuccess(persistSuccessOptions)\n\t\tawait onPersistSuccess?.(persistSuccessOptions)\n\t\tconst result: SuccessfulPersistResult = { type: 'nothingToPersist' }\n\t\tawait this.eventListenerStore.invoke({ type: 'persistSuccess' }, result)\n\t\treturn result\n\t}\n\n\tprivate async processSuccessfulPersistResult(\n\t\tmutationData: DataBindingTransactionResult,\n\t\toperations: SubMutationOperation[],\n\t\tonPersistSuccess: PersistOptions['onPersistSuccess'],\n\t) {\n\t\tconst persistedEntityIds = Object.values(mutationData.data).map(it => it.node?.id).filter((id): id is EntityId => id !== undefined)\n\t\tconst result: SuccessfulPersistResult = {\n\t\t\ttype: 'justSuccess',\n\t\t\tpersistedEntityIds,\n\t\t}\n\n\t\ttry {\n\t\t\tawait this.eventManager.asyncTransaction(async () => {\n\t\t\t\tthis.resetTreeAfterSuccessfulPersist()\n\t\t\t\tthis.treeAugmenter.updatePersistedData(\n\t\t\t\t\tObject.fromEntries(\n\t\t\t\t\t\tObject.entries(mutationData.data).map(([placeholderName, subTreeResponse]) => [\n\t\t\t\t\t\t\tplaceholderName,\n\t\t\t\t\t\t\tsubTreeResponse.node,\n\t\t\t\t\t\t]),\n\t\t\t\t\t),\n\t\t\t\t\toperations,\n\t\t\t\t)\n\t\t\t\tconst persistSuccessOptions: PersistSuccessOptions = {\n\t\t\t\t\t...this.bindingOperations,\n\t\t\t\t\tsuccessType: result.type,\n\t\t\t\t}\n\t\t\t\tawait this.eventManager.triggerOnPersistSuccess(persistSuccessOptions)\n\t\t\t\tawait onPersistSuccess?.(persistSuccessOptions)\n\t\t\t\tawait this.eventListenerStore.invoke({ type: 'persistSuccess' }, result)\n\n\t\t\t\tthis.treeAugmenter.resetCreatingSubTrees()\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tconsole.error(e)\n\t\t\tconst resultWithError = {\n\t\t\t\t...result,\n\t\t\t\tafterPersistError: e,\n\t\t\t}\n\t\t\tthis.onPersistSuccess(resultWithError, this)\n\t\t\treturn resultWithError\n\t\t}\n\t\tthis.onPersistSuccess(result, this)\n\t\treturn result\n\t}\n\n\tprivate async persistFail(error: ErrorPersistResult): Promise<ErrorPersistResult> {\n\t\tawait this.eventListenerStore.invoke({ type: 'persistError' }, error)\n\t\treturn error\n\t}\n\n\tprivate resolvedOnUpdate = ({ isMutating }: UpdateMetadata) => {\n\t\tthis.onUpdate(new TreeRootAccessor<Node>(this.dirtinessTracker.hasChanges(), isMutating, this.bindingOperations), this)\n\t}\n\n\t// This is currently useless but potentially future-compatible\n\t// private readonly addTreeRootEventListener: TreeRootAccessor.AddTreeRootEventListener = this.getAddEventListener(\n\t// \tthis.treeRootListeners,\n\t// )\n\n\tprivate pendingExtensions: Set<{\n\t\tmarkerTreeRoot: MarkerTreeRoot\n\t\tnewFragment: Node\n\t\tnewTreeRootId: TreeRootId | undefined\n\t\toptions: ExtendTreeOptions\n\t\tonError?: (error: Error) => void\n\t}> = new Set()\n\n\tprivate flushResult: Promise<boolean> | undefined\n\n\tpublic async extendTree(newFragment: Node, options: ExtendTreeOptions = {}): Promise<TreeRootId | undefined> {\n\t\tif (options.signal?.aborted) {\n\t\t\treturn Promise.reject(DataBindingExtendAborted)\n\t\t}\n\t\tconst markerTreeRoot = this.createMarkerTree(newFragment, options.environment ?? this.environment)\n\n\t\tif (!options.force && this.treeStore.effectivelyHasTreeRoot(markerTreeRoot)) {\n\t\t\t// This isn't perfectly accurate as theoretically, we could already have all the data necessary but this\n\t\t\t// could still be false.\n\n\t\t\treturn this.eventManager.syncOperation(() => {\n\t\t\t\tconst newTreeRootId = this.getNewTreeRootId()\n\t\t\t\tthis.treeAugmenter.extendTreeStates(newTreeRootId, markerTreeRoot)\n\t\t\t\treturn newTreeRootId\n\t\t\t})\n\t\t}\n\n\t\treturn await new Promise(async (resolve, reject) => {\n\t\t\tconst treeRootId = this.getNewTreeRootId()\n\t\t\tthis.pendingExtensions.add({\n\t\t\t\tmarkerTreeRoot,\n\t\t\t\tnewFragment,\n\t\t\t\tnewTreeRootId: treeRootId,\n\t\t\t\toptions,\n\t\t\t\tonError: options.onError,\n\t\t\t})\n\t\t\tthis.flushResult ??= (async () => {\n\t\t\t\tawait Promise.resolve()\n\t\t\t\tthis.flushResult = undefined\n\t\t\t\treturn await this.flushBatchedTreeExtensions()\n\t\t\t})()\n\n\t\t\tif (!(await this.flushResult) || options.signal?.aborted) {\n\t\t\t\treturn reject(DataBindingExtendAborted)\n\t\t\t}\n\n\t\t\tresolve(treeRootId)\n\t\t})\n\t}\n\n\tpublic async fetchData(fragment: Node, options?: { signal?: AbortSignal; environment?: Environment }): Promise<{\n\t\tdata: ReceivedDataTree\n\t\tmarkerTreeRoot: MarkerTreeRoot\n\t}> {\n\t\tconst markerTreeRoot = this.createMarkerTree(fragment, options?.environment ?? this.environment)\n\t\tconst data = await this.fetchPersistedData(markerTreeRoot, options?.signal)\n\n\t\treturn {\n\t\t\tdata: data,\n\t\t\tmarkerTreeRoot,\n\t\t}\n\t}\n\n\tprivate async flushBatchedTreeExtensions(): Promise<boolean> {\n\t\t// This is an async operation so we just take whatever pendingExtensions there are now and let any new ones\n\t\t// accumulate in an empty set.\n\t\tconst pendingExtensions = Array.from(this.pendingExtensions).filter(extension => {\n\t\t\treturn !extension.options.signal?.aborted\n\t\t})\n\t\tthis.pendingExtensions.clear()\n\n\t\tconst aggregateMarkerTreeRoot = pendingExtensions.reduce<MarkerTreeRoot | undefined>(\n\t\t\t(previousValue, currentValue) => {\n\t\t\t\tif (previousValue === undefined) {\n\t\t\t\t\treturn currentValue.markerTreeRoot\n\t\t\t\t}\n\t\t\t\treturn MarkerMerger.mergeMarkerTreeRoots(previousValue, currentValue.markerTreeRoot)\n\t\t\t},\n\t\t\tundefined,\n\t\t)\n\n\t\tif (aggregateMarkerTreeRoot === undefined) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst aggregateSignal = getCombinedSignal(pendingExtensions.map(extension => extension.options.signal))\n\n\t\tlet aggregatePersistedData: ReceivedDataTree\n\t\ttry {\n\t\t\taggregatePersistedData = await this.fetchPersistedData(aggregateMarkerTreeRoot, aggregateSignal)\n\t\t} catch (e) {\n\t\t\tif (e instanceof GraphQlClientError) {\n\t\t\t\tif (e.type === 'aborted') {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tfor (const extension of pendingExtensions) {\n\t\t\t\t\textension.onError?.(e)\n\t\t\t\t}\n\t\t\t\tif (!pendingExtensions.every(it => !!it.onError)) {\n\t\t\t\t\tthis.onError(e, this)\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t} else {\n\t\t\t\tthrow e\n\t\t\t}\n\t\t}\n\n\t\tif (aggregateSignal?.aborted) {\n\t\t\treturn false\n\t\t}\n\n\t\tthis.eventManager.syncOperation(() => {\n\t\t\tthis.treeAugmenter.extendPersistedData(aggregatePersistedData, aggregateMarkerTreeRoot)\n\n\t\t\tfor (const extension of pendingExtensions) {\n\t\t\t\tthis.treeAugmenter.extendTreeStates(extension.newTreeRootId, extension.markerTreeRoot)\n\t\t\t}\n\t\t})\n\t\treturn true\n\t}\n\n\tprivate async fetchPersistedData(\n\t\ttree: MarkerTreeRoot,\n\t\tsignal?: AbortSignal,\n\t): Promise<ReceivedDataTree> {\n\t\tconst queryGenerator = new QueryGenerator(tree, this.queryBuilder)\n\t\tconst query = queryGenerator.getReadQuery()\n\n\t\treturn await this.contentClient.query(query, {\n\t\t\tsignal,\n\t\t\tonBeforeRequest: ({ query, variables }) => {\n\t\t\t\tconsole.debug(query, variables)\n\t\t\t},\n\t\t})\n\t}\n\n\tprivate resetTreeAfterSuccessfulPersist() {\n\t\tthis.eventManager.syncTransaction(() => {\n\t\t\tthis.accessorErrorManager.clearErrors()\n\t\t\tthis.dirtinessTracker.reset()\n\n\t\t\tfor (const [, rootState] of StateIterator.eachRootState(this.treeStore)) {\n\t\t\t\tfor (const state of StateIterator.depthFirstAllNodes(rootState)) {\n\t\t\t\t\tswitch (state.type) {\n\t\t\t\t\t\tcase 'field': {\n\t\t\t\t\t\t\tif (state.hasUnpersistedChanges || state.touchLog?.size) {\n\t\t\t\t\t\t\t\tstate.touchLog?.clear()\n\t\t\t\t\t\t\t\tstate.hasUnpersistedChanges = false\n\t\t\t\t\t\t\t\tthis.eventManager.registerJustUpdated(state, EventManager.NO_CHANGES_DIFFERENCE)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'entityList':\n\t\t\t\t\t\t\tif (state.unpersistedChangesCount > 0 || state.plannedRemovals?.size) {\n\t\t\t\t\t\t\t\tstate.unpersistedChangesCount = 0\n\t\t\t\t\t\t\t\tstate.plannedRemovals?.clear()\n\t\t\t\t\t\t\t\tthis.eventManager.registerJustUpdated(state, EventManager.NO_CHANGES_DIFFERENCE)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase 'entityRealm': {\n\t\t\t\t\t\t\tif (state.unpersistedChangesCount > 0 || state.plannedHasOneDeletions?.size) {\n\t\t\t\t\t\t\t\tstate.unpersistedChangesCount = 0\n\t\t\t\t\t\t\t\tstate.plannedHasOneDeletions?.clear()\n\t\t\t\t\t\t\t\tthis.eventManager.registerJustUpdated(state, EventManager.NO_CHANGES_DIFFERENCE)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tassertNever(state)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate static getNextTreeRootIdSeed = (() => {\n\t\tlet seed = 1\n\t\treturn () => seed++\n\t})()\n\n\tprivate getNewTreeRootId() {\n\t\t// TODO this is an awful, awful hack.\n\t\t// TODO the particular shape of the alias is relied on in MutationAlias. If you change this, change it there too.\n\t\treturn this.treeStore.markerTrees.size === 0\n\t\t\t? undefined\n\t\t\t: `${generateEnumerabilityPreventingEntropy()}-${DataBinding.getNextTreeRootIdSeed()}`\n\t}\n}\n"],"names":["_DataBinding","options","query"],"mappings":";;;;;;;;;;;;;;;;;AAyCO,MAAM,eAAN,MAAMA,cAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAoBvB,YACW,kBACA,iBACA,iBACA,WACA,aACA,kBACA,gBACA,UACA,SACA,kBACA,SAGhB;AAbgB,SAAA,mB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AC;AAAA,EACF;AAAA,EAOQ,mBAAmB;AAG1B,WAAO,KAAK,UAAU,YAAY,SAAS,IACxC,SACA,GAAG,uCAAA,CAAwC,IAAIF,cAAY,sBAAA,CAAuB;AAAA,EACtF;AACD;AAZC,cAhZY,cAgZG,yBAAyB,uBAAM;AAC7C,MAAI,OAAO;AACX,SAAO,MAAM;AACd,IAAG;AAnZG,IAAM,cAAN;"}
|
|
1
|
+
{"version":3,"file":"DataBinding.js","sources":["../../../../../packages/binding-legacy/src/core/DataBinding.ts"],"sourcesContent":["import { ContentClient, ContentQueryBuilder, GraphQlClient, GraphQlClientError } from '@contember/client'\nimport type {\n\tDataBindingEventListenerMap,\n\tDataBindingTransactionResult,\n\tEntityId,\n\tEnvironment,\n\tMarkerTreeRoot,\n\tTreeRootId,\n} from '@contember/binding-common'\nimport {\n\tassertNever,\n\tAsyncBatchUpdatesOptions,\n\tBatchUpdatesOptions,\n\tBindingOperations,\n\tErrorPersistResult,\n\tEventListenersStore,\n\tExtendTreeOptions,\n\tMarkerMerger,\n\tPersistOptions,\n\tPersistSuccessOptions,\n\tReceivedDataTree,\n\tSuccessfulPersistResult,\n\tTreeRootAccessor,\n} from '@contember/binding-common'\nimport { generateEnumerabilityPreventingEntropy } from '../utils/index.js'\nimport { AccessorErrorManager } from './AccessorErrorManager.js'\nimport { Config } from './Config.js'\nimport { DirtinessTracker } from './DirtinessTracker.js'\nimport { EventManager } from './EventManager.js'\nimport { createBatchUpdatesOptions } from './factories/index.js'\nimport { MutationGenerator, SubMutationOperation } from './MutationGenerator.js'\nimport { QueryGenerator } from './QueryGenerator.js'\nimport { StateIterator } from './state/index.js'\nimport { StateInitializer } from './StateInitializer.js'\nimport { TreeAugmenter } from './TreeAugmenter.js'\nimport { TreeStore } from './TreeStore.js'\nimport type { UpdateMetadata } from './UpdateMetadata.js'\nimport { getCombinedSignal } from './utils/index.js'\nimport { createQueryBuilder } from '@contember/binding-common'\nimport { DataBindingExtendAborted } from '@contember/binding-common'\n\nexport class DataBinding<Node> {\n\tprivate readonly accessorErrorManager: AccessorErrorManager\n\tprivate readonly batchUpdatesOptions: BatchUpdatesOptions\n\tprivate readonly asyncBatchUpdatesOptions: AsyncBatchUpdatesOptions\n\tprivate readonly bindingOperations: BindingOperations<Node>\n\tprivate readonly config: Config\n\tprivate readonly dirtinessTracker: DirtinessTracker\n\tprivate readonly eventManager: EventManager\n\tprivate readonly stateInitializer: StateInitializer\n\tprivate readonly treeAugmenter: TreeAugmenter\n\tprivate readonly queryBuilder: ContentQueryBuilder\n\tprivate readonly contentClient: ContentClient\n\tprivate readonly eventListenerStore = new EventListenersStore<DataBindingEventListenerMap>()\n\n\t// private treeRootListeners: {\n\t// \teventListeners: {}\n\t// } = {\n\t// \teventListeners: {},\n\t// }\n\n\tpublic constructor(\n\t\tprivate readonly contentApiClient: GraphQlClient,\n\t\tprivate readonly systemApiClient: GraphQlClient,\n\t\tprivate readonly tenantApiClient: GraphQlClient,\n\t\tprivate readonly treeStore: TreeStore,\n\t\tprivate readonly environment: Environment,\n\t\tprivate readonly createMarkerTree: (node: Node, environment: Environment) => MarkerTreeRoot,\n\t\tprivate readonly batchedUpdates: (callback: () => any) => void,\n\t\tprivate readonly onUpdate: (newData: TreeRootAccessor<Node>, binding: DataBinding<Node>) => void,\n\t\tprivate readonly onError: (error: GraphQlClientError, binding: DataBinding<Node>) => void,\n\t\tprivate readonly onPersistSuccess: (result: SuccessfulPersistResult, binding: DataBinding<Node>) => void,\n\t\tprivate readonly options: {\n\t\t\tskipStateUpdateAfterPersist: boolean\n\t\t},\n\t) {\n\t\tthis.config = new Config()\n\t\tthis.batchUpdatesOptions = createBatchUpdatesOptions(environment, this.treeStore)\n\t\tthis.asyncBatchUpdatesOptions = {\n\t\t\t...this.batchUpdatesOptions,\n\t\t\tcontentClient: contentApiClient,\n\t\t\tsystemClient: systemApiClient,\n\t\t\ttenantClient: tenantApiClient,\n\t\t}\n\t\tthis.dirtinessTracker = new DirtinessTracker()\n\t\tthis.eventManager = new EventManager(\n\t\t\tthis.asyncBatchUpdatesOptions,\n\t\t\tthis.batchUpdatesOptions,\n\t\t\tthis.config,\n\t\t\tthis.dirtinessTracker,\n\t\t\tthis.resolvedOnUpdate,\n\t\t\tthis.treeStore,\n\t\t\tthis.batchedUpdates,\n\t\t)\n\t\tthis.accessorErrorManager = new AccessorErrorManager(this.eventManager, this.treeStore)\n\t\tthis.stateInitializer = new StateInitializer(\n\t\t\tthis.accessorErrorManager,\n\t\t\tthis.batchUpdatesOptions,\n\t\t\tthis.eventManager,\n\t\t\tthis.treeStore,\n\t\t)\n\t\tthis.treeAugmenter = new TreeAugmenter(this.eventManager, this.stateInitializer, this.treeStore, options.skipStateUpdateAfterPersist)\n\n\t\t// TODO move this elsewhere\n\t\tthis.bindingOperations = Object.freeze<BindingOperations<Node>>({\n\t\t\t...this.asyncBatchUpdatesOptions,\n\t\t\taddEventListener: (type, listener) => this.eventListenerStore.add({ type }, listener),\n\t\t\tbatchDeferredUpdates: performUpdates => {\n\t\t\t\tthis.eventManager.syncTransaction(() => performUpdates(this.bindingOperations))\n\t\t\t},\n\t\t\textendTree: async (...args) => await this.extendTree(...args),\n\t\t\tpersist: async options => await this.persist(options),\n\t\t\tfetchData: async (...args) => await this.fetchData(...args),\n\t\t})\n\t\tthis.queryBuilder = createQueryBuilder(this.environment.getSchema())\n\t\tthis.contentClient = new ContentClient(contentApiClient)\n\t}\n\n\tprivate async persist({ onPersistError, onPersistSuccess, signal }: PersistOptions = {}) {\n\t\treturn await this.eventManager.persistOperation(async () => {\n\t\t\t// TODO if the tree is in an inconsistent state, wait for lock releases\n\n\t\t\tthis.eventManager.syncTransaction(() => {\n\t\t\t\tthis.accessorErrorManager.clearErrors()\n\t\t\t})\n\t\t\tawait this.eventManager.triggerOnBeforePersist()\n\n\t\t\tawait this.checkErrorsBeforePersist(onPersistError)\n\n\t\t\tconst mutationResult = MutationGenerator.getPersistMutation(this.treeStore, this.queryBuilder)\n\n\t\t\tif (mutationResult.operations.length === 0) {\n\t\t\t\treturn await this.processEmptyPersistMutation(onPersistSuccess)\n\t\t\t}\n\n\t\t\tconst { mutations, operations } = mutationResult\n\n\t\t\tlet response: DataBindingTransactionResult\n\t\t\ttry {\n\t\t\t\tresponse = await this.contentClient.mutate(\n\t\t\t\t\tthis.queryBuilder.transaction(mutations, {\n\t\t\t\t\t\tdeferForeignKeyConstraints: true,\n\t\t\t\t\t}),\n\t\t\t\t\t{\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tonBeforeRequest: ({ query, variables }) => {\n\t\t\t\t\t\t\tconsole.debug(query, variables)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof GraphQlClientError) {\n\t\t\t\t\tthis.onError(e, this)\n\t\t\t\t\tthrow await this.persistFail({\n\t\t\t\t\t\terrors: [e],\n\t\t\t\t\t\ttype: 'invalidResponse',\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tthrow e\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (response.ok && Object.values(response.data).every(it => it.ok)) {\n\t\t\t\treturn await this.processSuccessfulPersistResult(response, operations, onPersistSuccess)\n\t\t\t} else {\n\t\t\t\tif (response.errorMessage) {\n\t\t\t\t\tconsole.debug(response.errorMessage)\n\t\t\t\t}\n\n\t\t\t\tthis.eventManager.syncTransaction(() => this.accessorErrorManager.replaceErrors(response, operations))\n\n\t\t\t\tawait this.eventManager.triggerOnPersistError(this.bindingOperations)\n\t\t\t\tawait onPersistError?.(this.bindingOperations)\n\t\t\t\tthrow await this.persistFail({\n\t\t\t\t\terrors: this.accessorErrorManager.getErrors(),\n\t\t\t\t\ttype: 'invalidInput',\n\t\t\t\t\tresponse,\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate async checkErrorsBeforePersist(onPersistError: PersistOptions['onPersistError']) {\n\t\tif (this.accessorErrorManager.hasErrors()) {\n\t\t\tawait this.eventManager.triggerOnPersistError(this.bindingOperations)\n\t\t\tawait onPersistError?.(this.bindingOperations)\n\t\t\tthrow await this.persistFail({\n\t\t\t\terrors: this.accessorErrorManager.getErrors(),\n\t\t\t\ttype: 'invalidInput',\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async processEmptyPersistMutation(onPersistSuccess: PersistOptions['onPersistSuccess']): Promise<SuccessfulPersistResult> {\n\t\tthis.dirtinessTracker.reset() // TODO This ideally shouldn't be necessary but given the current limitations, this makes for better UX.\n\t\tconst persistSuccessOptions: PersistSuccessOptions = {\n\t\t\t...this.bindingOperations,\n\t\t\tsuccessType: 'nothingToPersist',\n\t\t}\n\t\tawait this.eventManager.triggerOnPersistSuccess(persistSuccessOptions)\n\t\tawait onPersistSuccess?.(persistSuccessOptions)\n\t\tconst result: SuccessfulPersistResult = { type: 'nothingToPersist' }\n\t\tawait this.eventListenerStore.invoke({ type: 'persistSuccess' }, result)\n\t\treturn result\n\t}\n\n\tprivate async processSuccessfulPersistResult(\n\t\tmutationData: DataBindingTransactionResult,\n\t\toperations: SubMutationOperation[],\n\t\tonPersistSuccess: PersistOptions['onPersistSuccess'],\n\t) {\n\t\tconst persistedEntityIds = Object.values(mutationData.data).map(it => it.node?.id).filter((id): id is EntityId => id !== undefined)\n\t\tconst result: SuccessfulPersistResult = {\n\t\t\ttype: 'justSuccess',\n\t\t\tpersistedEntityIds,\n\t\t}\n\n\t\ttry {\n\t\t\tawait this.eventManager.asyncTransaction(async () => {\n\t\t\t\tthis.resetTreeAfterSuccessfulPersist()\n\t\t\t\tthis.treeAugmenter.updatePersistedData(\n\t\t\t\t\tObject.fromEntries(\n\t\t\t\t\t\tObject.entries(mutationData.data).map(([placeholderName, subTreeResponse]) => [\n\t\t\t\t\t\t\tplaceholderName,\n\t\t\t\t\t\t\tsubTreeResponse.node,\n\t\t\t\t\t\t]),\n\t\t\t\t\t),\n\t\t\t\t\toperations,\n\t\t\t\t)\n\t\t\t\tconst persistSuccessOptions: PersistSuccessOptions = {\n\t\t\t\t\t...this.bindingOperations,\n\t\t\t\t\tsuccessType: result.type,\n\t\t\t\t}\n\t\t\t\tawait this.eventManager.triggerOnPersistSuccess(persistSuccessOptions)\n\t\t\t\tawait onPersistSuccess?.(persistSuccessOptions)\n\t\t\t\tawait this.eventListenerStore.invoke({ type: 'persistSuccess' }, result)\n\n\t\t\t\tthis.treeAugmenter.resetCreatingSubTrees()\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tconsole.error(e)\n\t\t\tconst resultWithError = {\n\t\t\t\t...result,\n\t\t\t\tafterPersistError: e,\n\t\t\t}\n\t\t\tthis.onPersistSuccess(resultWithError, this)\n\t\t\treturn resultWithError\n\t\t}\n\t\tthis.onPersistSuccess(result, this)\n\t\treturn result\n\t}\n\n\tprivate async persistFail(error: ErrorPersistResult): Promise<ErrorPersistResult> {\n\t\tawait this.eventListenerStore.invoke({ type: 'persistError' }, error)\n\t\treturn error\n\t}\n\n\tprivate resolvedOnUpdate = ({ isMutating }: UpdateMetadata) => {\n\t\tthis.onUpdate(new TreeRootAccessor<Node>(this.dirtinessTracker.hasChanges(), isMutating, this.bindingOperations), this)\n\t}\n\n\t// This is currently useless but potentially future-compatible\n\t// private readonly addTreeRootEventListener: TreeRootAccessor.AddTreeRootEventListener = this.getAddEventListener(\n\t// \tthis.treeRootListeners,\n\t// )\n\n\tprivate pendingExtensions: Set<{\n\t\tmarkerTreeRoot: MarkerTreeRoot\n\t\tnewFragment: Node\n\t\tnewTreeRootId: TreeRootId | undefined\n\t\toptions: ExtendTreeOptions\n\t\tonError?: (error: Error) => void\n\t}> = new Set()\n\n\tprivate flushResult: Promise<boolean> | undefined\n\n\tpublic async extendTree(newFragment: Node, options: ExtendTreeOptions = {}): Promise<TreeRootId | undefined> {\n\t\tif (options.signal?.aborted) {\n\t\t\treturn Promise.reject(DataBindingExtendAborted)\n\t\t}\n\t\tconst markerTreeRoot = this.createMarkerTree(newFragment, options.environment ?? this.environment)\n\n\t\tif (!options.force && this.treeStore.effectivelyHasTreeRoot(markerTreeRoot)) {\n\t\t\t// This isn't perfectly accurate as theoretically, we could already have all the data necessary but this\n\t\t\t// could still be false.\n\n\t\t\treturn this.eventManager.syncOperation(() => {\n\t\t\t\tconst newTreeRootId = this.getNewTreeRootId()\n\t\t\t\tthis.treeAugmenter.extendTreeStates(newTreeRootId, markerTreeRoot)\n\t\t\t\treturn newTreeRootId\n\t\t\t})\n\t\t}\n\n\t\treturn await new Promise(async (resolve, reject) => {\n\t\t\tconst treeRootId = this.getNewTreeRootId()\n\t\t\tthis.pendingExtensions.add({\n\t\t\t\tmarkerTreeRoot,\n\t\t\t\tnewFragment,\n\t\t\t\tnewTreeRootId: treeRootId,\n\t\t\t\toptions,\n\t\t\t\tonError: options.onError,\n\t\t\t})\n\t\t\tthis.flushResult ??= (async () => {\n\t\t\t\tawait Promise.resolve()\n\t\t\t\tthis.flushResult = undefined\n\t\t\t\treturn await this.flushBatchedTreeExtensions()\n\t\t\t})()\n\n\t\t\tif (!(await this.flushResult) || options.signal?.aborted) {\n\t\t\t\treturn reject(DataBindingExtendAborted)\n\t\t\t}\n\n\t\t\tresolve(treeRootId)\n\t\t})\n\t}\n\n\tpublic async fetchData(fragment: Node, options?: { signal?: AbortSignal; environment?: Environment }): Promise<{\n\t\tdata: ReceivedDataTree\n\t\tmarkerTreeRoot: MarkerTreeRoot\n\t}> {\n\t\tconst markerTreeRoot = this.createMarkerTree(fragment, options?.environment ?? this.environment)\n\t\tconst data = await this.fetchPersistedData(markerTreeRoot, options?.signal)\n\n\t\treturn {\n\t\t\tdata: data,\n\t\t\tmarkerTreeRoot,\n\t\t}\n\t}\n\n\tprivate async flushBatchedTreeExtensions(): Promise<boolean> {\n\t\t// This is an async operation so we just take whatever pendingExtensions there are now and let any new ones\n\t\t// accumulate in an empty set.\n\t\tconst pendingExtensions = Array.from(this.pendingExtensions).filter(extension => {\n\t\t\treturn !extension.options.signal?.aborted\n\t\t})\n\t\tthis.pendingExtensions.clear()\n\n\t\tconst aggregateMarkerTreeRoot = pendingExtensions.reduce<MarkerTreeRoot | undefined>(\n\t\t\t(previousValue, currentValue) => {\n\t\t\t\tif (previousValue === undefined) {\n\t\t\t\t\treturn currentValue.markerTreeRoot\n\t\t\t\t}\n\t\t\t\treturn MarkerMerger.mergeMarkerTreeRoots(previousValue, currentValue.markerTreeRoot)\n\t\t\t},\n\t\t\tundefined,\n\t\t)\n\n\t\tif (aggregateMarkerTreeRoot === undefined) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst aggregateSignal = getCombinedSignal(pendingExtensions.map(extension => extension.options.signal))\n\n\t\tlet aggregatePersistedData: ReceivedDataTree\n\t\ttry {\n\t\t\taggregatePersistedData = await this.fetchPersistedData(aggregateMarkerTreeRoot, aggregateSignal)\n\t\t} catch (e) {\n\t\t\tif (e instanceof GraphQlClientError) {\n\t\t\t\tif (e.type === 'aborted') {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tfor (const extension of pendingExtensions) {\n\t\t\t\t\textension.onError?.(e)\n\t\t\t\t}\n\t\t\t\tif (!pendingExtensions.every(it => !!it.onError)) {\n\t\t\t\t\tthis.onError(e, this)\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t} else {\n\t\t\t\tthrow e\n\t\t\t}\n\t\t}\n\n\t\tif (aggregateSignal?.aborted) {\n\t\t\treturn false\n\t\t}\n\n\t\tthis.eventManager.syncOperation(() => {\n\t\t\tthis.treeAugmenter.extendPersistedData(aggregatePersistedData, aggregateMarkerTreeRoot)\n\n\t\t\tfor (const extension of pendingExtensions) {\n\t\t\t\tthis.treeAugmenter.extendTreeStates(extension.newTreeRootId, extension.markerTreeRoot)\n\t\t\t}\n\t\t})\n\t\treturn true\n\t}\n\n\tprivate async fetchPersistedData(\n\t\ttree: MarkerTreeRoot,\n\t\tsignal?: AbortSignal,\n\t): Promise<ReceivedDataTree> {\n\t\tconst queryGenerator = new QueryGenerator(tree, this.queryBuilder)\n\t\tconst query = queryGenerator.getReadQuery()\n\n\t\treturn await this.contentClient.query(query, {\n\t\t\tsignal,\n\t\t\tonBeforeRequest: ({ query, variables }) => {\n\t\t\t\tconsole.debug(query, variables)\n\t\t\t},\n\t\t})\n\t}\n\n\tprivate resetTreeAfterSuccessfulPersist() {\n\t\tthis.eventManager.syncTransaction(() => {\n\t\t\tthis.accessorErrorManager.clearErrors()\n\t\t\tthis.dirtinessTracker.reset()\n\n\t\t\tfor (const [, rootState] of StateIterator.eachRootState(this.treeStore)) {\n\t\t\t\tfor (const state of StateIterator.depthFirstAllNodes(rootState)) {\n\t\t\t\t\tswitch (state.type) {\n\t\t\t\t\t\tcase 'field': {\n\t\t\t\t\t\t\tif (state.hasUnpersistedChanges || state.touchLog?.size) {\n\t\t\t\t\t\t\t\tstate.touchLog?.clear()\n\t\t\t\t\t\t\t\tstate.hasUnpersistedChanges = false\n\t\t\t\t\t\t\t\tthis.eventManager.registerJustUpdated(state, EventManager.NO_CHANGES_DIFFERENCE)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase 'entityList':\n\t\t\t\t\t\t\tif (state.unpersistedChangesCount > 0 || state.plannedRemovals?.size) {\n\t\t\t\t\t\t\t\tstate.unpersistedChangesCount = 0\n\t\t\t\t\t\t\t\tstate.plannedRemovals?.clear()\n\t\t\t\t\t\t\t\tthis.eventManager.registerJustUpdated(state, EventManager.NO_CHANGES_DIFFERENCE)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase 'entityRealm': {\n\t\t\t\t\t\t\tif (state.unpersistedChangesCount > 0 || state.plannedHasOneDeletions?.size) {\n\t\t\t\t\t\t\t\tstate.unpersistedChangesCount = 0\n\t\t\t\t\t\t\t\tstate.plannedHasOneDeletions?.clear()\n\t\t\t\t\t\t\t\tthis.eventManager.registerJustUpdated(state, EventManager.NO_CHANGES_DIFFERENCE)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tassertNever(state)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate static getNextTreeRootIdSeed = (() => {\n\t\tlet seed = 1\n\t\treturn () => seed++\n\t})()\n\n\tprivate getNewTreeRootId() {\n\t\t// TODO this is an awful, awful hack.\n\t\t// TODO the particular shape of the alias is relied on in MutationAlias. If you change this, change it there too.\n\t\treturn this.treeStore.markerTrees.size === 0\n\t\t\t? undefined\n\t\t\t: `${generateEnumerabilityPreventingEntropy()}-${DataBinding.getNextTreeRootIdSeed()}`\n\t}\n}\n"],"names":["_DataBinding","options","query"],"mappings":";;;;;;;;;;;;;;;;;AAyCO,MAAM,eAAN,MAAMA,cAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAoBvB,YACW,kBACA,iBACA,iBACA,WACA,aACA,kBACA,gBACA,UACA,SACA,kBACA,SAGhB;AAbgB,SAAA,mBAAA;AACA,SAAA,kBAAA;AACA,SAAA,kBAAA;AACA,SAAA,YAAA;AACA,SAAA,cAAA;AACA,SAAA,mBAAA;AACA,SAAA,iBAAA;AACA,SAAA,WAAA;AACA,SAAA,UAAA;AACA,SAAA,mBAAA;AACA,SAAA,UAAA;AA9BlB,kBAAA,MAAiB,sBAAA;AACjB,kBAAA,MAAiB,qBAAA;AACjB,kBAAA,MAAiB,0BAAA;AACjB,kBAAA,MAAiB,mBAAA;AACjB,kBAAA,MAAiB,QAAA;AACjB,kBAAA,MAAiB,kBAAA;AACjB,kBAAA,MAAiB,cAAA;AACjB,kBAAA,MAAiB,kBAAA;AACjB,kBAAA,MAAiB,eAAA;AACjB,kBAAA,MAAiB,cAAA;AACjB,kBAAA,MAAiB,eAAA;AACjB,kBAAA,MAAiB,sBAAqB,IAAI,oBAAA,CAAiD;AA4M3F,kBAAA,MAAQ,oBAAmB,CAAC,EAAE,WAAA,MAAiC;AAC9D,WAAK,SA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BAAI,MAAM,yBAAyB,MAAM,UAAU,MAAM;AACxD,sBAAM,UAAU,MAAA;AAChB,sBAAM,wBAAwB;AAC9B,qBAAK,aAAa,oBAAoB,OAAO,aAAa,qBAAqB;AAAA,cAChF;AACA;AAAA,YACD;AAAA,YACA,KAAK;AACJ,kBAAI,MAAM,0BAA0B,KAAK,MAAM,iBAAiB,MAAM;AACrE,sBAAM,0BAA0B;AAChC,sBAAM,iBAAiB,MAAA;AACvB,qBAAK,aAAa,oBAAoB,OAAO,aAAa,qBAAqB;AAAA,cAChF;AACA;AAAA,YACD,KAAK,eAAe;AACnB,kBAAI,MAAM,0BAA0B,KAAK,MAAM,wBAAwB,MAAM;AAC5E,sBAAM,0BAA0B;AAChC,sBAAM,wBAAwB,MAAA;AAC9B,qBAAK,aAAa,oBAAoB,OAAO,aAAa,qBAAqB;AAAA,cAChF;AACA;AAAA,YACD;AAAA,YACA;AACC,0BAAY,KAAK;AAAA,UAAA;AAAA,QAEpB;AAAA,MACD;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAOQ,mBAAmB;AAG1B,WAAO,KAAK,UAAU,YAAY,SAAS,IACxC,SACA,GAAG,uCAAA,CAAwC,IAAIF,cAAY,sBAAA,CAAuB;AAAA,EACtF;AACD;AAZC,cAhZY,cAgZG,yBAAyB,uBAAM;AAC7C,MAAI,OAAO;AACX,SAAO,MAAM;AACd,IAAG;AAnZG,IAAM,cAAN;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ErrorsPreprocessor.cjs","sources":["../../../../../packages/binding-legacy/src/core/ErrorsPreprocessor.ts"],"sourcesContent":["import type { EntityId, ErrorAccessor, FieldName, PlaceholderName } from '@contember/binding-common'\nimport { DataBindingTransactionResult } from '@contember/binding-common'\nimport { assertNever } from '@contember/binding-common'\nimport { MutationAlias } from './requestAliases'\nimport { SubMutationOperation } from './MutationGenerator'\nimport { MutationError, MutationResult, ValidationError } from '@contember/client'\n\nclass ErrorsPreprocessor {\n\tpublic constructor(\n\t\tprivate readonly requestResponse: DataBindingTransactionResult,\n\t\tprivate readonly operations: SubMutationOperation[],\n\t) {}\n\n\tpublic preprocess(): ErrorsPreprocessor.ErrorTreeRoot {\n\t\tconst treeRoot: ErrorsPreprocessor.ErrorTreeRoot = new Map()\n\n\t\tif (this.requestResponse === undefined) {\n\t\t\treturn treeRoot\n\t\t}\n\n\t\tfor (const operation of this.operations) {\n\t\t\tconst mutationResponse = this.requestResponse.data[operation.alias]\n\t\t\tconst processedResponse = this.processMutationResponse(mutationResponse)\n\n\t\t\tif (processedResponse === undefined) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst { subTreeType, subTreePlaceholder, id } = operation\n\n\t\t\tif (subTreeType === 'single') {\n\t\t\t\tif (treeRoot.has(subTreePlaceholder)) {\n\t\t\t\t\treturn this.rejectCorruptData()\n\t\t\t\t}\n\t\t\t\ttreeRoot.set(subTreePlaceholder, processedResponse)\n\t\t\t} else if (subTreeType === 'list') {\n\t\t\t\tconst child = treeRoot.get(subTreePlaceholder)\n\n\t\t\t\tif (child === undefined) {\n\t\t\t\t\ttreeRoot.set(subTreePlaceholder, {\n\t\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\t\tchildren: new Map([[id, processedResponse]]),\n\t\t\t\t\t\tvalidation: [],\n\t\t\t\t\t\texecution: [],\n\t\t\t\t\t})\n\t\t\t\t} else if (child.nodeType === 'iNode') {\n\t\t\t\t\tchild.children.set(id, processedResponse)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn assertNever(subTreeType)\n\t\t\t}\n\t\t}\n\t\treturn treeRoot\n\t}\n\n\tprivate processMutationResponse(mutationResponse: MutationResult): ErrorsPreprocessor.ErrorNode | undefined {\n\t\tif (mutationResponse.ok && mutationResponse.validation?.valid && mutationResponse.errors.length === 0) {\n\t\t\treturn undefined\n\t\t}\n\t\tif (mutationResponse.validation?.errors.length) {\n\t\t\treturn this.getErrorNode(mutationResponse.validation?.errors)\n\t\t}\n\t\tif (mutationResponse.errors.length) {\n\t\t\treturn this.getErrorNode(mutationResponse.errors)\n\t\t}\n\t\treturn undefined\n\t}\n\n\tprivate getErrorNode(errors: ValidationError[] | MutationError[]): ErrorsPreprocessor.ErrorNode {\n\t\tconst [head, ...tail] = errors\n\n\t\tlet rootNode = this.getRootNode(head)\n\n\t\terrorLoop: for (const error of tail) {\n\t\t\tlet currentNode = rootNode\n\n\t\t\tconst path = 'paths' in error ? (error.paths[0] ?? []) : error.path\n\n\t\t\tfor (let i = 0, pathLength = path.length; i < pathLength; i++) {\n\t\t\t\tconst pathNode = path[i]\n\n\t\t\t\tif (currentNode.nodeType === 'leaf') {\n\t\t\t\t\t;(currentNode as any as ErrorsPreprocessor.ErrorINode).nodeType = 'iNode'\n\t\t\t\t\t;(currentNode as any as ErrorsPreprocessor.ErrorINode).children = new Map()\n\t\t\t\t}\n\n\t\t\t\tif ('field' in pathNode) {\n\t\t\t\t\tif (currentNode.nodeType === 'iNode') {\n\t\t\t\t\t\tlet alias = pathNode.field\n\t\t\t\t\t\tlet nextIndex = i + 1\n\t\t\t\t\t\tif (nextIndex in path) {\n\t\t\t\t\t\t\tconst nextPathNode = path[nextIndex]\n\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t'index' in nextPathNode\n\t\t\t\t\t\t\t\t&& typeof nextPathNode.alias === 'string'\n\t\t\t\t\t\t\t\t&& nextPathNode.alias.startsWith(pathNode.field)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t// We're dealing with a reduced hasMany relation.\n\t\t\t\t\t\t\t\ti++\n\t\t\t\t\t\t\t\tnextIndex++\n\t\t\t\t\t\t\t\talias = nextPathNode.alias\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!currentNode.children.has(alias)) {\n\t\t\t\t\t\t\tcurrentNode.children.set(alias, this.getRootNode(error, nextIndex))\n\t\t\t\t\t\t\tif (nextIndex <= path.length) {\n\t\t\t\t\t\t\t\t// This path has been handled by getRootNode\n\t\t\t\t\t\t\t\tcontinue errorLoop\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentNode = currentNode.children.get(alias)!\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.rejectCorruptData()\n\t\t\t\t\t}\n\t\t\t\t} else if ('index' in path) {\n\t\t\t\t\tif (currentNode.nodeType === 'iNode') {\n\t\t\t\t\t\tconst alias = pathNode.alias\n\n\t\t\t\t\t\tif (alias === null) {\n\t\t\t\t\t\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t\t\t\t\t\t`Corrupt data: undefined alias for node with index ${pathNode.index}.`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst entityId = MutationAlias.decodeEntityId(alias)\n\n\t\t\t\t\t\tif (!currentNode.children.has(entityId)) {\n\t\t\t\t\t\t\tcurrentNode.children.set(entityId, this.getRootNode(error, i + 1))\n\t\t\t\t\t\t\tif (i + 1 <= path.length) {\n\t\t\t\t\t\t\t\t// This path has been handled by getRootNode\n\t\t\t\t\t\t\t\tcontinue errorLoop\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentNode = currentNode.children.get(entityId)!\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.rejectCorruptData()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.isExecutionError(error)) {\n\t\t\t\tcurrentNode.execution.push({ type: 'execution', code: error.type, developerMessage: error.message })\n\t\t\t} else {\n\t\t\t\tcurrentNode.validation.push(this.createValidationError(error.message.text))\n\t\t\t}\n\t\t}\n\n\t\treturn rootNode\n\t}\n\n\tprivate getRootNode(error: ValidationError | MutationError, startIndex: number = 0): ErrorsPreprocessor.ErrorNode {\n\t\tlet rootNode: ErrorsPreprocessor.ErrorNode = {\n\t\t\tvalidation: this.isExecutionError(error) ? [] : [this.createValidationError(error.message.text)],\n\t\t\texecution: this.isExecutionError(error) ? [{ type: 'execution', code: error.type, developerMessage: error.message }] : [],\n\t\t\tnodeType: 'leaf',\n\t\t}\n\t\tconst path = 'paths' in error ? (error.paths[0] ?? []) : error.path\n\t\tfor (let i = path.length - 1; i >= startIndex; i--) {\n\t\t\tconst pathNode = path[i]\n\t\t\tif ('field' in pathNode) {\n\t\t\t\trootNode = {\n\t\t\t\t\tvalidation: [],\n\t\t\t\t\texecution: [],\n\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\tchildren: new Map([[pathNode.field, rootNode]]),\n\t\t\t\t}\n\t\t\t} else if ('index' in pathNode) {\n\t\t\t\tconst alias = pathNode.alias\n\n\t\t\t\tif (alias === null) {\n\t\t\t\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t\t\t\t`Corrupt data: undefined alias for node with index ${pathNode.index}.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\trootNode = {\n\t\t\t\t\tvalidation: [],\n\t\t\t\t\texecution: [],\n\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\tchildren: new Map([[MutationAlias.decodeEntityId(alias), rootNode]]),\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tassertNever(pathNode)\n\t\t\t}\n\t\t}\n\n\t\treturn rootNode\n\t}\n\n\tprivate createValidationError(message: string): ErrorAccessor.ValidationError {\n\t\tif (message === 'Field is required') {\n\t\t\t// TODO this is just awful. Validation errors currently don't have error codes which makes it more difficult\n\t\t\t// \tto translate the error messages. This is the most common such error, and so we just make up a code\n\t\t\t// \tin order to facilitate error handling further downstream.\n\t\t\treturn {\n\t\t\t\ttype: 'validation',\n\t\t\t\tcode: 'fieldRequired',\n\t\t\t\tmessage,\n\t\t\t}\n\t\t}\n\t\treturn { type: 'validation', message, code: undefined }\n\t}\n\n\tprivate isExecutionError(error: ValidationError | MutationError): error is MutationError {\n\t\treturn 'type' in error\n\t}\n\n\tprivate rejectCorruptData(): never {\n\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t'Received corrupted data: a node cannot be simultaneously field-indexed and path-indexed.',\n\t\t)\n\t}\n}\n\nnamespace ErrorsPreprocessor {\n\texport interface BaseErrorNode {\n\t\tvalidation: ErrorAccessor.ValidationError[]\n\t\texecution: ErrorAccessor.ExecutionError[]\n\t}\n\n\texport interface LeafErrorNode extends BaseErrorNode {\n\t\tnodeType: 'leaf'\n\t}\n\n\texport interface ErrorINode extends BaseErrorNode {\n\t\tnodeType: 'iNode'\n\t\tchildren: Map<FieldName | EntityId, ErrorNode>\n\t}\n\n\texport type ErrorNode = ErrorINode | LeafErrorNode\n\n\texport type ErrorTreeRoot = Map<PlaceholderName, ErrorNode>\n\n\texport class ErrorsPreprocessorError extends Error {}\n}\n\nexport { ErrorsPreprocessor }\n"],"names":["assertNever","MutationAlias","ErrorsPreprocessor"],"mappings":";;;;AAOA,MAAM,mBAAmB;AAAA,EACjB,YACW,iBACA,YAChB;AAFgB,SAAA,kBAAA;AACA,SAAA,aAAA;AAAA,EACf;AAAA,EAEI,aAA+C;AACrD,UAAM,+BAAiD,IAAA;AAEvD,QAAI,KAAK,oBAAoB,QAAW;AACvC,aAAO;AAAA,IACR;AAEA,eAAW,aAAa,KAAK,YAAY;AACxC,YAAM,mBAAmB,KAAK,gBAAgB,KAAK,UAAU,KAAK;AAClE,YAAM,oBAAoB,KAAK,wBAAwB,gBAAgB;AAEvE,UAAI,sBAAsB,QAAW;AACpC;AAAA,MACD;AACA,YAAM,EAAE,aAAa,oBAAoB,GAAA,IAAO;AAEhD,UAAI,gBAAgB,UAAU;AAC7B,YAAI,SAAS,IAAI,kBAAkB,GAAG;AACrC,iBAAO,KAAK,kBAAA;AAAA,QACb;AACA,iBAAS,IAAI,oBAAoB,iBAAiB;AAAA,MACnD,WAAW,gBAAgB,QAAQ;AAClC,cAAM,QAAQ,SAAS,IAAI,kBAAkB;AAE7C,YAAI,UAAU,QAAW;AACxB,mBAAS,IAAI,oBAAo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AAc,SAAS,MAAM,OAAA;AAAA,EAC7C;AAAA,EAEQ,iBAAiB,OAAgE;AACxF,WAAO,UAAU;AAAA,EAClB;AAAA,EAEQ,oBAA2B;AAClC,UAAM,IAAI,mBAAmB;AAAA,MAC5B;AAAA,IAAA;AAAA,EAEF;AACD;AAAA,CAEA,CAAUE,wBAAV;AAAA,EAmBQ,MAAM,gCAAgC,MAAM;AAAA,EAAA;AAA5CA,sBAAM,0BAAA;AAAA,GAnBJ,uBAAA,qBAAA,CAAA,EAAA;;"}
|
|
1
|
+
{"version":3,"file":"ErrorsPreprocessor.cjs","sources":["../../../../../packages/binding-legacy/src/core/ErrorsPreprocessor.ts"],"sourcesContent":["import type { EntityId, ErrorAccessor, FieldName, PlaceholderName } from '@contember/binding-common'\nimport { DataBindingTransactionResult } from '@contember/binding-common'\nimport { assertNever } from '@contember/binding-common'\nimport { MutationAlias } from './requestAliases/index.js'\nimport { SubMutationOperation } from './MutationGenerator.js'\nimport { MutationError, MutationResult, ValidationError } from '@contember/client'\n\nclass ErrorsPreprocessor {\n\tpublic constructor(\n\t\tprivate readonly requestResponse: DataBindingTransactionResult,\n\t\tprivate readonly operations: SubMutationOperation[],\n\t) {}\n\n\tpublic preprocess(): ErrorsPreprocessor.ErrorTreeRoot {\n\t\tconst treeRoot: ErrorsPreprocessor.ErrorTreeRoot = new Map()\n\n\t\tif (this.requestResponse === undefined) {\n\t\t\treturn treeRoot\n\t\t}\n\n\t\tfor (const operation of this.operations) {\n\t\t\tconst mutationResponse = this.requestResponse.data[operation.alias]\n\t\t\tconst processedResponse = this.processMutationResponse(mutationResponse)\n\n\t\t\tif (processedResponse === undefined) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst { subTreeType, subTreePlaceholder, id } = operation\n\n\t\t\tif (subTreeType === 'single') {\n\t\t\t\tif (treeRoot.has(subTreePlaceholder)) {\n\t\t\t\t\treturn this.rejectCorruptData()\n\t\t\t\t}\n\t\t\t\ttreeRoot.set(subTreePlaceholder, processedResponse)\n\t\t\t} else if (subTreeType === 'list') {\n\t\t\t\tconst child = treeRoot.get(subTreePlaceholder)\n\n\t\t\t\tif (child === undefined) {\n\t\t\t\t\ttreeRoot.set(subTreePlaceholder, {\n\t\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\t\tchildren: new Map([[id, processedResponse]]),\n\t\t\t\t\t\tvalidation: [],\n\t\t\t\t\t\texecution: [],\n\t\t\t\t\t})\n\t\t\t\t} else if (child.nodeType === 'iNode') {\n\t\t\t\t\tchild.children.set(id, processedResponse)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn assertNever(subTreeType)\n\t\t\t}\n\t\t}\n\t\treturn treeRoot\n\t}\n\n\tprivate processMutationResponse(mutationResponse: MutationResult): ErrorsPreprocessor.ErrorNode | undefined {\n\t\tif (mutationResponse.ok && mutationResponse.validation?.valid && mutationResponse.errors.length === 0) {\n\t\t\treturn undefined\n\t\t}\n\t\tif (mutationResponse.validation?.errors.length) {\n\t\t\treturn this.getErrorNode(mutationResponse.validation?.errors)\n\t\t}\n\t\tif (mutationResponse.errors.length) {\n\t\t\treturn this.getErrorNode(mutationResponse.errors)\n\t\t}\n\t\treturn undefined\n\t}\n\n\tprivate getErrorNode(errors: ValidationError[] | MutationError[]): ErrorsPreprocessor.ErrorNode {\n\t\tconst [head, ...tail] = errors\n\n\t\tlet rootNode = this.getRootNode(head)\n\n\t\terrorLoop: for (const error of tail) {\n\t\t\tlet currentNode = rootNode\n\n\t\t\tconst path = 'paths' in error ? (error.paths[0] ?? []) : error.path\n\n\t\t\tfor (let i = 0, pathLength = path.length; i < pathLength; i++) {\n\t\t\t\tconst pathNode = path[i]\n\n\t\t\t\tif (currentNode.nodeType === 'leaf') {\n\t\t\t\t\t;(currentNode as any as ErrorsPreprocessor.ErrorINode).nodeType = 'iNode'\n\t\t\t\t\t;(currentNode as any as ErrorsPreprocessor.ErrorINode).children = new Map()\n\t\t\t\t}\n\n\t\t\t\tif ('field' in pathNode) {\n\t\t\t\t\tif (currentNode.nodeType === 'iNode') {\n\t\t\t\t\t\tlet alias = pathNode.field\n\t\t\t\t\t\tlet nextIndex = i + 1\n\t\t\t\t\t\tif (nextIndex in path) {\n\t\t\t\t\t\t\tconst nextPathNode = path[nextIndex]\n\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t'index' in nextPathNode\n\t\t\t\t\t\t\t\t&& typeof nextPathNode.alias === 'string'\n\t\t\t\t\t\t\t\t&& nextPathNode.alias.startsWith(pathNode.field)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t// We're dealing with a reduced hasMany relation.\n\t\t\t\t\t\t\t\ti++\n\t\t\t\t\t\t\t\tnextIndex++\n\t\t\t\t\t\t\t\talias = nextPathNode.alias\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!currentNode.children.has(alias)) {\n\t\t\t\t\t\t\tcurrentNode.children.set(alias, this.getRootNode(error, nextIndex))\n\t\t\t\t\t\t\tif (nextIndex <= path.length) {\n\t\t\t\t\t\t\t\t// This path has been handled by getRootNode\n\t\t\t\t\t\t\t\tcontinue errorLoop\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentNode = currentNode.children.get(alias)!\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.rejectCorruptData()\n\t\t\t\t\t}\n\t\t\t\t} else if ('index' in path) {\n\t\t\t\t\tif (currentNode.nodeType === 'iNode') {\n\t\t\t\t\t\tconst alias = pathNode.alias\n\n\t\t\t\t\t\tif (alias === null) {\n\t\t\t\t\t\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t\t\t\t\t\t`Corrupt data: undefined alias for node with index ${pathNode.index}.`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst entityId = MutationAlias.decodeEntityId(alias)\n\n\t\t\t\t\t\tif (!currentNode.children.has(entityId)) {\n\t\t\t\t\t\t\tcurrentNode.children.set(entityId, this.getRootNode(error, i + 1))\n\t\t\t\t\t\t\tif (i + 1 <= path.length) {\n\t\t\t\t\t\t\t\t// This path has been handled by getRootNode\n\t\t\t\t\t\t\t\tcontinue errorLoop\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentNode = currentNode.children.get(entityId)!\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.rejectCorruptData()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.isExecutionError(error)) {\n\t\t\t\tcurrentNode.execution.push({ type: 'execution', code: error.type, developerMessage: error.message })\n\t\t\t} else {\n\t\t\t\tcurrentNode.validation.push(this.createValidationError(error.message.text))\n\t\t\t}\n\t\t}\n\n\t\treturn rootNode\n\t}\n\n\tprivate getRootNode(error: ValidationError | MutationError, startIndex: number = 0): ErrorsPreprocessor.ErrorNode {\n\t\tlet rootNode: ErrorsPreprocessor.ErrorNode = {\n\t\t\tvalidation: this.isExecutionError(error) ? [] : [this.createValidationError(error.message.text)],\n\t\t\texecution: this.isExecutionError(error) ? [{ type: 'execution', code: error.type, developerMessage: error.message }] : [],\n\t\t\tnodeType: 'leaf',\n\t\t}\n\t\tconst path = 'paths' in error ? (error.paths[0] ?? []) : error.path\n\t\tfor (let i = path.length - 1; i >= startIndex; i--) {\n\t\t\tconst pathNode = path[i]\n\t\t\tif ('field' in pathNode) {\n\t\t\t\trootNode = {\n\t\t\t\t\tvalidation: [],\n\t\t\t\t\texecution: [],\n\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\tchildren: new Map([[pathNode.field, rootNode]]),\n\t\t\t\t}\n\t\t\t} else if ('index' in pathNode) {\n\t\t\t\tconst alias = pathNode.alias\n\n\t\t\t\tif (alias === null) {\n\t\t\t\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t\t\t\t`Corrupt data: undefined alias for node with index ${pathNode.index}.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\trootNode = {\n\t\t\t\t\tvalidation: [],\n\t\t\t\t\texecution: [],\n\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\tchildren: new Map([[MutationAlias.decodeEntityId(alias), rootNode]]),\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tassertNever(pathNode)\n\t\t\t}\n\t\t}\n\n\t\treturn rootNode\n\t}\n\n\tprivate createValidationError(message: string): ErrorAccessor.ValidationError {\n\t\tif (message === 'Field is required') {\n\t\t\t// TODO this is just awful. Validation errors currently don't have error codes which makes it more difficult\n\t\t\t// \tto translate the error messages. This is the most common such error, and so we just make up a code\n\t\t\t// \tin order to facilitate error handling further downstream.\n\t\t\treturn {\n\t\t\t\ttype: 'validation',\n\t\t\t\tcode: 'fieldRequired',\n\t\t\t\tmessage,\n\t\t\t}\n\t\t}\n\t\treturn { type: 'validation', message, code: undefined }\n\t}\n\n\tprivate isExecutionError(error: ValidationError | MutationError): error is MutationError {\n\t\treturn 'type' in error\n\t}\n\n\tprivate rejectCorruptData(): never {\n\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t'Received corrupted data: a node cannot be simultaneously field-indexed and path-indexed.',\n\t\t)\n\t}\n}\n\nnamespace ErrorsPreprocessor {\n\texport interface BaseErrorNode {\n\t\tvalidation: ErrorAccessor.ValidationError[]\n\t\texecution: ErrorAccessor.ExecutionError[]\n\t}\n\n\texport interface LeafErrorNode extends BaseErrorNode {\n\t\tnodeType: 'leaf'\n\t}\n\n\texport interface ErrorINode extends BaseErrorNode {\n\t\tnodeType: 'iNode'\n\t\tchildren: Map<FieldName | EntityId, ErrorNode>\n\t}\n\n\texport type ErrorNode = ErrorINode | LeafErrorNode\n\n\texport type ErrorTreeRoot = Map<PlaceholderName, ErrorNode>\n\n\texport class ErrorsPreprocessorError extends Error {}\n}\n\nexport { ErrorsPreprocessor }\n"],"names":["assertNever","MutationAlias","ErrorsPreprocessor"],"mappings":";;;;AAOA,MAAM,mBAAm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,CAAC,CAAC,SAAS,OAAO,QAAQ,CAAC,CAAC;AAAA,QAAA;AAAA,MAEhD,WAAW,WAAW,UAAU;AAC/B,cAAM,QAAQ,SAAS;AAEvB,YAAI,UAAU,MAAM;AACnB,gBAAM,IAAI,mBAAmB;AAAA,YAC5B,qDAAqD,SAAS,KAAK;AAAA,UAAA;AAAA,QAErE;AAEA,mBAAW;AAAA,UACV,YAAY,CAAA;AAAA,UACZ,WAAW,CAAA;AAAA,UACX,UAAU;AAAA,UACV,UAAU,oBAAI,IAAI,CAAC,CAACA,cAAAA,cAAc,eAAe,KAAK,GAAG,QAAQ,CAAC,CAAC;AAAA,QAAA;AAAA,MAErE,OAAO;AACND,sBAAAA,YAAY,QAAQ;AAAA,MACrB;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AAAA,EAEQ,sBAAsB,SAAgD;AAC7E,QAAI,YAAY,qBAAqB;AAIpC,aAAO;AAAA,QACN,MAAM;AAAA,QACN,MAAM;AAAA,QACN;AAAA,MAAA;AAAA,IAEF;AACA,WAAO,EAAE,MAAM,cAAc,SAAS,MAAM,OAAA;AAAA,EAC7C;AAAA,EAEQ,iBAAiB,OAAgE;AACxF,WAAO,UAAU;AAAA,EAClB;AAAA,EAEQ,oBAA2B;AAClC,UAAM,IAAI,mBAAmB;AAAA,MAC5B;AAAA,IAAA;AAAA,EAEF;AACD;AAAA,CAEA,CAAUE,wBAAV;AAAA,EAmBQ,MAAM,gCAAgC,MAAM;AAAA,EAAA;AAA5CA,sBAAM,0BAAA;AAAA,GAnBJ,uBAAA,qBAAA,CAAA,EAAA;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ErrorsPreprocessor.js","sources":["../../../../../packages/binding-legacy/src/core/ErrorsPreprocessor.ts"],"sourcesContent":["import type { EntityId, ErrorAccessor, FieldName, PlaceholderName } from '@contember/binding-common'\nimport { DataBindingTransactionResult } from '@contember/binding-common'\nimport { assertNever } from '@contember/binding-common'\nimport { MutationAlias } from './requestAliases'\nimport { SubMutationOperation } from './MutationGenerator'\nimport { MutationError, MutationResult, ValidationError } from '@contember/client'\n\nclass ErrorsPreprocessor {\n\tpublic constructor(\n\t\tprivate readonly requestResponse: DataBindingTransactionResult,\n\t\tprivate readonly operations: SubMutationOperation[],\n\t) {}\n\n\tpublic preprocess(): ErrorsPreprocessor.ErrorTreeRoot {\n\t\tconst treeRoot: ErrorsPreprocessor.ErrorTreeRoot = new Map()\n\n\t\tif (this.requestResponse === undefined) {\n\t\t\treturn treeRoot\n\t\t}\n\n\t\tfor (const operation of this.operations) {\n\t\t\tconst mutationResponse = this.requestResponse.data[operation.alias]\n\t\t\tconst processedResponse = this.processMutationResponse(mutationResponse)\n\n\t\t\tif (processedResponse === undefined) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst { subTreeType, subTreePlaceholder, id } = operation\n\n\t\t\tif (subTreeType === 'single') {\n\t\t\t\tif (treeRoot.has(subTreePlaceholder)) {\n\t\t\t\t\treturn this.rejectCorruptData()\n\t\t\t\t}\n\t\t\t\ttreeRoot.set(subTreePlaceholder, processedResponse)\n\t\t\t} else if (subTreeType === 'list') {\n\t\t\t\tconst child = treeRoot.get(subTreePlaceholder)\n\n\t\t\t\tif (child === undefined) {\n\t\t\t\t\ttreeRoot.set(subTreePlaceholder, {\n\t\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\t\tchildren: new Map([[id, processedResponse]]),\n\t\t\t\t\t\tvalidation: [],\n\t\t\t\t\t\texecution: [],\n\t\t\t\t\t})\n\t\t\t\t} else if (child.nodeType === 'iNode') {\n\t\t\t\t\tchild.children.set(id, processedResponse)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn assertNever(subTreeType)\n\t\t\t}\n\t\t}\n\t\treturn treeRoot\n\t}\n\n\tprivate processMutationResponse(mutationResponse: MutationResult): ErrorsPreprocessor.ErrorNode | undefined {\n\t\tif (mutationResponse.ok && mutationResponse.validation?.valid && mutationResponse.errors.length === 0) {\n\t\t\treturn undefined\n\t\t}\n\t\tif (mutationResponse.validation?.errors.length) {\n\t\t\treturn this.getErrorNode(mutationResponse.validation?.errors)\n\t\t}\n\t\tif (mutationResponse.errors.length) {\n\t\t\treturn this.getErrorNode(mutationResponse.errors)\n\t\t}\n\t\treturn undefined\n\t}\n\n\tprivate getErrorNode(errors: ValidationError[] | MutationError[]): ErrorsPreprocessor.ErrorNode {\n\t\tconst [head, ...tail] = errors\n\n\t\tlet rootNode = this.getRootNode(head)\n\n\t\terrorLoop: for (const error of tail) {\n\t\t\tlet currentNode = rootNode\n\n\t\t\tconst path = 'paths' in error ? (error.paths[0] ?? []) : error.path\n\n\t\t\tfor (let i = 0, pathLength = path.length; i < pathLength; i++) {\n\t\t\t\tconst pathNode = path[i]\n\n\t\t\t\tif (currentNode.nodeType === 'leaf') {\n\t\t\t\t\t;(currentNode as any as ErrorsPreprocessor.ErrorINode).nodeType = 'iNode'\n\t\t\t\t\t;(currentNode as any as ErrorsPreprocessor.ErrorINode).children = new Map()\n\t\t\t\t}\n\n\t\t\t\tif ('field' in pathNode) {\n\t\t\t\t\tif (currentNode.nodeType === 'iNode') {\n\t\t\t\t\t\tlet alias = pathNode.field\n\t\t\t\t\t\tlet nextIndex = i + 1\n\t\t\t\t\t\tif (nextIndex in path) {\n\t\t\t\t\t\t\tconst nextPathNode = path[nextIndex]\n\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t'index' in nextPathNode\n\t\t\t\t\t\t\t\t&& typeof nextPathNode.alias === 'string'\n\t\t\t\t\t\t\t\t&& nextPathNode.alias.startsWith(pathNode.field)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t// We're dealing with a reduced hasMany relation.\n\t\t\t\t\t\t\t\ti++\n\t\t\t\t\t\t\t\tnextIndex++\n\t\t\t\t\t\t\t\talias = nextPathNode.alias\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!currentNode.children.has(alias)) {\n\t\t\t\t\t\t\tcurrentNode.children.set(alias, this.getRootNode(error, nextIndex))\n\t\t\t\t\t\t\tif (nextIndex <= path.length) {\n\t\t\t\t\t\t\t\t// This path has been handled by getRootNode\n\t\t\t\t\t\t\t\tcontinue errorLoop\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentNode = currentNode.children.get(alias)!\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.rejectCorruptData()\n\t\t\t\t\t}\n\t\t\t\t} else if ('index' in path) {\n\t\t\t\t\tif (currentNode.nodeType === 'iNode') {\n\t\t\t\t\t\tconst alias = pathNode.alias\n\n\t\t\t\t\t\tif (alias === null) {\n\t\t\t\t\t\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t\t\t\t\t\t`Corrupt data: undefined alias for node with index ${pathNode.index}.`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst entityId = MutationAlias.decodeEntityId(alias)\n\n\t\t\t\t\t\tif (!currentNode.children.has(entityId)) {\n\t\t\t\t\t\t\tcurrentNode.children.set(entityId, this.getRootNode(error, i + 1))\n\t\t\t\t\t\t\tif (i + 1 <= path.length) {\n\t\t\t\t\t\t\t\t// This path has been handled by getRootNode\n\t\t\t\t\t\t\t\tcontinue errorLoop\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentNode = currentNode.children.get(entityId)!\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.rejectCorruptData()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.isExecutionError(error)) {\n\t\t\t\tcurrentNode.execution.push({ type: 'execution', code: error.type, developerMessage: error.message })\n\t\t\t} else {\n\t\t\t\tcurrentNode.validation.push(this.createValidationError(error.message.text))\n\t\t\t}\n\t\t}\n\n\t\treturn rootNode\n\t}\n\n\tprivate getRootNode(error: ValidationError | MutationError, startIndex: number = 0): ErrorsPreprocessor.ErrorNode {\n\t\tlet rootNode: ErrorsPreprocessor.ErrorNode = {\n\t\t\tvalidation: this.isExecutionError(error) ? [] : [this.createValidationError(error.message.text)],\n\t\t\texecution: this.isExecutionError(error) ? [{ type: 'execution', code: error.type, developerMessage: error.message }] : [],\n\t\t\tnodeType: 'leaf',\n\t\t}\n\t\tconst path = 'paths' in error ? (error.paths[0] ?? []) : error.path\n\t\tfor (let i = path.length - 1; i >= startIndex; i--) {\n\t\t\tconst pathNode = path[i]\n\t\t\tif ('field' in pathNode) {\n\t\t\t\trootNode = {\n\t\t\t\t\tvalidation: [],\n\t\t\t\t\texecution: [],\n\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\tchildren: new Map([[pathNode.field, rootNode]]),\n\t\t\t\t}\n\t\t\t} else if ('index' in pathNode) {\n\t\t\t\tconst alias = pathNode.alias\n\n\t\t\t\tif (alias === null) {\n\t\t\t\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t\t\t\t`Corrupt data: undefined alias for node with index ${pathNode.index}.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\trootNode = {\n\t\t\t\t\tvalidation: [],\n\t\t\t\t\texecution: [],\n\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\tchildren: new Map([[MutationAlias.decodeEntityId(alias), rootNode]]),\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tassertNever(pathNode)\n\t\t\t}\n\t\t}\n\n\t\treturn rootNode\n\t}\n\n\tprivate createValidationError(message: string): ErrorAccessor.ValidationError {\n\t\tif (message === 'Field is required') {\n\t\t\t// TODO this is just awful. Validation errors currently don't have error codes which makes it more difficult\n\t\t\t// \tto translate the error messages. This is the most common such error, and so we just make up a code\n\t\t\t// \tin order to facilitate error handling further downstream.\n\t\t\treturn {\n\t\t\t\ttype: 'validation',\n\t\t\t\tcode: 'fieldRequired',\n\t\t\t\tmessage,\n\t\t\t}\n\t\t}\n\t\treturn { type: 'validation', message, code: undefined }\n\t}\n\n\tprivate isExecutionError(error: ValidationError | MutationError): error is MutationError {\n\t\treturn 'type' in error\n\t}\n\n\tprivate rejectCorruptData(): never {\n\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t'Received corrupted data: a node cannot be simultaneously field-indexed and path-indexed.',\n\t\t)\n\t}\n}\n\nnamespace ErrorsPreprocessor {\n\texport interface BaseErrorNode {\n\t\tvalidation: ErrorAccessor.ValidationError[]\n\t\texecution: ErrorAccessor.ExecutionError[]\n\t}\n\n\texport interface LeafErrorNode extends BaseErrorNode {\n\t\tnodeType: 'leaf'\n\t}\n\n\texport interface ErrorINode extends BaseErrorNode {\n\t\tnodeType: 'iNode'\n\t\tchildren: Map<FieldName | EntityId, ErrorNode>\n\t}\n\n\texport type ErrorNode = ErrorINode | LeafErrorNode\n\n\texport type ErrorTreeRoot = Map<PlaceholderName, ErrorNode>\n\n\texport class ErrorsPreprocessorError extends Error {}\n}\n\nexport { ErrorsPreprocessor }\n"],"names":["ErrorsPreprocessor"],"mappings":";;AAOA,MAAM,mBAAmB;AAAA,EACjB,YACW,iBACA,YAChB;AAFgB,SAAA,kBAAA;AACA,SAAA,aAAA;AAAA,EACf;AAAA,EAEI,aAA+C;AACrD,UAAM,+BAAiD,IAAA;AAEvD,QAAI,KAAK,oBAAoB,QAAW;AACvC,aAAO;AAAA,IACR;AAEA,eAAW,aAAa,KAAK,YAAY;AACxC,YAAM,mBAAmB,KAAK,gBAAgB,KAAK,UAAU,KAAK;AAClE,YAAM,oBAAoB,KAAK,wBAAwB,gBAAgB;AAEvE,UAAI,sBAAsB,QAAW;AACpC;AAAA,MACD;AACA,YAAM,EAAE,aAAa,oBAAoB,GAAA,IAAO;AAEhD,UAAI,gBAAgB,UAAU;AAC7B,YAAI,SAAS,IAAI,kBAAkB,GAAG;AACrC,iBAAO,KAAK,kBAAA;AAAA,QACb;AACA,iBAAS,IAAI,oBAAoB,iBAAiB;AAAA,MACnD,WAAW,gBAAgB,QAAQ;AAClC,cA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N;AAAA,MAAA;AAAA,IAEF;AACA,WAAO,EAAE,MAAM,cAAc,SAAS,MAAM,OAAA;AAAA,EAC7C;AAAA,EAEQ,iBAAiB,OAAgE;AACxF,WAAO,UAAU;AAAA,EAClB;AAAA,EAEQ,oBAA2B;AAClC,UAAM,IAAI,mBAAmB;AAAA,MAC5B;AAAA,IAAA;AAAA,EAEF;AACD;AAAA,CAEA,CAAUA,wBAAV;AAAA,EAmBQ,MAAM,gCAAgC,MAAM;AAAA,EAAA;AAA5CA,sBAAM,0BAAA;AAAA,GAnBJ,uBAAA,qBAAA,CAAA,EAAA;"}
|
|
1
|
+
{"version":3,"file":"ErrorsPreprocessor.js","sources":["../../../../../packages/binding-legacy/src/core/ErrorsPreprocessor.ts"],"sourcesContent":["import type { EntityId, ErrorAccessor, FieldName, PlaceholderName } from '@contember/binding-common'\nimport { DataBindingTransactionResult } from '@contember/binding-common'\nimport { assertNever } from '@contember/binding-common'\nimport { MutationAlias } from './requestAliases/index.js'\nimport { SubMutationOperation } from './MutationGenerator.js'\nimport { MutationError, MutationResult, ValidationError } from '@contember/client'\n\nclass ErrorsPreprocessor {\n\tpublic constructor(\n\t\tprivate readonly requestResponse: DataBindingTransactionResult,\n\t\tprivate readonly operations: SubMutationOperation[],\n\t) {}\n\n\tpublic preprocess(): ErrorsPreprocessor.ErrorTreeRoot {\n\t\tconst treeRoot: ErrorsPreprocessor.ErrorTreeRoot = new Map()\n\n\t\tif (this.requestResponse === undefined) {\n\t\t\treturn treeRoot\n\t\t}\n\n\t\tfor (const operation of this.operations) {\n\t\t\tconst mutationResponse = this.requestResponse.data[operation.alias]\n\t\t\tconst processedResponse = this.processMutationResponse(mutationResponse)\n\n\t\t\tif (processedResponse === undefined) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst { subTreeType, subTreePlaceholder, id } = operation\n\n\t\t\tif (subTreeType === 'single') {\n\t\t\t\tif (treeRoot.has(subTreePlaceholder)) {\n\t\t\t\t\treturn this.rejectCorruptData()\n\t\t\t\t}\n\t\t\t\ttreeRoot.set(subTreePlaceholder, processedResponse)\n\t\t\t} else if (subTreeType === 'list') {\n\t\t\t\tconst child = treeRoot.get(subTreePlaceholder)\n\n\t\t\t\tif (child === undefined) {\n\t\t\t\t\ttreeRoot.set(subTreePlaceholder, {\n\t\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\t\tchildren: new Map([[id, processedResponse]]),\n\t\t\t\t\t\tvalidation: [],\n\t\t\t\t\t\texecution: [],\n\t\t\t\t\t})\n\t\t\t\t} else if (child.nodeType === 'iNode') {\n\t\t\t\t\tchild.children.set(id, processedResponse)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn assertNever(subTreeType)\n\t\t\t}\n\t\t}\n\t\treturn treeRoot\n\t}\n\n\tprivate processMutationResponse(mutationResponse: MutationResult): ErrorsPreprocessor.ErrorNode | undefined {\n\t\tif (mutationResponse.ok && mutationResponse.validation?.valid && mutationResponse.errors.length === 0) {\n\t\t\treturn undefined\n\t\t}\n\t\tif (mutationResponse.validation?.errors.length) {\n\t\t\treturn this.getErrorNode(mutationResponse.validation?.errors)\n\t\t}\n\t\tif (mutationResponse.errors.length) {\n\t\t\treturn this.getErrorNode(mutationResponse.errors)\n\t\t}\n\t\treturn undefined\n\t}\n\n\tprivate getErrorNode(errors: ValidationError[] | MutationError[]): ErrorsPreprocessor.ErrorNode {\n\t\tconst [head, ...tail] = errors\n\n\t\tlet rootNode = this.getRootNode(head)\n\n\t\terrorLoop: for (const error of tail) {\n\t\t\tlet currentNode = rootNode\n\n\t\t\tconst path = 'paths' in error ? (error.paths[0] ?? []) : error.path\n\n\t\t\tfor (let i = 0, pathLength = path.length; i < pathLength; i++) {\n\t\t\t\tconst pathNode = path[i]\n\n\t\t\t\tif (currentNode.nodeType === 'leaf') {\n\t\t\t\t\t;(currentNode as any as ErrorsPreprocessor.ErrorINode).nodeType = 'iNode'\n\t\t\t\t\t;(currentNode as any as ErrorsPreprocessor.ErrorINode).children = new Map()\n\t\t\t\t}\n\n\t\t\t\tif ('field' in pathNode) {\n\t\t\t\t\tif (currentNode.nodeType === 'iNode') {\n\t\t\t\t\t\tlet alias = pathNode.field\n\t\t\t\t\t\tlet nextIndex = i + 1\n\t\t\t\t\t\tif (nextIndex in path) {\n\t\t\t\t\t\t\tconst nextPathNode = path[nextIndex]\n\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t'index' in nextPathNode\n\t\t\t\t\t\t\t\t&& typeof nextPathNode.alias === 'string'\n\t\t\t\t\t\t\t\t&& nextPathNode.alias.startsWith(pathNode.field)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t// We're dealing with a reduced hasMany relation.\n\t\t\t\t\t\t\t\ti++\n\t\t\t\t\t\t\t\tnextIndex++\n\t\t\t\t\t\t\t\talias = nextPathNode.alias\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!currentNode.children.has(alias)) {\n\t\t\t\t\t\t\tcurrentNode.children.set(alias, this.getRootNode(error, nextIndex))\n\t\t\t\t\t\t\tif (nextIndex <= path.length) {\n\t\t\t\t\t\t\t\t// This path has been handled by getRootNode\n\t\t\t\t\t\t\t\tcontinue errorLoop\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentNode = currentNode.children.get(alias)!\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.rejectCorruptData()\n\t\t\t\t\t}\n\t\t\t\t} else if ('index' in path) {\n\t\t\t\t\tif (currentNode.nodeType === 'iNode') {\n\t\t\t\t\t\tconst alias = pathNode.alias\n\n\t\t\t\t\t\tif (alias === null) {\n\t\t\t\t\t\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t\t\t\t\t\t`Corrupt data: undefined alias for node with index ${pathNode.index}.`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst entityId = MutationAlias.decodeEntityId(alias)\n\n\t\t\t\t\t\tif (!currentNode.children.has(entityId)) {\n\t\t\t\t\t\t\tcurrentNode.children.set(entityId, this.getRootNode(error, i + 1))\n\t\t\t\t\t\t\tif (i + 1 <= path.length) {\n\t\t\t\t\t\t\t\t// This path has been handled by getRootNode\n\t\t\t\t\t\t\t\tcontinue errorLoop\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentNode = currentNode.children.get(entityId)!\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.rejectCorruptData()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.isExecutionError(error)) {\n\t\t\t\tcurrentNode.execution.push({ type: 'execution', code: error.type, developerMessage: error.message })\n\t\t\t} else {\n\t\t\t\tcurrentNode.validation.push(this.createValidationError(error.message.text))\n\t\t\t}\n\t\t}\n\n\t\treturn rootNode\n\t}\n\n\tprivate getRootNode(error: ValidationError | MutationError, startIndex: number = 0): ErrorsPreprocessor.ErrorNode {\n\t\tlet rootNode: ErrorsPreprocessor.ErrorNode = {\n\t\t\tvalidation: this.isExecutionError(error) ? [] : [this.createValidationError(error.message.text)],\n\t\t\texecution: this.isExecutionError(error) ? [{ type: 'execution', code: error.type, developerMessage: error.message }] : [],\n\t\t\tnodeType: 'leaf',\n\t\t}\n\t\tconst path = 'paths' in error ? (error.paths[0] ?? []) : error.path\n\t\tfor (let i = path.length - 1; i >= startIndex; i--) {\n\t\t\tconst pathNode = path[i]\n\t\t\tif ('field' in pathNode) {\n\t\t\t\trootNode = {\n\t\t\t\t\tvalidation: [],\n\t\t\t\t\texecution: [],\n\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\tchildren: new Map([[pathNode.field, rootNode]]),\n\t\t\t\t}\n\t\t\t} else if ('index' in pathNode) {\n\t\t\t\tconst alias = pathNode.alias\n\n\t\t\t\tif (alias === null) {\n\t\t\t\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t\t\t\t`Corrupt data: undefined alias for node with index ${pathNode.index}.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\trootNode = {\n\t\t\t\t\tvalidation: [],\n\t\t\t\t\texecution: [],\n\t\t\t\t\tnodeType: 'iNode',\n\t\t\t\t\tchildren: new Map([[MutationAlias.decodeEntityId(alias), rootNode]]),\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tassertNever(pathNode)\n\t\t\t}\n\t\t}\n\n\t\treturn rootNode\n\t}\n\n\tprivate createValidationError(message: string): ErrorAccessor.ValidationError {\n\t\tif (message === 'Field is required') {\n\t\t\t// TODO this is just awful. Validation errors currently don't have error codes which makes it more difficult\n\t\t\t// \tto translate the error messages. This is the most common such error, and so we just make up a code\n\t\t\t// \tin order to facilitate error handling further downstream.\n\t\t\treturn {\n\t\t\t\ttype: 'validation',\n\t\t\t\tcode: 'fieldRequired',\n\t\t\t\tmessage,\n\t\t\t}\n\t\t}\n\t\treturn { type: 'validation', message, code: undefined }\n\t}\n\n\tprivate isExecutionError(error: ValidationError | MutationError): error is MutationError {\n\t\treturn 'type' in error\n\t}\n\n\tprivate rejectCorruptData(): never {\n\t\tthrow new ErrorsPreprocessor.ErrorsPreprocessorError(\n\t\t\t'Received corrupted data: a node cannot be simultaneously field-indexed and path-indexed.',\n\t\t)\n\t}\n}\n\nnamespace ErrorsPreprocessor {\n\texport interface BaseErrorNode {\n\t\tvalidation: ErrorAccessor.ValidationError[]\n\t\texecution: ErrorAccessor.ExecutionError[]\n\t}\n\n\texport interface LeafErrorNode extends BaseErrorNode {\n\t\tnodeType: 'leaf'\n\t}\n\n\texport interface ErrorINode extends BaseErrorNode {\n\t\tnodeType: 'iNode'\n\t\tchildren: Map<FieldName | EntityId, ErrorNode>\n\t}\n\n\texport type ErrorNode = ErrorINode | LeafErrorNode\n\n\texport type ErrorTreeRoot = Map<PlaceholderName, ErrorNode>\n\n\texport class ErrorsPreprocessorError extends Error {}\n}\n\nexport { ErrorsPreprocessor }\n"],"names":["ErrorsPreprocess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,8BAAc,IAAI,CAAC,CAAC,SAAS,OAAO,QAAQ,CAAC,CAAC;AAAA,QAAA;AAAA,MAEhD,WAAW,WAAW,UAAU;AAC/B,cAAM,QAAQ,SAAS;AAEvB,YAAI,UAAU,MAAM;AACnB,gBAAM,IAAI,mBAAmB;AAAA,YAC5B,qDAAqD,SAAS,KAAK;AAAA,UAAA;AAAA,QAErE;AAEA,mBAAW;AAAA,UACV,YAAY,CAAA;AAAA,UACZ,WAAW,CAAA;AAAA,UACX,UAAU;AAAA,UACV,UAAU,oBAAI,IAAI,CAAC,CAAC,cAAc,eAAe,KAAK,GAAG,QAAQ,CAAC,CAAC;AAAA,QAAA;AAAA,MAErE,OAAO;AACN,oBAAY,QAAQ;AAAA,MACrB;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AAAA,EAEQ,sBAAsB,SAAgD;AAC7E,QAAI,YAAY,qBAAqB;AAIpC,aAAO;AAAA,QACN,MAAM;AAAA,QACN,MAAM;AAAA,QACN;AAAA,MAAA;AAAA,IAEF;AACA,WAAO,EAAE,MAAM,cAAc,SAAS,MAAM,OAAA;AAAA,EAC7C;AAAA,EAEQ,iBAAiB,OAAgE;AACxF,WAAO,UAAU;AAAA,EAClB;AAAA,EAEQ,oBAA2B;AAClC,UAAM,IAAI,mBAAmB;AAAA,MAC5B;AAAA,IAAA;AAAA,EAEF;AACD;AAAA,CAEA,CAAUA,wBAAV;AAAA,EAmBQ,MAAM,gCAAgC,MAAM;AAAA,EAAA;AAA5CA,sBAAM,0BAAA;AAAA,GAnBJ,uBAAA,qBAAA,CAAA,EAAA;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EventManager.cjs","sources":["../../../../../packages/binding-legacy/src/core/EventManager.ts"],"sourcesContent":["import type {\n\tAsyncBatchUpdatesOptions,\n\tBatchUpdatesOptions,\n\tEntityAccessor,\n\tEntityListAccessor,\n\tFieldAccessor,\n\tPersistErrorOptions,\n\tPersistSuccessOptions,\n} from '@contember/binding-common'\nimport type { SuccessfulPersistResult } from '@contember/binding-common'\nimport { BindingError } from '@contember/binding-common'\nimport type { PlaceholderName } from '@contember/binding-common'\nimport { assertNever } from '@contember/binding-common'\nimport type { Config } from './Config'\nimport type { DirtinessTracker } from './DirtinessTracker'\nimport { EntityListState, EntityRealmState, FieldState, getEntityMarker, RootStateNode, StateINode, StateIterator, StateNode } from './state'\nimport type { TreeStore } from './TreeStore'\nimport type { UpdateMetadata } from './UpdateMetadata'\nimport type { EventListenersStore } from '@contember/binding-common'\n\nexport class EventManager {\n\tpublic static readonly NO_CHANGES_DIFFERENCE = 0\n\n\tprivate transactionDepth = 0\n\tprivate isFrozenWhileUpdating = false\n\n\t// This should ideally not exists as it should be synonymous to `this.ongoingPersistOperation !== undefined`\n\t// but it makes persist-related promise juggling significantly more straightforward.\n\tprivate isMutating: boolean = false\n\tprivate ongoingPersistOperation: Promise<SuccessfulPersistResult> | undefined = undefined\n\n\tprivate previousMetadata: UpdateMetadata | undefined = undefined\n\n\tprivate newlyInitializedWithListeners: Set<EntityListState | EntityRealmState | FieldState> = new Set()\n\tprivate pendingWithBeforeUpdate: Set<StateNode> = new Set()\n\tprivate rootsWithPendingUpdates: Set<RootStateNode> = new Set()\n\n\tpublic constructor(\n\t\tprivate readonly asyncBatchUpdatesOptions: AsyncBatchUpdatesOptions,\n\t\tprivate readonly batchUpdatesOptions: BatchUpdatesOptions,\n\t\tprivate readonly config: Config,\n\t\tprivate readonly dirtinessTracker: DirtinessTracker,\n\t\tprivate readonly onUpdate: (metadata: UpdateMetadata) => void,\n\t\tprivate readonly treeStore: TreeStore,\n\t\tprivate readonly batchedUpdates: (callback: () => any) => void,\n\t) {}\n\n\tpublic async persistOperation(operation: () => Promise<SuccessfulPersistResult>): Promise<SuccessfulPersistResult> {\n\t\tif (this.ongoingPersistOperation !== undefined) {\n\t\t\tif (this.isMutating) {\n\t\t\t\tthrow new BindingError(`Cannot trigger a persist whilst another one is ongoing!`)\n\t\t\t}\n\t\t\treturn await this.ongoingPersistOperation\n\t\t}\n\t\tif (this.transactionDepth > 0) {\n\t\t\tthrow new BindingError(`Cannot trigger a persist whilst batching updates!`)\n\t\t}\n\t\treturn await (this.ongoingPersistOperation = new Promise<SuccessfulPersistResult>(async (resolve, reject) => {\n\t\t\tawait Promise.resolve()\n\n\t\t\tthis.isMutating = true\n\t\t\tthis.flushUpdates() // Let the world know that we're mutating\n\n\t\t\ttry {\n\t\t\t\tresolve(await this.asyncOperation(operation))\n\t\t\t} catch (e) {\n\t\t\t\tif (!(typeof e === 'object' && e !== null && 'type' in e && e.type === 'invalidInput')) {\n\t\t\t\t\tconsole.error('PersistError', e)\n\t\t\t\t}\n\t\t\t\treject(e)\n\t\t\t} finally {\n\t\t\t\tthis.ongoingPersistOperation = undefined\n\t\t\t\tthis.isMutating = false\n\t\t\t\tthis.flushUpdates()\n\t\t\t}\n\t\t}))\n\t}\n\n\tpublic syncTransaction<T>(transaction: () => T) {\n\t\ttry {\n\t\t\tthis.transactionDepth++\n\t\t\treturn transaction()\n\t\t} finally {\n\t\t\tthis.transactionDepth--\n\t\t}\n\t}\n\tpublic syncOperation<T>(operation: () => T) {\n\t\tconst result = this.syncTransaction(operation)\n\t\tthis.flushUpdates()\n\t\treturn result\n\t}\n\n\tpublic async asyncTransaction<T>(transaction: () => Promise<T>): Promise<T> {\n\t\ttry {\n\t\t\tthis.transactionDepth++\n\t\t\treturn await transaction()\n\t\t} finally {\n\t\t\tthis.transactionDepth--\n\t\t}\n\t}\n\tpublic async asyncOperation<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = await this.asyncTransaction(operation)\n\t\tthis.flushUpdates()\n\t\treturn result\n\t}\n\n\tprivate flushUpdates() {\n\t\tif (this.transactionDepth > 0) {\n\t\t\treturn\n\t\t}\n\n\t\tif (this.isFrozenWhileUpdating) {\n\t\t\tthrow new BindingError(\n\t\t\t\t`Trying to perform an update while the whole accessor tree is already updating. This is most likely caused `\n\t\t\t\t\t+ `by updating the accessor tree while rendering or from within the 'update' event handler, which is a no-op. `\n\t\t\t\t\t+ `If you wish to mutate the tree in reaction to other changes, use the 'beforeUpdate' event.`,\n\t\t\t)\n\t\t}\n\n\t\tconst newMetadata = this.getNewUpdateMetadata()\n\n\t\tif (!this.shouldFlushUpdates(newMetadata)) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.batchedUpdates(() => {\n\t\t\tthis.isFrozenWhileUpdating = true\n\t\t\tthis.triggerBeforeFlushEvents()\n\t\t\tthis.onUpdate(newMetadata)\n\t\t\tconst rootStates = Array.from(this.rootsWithPendingUpdates)\n\t\t\tthis.flushPendingAccessorUpdates(rootStates)\n\t\t\tthis.rootsWithPendingUpdates.clear()\n\t\t\tthis.isFrozenWhileUpdating = false\n\t\t\tthis.previousMetadata = newMetadata\n\t\t})\n\t}\n\n\tprivate getNewUpdateMetadata(): UpdateMetadata {\n\t\treturn {\n\t\t\tisMutating: this.isMutating,\n\t\t}\n\t}\n\n\tprivate shouldFlushUpdates(newMetadata: UpdateMetadata): boolean {\n\t\tif (this.transactionDepth > 0) {\n\t\t\treturn false\n\t\t}\n\t\tif (this.previousMetadata === undefined) {\n\t\t\treturn true\n\t\t}\n\t\tif (this.rootsWithPendingUpdates.size) {\n\t\t\treturn true\n\t\t}\n\t\tfor (const key in newMetadata) {\n\t\t\tconst fromPrevious = this.previousMetadata[key as keyof UpdateMetadata]\n\t\t\tconst fromNew = newMetadata[key as keyof UpdateMetadata]\n\n\t\t\tif (!Object.is(fromPrevious, fromNew)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tpublic registerNewlyInitialized(newlyInitialized: StateNode) {\n\t\tconst initializeListeners = this.getEventListeners(newlyInitialized, { type: 'initialize' })\n\n\t\tif (initializeListeners === undefined) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.newlyInitializedWithListeners.add(newlyInitialized)\n\n\t\tif (this.transactionDepth === 0) {\n\t\t\tthis.triggerOnInitialize()\n\t\t}\n\t}\n\n\tpublic registerUpdatedConnection(parentState: EntityRealmState, placeholderName: PlaceholderName) {\n\t\tif (parentState.fieldsWithPendingConnectionUpdates === undefined) {\n\t\t\tparentState.fieldsWithPendingConnectionUpdates = new Set()\n\t\t}\n\n\t\tconst marker = getEntityMarker(parentState)\n\t\tplaceholders: for (const [fieldName, placeholdersByField] of marker.fields.placeholders) {\n\t\t\tif (typeof placeholdersByField === 'string') {\n\t\t\t\tif (placeholdersByField === placeholderName) {\n\t\t\t\t\tparentState.fieldsWithPendingConnectionUpdates.add(fieldName)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (const placeholderByFieldName of placeholdersByField) {\n\t\t\t\t\tif (placeholderByFieldName === placeholderName) {\n\t\t\t\t\t\tparentState.fieldsWithPendingConnectionUpdates.add(fieldName)\n\t\t\t\t\t\tcontinue placeholders\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic registerJustUpdated(justUpdated: StateNode, changesDelta: number) {\n\t\tconst beforeUpdateListeners = this.getEventListeners(justUpdated, { type: 'beforeUpdate' })\n\t\tif (beforeUpdateListeners !== undefined) {\n\t\t\tthis.pendingWithBeforeUpdate.add(justUpdated)\n\t\t}\n\t\tjustUpdated.accessor = undefined\n\n\t\tswitch (justUpdated.type) {\n\t\t\tcase 'entityRealm':\n\t\t\tcase 'entityList': {\n\t\t\t\tjustUpdated.unpersistedChangesCount += changesDelta\n\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tif (justUpdated.unpersistedChangesCount < 0) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t`We have *JUST* reached a completely invalid state. From now on, anything can (and likely will) `\n\t\t\t\t\t\t\t\t+ `go wrong. This is definitely a bug. Please try to report whatever led to this situation.`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst parent = justUpdated.blueprint.parent\n\n\t\t\t\tif (parent === undefined) {\n\t\t\t\t\tthis.rootsWithPendingUpdates.add(justUpdated)\n\n\t\t\t\t\tif (\n\t\t\t\t\t\t!(justUpdated.blueprint.type === 'subTree' && justUpdated.blueprint.marker.parameters.isCreating\n\t\t\t\t\t\t\t&& justUpdated.blueprint.marker.parameters.isUnpersisted)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.dirtinessTracker.increaseBy(changesDelta)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (!parent.childrenWithPendingUpdates) {\n\t\t\t\t\t\tparent.childrenWithPendingUpdates = new Set()\n\t\t\t\t\t}\n\t\t\t\t\tparent.childrenWithPendingUpdates.add(justUpdated as any)\n\t\t\t\t\tthis.registerJustUpdated(parent, changesDelta)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'field': {\n\t\t\t\tconst parent = justUpdated.parent\n\t\t\t\tif (!parent.childrenWithPendingUpdates) {\n\t\t\t\t\tparent.childrenWithPendingUpdates = new Set()\n\t\t\t\t}\n\t\t\t\tparent.childrenWithPendingUpdates.add(justUpdated as any)\n\t\t\t\tthis.registerJustUpdated(justUpdated.parent, changesDelta)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate flushPendingAccessorUpdates(rootStates: Array<StateINode>) {\n\t\t// It is *CRUCIAL* that this is a BFS so that we update the components in top-down order.\n\t\tconst agenda: StateNode[] = rootStates\n\n\t\tfor (const state of agenda) {\n\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\tconst updateListeners = state.type === 'field'\n\t\t\t\t? this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\t\t\t\t: state.type === 'entityRealm'\n\t\t\t\t? this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\t\t\t\t: this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\n\t\t\tif (updateListeners !== undefined) {\n\t\t\t\tfor (const handler of updateListeners) {\n\t\t\t\t\t// TS can't quite handle the polymorphism here but this is fine.\n\t\t\t\t\thandler()\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (state.type === 'entityRealm' && state.fieldsWithPendingConnectionUpdates) {\n\t\t\t\tfor (const updatedField of state.fieldsWithPendingConnectionUpdates) {\n\t\t\t\t\tconst listeners = this.getEventListeners(state, { type: 'connectionUpdate', key: updatedField })\n\t\t\t\t\tif (!listeners) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tlistener(state.getAccessor())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch (state.type) {\n\t\t\t\tcase 'entityRealm':\n\t\t\t\tcase 'entityList': {\n\t\t\t\t\tif (state.childrenWithPendingUpdates !== undefined) {\n\t\t\t\t\t\tfor (const childState of state.childrenWithPendingUpdates) {\n\t\t\t\t\t\t\tagenda.push(childState)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstate.childrenWithPendingUpdates.clear()\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'field':\n\t\t\t\t\t// Do nothing\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(state)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async triggerAsyncMutatingEvent(eventType: 'beforePersist', options: AsyncBatchUpdatesOptions): Promise<void>\n\tprivate async triggerAsyncMutatingEvent(eventType: 'persistSuccess', options: PersistSuccessOptions): Promise<void>\n\tprivate async triggerAsyncMutatingEvent(\n\t\teventType: 'beforePersist' | 'persistSuccess',\n\t\toptions: AsyncBatchUpdatesOptions | PersistSuccessOptions,\n\t): Promise<void> {\n\t\tawait this.asyncTransaction(async () => {\n\t\t\t// TODO if an entity from here (or its parent) gets deleted, we need to remove stale handlers from here.\n\t\t\tconst callbackQueue: Array<\n\t\t\t\t[\n\t\t\t\t\t// The typings could be nicer but TS…\n\t\t\t\t\tStateINode,\n\t\t\t\t\t(\n\t\t\t\t\t\t| EntityAccessor.EntityEventListenerMap[typeof eventType]\n\t\t\t\t\t\t| EntityListAccessor.EntityListEventListenerMap[typeof eventType]\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t> = []\n\n\t\t\tfor (const [, subTreeState] of StateIterator.eachRootState(this.treeStore)) {\n\t\t\t\tfor (const iNode of StateIterator.depthFirstINodes(subTreeState)) {\n\t\t\t\t\tconst listeners = this.getEventListeners(iNode, { type: eventType }) ?? []\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tcallbackQueue.push([iNode, listener])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (\n\t\t\t\tlet waterfallDepth = 0;\n\t\t\t\twaterfallDepth < this.config.getValue(`${eventType}SettleLimit` as const);\n\t\t\t\twaterfallDepth++\n\t\t\t) {\n\t\t\t\tconst promiseReturns: Array<\n\t\t\t\t\tPromise<\n\t\t\t\t\t\t| void\n\t\t\t\t\t\t| EntityAccessor.EntityEventListenerMap[typeof eventType]\n\t\t\t\t\t\t| EntityListAccessor.EntityListEventListenerMap[typeof eventType]\n\t\t\t\t\t>\n\t\t\t\t> = []\n\t\t\t\tconst correspondingStates: Array<StateINode> = []\n\n\t\t\t\tif (callbackQueue.length === 0) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tfor (const [state, callback] of callbackQueue) {\n\t\t\t\t\tcorrespondingStates.push(state)\n\t\t\t\t\tconst changesCountBefore = this.dirtinessTracker.getTotalTouchCount()\n\t\t\t\t\tlet validateChanges = false\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = callback(state.getAccessor as any, options as any) // TS can't quite handle this but this is sound.\n\t\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\t\tvalidateChanges = true\n\t\t\t\t\t\t\tpromiseReturns.push(result)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpromiseReturns.push(Promise.resolve(result))\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tpromiseReturns.push(Promise.reject(e))\n\t\t\t\t\t}\n\t\t\t\t\tif (validateChanges) {\n\t\t\t\t\t\tthis.validateWithoutChanges(changesCountBefore, eventType)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// TODO timeout\n\n\t\t\t\tconst changesCountBefore = this.dirtinessTracker.getTotalTouchCount()\n\t\t\t\tconst newCallbacks = await Promise.allSettled(promiseReturns)\n\t\t\t\tthis.validateWithoutChanges(changesCountBefore, eventType)\n\n\t\t\t\tcallbackQueue.length = 0 // Empties the queue\n\n\t\t\t\t// TODO we're drifting away from the original depth-first order. Let's see if that's ever even an issue.\n\t\t\t\tfor (const newlyInitialized of this.newlyInitializedWithListeners) {\n\t\t\t\t\tif (newlyInitialized.type === 'field') {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst beforePersistHandlers = this.getEventListeners(newlyInitialized, { type: eventType })\n\t\t\t\t\tif (beforePersistHandlers) {\n\t\t\t\t\t\tfor (const listener of beforePersistHandlers) {\n\t\t\t\t\t\t\tcallbackQueue.push([newlyInitialized, listener])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.triggerBeforeFlushEvents()\n\t\t\t\tthis.handleRejections(eventType, newCallbacks)\n\n\t\t\t\tfor (let i = 0; i < newCallbacks.length; i++) {\n\t\t\t\t\tconst result = newCallbacks[i]\n\t\t\t\t\tconst correspondingState = correspondingStates[i]\n\n\t\t\t\t\tif (result.status === 'fulfilled') {\n\t\t\t\t\t\tif (typeof result.value === 'function') {\n\t\t\t\t\t\t\tcallbackQueue.push([correspondingState, result.value])\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Otherwise do nothing. This is just a handler that albeit async, doesn't appear to\n\t\t\t\t\t\t// interact with data binding.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tif (callbackQueue.length) {\n\t\t\t\t\tthrow new BindingError(\n\t\t\t\t\t\t`Exceeded the ${eventType} settle limit. Your code likely contains a deadlock. `\n\t\t\t\t\t\t\t+ `If that's not the case, raise the settle limit from DataBindingProvider.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate triggerBeforeFlushEvents() {\n\t\tthis.syncTransaction(() => {\n\t\t\tconst settleLimit = this.config.getValue('beforeUpdateSettleLimit')\n\n\t\t\tfor (let attemptNumber = 0; attemptNumber < settleLimit; attemptNumber++) {\n\t\t\t\tif (!this.pendingWithBeforeUpdate.size) {\n\t\t\t\t\tthis.triggerOnInitialize()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconst withBeforeUpdate = this.pendingWithBeforeUpdate\n\t\t\t\tthis.pendingWithBeforeUpdate = new Set()\n\n\t\t\t\tfor (const state of withBeforeUpdate) {\n\t\t\t\t\tconst listeners = this.getEventListeners(state, { type: 'beforeUpdate' })\n\t\t\t\t\tif (listeners === undefined) {\n\t\t\t\t\t\t// This can happen if the listener has unsubscribed since we added it to the set.\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tswitch (state.type) {\n\t\t\t\t\t\tcase 'field':\n\t\t\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\t\t\t;(listener as FieldAccessor.BeforeUpdateListener)(state.getAccessor())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase 'entityRealm':\n\t\t\t\t\t\tcase 'entityList':\n\t\t\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\t\t\tstate.getAccessor().batchUpdates(listener as any)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn assertNever(state)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.triggerOnInitialize()\n\t\t\t}\n\t\t\tthrow new BindingError(\n\t\t\t\t`Maximum stabilization limit of updates caused by 'beforeUpdate' exceeded. `\n\t\t\t\t\t+ `This likely means there is an infinite feedback loop in your code.`,\n\t\t\t)\n\t\t})\n\t}\n\n\tprivate triggerOnInitialize() {\n\t\tthis.syncTransaction(() => {\n\t\t\tfor (const state of this.newlyInitializedWithListeners) {\n\t\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\t\tconst listeners = state.type === 'field'\n\t\t\t\t\t? this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\t\t\t\t\t: state.type === 'entityRealm'\n\t\t\t\t\t? this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\t\t\t\t\t: this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\n\t\t\t\tif (listeners) {\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tlistener()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (state.type === 'entityRealm') {\n\t\t\t\t\tstate.entity.hasIdSetInStone = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.newlyInitializedWithListeners.clear()\n\t\t})\n\t}\n\n\tpublic async triggerOnPersistError(options: PersistErrorOptions) {\n\t\tawait this.asyncTransaction(async () => {\n\t\t\tconst handlerPromises: Array<Promise<void>> = []\n\n\t\t\tfor (const [, subTreeState] of StateIterator.eachRootState(this.treeStore)) {\n\t\t\t\tfor (const iNode of StateIterator.depthFirstINodes(subTreeState)) {\n\t\t\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\t\t\tconst dispatchers = iNode.type === 'entityRealm'\n\t\t\t\t\t\t? this.getEventDispatchers(iNode, { type: 'persistError' }, [iNode.getAccessor, options])\n\t\t\t\t\t\t: this.getEventDispatchers(iNode, { type: 'persistError' }, [iNode.getAccessor, options])\n\t\t\t\t\tif (dispatchers === undefined) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfor (const listener of dispatchers ?? []) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = listener()\n\t\t\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\t\t\thandlerPromises.push(result)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\thandlerPromises.push(Promise.resolve(result))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\thandlerPromises.push(Promise.reject(e))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO timeout\n\t\t\tconst handlerResults = await Promise.allSettled(handlerPromises)\n\t\t\tthis.handleRejections('persistError', handlerResults)\n\t\t})\n\t}\n\n\tpublic async triggerOnBeforePersist() {\n\t\treturn this.triggerAsyncMutatingEvent('beforePersist', this.asyncBatchUpdatesOptions)\n\t}\n\n\tpublic async triggerOnPersistSuccess(options: PersistSuccessOptions) {\n\t\treturn this.triggerAsyncMutatingEvent('persistSuccess', options)\n\t}\n\n\tpublic getEventListeners<\n\t\tState extends StateNode,\n\t\tEventListenerTypes extends Exclude<State['eventListeners'], undefined> extends EventListenersStore<infer Map> ? [keyof Map, Map] : never,\n\t\tEventType extends EventListenerTypes[0],\n\t>(state: State, event: { type: EventType; key?: string }): Set<Exclude<EventListenerTypes[1][EventType], undefined>> | undefined {\n\t\tif (!state.eventListeners) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn (state.eventListeners as EventListenersStore<EventListenerTypes[1]>).get(event) as Set<\n\t\t\tExclude<EventListenerTypes[1][EventType], undefined>\n\t\t>\n\t}\n\n\tpublic getEventDispatchers<\n\t\tState extends StateNode,\n\t\tEventListenerTypes extends Exclude<State['eventListeners'], undefined> extends EventListenersStore<infer Map> ? [keyof Map, Map] : never,\n\t\tEventType extends EventListenerTypes[0],\n\t>(\n\t\tstate: State,\n\t\tevent: { type: EventType; key?: string },\n\t\tlistenerArgs: Parameters<Exclude<EventListenerTypes[1][EventType], undefined>>,\n\t): Array<() => ReturnType<Exclude<EventListenerTypes[1][EventType], undefined>>> | undefined {\n\t\tconst eventListeners = this.getEventListeners(state, event)\n\t\tif (eventListeners === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn Array.from(eventListeners.values(), listener => {\n\t\t\treturn () => listener(...listenerArgs)\n\t\t}) as Array<() => ReturnType<Exclude<EventListenerTypes[1][EventType], undefined>>>\n\t}\n\n\tprivate handleRejections(handler: string, promises: PromiseSettledResult<any>[]) {\n\t\tconst rejections = promises.filter((it): it is PromiseRejectedResult => it.status === 'rejected')\n\t\tif (rejections.length === 0) {\n\t\t\treturn\n\t\t}\n\t\trejections.forEach(it => console.error(it.reason))\n\t\tif (import.meta.env.DEV) {\n\t\t\tthrow new BindingError(\n\t\t\t\t`A ${handler} handler returned a promise that rejected. `\n\t\t\t\t\t+ `This is a no-op that will fail silently in production.`,\n\t\t\t)\n\t\t}\n\t}\n\n\tprivate validateWithoutChanges(initialCount: number, eventType: string): void {\n\t\tconst changesCountAfter = this.dirtinessTracker.getTotalTouchCount()\n\t\tif (import.meta.env.DEV) {\n\t\t\tif (initialCount !== changesCountAfter) {\n\t\t\t\t// This isn't bulletproof. They could e.g. undo a change and make another one which would\n\t\t\t\t// slip through this detection. But for most cases, it should be good enough and not too expensive.\n\t\t\t\tthrow new BindingError(\n\t\t\t\t\t`A ${eventType} event handler cannot be asynchronous and alter the accessor tree at the same time. `\n\t\t\t\t\t\t+ `To achieve this, prepare your data asynchronously but only touch the tree from a returned callback.`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}\n"],"names":["BindingError","getEntityMarker","assertNever","StateIterator","changesCountBefore"],"mappings":";;;;;;;;AAoBO,MAAM,aAAa;AAAA,EAiBlB,YACW,0BACA,qBACA,QACA,kBACA,UACA,WACA,gBAChB;AAPgB,SAAA,2BAAA;AACA,SAAA,sBAAA;AACA,SAAA,SAAA;AACA,SAAA,mBAAA;AACA,SAAA,WAAA;AACA,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AC,MAAM,gBAAgB;AAC1B,aAAO;AAAA,IACR;AACA,WAAQ,MAAM,eAA8D,IAAI,KAAK;AAAA,EAGtF;AAAA,EAEO,oBAKN,OACA,OACA,cAC4F;AAC5F,UAAM,iBAAiB,KAAK,kBAAkB,OAAO,KAAK;AAC1D,QAAI,mBAAmB,QAAW;AACjC,aAAO;AAAA,IACR;AACA,WAAO,MAAM,KAAK,eAAe,OAAA,GAAU,CAAA,aAAY;AACtD,aAAO,MAAM,SAAS,GAAG,YAAY;AAAA,IACtC,CAAC;AAAA,EACF;AAAA,EAEQ,iBAAiB,SAAiB,UAAuC;AAChF,UAAM,aAAa,SAAS,OAAO,CAAC,OAAoC,GAAG,WAAW,UAAU;AAChG,QAAI,WAAW,WAAW,GAAG;AAC5B;AAAA,IACD;AACA,eAAW,QAAQ,CAAA,OAAM,QAAQ,MAAM,GAAG,MAAM,CAAC;AACxB;AACxB,YAAM,IAAIH,cAAAA;AAAAA,QACT,KAAK,OAAO;AAAA,MAAA;AAAA,IAGd;AAAA,EACD;AAAA,EAEQ,uBAAuB,cAAsB,WAAyB;AAC7E,UAAM,oBAAoB,KAAK,iBAAiB,mBAAA;AACvB;AACxB,UAAI,iBAAiB,mBAAmB;AAGvC,cAAM,IAAIA,cAAAA;AAAAA,UACT,KAAK,SAAS;AAAA,QAAA;AAAA,MAGhB;AAAA,IACD;AAAA,EACD;AACD;AAjjBC,cADY,cACW,yBAAwB,CAAA;;"}
|
|
1
|
+
{"version":3,"file":"EventManager.cjs","sources":["../../../../../packages/binding-legacy/src/core/EventManager.ts"],"sourcesContent":["import type {\n\tAsyncBatchUpdatesOptions,\n\tBatchUpdatesOptions,\n\tEntityAccessor,\n\tEntityListAccessor,\n\tFieldAccessor,\n\tPersistErrorOptions,\n\tPersistSuccessOptions,\n} from '@contember/binding-common'\nimport type { SuccessfulPersistResult } from '@contember/binding-common'\nimport { BindingError } from '@contember/binding-common'\nimport type { PlaceholderName } from '@contember/binding-common'\nimport { assertNever } from '@contember/binding-common'\nimport type { Config } from './Config.js'\nimport type { DirtinessTracker } from './DirtinessTracker.js'\nimport { EntityListState, EntityRealmState, FieldState, getEntityMarker, RootStateNode, StateINode, StateIterator, StateNode } from './state/index.js'\nimport type { TreeStore } from './TreeStore.js'\nimport type { UpdateMetadata } from './UpdateMetadata.js'\nimport type { EventListenersStore } from '@contember/binding-common'\n\nexport class EventManager {\n\tpublic static readonly NO_CHANGES_DIFFERENCE = 0\n\n\tprivate transactionDepth = 0\n\tprivate isFrozenWhileUpdating = false\n\n\t// This should ideally not exists as it should be synonymous to `this.ongoingPersistOperation !== undefined`\n\t// but it makes persist-related promise juggling significantly more straightforward.\n\tprivate isMutating: boolean = false\n\tprivate ongoingPersistOperation: Promise<SuccessfulPersistResult> | undefined = undefined\n\n\tprivate previousMetadata: UpdateMetadata | undefined = undefined\n\n\tprivate newlyInitializedWithListeners: Set<EntityListState | EntityRealmState | FieldState> = new Set()\n\tprivate pendingWithBeforeUpdate: Set<StateNode> = new Set()\n\tprivate rootsWithPendingUpdates: Set<RootStateNode> = new Set()\n\n\tpublic constructor(\n\t\tprivate readonly asyncBatchUpdatesOptions: AsyncBatchUpdatesOptions,\n\t\tprivate readonly batchUpdatesOptions: BatchUpdatesOptions,\n\t\tprivate readonly config: Config,\n\t\tprivate readonly dirtinessTracker: DirtinessTracker,\n\t\tprivate readonly onUpdate: (metadata: UpdateMetadata) => void,\n\t\tprivate readonly treeStore: TreeStore,\n\t\tprivate readonly batchedUpdates: (callback: () => any) => void,\n\t) {}\n\n\tpublic async persistOperation(operation: () => Promise<SuccessfulPersistResult>): Promise<SuccessfulPersistResult> {\n\t\tif (this.ongoingPersistOperation !== undefined) {\n\t\t\tif (this.isMutating) {\n\t\t\t\tthrow new BindingError(`Cannot trigger a persist whilst another one is ongoing!`)\n\t\t\t}\n\t\t\treturn await this.ongoingPersistOperation\n\t\t}\n\t\tif (this.transactionDepth > 0) {\n\t\t\tthrow new BindingError(`Cannot trigger a persist whilst batching updates!`)\n\t\t}\n\t\treturn await (this.ongoingPersistOperation = new Promise<SuccessfulPersistResult>(async (resolve, reject) => {\n\t\t\tawait Promise.resolve()\n\n\t\t\tthis.isMutating = true\n\t\t\tthis.flushUpdates() // Let the world know that we're mutating\n\n\t\t\ttry {\n\t\t\t\tresolve(await this.asyncOperation(operation))\n\t\t\t} catch (e) {\n\t\t\t\tif (!(typeof e === 'object' && e !== null && 'type' in e && e.type === 'invalidInput')) {\n\t\t\t\t\tconsole.error('PersistError', e)\n\t\t\t\t}\n\t\t\t\treject(e)\n\t\t\t} finally {\n\t\t\t\tthis.ongoingPersistOperation = undefined\n\t\t\t\tthis.isMutating = false\n\t\t\t\tthis.flushUpdates()\n\t\t\t}\n\t\t}))\n\t}\n\n\tpublic syncTransaction<T>(transaction: () => T) {\n\t\ttry {\n\t\t\tthis.transactionDepth++\n\t\t\treturn transaction()\n\t\t} finally {\n\t\t\tthis.transactionDepth--\n\t\t}\n\t}\n\tpublic syncOperation<T>(operation: () => T) {\n\t\tconst result = this.syncTransaction(operation)\n\t\tthis.flushUpdates()\n\t\treturn result\n\t}\n\n\tpublic async asyncTransaction<T>(transaction: () => Promise<T>): Promise<T> {\n\t\ttry {\n\t\t\tthis.transactionDepth++\n\t\t\treturn await transaction()\n\t\t} finally {\n\t\t\tthis.transactionDepth--\n\t\t}\n\t}\n\tpublic async asyncOperation<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = await this.asyncTransaction(operation)\n\t\tthis.flushUpdates()\n\t\treturn result\n\t}\n\n\tprivate flushUpdates() {\n\t\tif (this.transactionDepth > 0) {\n\t\t\treturn\n\t\t}\n\n\t\tif (this.isFrozenWhileUpdating) {\n\t\t\tthrow new BindingError(\n\t\t\t\t`Trying to perform an update while the whole accessor tree is already updating. This is most likely caused `\n\t\t\t\t\t+ `by updating the accessor tree while rendering or from within the 'update' event handler, which is a no-op. `\n\t\t\t\t\t+ `If you wish to mutate the tree in reaction to other changes, use the 'beforeUpdate' event.`,\n\t\t\t)\n\t\t}\n\n\t\tconst newMetadata = this.getNewUpdateMetadata()\n\n\t\tif (!this.shouldFlushUpdates(newMetadata)) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.batchedUpdates(() => {\n\t\t\tthis.isFrozenWhileUpdating = true\n\t\t\tthis.triggerBeforeFlushEvents()\n\t\t\tthis.onUpdate(newMetadata)\n\t\t\tconst rootStates = Array.from(this.rootsWithPendingUpdates)\n\t\t\tthis.flushPendingAccessorUpdates(rootStates)\n\t\t\tthis.rootsWithPendingUpdates.clear()\n\t\t\tthis.isFrozenWhileUpdating = false\n\t\t\tthis.previousMetadata = newMetadata\n\t\t})\n\t}\n\n\tprivate getNewUpdateMetadata(): UpdateMetadata {\n\t\treturn {\n\t\t\tisMutating: this.isMutating,\n\t\t}\n\t}\n\n\tprivate shouldFlushUpdates(newMetadata: UpdateMetadata): boolean {\n\t\tif (this.transactionDepth > 0) {\n\t\t\treturn false\n\t\t}\n\t\tif (this.previousMetadata === undefined) {\n\t\t\treturn true\n\t\t}\n\t\tif (this.rootsWithPendingUpdates.size) {\n\t\t\treturn true\n\t\t}\n\t\tfor (const key in newMetadata) {\n\t\t\tconst fromPrevious = this.previousMetadata[key as keyof UpdateMetadata]\n\t\t\tconst fromNew = newMetadata[key as keyof UpdateMetadata]\n\n\t\t\tif (!Object.is(fromPrevious, fromNew)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tpublic registerNewlyInitialized(newlyInitialized: StateNode) {\n\t\tconst initializeListeners = this.getEventListeners(newlyInitialized, { type: 'initialize' })\n\n\t\tif (initializeListeners === undefined) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.newlyInitializedWithListeners.add(newlyInitialized)\n\n\t\tif (this.transactionDepth === 0) {\n\t\t\tthis.triggerOnInitialize()\n\t\t}\n\t}\n\n\tpublic registerUpdatedConnection(parentState: EntityRealmState, placeholderName: PlaceholderName) {\n\t\tif (parentState.fieldsWithPendingConnectionUpdates === undefined) {\n\t\t\tparentState.fieldsWithPendingConnectionUpdates = new Set()\n\t\t}\n\n\t\tconst marker = getEntityMarker(parentState)\n\t\tplaceholders: for (const [fieldName, placeholdersByField] of marker.fields.placeholders) {\n\t\t\tif (typeof placeholdersByField === 'string') {\n\t\t\t\tif (placeholdersByField === placeholderName) {\n\t\t\t\t\tparentState.fieldsWithPendingConnectionUpdates.add(fieldName)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (const placeholderByFieldName of placeholdersByField) {\n\t\t\t\t\tif (placeholderByFieldName === placeholderName) {\n\t\t\t\t\t\tparentState.fieldsWithPendingConnectionUpdates.add(fieldName)\n\t\t\t\t\t\tcontinue placeholders\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic registerJustUpdated(justUpdated: StateNode, changesDelta: number) {\n\t\tconst beforeUpdateListeners = this.getEventListeners(justUpdated, { type: 'beforeUpdate' })\n\t\tif (beforeUpdateListeners !== undefined) {\n\t\t\tthis.pendingWithBeforeUpdate.add(justUpdated)\n\t\t}\n\t\tjustUpdated.accessor = undefined\n\n\t\tswitch (justUpdated.type) {\n\t\t\tcase 'entityRealm':\n\t\t\tcase 'entityList': {\n\t\t\t\tjustUpdated.unpersistedChangesCount += changesDelta\n\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tif (justUpdated.unpersistedChangesCount < 0) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t`We have *JUST* reached a completely invalid state. From now on, anything can (and likely will) `\n\t\t\t\t\t\t\t\t+ `go wrong. This is definitely a bug. Please try to report whatever led to this situation.`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst parent = justUpdated.blueprint.parent\n\n\t\t\t\tif (parent === undefined) {\n\t\t\t\t\tthis.rootsWithPendingUpdates.add(justUpdated)\n\n\t\t\t\t\tif (\n\t\t\t\t\t\t!(justUpdated.blueprint.type === 'subTree' && justUpdated.blueprint.marker.parameters.isCreating\n\t\t\t\t\t\t\t&& justUpdated.blueprint.marker.parameters.isUnpersisted)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.dirtinessTracker.increaseBy(changesDelta)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (!parent.childrenWithPendingUpdates) {\n\t\t\t\t\t\tparent.childrenWithPendingUpdates = new Set()\n\t\t\t\t\t}\n\t\t\t\t\tparent.childrenWithPendingUpdates.add(justUpdated as any)\n\t\t\t\t\tthis.registerJustUpdated(parent, changesDelta)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'field': {\n\t\t\t\tconst parent = justUpdated.parent\n\t\t\t\tif (!parent.childrenWithPendingUpdates) {\n\t\t\t\t\tparent.childrenWithPendingUpdates = new Set()\n\t\t\t\t}\n\t\t\t\tparent.childrenWithPendingUpdates.add(justUpdated as any)\n\t\t\t\tthis.registerJustUpdated(justUpdated.parent, changesDelta)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate flushPendingAccessorUpdates(rootStates: Array<StateINode>) {\n\t\t// It is *CRUCIAL* that this is a BFS so that we update the components in top-down order.\n\t\tconst agenda: StateNode[] = rootStates\n\n\t\tfor (const state of agenda) {\n\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\tconst updateListeners = state.type === 'field'\n\t\t\t\t? this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\t\t\t\t: state.type === 'entityRealm'\n\t\t\t\t? this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\t\t\t\t: this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\n\t\t\tif (updateListeners !== undefined) {\n\t\t\t\tfor (const handler of updateListeners) {\n\t\t\t\t\t// TS can't quite handle the polymorphism here but this is fine.\n\t\t\t\t\thandler()\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (state.type === 'entityRealm' && state.fieldsWithPendingConnectionUpdates) {\n\t\t\t\tfor (const updatedField of state.fieldsWithPendingConnectionUpdates) {\n\t\t\t\t\tconst listeners = this.getEventListeners(state, { type: 'connectionUpdate', key: updatedField })\n\t\t\t\t\tif (!listeners) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tlistener(state.getAccessor())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch (state.type) {\n\t\t\t\tcase 'entityRealm':\n\t\t\t\tcase 'entityList': {\n\t\t\t\t\tif (state.childrenWithPendingUpdates !== undefined) {\n\t\t\t\t\t\tfor (const childState of state.childrenWithPendingUpdates) {\n\t\t\t\t\t\t\tagenda.push(childState)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstate.childrenWithPendingUpdates.clear()\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'field':\n\t\t\t\t\t// Do nothing\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(state)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async triggerAsyncMutatingEvent(eventType: 'beforePersist', options: AsyncBatchUpdatesOptions): Promise<void>\n\tprivate async triggerAsyncMutatingEvent(eventType: 'persistSuccess', options: PersistSuccessOptions): Promise<void>\n\tprivate async triggerAsyncMutatingEvent(\n\t\teventType: 'beforePersist' | 'persistSuccess',\n\t\toptions: AsyncBatchUpdatesOptions | PersistSuccessOptions,\n\t): Promise<void> {\n\t\tawait this.asyncTransaction(async () => {\n\t\t\t// TODO if an entity from here (or its parent) gets deleted, we need to remove stale handlers from here.\n\t\t\tconst callbackQueue: Array<\n\t\t\t\t[\n\t\t\t\t\t// The typings could be nicer but TS…\n\t\t\t\t\tStateINode,\n\t\t\t\t\t(\n\t\t\t\t\t\t| EntityAccessor.EntityEventListenerMap[typeof eventType]\n\t\t\t\t\t\t| EntityListAccessor.EntityListEventListenerMap[typeof eventType]\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t> = []\n\n\t\t\tfor (const [, subTreeState] of StateIterator.eachRootState(this.treeStore)) {\n\t\t\t\tfor (const iNode of StateIterator.depthFirstINodes(subTreeState)) {\n\t\t\t\t\tconst listeners = this.getEventListeners(iNode, { type: eventType }) ?? []\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tcallbackQueue.push([iNode, listener])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (\n\t\t\t\tlet waterfallDepth = 0;\n\t\t\t\twaterfallDepth < this.config.getValue(`${eventType}SettleLimit` as const);\n\t\t\t\twaterfallDepth++\n\t\t\t) {\n\t\t\t\tconst promiseReturns: Array<\n\t\t\t\t\tPromise<\n\t\t\t\t\t\t| void\n\t\t\t\t\t\t| EntityAccessor.EntityEventListenerMap[typeof eventType]\n\t\t\t\t\t\t| EntityListAccessor.EntityListEventListenerMap[typeof eventType]\n\t\t\t\t\t>\n\t\t\t\t> = []\n\t\t\t\tconst correspondingStates: Array<StateINode> = []\n\n\t\t\t\tif (callbackQueue.length === 0) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tfor (const [state, callback] of callbackQueue) {\n\t\t\t\t\tcorrespondingStates.push(state)\n\t\t\t\t\tconst changesCountBefore = this.dirtinessTracker.getTotalTouchCount()\n\t\t\t\t\tlet validateChanges = false\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = callback(state.getAccessor as any, options as any) // TS can't quite handle this but this is sound.\n\t\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\t\tvalidateChanges = true\n\t\t\t\t\t\t\tpromiseReturns.push(result)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpromiseReturns.push(Promise.resolve(result))\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tpromiseReturns.push(Promise.reject(e))\n\t\t\t\t\t}\n\t\t\t\t\tif (validateChanges) {\n\t\t\t\t\t\tthis.validateWithoutChanges(changesCountBefore, eventType)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// TODO timeout\n\n\t\t\t\tconst changesCountBefore = this.dirtinessTracker.getTotalTouchCount()\n\t\t\t\tconst newCallbacks = await Promise.allSettled(promiseReturns)\n\t\t\t\tthis.validateWithoutChanges(changesCountBefore, eventType)\n\n\t\t\t\tcallbackQueue.length = 0 // Empties the queue\n\n\t\t\t\t// TODO we're drifting away from the original depth-first order. Let's see if that's ever even an issue.\n\t\t\t\tfor (const newlyInitialized of this.newlyInitializedWithListeners) {\n\t\t\t\t\tif (newlyInitialized.type === 'field') {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst beforePersistHandlers = this.getEventListeners(newlyInitialized, { type: eventType })\n\t\t\t\t\tif (beforePersistHandlers) {\n\t\t\t\t\t\tfor (const listener of beforePersistHandlers) {\n\t\t\t\t\t\t\tcallbackQueue.push([newlyInitialized, listener])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.triggerBeforeFlushEvents()\n\t\t\t\tthis.handleRejections(eventType, newCallbacks)\n\n\t\t\t\tfor (let i = 0; i < newCallbacks.length; i++) {\n\t\t\t\t\tconst result = newCallbacks[i]\n\t\t\t\t\tconst correspondingState = correspondingStates[i]\n\n\t\t\t\t\tif (result.status === 'fulfilled') {\n\t\t\t\t\t\tif (typeof result.value === 'function') {\n\t\t\t\t\t\t\tcallbackQueue.push([correspondingState, result.value])\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Otherwise do nothing. This is just a handler that albeit async, doesn't appear to\n\t\t\t\t\t\t// interact with data binding.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tif (callbackQueue.length) {\n\t\t\t\t\tthrow new BindingError(\n\t\t\t\t\t\t`Exceeded the ${eventType} settle limit. Your code likely contains a deadlock. `\n\t\t\t\t\t\t\t+ `If that's not the case, raise the settle limit from DataBindingProvider.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate triggerBeforeFlushEvents() {\n\t\tthis.syncTransaction(() => {\n\t\t\tconst settleLimit = this.config.getValue('beforeUpdateSettleLimit')\n\n\t\t\tfor (let attemptNumber = 0; attemptNumber < settleLimit; attemptNumber++) {\n\t\t\t\tif (!this.pendingWithBeforeUpdate.size) {\n\t\t\t\t\tthis.triggerOnInitialize()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconst withBeforeUpdate = this.pendingWithBeforeUpdate\n\t\t\t\tthis.pendingWithBeforeUpdate = new Set()\n\n\t\t\t\tfor (const state of withBeforeUpdate) {\n\t\t\t\t\tconst listeners = this.getEventListeners(state, { type: 'beforeUpdate' })\n\t\t\t\t\tif (listeners === undefined) {\n\t\t\t\t\t\t// This can happen if the listener has unsubscribed since we added it to the set.\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tswitch (state.type) {\n\t\t\t\t\t\tcase 'field':\n\t\t\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\t\t\t;(listener as FieldAccessor.BeforeUpdateListener)(state.getAccessor())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase 'entityRealm':\n\t\t\t\t\t\tcase 'entityList':\n\t\t\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\t\t\tstate.getAccessor().batchUpdates(listener as any)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn assertNever(state)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.triggerOnInitialize()\n\t\t\t}\n\t\t\tthrow new BindingError(\n\t\t\t\t`Maximum stabilization limit of updates caused by 'beforeUpdate' exceeded. `\n\t\t\t\t\t+ `This likely means there is an infinite feedback loop in your code.`,\n\t\t\t)\n\t\t})\n\t}\n\n\tprivate triggerOnInitialize() {\n\t\tthis.syncTransaction(() => {\n\t\t\tfor (const state of this.newlyInitializedWithListeners) {\n\t\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\t\tconst listeners = state.type === 'field'\n\t\t\t\t\t? this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\t\t\t\t\t: state.type === 'entityRealm'\n\t\t\t\t\t? this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\t\t\t\t\t: this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\n\t\t\t\tif (listeners) {\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tlistener()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (state.type === 'entityRealm') {\n\t\t\t\t\tstate.entity.hasIdSetInStone = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.newlyInitializedWithListeners.clear()\n\t\t})\n\t}\n\n\tpublic async triggerOnPersistError(options: PersistErrorOptions) {\n\t\tawait this.asyncTransaction(async () => {\n\t\t\tconst handlerPromises: Array<Promise<void>> = []\n\n\t\t\tfor (const [, subTreeState] of StateIterator.eachRootState(this.treeStore)) {\n\t\t\t\tfor (const iNode of StateIterator.depthFirstINodes(subTreeState)) {\n\t\t\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\t\t\tconst dispatchers = iNode.type === 'entityRealm'\n\t\t\t\t\t\t? this.getEventDispatchers(iNode, { type: 'persistError' }, [iNode.getAccessor, options])\n\t\t\t\t\t\t: this.getEventDispatchers(iNode, { type: 'persistError' }, [iNode.getAccessor, options])\n\t\t\t\t\tif (dispatchers === undefined) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfor (const listener of dispatchers ?? []) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = listener()\n\t\t\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\t\t\thandlerPromises.push(result)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\thandlerPromises.push(Promise.resolve(result))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\thandlerPromises.push(Promise.reject(e))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO timeout\n\t\t\tconst handlerResults = await Promise.allSettled(handlerPromises)\n\t\t\tthis.handleRejections('persistError', handlerResults)\n\t\t})\n\t}\n\n\tpublic async triggerOnBeforePersist() {\n\t\treturn this.triggerAsyncMutatingEvent('beforePersist', this.asyncBatchUpdatesOptions)\n\t}\n\n\tpublic async triggerOnPersistSuccess(options: PersistSuccessOptions) {\n\t\treturn this.triggerAsyncMutatingEvent('persistSuccess', options)\n\t}\n\n\tpublic getEventListeners<\n\t\tState extends StateNode,\n\t\tEventListenerTypes extends Exclude<State['eventListeners'], undefined> extends EventListenersStore<infer Map> ? [keyof Map, Map] : never,\n\t\tEventType extends EventListenerTypes[0],\n\t>(state: State, event: { type: EventType; key?: string }): Set<Exclude<EventListenerTypes[1][EventType], undefined>> | undefined {\n\t\tif (!state.eventListeners) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn (state.eventListeners as EventListenersStore<EventListenerTypes[1]>).get(event) as Set<\n\t\t\tExclude<EventListenerTypes[1][EventType], undefined>\n\t\t>\n\t}\n\n\tpublic getEventDispatchers<\n\t\tState extends StateNode,\n\t\tEventListenerTypes extends Exclude<State['eventListeners'], undefined> extends EventListenersStore<infer Map> ? [keyof Map, Map] : never,\n\t\tEventType extends EventListenerTypes[0],\n\t>(\n\t\tstate: State,\n\t\tevent: { type: EventType; key?: string },\n\t\tlistenerArgs: Parameters<Exclude<EventListenerTypes[1][EventType], undefined>>,\n\t): Array<() => ReturnType<Exclude<EventListenerTypes[1][EventType], undefined>>> | undefined {\n\t\tconst eventListeners = this.getEventListeners(state, event)\n\t\tif (eventListeners === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn Array.from(eventListeners.values(), listener => {\n\t\t\treturn () => listener(...listenerArgs)\n\t\t}) as Array<() => ReturnType<Exclude<EventListenerTypes[1][EventType], undefined>>>\n\t}\n\n\tprivate handleRejections(handler: string, promises: PromiseSettledResult<any>[]) {\n\t\tconst rejections = promises.filter((it): it is PromiseRejectedResult => it.status === 'rejected')\n\t\tif (rejections.length === 0) {\n\t\t\treturn\n\t\t}\n\t\trejections.forEach(it => console.error(it.reason))\n\t\tif (import.meta.env.DEV) {\n\t\t\tthrow new BindingError(\n\t\t\t\t`A ${handler} handler returned a promise that rejected. `\n\t\t\t\t\t+ `This is a no-op that will fail silently in production.`,\n\t\t\t)\n\t\t}\n\t}\n\n\tprivate validateWithoutChanges(initialCount: number, eventType: string): void {\n\t\tconst changesCountAfter = this.dirtinessTracker.getTotalTouchCount()\n\t\tif (import.meta.env.DEV) {\n\t\t\tif (initialCount !== changesCountAfter) {\n\t\t\t\t// This isn't bulletproof. They could e.g. undo a change and make another one which would\n\t\t\t\t// slip through this detection. But for most cases, it should be good enough and not too expensive.\n\t\t\t\tthrow new BindingError(\n\t\t\t\t\t`A ${eventType} event handler cannot be asynchronous and alter the accessor tree at the same time. `\n\t\t\t\t\t\t+ `To achieve this, prepare your data asynchronously but only touch the tree from a returned callback.`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}\n"],"names":["BindingError","getEntityMarker","assertNever","StateIterator","changesCountBefore"],"mappings":";;;;;;;;AAoBO,MAAM,aAAa;AAAA,EAiBlB,YACW,0BACA,qBACA,QACA,kBACA,UACA,WACA,gBAChB;AAPgB,SAAA,2BAAA;AACA,SAAA,sBAAA;AACA,SAAA,SAAA;AACA,SAAA,mBAAA;AACA,SAAA,WAAA;AACA,SAAA,YAAA;AACA,SAAA,iBAAA;AArBlB,kBAAA,MAAQ,oBAAmB,CAAA;AAC3B,kBAAA,MAAQ,yBAA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AAAA,EAEO,oBAKN,OACA,OACA,cAC4F;AAC5F,UAAM,iBAAiB,KAAK,kBAAkB,OAAO,KAAK;AAC1D,QAAI,mBAAmB,QAAW;AACjC,aAAO;AAAA,IACR;AACA,WAAO,MAAM,KAAK,eAAe,OAAA,GAAU,CAAA,aAAY;AACtD,aAAO,MAAM,SAAS,GAAG,YAAY;AAAA,IACtC,CAAC;AAAA,EACF;AAAA,EAEQ,iBAAiB,SAAiB,UAAuC;AAChF,UAAM,aAAa,SAAS,OAAO,CAAC,OAAoC,GAAG,WAAW,UAAU;AAChG,QAAI,WAAW,WAAW,GAAG;AAC5B;AAAA,IACD;AACA,eAAW,QAAQ,CAAA,OAAM,QAAQ,MAAM,GAAG,MAAM,CAAC;AACxB;AACxB,YAAM,IAAIH,cAAAA;AAAAA,QACT,KAAK,OAAO;AAAA,MAAA;AAAA,IAGd;AAAA,EACD;AAAA,EAEQ,uBAAuB,cAAsB,WAAyB;AAC7E,UAAM,oBAAoB,KAAK,iBAAiB,mBAAA;AACvB;AACxB,UAAI,iBAAiB,mBAAmB;AAGvC,cAAM,IAAIA,cAAAA;AAAAA,UACT,KAAK,SAAS;AAAA,QAAA;AAAA,MAGhB;AAAA,IACD;AAAA,EACD;AACD;AAjjBC,cADY,cACW,yBAAwB,CAAA;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EventManager.js","sources":["../../../../../packages/binding-legacy/src/core/EventManager.ts"],"sourcesContent":["import type {\n\tAsyncBatchUpdatesOptions,\n\tBatchUpdatesOptions,\n\tEntityAccessor,\n\tEntityListAccessor,\n\tFieldAccessor,\n\tPersistErrorOptions,\n\tPersistSuccessOptions,\n} from '@contember/binding-common'\nimport type { SuccessfulPersistResult } from '@contember/binding-common'\nimport { BindingError } from '@contember/binding-common'\nimport type { PlaceholderName } from '@contember/binding-common'\nimport { assertNever } from '@contember/binding-common'\nimport type { Config } from './Config'\nimport type { DirtinessTracker } from './DirtinessTracker'\nimport { EntityListState, EntityRealmState, FieldState, getEntityMarker, RootStateNode, StateINode, StateIterator, StateNode } from './state'\nimport type { TreeStore } from './TreeStore'\nimport type { UpdateMetadata } from './UpdateMetadata'\nimport type { EventListenersStore } from '@contember/binding-common'\n\nexport class EventManager {\n\tpublic static readonly NO_CHANGES_DIFFERENCE = 0\n\n\tprivate transactionDepth = 0\n\tprivate isFrozenWhileUpdating = false\n\n\t// This should ideally not exists as it should be synonymous to `this.ongoingPersistOperation !== undefined`\n\t// but it makes persist-related promise juggling significantly more straightforward.\n\tprivate isMutating: boolean = false\n\tprivate ongoingPersistOperation: Promise<SuccessfulPersistResult> | undefined = undefined\n\n\tprivate previousMetadata: UpdateMetadata | undefined = undefined\n\n\tprivate newlyInitializedWithListeners: Set<EntityListState | EntityRealmState | FieldState> = new Set()\n\tprivate pendingWithBeforeUpdate: Set<StateNode> = new Set()\n\tprivate rootsWithPendingUpdates: Set<RootStateNode> = new Set()\n\n\tpublic constructor(\n\t\tprivate readonly asyncBatchUpdatesOptions: AsyncBatchUpdatesOptions,\n\t\tprivate readonly batchUpdatesOptions: BatchUpdatesOptions,\n\t\tprivate readonly config: Config,\n\t\tprivate readonly dirtinessTracker: DirtinessTracker,\n\t\tprivate readonly onUpdate: (metadata: UpdateMetadata) => void,\n\t\tprivate readonly treeStore: TreeStore,\n\t\tprivate readonly batchedUpdates: (callback: () => any) => void,\n\t) {}\n\n\tpublic async persistOperation(operation: () => Promise<SuccessfulPersistResult>): Promise<SuccessfulPersistResult> {\n\t\tif (this.ongoingPersistOperation !== undefined) {\n\t\t\tif (this.isMutating) {\n\t\t\t\tthrow new BindingError(`Cannot trigger a persist whilst another one is ongoing!`)\n\t\t\t}\n\t\t\treturn await this.ongoingPersistOperation\n\t\t}\n\t\tif (this.transactionDepth > 0) {\n\t\t\tthrow new BindingError(`Cannot trigger a persist whilst batching updates!`)\n\t\t}\n\t\treturn await (this.ongoingPersistOperation = new Promise<SuccessfulPersistResult>(async (resolve, reject) => {\n\t\t\tawait Promise.resolve()\n\n\t\t\tthis.isMutating = true\n\t\t\tthis.flushUpdates() // Let the world know that we're mutating\n\n\t\t\ttry {\n\t\t\t\tresolve(await this.asyncOperation(operation))\n\t\t\t} catch (e) {\n\t\t\t\tif (!(typeof e === 'object' && e !== null && 'type' in e && e.type === 'invalidInput')) {\n\t\t\t\t\tconsole.error('PersistError', e)\n\t\t\t\t}\n\t\t\t\treject(e)\n\t\t\t} finally {\n\t\t\t\tthis.ongoingPersistOperation = undefined\n\t\t\t\tthis.isMutating = false\n\t\t\t\tthis.flushUpdates()\n\t\t\t}\n\t\t}))\n\t}\n\n\tpublic syncTransaction<T>(transaction: () => T) {\n\t\ttry {\n\t\t\tthis.transactionDepth++\n\t\t\treturn transaction()\n\t\t} finally {\n\t\t\tthis.transactionDepth--\n\t\t}\n\t}\n\tpublic syncOperation<T>(operation: () => T) {\n\t\tconst result = this.syncTransaction(operation)\n\t\tthis.flushUpdates()\n\t\treturn result\n\t}\n\n\tpublic async asyncTransaction<T>(transaction: () => Promise<T>): Promise<T> {\n\t\ttry {\n\t\t\tthis.transactionDepth++\n\t\t\treturn await transaction()\n\t\t} finally {\n\t\t\tthis.transactionDepth--\n\t\t}\n\t}\n\tpublic async asyncOperation<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = await this.asyncTransaction(operation)\n\t\tthis.flushUpdates()\n\t\treturn result\n\t}\n\n\tprivate flushUpdates() {\n\t\tif (this.transactionDepth > 0) {\n\t\t\treturn\n\t\t}\n\n\t\tif (this.isFrozenWhileUpdating) {\n\t\t\tthrow new BindingError(\n\t\t\t\t`Trying to perform an update while the whole accessor tree is already updating. This is most likely caused `\n\t\t\t\t\t+ `by updating the accessor tree while rendering or from within the 'update' event handler, which is a no-op. `\n\t\t\t\t\t+ `If you wish to mutate the tree in reaction to other changes, use the 'beforeUpdate' event.`,\n\t\t\t)\n\t\t}\n\n\t\tconst newMetadata = this.getNewUpdateMetadata()\n\n\t\tif (!this.shouldFlushUpdates(newMetadata)) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.batchedUpdates(() => {\n\t\t\tthis.isFrozenWhileUpdating = true\n\t\t\tthis.triggerBeforeFlushEvents()\n\t\t\tthis.onUpdate(newMetadata)\n\t\t\tconst rootStates = Array.from(this.rootsWithPendingUpdates)\n\t\t\tthis.flushPendingAccessorUpdates(rootStates)\n\t\t\tthis.rootsWithPendingUpdates.clear()\n\t\t\tthis.isFrozenWhileUpdating = false\n\t\t\tthis.previousMetadata = newMetadata\n\t\t})\n\t}\n\n\tprivate getNewUpdateMetadata(): UpdateMetadata {\n\t\treturn {\n\t\t\tisMutating: this.isMutating,\n\t\t}\n\t}\n\n\tprivate shouldFlushUpdates(newMetadata: UpdateMetadata): boolean {\n\t\tif (this.transactionDepth > 0) {\n\t\t\treturn false\n\t\t}\n\t\tif (this.previousMetadata === undefined) {\n\t\t\treturn true\n\t\t}\n\t\tif (this.rootsWithPendingUpdates.size) {\n\t\t\treturn true\n\t\t}\n\t\tfor (const key in newMetadata) {\n\t\t\tconst fromPrevious = this.previousMetadata[key as keyof UpdateMetadata]\n\t\t\tconst fromNew = newMetadata[key as keyof UpdateMetadata]\n\n\t\t\tif (!Object.is(fromPrevious, fromNew)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tpublic registerNewlyInitialized(newlyInitialized: StateNode) {\n\t\tconst initializeListeners = this.getEventListeners(newlyInitialized, { type: 'initialize' })\n\n\t\tif (initializeListeners === undefined) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.newlyInitializedWithListeners.add(newlyInitialized)\n\n\t\tif (this.transactionDepth === 0) {\n\t\t\tthis.triggerOnInitialize()\n\t\t}\n\t}\n\n\tpublic registerUpdatedConnection(parentState: EntityRealmState, placeholderName: PlaceholderName) {\n\t\tif (parentState.fieldsWithPendingConnectionUpdates === undefined) {\n\t\t\tparentState.fieldsWithPendingConnectionUpdates = new Set()\n\t\t}\n\n\t\tconst marker = getEntityMarker(parentState)\n\t\tplaceholders: for (const [fieldName, placeholdersByField] of marker.fields.placeholders) {\n\t\t\tif (typeof placeholdersByField === 'string') {\n\t\t\t\tif (placeholdersByField === placeholderName) {\n\t\t\t\t\tparentState.fieldsWithPendingConnectionUpdates.add(fieldName)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (const placeholderByFieldName of placeholdersByField) {\n\t\t\t\t\tif (placeholderByFieldName === placeholderName) {\n\t\t\t\t\t\tparentState.fieldsWithPendingConnectionUpdates.add(fieldName)\n\t\t\t\t\t\tcontinue placeholders\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic registerJustUpdated(justUpdated: StateNode, changesDelta: number) {\n\t\tconst beforeUpdateListeners = this.getEventListeners(justUpdated, { type: 'beforeUpdate' })\n\t\tif (beforeUpdateListeners !== undefined) {\n\t\t\tthis.pendingWithBeforeUpdate.add(justUpdated)\n\t\t}\n\t\tjustUpdated.accessor = undefined\n\n\t\tswitch (justUpdated.type) {\n\t\t\tcase 'entityRealm':\n\t\t\tcase 'entityList': {\n\t\t\t\tjustUpdated.unpersistedChangesCount += changesDelta\n\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tif (justUpdated.unpersistedChangesCount < 0) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t`We have *JUST* reached a completely invalid state. From now on, anything can (and likely will) `\n\t\t\t\t\t\t\t\t+ `go wrong. This is definitely a bug. Please try to report whatever led to this situation.`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst parent = justUpdated.blueprint.parent\n\n\t\t\t\tif (parent === undefined) {\n\t\t\t\t\tthis.rootsWithPendingUpdates.add(justUpdated)\n\n\t\t\t\t\tif (\n\t\t\t\t\t\t!(justUpdated.blueprint.type === 'subTree' && justUpdated.blueprint.marker.parameters.isCreating\n\t\t\t\t\t\t\t&& justUpdated.blueprint.marker.parameters.isUnpersisted)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.dirtinessTracker.increaseBy(changesDelta)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (!parent.childrenWithPendingUpdates) {\n\t\t\t\t\t\tparent.childrenWithPendingUpdates = new Set()\n\t\t\t\t\t}\n\t\t\t\t\tparent.childrenWithPendingUpdates.add(justUpdated as any)\n\t\t\t\t\tthis.registerJustUpdated(parent, changesDelta)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'field': {\n\t\t\t\tconst parent = justUpdated.parent\n\t\t\t\tif (!parent.childrenWithPendingUpdates) {\n\t\t\t\t\tparent.childrenWithPendingUpdates = new Set()\n\t\t\t\t}\n\t\t\t\tparent.childrenWithPendingUpdates.add(justUpdated as any)\n\t\t\t\tthis.registerJustUpdated(justUpdated.parent, changesDelta)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate flushPendingAccessorUpdates(rootStates: Array<StateINode>) {\n\t\t// It is *CRUCIAL* that this is a BFS so that we update the components in top-down order.\n\t\tconst agenda: StateNode[] = rootStates\n\n\t\tfor (const state of agenda) {\n\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\tconst updateListeners = state.type === 'field'\n\t\t\t\t? this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\t\t\t\t: state.type === 'entityRealm'\n\t\t\t\t? this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\t\t\t\t: this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\n\t\t\tif (updateListeners !== undefined) {\n\t\t\t\tfor (const handler of updateListeners) {\n\t\t\t\t\t// TS can't quite handle the polymorphism here but this is fine.\n\t\t\t\t\thandler()\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (state.type === 'entityRealm' && state.fieldsWithPendingConnectionUpdates) {\n\t\t\t\tfor (const updatedField of state.fieldsWithPendingConnectionUpdates) {\n\t\t\t\t\tconst listeners = this.getEventListeners(state, { type: 'connectionUpdate', key: updatedField })\n\t\t\t\t\tif (!listeners) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tlistener(state.getAccessor())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch (state.type) {\n\t\t\t\tcase 'entityRealm':\n\t\t\t\tcase 'entityList': {\n\t\t\t\t\tif (state.childrenWithPendingUpdates !== undefined) {\n\t\t\t\t\t\tfor (const childState of state.childrenWithPendingUpdates) {\n\t\t\t\t\t\t\tagenda.push(childState)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstate.childrenWithPendingUpdates.clear()\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'field':\n\t\t\t\t\t// Do nothing\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(state)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async triggerAsyncMutatingEvent(eventType: 'beforePersist', options: AsyncBatchUpdatesOptions): Promise<void>\n\tprivate async triggerAsyncMutatingEvent(eventType: 'persistSuccess', options: PersistSuccessOptions): Promise<void>\n\tprivate async triggerAsyncMutatingEvent(\n\t\teventType: 'beforePersist' | 'persistSuccess',\n\t\toptions: AsyncBatchUpdatesOptions | PersistSuccessOptions,\n\t): Promise<void> {\n\t\tawait this.asyncTransaction(async () => {\n\t\t\t// TODO if an entity from here (or its parent) gets deleted, we need to remove stale handlers from here.\n\t\t\tconst callbackQueue: Array<\n\t\t\t\t[\n\t\t\t\t\t// The typings could be nicer but TS…\n\t\t\t\t\tStateINode,\n\t\t\t\t\t(\n\t\t\t\t\t\t| EntityAccessor.EntityEventListenerMap[typeof eventType]\n\t\t\t\t\t\t| EntityListAccessor.EntityListEventListenerMap[typeof eventType]\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t> = []\n\n\t\t\tfor (const [, subTreeState] of StateIterator.eachRootState(this.treeStore)) {\n\t\t\t\tfor (const iNode of StateIterator.depthFirstINodes(subTreeState)) {\n\t\t\t\t\tconst listeners = this.getEventListeners(iNode, { type: eventType }) ?? []\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tcallbackQueue.push([iNode, listener])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (\n\t\t\t\tlet waterfallDepth = 0;\n\t\t\t\twaterfallDepth < this.config.getValue(`${eventType}SettleLimit` as const);\n\t\t\t\twaterfallDepth++\n\t\t\t) {\n\t\t\t\tconst promiseReturns: Array<\n\t\t\t\t\tPromise<\n\t\t\t\t\t\t| void\n\t\t\t\t\t\t| EntityAccessor.EntityEventListenerMap[typeof eventType]\n\t\t\t\t\t\t| EntityListAccessor.EntityListEventListenerMap[typeof eventType]\n\t\t\t\t\t>\n\t\t\t\t> = []\n\t\t\t\tconst correspondingStates: Array<StateINode> = []\n\n\t\t\t\tif (callbackQueue.length === 0) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tfor (const [state, callback] of callbackQueue) {\n\t\t\t\t\tcorrespondingStates.push(state)\n\t\t\t\t\tconst changesCountBefore = this.dirtinessTracker.getTotalTouchCount()\n\t\t\t\t\tlet validateChanges = false\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = callback(state.getAccessor as any, options as any) // TS can't quite handle this but this is sound.\n\t\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\t\tvalidateChanges = true\n\t\t\t\t\t\t\tpromiseReturns.push(result)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpromiseReturns.push(Promise.resolve(result))\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tpromiseReturns.push(Promise.reject(e))\n\t\t\t\t\t}\n\t\t\t\t\tif (validateChanges) {\n\t\t\t\t\t\tthis.validateWithoutChanges(changesCountBefore, eventType)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// TODO timeout\n\n\t\t\t\tconst changesCountBefore = this.dirtinessTracker.getTotalTouchCount()\n\t\t\t\tconst newCallbacks = await Promise.allSettled(promiseReturns)\n\t\t\t\tthis.validateWithoutChanges(changesCountBefore, eventType)\n\n\t\t\t\tcallbackQueue.length = 0 // Empties the queue\n\n\t\t\t\t// TODO we're drifting away from the original depth-first order. Let's see if that's ever even an issue.\n\t\t\t\tfor (const newlyInitialized of this.newlyInitializedWithListeners) {\n\t\t\t\t\tif (newlyInitialized.type === 'field') {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst beforePersistHandlers = this.getEventListeners(newlyInitialized, { type: eventType })\n\t\t\t\t\tif (beforePersistHandlers) {\n\t\t\t\t\t\tfor (const listener of beforePersistHandlers) {\n\t\t\t\t\t\t\tcallbackQueue.push([newlyInitialized, listener])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.triggerBeforeFlushEvents()\n\t\t\t\tthis.handleRejections(eventType, newCallbacks)\n\n\t\t\t\tfor (let i = 0; i < newCallbacks.length; i++) {\n\t\t\t\t\tconst result = newCallbacks[i]\n\t\t\t\t\tconst correspondingState = correspondingStates[i]\n\n\t\t\t\t\tif (result.status === 'fulfilled') {\n\t\t\t\t\t\tif (typeof result.value === 'function') {\n\t\t\t\t\t\t\tcallbackQueue.push([correspondingState, result.value])\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Otherwise do nothing. This is just a handler that albeit async, doesn't appear to\n\t\t\t\t\t\t// interact with data binding.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tif (callbackQueue.length) {\n\t\t\t\t\tthrow new BindingError(\n\t\t\t\t\t\t`Exceeded the ${eventType} settle limit. Your code likely contains a deadlock. `\n\t\t\t\t\t\t\t+ `If that's not the case, raise the settle limit from DataBindingProvider.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate triggerBeforeFlushEvents() {\n\t\tthis.syncTransaction(() => {\n\t\t\tconst settleLimit = this.config.getValue('beforeUpdateSettleLimit')\n\n\t\t\tfor (let attemptNumber = 0; attemptNumber < settleLimit; attemptNumber++) {\n\t\t\t\tif (!this.pendingWithBeforeUpdate.size) {\n\t\t\t\t\tthis.triggerOnInitialize()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconst withBeforeUpdate = this.pendingWithBeforeUpdate\n\t\t\t\tthis.pendingWithBeforeUpdate = new Set()\n\n\t\t\t\tfor (const state of withBeforeUpdate) {\n\t\t\t\t\tconst listeners = this.getEventListeners(state, { type: 'beforeUpdate' })\n\t\t\t\t\tif (listeners === undefined) {\n\t\t\t\t\t\t// This can happen if the listener has unsubscribed since we added it to the set.\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tswitch (state.type) {\n\t\t\t\t\t\tcase 'field':\n\t\t\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\t\t\t;(listener as FieldAccessor.BeforeUpdateListener)(state.getAccessor())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase 'entityRealm':\n\t\t\t\t\t\tcase 'entityList':\n\t\t\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\t\t\tstate.getAccessor().batchUpdates(listener as any)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn assertNever(state)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.triggerOnInitialize()\n\t\t\t}\n\t\t\tthrow new BindingError(\n\t\t\t\t`Maximum stabilization limit of updates caused by 'beforeUpdate' exceeded. `\n\t\t\t\t\t+ `This likely means there is an infinite feedback loop in your code.`,\n\t\t\t)\n\t\t})\n\t}\n\n\tprivate triggerOnInitialize() {\n\t\tthis.syncTransaction(() => {\n\t\t\tfor (const state of this.newlyInitializedWithListeners) {\n\t\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\t\tconst listeners = state.type === 'field'\n\t\t\t\t\t? this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\t\t\t\t\t: state.type === 'entityRealm'\n\t\t\t\t\t? this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\t\t\t\t\t: this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\n\t\t\t\tif (listeners) {\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tlistener()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (state.type === 'entityRealm') {\n\t\t\t\t\tstate.entity.hasIdSetInStone = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.newlyInitializedWithListeners.clear()\n\t\t})\n\t}\n\n\tpublic async triggerOnPersistError(options: PersistErrorOptions) {\n\t\tawait this.asyncTransaction(async () => {\n\t\t\tconst handlerPromises: Array<Promise<void>> = []\n\n\t\t\tfor (const [, subTreeState] of StateIterator.eachRootState(this.treeStore)) {\n\t\t\t\tfor (const iNode of StateIterator.depthFirstINodes(subTreeState)) {\n\t\t\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\t\t\tconst dispatchers = iNode.type === 'entityRealm'\n\t\t\t\t\t\t? this.getEventDispatchers(iNode, { type: 'persistError' }, [iNode.getAccessor, options])\n\t\t\t\t\t\t: this.getEventDispatchers(iNode, { type: 'persistError' }, [iNode.getAccessor, options])\n\t\t\t\t\tif (dispatchers === undefined) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfor (const listener of dispatchers ?? []) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = listener()\n\t\t\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\t\t\thandlerPromises.push(result)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\thandlerPromises.push(Promise.resolve(result))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\thandlerPromises.push(Promise.reject(e))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO timeout\n\t\t\tconst handlerResults = await Promise.allSettled(handlerPromises)\n\t\t\tthis.handleRejections('persistError', handlerResults)\n\t\t})\n\t}\n\n\tpublic async triggerOnBeforePersist() {\n\t\treturn this.triggerAsyncMutatingEvent('beforePersist', this.asyncBatchUpdatesOptions)\n\t}\n\n\tpublic async triggerOnPersistSuccess(options: PersistSuccessOptions) {\n\t\treturn this.triggerAsyncMutatingEvent('persistSuccess', options)\n\t}\n\n\tpublic getEventListeners<\n\t\tState extends StateNode,\n\t\tEventListenerTypes extends Exclude<State['eventListeners'], undefined> extends EventListenersStore<infer Map> ? [keyof Map, Map] : never,\n\t\tEventType extends EventListenerTypes[0],\n\t>(state: State, event: { type: EventType; key?: string }): Set<Exclude<EventListenerTypes[1][EventType], undefined>> | undefined {\n\t\tif (!state.eventListeners) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn (state.eventListeners as EventListenersStore<EventListenerTypes[1]>).get(event) as Set<\n\t\t\tExclude<EventListenerTypes[1][EventType], undefined>\n\t\t>\n\t}\n\n\tpublic getEventDispatchers<\n\t\tState extends StateNode,\n\t\tEventListenerTypes extends Exclude<State['eventListeners'], undefined> extends EventListenersStore<infer Map> ? [keyof Map, Map] : never,\n\t\tEventType extends EventListenerTypes[0],\n\t>(\n\t\tstate: State,\n\t\tevent: { type: EventType; key?: string },\n\t\tlistenerArgs: Parameters<Exclude<EventListenerTypes[1][EventType], undefined>>,\n\t): Array<() => ReturnType<Exclude<EventListenerTypes[1][EventType], undefined>>> | undefined {\n\t\tconst eventListeners = this.getEventListeners(state, event)\n\t\tif (eventListeners === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn Array.from(eventListeners.values(), listener => {\n\t\t\treturn () => listener(...listenerArgs)\n\t\t}) as Array<() => ReturnType<Exclude<EventListenerTypes[1][EventType], undefined>>>\n\t}\n\n\tprivate handleRejections(handler: string, promises: PromiseSettledResult<any>[]) {\n\t\tconst rejections = promises.filter((it): it is PromiseRejectedResult => it.status === 'rejected')\n\t\tif (rejections.length === 0) {\n\t\t\treturn\n\t\t}\n\t\trejections.forEach(it => console.error(it.reason))\n\t\tif (import.meta.env.DEV) {\n\t\t\tthrow new BindingError(\n\t\t\t\t`A ${handler} handler returned a promise that rejected. `\n\t\t\t\t\t+ `This is a no-op that will fail silently in production.`,\n\t\t\t)\n\t\t}\n\t}\n\n\tprivate validateWithoutChanges(initialCount: number, eventType: string): void {\n\t\tconst changesCountAfter = this.dirtinessTracker.getTotalTouchCount()\n\t\tif (import.meta.env.DEV) {\n\t\t\tif (initialCount !== changesCountAfter) {\n\t\t\t\t// This isn't bulletproof. They could e.g. undo a change and make another one which would\n\t\t\t\t// slip through this detection. But for most cases, it should be good enough and not too expensive.\n\t\t\t\tthrow new BindingError(\n\t\t\t\t\t`A ${eventType} event handler cannot be asynchronous and alter the accessor tree at the same time. `\n\t\t\t\t\t\t+ `To achieve this, prepare your data asynchronously but only touch the tree from a returned callback.`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}\n"],"names":["changesCountBefore"],"mappings":";;;;;;AAoBO,MAAM,aAAa;AAAA,EAiBlB,YACW,0BACA,qBACA,QACA,kBACA,UACA,WACA,gBAChB;AAPgB,SAAA,2BAAA;AACA,SAAA,sBAAA;AACA,SAAA,SAAA;AACA,SAAA,mBAAA;AACA,SAAA,WAAA;AACA,SAAA,YAAA;AACA,SAAA,iBAAA;AArBlB,kBAAA,MAAQ,oBAAmB,CAAA;AAC3B,kBAAA,MAAQ,yBAAwB,KAAA;AAIhC,kBAAA,MAAQ,cAAsB,KAAA;AAC9B,kBAAA,MAAQ,yBAAA;AAER,kBAAA,MAAQ,kBAAA;AAER,kBAAA,MAAQ,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;AAAA,IACtC,CAAC;AAAA,EACF;AAAA,EAEQ,iBAAiB,SAAiB,UAAuC;AAChF,UAAM,aAAa,SAAS,OAAO,CAAC,OAAoC,GAAG,WAAW,UAAU;AAChG,QAAI,WAAW,WAAW,GAAG;AAC5B;AAAA,IACD;AACA,eAAW,QAAQ,CAAA,OAAM,QAAQ,MAAM,GAAG,MAAM,CAAC;AACxB;AACxB,YAAM,IAAI;AAAA,QACT,KAAK,OAAO;AAAA,MAAA;AAAA,IAGd;AAAA,EACD;AAAA,EAEQ,uBAAuB,cAAsB,WAAyB;AAC7E,UAAM,oBAAoB,KAAK,iBAAiB,mBAAA;AACvB;AACxB,UAAI,iBAAiB,mBAAmB;AAGvC,cAAM,IAAI;AAAA,UACT,KAAK,SAAS;AAAA,QAAA;AAAA,MAGhB;AAAA,IACD;AAAA,EACD;AACD;AAjjBC,cADY,cACW,yBAAwB,CAAA;"}
|
|
1
|
+
{"version":3,"file":"EventManager.js","sources":["../../../../../packages/binding-legacy/src/core/EventManager.ts"],"sourcesContent":["import type {\n\tAsyncBatchUpdatesOptions,\n\tBatchUpdatesOptions,\n\tEntityAccessor,\n\tEntityListAccessor,\n\tFieldAccessor,\n\tPersistErrorOptions,\n\tPersistSuccessOptions,\n} from '@contember/binding-common'\nimport type { SuccessfulPersistResult } from '@contember/binding-common'\nimport { BindingError } from '@contember/binding-common'\nimport type { PlaceholderName } from '@contember/binding-common'\nimport { assertNever } from '@contember/binding-common'\nimport type { Config } from './Config.js'\nimport type { DirtinessTracker } from './DirtinessTracker.js'\nimport { EntityListState, EntityRealmState, FieldState, getEntityMarker, RootStateNode, StateINode, StateIterator, StateNode } from './state/index.js'\nimport type { TreeStore } from './TreeStore.js'\nimport type { UpdateMetadata } from './UpdateMetadata.js'\nimport type { EventListenersStore } from '@contember/binding-common'\n\nexport class EventManager {\n\tpublic static readonly NO_CHANGES_DIFFERENCE = 0\n\n\tprivate transactionDepth = 0\n\tprivate isFrozenWhileUpdating = false\n\n\t// This should ideally not exists as it should be synonymous to `this.ongoingPersistOperation !== undefined`\n\t// but it makes persist-related promise juggling significantly more straightforward.\n\tprivate isMutating: boolean = false\n\tprivate ongoingPersistOperation: Promise<SuccessfulPersistResult> | undefined = undefined\n\n\tprivate previousMetadata: UpdateMetadata | undefined = undefined\n\n\tprivate newlyInitializedWithListeners: Set<EntityListState | EntityRealmState | FieldState> = new Set()\n\tprivate pendingWithBeforeUpdate: Set<StateNode> = new Set()\n\tprivate rootsWithPendingUpdates: Set<RootStateNode> = new Set()\n\n\tpublic constructor(\n\t\tprivate readonly asyncBatchUpdatesOptions: AsyncBatchUpdatesOptions,\n\t\tprivate readonly batchUpdatesOptions: BatchUpdatesOptions,\n\t\tprivate readonly config: Config,\n\t\tprivate readonly dirtinessTracker: DirtinessTracker,\n\t\tprivate readonly onUpdate: (metadata: UpdateMetadata) => void,\n\t\tprivate readonly treeStore: TreeStore,\n\t\tprivate readonly batchedUpdates: (callback: () => any) => void,\n\t) {}\n\n\tpublic async persistOperation(operation: () => Promise<SuccessfulPersistResult>): Promise<SuccessfulPersistResult> {\n\t\tif (this.ongoingPersistOperation !== undefined) {\n\t\t\tif (this.isMutating) {\n\t\t\t\tthrow new BindingError(`Cannot trigger a persist whilst another one is ongoing!`)\n\t\t\t}\n\t\t\treturn await this.ongoingPersistOperation\n\t\t}\n\t\tif (this.transactionDepth > 0) {\n\t\t\tthrow new BindingError(`Cannot trigger a persist whilst batching updates!`)\n\t\t}\n\t\treturn await (this.ongoingPersistOperation = new Promise<SuccessfulPersistResult>(async (resolve, reject) => {\n\t\t\tawait Promise.resolve()\n\n\t\t\tthis.isMutating = true\n\t\t\tthis.flushUpdates() // Let the world know that we're mutating\n\n\t\t\ttry {\n\t\t\t\tresolve(await this.asyncOperation(operation))\n\t\t\t} catch (e) {\n\t\t\t\tif (!(typeof e === 'object' && e !== null && 'type' in e && e.type === 'invalidInput')) {\n\t\t\t\t\tconsole.error('PersistError', e)\n\t\t\t\t}\n\t\t\t\treject(e)\n\t\t\t} finally {\n\t\t\t\tthis.ongoingPersistOperation = undefined\n\t\t\t\tthis.isMutating = false\n\t\t\t\tthis.flushUpdates()\n\t\t\t}\n\t\t}))\n\t}\n\n\tpublic syncTransaction<T>(transaction: () => T) {\n\t\ttry {\n\t\t\tthis.transactionDepth++\n\t\t\treturn transaction()\n\t\t} finally {\n\t\t\tthis.transactionDepth--\n\t\t}\n\t}\n\tpublic syncOperation<T>(operation: () => T) {\n\t\tconst result = this.syncTransaction(operation)\n\t\tthis.flushUpdates()\n\t\treturn result\n\t}\n\n\tpublic async asyncTransaction<T>(transaction: () => Promise<T>): Promise<T> {\n\t\ttry {\n\t\t\tthis.transactionDepth++\n\t\t\treturn await transaction()\n\t\t} finally {\n\t\t\tthis.transactionDepth--\n\t\t}\n\t}\n\tpublic async asyncOperation<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = await this.asyncTransaction(operation)\n\t\tthis.flushUpdates()\n\t\treturn result\n\t}\n\n\tprivate flushUpdates() {\n\t\tif (this.transactionDepth > 0) {\n\t\t\treturn\n\t\t}\n\n\t\tif (this.isFrozenWhileUpdating) {\n\t\t\tthrow new BindingError(\n\t\t\t\t`Trying to perform an update while the whole accessor tree is already updating. This is most likely caused `\n\t\t\t\t\t+ `by updating the accessor tree while rendering or from within the 'update' event handler, which is a no-op. `\n\t\t\t\t\t+ `If you wish to mutate the tree in reaction to other changes, use the 'beforeUpdate' event.`,\n\t\t\t)\n\t\t}\n\n\t\tconst newMetadata = this.getNewUpdateMetadata()\n\n\t\tif (!this.shouldFlushUpdates(newMetadata)) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.batchedUpdates(() => {\n\t\t\tthis.isFrozenWhileUpdating = true\n\t\t\tthis.triggerBeforeFlushEvents()\n\t\t\tthis.onUpdate(newMetadata)\n\t\t\tconst rootStates = Array.from(this.rootsWithPendingUpdates)\n\t\t\tthis.flushPendingAccessorUpdates(rootStates)\n\t\t\tthis.rootsWithPendingUpdates.clear()\n\t\t\tthis.isFrozenWhileUpdating = false\n\t\t\tthis.previousMetadata = newMetadata\n\t\t})\n\t}\n\n\tprivate getNewUpdateMetadata(): UpdateMetadata {\n\t\treturn {\n\t\t\tisMutating: this.isMutating,\n\t\t}\n\t}\n\n\tprivate shouldFlushUpdates(newMetadata: UpdateMetadata): boolean {\n\t\tif (this.transactionDepth > 0) {\n\t\t\treturn false\n\t\t}\n\t\tif (this.previousMetadata === undefined) {\n\t\t\treturn true\n\t\t}\n\t\tif (this.rootsWithPendingUpdates.size) {\n\t\t\treturn true\n\t\t}\n\t\tfor (const key in newMetadata) {\n\t\t\tconst fromPrevious = this.previousMetadata[key as keyof UpdateMetadata]\n\t\t\tconst fromNew = newMetadata[key as keyof UpdateMetadata]\n\n\t\t\tif (!Object.is(fromPrevious, fromNew)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tpublic registerNewlyInitialized(newlyInitialized: StateNode) {\n\t\tconst initializeListeners = this.getEventListeners(newlyInitialized, { type: 'initialize' })\n\n\t\tif (initializeListeners === undefined) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.newlyInitializedWithListeners.add(newlyInitialized)\n\n\t\tif (this.transactionDepth === 0) {\n\t\t\tthis.triggerOnInitialize()\n\t\t}\n\t}\n\n\tpublic registerUpdatedConnection(parentState: EntityRealmState, placeholderName: PlaceholderName) {\n\t\tif (parentState.fieldsWithPendingConnectionUpdates === undefined) {\n\t\t\tparentState.fieldsWithPendingConnectionUpdates = new Set()\n\t\t}\n\n\t\tconst marker = getEntityMarker(parentState)\n\t\tplaceholders: for (const [fieldName, placeholdersByField] of marker.fields.placeholders) {\n\t\t\tif (typeof placeholdersByField === 'string') {\n\t\t\t\tif (placeholdersByField === placeholderName) {\n\t\t\t\t\tparentState.fieldsWithPendingConnectionUpdates.add(fieldName)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (const placeholderByFieldName of placeholdersByField) {\n\t\t\t\t\tif (placeholderByFieldName === placeholderName) {\n\t\t\t\t\t\tparentState.fieldsWithPendingConnectionUpdates.add(fieldName)\n\t\t\t\t\t\tcontinue placeholders\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic registerJustUpdated(justUpdated: StateNode, changesDelta: number) {\n\t\tconst beforeUpdateListeners = this.getEventListeners(justUpdated, { type: 'beforeUpdate' })\n\t\tif (beforeUpdateListeners !== undefined) {\n\t\t\tthis.pendingWithBeforeUpdate.add(justUpdated)\n\t\t}\n\t\tjustUpdated.accessor = undefined\n\n\t\tswitch (justUpdated.type) {\n\t\t\tcase 'entityRealm':\n\t\t\tcase 'entityList': {\n\t\t\t\tjustUpdated.unpersistedChangesCount += changesDelta\n\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tif (justUpdated.unpersistedChangesCount < 0) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t`We have *JUST* reached a completely invalid state. From now on, anything can (and likely will) `\n\t\t\t\t\t\t\t\t+ `go wrong. This is definitely a bug. Please try to report whatever led to this situation.`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst parent = justUpdated.blueprint.parent\n\n\t\t\t\tif (parent === undefined) {\n\t\t\t\t\tthis.rootsWithPendingUpdates.add(justUpdated)\n\n\t\t\t\t\tif (\n\t\t\t\t\t\t!(justUpdated.blueprint.type === 'subTree' && justUpdated.blueprint.marker.parameters.isCreating\n\t\t\t\t\t\t\t&& justUpdated.blueprint.marker.parameters.isUnpersisted)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.dirtinessTracker.increaseBy(changesDelta)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (!parent.childrenWithPendingUpdates) {\n\t\t\t\t\t\tparent.childrenWithPendingUpdates = new Set()\n\t\t\t\t\t}\n\t\t\t\t\tparent.childrenWithPendingUpdates.add(justUpdated as any)\n\t\t\t\t\tthis.registerJustUpdated(parent, changesDelta)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'field': {\n\t\t\t\tconst parent = justUpdated.parent\n\t\t\t\tif (!parent.childrenWithPendingUpdates) {\n\t\t\t\t\tparent.childrenWithPendingUpdates = new Set()\n\t\t\t\t}\n\t\t\t\tparent.childrenWithPendingUpdates.add(justUpdated as any)\n\t\t\t\tthis.registerJustUpdated(justUpdated.parent, changesDelta)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate flushPendingAccessorUpdates(rootStates: Array<StateINode>) {\n\t\t// It is *CRUCIAL* that this is a BFS so that we update the components in top-down order.\n\t\tconst agenda: StateNode[] = rootStates\n\n\t\tfor (const state of agenda) {\n\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\tconst updateListeners = state.type === 'field'\n\t\t\t\t? this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\t\t\t\t: state.type === 'entityRealm'\n\t\t\t\t? this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\t\t\t\t: this.getEventDispatchers(state, { type: 'update' }, [state.getAccessor()])\n\n\t\t\tif (updateListeners !== undefined) {\n\t\t\t\tfor (const handler of updateListeners) {\n\t\t\t\t\t// TS can't quite handle the polymorphism here but this is fine.\n\t\t\t\t\thandler()\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (state.type === 'entityRealm' && state.fieldsWithPendingConnectionUpdates) {\n\t\t\t\tfor (const updatedField of state.fieldsWithPendingConnectionUpdates) {\n\t\t\t\t\tconst listeners = this.getEventListeners(state, { type: 'connectionUpdate', key: updatedField })\n\t\t\t\t\tif (!listeners) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tlistener(state.getAccessor())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch (state.type) {\n\t\t\t\tcase 'entityRealm':\n\t\t\t\tcase 'entityList': {\n\t\t\t\t\tif (state.childrenWithPendingUpdates !== undefined) {\n\t\t\t\t\t\tfor (const childState of state.childrenWithPendingUpdates) {\n\t\t\t\t\t\t\tagenda.push(childState)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstate.childrenWithPendingUpdates.clear()\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase 'field':\n\t\t\t\t\t// Do nothing\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(state)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async triggerAsyncMutatingEvent(eventType: 'beforePersist', options: AsyncBatchUpdatesOptions): Promise<void>\n\tprivate async triggerAsyncMutatingEvent(eventType: 'persistSuccess', options: PersistSuccessOptions): Promise<void>\n\tprivate async triggerAsyncMutatingEvent(\n\t\teventType: 'beforePersist' | 'persistSuccess',\n\t\toptions: AsyncBatchUpdatesOptions | PersistSuccessOptions,\n\t): Promise<void> {\n\t\tawait this.asyncTransaction(async () => {\n\t\t\t// TODO if an entity from here (or its parent) gets deleted, we need to remove stale handlers from here.\n\t\t\tconst callbackQueue: Array<\n\t\t\t\t[\n\t\t\t\t\t// The typings could be nicer but TS…\n\t\t\t\t\tStateINode,\n\t\t\t\t\t(\n\t\t\t\t\t\t| EntityAccessor.EntityEventListenerMap[typeof eventType]\n\t\t\t\t\t\t| EntityListAccessor.EntityListEventListenerMap[typeof eventType]\n\t\t\t\t\t),\n\t\t\t\t]\n\t\t\t> = []\n\n\t\t\tfor (const [, subTreeState] of StateIterator.eachRootState(this.treeStore)) {\n\t\t\t\tfor (const iNode of StateIterator.depthFirstINodes(subTreeState)) {\n\t\t\t\t\tconst listeners = this.getEventListeners(iNode, { type: eventType }) ?? []\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tcallbackQueue.push([iNode, listener])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (\n\t\t\t\tlet waterfallDepth = 0;\n\t\t\t\twaterfallDepth < this.config.getValue(`${eventType}SettleLimit` as const);\n\t\t\t\twaterfallDepth++\n\t\t\t) {\n\t\t\t\tconst promiseReturns: Array<\n\t\t\t\t\tPromise<\n\t\t\t\t\t\t| void\n\t\t\t\t\t\t| EntityAccessor.EntityEventListenerMap[typeof eventType]\n\t\t\t\t\t\t| EntityListAccessor.EntityListEventListenerMap[typeof eventType]\n\t\t\t\t\t>\n\t\t\t\t> = []\n\t\t\t\tconst correspondingStates: Array<StateINode> = []\n\n\t\t\t\tif (callbackQueue.length === 0) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tfor (const [state, callback] of callbackQueue) {\n\t\t\t\t\tcorrespondingStates.push(state)\n\t\t\t\t\tconst changesCountBefore = this.dirtinessTracker.getTotalTouchCount()\n\t\t\t\t\tlet validateChanges = false\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = callback(state.getAccessor as any, options as any) // TS can't quite handle this but this is sound.\n\t\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\t\tvalidateChanges = true\n\t\t\t\t\t\t\tpromiseReturns.push(result)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpromiseReturns.push(Promise.resolve(result))\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tpromiseReturns.push(Promise.reject(e))\n\t\t\t\t\t}\n\t\t\t\t\tif (validateChanges) {\n\t\t\t\t\t\tthis.validateWithoutChanges(changesCountBefore, eventType)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// TODO timeout\n\n\t\t\t\tconst changesCountBefore = this.dirtinessTracker.getTotalTouchCount()\n\t\t\t\tconst newCallbacks = await Promise.allSettled(promiseReturns)\n\t\t\t\tthis.validateWithoutChanges(changesCountBefore, eventType)\n\n\t\t\t\tcallbackQueue.length = 0 // Empties the queue\n\n\t\t\t\t// TODO we're drifting away from the original depth-first order. Let's see if that's ever even an issue.\n\t\t\t\tfor (const newlyInitialized of this.newlyInitializedWithListeners) {\n\t\t\t\t\tif (newlyInitialized.type === 'field') {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst beforePersistHandlers = this.getEventListeners(newlyInitialized, { type: eventType })\n\t\t\t\t\tif (beforePersistHandlers) {\n\t\t\t\t\t\tfor (const listener of beforePersistHandlers) {\n\t\t\t\t\t\t\tcallbackQueue.push([newlyInitialized, listener])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.triggerBeforeFlushEvents()\n\t\t\t\tthis.handleRejections(eventType, newCallbacks)\n\n\t\t\t\tfor (let i = 0; i < newCallbacks.length; i++) {\n\t\t\t\t\tconst result = newCallbacks[i]\n\t\t\t\t\tconst correspondingState = correspondingStates[i]\n\n\t\t\t\t\tif (result.status === 'fulfilled') {\n\t\t\t\t\t\tif (typeof result.value === 'function') {\n\t\t\t\t\t\t\tcallbackQueue.push([correspondingState, result.value])\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Otherwise do nothing. This is just a handler that albeit async, doesn't appear to\n\t\t\t\t\t\t// interact with data binding.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tif (callbackQueue.length) {\n\t\t\t\t\tthrow new BindingError(\n\t\t\t\t\t\t`Exceeded the ${eventType} settle limit. Your code likely contains a deadlock. `\n\t\t\t\t\t\t\t+ `If that's not the case, raise the settle limit from DataBindingProvider.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate triggerBeforeFlushEvents() {\n\t\tthis.syncTransaction(() => {\n\t\t\tconst settleLimit = this.config.getValue('beforeUpdateSettleLimit')\n\n\t\t\tfor (let attemptNumber = 0; attemptNumber < settleLimit; attemptNumber++) {\n\t\t\t\tif (!this.pendingWithBeforeUpdate.size) {\n\t\t\t\t\tthis.triggerOnInitialize()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconst withBeforeUpdate = this.pendingWithBeforeUpdate\n\t\t\t\tthis.pendingWithBeforeUpdate = new Set()\n\n\t\t\t\tfor (const state of withBeforeUpdate) {\n\t\t\t\t\tconst listeners = this.getEventListeners(state, { type: 'beforeUpdate' })\n\t\t\t\t\tif (listeners === undefined) {\n\t\t\t\t\t\t// This can happen if the listener has unsubscribed since we added it to the set.\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tswitch (state.type) {\n\t\t\t\t\t\tcase 'field':\n\t\t\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\t\t\t;(listener as FieldAccessor.BeforeUpdateListener)(state.getAccessor())\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase 'entityRealm':\n\t\t\t\t\t\tcase 'entityList':\n\t\t\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\t\t\tstate.getAccessor().batchUpdates(listener as any)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn assertNever(state)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tthis.triggerOnInitialize()\n\t\t\t}\n\t\t\tthrow new BindingError(\n\t\t\t\t`Maximum stabilization limit of updates caused by 'beforeUpdate' exceeded. `\n\t\t\t\t\t+ `This likely means there is an infinite feedback loop in your code.`,\n\t\t\t)\n\t\t})\n\t}\n\n\tprivate triggerOnInitialize() {\n\t\tthis.syncTransaction(() => {\n\t\t\tfor (const state of this.newlyInitializedWithListeners) {\n\t\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\t\tconst listeners = state.type === 'field'\n\t\t\t\t\t? this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\t\t\t\t\t: state.type === 'entityRealm'\n\t\t\t\t\t? this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\t\t\t\t\t: this.getEventDispatchers(state, { type: 'initialize' }, [state.getAccessor, this.batchUpdatesOptions])\n\n\t\t\t\tif (listeners) {\n\t\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\t\tlistener()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (state.type === 'entityRealm') {\n\t\t\t\t\tstate.entity.hasIdSetInStone = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.newlyInitializedWithListeners.clear()\n\t\t})\n\t}\n\n\tpublic async triggerOnPersistError(options: PersistErrorOptions) {\n\t\tawait this.asyncTransaction(async () => {\n\t\t\tconst handlerPromises: Array<Promise<void>> = []\n\n\t\t\tfor (const [, subTreeState] of StateIterator.eachRootState(this.treeStore)) {\n\t\t\t\tfor (const iNode of StateIterator.depthFirstINodes(subTreeState)) {\n\t\t\t\t\t// yes, the calls are same, but this way we can avoid type casting\n\t\t\t\t\tconst dispatchers = iNode.type === 'entityRealm'\n\t\t\t\t\t\t? this.getEventDispatchers(iNode, { type: 'persistError' }, [iNode.getAccessor, options])\n\t\t\t\t\t\t: this.getEventDispatchers(iNode, { type: 'persistError' }, [iNode.getAccessor, options])\n\t\t\t\t\tif (dispatchers === undefined) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfor (const listener of dispatchers ?? []) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = listener()\n\t\t\t\t\t\t\tif (result instanceof Promise) {\n\t\t\t\t\t\t\t\thandlerPromises.push(result)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\thandlerPromises.push(Promise.resolve(result))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\thandlerPromises.push(Promise.reject(e))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO timeout\n\t\t\tconst handlerResults = await Promise.allSettled(handlerPromises)\n\t\t\tthis.handleRejections('persistError', handlerResults)\n\t\t})\n\t}\n\n\tpublic async triggerOnBeforePersist() {\n\t\treturn this.triggerAsyncMutatingEvent('beforePersist', this.asyncBatchUpdatesOptions)\n\t}\n\n\tpublic async triggerOnPersistSuccess(options: PersistSuccessOptions) {\n\t\treturn this.triggerAsyncMutatingEvent('persistSuccess', options)\n\t}\n\n\tpublic getEventListeners<\n\t\tState extends StateNode,\n\t\tEventListenerTypes extends Exclude<State['eventListeners'], undefined> extends EventListenersStore<infer Map> ? [keyof Map, Map] : never,\n\t\tEventType extends EventListenerTypes[0],\n\t>(state: State, event: { type: EventType; key?: string }): Set<Exclude<EventListenerTypes[1][EventType], undefined>> | undefined {\n\t\tif (!state.eventListeners) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn (state.eventListeners as EventListenersStore<EventListenerTypes[1]>).get(event) as Set<\n\t\t\tExclude<EventListenerTypes[1][EventType], undefined>\n\t\t>\n\t}\n\n\tpublic getEventDispatchers<\n\t\tState extends StateNode,\n\t\tEventListenerTypes extends Exclude<State['eventListeners'], undefined> extends EventListenersStore<infer Map> ? [keyof Map, Map] : never,\n\t\tEventType extends EventListenerTypes[0],\n\t>(\n\t\tstate: State,\n\t\tevent: { type: EventType; key?: string },\n\t\tlistenerArgs: Parameters<Exclude<EventListenerTypes[1][EventType], undefined>>,\n\t): Array<() => ReturnType<Exclude<EventListenerTypes[1][EventType], undefined>>> | undefined {\n\t\tconst eventListeners = this.getEventListeners(state, event)\n\t\tif (eventListeners === undefined) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn Array.from(eventListeners.values(), listener => {\n\t\t\treturn () => listener(...listenerArgs)\n\t\t}) as Array<() => ReturnType<Exclude<EventListenerTypes[1][EventType], undefined>>>\n\t}\n\n\tprivate handleRejections(handler: string, promises: PromiseSettledResult<any>[]) {\n\t\tconst rejections = promises.filter((it): it is PromiseRejectedResult => it.status === 'rejected')\n\t\tif (rejections.length === 0) {\n\t\t\treturn\n\t\t}\n\t\trejections.forEach(it => console.error(it.reason))\n\t\tif (import.meta.env.DEV) {\n\t\t\tthrow new BindingError(\n\t\t\t\t`A ${handler} handler returned a promise that rejected. `\n\t\t\t\t\t+ `This is a no-op that will fail silently in production.`,\n\t\t\t)\n\t\t}\n\t}\n\n\tprivate validateWithoutChanges(initialCount: number, eventType: string): void {\n\t\tconst changesCountAfter = this.dirtinessTracker.getTotalTouchCount()\n\t\tif (import.meta.env.DEV) {\n\t\t\tif (initialCount !== changesCountAfter) {\n\t\t\t\t// This isn't bulletproof. They could e.g. undo a change and make another one which would\n\t\t\t\t// slip through this detection. But for most cases, it should be good enough and not too expensive.\n\t\t\t\tthrow new BindingError(\n\t\t\t\t\t`A ${eventType} event handler cannot be asynchronous and alter the accessor tree at the same time. `\n\t\t\t\t\t\t+ `To achieve this, prepare your data asynchronously but only touch the tree from a returned callback.`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}\n"],"names":["changesCountBefore"],"mappings":";;;;;;AAoBO,MAAM,aAAa;AAAA,EAiBlB,YACW,0BACA,qBACA,QACA,kBACA,UACA,WACA,gBAChB;AAPgB,SAAA,2BAAA;AACA,SAAA,sBAAA;AACA,SAAA,SAAA;AACA,SAAA,mBAAA;AACA,SAAA,WAAA;AACA,SAAA,YAAA;AACA,SAAA,iBAAA;AArBlB,kBAAA,MAAQ,oBAAmB,CAAA;AAC3B,kBAAA,MAAQ,yBAAwB,KAAA;AAIhC,kBAAA,MAAQ,cAAsB,KAAA;AAC9B,kBAAA,MAAQ,yBAAA;AAER,kBAAA,MAAQ,kBAAA;AAER,kBAAA,MAAQ,qDAA0F,IAAA,CAAI;AACtG,kBAAA,MAAQ,+CAA8C,IAAA,CAAI;AAC1D,kBAAA,MAAQ,+CAAkD,IAAA,CAAI;AAAA,EAU3D;AAAA,EAEH,MAAa,iBAAiB,WAAqF;AAClH,QAAI,KAAK,4BAA4B,QAAW;AAC/C,UAAI,KAAK,YAAY;AACpB,cAAM,IAAI,aAAa,yDAAyD;AAAA,MACj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