joist-core 2.4.0-next.2 → 2.4.0-next.21
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/build/EntityManager.cjs +25 -11
- package/build/EntityManager.cjs.map +1 -1
- package/build/EntityManager.d.cts +11 -4
- package/build/EntityManager.d.cts.map +1 -1
- package/build/EntityManager.d.mts +11 -4
- package/build/EntityManager.d.mts.map +1 -1
- package/build/EntityManager.js +25 -13
- package/build/EntityManager.js.map +1 -1
- package/build/EntityMetadata.cjs +0 -1
- package/build/EntityMetadata.cjs.map +1 -1
- package/build/EntityMetadata.d.cts +8 -4
- package/build/EntityMetadata.d.cts.map +1 -1
- package/build/EntityMetadata.d.mts +8 -4
- package/build/EntityMetadata.d.mts.map +1 -1
- package/build/EntityMetadata.js +0 -1
- package/build/EntityMetadata.js.map +1 -1
- package/build/IndexManager.cjs +23 -5
- package/build/IndexManager.cjs.map +1 -1
- package/build/IndexManager.d.cts.map +1 -1
- package/build/IndexManager.d.mts.map +1 -1
- package/build/IndexManager.js +23 -5
- package/build/IndexManager.js.map +1 -1
- package/build/batchloaders/populateBatchLoader.cjs +2 -2
- package/build/batchloaders/populateBatchLoader.js +2 -2
- package/build/batchloaders/recursiveChildrenBatchLoader.cjs +1 -1
- package/build/batchloaders/recursiveChildrenBatchLoader.js +1 -1
- package/build/batchloaders/recursiveM2mBatchLoader.cjs +1 -1
- package/build/batchloaders/recursiveM2mBatchLoader.js +1 -1
- package/build/batchloaders/recursiveParentsBatchLoader.cjs +1 -1
- package/build/batchloaders/recursiveParentsBatchLoader.js +1 -1
- package/build/config.cjs +74 -1
- package/build/config.cjs.map +1 -1
- package/build/config.d.cts +83 -2
- package/build/config.d.cts.map +1 -1
- package/build/config.d.mts +83 -2
- package/build/config.d.mts.map +1 -1
- package/build/config.js +74 -1
- package/build/config.js.map +1 -1
- package/build/configure.cjs +6 -2
- package/build/configure.cjs.map +1 -1
- package/build/configure.d.cts.map +1 -1
- package/build/configure.d.mts.map +1 -1
- package/build/configure.js +6 -2
- package/build/configure.js.map +1 -1
- package/build/dataloaders/findDataLoader.cjs +1 -1
- package/build/dataloaders/findDataLoader.js +1 -1
- package/build/dataloaders/findOrCreateDataLoader.cjs +6 -2
- package/build/dataloaders/findOrCreateDataLoader.cjs.map +1 -1
- package/build/dataloaders/findOrCreateDataLoader.d.cts.map +1 -1
- package/build/dataloaders/findOrCreateDataLoader.d.mts.map +1 -1
- package/build/dataloaders/findOrCreateDataLoader.js +7 -3
- package/build/dataloaders/findOrCreateDataLoader.js.map +1 -1
- package/build/dataloaders/findPaginatedDataLoader.cjs +1 -1
- package/build/dataloaders/findPaginatedDataLoader.js +1 -1
- package/build/defaults.cjs +2 -2
- package/build/defaults.js +2 -2
- package/build/fields.cjs +1 -0
- package/build/fields.cjs.map +1 -1
- package/build/fields.d.cts.map +1 -1
- package/build/fields.d.mts.map +1 -1
- package/build/fields.js +1 -0
- package/build/fields.js.map +1 -1
- package/build/index.cjs +13 -8
- package/build/index.cjs.map +1 -1
- package/build/index.d.cts +4 -3
- package/build/index.d.cts.map +1 -1
- package/build/index.d.mts +4 -3
- package/build/index.d.mts.map +1 -1
- package/build/index.js +13 -10
- package/build/index.js.map +1 -1
- package/build/json.cjs +3 -3
- package/build/json.js +3 -3
- package/build/loading/loadHints.cjs +1 -1
- package/build/loading/loadHints.js +1 -1
- package/build/loading/withLoaded.cjs +2 -2
- package/build/loading/withLoaded.js +2 -2
- package/build/newTestInstance.cjs +1 -0
- package/build/newTestInstance.cjs.map +1 -1
- package/build/newTestInstance.d.cts.map +1 -1
- package/build/newTestInstance.d.mts.map +1 -1
- package/build/newTestInstance.js +1 -0
- package/build/newTestInstance.js.map +1 -1
- package/build/preloading/partitionHint.cjs +1 -1
- package/build/preloading/partitionHint.js +1 -1
- package/build/queries/sql/execute.cjs +68 -89
- package/build/queries/sql/execute.cjs.map +1 -1
- package/build/queries/sql/execute.d.cts +35 -18
- package/build/queries/sql/execute.d.cts.map +1 -1
- package/build/queries/sql/execute.d.mts +35 -18
- package/build/queries/sql/execute.d.mts.map +1 -1
- package/build/queries/sql/execute.js +70 -91
- package/build/queries/sql/execute.js.map +1 -1
- package/build/queries/sql/query.cjs +77 -30
- package/build/queries/sql/query.cjs.map +1 -1
- package/build/queries/sql/query.d.cts +64 -21
- package/build/queries/sql/query.d.cts.map +1 -1
- package/build/queries/sql/query.d.mts +64 -21
- package/build/queries/sql/query.d.mts.map +1 -1
- package/build/queries/sql/query.js +75 -30
- package/build/queries/sql/query.js.map +1 -1
- package/build/reactivity/ReactionsManager.cjs +168 -2
- package/build/reactivity/ReactionsManager.cjs.map +1 -1
- package/build/reactivity/ReactionsManager.d.cts +54 -1
- package/build/reactivity/ReactionsManager.d.cts.map +1 -1
- package/build/reactivity/ReactionsManager.d.mts +54 -1
- package/build/reactivity/ReactionsManager.d.mts.map +1 -1
- package/build/reactivity/ReactionsManager.js +169 -3
- package/build/reactivity/ReactionsManager.js.map +1 -1
- package/build/reactivity/reactiveHints.cjs +3 -3
- package/build/reactivity/reactiveHints.cjs.map +1 -1
- package/build/reactivity/reactiveHints.d.cts.map +1 -1
- package/build/reactivity/reactiveHints.d.mts.map +1 -1
- package/build/reactivity/reactiveHints.js +3 -3
- package/build/reactivity/reactiveHints.js.map +1 -1
- package/build/relations/AsyncReactiveField.cjs +3 -3
- package/build/relations/AsyncReactiveField.js +3 -3
- package/build/relations/LazyField.cjs +14 -0
- package/build/relations/LazyField.cjs.map +1 -1
- package/build/relations/LazyField.d.cts +6 -0
- package/build/relations/LazyField.d.cts.map +1 -1
- package/build/relations/LazyField.d.mts +6 -0
- package/build/relations/LazyField.d.mts.map +1 -1
- package/build/relations/LazyField.js +14 -0
- package/build/relations/LazyField.js.map +1 -1
- package/build/relations/ReactiveField.cjs +2 -2
- package/build/relations/ReactiveField.js +2 -2
- package/build/relations/ReactiveManyToMany.cjs +1 -1
- package/build/relations/ReactiveManyToMany.js +1 -1
- package/build/relations/ReactiveReference.cjs +1 -1
- package/build/relations/ReactiveReference.js +1 -1
- package/build/relations/RecursiveCollection.cjs +3 -3
- package/build/relations/RecursiveCollection.js +3 -3
- package/build/relations/hasProperty.cjs +2 -2
- package/build/relations/hasProperty.js +2 -2
- package/build/relations/index.cjs +5 -5
- package/build/relations/index.js +5 -5
- package/build/resurrection.cjs +11 -1
- package/build/resurrection.cjs.map +1 -1
- package/build/resurrection.d.cts +4 -1
- package/build/resurrection.d.cts.map +1 -1
- package/build/resurrection.d.mts +4 -1
- package/build/resurrection.d.mts.map +1 -1
- package/build/resurrection.js +11 -2
- package/build/resurrection.js.map +1 -1
- package/build/transitions.cjs +89 -0
- package/build/transitions.cjs.map +1 -0
- package/build/transitions.d.cts +110 -0
- package/build/transitions.d.cts.map +1 -0
- package/build/transitions.d.mts +110 -0
- package/build/transitions.d.mts.map +1 -0
- package/build/transitions.js +84 -0
- package/build/transitions.js.map +1 -0
- package/package.json +2 -2
package/build/index.js
CHANGED
|
@@ -3,15 +3,9 @@ import { AbstractRelationImpl } from "./relations/AbstractRelationImpl.js";
|
|
|
3
3
|
import { CustomCollection, hasCustomCollection } from "./relations/CustomCollection.js";
|
|
4
4
|
import { EnumCollectionImpl, hasEnumCollection } from "./relations/EnumCollection.js";
|
|
5
5
|
import { CustomReference, hasCustomReference } from "./relations/CustomReference.js";
|
|
6
|
-
import { deepNormalizeHint, normalizeHint } from "./normalizeHints.js";
|
|
7
|
-
import { hasReactiveGetter, isReactiveGetter } from "./relations/ReactiveGetter.js";
|
|
8
|
-
import { isRelation } from "./relations/Relation.js";
|
|
9
|
-
import { isLoadedReadOnlyCollection, isReadOnlyCollection } from "./relations/ReadOnlyCollection.js";
|
|
10
|
-
import { RecursiveCycleError } from "./relations/RecursiveCycleError.js";
|
|
11
|
-
import { hasRecursiveChildren, hasRecursiveM2m, hasRecursiveParents } from "./relations/RecursiveCollection.js";
|
|
12
|
-
import { convertToLoadHint, isTypeOrSubType, reverseReactiveHint } from "./reactivity/reactiveHints.js";
|
|
13
6
|
import { assertLoaded, ensureLoaded, isLoaded, isNew, maybePopulateThen, unsafeLoaded } from "./loading/loadHints.js";
|
|
14
7
|
import { hasAsyncMethod } from "./relations/hasAsyncMethod.js";
|
|
8
|
+
import { RecursiveCycleError } from "./relations/RecursiveCycleError.js";
|
|
15
9
|
import { PropertyImpl, hasProperty, hasReactiveProperty, isLoadedProperty, isProperty } from "./relations/hasProperty.js";
|
|
16
10
|
import { AsyncPropertyImpl, hasAsyncProperty, isAsyncProperty, isLoadedAsyncProperty } from "./relations/AsyncProperty.js";
|
|
17
11
|
import { Temporal, maybeRequireTemporal, requireTemporal } from "./serde/temporal.js";
|
|
@@ -26,6 +20,7 @@ import { isLoadedReference, isReference } from "./relations/Reference.js";
|
|
|
26
20
|
import { hasOneDerived } from "./relations/hasOneDerived.js";
|
|
27
21
|
import { hasOneThrough } from "./relations/hasOneThrough.js";
|
|
28
22
|
import { ManyToManyCollection, hasManyToMany } from "./relations/ManyToManyCollection.js";
|
|
23
|
+
import { isRelation } from "./relations/Relation.js";
|
|
29
24
|
import { ManyToManyLargeCollection, hasLargeManyToMany } from "./relations/ManyToManyLargeCollection.js";
|
|
30
25
|
import { skipCondition } from "./queries/skipCondition.js";
|
|
31
26
|
import { alias, aliases, getAliasMetadata, getAliasMgmt, getMaybeCtiAlias, isAlias, newAliasProxy } from "./queries/find/Aliases.js";
|
|
@@ -43,20 +38,25 @@ import { ReactiveReferenceImpl, hasReactiveReference, isReactiveReference } from
|
|
|
43
38
|
import { OneToOneReferenceImpl, hasOneToOne, isLoadedOneToOneReference, isOneToOneReference } from "./relations/OneToOneReference.js";
|
|
44
39
|
import { PolymorphicReferenceImpl, hasOnePolymorphic, isPolymorphicReference } from "./relations/PolymorphicReference.js";
|
|
45
40
|
import { ReactiveFieldImpl, hasReactiveField, isReactiveField } from "./relations/ReactiveField.js";
|
|
41
|
+
import { hasReactiveGetter, isReactiveGetter } from "./relations/ReactiveGetter.js";
|
|
46
42
|
import { ReactiveManyToManyImpl, hasReactiveManyToMany, isReactiveManyToMany } from "./relations/ReactiveManyToMany.js";
|
|
47
43
|
import { ReactiveManyToManyOtherSideImpl, hasReactiveManyToManyOtherSide, isReactiveManyToManyOtherSide } from "./relations/ReactiveManyToManyOtherSide.js";
|
|
48
44
|
import { AsyncReactiveFieldImpl, hasAsyncReactiveField, isAsyncReactiveField } from "./relations/AsyncReactiveField.js";
|
|
45
|
+
import { hasRecursiveChildren, hasRecursiveM2m, hasRecursiveParents } from "./relations/RecursiveCollection.js";
|
|
46
|
+
import { isLoadedReadOnlyCollection, isReadOnlyCollection } from "./relations/ReadOnlyCollection.js";
|
|
49
47
|
import "./relations/index.js";
|
|
50
48
|
import { abbreviation, asNew, assertNever, cleanSql, cleanStringValue, fail, failIfAnyRejected, indexBy, partition, zeroTo } from "./utils.js";
|
|
51
49
|
import { lazyField } from "./newEntity.js";
|
|
52
50
|
import { UnknownProperty, getLazyFields, getProperties } from "./getProperties.js";
|
|
51
|
+
import { deepNormalizeHint, normalizeHint } from "./normalizeHints.js";
|
|
52
|
+
import { convertToLoadHint, isTypeOrSubType, reverseReactiveHint } from "./reactivity/reactiveHints.js";
|
|
53
53
|
import "./typeMap.js";
|
|
54
54
|
import { newChangesProxy } from "./changes.js";
|
|
55
55
|
import { ValidationCode, ValidationErrors, cannotBeChanged, cannotBeUpdated, maxValueRule, minValueRule, mustBeSubType, newRequiredLazyFieldRule, newRequiredRule, rangeValueRule } from "./rules.js";
|
|
56
|
+
import { ConfigApi, resetBootFlag } from "./config.js";
|
|
56
57
|
import { getRuntimeConfig, setRuntimeConfig } from "./runtimeConfig.js";
|
|
57
58
|
import { FieldColumn, PolyComponent, PolymorphicKeySerde, SimpleFieldSerde, hasSerde, polymorphicField } from "./serde/fieldSerde.js";
|
|
58
59
|
import { configureMetadata, getConstructorFromTaggedId, getMetadataForTable, getMetadataForType, maybeGetConstructorFromReference } from "./configure.js";
|
|
59
|
-
import { ConfigApi, resetBootFlag } from "./config.js";
|
|
60
60
|
import { getBaseAndSelfMetas, getBaseMeta, getBaseSelfAndSubMetas, getMetadata, getMetadataForField, getSubMetas, isCollectionField, isManyToManyEnumField, isManyToManyField, isManyToOneField, isOneToManyField, isOneToOneField, isPolymorphicField, isReferenceField } from "./EntityMetadata.js";
|
|
61
61
|
import { isInTrustedContext, runInTrustedContext } from "./trusted.js";
|
|
62
62
|
import { getDefaultDependencies } from "./defaults.js";
|
|
@@ -94,7 +94,7 @@ import { entityQueryBrand, query, queryMaybe, recursiveQuery, sql, subqueryBrand
|
|
|
94
94
|
import { nowUTC } from "./nowUTC.js";
|
|
95
95
|
import { updatePartial, upsert } from "./upsert.js";
|
|
96
96
|
import { StubbedRelation, ensureWithLoaded, withLoaded } from "./loading/withLoaded.js";
|
|
97
|
-
import { EntityManager, NotFoundError, ReadOnlyError, TooManyError, appendStack, createRowFromEntityData, driverAfterBegin, driverAfterCommit, driverBeforeBegin, driverBeforeCommit, getDefaultEntityLimit, getEmInternalApi, isDefined, isId, isKey, resetDefaultEntityLimit, sameEntity, sameReference, setDefaultEntityLimit, setLastNow } from "./EntityManager.js";
|
|
97
|
+
import { EntityManager, FailedFlushError, NotFoundError, ReadOnlyError, TooManyError, appendStack, createRowFromEntityData, driverAfterBegin, driverAfterCommit, driverBeforeBegin, driverBeforeCommit, getDefaultEntityLimit, getEmInternalApi, invokeRule, isDefined, isId, isKey, resetDefaultEntityLimit, sameEntity, sameReference, setDefaultEntityLimit, setLastNow } from "./EntityManager.js";
|
|
98
98
|
import { isEntity } from "./Entity.js";
|
|
99
99
|
import { BaseEntity, getInstanceData } from "./BaseEntity.js";
|
|
100
100
|
import { newPgConnectionConfig } from "joist-utils";
|
|
@@ -152,6 +152,9 @@ function setOpt(meta, entity, key, _value, partial = false, calledFromConstructo
|
|
|
152
152
|
else if (current instanceof AsyncReactiveFieldImpl) current.setFactoryValue(value.value);
|
|
153
153
|
else throw new Error(`Unhandled case ${current.constructor.name}`);
|
|
154
154
|
} else throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);
|
|
155
|
+
} else if (value instanceof FactoryInitialValue) {
|
|
156
|
+
entity[key] = value.value;
|
|
157
|
+
getEmInternalApi(entity.em).rm.forgetCreationTransition(entity, key);
|
|
155
158
|
} else if (key === "id" && entity.isNewEntity) setField(entity, key, value);
|
|
156
159
|
else entity[key] = value;
|
|
157
160
|
}
|
|
@@ -192,6 +195,6 @@ function isNewEntity(entity) {
|
|
|
192
195
|
return entity.isNewEntity;
|
|
193
196
|
}
|
|
194
197
|
//#endregion
|
|
195
|
-
export { AliasAssigner, AsyncPropertyImpl, BaseEntity, BigIntSerde, Column, ConditionBuilder, ConfigApi, CustomCollection, CustomReference, CustomSerdeAdapter, DateSerde, DecimalToNumberSerde, EntityManager, EnumArrayFieldSerde, EnumCollectionImpl, EnumFieldSerde, FieldColumn, FieldLogger, ImmutableEntitiesPlugin, InstanceData, JoinRowOperation, JsonAggregatePreloader, JsonSerde, KeySerde, LazyFieldImpl, ManyToManyCollection, ManyToManyLargeCollection, ManyToOneReferenceImpl, NoIdError, NotFoundError, OneToManyCollection, OneToManyLargeCollection, OneToOneReferenceImpl, PlainDateSerde, PlainDateTimeSerde, PlainTimeSerde, Plugin, PojoRowData, PolyComponent, PolymorphicKeySerde, PolymorphicReferenceImpl, PrimitiveSerde, PropertyImpl, RandomUuidAssigner, ReactionLogger, ReactiveManyToManyImpl, ReactiveManyToManyOtherSideImpl, ReactiveReferenceImpl, ReadOnlyError, RecursiveCycleError, SequenceIdAssigner, SimpleFieldSerde, StubbedRelation, SuperstructSerde, Temporal, TestUuidAssigner, Todo, TooManyError, UnknownProperty, ValidationCode, ValidationErrors, ZodSerde, ZonedDateTimeSerde, abbreviation, addTablePerClassJoinsAndClassTag, alias, aliases, appendStack, asConcreteCstr, asNew, assertIdIsTagged, assertIdsAreTagged, assertLoaded, assertNever, buildCteSql, buildRawQuery, buildUnnestCte, buildValueCondition, buildWhereClause, cannotBeChanged, cannotBeUpdated, cleanSql, cleanStringValue, configureMetadata, convertToLoadHint, createRowFromEntityData, deTagId, deTagIds, declareTable, deepNormalizeHint, defaultValue, driverAfterBegin, driverAfterCommit, driverApi, driverBeforeBegin, driverBeforeCommit, emptyRowData, ensureLoaded, ensureNotDeleted, ensureRectangularArraySizes, ensureTagged, ensureWithLoaded, entityQueryBrand, expr, exprBrand, factories, fail, failIfAnyRejected, failNoIdYet, filterSoftDeletes, findFilterField, generateOps, getAliasMetadata, getAliasMgmt, getBaseAndSelfMetas, getBaseMeta, getBaseSelfAndSubMetas, getConstructorFromTaggedId, getDefaultEntityLimit, getEmInternalApi, getField, getInstanceData, getLazyFields, getLens, getLensPath, getMaybeCtiAlias, getMetadata, getMetadataForField, getMetadataForTable, getMetadataForType, getProperties, getRelationEntries, getRelations, getRequiredKeys, getRuntimeConfig, getSubMetas, getTableMetadata, getTableMgmt, getTables, getTestIndex, hasAsyncMethod, hasAsyncProperty, hasAsyncReactiveField, hasCustomCollection, hasCustomReference, hasEnumCollection, hasLargeMany, hasLargeManyToMany, hasLazyField, hasMany, hasManyDerived, hasManyThrough, hasManyToMany, hasOne, hasOneDerived, hasOnePolymorphic, hasOneThrough, hasOneToOne, hasProperty, hasReactiveField, hasReactiveGetter, hasReactiveManyToMany, hasReactiveManyToManyOtherSide, hasReactiveProperty, hasReactiveReference, hasRecursiveChildren, hasRecursiveM2m, hasRecursiveParents, hasSerde, indexBy, internals, isAlias, isAllSqlPaths, isAsyncProperty, isAsyncReactiveField, isChangeableField, isCollection, isCollectionField, isDefined, isEntity, isFactoryCreation, isFieldSet, isId, isInTrustedContext, isKey, isLazyField, isLensLoaded, isLensLoadedPath, isLoaded, isLoadedAsyncProperty, isLoadedCollection, isLoadedLazyField, isLoadedOneToOneReference, isLoadedProperty, isLoadedReadOnlyCollection, isLoadedReference, isManyToManyEnumField, isManyToManyField, isManyToOneField, isManyToOneReference, isNew, isNewEntity, isOneToManyField, isOneToOneField, isOneToOneReference, isPolymorphicField, isPolymorphicReference, isProperty, isReactiveField, isReactiveGetter, isReactiveManyToMany, isReactiveManyToManyOtherSide, isReactiveReference, isReadOnlyCollection, isReference, isReferenceField, isRelation, isScope, isScopeJoinFilter, isSelectAllFilter, isTable, isTaggedId, isTypeOrSubType, keyToNumber, keyToTaggedId, kq, kqDot, kqStar, lazyExcludedSelects, lazyField, lensPathToLoadHint, lensToLoadHint, lensToPath, loadLens, loadLensPath, makeLike, mapPathsToTarget, mapToDb, maxValueRule, maybeAddIdNotNulls, maybeAddNotSoftDeleted, maybeAddOrderBy, maybeBranchValue, maybeGetConstructorFromReference, maybeNew, maybeNewPoly, maybePopulateThen, maybeRequireTemporal, maybeResolveReferenceToId, mergeFindOptions, minValueRule, mustBeSubType, newAliasProxy, newChangesProxy, newPgConnectionConfig, newRequiredLazyFieldRule, newRequiredRule, newScopeFn, newTableProxy, newTestInstance, noValue, noopFieldLogger, normalizeHint, nowUTC, opToFn, operators, optimizeCollectionJoins, parseAlias, parseEntityFilter, parseFindQuery, parseValueFilter, partition, plainDateMapper, plainDateTimeMapper, plainTimeMapper, polymorphicField, query, queryMaybe, rangeValueRule, recursiveQuery, requireTemporal, resetBootFlag, resetDefaultEntityLimit, resolveScope, reverseReactiveHint, runInTrustedContext, sameEntity, sameReference, setDefaultEntityLimit, setFactoryLogging, setFactoryWriter, setField, setLastNow, setOpt, setOpts, setReactionLogging, setRuntimeConfig, setTaggedIdDelimiter, skipCondition, sql, stiSubtypeFilter, subqueryBrand, table, tableMgmt, tables, tagFromId, tagId, tagIds, taggedIdPrefix, testIndex, testing, toIdOf, toJSON, toTaggedId, unsafeDeTagIds, unsafeLoaded, updatePartial, upsert, visitConditions, withLoaded, zeroTo, zonedDateTimeMapper };
|
|
198
|
+
export { AliasAssigner, AsyncPropertyImpl, BaseEntity, BigIntSerde, Column, ConditionBuilder, ConfigApi, CustomCollection, CustomReference, CustomSerdeAdapter, DateSerde, DecimalToNumberSerde, EntityManager, EnumArrayFieldSerde, EnumCollectionImpl, EnumFieldSerde, FailedFlushError, FieldColumn, FieldLogger, ImmutableEntitiesPlugin, InstanceData, JoinRowOperation, JsonAggregatePreloader, JsonSerde, KeySerde, LazyFieldImpl, ManyToManyCollection, ManyToManyLargeCollection, ManyToOneReferenceImpl, NoIdError, NotFoundError, OneToManyCollection, OneToManyLargeCollection, OneToOneReferenceImpl, PlainDateSerde, PlainDateTimeSerde, PlainTimeSerde, Plugin, PojoRowData, PolyComponent, PolymorphicKeySerde, PolymorphicReferenceImpl, PrimitiveSerde, PropertyImpl, RandomUuidAssigner, ReactionLogger, ReactiveManyToManyImpl, ReactiveManyToManyOtherSideImpl, ReactiveReferenceImpl, ReadOnlyError, RecursiveCycleError, SequenceIdAssigner, SimpleFieldSerde, StubbedRelation, SuperstructSerde, Temporal, TestUuidAssigner, Todo, TooManyError, UnknownProperty, ValidationCode, ValidationErrors, ZodSerde, ZonedDateTimeSerde, abbreviation, addTablePerClassJoinsAndClassTag, alias, aliases, appendStack, asConcreteCstr, asNew, assertIdIsTagged, assertIdsAreTagged, assertLoaded, assertNever, buildCteSql, buildRawQuery, buildUnnestCte, buildValueCondition, buildWhereClause, cannotBeChanged, cannotBeUpdated, cleanSql, cleanStringValue, configureMetadata, convertToLoadHint, createRowFromEntityData, deTagId, deTagIds, declareTable, deepNormalizeHint, defaultValue, driverAfterBegin, driverAfterCommit, driverApi, driverBeforeBegin, driverBeforeCommit, emptyRowData, ensureLoaded, ensureNotDeleted, ensureRectangularArraySizes, ensureTagged, ensureWithLoaded, entityQueryBrand, expr, exprBrand, factories, fail, failIfAnyRejected, failNoIdYet, filterSoftDeletes, findFilterField, generateOps, getAliasMetadata, getAliasMgmt, getBaseAndSelfMetas, getBaseMeta, getBaseSelfAndSubMetas, getConstructorFromTaggedId, getDefaultEntityLimit, getEmInternalApi, getField, getInstanceData, getLazyFields, getLens, getLensPath, getMaybeCtiAlias, getMetadata, getMetadataForField, getMetadataForTable, getMetadataForType, getProperties, getRelationEntries, getRelations, getRequiredKeys, getRuntimeConfig, getSubMetas, getTableMetadata, getTableMgmt, getTables, getTestIndex, hasAsyncMethod, hasAsyncProperty, hasAsyncReactiveField, hasCustomCollection, hasCustomReference, hasEnumCollection, hasLargeMany, hasLargeManyToMany, hasLazyField, hasMany, hasManyDerived, hasManyThrough, hasManyToMany, hasOne, hasOneDerived, hasOnePolymorphic, hasOneThrough, hasOneToOne, hasProperty, hasReactiveField, hasReactiveGetter, hasReactiveManyToMany, hasReactiveManyToManyOtherSide, hasReactiveProperty, hasReactiveReference, hasRecursiveChildren, hasRecursiveM2m, hasRecursiveParents, hasSerde, indexBy, internals, invokeRule, isAlias, isAllSqlPaths, isAsyncProperty, isAsyncReactiveField, isChangeableField, isCollection, isCollectionField, isDefined, isEntity, isFactoryCreation, isFieldSet, isId, isInTrustedContext, isKey, isLazyField, isLensLoaded, isLensLoadedPath, isLoaded, isLoadedAsyncProperty, isLoadedCollection, isLoadedLazyField, isLoadedOneToOneReference, isLoadedProperty, isLoadedReadOnlyCollection, isLoadedReference, isManyToManyEnumField, isManyToManyField, isManyToOneField, isManyToOneReference, isNew, isNewEntity, isOneToManyField, isOneToOneField, isOneToOneReference, isPolymorphicField, isPolymorphicReference, isProperty, isReactiveField, isReactiveGetter, isReactiveManyToMany, isReactiveManyToManyOtherSide, isReactiveReference, isReadOnlyCollection, isReference, isReferenceField, isRelation, isScope, isScopeJoinFilter, isSelectAllFilter, isTable, isTaggedId, isTypeOrSubType, keyToNumber, keyToTaggedId, kq, kqDot, kqStar, lazyExcludedSelects, lazyField, lensPathToLoadHint, lensToLoadHint, lensToPath, loadLens, loadLensPath, makeLike, mapPathsToTarget, mapToDb, maxValueRule, maybeAddIdNotNulls, maybeAddNotSoftDeleted, maybeAddOrderBy, maybeBranchValue, maybeGetConstructorFromReference, maybeNew, maybeNewPoly, maybePopulateThen, maybeRequireTemporal, maybeResolveReferenceToId, mergeFindOptions, minValueRule, mustBeSubType, newAliasProxy, newChangesProxy, newPgConnectionConfig, newRequiredLazyFieldRule, newRequiredRule, newScopeFn, newTableProxy, newTestInstance, noValue, noopFieldLogger, normalizeHint, nowUTC, opToFn, operators, optimizeCollectionJoins, parseAlias, parseEntityFilter, parseFindQuery, parseValueFilter, partition, plainDateMapper, plainDateTimeMapper, plainTimeMapper, polymorphicField, query, queryMaybe, rangeValueRule, recursiveQuery, requireTemporal, resetBootFlag, resetDefaultEntityLimit, resolveScope, reverseReactiveHint, runInTrustedContext, sameEntity, sameReference, setDefaultEntityLimit, setFactoryLogging, setFactoryWriter, setField, setLastNow, setOpt, setOpts, setReactionLogging, setRuntimeConfig, setTaggedIdDelimiter, skipCondition, sql, stiSubtypeFilter, subqueryBrand, table, tableMgmt, tables, tagFromId, tagId, tagIds, taggedIdPrefix, testIndex, testing, toIdOf, toJSON, toTaggedId, unsafeDeTagIds, unsafeLoaded, updatePartial, upsert, visitConditions, withLoaded, zeroTo, zonedDateTimeMapper };
|
|
196
199
|
|
|
197
200
|
//# sourceMappingURL=index.js.map
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { getDefaultDependencies } from \"src/defaults.ts\";\nimport { type Entity } from \"src/Entity.ts\";\nimport { type EntityConstructor, type MaybeAbstractEntityConstructor } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, getBaseMeta, getMetadata } from \"src/EntityMetadata.ts\";\nimport { getField, setField } from \"src/fields.ts\";\nimport { getProperties } from \"src/getProperties.ts\";\nimport type { New } from \"src/loading/loadHints.ts\";\nimport { isAllSqlPaths } from \"src/loading/loadLens.ts\";\nimport { FactoryInitialValue } from \"src/newTestInstance.ts\";\nimport { partitionHint } from \"src/preloading/partitionHint.ts\";\nimport { buildWhereClause } from \"src/queries/renderConditions.ts\";\nimport { AbstractRelationImpl } from \"src/relations/AbstractRelationImpl.ts\";\nimport { AsyncReactiveFieldImpl } from \"src/relations/AsyncReactiveField.ts\";\nimport {\n isAsyncProperty,\n isAsyncReactiveField,\n isLazyField,\n isProperty,\n isReactiveField,\n isReactiveGetter,\n} from \"src/relations/index.ts\";\nimport { ReactiveFieldImpl } from \"src/relations/ReactiveField.ts\";\nimport { type OptsOf } from \"src/typeMap.ts\";\nimport { fail } from \"src/utils.ts\";\n\nexport const testing = { isAllSqlPaths, getDefaultDependencies, partitionHint };\nexport const internals = { buildWhereClause };\nexport { newPgConnectionConfig } from \"joist-utils\";\nexport { AliasAssigner } from \"src/queries/sql/AliasAssigner.ts\";\nexport type { JoinTree } from \"src/queries/sql/JoinTree.ts\";\nexport {\n type AndCondition,\n type ConditionGroup,\n type DomainPredicate,\n type OrCondition,\n type PredicateBrand,\n type SqlCondition,\n type SqlPredicate,\n} from \"src/queries/conditions.ts\";\n// Domain aliases belong to em.find; physical table expressions belong to em.query/em.execute.\nexport {\n alias,\n aliases,\n getAliasMetadata,\n getAliasMgmt,\n getMaybeCtiAlias,\n isAlias,\n newAliasProxy,\n type Alias,\n type AliasBrand,\n type AliasMgmt,\n type AliasColumn,\n type EntityAlias,\n type PolyAlias,\n type PrimitiveAlias,\n} from \"src/queries/find/Aliases.ts\";\nexport {\n table,\n tables,\n tableMgmt,\n getTableMetadata,\n getTableMgmt,\n isTable,\n newTableProxy,\n type Table,\n type TableFilter,\n type TableBrand,\n type TableSourceBrand,\n type TableFor,\n type TableMgmt,\n type TableSourceMgmt,\n type ReferenceJoin,\n type PrimitiveColumn,\n type EntityColumn,\n type ReferenceColumn,\n type CollectionJoin,\n type PolyReference,\n} from \"src/queries/sql/Tables.ts\";\nexport {\n declareTable,\n type CustomColumnConfig,\n type CustomColumnInput,\n type CustomColumnInputs,\n type CustomColumnType,\n type CustomTable,\n type CustomTableDefinition,\n type CustomTableFor,\n} from \"src/queries/sql/custom.ts\";\nexport { BaseEntity, getInstanceData } from \"src/BaseEntity.ts\";\nexport { ConditionBuilder } from \"src/queries/ConditionBuilder.ts\";\nexport { type Entity, type IdType, isEntity } from \"src/Entity.ts\";\nexport type * from \"src/EntityFields.ts\";\nexport * from \"src/queries/find/EntityFilter.ts\";\nexport * from \"src/queries/find/EntityGraphQLFilter.ts\";\nexport * from \"src/EntityManager.ts\";\nexport * from \"src/EntityMetadata.ts\";\nexport type {\n DeleteStatement,\n ExecuteResult,\n InsertStatement,\n InsertValues,\n MutationReturning,\n MutationStatement,\n UpdateStatement,\n UpdateValues,\n} from \"src/queries/sql/execute.ts\";\nexport type { EnumMetadata } from \"src/EnumMetadata.ts\";\n// `em.query`'s expression surface. Only the user-facing types are re-exported: the runtime half\n// (BaseExpr, asNode, deferredCondition, the FnExpr/TemplateExpr node classes) stays internal to\n// joist-core, so `toSql`/`decode`/`encode` never show up as something a user could call.\nexport {\n type ArrayAggOptions,\n type Expr,\n type ExprBrand,\n exprBrand,\n type ExprLike,\n type InnerJoin,\n type LeftJoin,\n} from \"src/queries/sql/Expr.ts\";\nexport {\n expr,\n type CaseElse,\n type CaseWhen,\n type ExprFromInput,\n type ExprInput,\n} from \"src/queries/sql/expressions/expression.ts\";\nexport { skipCondition } from \"src/queries/skipCondition.ts\";\nexport type { EntityOrId, HintNode } from \"src/loading/HintTree.ts\";\nexport { InstanceData } from \"src/InstanceData.ts\";\nexport { type JoinColumnValue, type JoinRow, JoinRowOperation, type ManyToManyLike } from \"src/flush/JoinRows.ts\";\nexport type * from \"src/flush/PendingChanges.ts\";\nexport { Plugin } from \"src/PluginManager.ts\";\nexport * from \"src/queries/find/QueryParser.ts\";\nexport * from \"src/queries/find/buildFindQuery.ts\";\nexport * from \"src/queries/renderConditions.ts\";\nexport type {\n ColumnCondition,\n ExistsCondition,\n ParsedExpressionCondition,\n ParsedExpressionFilter,\n ParsedValueFilter,\n RawCondition,\n} from \"src/queries/parsedConditions.ts\";\nexport {\n type ParsedEntityFilter,\n makeLike,\n mapToDb,\n parseEntityFilter,\n parseValueFilter,\n} from \"src/queries/valueFilters.ts\";\nexport {\n filterSoftDeletes,\n lazyExcludedSelects,\n maybeAddNotSoftDeleted,\n stiSubtypeFilter,\n} from \"src/queries/entityQueryUtils.ts\";\nexport * from \"src/queries/find/QueryParser.collectionJoins.ts\";\nexport { visitConditions } from \"src/queries/find/QueryVisitor.ts\";\nexport * from \"src/RowData.ts\";\nexport { type JoinRowTodo, Todo } from \"src/flush/Todo.ts\";\nexport * from \"src/changes.ts\";\nexport { ConfigApi, type EntityHook, resetBootFlag } from \"src/config.ts\";\nexport {\n configureMetadata,\n getConstructorFromTaggedId,\n getMetadataForTable,\n getMetadataForType,\n maybeGetConstructorFromReference,\n} from \"src/configure.ts\";\nexport { driverApi } from \"src/drivers/driverApi.ts\";\nexport * from \"src/drivers/index.ts\";\nexport { getField, isChangeableField, isFieldSet, setField } from \"src/fields.ts\";\nexport * from \"src/getProperties.ts\";\nexport * from \"src/json.ts\";\nexport * from \"src/keys.ts\";\nexport { kq, kqDot, kqStar } from \"src/queries/sql/keywords.ts\";\nexport {\n assertLoaded,\n type DeepNew,\n ensureLoaded,\n isLoaded,\n isNew,\n type Loadable,\n type Loaded,\n type LoadHint,\n type MarkLoaded,\n maybePopulateThen,\n type NestedLoadHint,\n type New,\n type RelationsIn,\n unsafeLoaded,\n} from \"src/loading/loadHints.ts\";\nexport * from \"src/loading/loadLens.ts\";\nexport { setFactoryWriter } from \"src/logging/FactoryLogger.ts\";\nexport * from \"src/logging/FieldLogger.ts\";\nexport { ReactionLogger, setReactionLogging } from \"src/logging/ReactionLogger.ts\";\nexport { lazyField } from \"src/newEntity.ts\";\nexport {\n defaultValue,\n factories,\n type FactoryEntityOpt,\n type FactoryOpts,\n getTestIndex,\n isFactoryCreation,\n maybeBranchValue,\n maybeNew,\n maybeNewPoly,\n newTestInstance,\n noValue,\n setFactoryLogging,\n testIndex,\n} from \"src/newTestInstance.ts\";\nexport { deepNormalizeHint, normalizeHint } from \"src/normalizeHints.ts\";\nexport { ImmutableEntitiesPlugin } from \"src/plugins/ImmutableEntitiesPlugin.ts\";\nexport type { JoinResult, PreloadHydrator, PreloadPlugin } from \"src/plugins/PreloadPlugin.ts\";\nexport { JsonAggregatePreloader } from \"src/preloading/JsonAggregatePreloader.ts\";\n// `em.query`'s query surface; the parse pipeline (SubqueryHandle, parseUserQuery, Plan) stays internal\nexport {\n type CheckScope,\n type Clauses,\n type EntityQuery,\n type ExpressionOrderBy,\n type ExistsQuery,\n entityQueryBrand,\n type MaybeNull,\n type NameOf,\n type NotWidened,\n type OrderByDirection,\n type OrderByKeys,\n type Query,\n type QueryArg,\n type QueryCondition,\n type QueryJoin,\n type QueryJoinInput,\n type QueryJoinList,\n type QueryRow,\n type QuerySelect,\n type QuerySource,\n type QueryValue,\n recursiveQuery,\n type RecursiveOptions,\n type ResolvedJoins,\n type ScalarQuery,\n type SetQuery,\n query,\n queryMaybe,\n sql,\n type Subquery,\n type SubqueryBrand,\n subqueryBrand,\n type WithInput,\n type WithSource,\n} from \"src/queries/sql/query.ts\";\nexport {\n convertToLoadHint,\n isTypeOrSubType,\n type Reactable,\n type Reacted,\n type ReactiveHint,\n type ReactiveTarget,\n reverseReactiveHint,\n} from \"src/reactivity/reactiveHints.ts\";\nexport * from \"src/relations/index.ts\";\nexport {\n cannotBeChanged,\n cannotBeUpdated,\n type GenericError,\n maxValueRule,\n minValueRule,\n mustBeSubType,\n newRequiredLazyFieldRule,\n newRequiredRule,\n rangeValueRule,\n ValidationCode,\n type ValidationError,\n ValidationErrors,\n type ValidationRule,\n type ValidationRuleInternal,\n type ValidationRuleResult,\n} from \"src/rules.ts\";\nexport { getRuntimeConfig, setRuntimeConfig, type RuntimeConfig } from \"src/runtimeConfig.ts\";\nexport { nowUTC } from \"src/nowUTC.ts\";\nexport * from \"src/serde/serde.ts\";\nexport * from \"src/serde/columns.ts\";\nexport * from \"src/serde/fieldSerde.ts\";\nexport * from \"src/queries/find/scopes.ts\";\nexport { maybeRequireTemporal, requireTemporal, Temporal } from \"src/serde/temporal.ts\";\nexport * from \"src/serde/temporalMappers.ts\";\nexport { isInTrustedContext, runInTrustedContext } from \"src/trusted.ts\";\nexport type * from \"src/typeMap.ts\";\nexport { buildUnnestCte, ensureRectangularArraySizes } from \"src/queries/unnest.ts\";\nexport { type DeepPartialOrNull, updatePartial, upsert } from \"src/upsert.ts\";\nexport {\n abbreviation,\n asNew,\n assertNever,\n cleanSql,\n cleanStringValue,\n fail,\n failIfAnyRejected,\n indexBy,\n partition,\n zeroTo,\n} from \"src/utils.ts\";\nexport { ensureWithLoaded, StubbedRelation, type WithLoaded, withLoaded } from \"src/loading/withLoaded.ts\";\n\n// https://spin.atomicobject.com/2018/01/15/typescript-flexible-nominal-typing/\ninterface Flavoring<FlavorT> {\n _type?: FlavorT;\n}\n\nexport type Flavor<T, FlavorT> = T & Flavoring<FlavorT>;\n\n/**\n * Sets each value in `values` on the current entity.\n *\n * The default behavior is that passing a value as either `null` or `undefined` will set\n * the field as `undefined`, i.e. automatic `null` to `undefined` conversion.\n *\n * However, if you pass `ignoreUndefined: true`, then any opt that is `undefined` will be treated\n * as \"do not set\", and `null` will still mean \"set to `undefined`\". This is useful for implementing\n * APIs were an input of `undefined` means \"do not set / noop\" and `null` means \"unset\".\n *\n * Note that constructors _always_ call this method, but if the call is coming from `em.hydrate`, we\n * use `values` being a primary key to short-circuit and let hydration callers assign the values\n * returned by the serde `fromRow` methods.\n */\nexport function setOpts<T extends Entity>(\n entity: T,\n values: Partial<OptsOf<T>> | undefined,\n opts?: { partial?: boolean; calledFromConstructor?: boolean },\n): void {\n const { calledFromConstructor = false, partial } = opts || {};\n // If `values` is undefined, we're being called by `createPartial` that will do its\n // own opt handling, but we still want the sync defaults applied after this opts handling.\n if (values !== undefined) {\n const meta = getMetadata(entity);\n for (const [key, _value] of Object.entries(values as {})) {\n setOpt(meta, entity, key, _value, partial, calledFromConstructor);\n }\n }\n}\n\n/**\n * Applies some standard behavior & protections to `entity[key] = value`. I.e.\n *\n * - We don't set over AsyncProperties/relations/etc., and instead call current.set(value)\n * - We catch missing/invalid field names\n * - We handle FactoryInitialValues\n */\nexport function setOpt<T extends Entity>(\n meta: EntityMetadata<T>,\n entity: T,\n key: string,\n _value: any,\n partial = false,\n calledFromConstructor = false,\n): void {\n const field = meta.allFields[key];\n if (!field) {\n // Allow setting non-field properties like fullName setters\n const prop = getProperties(meta)[key];\n if (!prop) {\n throw new Error(`Unknown field ${key}`);\n }\n }\n\n // If partial is set, we treat undefined as a noop\n if (partial && _value === undefined) return;\n // Ignore the STI discriminator, em.register will set this accordingly\n if (meta.inheritanceType === \"sti\" && getBaseMeta(meta).stiDiscriminatorField === key) return;\n\n // We let optional opts fields be `| null` for convenience, and convert to undefined.\n const value = _value === null ? undefined : _value;\n\n // Use `getField` to side-step `id` blowing up on new entities that are setting an\n // explicit id; otherwise use `entity[key]` to get back the relation.\n const current = key === \"id\" ? getField(entity, key) : (entity as any)[key];\n\n if (current instanceof AbstractRelationImpl) {\n if (calledFromConstructor) {\n current.setFromOpts(value);\n } else {\n current.set(value);\n }\n } else if (isLazyField(current)) {\n current.set(value);\n } else if (isProperty(current) || isAsyncProperty(current) || isReactiveGetter(current)) {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n } else if (isReactiveField(current) || isAsyncReactiveField(current)) {\n if (value instanceof FactoryInitialValue) {\n if (current instanceof ReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else if (current instanceof AsyncReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else {\n throw new Error(`Unhandled case ${current.constructor.name}`);\n }\n } else {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n }\n } else {\n // If setting an explicit id, go through setField, otherwise use\n // `entity[key]` to set the value directly to that we go through setters.\n if (key === \"id\" && entity.isNewEntity) {\n setField(entity, key, value);\n } else {\n (entity as any)[key] = value;\n }\n }\n}\n\nexport function ensureNotDeleted(entity: Entity, ignore?: \"pending\"): void {\n if (entity.isDeletedEntity && (ignore === undefined || getInstanceData(entity).isDeletedAndFlushed)) {\n fail(`${entity} is marked as deleted`);\n }\n}\n\n/** Adds `null` to every key in `T` to accept partial-update-style input. */\nexport type PartialOrNull<T> = {\n [P in keyof T]?: T[P] | null;\n};\n\nexport function getRequiredKeys<T extends Entity>(entity: T): string[];\nexport function getRequiredKeys<T extends Entity>(type: EntityConstructor<T>): string[];\nexport function getRequiredKeys<T extends Entity>(entityOrType: T | EntityConstructor<T>): string[] {\n return Object.values(getMetadata(entityOrType as any).fields)\n .filter((f) => f.required)\n .map((f) => f.fieldName);\n}\n\nexport function getRelations(entity: Entity): AbstractRelationImpl<any, any>[] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => (entity as any)[name]);\n}\n\nexport function getRelationEntries(entity: Entity): [string, AbstractRelationImpl<any, any>][] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => [name, (entity as any)[name]]);\n}\n\n/** Casts a \"maybe abstract\" cstr to a concrete cstr when the calling code knows it's safe. */\nexport function asConcreteCstr<T extends Entity>(cstr: MaybeAbstractEntityConstructor<T>): EntityConstructor<T> {\n return cstr as any;\n}\n\n/**\n * Thrown when `.id` is accessed on an entity that does not have an id yet.\n *\n * For Postgres, entities are actually allowed to have ids pre-INSERT, if you call\n * `em.assignNewIds()`. Other databases typically require INSERTs to trigger the auto\n * id assignment.\n */\nexport class NoIdError extends Error {}\n\n/** Throws a `NoIdError` for `entity`, i.e. because `id` was called before being saved. */\nexport function failNoIdYet(entity: string): never {\n throw new NoIdError(`${entity} has no id yet`);\n}\n\n/**\n * Add a static function since getters can't have type guards.\n *\n * See https://github.com/microsoft/TypeScript/issues/43368\n */\nexport function isNewEntity<T extends Entity>(entity: T): entity is New<T> {\n return entity.isNewEntity;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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/BaseEntity.ts\";\nimport { getDefaultDependencies } from \"src/defaults.ts\";\nimport { type Entity } from \"src/Entity.ts\";\nimport { type EntityConstructor, type MaybeAbstractEntityConstructor, getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, getBaseMeta, getMetadata } from \"src/EntityMetadata.ts\";\nimport { getField, setField } from \"src/fields.ts\";\nimport { getProperties } from \"src/getProperties.ts\";\nimport type { New } from \"src/loading/loadHints.ts\";\nimport { isAllSqlPaths } from \"src/loading/loadLens.ts\";\nimport { FactoryInitialValue } from \"src/newTestInstance.ts\";\nimport { partitionHint } from \"src/preloading/partitionHint.ts\";\nimport { buildWhereClause } from \"src/queries/renderConditions.ts\";\nimport { AbstractRelationImpl } from \"src/relations/AbstractRelationImpl.ts\";\nimport { AsyncReactiveFieldImpl } from \"src/relations/AsyncReactiveField.ts\";\nimport {\n isAsyncProperty,\n isAsyncReactiveField,\n isLazyField,\n isProperty,\n isReactiveField,\n isReactiveGetter,\n} from \"src/relations/index.ts\";\nimport { ReactiveFieldImpl } from \"src/relations/ReactiveField.ts\";\nimport { type OptsOf } from \"src/typeMap.ts\";\nimport { fail } from \"src/utils.ts\";\n\nexport const testing = { isAllSqlPaths, getDefaultDependencies, partitionHint };\nexport const internals = { buildWhereClause };\nexport { newPgConnectionConfig } from \"joist-utils\";\nexport { AliasAssigner } from \"src/queries/sql/AliasAssigner.ts\";\nexport type { JoinTree } from \"src/queries/sql/JoinTree.ts\";\nexport {\n type AndCondition,\n type ConditionGroup,\n type DomainPredicate,\n type OrCondition,\n type PredicateBrand,\n type SqlCondition,\n type SqlPredicate,\n} from \"src/queries/conditions.ts\";\n// Domain aliases belong to em.find; physical table expressions belong to em.query/em.execute.\nexport {\n alias,\n aliases,\n getAliasMetadata,\n getAliasMgmt,\n getMaybeCtiAlias,\n isAlias,\n newAliasProxy,\n type Alias,\n type AliasBrand,\n type AliasMgmt,\n type AliasColumn,\n type EntityAlias,\n type PolyAlias,\n type PrimitiveAlias,\n} from \"src/queries/find/Aliases.ts\";\nexport {\n table,\n tables,\n tableMgmt,\n getTableMetadata,\n getTableMgmt,\n isTable,\n newTableProxy,\n type Table,\n type TableFilter,\n type TableBrand,\n type TableSourceBrand,\n type TableFor,\n type TableMgmt,\n type TableSourceMgmt,\n type ReferenceJoin,\n type PrimitiveColumn,\n type EntityColumn,\n type ReferenceColumn,\n type CollectionJoin,\n type PolyReference,\n} from \"src/queries/sql/Tables.ts\";\nexport {\n declareTable,\n type CustomColumnConfig,\n type CustomColumnInput,\n type CustomColumnInputs,\n type CustomColumnType,\n type CustomTable,\n type CustomTableDefinition,\n type CustomTableFor,\n} from \"src/queries/sql/custom.ts\";\nexport { BaseEntity, getInstanceData } from \"src/BaseEntity.ts\";\nexport { ConditionBuilder } from \"src/queries/ConditionBuilder.ts\";\nexport { type Entity, type IdType, isEntity } from \"src/Entity.ts\";\nexport type * from \"src/EntityFields.ts\";\nexport * from \"src/queries/find/EntityFilter.ts\";\nexport * from \"src/queries/find/EntityGraphQLFilter.ts\";\nexport * from \"src/EntityManager.ts\";\nexport * from \"src/EntityMetadata.ts\";\nexport type {\n DeleteStatement,\n ExecuteResult,\n InsertStatement,\n InsertValues,\n MutationReturning,\n MutationStatement,\n UpdateStatement,\n UpdateValues,\n} from \"src/queries/sql/execute.ts\";\nexport type { EnumMetadata } from \"src/EnumMetadata.ts\";\n// `em.query`'s expression surface. Only the user-facing types are re-exported: the runtime half\n// (BaseExpr, asNode, deferredCondition, the FnExpr/TemplateExpr node classes) stays internal to\n// joist-core, so `toSql`/`decode`/`encode` never show up as something a user could call.\nexport {\n type ArrayAggOptions,\n type Expr,\n type ExprBrand,\n exprBrand,\n type ExprLike,\n type InnerJoin,\n type LeftJoin,\n} from \"src/queries/sql/Expr.ts\";\nexport {\n expr,\n type CaseElse,\n type CaseWhen,\n type ExprFromInput,\n type ExprInput,\n} from \"src/queries/sql/expressions/expression.ts\";\nexport { skipCondition } from \"src/queries/skipCondition.ts\";\nexport type { EntityOrId, HintNode } from \"src/loading/HintTree.ts\";\nexport { InstanceData } from \"src/InstanceData.ts\";\nexport { type JoinColumnValue, type JoinRow, JoinRowOperation, type ManyToManyLike } from \"src/flush/JoinRows.ts\";\nexport type * from \"src/flush/PendingChanges.ts\";\nexport { Plugin } from \"src/PluginManager.ts\";\nexport * from \"src/queries/find/QueryParser.ts\";\nexport * from \"src/queries/find/buildFindQuery.ts\";\nexport * from \"src/queries/renderConditions.ts\";\nexport type {\n ColumnCondition,\n ExistsCondition,\n ParsedExpressionCondition,\n ParsedExpressionFilter,\n ParsedValueFilter,\n RawCondition,\n} from \"src/queries/parsedConditions.ts\";\nexport {\n type ParsedEntityFilter,\n makeLike,\n mapToDb,\n parseEntityFilter,\n parseValueFilter,\n} from \"src/queries/valueFilters.ts\";\nexport {\n filterSoftDeletes,\n lazyExcludedSelects,\n maybeAddNotSoftDeleted,\n stiSubtypeFilter,\n} from \"src/queries/entityQueryUtils.ts\";\nexport * from \"src/queries/find/QueryParser.collectionJoins.ts\";\nexport { visitConditions } from \"src/queries/find/QueryVisitor.ts\";\nexport * from \"src/RowData.ts\";\nexport { type JoinRowTodo, Todo } from \"src/flush/Todo.ts\";\nexport * from \"src/changes.ts\";\nexport { ConfigApi, type EntityHook, resetBootFlag } from \"src/config.ts\";\nexport { type GuardTransitionMatch, type OnTransitionMatch, type TransitionTable } from \"src/transitions.ts\";\nexport {\n configureMetadata,\n getConstructorFromTaggedId,\n getMetadataForTable,\n getMetadataForType,\n maybeGetConstructorFromReference,\n} from \"src/configure.ts\";\nexport { driverApi } from \"src/drivers/driverApi.ts\";\nexport * from \"src/drivers/index.ts\";\nexport { getField, isChangeableField, isFieldSet, setField } from \"src/fields.ts\";\nexport * from \"src/getProperties.ts\";\nexport * from \"src/json.ts\";\nexport * from \"src/keys.ts\";\nexport { kq, kqDot, kqStar } from \"src/queries/sql/keywords.ts\";\nexport {\n assertLoaded,\n type DeepNew,\n ensureLoaded,\n isLoaded,\n isNew,\n type Loadable,\n type Loaded,\n type LoadHint,\n type MarkLoaded,\n maybePopulateThen,\n type NestedLoadHint,\n type New,\n type RelationsIn,\n unsafeLoaded,\n} from \"src/loading/loadHints.ts\";\nexport * from \"src/loading/loadLens.ts\";\nexport { setFactoryWriter } from \"src/logging/FactoryLogger.ts\";\nexport * from \"src/logging/FieldLogger.ts\";\nexport { ReactionLogger, setReactionLogging } from \"src/logging/ReactionLogger.ts\";\nexport { lazyField } from \"src/newEntity.ts\";\nexport {\n defaultValue,\n factories,\n type FactoryEntityOpt,\n type FactoryOpts,\n getTestIndex,\n isFactoryCreation,\n maybeBranchValue,\n maybeNew,\n maybeNewPoly,\n newTestInstance,\n noValue,\n setFactoryLogging,\n testIndex,\n} from \"src/newTestInstance.ts\";\nexport { deepNormalizeHint, normalizeHint } from \"src/normalizeHints.ts\";\nexport { ImmutableEntitiesPlugin } from \"src/plugins/ImmutableEntitiesPlugin.ts\";\nexport type { JoinResult, PreloadHydrator, PreloadPlugin } from \"src/plugins/PreloadPlugin.ts\";\nexport { JsonAggregatePreloader } from \"src/preloading/JsonAggregatePreloader.ts\";\n// `em.query`'s query surface; the parse pipeline (SubqueryHandle, parseRootQuery, Plan) stays internal\nexport {\n type CheckScope,\n type Clauses,\n type EntityQuery,\n type ExpressionOrderBy,\n type ExistsQuery,\n entityQueryBrand,\n type MaybeNull,\n type NameOf,\n type NotWidened,\n type OrderByDirection,\n type OrderByKeys,\n type Query,\n type QueryArg,\n type QueryCondition,\n type QueryJoin,\n type QueryJoinInput,\n type QueryJoinList,\n type QueryRow,\n type QuerySelect,\n type QuerySource,\n type QueryValue,\n recursiveQuery,\n type RecursiveOptions,\n type ResolvedJoins,\n type ScalarQuery,\n type SetQuery,\n query,\n queryMaybe,\n sql,\n type QueryTable,\n type QueryTableBrand,\n type Subquery,\n type SubqueryBrand,\n subqueryBrand,\n type WithInput,\n type WithSource,\n} from \"src/queries/sql/query.ts\";\nexport {\n convertToLoadHint,\n isTypeOrSubType,\n type Reactable,\n type Reacted,\n type ReactiveHint,\n type ReactiveTarget,\n reverseReactiveHint,\n} from \"src/reactivity/reactiveHints.ts\";\nexport * from \"src/relations/index.ts\";\nexport {\n cannotBeChanged,\n cannotBeUpdated,\n type GenericError,\n maxValueRule,\n minValueRule,\n mustBeSubType,\n newRequiredLazyFieldRule,\n newRequiredRule,\n rangeValueRule,\n ValidationCode,\n type ValidationError,\n ValidationErrors,\n type ValidationRule,\n type ValidationRuleInternal,\n type ValidationRuleResult,\n} from \"src/rules.ts\";\nexport { getRuntimeConfig, setRuntimeConfig, type RuntimeConfig } from \"src/runtimeConfig.ts\";\nexport { nowUTC } from \"src/nowUTC.ts\";\nexport * from \"src/serde/serde.ts\";\nexport * from \"src/serde/columns.ts\";\nexport * from \"src/serde/fieldSerde.ts\";\nexport * from \"src/queries/find/scopes.ts\";\nexport { maybeRequireTemporal, requireTemporal, Temporal } from \"src/serde/temporal.ts\";\nexport * from \"src/serde/temporalMappers.ts\";\nexport { isInTrustedContext, runInTrustedContext } from \"src/trusted.ts\";\nexport type * from \"src/typeMap.ts\";\nexport { buildUnnestCte, ensureRectangularArraySizes } from \"src/queries/unnest.ts\";\nexport { type DeepPartialOrNull, updatePartial, upsert } from \"src/upsert.ts\";\nexport {\n abbreviation,\n asNew,\n assertNever,\n cleanSql,\n cleanStringValue,\n fail,\n failIfAnyRejected,\n indexBy,\n partition,\n zeroTo,\n} from \"src/utils.ts\";\nexport { ensureWithLoaded, StubbedRelation, type WithLoaded, withLoaded } from \"src/loading/withLoaded.ts\";\n\n// https://spin.atomicobject.com/2018/01/15/typescript-flexible-nominal-typing/\ninterface Flavoring<FlavorT> {\n _type?: FlavorT;\n}\n\nexport type Flavor<T, FlavorT> = T & Flavoring<FlavorT>;\n\n/**\n * Sets each value in `values` on the current entity.\n *\n * The default behavior is that passing a value as either `null` or `undefined` will set\n * the field as `undefined`, i.e. automatic `null` to `undefined` conversion.\n *\n * However, if you pass `ignoreUndefined: true`, then any opt that is `undefined` will be treated\n * as \"do not set\", and `null` will still mean \"set to `undefined`\". This is useful for implementing\n * APIs were an input of `undefined` means \"do not set / noop\" and `null` means \"unset\".\n *\n * Note that constructors _always_ call this method, but if the call is coming from `em.hydrate`, we\n * use `values` being a primary key to short-circuit and let hydration callers assign the values\n * returned by the serde `fromRow` methods.\n */\nexport function setOpts<T extends Entity>(\n entity: T,\n values: Partial<OptsOf<T>> | undefined,\n opts?: { partial?: boolean; calledFromConstructor?: boolean },\n): void {\n const { calledFromConstructor = false, partial } = opts || {};\n // If `values` is undefined, we're being called by `createPartial` that will do its\n // own opt handling, but we still want the sync defaults applied after this opts handling.\n if (values !== undefined) {\n const meta = getMetadata(entity);\n for (const [key, _value] of Object.entries(values as {})) {\n setOpt(meta, entity, key, _value, partial, calledFromConstructor);\n }\n }\n}\n\n/**\n * Applies some standard behavior & protections to `entity[key] = value`. I.e.\n *\n * - We don't set over AsyncProperties/relations/etc., and instead call current.set(value)\n * - We catch missing/invalid field names\n * - We handle FactoryInitialValues\n */\nexport function setOpt<T extends Entity>(\n meta: EntityMetadata<T>,\n entity: T,\n key: string,\n _value: any,\n partial = false,\n calledFromConstructor = false,\n): void {\n const field = meta.allFields[key];\n if (!field) {\n // Allow setting non-field properties like fullName setters\n const prop = getProperties(meta)[key];\n if (!prop) {\n throw new Error(`Unknown field ${key}`);\n }\n }\n\n // If partial is set, we treat undefined as a noop\n if (partial && _value === undefined) return;\n // Ignore the STI discriminator, em.register will set this accordingly\n if (meta.inheritanceType === \"sti\" && getBaseMeta(meta).stiDiscriminatorField === key) return;\n\n // We let optional opts fields be `| null` for convenience, and convert to undefined.\n const value = _value === null ? undefined : _value;\n\n // Use `getField` to side-step `id` blowing up on new entities that are setting an\n // explicit id; otherwise use `entity[key]` to get back the relation.\n const current = key === \"id\" ? getField(entity, key) : (entity as any)[key];\n\n if (current instanceof AbstractRelationImpl) {\n if (calledFromConstructor) {\n current.setFromOpts(value);\n } else {\n current.set(value);\n }\n } else if (isLazyField(current)) {\n current.set(value);\n } else if (isProperty(current) || isAsyncProperty(current) || isReactiveGetter(current)) {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n } else if (isReactiveField(current) || isAsyncReactiveField(current)) {\n if (value instanceof FactoryInitialValue) {\n if (current instanceof ReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else if (current instanceof AsyncReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else {\n throw new Error(`Unhandled case ${current.constructor.name}`);\n }\n } else {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n }\n } else if (value instanceof FactoryInitialValue) {\n // A factory's `withStatus`-style opt: trust the created value, so its `onTransition`s don't fire\n (entity as any)[key] = value.value;\n getEmInternalApi(entity.em).rm.forgetCreationTransition(entity, key);\n } else {\n // If setting an explicit id, go through setField, otherwise use\n // `entity[key]` to set the value directly to that we go through setters.\n if (key === \"id\" && entity.isNewEntity) {\n setField(entity, key, value);\n } else {\n (entity as any)[key] = value;\n }\n }\n}\n\nexport function ensureNotDeleted(entity: Entity, ignore?: \"pending\"): void {\n if (entity.isDeletedEntity && (ignore === undefined || getInstanceData(entity).isDeletedAndFlushed)) {\n fail(`${entity} is marked as deleted`);\n }\n}\n\n/** Adds `null` to every key in `T` to accept partial-update-style input. */\nexport type PartialOrNull<T> = {\n [P in keyof T]?: T[P] | null;\n};\n\nexport function getRequiredKeys<T extends Entity>(entity: T): string[];\nexport function getRequiredKeys<T extends Entity>(type: EntityConstructor<T>): string[];\nexport function getRequiredKeys<T extends Entity>(entityOrType: T | EntityConstructor<T>): string[] {\n return Object.values(getMetadata(entityOrType as any).fields)\n .filter((f) => f.required)\n .map((f) => f.fieldName);\n}\n\nexport function getRelations(entity: Entity): AbstractRelationImpl<any, any>[] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => (entity as any)[name]);\n}\n\nexport function getRelationEntries(entity: Entity): [string, AbstractRelationImpl<any, any>][] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => [name, (entity as any)[name]]);\n}\n\n/** Casts a \"maybe abstract\" cstr to a concrete cstr when the calling code knows it's safe. */\nexport function asConcreteCstr<T extends Entity>(cstr: MaybeAbstractEntityConstructor<T>): EntityConstructor<T> {\n return cstr as any;\n}\n\n/**\n * Thrown when `.id` is accessed on an entity that does not have an id yet.\n *\n * For Postgres, entities are actually allowed to have ids pre-INSERT, if you call\n * `em.assignNewIds()`. Other databases typically require INSERTs to trigger the auto\n * id assignment.\n */\nexport class NoIdError extends Error {}\n\n/** Throws a `NoIdError` for `entity`, i.e. because `id` was called before being saved. */\nexport function failNoIdYet(entity: string): never {\n throw new NoIdError(`${entity} has no id yet`);\n}\n\n/**\n * Add a static function since getters can't have type guards.\n *\n * See https://github.com/microsoft/TypeScript/issues/43368\n */\nexport function isNewEntity<T extends Entity>(entity: T): entity is New<T> {\n return entity.isNewEntity;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,UAAU;CAAE;CAAe;CAAwB;AAAc;AAC9E,MAAa,YAAY,EAAE,iBAAiB;;;;;;;;;;;;;;;AAgT5C,SAAgB,QACd,QACA,QACA,MACM;CACN,MAAM,EAAE,wBAAwB,OAAO,YAAY,QAAQ,CAAC;CAG5D,IAAI,WAAW,KAAA,GAAW;EACxB,MAAM,OAAO,YAAY,MAAM;EAC/B,KAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,MAAY,GACrD,OAAO,MAAM,QAAQ,KAAK,QAAQ,SAAS,qBAAqB;CAEpE;AACF;;;;;;;;AASA,SAAgB,OACd,MACA,QACA,KACA,QACA,UAAU,OACV,wBAAwB,OAClB;CAEN,IAAI,CADU,KAAK,UAAU,MAIvB;MAAA,CADS,cAAc,IAA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AO,sBAAsB;AAEzC;AASA,SAAgB,gBAAkC,cAAkD;CAClG,OAAO,OAAO,OAAO,YAAY,YAAmB,CAAC,CAAC,MAAM,CAAC,CAC1D,QAAQ,MAAM,EAAE,QAAQ,CAAC,CACzB,KAAK,MAAM,EAAE,SAAS;AAC3B;AAEA,SAAgB,aAAa,QAAkD;CAC7E,OAAO,OAAO,QAAQ,cAAc,YAAY,MAAM,CAAC,CAAC,CAAC,CACtD,QAAQ,GAAG,OAAO,aAAa,oBAAoB,CAAC,CACpD,KAAK,CAAC,UAAW,OAAe,KAAK;AAC1C;AAEA,SAAgB,mBAAmB,QAA4D;CAC7F,OAAO,OAAO,QAAQ,cAAc,YAAY,MAAM,CAAC,CAAC,CAAC,CACtD,QAAQ,GAAG,OAAO,aAAa,oBAAoB,CAAC,CACpD,KAAK,CAAC,UAAU,CAAC,MAAO,OAAe,KAAK,CAAC;AAClD;;AAGA,SAAgB,eAAiC,MAA+D;CAC9G,OAAO;AACT;;;;;;;;AASA,IAAa,YAAb,cAA+B,MAAM,CAAC;;AAGtC,SAAgB,YAAY,QAAuB;CACjD,MAAM,IAAI,UAAU,GAAG,OAAO,eAAe;AAC/C;;;;;;AAOA,SAAgB,YAA8B,QAA6B;CACzE,OAAO,OAAO;AAChB"}
|
package/build/json.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_relations_AbstractRelationImpl = require("./relations/AbstractRelationImpl.cjs");
|
|
3
|
-
const require_normalizeHints = require("./normalizeHints.cjs");
|
|
4
|
-
const require_relations_ReactiveGetter = require("./relations/ReactiveGetter.cjs");
|
|
5
|
-
const require_reactivity_reactiveHints = require("./reactivity/reactiveHints.cjs");
|
|
6
3
|
const require_relations_hasProperty = require("./relations/hasProperty.cjs");
|
|
7
4
|
const require_relations_ReactiveField = require("./relations/ReactiveField.cjs");
|
|
5
|
+
const require_relations_ReactiveGetter = require("./relations/ReactiveGetter.cjs");
|
|
8
6
|
const require_relations_AsyncReactiveField = require("./relations/AsyncReactiveField.cjs");
|
|
9
7
|
require("./relations/index.cjs");
|
|
8
|
+
const require_normalizeHints = require("./normalizeHints.cjs");
|
|
9
|
+
const require_reactivity_reactiveHints = require("./reactivity/reactiveHints.cjs");
|
|
10
10
|
const require_EntityMetadata = require("./EntityMetadata.cjs");
|
|
11
11
|
require("./EntityManager.cjs");
|
|
12
12
|
const require_Entity = require("./Entity.cjs");
|
package/build/json.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { AbstractRelationImpl } from "./relations/AbstractRelationImpl.js";
|
|
2
|
-
import { normalizeHint } from "./normalizeHints.js";
|
|
3
|
-
import { ReactiveGetterImpl } from "./relations/ReactiveGetter.js";
|
|
4
|
-
import { convertToLoadHint } from "./reactivity/reactiveHints.js";
|
|
5
2
|
import { PropertyImpl } from "./relations/hasProperty.js";
|
|
6
3
|
import { ReactiveFieldImpl } from "./relations/ReactiveField.js";
|
|
4
|
+
import { ReactiveGetterImpl } from "./relations/ReactiveGetter.js";
|
|
7
5
|
import { AsyncReactiveFieldImpl } from "./relations/AsyncReactiveField.js";
|
|
8
6
|
import "./relations/index.js";
|
|
7
|
+
import { normalizeHint } from "./normalizeHints.js";
|
|
8
|
+
import { convertToLoadHint } from "./reactivity/reactiveHints.js";
|
|
9
9
|
import { getMetadata } from "./EntityMetadata.js";
|
|
10
10
|
import "./EntityManager.js";
|
|
11
11
|
import { isEntity } from "./Entity.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_reactivity_reactiveHints = require("../reactivity/reactiveHints.cjs");
|
|
3
2
|
const require_utils = require("../utils.cjs");
|
|
3
|
+
const require_reactivity_reactiveHints = require("../reactivity/reactiveHints.cjs");
|
|
4
4
|
//#region src/loading/loadHints.ts
|
|
5
5
|
/** Detects whether an entity is newly created, and so we can treat all the relations as loaded. */
|
|
6
6
|
function isNew(e) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { getRelationFromMaybePolyKey } from "../reactivity/reactiveHints.js";
|
|
2
1
|
import { fail } from "../utils.js";
|
|
2
|
+
import { getRelationFromMaybePolyKey } from "../reactivity/reactiveHints.js";
|
|
3
3
|
//#region src/loading/loadHints.ts
|
|
4
4
|
/** Detects whether an entity is newly created, and so we can treat all the relations as loaded. */
|
|
5
5
|
function isNew(e) {
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_relations_Collection = require("../relations/Collection.cjs");
|
|
3
|
-
const require_relations_ReactiveGetter = require("../relations/ReactiveGetter.cjs");
|
|
4
|
-
const require_relations_Relation = require("../relations/Relation.cjs");
|
|
5
3
|
const require_loading_loadHints = require("./loadHints.cjs");
|
|
6
4
|
const require_relations_hasProperty = require("../relations/hasProperty.cjs");
|
|
7
5
|
const require_relations_Reference = require("../relations/Reference.cjs");
|
|
6
|
+
const require_relations_Relation = require("../relations/Relation.cjs");
|
|
8
7
|
const require_relations_ReactiveField = require("../relations/ReactiveField.cjs");
|
|
8
|
+
const require_relations_ReactiveGetter = require("../relations/ReactiveGetter.cjs");
|
|
9
9
|
const require_relations_AsyncReactiveField = require("../relations/AsyncReactiveField.cjs");
|
|
10
10
|
require("../relations/index.cjs");
|
|
11
11
|
const require_utils = require("../utils.cjs");
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { isLoadedCollection } from "../relations/Collection.js";
|
|
2
|
-
import { isReactiveGetter } from "../relations/ReactiveGetter.js";
|
|
3
|
-
import { isRelation } from "../relations/Relation.js";
|
|
4
2
|
import { assertLoaded } from "./loadHints.js";
|
|
5
3
|
import { isLoadedProperty, isProperty } from "../relations/hasProperty.js";
|
|
6
4
|
import { isLoadedReference } from "../relations/Reference.js";
|
|
5
|
+
import { isRelation } from "../relations/Relation.js";
|
|
7
6
|
import { isReactiveField } from "../relations/ReactiveField.js";
|
|
7
|
+
import { isReactiveGetter } from "../relations/ReactiveGetter.js";
|
|
8
8
|
import { isAsyncReactiveField, isLoadedAsyncReactiveField } from "../relations/AsyncReactiveField.js";
|
|
9
9
|
import "../relations/index.js";
|
|
10
10
|
import { fail, maybePromiseThen } from "../utils.js";
|
|
@@ -140,6 +140,7 @@ function newTestInstance(em, cstr, testOpts = {}, factoryOpts = {}) {
|
|
|
140
140
|
const realName = fieldName[4].toLowerCase() + fieldName.substring(5);
|
|
141
141
|
const realField = meta.allFields[realName];
|
|
142
142
|
if (realField && "derived" in realField && realField.derived === "async") return [realName, new FactoryInitialValue(optValue)];
|
|
143
|
+
if (realField?.kind === "enum" && meta.transitions.has(realName)) return [realName, new FactoryInitialValue(optValue)];
|
|
143
144
|
}
|
|
144
145
|
throw new Error(`Unknown field ${fieldName}`);
|
|
145
146
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"newTestInstance.cjs","names":["maybeRequireTemporal","FactoryLogger","getMetadata","hasDefaultValue","assertNever","isOneToOneField","isEntity","isId","isPlainObject","getBaseSelfAndSubMetas","isManyToOneField","getInstanceData"],"sources":["../src/newTestInstance.ts"],"sourcesContent":["import { isPlainObject } from \"joist-utils\";\nimport { getInstanceData } from \"src/BaseEntity.ts\";\nimport { hasDefaultValue, setAsyncDefaultsSynchronously } from \"src/defaults.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport {\n type EntityConstructor,\n type EntityManager,\n type IdOf,\n type MaybeAbstractEntityConstructor,\n isId,\n} from \"src/EntityManager.ts\";\nimport {\n type EntityMetadata,\n type ManyToManyField,\n type ManyToOneField,\n type OneToManyField,\n type OneToOneField,\n type PolymorphicField,\n type PrimitiveField,\n getBaseAndSelfMetas,\n getBaseSelfAndSubMetas,\n getMetadata,\n isManyToOneField,\n isOneToOneField,\n} from \"src/EntityMetadata.ts\";\nimport { type DeepNew, type FactoryExtrasOf, type New } from \"src/index.ts\";\nimport { FactoryLogger } from \"src/logging/FactoryLogger.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { type ActualFactoryOpts, type OptsOf } from \"src/typeMap.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\nlet logger: FactoryLogger | undefined = undefined;\n\n// Maybe we should scope this per-em, but assuming tests are single-threaded for now\nlet factoryCreated = new WeakSet();\n\n// The last EntityManager used in a factory call, for the `factories` proxy to resolve entities\nlet lastFactoryEm: EntityManager | undefined;\n\nconst factoryKeyRegex = /^([a-zA-Z]+)(\\d+)$/;\n\n/**\n * A proxy that allows accessing factory-created entities by their factory id.\n *\n * For example, after creating entities with `as` keys:\n *\n * ```ts\n * newAuthor(em, { books: [{ is: \"b#1\" }, { is: \"b#2\", prequel: \"b#1\" }] });\n * const { b1, b2 } = factories;\n * ```\n *\n * The proxy parses property names like `b1` into `b#1` and looks up the entity\n * in the most recently used EntityManager.\n */\nexport const factories: Record<string, any> = new Proxy(Object.create(null), {\n get(_target, prop) {\n if (typeof prop !== \"string\") return undefined;\n const match = prop.match(factoryKeyRegex);\n if (!match) throw new Error(`Invalid id '${prop}', expected 'b1' or 'a2'`);\n const [, tag, id] = match;\n if (!lastFactoryEm) throw new Error(\"No EntityManager available; call a factory like newAuthor(em) first\");\n const testId = `${tag}#${id}`;\n const entity = lastFactoryEm.entities.find((e) => getTestId(lastFactoryEm!, e) === testId);\n if (!entity) throw new Error(`No factory entity found for '${testId}'`);\n return entity;\n },\n});\n\n/**\n * DeepPartial-esque type specific to our `newTestInstance` factory.\n *\n * Specifically (vs using DeepPartial directly) this:\n *\n * 1. Adds a `use` tag of `Entity | Entity[]` that will be checked for existing\n * entities before creating new ones (i.e. \"if `newTestInstance` needs a `Book`,\n * use the one in `use` instead of making a new one).\n *\n * 2. Works specifically against the constructor/entity opts fields.\n */\nexport type FactoryOpts<T extends Entity> = DeepPartialOpts<T> & {\n is?: string;\n use?: Entity | Entity[];\n useFactoryDefaults?: boolean | \"none\";\n useExistingCheck?: boolean;\n useLogging?: boolean;\n} & {\n // We use a mapped type here with an explicit `?`, instead of just `FactoryExtrasOf<T>`,\n // so that tsc knows that `{}` is a valid default opts value.\n [K in keyof FactoryExtrasOf<T>]?: FactoryExtrasOf<T>[K];\n};\n\n// Chosen b/c it's a monday https://www.timeanddate.com/calendar/monthly.html?year=2018&month=1&country=1\nconst jan1 = new Date(2018, 0, 1);\nexport const testDate = jan1;\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport const testPlainDate = Temporal?.PlainDate.from(\"2018-01-01\");\nexport const testPlainDateTime = testPlainDate?.toPlainDateTime(\"00:00:00\");\nexport const testZonedDateTime = testPlainDate?.toZonedDateTime(\"UTC\");\n\nconst knownUseKeys = [\"is\", \"use\", \"useLogging\", \"useExistingCheck\", \"useFactoryDefaults\"];\n\n/**\n * Creates a test instance of `T`.\n *\n * If the factory code passes factoryOpts.useExisting, they can \"intercept\" the `em.create`\n * to try and resolve \"already created\" / singleton instances. The `useExisting` callback is\n * useful b/c the `opts` will be the \"resolved-to-entity\" opts, and not the raw \"maybe object\n * literal, maybe object instance\" opts that tests pass into the factory.\n */\nexport function newTestInstance<T extends Entity>(\n em: EntityManager,\n cstr: EntityConstructor<T>,\n /** The test's test-specific override opts. */\n testOpts: FactoryOpts<T> = {},\n /** The factory file's default opts. */\n factoryOpts: FactoryOpts<T> & {\n useExisting?: (opts: OptsOf<T>, existing: DeepNew<T>) => boolean;\n } = {},\n): DeepNew<T> {\n // Remember the em so the `factories` proxy can look up entities\n lastFactoryEm = em;\n\n // The first factory that is asked to debug, without one in place, will create+unset the logger.\n let ownsTheLogger = !logger && testOpts.useLogging;\n if (ownsTheLogger) logger = new FactoryLogger();\n\n logger?.logCreating(cstr);\n logger?.indent();\n\n const meta = getMetadata(cstr);\n const opts = mergeOpts(meta, testOpts, factoryOpts);\n const use = getOrCreateUseMap(opts);\n\n const selfFields: string[] = [];\n\n // Create just the primitive and m2o fields 1st, so we can create a minimal/valid\n // instance of the entity. We'll do the o2m/other fields as a second pass.\n const initialOpts = Object.values(meta.allFields)\n .map((field) => {\n const { fieldName } = field;\n\n // Don't fill in required fields if told not to\n const ignoreAllDefaults = \"useFactoryDefaults\" in opts && opts.useFactoryDefaults === \"none\";\n // If the field has a default value, don't force fill it, even if passed `author: undefined`\n const required = field.required && !ignoreAllDefaults && !hasDefaultValue(meta, fieldName);\n\n // Use the opts value if they passed one in\n if (fieldName in opts && (opts as any)[fieldName] !== defaultValueMarker) {\n const optValue = (opts as any)[fieldName];\n // We don't explicitly support null (callers should pass undefined), but we accept it\n // because the factory might have done `const { author, ... } = opts` and is accidentally\n // passing an `author: undefined` without meaning too.\n const shouldRespectUndefined = !required;\n if (optValue === null || (optValue === undefined && shouldRespectUndefined)) {\n return [];\n }\n switch (field.kind) {\n case \"m2o\":\n case \"poly\":\n return [fieldName, resolveFactoryOpt(em, opts, field, optValue, undefined, undefined)];\n case \"o2o\":\n case \"o2m\":\n case \"m2m\":\n // We do these in the 2nd pass after `entity` exists (see additionalOpts)\n return [];\n case \"m2mEnum\":\n // Enum codes have no entity identity, so pass them straight through.\n return [fieldName, optValue];\n case \"lo2m\":\n // If a child is passing themselves into a parent that is a large collection, just ignore it\n return [];\n case \"primitive\":\n case \"enum\":\n case \"primaryKey\":\n // Look for strings that want to use the test index\n if (typeof optValue === \"string\" && optValue.includes(testIndexString)) {\n const actualIndex = getTestIndex(em, meta.cstr);\n const value = optValue.replace(testIndexString, String(actualIndex));\n return [fieldName, value];\n } else if (typeof optValue === \"number\" && optValue === testIndex) {\n const actualIndex = getTestIndex(em, meta.cstr);\n return [fieldName, actualIndex];\n }\n // Otherwise just use the user's opt value as-is\n return [fieldName, optValue];\n default:\n return assertNever(field);\n }\n }\n\n if (\n field.kind === \"primitive\" &&\n (required || (opts as any)[fieldName] === defaultValueMarker) &&\n !field.derived &&\n !field.protected\n ) {\n return [fieldName, defaultValueForField(em, cstr, field)];\n } else if (field.kind === \"m2o\" && !field.derived) {\n // If neither the user nor the factory (i.e. for an explicit \"fan out\" case) set this field,\n // then look in `use` and for an \"obvious\" there-is-only-one default (even for optional fields)\n const [existing, loggerKey] = getObviousDefault(em, field.otherMetadata(), use);\n // If this is a m2o pointing to an o2o, i.e. that as a unique constraint, make sure the\n // existing entity we found isn't already claimed\n const isUniqueAndAlreadyUsed =\n existing &&\n isOneToOneField(field.otherMetadata().allFields[field.otherFieldName]) &&\n (existing as any)[field.otherFieldName].isLoaded &&\n (existing as any)[field.otherFieldName].isSet;\n if (existing && !isUniqueAndAlreadyUsed && !ignoreAllDefaults) {\n logger?.[loggerKey](fieldName, existing);\n return [fieldName, existing];\n }\n // Otherwise, only make a new entity only if the field is required\n if (required) {\n // ...unless this is a self-referential key, in which case avoid infinite looping.\n if (field.otherMetadata() === meta) {\n selfFields.push(fieldName);\n return [];\n } else {\n return [fieldName, resolveFactoryOpt(em, opts, field, undefined, undefined, undefined)];\n }\n }\n } else if (field.kind === \"enum\" && required && !field.derived) {\n return [fieldName, field.enumDetailType.getValues()[0]];\n } else if (field.kind === \"poly\" && required) {\n return [fieldName, resolveFactoryOpt(em, opts, field, undefined, undefined, undefined)];\n }\n\n return [];\n })\n .filter((t) => t.length > 0);\n\n const createOpts = Object.fromEntries(initialOpts);\n\n if (factoryOpts.useExisting && testOpts.useExistingCheck !== false) {\n const existing = em.entities\n .filter((e) => e instanceof meta.cstr)\n .find((e) => factoryOpts.useExisting!(createOpts as OptsOf<T>, e as DeepNew<T>));\n if (existing) {\n logger?.logFoundExisting(existing);\n logger?.dedent();\n if (ownsTheLogger) logger = undefined;\n return existing as DeepNew<T>;\n }\n }\n\n const entity = em.create(cstr, createOpts) as New<T>;\n\n // Verify the `as` assertion if provided\n if ((opts as any).is) {\n const expected = (opts as any).is;\n const actual = getTestId(em, entity);\n if (actual !== expected) {\n throw new Error(`Test used 'is: ${expected}' but the entity is actually ${actual}`);\n }\n }\n\n // Report this as factory-created until the next em.flush\n factoryCreated.add(entity);\n\n // If the type we just made doesn't exist in `use` yet, remember it. This works better than\n // looking at the values in `fullOpts`, because instead of waiting until the end of the\n // `build fullOpts` loop, we're also invoking `newTestInstance` as we go through the loop itself,\n // creating each test instance within nested/recursive `newTestInstance` calls.\n if (!use.has(entity.constructor) || use.get(entity.constructor)![1] === \"diffBranch\") {\n addToUseMap(use, entity, \"sameBranch\");\n } else {\n // The `addToUseMap` does its own 'created & added to scope'\n logger?.logCreated(entity);\n }\n\n // Now that we've got the entity, do a 2nd pass for o2m/m2m where we pass\n // `{ parent: entity }` down to children (i.e. to replace our original\n // null marker approach).\n const additionalOpts = Object.entries(opts).map(([fieldName, optValue]) => {\n const field = meta.allFields[fieldName];\n // Look for `use` / etc\n if (knownUseKeys.includes(fieldName)) return [];\n if (!field) {\n // Look for extra/derived fields\n if (fieldName.startsWith(\"with\")) {\n const realName = fieldName[4].toLowerCase() + fieldName.substring(5);\n const realField = meta.allFields[realName];\n if (realField && \"derived\" in realField && realField.derived === \"async\") {\n return [realName, new FactoryInitialValue(optValue)];\n }\n }\n throw new Error(`Unknown field ${fieldName}`);\n }\n if (optValue === null || optValue === undefined) return [];\n if (field.kind === \"o2m\") {\n // If this is a list of children, i.e. book.authors, handle partials to newTestInstance'd\n return [\n fieldName,\n (optValue as Array<any>).map((opt, i) => {\n // console.log(`${field.fieldName}`, i);\n return resolveFactoryOpt(em, withBranchMap(opts), field, opt, entity, i);\n }),\n ];\n } else if (field.kind == \"m2m\") {\n return [\n fieldName,\n (optValue as Array<any>).map((opt, i) =>\n resolveFactoryOpt(em, withBranchMap(opts), field, opt, [entity] as any, i),\n ),\n ];\n } else if (field.kind === \"o2o\") {\n const otherField = field.otherMetadata().allFields[field.otherFieldName];\n const isReactiveReference = \"derived\" in otherField && otherField.derived === \"async\";\n if (isReactiveReference) return [];\n // If this is an o2o, i.e. author.image, just pass the optValue (i.e. it won't be a list)\n return [fieldName, resolveFactoryOpt(em, opts, field, optValue as any, entity, undefined)];\n } else {\n return []; // Assume createOpts handled this\n }\n });\n\n for (const fieldName of selfFields) {\n additionalOpts.push([fieldName, entity]);\n }\n\n entity.set(Object.fromEntries(additionalOpts.filter((t) => t.length > 0)));\n\n // em.create applied synchronous defaults automatically; since we're a factory with likely\n // deeply-loaded instances, go ahead and synchronously invoke the async defaults, at least\n // the ones that just use load hints + a synchronous lambda.\n // (...would be nice to log these in the setFactoryLogging output)\n setAsyncDefaultsSynchronously(em.ctx, entity);\n\n // Set it back to undefined\n logger?.dedent();\n if (ownsTheLogger) logger = undefined;\n\n return entity as DeepNew<T>;\n}\n\n/**\n * Resolves a `FactoryEntityOpt` (i.e. maybe an existing entity, maybe an id, maybe a hash of opts) to an entity.\n *\n * If `opt` is `undefined`, then the usual factory semantics of \"check use\", \"look for only one instance\" are\n * checked before finally creating a brand new entity.\n *\n * We also accept an optional `otherFieldName` so that, if we do create a new entity, we pass along the null\n * marker for them to know not to create their own version of us.\n *\n * (This was originally intended to be a public API, but the use case ended up being handled\n * by the more-ergonomic `maybeNew` feature; we could explore making this public if another\n * similar use case comes up in the future.)\n */\nfunction resolveFactoryOpt<T extends Entity>(\n em: EntityManager,\n opts: FactoryOpts<any>,\n field: OneToManyField | ManyToOneField | OneToOneField | ManyToManyField | PolymorphicField,\n opt: FactoryEntityOpt<any> | undefined,\n maybeEntity: T | undefined,\n fieldIndex: number | undefined,\n): T | IdOf<T> {\n const use = getOrCreateUseMap(opts);\n const { meta, otherFieldName } = metaFromFieldAndOpt(field, opt);\n // const meta = field.kind === \"poly\" ? field.components[0].otherMetadata() : field.otherMetadata();\n // const otherFieldName = field.kind === \"poly\" ? field.components[0].otherFieldName : field.otherFieldName;\n const fieldWithIndex = `${field.fieldName}${fieldIndex !== undefined ? `[${fieldIndex}]` : \"\"}`;\n if (isEntity(opt)) {\n logger?.logFoundOpt(fieldWithIndex, opt);\n return opt as T;\n } else if (isId(opt)) {\n // Try finding the entity in the UoW, otherwise fallback on just setting it as the id (which we support that now)\n const found = (em.entities.find((e) => e.idTaggedMaybe === opt || getTestId(em, e) === opt) as T) || opt;\n logger?.logFoundOpt(fieldWithIndex, found);\n return found;\n } else if (opt && !isPlainObject(opt) && !(opt instanceof MaybeNew)) {\n // If opt isn't a POJO, assume this is a completely-custom factory\n logger?.logNotFoundAndCreating(fieldWithIndex, meta);\n return meta.factory(em, opt);\n } else {\n // Look for an obvious default\n if (opt === undefined || opt instanceof MaybeNew) {\n if (\n field.kind === \"poly\" ||\n (field.otherMetadata().subTypes.length > 0 && opt instanceof MaybeNew && opt.polyRefPreferredOrder.length > 0)\n ) {\n // We have a polymorphic maybeNew to sort through\n const [existing, loggerKey] = (opt instanceof MaybeNew\n ? opt.polyRefPreferredOrder.map((cstr) => getMetadata(cstr))\n : field.kind === \"poly\"\n ? field.components.map((c) => c.otherMetadata())\n : [meta]\n )\n .map((meta) => getObviousDefault(em, meta, use))\n .find((existing) => !!existing[0]) || [undefined, undefined];\n if (existing) {\n logger?.[loggerKey](fieldWithIndex, existing);\n return existing as T;\n }\n } else {\n // Otherwise fall though to making a new entity via the factory\n const [existing, loggerKey] = getObviousDefault(em, meta, use);\n if (existing) {\n logger?.[loggerKey](fieldWithIndex, existing);\n return existing as T;\n }\n }\n }\n // If this is image.author (m2o) but the other-side is an o2o, pass null instead of []\n maybeEntity ??= (meta.allFields[otherFieldName].kind === \"o2o\" ? null : []) as any;\n logger?.logNotFoundAndCreating(fieldWithIndex, meta);\n return meta.factory(em, {\n // Because of the `!isPlainObject` above, opt will either be undefined or an object here\n ...applyUse((opt as any) || {}, use, meta),\n ...(opt instanceof MaybeNew && opt.opts),\n [otherFieldName]: maybeEntity,\n });\n }\n}\n\n/** Determines the metadata and otherFieldName to use in resolveFactoryOpt to account for polymorphic fields */\nfunction metaFromFieldAndOpt<T extends Entity>(\n field: OneToManyField | ManyToOneField | OneToOneField | ManyToManyField | PolymorphicField,\n opt: FactoryEntityOpt<T> | undefined,\n): { meta: EntityMetadata; otherFieldName: string } {\n if (field.kind === \"poly\") {\n let componentToUse =\n // Otherwise, we check if the `opt` specifies a particular component to use, and if not fall back to the first one\n field.components.find(\n (component) =>\n opt instanceof MaybeNew &&\n getBaseSelfAndSubMetas(component.otherMetadata())\n .map((m) => m.cstr)\n .includes(opt.polyRefPreferredOrder[0]),\n ) ?? field.components[0];\n return { meta: componentToUse.otherMetadata(), otherFieldName: componentToUse.otherFieldName };\n } else if (\n field.otherMetadata().subTypes.length > 0 &&\n opt instanceof MaybeNew &&\n opt.polyRefPreferredOrder.length > 0\n ) {\n const otherMeta = field.otherMetadata();\n const types = getBaseSelfAndSubMetas(otherMeta);\n const typeToUse = types.find((subType) => subType.cstr === opt.polyRefPreferredOrder[0]) ?? otherMeta;\n return { meta: typeToUse, otherFieldName: field.otherFieldName };\n } else {\n // If it isn't a poly field, then the field itself can tell us everything we need to know\n return { meta: field.otherMetadata(), otherFieldName: field.otherFieldName };\n }\n}\n\n/** We look for `use`-cached entities, which are either those we created, or had \"if-only-one\" defaults. */\nfunction getObviousDefault<T extends Entity>(\n em: EntityManager,\n metadata: EntityMetadata,\n use: UseMap,\n): [T, \"logFoundInUseMap\" | \"logFoundSingleEntity\"] | [undefined, undefined] {\n if (use.has(metadata.cstr)) {\n return [use.get(metadata.cstr)![0] as T, \"logFoundInUseMap\"];\n }\n // If there is a single existing instance of this type, assume the caller is fine with that.\n // ...in theory seeding our `use` map with the only-one entities was supposed to prevent the\n // need for doing this (the entities would already be in the use map that we just checked),\n // but that approach doesn't catch created-as-side-effect entities.\n const existing = em.getEntities(metadata.cstr);\n if (existing.length === 1) {\n return [existing[0] as T, \"logFoundSingleEntity\"];\n }\n return [undefined, undefined];\n}\n\n// When a factory is called, i.e. `newAuthor`, opts will:\n//\n// - Have values explicitly passed by the user/other factories\n// - Have values from the user's explicit `use` parameter\n// - NOT have guessed (i.e. \"only existing entity\") or an implicitly-created `use` parameter\n//\n// This allows the factory to \"fan out\" by default, i.e. newInternalUser creating its own User\n// and Market creating its own ProductAttribute, which originally we couldn't do when\n// guessed/implicit opts were passed directly to `newAuthor`.\n//\n// Now, if the `newAuthor` factory doesn't explicitly \"fan out\" (by passing `user: {}` to\n// `newTestInstance`), we still \"fan in\" by having `newTestInstance` sneak in the guessed/implicit\n// opts of only-one-existing or factory-created instances.\n\n/** Given we're going to call a factory, make sure any `use`s are put into `opts`. */\nfunction applyUse(optsMaybeNew: object, use: UseMap, metadata: EntityMetadata): object {\n const opts = optsMaybeNew instanceof MaybeNew ? optsMaybeNew.opts : optsMaybeNew;\n // Find any unset fields\n Object.values(metadata.fields)\n .filter((f) => !(f.fieldName in opts))\n .forEach((f) => {\n // And set them to the current `use` entity for their type, if it exists\n if (((isManyToOneField(f) && !f.derived) || isOneToOneField(f)) && use.has(f.otherMetadata().cstr)) {\n const def = use.get(f.otherMetadata().cstr)!;\n // Only pass explicit/user-defined `use` entities, so that factories can \"fan out\" if they want,\n // and not see other factory-created entities look like user-specific values.\n if (def[1] === \"useOpt\") {\n (opts as any)[f.fieldName] = def[0];\n }\n }\n });\n // Make a copy so that we don't leak `use` onto opts that tests might later use in assertions.\n return { ...opts, use };\n}\n\n/**\n * A marker value for later replacement with the test instance's \"unique-ish\" index.\n *\n * This is meant to just be a helpful identifier in fields like entity names/descriptions for\n * debugging purposes.\n */\nexport const testIndex: number = -1_111_111_222;\n\nconst testIndexString = String(testIndex);\n\nconst defaultValueMarker: any = {};\nconst branchValueSym = Symbol(\"branchValue\");\n\n/**\n * A marker value for the default `newTestInstance` behavior.\n *\n * Useful for passing arguments to `newTestInstance` where you sometimes want to\n * provide a specific value, and other times ask for the \"pick a default\" behavior\n * (i.e. you don't want to pass `undefined` b/c that means explicitly \"leave this\n * key unset\").\n *\n * Note that this is a function so that we can infer the return type as basically\n * `any` without really using `any` (which would disable type-checking in the rest\n * of the expression).\n */\nexport function defaultValue<T>(): T {\n return defaultValueMarker;\n}\n\n/**\n * A marker value to never set a field, even if it's required.\n *\n * The factories treat `{ author: undefined }` as \"still set the author\", because of how easy\n * it is for destructuring/restructuring opts to implicitly set `undefined` values.\n *\n * If you want to force a field to not be set, you can use `{ author: noValue() }`.\n */\nexport function noValue<T>(): T {\n return null as T;\n}\n\n/**\n * A marker value to accept values only if explicitly created-or-passed within the current,\n * unique \"branch\" of a factory call.\n *\n * This is useful for \"diamond-shape\" entity models like:\n *\n * ```\n * ParentGroup <-- ParentItem\n * | |\n * ChildGroup <-- ChildItem\n * ```\n *\n * Where it's important that the `ChildItem -> ParentItem -> ParentGroup` path matches\n * the `ChildItem -> ChildGroup -> ParentGroup` path.\n *\n * This can be hard to achieve in normal factory behavior, i.e. for a call like:\n *\n * ```ts\n * const c = newChild(em, {\n * groups: [\n * { childItems: [{}, {}] },\n * { childItems: [{}, {}] },\n * ],\n * });\n * ```\n *\n * The first `ChildGroup` will create a new `ParentGroup` that is used by everything, which\n * is not our intent, as both `ChildGroup`s, and all four `ParentItem`s, will live in a single\n * `ParentGroup`.\n *\n * An initial idea is to pass `parentGroup: {}` in the factories, because that turns off \"reusing\n * existing instances\", but for this problem the `{}` approach is \"too good\" at creating new\n * instances, b/c the above diamond pattern will be disconnected.\n *\n * So `branchValue` provides a middle ground, where _usually_ it will be a new entity, unless\n * it was explicitly created within the same \"branch\" of a factory call.\n */\nexport function maybeBranchValue<T>(opts?: ActualFactoryOpts<T>): T {\n // opts get mutated, so we have to return a new value\n return { [branchValueSym]: true, ...(opts ? opts : undefined) } as any;\n}\n\n/**\n * Allows a factory to declare that an optional relation should be filled in with an\n * \"obvious default\", or a new entity if one doesn't exist.\n *\n * This \"obvious default or new entity\" is what Joist already does for _required_ relations,\n * and so `maybeNew` lets the factory tell Joist to apply the same behavior to an optional\n * field.\n *\n * I.e.:\n *\n * ```typescript\n * export function newAuthor(em: Entity, opts: FactoryOpts<Author>) {\n * return newTestInstance(em, Author, {\n * // this always make a new publisher, unless explicitly overridden by the test,\n * // i.e. when each author really needs \"their own\" publisher.\n * publisher: {},\n * // this will make a new publisher but first looks for \"good defaults\" in the\n * // test, i.e. an already-created publisher. This is the default behavior of\n * // required fields (\"look for a good default\"), and `maybeNew` lets you tell\n * // Joist to invoke that same \"maybe new\" behavior for an optional field.\n * publisher: maybeNew<Publisher>({}),\n * ...opts,\n * });\n * }\n * ```\n */\nexport function maybeNew<T extends Entity>(opts?: ActualFactoryOpts<T>): FactoryEntityOpt<T> {\n // Return a marker that resolveFactoryOpt will look for\n return new MaybeNew<T>((opts || {}) as any) as any;\n}\n\n/**\n * Similar to `maybeNew` in behaviour/use but with enhancements to support polymorphic fields:\n * 1) Allows you to specify which entity type to create, if it is found a new one is needed\n * 2) Allows you to prioritize which existing entities to select\n *\n * For example below, we are specifying that an Author should be created if needed (and optionally it's default opts\n * in the `ifNewOpts` field), and also that the priority order for choosing existing entities is Author, Book, and then Publisher.\n * Note since BookReview is excluded from `existingSearchOrder`, an existing BookReview will never be chosen.\n *\n * ```typescript\n * export function newComment(em: EntityManager, opts: FactoryOpts<Comment> = {}): New<Comment> {\n * return newTestInstance(em, Comment, {\n * parent: maybeNewPoly<CommentParent, Author>(\n * Author, {\n * ifNewOpts: { firstName: \"optional\"},\n * existingSearchOrder: [Author, Book, Publisher]\n * }),\n * ...opts,\n * });\n * }\n * ```\n */\nexport function maybeNewPoly<T extends Entity, NewT extends T = T>(\n ifNewCstr: EntityConstructor<NewT>,\n opts?: {\n ifNewOpts?: ActualFactoryOpts<NewT>;\n existingSearchOrder?: MaybeAbstractEntityConstructor<T>[];\n },\n): FactoryEntityOpt<NewT> {\n // Return a marker that resolveFactoryOpt will look for\n return new MaybeNew<T>((opts?.ifNewOpts || {}) as any, opts?.existingSearchOrder ?? [ifNewCstr]) as any;\n}\n\nclass MaybeNew<T extends Entity> {\n constructor(\n public opts: FactoryOpts<T>,\n public polyRefPreferredOrder: MaybeAbstractEntityConstructor<T>[] = [],\n ) {}\n}\n\n/**\n * Returns a unique-ish test index for putting in `name` fields.\n *\n * Note that `testIndex` is easier to just include in a string, because it doesn't require passing\n * the `EntityManger` and `type`. But if a factory really wants the test index as a number, they can\n * call this method.\n *\n * Despite the name, these are 1-based, i.e. the first `Author` is `a1`.\n */\nexport function getTestIndex<T extends Entity>(em: EntityManager, type: MaybeAbstractEntityConstructor<T>): number {\n const existing = em.getEntities(type);\n return existing.length + 1;\n}\n\n/** Returns the stable `a#1` factory id for em.create-d entities, using the createId assigned at creation time. */\nfunction getTestId<T extends Entity>(em: EntityManager, entity: T): string | undefined {\n const meta = getMetadata(entity);\n const createId = getInstanceData(entity).createId;\n return createId ? `${meta.tagName}#${createId}` : undefined;\n}\n\n// We keep a local copy of `global.Date`, in case a faking library\n// like @sinonjs/fake-timers is used and rewrites `global.Date` to\n// their own `ClockDate`, which would make our `===` check below fail.\nconst globalDate = global.Date;\n\nfunction defaultValueForField(em: EntityManager, cstr: EntityConstructor<any>, field: PrimitiveField): unknown {\n if (field.serde.columns[0].isArray) return [];\n if (field.type === \"string\") {\n if (field.fieldName === \"name\") {\n return `${cstr.name} ${getTestIndex(em, cstr)}`;\n }\n return field.fieldName;\n } else if (field.type === \"number\") {\n return 0;\n } else if (field.type === \"bigint\") {\n return 0n;\n } else if (field.type === globalDate) {\n return testDate;\n } else if (field.type === \"boolean\") {\n return false;\n } else if (field.type === \"Object\") {\n // A required jsonb column, i.e. so factories can satisfy a required (possibly `lazy`) column.\n return {};\n } else if (Temporal) {\n if (field.type === Temporal.PlainDate) {\n return testPlainDate;\n } else if (field.type === Temporal.PlainDateTime) {\n return testPlainDateTime;\n } else if (field.type === Temporal.ZonedDateTime) {\n return testZonedDateTime;\n }\n }\n\n return null;\n}\n\n// Utility type to destructure T out of T | undefined\ntype DefinedOr<T> = T | undefined | null;\n\ntype DeepPartialOpts<T extends Entity> = AllowRelationsOrPartials<OptsOf<T>>;\n\n/** What a factory can accept for a given entity. */\nexport type FactoryEntityOpt<T extends Entity> =\n | T\n // The ability to use an id, like `newAuthor(em, { publisher: \"p:1\" })` is not necessarily\n // on purpose, but the AuthorOpts already have `publisher: Publisher | PublisherId` in them,\n // so `newTestInstance` has to handle this typing anyway, unless we explicitly go out of our\n // way to remove the `PublisherId` from the Opts type.\n | IdOf<T>\n | (ActualFactoryOpts<T> & { useFactoryDefaults?: boolean | \"none\" });\n\ntype AllowRelationsOrPartials<T> = {\n [P in keyof T]?: T[P] extends DefinedOr<infer U>\n ? U extends Array<infer V>\n ? V extends Entity\n ? Array<FactoryEntityOpt<V>>\n : T[P]\n : U extends Entity\n ? FactoryEntityOpt<U>\n : T[P]\n : T[P];\n};\n\n// Map of constructor --> [\n// default entity,\n// | \"testOpts\" === explicitly passed into the top-level `newFactory` that creates the UseMap\n// | \"useOpt\" === explicitly passed in as a `use` flag\n// | \"diffBranch\" == created internally within the current factory call, but a different branch of children\n// | \"sameBranch\" === created internally within the current factory call, in the current branch of entities\n// ]\nexport type UseMapSource = \"testOpts\" | \"useOpt\" | \"sameBranch\" | \"diffBranch\";\ntype UseMapValue = [Entity, UseMapSource];\ntype UseMap = Map<Function, UseMapValue>;\n\n// Do a one-time conversion of the user's `use` array into a map for internal use, which we'll\n// then re-use across all `newTestInstance` calls within a given `new<Entity>` call.\nfunction getOrCreateUseMap(opts: FactoryOpts<any>): UseMap {\n const use: Entity | Entity[] | UseMap | undefined = opts.use;\n let map: UseMap;\n\n if (use instanceof Map) {\n // it's already a map\n map = use;\n } else {\n map = new Map();\n if (use instanceof Array) {\n // it's a top-level `newAuthor` with a user-passed `use: array`\n use.forEach((e) => addToUseMap(map, e, \"useOpt\"));\n } else if (use) {\n // it's a top-level `newAuthor` w/o a `use: entity` param\n addToUseMap(map, use, \"useOpt\");\n }\n // Scan opts for entities to add to the map, i.e. if the user calls `newAuthor(em, { book: b1 })`,\n // we'll use `b1` for any other books we might happen to create.\n const todo = [opts];\n while (todo.length > 0) {\n const opts = todo.pop();\n for (const opt of Object.values(opts || {})) {\n if (isEntity(opt) && !map.has(opt.constructor)) {\n addToUseMap(map, opt, \"testOpts\");\n } else if (opt instanceof Array) {\n // Push the array as-is, because it will be `Object.value`-d on the next iteration\n todo.push(opt);\n } else if (isPlainObject(opt)) {\n todo.push(opt);\n }\n }\n }\n }\n // Store our potentially-massaged map back into opts i.e. in case resolveFactoryOpt needs it.\n // Use as any b/c UseMap is our internal impl detail and not public.\n (opts as any).use = map;\n return map;\n}\n\n// If e is a subtype like SmallPublisher, register it for the base Publisher as well\nfunction addToUseMap(map: UseMap, e: Entity, source: UseMapSource) {\n logger?.logAddToUseMap(e, source);\n const meta = getMetadata(e);\n if (meta.baseType || meta.subTypes.length) {\n getBaseAndSelfMetas(meta).forEach((m) => {\n // console.log(`Putting ${e.toString()} into ${objectId(map)} as ${source}`);\n map.set(m.cstr, [e, source]);\n });\n } else {\n // console.log(`Putting ${e.toString()} into ${objectId(map)} as ${source}`);\n map.set(meta.cstr, [e, source]);\n }\n}\n\n/** Merge the factory's opts and the test's opts so that `{ age: 40 }` and `{ firstName: \"b1\" }` get merged. */\nfunction mergeOpts(meta: EntityMetadata, testOpts: Record<string, any>, factoryOpts: Record<string, any>): object {\n // Merge the factory's opts and the test's opts so that `{ age: 40 }` and `{ firstName: \"b1\" }` get merged\n if (testOpts.useFactoryDefaults === false || testOpts.useFactoryDefaults === \"none\") {\n return testOpts;\n }\n\n const opts: any = { ...testOpts };\n Object.entries(factoryOpts).forEach(([key, factoryValue]) => {\n // Skip special opts\n if (key === \"useExisting\") return;\n const testValue = testOpts[key];\n if (testOpts[key] === undefined) {\n // If the test doesn't define an opt, we have nothing to merge...unless\n // they literally passed `foo: undefined`, in which case they win.\n if (!(key in testOpts)) {\n opts[key] = factoryValue;\n }\n } else if (isPlainObject(factoryValue) && isPlainObject(testValue)) {\n // Should this deep merge? Probably?\n opts[key] = mergeOpts(meta, testValue, factoryValue);\n } else if (factoryValue instanceof MaybeNew && isPlainObject(testValue)) {\n opts[key] = mergeOpts(meta, testValue, factoryValue.opts);\n } else if (factoryValue instanceof MaybeNew && testValue instanceof MaybeNew) {\n opts[key] = new MaybeNew<any>(\n mergeOpts(meta, testValue.opts, factoryValue.opts),\n testValue.polyRefPreferredOrder ?? factoryValue.polyRefPreferredOrder,\n );\n }\n // This seemed like a good idea\n if (opts[key]?.[branchValueSym]) {\n const field = meta.allFields[key];\n if (field.kind === \"m2o\") {\n const use = testOpts.use as UseMap;\n const inTree = use?.get(field.otherMetadata().cstr);\n if (inTree && (inTree[1] === \"sameBranch\" || inTree[1] === \"testOpts\")) {\n // console.log(`Putting ${field.fieldName} to`, inTree[0]);\n opts[key] = inTree[0];\n }\n } else {\n throw new Error(`branchValue is not implemented for ${field.kind}`);\n }\n delete opts[key]?.[branchValueSym];\n }\n });\n return opts;\n}\n\n// As we branch out to children, going down the tree, give each branch its own playground of entities\nfunction withBranchMap(opts: object): object {\n const oldMap = (opts as any).use;\n const newMap = new CopyMap(oldMap);\n return { ...opts, use: newMap };\n}\n\n/** Writes new entities into our branch's map (this map), as well as the root we came from. */\nclass CopyMap extends Map<Function, UseMapValue> {\n constructor(private readonly root: UseMap) {\n super(root);\n }\n set(k: Function, v: UseMapValue): this {\n // Purposefully downgrade this to source=diffBranch so that it will not be used by `branchValue()`\n // calls that override `{}`, but can still be used to in-fan, i.e. if making multiple books by\n // default they get the same author.\n // ...also use `root?` because the `super(root)` will call `set` while copying the other map\n // but our `this.root` has not been set yet; which is fine, we want to ignore those anyway.\n this.root?.set(k, [v[0], \"diffBranch\"]);\n return super.set(k, v);\n }\n}\n\n// const objectId = (() => {\n// let currentId = 0;\n// const map = new WeakMap();\n// return (object: object): number => {\n// if (!map.has(object)) {\n// map.set(object, ++currentId);\n// }\n// return map.get(object)!;\n// };\n// })();\n/** Enables factory logging for all factories. */\nexport function setFactoryLogging(enabled: boolean): void {\n logger = enabled ? new FactoryLogger() : undefined;\n}\n\n/** Marker for tests setting derived values during test setup. */\nexport class FactoryInitialValue {\n constructor(public readonly value: any) {}\n}\n\nexport function isFactoryCreation(entity: Entity): boolean {\n return factoryCreated.has(entity);\n}\n\nexport function resetFactoryCreated(): void {\n factoryCreated = new WeakSet<Entity>();\n}\n"],"mappings":";;;;;;;;;;;;;AA+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A,OAAA;CAE7B;CACA,IAAI,GAAa,GAAsB;EAMrC,KAAK,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,YAAY,CAAC;EACtC,OAAO,MAAM,IAAI,GAAG,CAAC;CACvB;AACF;;AAaA,SAAgB,kBAAkB,SAAwB;CACxD,SAAS,UAAU,IAAIP,8BAAAA,cAAc,IAAI,KAAA;AAC3C;;AAGA,IAAa,sBAAb,MAAiC;CACH;CAA5B,YAAY,OAA4B;EAAZ,KAAA,QAAA;CAAa;AAC3C;AAEA,SAAgB,kBAAkB,QAAyB;CACzD,OAAO,eAAe,IAAI,MAAM;AAClC;AAEA,SAAgB,sBAA4B;CAC1C,iCAAiB,IAAI,QAAgB;AACvC"}
|
|
1
|
+
{"version":3,"file":"newTestInstance.cjs","names":["maybeRequireTemporal","FactoryLogger","getMetadata","hasDefaultValue","assertNever","isOneToOneField","isEntity","isId","isPlainObject","getBaseSelfAndSubMetas","isManyToOneField","getInstanceData"],"sources":["../src/newTestInstance.ts"],"sourcesContent":["import { isPlainObject } from \"joist-utils\";\nimport { getInstanceData } from \"src/BaseEntity.ts\";\nimport { hasDefaultValue, setAsyncDefaultsSynchronously } from \"src/defaults.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport {\n type EntityConstructor,\n type EntityManager,\n type IdOf,\n type MaybeAbstractEntityConstructor,\n isId,\n} from \"src/EntityManager.ts\";\nimport {\n type EntityMetadata,\n type ManyToManyField,\n type ManyToOneField,\n type OneToManyField,\n type OneToOneField,\n type PolymorphicField,\n type PrimitiveField,\n getBaseAndSelfMetas,\n getBaseSelfAndSubMetas,\n getMetadata,\n isManyToOneField,\n isOneToOneField,\n} from \"src/EntityMetadata.ts\";\nimport { type DeepNew, type FactoryExtrasOf, type New } from \"src/index.ts\";\nimport { FactoryLogger } from \"src/logging/FactoryLogger.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { type ActualFactoryOpts, type OptsOf } from \"src/typeMap.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\nlet logger: FactoryLogger | undefined = undefined;\n\n// Maybe we should scope this per-em, but assuming tests are single-threaded for now\nlet factoryCreated = new WeakSet();\n\n// The last EntityManager used in a factory call, for the `factories` proxy to resolve entities\nlet lastFactoryEm: EntityManager | undefined;\n\nconst factoryKeyRegex = /^([a-zA-Z]+)(\\d+)$/;\n\n/**\n * A proxy that allows accessing factory-created entities by their factory id.\n *\n * For example, after creating entities with `as` keys:\n *\n * ```ts\n * newAuthor(em, { books: [{ is: \"b#1\" }, { is: \"b#2\", prequel: \"b#1\" }] });\n * const { b1, b2 } = factories;\n * ```\n *\n * The proxy parses property names like `b1` into `b#1` and looks up the entity\n * in the most recently used EntityManager.\n */\nexport const factories: Record<string, any> = new Proxy(Object.create(null), {\n get(_target, prop) {\n if (typeof prop !== \"string\") return undefined;\n const match = prop.match(factoryKeyRegex);\n if (!match) throw new Error(`Invalid id '${prop}', expected 'b1' or 'a2'`);\n const [, tag, id] = match;\n if (!lastFactoryEm) throw new Error(\"No EntityManager available; call a factory like newAuthor(em) first\");\n const testId = `${tag}#${id}`;\n const entity = lastFactoryEm.entities.find((e) => getTestId(lastFactoryEm!, e) === testId);\n if (!entity) throw new Error(`No factory entity found for '${testId}'`);\n return entity;\n },\n});\n\n/**\n * DeepPartial-esque type specific to our `newTestInstance` factory.\n *\n * Specifically (vs using DeepPartial directly) this:\n *\n * 1. Adds a `use` tag of `Entity | Entity[]` that will be checked for existing\n * entities before creating new ones (i.e. \"if `newTestInstance` needs a `Book`,\n * use the one in `use` instead of making a new one).\n *\n * 2. Works specifically against the constructor/entity opts fields.\n */\nexport type FactoryOpts<T extends Entity> = DeepPartialOpts<T> & {\n is?: string;\n use?: Entity | Entity[];\n useFactoryDefaults?: boolean | \"none\";\n useExistingCheck?: boolean;\n useLogging?: boolean;\n} & {\n // We use a mapped type here with an explicit `?`, instead of just `FactoryExtrasOf<T>`,\n // so that tsc knows that `{}` is a valid default opts value.\n [K in keyof FactoryExtrasOf<T>]?: FactoryExtrasOf<T>[K];\n};\n\n// Chosen b/c it's a monday https://www.timeanddate.com/calendar/monthly.html?year=2018&month=1&country=1\nconst jan1 = new Date(2018, 0, 1);\nexport const testDate = jan1;\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport const testPlainDate = Temporal?.PlainDate.from(\"2018-01-01\");\nexport const testPlainDateTime = testPlainDate?.toPlainDateTime(\"00:00:00\");\nexport const testZonedDateTime = testPlainDate?.toZonedDateTime(\"UTC\");\n\nconst knownUseKeys = [\"is\", \"use\", \"useLogging\", \"useExistingCheck\", \"useFactoryDefaults\"];\n\n/**\n * Creates a test instance of `T`.\n *\n * If the factory code passes factoryOpts.useExisting, they can \"intercept\" the `em.create`\n * to try and resolve \"already created\" / singleton instances. The `useExisting` callback is\n * useful b/c the `opts` will be the \"resolved-to-entity\" opts, and not the raw \"maybe object\n * literal, maybe object instance\" opts that tests pass into the factory.\n */\nexport function newTestInstance<T extends Entity>(\n em: EntityManager,\n cstr: EntityConstructor<T>,\n /** The test's test-specific override opts. */\n testOpts: FactoryOpts<T> = {},\n /** The factory file's default opts. */\n factoryOpts: FactoryOpts<T> & {\n useExisting?: (opts: OptsOf<T>, existing: DeepNew<T>) => boolean;\n } = {},\n): DeepNew<T> {\n // Remember the em so the `factories` proxy can look up entities\n lastFactoryEm = em;\n\n // The first factory that is asked to debug, without one in place, will create+unset the logger.\n let ownsTheLogger = !logger && testOpts.useLogging;\n if (ownsTheLogger) logger = new FactoryLogger();\n\n logger?.logCreating(cstr);\n logger?.indent();\n\n const meta = getMetadata(cstr);\n const opts = mergeOpts(meta, testOpts, factoryOpts);\n const use = getOrCreateUseMap(opts);\n\n const selfFields: string[] = [];\n\n // Create just the primitive and m2o fields 1st, so we can create a minimal/valid\n // instance of the entity. We'll do the o2m/other fields as a second pass.\n const initialOpts = Object.values(meta.allFields)\n .map((field) => {\n const { fieldName } = field;\n\n // Don't fill in required fields if told not to\n const ignoreAllDefaults = \"useFactoryDefaults\" in opts && opts.useFactoryDefaults === \"none\";\n // If the field has a default value, don't force fill it, even if passed `author: undefined`\n const required = field.required && !ignoreAllDefaults && !hasDefaultValue(meta, fieldName);\n\n // Use the opts value if they passed one in\n if (fieldName in opts && (opts as any)[fieldName] !== defaultValueMarker) {\n const optValue = (opts as any)[fieldName];\n // We don't explicitly support null (callers should pass undefined), but we accept it\n // because the factory might have done `const { author, ... } = opts` and is accidentally\n // passing an `author: undefined` without meaning too.\n const shouldRespectUndefined = !required;\n if (optValue === null || (optValue === undefined && shouldRespectUndefined)) {\n return [];\n }\n switch (field.kind) {\n case \"m2o\":\n case \"poly\":\n return [fieldName, resolveFactoryOpt(em, opts, field, optValue, undefined, undefined)];\n case \"o2o\":\n case \"o2m\":\n case \"m2m\":\n // We do these in the 2nd pass after `entity` exists (see additionalOpts)\n return [];\n case \"m2mEnum\":\n // Enum codes have no entity identity, so pass them straight through.\n return [fieldName, optValue];\n case \"lo2m\":\n // If a child is passing themselves into a parent that is a large collection, just ignore it\n return [];\n case \"primitive\":\n case \"enum\":\n case \"primaryKey\":\n // Look for strings that want to use the test index\n if (typeof optValue === \"string\" && optValue.includes(testIndexString)) {\n const actualIndex = getTestIndex(em, meta.cstr);\n const value = optValue.replace(testIndexString, String(actualIndex));\n return [fieldName, value];\n } else if (typeof optValue === \"number\" && optValue === testIndex) {\n const actualIndex = getTestIndex(em, meta.cstr);\n return [fieldName, actualIndex];\n }\n // Otherwise just use the user's opt value as-is\n return [fieldName, optValue];\n default:\n return assertNever(field);\n }\n }\n\n if (\n field.kind === \"primitive\" &&\n (required || (opts as any)[fieldName] === defaultValueMarker) &&\n !field.derived &&\n !field.protected\n ) {\n return [fieldName, defaultValueForField(em, cstr, field)];\n } else if (field.kind === \"m2o\" && !field.derived) {\n // If neither the user nor the factory (i.e. for an explicit \"fan out\" case) set this field,\n // then look in `use` and for an \"obvious\" there-is-only-one default (even for optional fields)\n const [existing, loggerKey] = getObviousDefault(em, field.otherMetadata(), use);\n // If this is a m2o pointing to an o2o, i.e. that as a unique constraint, make sure the\n // existing entity we found isn't already claimed\n const isUniqueAndAlreadyUsed =\n existing &&\n isOneToOneField(field.otherMetadata().allFields[field.otherFieldName]) &&\n (existing as any)[field.otherFieldName].isLoaded &&\n (existing as any)[field.otherFieldName].isSet;\n if (existing && !isUniqueAndAlreadyUsed && !ignoreAllDefaults) {\n logger?.[loggerKey](fieldName, existing);\n return [fieldName, existing];\n }\n // Otherwise, only make a new entity only if the field is required\n if (required) {\n // ...unless this is a self-referential key, in which case avoid infinite looping.\n if (field.otherMetadata() === meta) {\n selfFields.push(fieldName);\n return [];\n } else {\n return [fieldName, resolveFactoryOpt(em, opts, field, undefined, undefined, undefined)];\n }\n }\n } else if (field.kind === \"enum\" && required && !field.derived) {\n return [fieldName, field.enumDetailType.getValues()[0]];\n } else if (field.kind === \"poly\" && required) {\n return [fieldName, resolveFactoryOpt(em, opts, field, undefined, undefined, undefined)];\n }\n\n return [];\n })\n .filter((t) => t.length > 0);\n\n const createOpts = Object.fromEntries(initialOpts);\n\n if (factoryOpts.useExisting && testOpts.useExistingCheck !== false) {\n const existing = em.entities\n .filter((e) => e instanceof meta.cstr)\n .find((e) => factoryOpts.useExisting!(createOpts as OptsOf<T>, e as DeepNew<T>));\n if (existing) {\n logger?.logFoundExisting(existing);\n logger?.dedent();\n if (ownsTheLogger) logger = undefined;\n return existing as DeepNew<T>;\n }\n }\n\n const entity = em.create(cstr, createOpts) as New<T>;\n\n // Verify the `as` assertion if provided\n if ((opts as any).is) {\n const expected = (opts as any).is;\n const actual = getTestId(em, entity);\n if (actual !== expected) {\n throw new Error(`Test used 'is: ${expected}' but the entity is actually ${actual}`);\n }\n }\n\n // Report this as factory-created until the next em.flush\n factoryCreated.add(entity);\n\n // If the type we just made doesn't exist in `use` yet, remember it. This works better than\n // looking at the values in `fullOpts`, because instead of waiting until the end of the\n // `build fullOpts` loop, we're also invoking `newTestInstance` as we go through the loop itself,\n // creating each test instance within nested/recursive `newTestInstance` calls.\n if (!use.has(entity.constructor) || use.get(entity.constructor)![1] === \"diffBranch\") {\n addToUseMap(use, entity, \"sameBranch\");\n } else {\n // The `addToUseMap` does its own 'created & added to scope'\n logger?.logCreated(entity);\n }\n\n // Now that we've got the entity, do a 2nd pass for o2m/m2m where we pass\n // `{ parent: entity }` down to children (i.e. to replace our original\n // null marker approach).\n const additionalOpts = Object.entries(opts).map(([fieldName, optValue]) => {\n const field = meta.allFields[fieldName];\n // Look for `use` / etc\n if (knownUseKeys.includes(fieldName)) return [];\n if (!field) {\n // Look for extra/derived fields\n if (fieldName.startsWith(\"with\")) {\n const realName = fieldName[4].toLowerCase() + fieldName.substring(5);\n const realField = meta.allFields[realName];\n if (realField && \"derived\" in realField && realField.derived === \"async\") {\n return [realName, new FactoryInitialValue(optValue)];\n }\n // Fields with `config.transitions`/`onTransition`s accept a trusted created value, like ReactiveFields\n if (realField?.kind === \"enum\" && meta.transitions!.has(realName)) {\n return [realName, new FactoryInitialValue(optValue)];\n }\n }\n throw new Error(`Unknown field ${fieldName}`);\n }\n if (optValue === null || optValue === undefined) return [];\n if (field.kind === \"o2m\") {\n // If this is a list of children, i.e. book.authors, handle partials to newTestInstance'd\n return [\n fieldName,\n (optValue as Array<any>).map((opt, i) => {\n // console.log(`${field.fieldName}`, i);\n return resolveFactoryOpt(em, withBranchMap(opts), field, opt, entity, i);\n }),\n ];\n } else if (field.kind == \"m2m\") {\n return [\n fieldName,\n (optValue as Array<any>).map((opt, i) =>\n resolveFactoryOpt(em, withBranchMap(opts), field, opt, [entity] as any, i),\n ),\n ];\n } else if (field.kind === \"o2o\") {\n const otherField = field.otherMetadata().allFields[field.otherFieldName];\n const isReactiveReference = \"derived\" in otherField && otherField.derived === \"async\";\n if (isReactiveReference) return [];\n // If this is an o2o, i.e. author.image, just pass the optValue (i.e. it won't be a list)\n return [fieldName, resolveFactoryOpt(em, opts, field, optValue as any, entity, undefined)];\n } else {\n return []; // Assume createOpts handled this\n }\n });\n\n for (const fieldName of selfFields) {\n additionalOpts.push([fieldName, entity]);\n }\n\n entity.set(Object.fromEntries(additionalOpts.filter((t) => t.length > 0)));\n\n // em.create applied synchronous defaults automatically; since we're a factory with likely\n // deeply-loaded instances, go ahead and synchronously invoke the async defaults, at least\n // the ones that just use load hints + a synchronous lambda.\n // (...would be nice to log these in the setFactoryLogging output)\n setAsyncDefaultsSynchronously(em.ctx, entity);\n\n // Set it back to undefined\n logger?.dedent();\n if (ownsTheLogger) logger = undefined;\n\n return entity as DeepNew<T>;\n}\n\n/**\n * Resolves a `FactoryEntityOpt` (i.e. maybe an existing entity, maybe an id, maybe a hash of opts) to an entity.\n *\n * If `opt` is `undefined`, then the usual factory semantics of \"check use\", \"look for only one instance\" are\n * checked before finally creating a brand new entity.\n *\n * We also accept an optional `otherFieldName` so that, if we do create a new entity, we pass along the null\n * marker for them to know not to create their own version of us.\n *\n * (This was originally intended to be a public API, but the use case ended up being handled\n * by the more-ergonomic `maybeNew` feature; we could explore making this public if another\n * similar use case comes up in the future.)\n */\nfunction resolveFactoryOpt<T extends Entity>(\n em: EntityManager,\n opts: FactoryOpts<any>,\n field: OneToManyField | ManyToOneField | OneToOneField | ManyToManyField | PolymorphicField,\n opt: FactoryEntityOpt<any> | undefined,\n maybeEntity: T | undefined,\n fieldIndex: number | undefined,\n): T | IdOf<T> {\n const use = getOrCreateUseMap(opts);\n const { meta, otherFieldName } = metaFromFieldAndOpt(field, opt);\n // const meta = field.kind === \"poly\" ? field.components[0].otherMetadata() : field.otherMetadata();\n // const otherFieldName = field.kind === \"poly\" ? field.components[0].otherFieldName : field.otherFieldName;\n const fieldWithIndex = `${field.fieldName}${fieldIndex !== undefined ? `[${fieldIndex}]` : \"\"}`;\n if (isEntity(opt)) {\n logger?.logFoundOpt(fieldWithIndex, opt);\n return opt as T;\n } else if (isId(opt)) {\n // Try finding the entity in the UoW, otherwise fallback on just setting it as the id (which we support that now)\n const found = (em.entities.find((e) => e.idTaggedMaybe === opt || getTestId(em, e) === opt) as T) || opt;\n logger?.logFoundOpt(fieldWithIndex, found);\n return found;\n } else if (opt && !isPlainObject(opt) && !(opt instanceof MaybeNew)) {\n // If opt isn't a POJO, assume this is a completely-custom factory\n logger?.logNotFoundAndCreating(fieldWithIndex, meta);\n return meta.factory(em, opt);\n } else {\n // Look for an obvious default\n if (opt === undefined || opt instanceof MaybeNew) {\n if (\n field.kind === \"poly\" ||\n (field.otherMetadata().subTypes.length > 0 && opt instanceof MaybeNew && opt.polyRefPreferredOrder.length > 0)\n ) {\n // We have a polymorphic maybeNew to sort through\n const [existing, loggerKey] = (opt instanceof MaybeNew\n ? opt.polyRefPreferredOrder.map((cstr) => getMetadata(cstr))\n : field.kind === \"poly\"\n ? field.components.map((c) => c.otherMetadata())\n : [meta]\n )\n .map((meta) => getObviousDefault(em, meta, use))\n .find((existing) => !!existing[0]) || [undefined, undefined];\n if (existing) {\n logger?.[loggerKey](fieldWithIndex, existing);\n return existing as T;\n }\n } else {\n // Otherwise fall though to making a new entity via the factory\n const [existing, loggerKey] = getObviousDefault(em, meta, use);\n if (existing) {\n logger?.[loggerKey](fieldWithIndex, existing);\n return existing as T;\n }\n }\n }\n // If this is image.author (m2o) but the other-side is an o2o, pass null instead of []\n maybeEntity ??= (meta.allFields[otherFieldName].kind === \"o2o\" ? null : []) as any;\n logger?.logNotFoundAndCreating(fieldWithIndex, meta);\n return meta.factory(em, {\n // Because of the `!isPlainObject` above, opt will either be undefined or an object here\n ...applyUse((opt as any) || {}, use, meta),\n ...(opt instanceof MaybeNew && opt.opts),\n [otherFieldName]: maybeEntity,\n });\n }\n}\n\n/** Determines the metadata and otherFieldName to use in resolveFactoryOpt to account for polymorphic fields */\nfunction metaFromFieldAndOpt<T extends Entity>(\n field: OneToManyField | ManyToOneField | OneToOneField | ManyToManyField | PolymorphicField,\n opt: FactoryEntityOpt<T> | undefined,\n): { meta: EntityMetadata; otherFieldName: string } {\n if (field.kind === \"poly\") {\n let componentToUse =\n // Otherwise, we check if the `opt` specifies a particular component to use, and if not fall back to the first one\n field.components.find(\n (component) =>\n opt instanceof MaybeNew &&\n getBaseSelfAndSubMetas(component.otherMetadata())\n .map((m) => m.cstr)\n .includes(opt.polyRefPreferredOrder[0]),\n ) ?? field.components[0];\n return { meta: componentToUse.otherMetadata(), otherFieldName: componentToUse.otherFieldName };\n } else if (\n field.otherMetadata().subTypes.length > 0 &&\n opt instanceof MaybeNew &&\n opt.polyRefPreferredOrder.length > 0\n ) {\n const otherMeta = field.otherMetadata();\n const types = getBaseSelfAndSubMetas(otherMeta);\n const typeToUse = types.find((subType) => subType.cstr === opt.polyRefPreferredOrder[0]) ?? otherMeta;\n return { meta: typeToUse, otherFieldName: field.otherFieldName };\n } else {\n // If it isn't a poly field, then the field itself can tell us everything we need to know\n return { meta: field.otherMetadata(), otherFieldName: field.otherFieldName };\n }\n}\n\n/** We look for `use`-cached entities, which are either those we created, or had \"if-only-one\" defaults. */\nfunction getObviousDefault<T extends Entity>(\n em: EntityManager,\n metadata: EntityMetadata,\n use: UseMap,\n): [T, \"logFoundInUseMap\" | \"logFoundSingleEntity\"] | [undefined, undefined] {\n if (use.has(metadata.cstr)) {\n return [use.get(metadata.cstr)![0] as T, \"logFoundInUseMap\"];\n }\n // If there is a single existing instance of this type, assume the caller is fine with that.\n // ...in theory seeding our `use` map with the only-one entities was supposed to prevent the\n // need for doing this (the entities would already be in the use map that we just checked),\n // but that approach doesn't catch created-as-side-effect entities.\n const existing = em.getEntities(metadata.cstr);\n if (existing.length === 1) {\n return [existing[0] as T, \"logFoundSingleEntity\"];\n }\n return [undefined, undefined];\n}\n\n// When a factory is called, i.e. `newAuthor`, opts will:\n//\n// - Have values explicitly passed by the user/other factories\n// - Have values from the user's explicit `use` parameter\n// - NOT have guessed (i.e. \"only existing entity\") or an implicitly-created `use` parameter\n//\n// This allows the factory to \"fan out\" by default, i.e. newInternalUser creating its own User\n// and Market creating its own ProductAttribute, which originally we couldn't do when\n// guessed/implicit opts were passed directly to `newAuthor`.\n//\n// Now, if the `newAuthor` factory doesn't explicitly \"fan out\" (by passing `user: {}` to\n// `newTestInstance`), we still \"fan in\" by having `newTestInstance` sneak in the guessed/implicit\n// opts of only-one-existing or factory-created instances.\n\n/** Given we're going to call a factory, make sure any `use`s are put into `opts`. */\nfunction applyUse(optsMaybeNew: object, use: UseMap, metadata: EntityMetadata): object {\n const opts = optsMaybeNew instanceof MaybeNew ? optsMaybeNew.opts : optsMaybeNew;\n // Find any unset fields\n Object.values(metadata.fields)\n .filter((f) => !(f.fieldName in opts))\n .forEach((f) => {\n // And set them to the current `use` entity for their type, if it exists\n if (((isManyToOneField(f) && !f.derived) || isOneToOneField(f)) && use.has(f.otherMetadata().cstr)) {\n const def = use.get(f.otherMetadata().cstr)!;\n // Only pass explicit/user-defined `use` entities, so that factories can \"fan out\" if they want,\n // and not see other factory-created entities look like user-specific values.\n if (def[1] === \"useOpt\") {\n (opts as any)[f.fieldName] = def[0];\n }\n }\n });\n // Make a copy so that we don't leak `use` onto opts that tests might later use in assertions.\n return { ...opts, use };\n}\n\n/**\n * A marker value for later replacement with the test instance's \"unique-ish\" index.\n *\n * This is meant to just be a helpful identifier in fields like entity names/descriptions for\n * debugging purposes.\n */\nexport const testIndex: number = -1_111_111_222;\n\nconst testIndexString = String(testIndex);\n\nconst defaultValueMarker: any = {};\nconst branchValueSym = Symbol(\"branchValue\");\n\n/**\n * A marker value for the default `newTestInstance` behavior.\n *\n * Useful for passing arguments to `newTestInstance` where you sometimes want to\n * provide a specific value, and other times ask for the \"pick a default\" behavior\n * (i.e. you don't want to pass `undefined` b/c that means explicitly \"leave this\n * key unset\").\n *\n * Note that this is a function so that we can infer the return type as basically\n * `any` without really using `any` (which would disable type-checking in the rest\n * of the expression).\n */\nexport function defaultValue<T>(): T {\n return defaultValueMarker;\n}\n\n/**\n * A marker value to never set a field, even if it's required.\n *\n * The factories treat `{ author: undefined }` as \"still set the author\", because of how easy\n * it is for destructuring/restructuring opts to implicitly set `undefined` values.\n *\n * If you want to force a field to not be set, you can use `{ author: noValue() }`.\n */\nexport function noValue<T>(): T {\n return null as T;\n}\n\n/**\n * A marker value to accept values only if explicitly created-or-passed within the current,\n * unique \"branch\" of a factory call.\n *\n * This is useful for \"diamond-shape\" entity models like:\n *\n * ```\n * ParentGroup <-- ParentItem\n * | |\n * ChildGroup <-- ChildItem\n * ```\n *\n * Where it's important that the `ChildItem -> ParentItem -> ParentGroup` path matches\n * the `ChildItem -> ChildGroup -> ParentGroup` path.\n *\n * This can be hard to achieve in normal factory behavior, i.e. for a call like:\n *\n * ```ts\n * const c = newChild(em, {\n * groups: [\n * { childItems: [{}, {}] },\n * { childItems: [{}, {}] },\n * ],\n * });\n * ```\n *\n * The first `ChildGroup` will create a new `ParentGroup` that is used by everything, which\n * is not our intent, as both `ChildGroup`s, and all four `ParentItem`s, will live in a single\n * `ParentGroup`.\n *\n * An initial idea is to pass `parentGroup: {}` in the factories, because that turns off \"reusing\n * existing instances\", but for this problem the `{}` approach is \"too good\" at creating new\n * instances, b/c the above diamond pattern will be disconnected.\n *\n * So `branchValue` provides a middle ground, where _usually_ it will be a new entity, unless\n * it was explicitly created within the same \"branch\" of a factory call.\n */\nexport function maybeBranchValue<T>(opts?: ActualFactoryOpts<T>): T {\n // opts get mutated, so we have to return a new value\n return { [branchValueSym]: true, ...(opts ? opts : undefined) } as any;\n}\n\n/**\n * Allows a factory to declare that an optional relation should be filled in with an\n * \"obvious default\", or a new entity if one doesn't exist.\n *\n * This \"obvious default or new entity\" is what Joist already does for _required_ relations,\n * and so `maybeNew` lets the factory tell Joist to apply the same behavior to an optional\n * field.\n *\n * I.e.:\n *\n * ```typescript\n * export function newAuthor(em: Entity, opts: FactoryOpts<Author>) {\n * return newTestInstance(em, Author, {\n * // this always make a new publisher, unless explicitly overridden by the test,\n * // i.e. when each author really needs \"their own\" publisher.\n * publisher: {},\n * // this will make a new publisher but first looks for \"good defaults\" in the\n * // test, i.e. an already-created publisher. This is the default behavior of\n * // required fields (\"look for a good default\"), and `maybeNew` lets you tell\n * // Joist to invoke that same \"maybe new\" behavior for an optional field.\n * publisher: maybeNew<Publisher>({}),\n * ...opts,\n * });\n * }\n * ```\n */\nexport function maybeNew<T extends Entity>(opts?: ActualFactoryOpts<T>): FactoryEntityOpt<T> {\n // Return a marker that resolveFactoryOpt will look for\n return new MaybeNew<T>((opts || {}) as any) as any;\n}\n\n/**\n * Similar to `maybeNew` in behaviour/use but with enhancements to support polymorphic fields:\n * 1) Allows you to specify which entity type to create, if it is found a new one is needed\n * 2) Allows you to prioritize which existing entities to select\n *\n * For example below, we are specifying that an Author should be created if needed (and optionally it's default opts\n * in the `ifNewOpts` field), and also that the priority order for choosing existing entities is Author, Book, and then Publisher.\n * Note since BookReview is excluded from `existingSearchOrder`, an existing BookReview will never be chosen.\n *\n * ```typescript\n * export function newComment(em: EntityManager, opts: FactoryOpts<Comment> = {}): New<Comment> {\n * return newTestInstance(em, Comment, {\n * parent: maybeNewPoly<CommentParent, Author>(\n * Author, {\n * ifNewOpts: { firstName: \"optional\"},\n * existingSearchOrder: [Author, Book, Publisher]\n * }),\n * ...opts,\n * });\n * }\n * ```\n */\nexport function maybeNewPoly<T extends Entity, NewT extends T = T>(\n ifNewCstr: EntityConstructor<NewT>,\n opts?: {\n ifNewOpts?: ActualFactoryOpts<NewT>;\n existingSearchOrder?: MaybeAbstractEntityConstructor<T>[];\n },\n): FactoryEntityOpt<NewT> {\n // Return a marker that resolveFactoryOpt will look for\n return new MaybeNew<T>((opts?.ifNewOpts || {}) as any, opts?.existingSearchOrder ?? [ifNewCstr]) as any;\n}\n\nclass MaybeNew<T extends Entity> {\n constructor(\n public opts: FactoryOpts<T>,\n public polyRefPreferredOrder: MaybeAbstractEntityConstructor<T>[] = [],\n ) {}\n}\n\n/**\n * Returns a unique-ish test index for putting in `name` fields.\n *\n * Note that `testIndex` is easier to just include in a string, because it doesn't require passing\n * the `EntityManger` and `type`. But if a factory really wants the test index as a number, they can\n * call this method.\n *\n * Despite the name, these are 1-based, i.e. the first `Author` is `a1`.\n */\nexport function getTestIndex<T extends Entity>(em: EntityManager, type: MaybeAbstractEntityConstructor<T>): number {\n const existing = em.getEntities(type);\n return existing.length + 1;\n}\n\n/** Returns the stable `a#1` factory id for em.create-d entities, using the createId assigned at creation time. */\nfunction getTestId<T extends Entity>(em: EntityManager, entity: T): string | undefined {\n const meta = getMetadata(entity);\n const createId = getInstanceData(entity).createId;\n return createId ? `${meta.tagName}#${createId}` : undefined;\n}\n\n// We keep a local copy of `global.Date`, in case a faking library\n// like @sinonjs/fake-timers is used and rewrites `global.Date` to\n// their own `ClockDate`, which would make our `===` check below fail.\nconst globalDate = global.Date;\n\nfunction defaultValueForField(em: EntityManager, cstr: EntityConstructor<any>, field: PrimitiveField): unknown {\n if (field.serde.columns[0].isArray) return [];\n if (field.type === \"string\") {\n if (field.fieldName === \"name\") {\n return `${cstr.name} ${getTestIndex(em, cstr)}`;\n }\n return field.fieldName;\n } else if (field.type === \"number\") {\n return 0;\n } else if (field.type === \"bigint\") {\n return 0n;\n } else if (field.type === globalDate) {\n return testDate;\n } else if (field.type === \"boolean\") {\n return false;\n } else if (field.type === \"Object\") {\n // A required jsonb column, i.e. so factories can satisfy a required (possibly `lazy`) column.\n return {};\n } else if (Temporal) {\n if (field.type === Temporal.PlainDate) {\n return testPlainDate;\n } else if (field.type === Temporal.PlainDateTime) {\n return testPlainDateTime;\n } else if (field.type === Temporal.ZonedDateTime) {\n return testZonedDateTime;\n }\n }\n\n return null;\n}\n\n// Utility type to destructure T out of T | undefined\ntype DefinedOr<T> = T | undefined | null;\n\ntype DeepPartialOpts<T extends Entity> = AllowRelationsOrPartials<OptsOf<T>>;\n\n/** What a factory can accept for a given entity. */\nexport type FactoryEntityOpt<T extends Entity> =\n | T\n // The ability to use an id, like `newAuthor(em, { publisher: \"p:1\" })` is not necessarily\n // on purpose, but the AuthorOpts already have `publisher: Publisher | PublisherId` in them,\n // so `newTestInstance` has to handle this typing anyway, unless we explicitly go out of our\n // way to remove the `PublisherId` from the Opts type.\n | IdOf<T>\n | (ActualFactoryOpts<T> & { useFactoryDefaults?: boolean | \"none\" });\n\ntype AllowRelationsOrPartials<T> = {\n [P in keyof T]?: T[P] extends DefinedOr<infer U>\n ? U extends Array<infer V>\n ? V extends Entity\n ? Array<FactoryEntityOpt<V>>\n : T[P]\n : U extends Entity\n ? FactoryEntityOpt<U>\n : T[P]\n : T[P];\n};\n\n// Map of constructor --> [\n// default entity,\n// | \"testOpts\" === explicitly passed into the top-level `newFactory` that creates the UseMap\n// | \"useOpt\" === explicitly passed in as a `use` flag\n// | \"diffBranch\" == created internally within the current factory call, but a different branch of children\n// | \"sameBranch\" === created internally within the current factory call, in the current branch of entities\n// ]\nexport type UseMapSource = \"testOpts\" | \"useOpt\" | \"sameBranch\" | \"diffBranch\";\ntype UseMapValue = [Entity, UseMapSource];\ntype UseMap = Map<Function, UseMapValue>;\n\n// Do a one-time conversion of the user's `use` array into a map for internal use, which we'll\n// then re-use across all `newTestInstance` calls within a given `new<Entity>` call.\nfunction getOrCreateUseMap(opts: FactoryOpts<any>): UseMap {\n const use: Entity | Entity[] | UseMap | undefined = opts.use;\n let map: UseMap;\n\n if (use instanceof Map) {\n // it's already a map\n map = use;\n } else {\n map = new Map();\n if (use instanceof Array) {\n // it's a top-level `newAuthor` with a user-passed `use: array`\n use.forEach((e) => addToUseMap(map, e, \"useOpt\"));\n } else if (use) {\n // it's a top-level `newAuthor` w/o a `use: entity` param\n addToUseMap(map, use, \"useOpt\");\n }\n // Scan opts for entities to add to the map, i.e. if the user calls `newAuthor(em, { book: b1 })`,\n // we'll use `b1` for any other books we might happen to create.\n const todo = [opts];\n while (todo.length > 0) {\n const opts = todo.pop();\n for (const opt of Object.values(opts || {})) {\n if (isEntity(opt) && !map.has(opt.constructor)) {\n addToUseMap(map, opt, \"testOpts\");\n } else if (opt instanceof Array) {\n // Push the array as-is, because it will be `Object.value`-d on the next iteration\n todo.push(opt);\n } else if (isPlainObject(opt)) {\n todo.push(opt);\n }\n }\n }\n }\n // Store our potentially-massaged map back into opts i.e. in case resolveFactoryOpt needs it.\n // Use as any b/c UseMap is our internal impl detail and not public.\n (opts as any).use = map;\n return map;\n}\n\n// If e is a subtype like SmallPublisher, register it for the base Publisher as well\nfunction addToUseMap(map: UseMap, e: Entity, source: UseMapSource) {\n logger?.logAddToUseMap(e, source);\n const meta = getMetadata(e);\n if (meta.baseType || meta.subTypes.length) {\n getBaseAndSelfMetas(meta).forEach((m) => {\n // console.log(`Putting ${e.toString()} into ${objectId(map)} as ${source}`);\n map.set(m.cstr, [e, source]);\n });\n } else {\n // console.log(`Putting ${e.toString()} into ${objectId(map)} as ${source}`);\n map.set(meta.cstr, [e, source]);\n }\n}\n\n/** Merge the factory's opts and the test's opts so that `{ age: 40 }` and `{ firstName: \"b1\" }` get merged. */\nfunction mergeOpts(meta: EntityMetadata, testOpts: Record<string, any>, factoryOpts: Record<string, any>): object {\n // Merge the factory's opts and the test's opts so that `{ age: 40 }` and `{ firstName: \"b1\" }` get merged\n if (testOpts.useFactoryDefaults === false || testOpts.useFactoryDefaults === \"none\") {\n return testOpts;\n }\n\n const opts: any = { ...testOpts };\n Object.entries(factoryOpts).forEach(([key, factoryValue]) => {\n // Skip special opts\n if (key === \"useExisting\") return;\n const testValue = testOpts[key];\n if (testOpts[key] === undefined) {\n // If the test doesn't define an opt, we have nothing to merge...unless\n // they literally passed `foo: undefined`, in which case they win.\n if (!(key in testOpts)) {\n opts[key] = factoryValue;\n }\n } else if (isPlainObject(factoryValue) && isPlainObject(testValue)) {\n // Should this deep merge? Probably?\n opts[key] = mergeOpts(meta, testValue, factoryValue);\n } else if (factoryValue instanceof MaybeNew && isPlainObject(testValue)) {\n opts[key] = mergeOpts(meta, testValue, factoryValue.opts);\n } else if (factoryValue instanceof MaybeNew && testValue instanceof MaybeNew) {\n opts[key] = new MaybeNew<any>(\n mergeOpts(meta, testValue.opts, factoryValue.opts),\n testValue.polyRefPreferredOrder ?? factoryValue.polyRefPreferredOrder,\n );\n }\n // This seemed like a good idea\n if (opts[key]?.[branchValueSym]) {\n const field = meta.allFields[key];\n if (field.kind === \"m2o\") {\n const use = testOpts.use as UseMap;\n const inTree = use?.get(field.otherMetadata().cstr);\n if (inTree && (inTree[1] === \"sameBranch\" || inTree[1] === \"testOpts\")) {\n // console.log(`Putting ${field.fieldName} to`, inTree[0]);\n opts[key] = inTree[0];\n }\n } else {\n throw new Error(`branchValue is not implemented for ${field.kind}`);\n }\n delete opts[key]?.[branchValueSym];\n }\n });\n return opts;\n}\n\n// As we branch out to children, going down the tree, give each branch its own playground of entities\nfunction withBranchMap(opts: object): object {\n const oldMap = (opts as any).use;\n const newMap = new CopyMap(oldMap);\n return { ...opts, use: newMap };\n}\n\n/** Writes new entities into our branch's map (this map), as well as the root we came from. */\nclass CopyMap extends Map<Function, UseMapValue> {\n constructor(private readonly root: UseMap) {\n super(root);\n }\n set(k: Function, v: UseMapValue): this {\n // Purposefully downgrade this to source=diffBranch so that it will not be used by `branchValue()`\n // calls that override `{}`, but can still be used to in-fan, i.e. if making multiple books by\n // default they get the same author.\n // ...also use `root?` because the `super(root)` will call `set` while copying the other map\n // but our `this.root` has not been set yet; which is fine, we want to ignore those anyway.\n this.root?.set(k, [v[0], \"diffBranch\"]);\n return super.set(k, v);\n }\n}\n\n// const objectId = (() => {\n// let currentId = 0;\n// const map = new WeakMap();\n// return (object: object): number => {\n// if (!map.has(object)) {\n// map.set(object, ++currentId);\n// }\n// return map.get(object)!;\n// };\n// })();\n/** Enables factory logging for all factories. */\nexport function setFactoryLogging(enabled: boolean): void {\n logger = enabled ? new FactoryLogger() : undefined;\n}\n\n/** Marker for tests setting derived values during test setup. */\nexport class FactoryInitialValue {\n constructor(public readonly value: any) {}\n}\n\nexport function isFactoryCreation(entity: Entity): boolean {\n return factoryCreated.has(entity);\n}\n\nexport function resetFactoryCreated(): void {\n factoryCreated = new WeakSet<Entity>();\n}\n"],"mappings":";;;;;;;;;;;;;AA+BA,IAAI,SAA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O;AAChC;;AAGA,IAAM,UAAN,cAAsB,IAA2B;CAClB;CAA7B,YAAY,MAA+B;EACzC,MAAM,IAAI;EADiB,KAAA,OAAA;CAE7B;CACA,IAAI,GAAa,GAAsB;EAMrC,KAAK,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,YAAY,CAAC;EACtC,OAAO,MAAM,IAAI,GAAG,CAAC;CACvB;AACF;;AAaA,SAAgB,kBAAkB,SAAwB;CACxD,SAAS,UAAU,IAAIP,8BAAAA,cAAc,IAAI,KAAA;AAC3C;;AAGA,IAAa,sBAAb,MAAiC;CACH;CAA5B,YAAY,OAA4B;EAAZ,KAAA,QAAA;CAAa;AAC3C;AAEA,SAAgB,kBAAkB,QAAyB;CACzD,OAAO,eAAe,IAAI,MAAM;AAClC;AAEA,SAAgB,sBAA4B;CAC1C,iCAAiB,IAAI,QAAgB;AACvC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"newTestInstance.d.cts","names":[],"sources":["../src/newTestInstance.ts"],"mappings":";;;;;;;;;;;;;;;;;;;cAsDa,WAAW;;;;;;;;;;;;KAyBZ,YAAY,UAAU,UAAU,gBAAgB;EAC1D;EACA,MAAM,SAAS;EACf;EACA;EACA;OAIC,WAAW,gBAAgB,MAAM,gBAAgB,GAAG;cAK1C,UAAQ;cAER,uCAAa,SAAA;cACb,2CAAiB,SAAA;cACjB,2CAAiB,SAAA;;;;;;;;;iBAYd,gBAAgB,UAAU,QACxC,IAAI,eACJ,MAAM,kBAAkB,IAExB;;AAAA,WAAU,YAAY,IAEtB;;AAAA,cAAa,YAAY;EACvB,eAAe,MAAM,OAAO,IAAI,UAAU,QAAQ;IAEnD,QAAQ;;;;;;;
|
|
1
|
+
{"version":3,"file":"newTestInstance.d.cts","names":[],"sources":["../src/newTestInstance.ts"],"mappings":";;;;;;;;;;;;;;;;;;;cAsDa,WAAW;;;;;;;;;;;;KAyBZ,YAAY,UAAU,UAAU,gBAAgB;EAC1D;EACA,MAAM,SAA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aAAa,IAAI,GAC9D,WAAW,kBAAkB,OAC7B;EACE,YAAY,kBAAkB;EAC9B,sBAAsB,+BAA+B;IAEtD,iBAAiB;;;;;;;;;;iBAqBJ,aAAa,UAAU,QAAQ,IAAI,eAAe,MAAM,+BAA+B;KAiDlG,UAAU,KAAK;KAEf,gBAAgB,UAAU,UAAU,yBAAyB,OAAO;;KAG7D,iBAAiB,UAAU,UACnC,IAKA,KAAK,MACJ,kBAAkB;EAAO;;KAEzB,yBAAyB,QAC3B,WAAW,KAAK,EAAE,WAAW,gBAAgB,KAC1C,UAAU,YAAY,KACpB,UAAU,SACR,MAAM,iBAAiB,MACvB,EAAE,KACJ,UAAU,SACR,iBAAiB,KACjB,EAAE,KACN,EAAE;KAUI;;iBA8II,kBAAkB;;cAKrB;WACiB;EAA5B,YAA4B;;iBAGd,kBAAkB,QAAQ;iBAI1B"}
|
package/build/newTestInstance.js
CHANGED
|
@@ -139,6 +139,7 @@ function newTestInstance(em, cstr, testOpts = {}, factoryOpts = {}) {
|
|
|
139
139
|
const realName = fieldName[4].toLowerCase() + fieldName.substring(5);
|
|
140
140
|
const realField = meta.allFields[realName];
|
|
141
141
|
if (realField && "derived" in realField && realField.derived === "async") return [realName, new FactoryInitialValue(optValue)];
|
|
142
|
+
if (realField?.kind === "enum" && meta.transitions.has(realName)) return [realName, new FactoryInitialValue(optValue)];
|
|
142
143
|
}
|
|
143
144
|
throw new Error(`Unknown field ${fieldName}`);
|
|
144
145
|
}
|