joist-test-utils 2.5.0-next.15 → 2.5.0-next.17
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/RunPlugin.cjs +19 -16
- package/build/RunPlugin.cjs.map +1 -1
- package/build/RunPlugin.js +19 -16
- package/build/RunPlugin.js.map +1 -1
- package/build/run.cjs +1 -1
- package/build/run.cjs.map +1 -1
- package/build/run.js +2 -2
- package/build/run.js.map +1 -1
- package/package.json +3 -3
package/build/RunPlugin.cjs
CHANGED
|
@@ -22,14 +22,15 @@ var RunPlugin = class extends joist_core.Plugin {
|
|
|
22
22
|
}
|
|
23
23
|
#syncEntityData(entityTodos) {
|
|
24
24
|
const { em } = this;
|
|
25
|
-
const
|
|
25
|
+
const api = (0, joist_core.getEmInternalApi)(em);
|
|
26
|
+
const { isLoadedCache } = api;
|
|
26
27
|
Object.values(entityTodos).forEach((todo) => {
|
|
27
28
|
todo.inserts.forEach((newEntity) => {
|
|
28
29
|
const row = (0, joist_core.createRowFromEntityData)(newEntity, { preferOriginalData: false });
|
|
29
30
|
em.hydrate(newEntity.constructor, [row]);
|
|
30
31
|
});
|
|
31
32
|
todo.updates.forEach((newEntity) => {
|
|
32
|
-
const oldEntity =
|
|
33
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
33
34
|
if (!oldEntity) (0, joist_core.fail)(`Expected to find existing entity for $ {e.idTagged}`);
|
|
34
35
|
const { data: newData } = (0, joist_core.getInstanceData)(newEntity);
|
|
35
36
|
const { data: oldData } = (0, joist_core.getInstanceData)(oldEntity);
|
|
@@ -48,7 +49,7 @@ var RunPlugin = class extends joist_core.Plugin {
|
|
|
48
49
|
});
|
|
49
50
|
});
|
|
50
51
|
todo.deletes.forEach((newEntity) => {
|
|
51
|
-
const existing =
|
|
52
|
+
const existing = api.getEntity(newEntity.idTagged);
|
|
52
53
|
if (!existing) (0, joist_core.fail)(`Expected to find existing entity for $ {e.idTagged}`);
|
|
53
54
|
(0, joist_core.getInstanceData)(existing).markDeletedBecauseNotFound();
|
|
54
55
|
});
|
|
@@ -56,29 +57,30 @@ var RunPlugin = class extends joist_core.Plugin {
|
|
|
56
57
|
}
|
|
57
58
|
#syncReferencesAndLazyFields(entityTodos) {
|
|
58
59
|
const { em } = this;
|
|
60
|
+
const api = (0, joist_core.getEmInternalApi)(em);
|
|
59
61
|
Object.values(entityTodos).forEach((todo) => {
|
|
60
62
|
todo.inserts.forEach((newEntity) => {
|
|
61
|
-
const oldEntity =
|
|
63
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
62
64
|
for (const field of getLazyFields(newEntity)) preloadLazyField(oldEntity, field.fieldName);
|
|
63
65
|
getReferences(newEntity).forEach((r) => {
|
|
64
|
-
const other = r.isSet ?
|
|
66
|
+
const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : void 0;
|
|
65
67
|
preloadReference(em, r.fieldName, oldEntity, other);
|
|
66
68
|
if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);
|
|
67
69
|
});
|
|
68
70
|
});
|
|
69
71
|
todo.updates.forEach((newEntity) => {
|
|
70
|
-
const oldEntity =
|
|
72
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
71
73
|
for (const field of getLazyFields(newEntity)) if (newEntity.changes[field.fieldName].hasChanged) preloadLazyField(oldEntity, field.fieldName);
|
|
72
74
|
getReferences(newEntity).filter((r) => newEntity.changes[r.fieldName].hasChanged).forEach((r) => {
|
|
73
|
-
const other = r.isSet ?
|
|
75
|
+
const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : void 0;
|
|
74
76
|
preloadReference(em, r.fieldName, oldEntity, other);
|
|
75
77
|
if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);
|
|
76
78
|
const originalId = newEntity.changes[r.fieldName].originalValue;
|
|
77
|
-
const originalOther = originalId ?
|
|
79
|
+
const originalOther = originalId ? api.getEntity(originalId) : void 0;
|
|
78
80
|
if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);
|
|
79
81
|
});
|
|
80
82
|
if ("deletedAt" in newEntity && newEntity.changes.deletedAt.hasChanged) getReferences(oldEntity).forEach((r) => {
|
|
81
|
-
const other = r.isSet ?
|
|
83
|
+
const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : void 0;
|
|
82
84
|
if (other) {
|
|
83
85
|
const otherSide = getOtherSide(r.fieldName, oldEntity, other);
|
|
84
86
|
if (otherSide instanceof joist_core.OneToManyCollection) otherSide.resetIsLoaded();
|
|
@@ -86,10 +88,10 @@ var RunPlugin = class extends joist_core.Plugin {
|
|
|
86
88
|
});
|
|
87
89
|
});
|
|
88
90
|
todo.deletes.forEach((newEntity) => {
|
|
89
|
-
const oldEntity =
|
|
91
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
90
92
|
getReferences(newEntity).forEach((r) => {
|
|
91
93
|
const entityOrId = (0, joist_core.getInstanceData)(oldEntity).data[r.fieldName];
|
|
92
|
-
const originalOther = entityOrId ?
|
|
94
|
+
const originalOther = entityOrId ? api.getEntity((0, joist_core.isEntity)(entityOrId) ? entityOrId.idTagged : entityOrId) : void 0;
|
|
93
95
|
if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);
|
|
94
96
|
});
|
|
95
97
|
});
|
|
@@ -122,7 +124,7 @@ var RunPlugin = class extends joist_core.Plugin {
|
|
|
122
124
|
rows.forEach((row) => {
|
|
123
125
|
const newEntity = row.columns[columnName];
|
|
124
126
|
const enumId = row.columns[otherColumnName];
|
|
125
|
-
const oldEntity =
|
|
127
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
126
128
|
if (!oldEntity || oldEntity.isDeletedEntity) return;
|
|
127
129
|
const oldCollection = oldEntity[fieldName];
|
|
128
130
|
if (!oldCollection.isLoaded && !newEntity.isNewEntity) return;
|
|
@@ -143,11 +145,12 @@ var RunPlugin = class extends joist_core.Plugin {
|
|
|
143
145
|
}
|
|
144
146
|
#preloadUnloadedRelations(entityTodos) {
|
|
145
147
|
const { em } = this;
|
|
148
|
+
const api = (0, joist_core.getEmInternalApi)(em);
|
|
146
149
|
Object.entries(entityTodos).forEach(([, todo]) => {
|
|
147
150
|
todo.inserts.forEach((newEntity) => {
|
|
148
|
-
const oldEntity =
|
|
151
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
149
152
|
getCollections(oldEntity).filter((r) => !r.isLoaded && !r.isPreloaded).forEach((r) => {
|
|
150
|
-
|
|
153
|
+
api.setPreloadedRelation(oldEntity.idTagged, r.fieldName, []);
|
|
151
154
|
r.preload();
|
|
152
155
|
});
|
|
153
156
|
});
|
|
@@ -203,11 +206,11 @@ function processJoinRows(em, joinTable, rows, toPreload, add) {
|
|
|
203
206
|
e1
|
|
204
207
|
]]) {
|
|
205
208
|
const { idTagged: id } = newEntity;
|
|
206
|
-
const oldEntity =
|
|
209
|
+
const oldEntity = api.getEntity(id);
|
|
207
210
|
if (oldEntity.isDeletedEntity) continue;
|
|
208
211
|
const { fieldName } = getManyToManys(newEntity).find((r) => r.joinTableName === joinTable && r.columnName === column);
|
|
209
212
|
const oldM2m = oldEntity[fieldName];
|
|
210
|
-
const oldOther =
|
|
213
|
+
const oldOther = api.getEntity(newOther.idTagged);
|
|
211
214
|
const joinRows = api.joinRows(oldM2m);
|
|
212
215
|
let entities;
|
|
213
216
|
if (toPreload.has(oldM2m)) entities = api.getPreloadedRelation(id, fieldName);
|
package/build/RunPlugin.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RunPlugin.cjs","names":["Plugin","getEmInternalApi","createRowFromEntityData","getInstanceData","getMetadata","PolymorphicKeySerde","PojoRowData","OneToManyCollection","isEntity","getRelations","OneToOneReferenceImpl","ReactiveManyToManyImpl","ManyToOneReferenceImpl","ReactiveReferenceImpl","PolymorphicReferenceImpl","ManyToManyCollection","ReactiveManyToManyOtherSideImpl","EnumCollectionImpl"],"sources":["../src/RunPlugin.ts"],"sourcesContent":["import {\n type Entity,\n type EntityManager,\n EnumCollectionImpl,\n type FieldColumn,\n type JoinRow,\n type JoinRowTodo,\n type LazyFieldImpl,\n ManyToManyCollection,\n ManyToOneReferenceImpl,\n type MaybeAbstractEntityConstructor,\n OneToManyCollection,\n OneToOneReferenceImpl,\n Plugin,\n PojoRowData,\n PolymorphicKeySerde,\n PolymorphicReferenceImpl,\n type PrimitiveField,\n ReactiveManyToManyImpl,\n ReactiveManyToManyOtherSideImpl,\n ReactiveReferenceImpl,\n type Todo,\n assertNever,\n createRowFromEntityData,\n fail,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getRelations,\n isEntity,\n} from \"joist-core\";\n\n/*\n * `run...` helpers use this plugin to mirror changes from their isolated entity manager to the original\n * entity manager they were passed. This allows changes to be synchronously reflected between the two entity managers\n * without needing to query the database.\n */\nexport class RunPlugin extends Plugin {\n // The em passed here is the target which we'll mirror changes to. The plugin should not be added to it, but rather\n // to the new em `run..` helpers create or by downstream ems created by implementation code\n constructor(public readonly em: EntityManager) {\n super();\n }\n\n maybeCloneForNewEm() {\n return this;\n }\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>) {\n const api = getEmInternalApi(this.em);\n // We don't want any old preloaded data leaking into our changes, so we clear it out before we start as a precaution\n api.clearPreloadedRelations();\n // Likewise, any data loaders in memory will have stale data, so we clear them out as well\n api.clearDataloaders();\n this.#syncEntityData(entityTodos);\n this.#syncReferencesAndLazyFields(entityTodos);\n this.#syncManyToManys(joinRowTodos);\n this.#syncEnumCollections(joinRowTodos);\n this.#preloadUnloadedRelations(entityTodos);\n }\n\n #syncEntityData(entityTodos: Record<string, Todo>) {\n const { em } = this;\n const { isLoadedCache } = getEmInternalApi(em);\n Object.values(entityTodos).forEach((todo) => {\n todo.inserts.forEach((newEntity) => {\n const row = createRowFromEntityData(newEntity, { preferOriginalData: false });\n em.hydrate(newEntity.constructor as MaybeAbstractEntityConstructor<Entity>, [row]);\n });\n todo.updates.forEach((newEntity) => {\n const oldEntity = em.findExistingInstance(newEntity.idTagged);\n // This fail shouldn't really be possible, since any entity should either have been created:\n // * via factory or em.create in the original em\n // * by the new em inside the `run` call, in which case it'd be an insert instead of an update\n // * by a previous afterWrite call, which would have already been an insert and added to the original em\n // * by a previous `run` call, which would have already been an insert as well\n if (!oldEntity) fail(`Expected to find existing entity for $ {e.idTagged}`);\n const { data: newData } = getInstanceData(newEntity);\n const { data: oldData } = getInstanceData(oldEntity);\n const meta = getMetadata(newEntity);\n (newEntity as any).changes.fields\n .values()\n .filter((fieldName: string) => fieldName in newData)\n .filter((fieldName: string) => !!meta.allFields[fieldName].serde)\n .forEach((fieldName: string) => {\n // We're imitating a round trip to the database here, so we use our field's serde to map the value back\n // and forth.\n const serde = meta.allFields[fieldName].serde!;\n let column: FieldColumn | undefined;\n let value: any;\n if (serde instanceof PolymorphicKeySerde) {\n [column, value] =\n serde.columns\n .values()\n .map((c) => [c, c.rowValue(newData)] as const)\n .find(([, v]) => v !== undefined) ?? [];\n } else {\n [column] = serde.columns;\n // the 2nd and 3rd arguments are only used if the 4th argument is defined, so it's OK to pass undefined here\n value = column.rowValue(newData);\n }\n oldData[fieldName] = serde.fromRow(new PojoRowData([column ? { [column.columnName]: value } : {}]), 0);\n // Mirror setField's cache invalidation for these changed fields without making test entities dirty\n // or queuing business reactions that the isolated EM has already processed.\n isLoadedCache.resetIsLoaded(oldEntity, fieldName);\n });\n });\n todo.deletes.forEach((newEntity) => {\n const existing = em.findExistingInstance(newEntity.idTagged);\n // Again it shouldn't really be possible for a deletion to happen without the entity being present in the\n // original em, but just in case we'll skip if we don't find it\n if (!existing) fail(`Expected to find existing entity for $ {e.idTagged}`);\n getInstanceData(existing).markDeletedBecauseNotFound();\n });\n });\n }\n\n // Ensure m2o/rr/poly changes and known lazy values from the new em are loaded in the original em\n // Run is a test helper, so we eagerly preload the test entity graph for synchronous assertions. LazyFields are an\n // exception: they can hold large payloads, so we only preload values known from inserts or changed columns. Untouched\n // lazy fields keep their loaded state instead of fetching data that the production code did not write.\n #syncReferencesAndLazyFields(entityTodos: Record<string, Todo>) {\n const { em } = this;\n Object.values(entityTodos).forEach((todo) => {\n todo.inserts.forEach((newEntity) => {\n const oldEntity = em.findExistingInstance(newEntity.idTagged)!;\n // New entities always have the lazy field's initial value, so always preload them\n for (const field of getLazyFields(newEntity)) {\n preloadLazyField(oldEntity, field.fieldName);\n }\n\n getReferences(newEntity).forEach((r) => {\n const other = r.isSet ? em.findExistingInstance(r.idTaggedMaybe) : undefined;\n preloadReference(em, r.fieldName, oldEntity, other);\n if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);\n });\n });\n todo.updates.forEach((newEntity) => {\n const oldEntity = em.findExistingInstance(newEntity.idTagged)!;\n // Only preload lazy fields that were actively changed, b/c they're already available/loaded in the entity we're copying from\n for (const field of getLazyFields(newEntity)) {\n if ((newEntity as any).changes[field.fieldName].hasChanged) {\n preloadLazyField(oldEntity, field.fieldName);\n }\n }\n\n getReferences(newEntity)\n .filter((r) => (newEntity as any).changes[r.fieldName].hasChanged)\n .forEach((r) => {\n const other = r.isSet ? em.findExistingInstance(r.idTaggedMaybe) : undefined;\n preloadReference(em, r.fieldName, oldEntity, other);\n if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);\n const originalId = (newEntity as any).changes[r.fieldName].originalValue;\n const originalOther = originalId ? em.findExistingInstance(originalId) : undefined;\n if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);\n });\n // If the entity was soft-deleted, then we need to clear out the caches for any o2m collections that contain it\n if (\"deletedAt\" in newEntity && (newEntity as any).changes.deletedAt.hasChanged) {\n getReferences(oldEntity).forEach((r) => {\n const other = r.isSet ? em.findExistingInstance(r.idTaggedMaybe) : undefined;\n if (other) {\n const otherSide = getOtherSide(r.fieldName, oldEntity, other);\n if (otherSide instanceof OneToManyCollection) otherSide.resetIsLoaded();\n }\n });\n }\n });\n todo.deletes.forEach((newEntity) => {\n const oldEntity = em.findExistingInstance(newEntity.idTagged)!;\n getReferences(newEntity).forEach((r) => {\n // Since both old and new entities are marked as deleted, we can't just go looking through their relations\n // for the other side's id since this will error. Likewise, we only care about the collection that this\n // entity used to belong to in the old em so we can remove it. So just grab the other id directly from the\n // old entity's data and then preload its other side relation.\n const entityOrId = getInstanceData(oldEntity).data[r.fieldName];\n const originalOther = entityOrId\n ? em.findExistingInstance(isEntity(entityOrId) ? entityOrId.idTagged : entityOrId)\n : undefined;\n if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);\n });\n });\n });\n }\n\n // Ensure m2m changes are propagated from the new em to the original em\n #syncManyToManys(joinRowTodos: Record<string, JoinRowTodo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n Object.entries(joinRowTodos).forEach(([joinTable, todo]) => {\n // Enum m2ms (EnumCollections) aren't entity-to-entity, so there's nothing to mirror between ems.\n if (todo.m2m.otherEnum) return;\n const toPreload = new Set<ManyToMany>();\n processJoinRows(em, joinTable, todo.newRows, toPreload, true);\n processJoinRows(em, joinTable, todo.deletedRows, toPreload, false);\n // Since multiple join rows could reference the same m2m, our processJoinRows doesn't actually call preload() so\n // we need to do it now\n toPreload.values().forEach((r) => {\n const id = r.entity.idTagged;\n const entities = api.getPreloadedRelation(id, r.fieldName) as Entity[];\n // unique our entities in case somehow an entity was inserted by multiple join rows\n api.setPreloadedRelation(id, r.fieldName, [...new Set(entities)]);\n r.preload();\n });\n });\n }\n\n // Ensure enum m2m (EnumCollection) membership changes are propagated from the new em to the original em\n #syncEnumCollections(joinRowTodos: Record<string, JoinRowTodo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n const touched = new Set<EnumCollectionImpl<Entity, any>>();\n Object.values(joinRowTodos).forEach((todo) => {\n // Only enum m2ms; entity-to-entity m2ms are handled by `#syncManyToManys`.\n if (!todo.m2m.otherEnum) return;\n const { columnName, otherColumnName, fieldName } = todo.m2m;\n const sync = (rows: JoinRow[], add: boolean) => {\n rows.forEach((row) => {\n const newEntity = row.columns[columnName] as Entity;\n const enumId = row.columns[otherColumnName] as number;\n const oldEntity = em.findExistingInstance(newEntity.idTagged);\n if (!oldEntity || oldEntity.isDeletedEntity) return;\n const oldCollection = (oldEntity as any)[fieldName] as EnumCollectionImpl<Entity, any>;\n // Only mirror collections the original em has loaded (or new entities, whose rows are all\n // adds); otherwise a later `.load()` will read the (same-txn) db and see the change itself.\n if (!oldCollection.isLoaded && !newEntity.isNewEntity) return;\n const joinRows = api.joinRows(oldCollection);\n if (add) {\n joinRows.addPreloadedRow(oldCollection, undefined, oldEntity, enumId);\n } else {\n joinRows.removePreloadedRow(oldCollection, oldEntity, enumId);\n }\n touched.add(oldCollection);\n });\n };\n sync(todo.newRows, true);\n sync(todo.deletedRows, false);\n });\n // Re-publish each touched collection's codes and mark it loaded.\n touched.forEach((oldCollection) => {\n const joinRows = api.joinRows(oldCollection);\n const codes = (joinRows.getOthers(oldCollection.columnName, oldCollection.entity) as number[]).map(\n (id) => oldCollection.otherEnum!.findById(id)!.code,\n );\n api.setPreloadedRelation(oldCollection.entity.idTagged, oldCollection.fieldName, codes);\n oldCollection.preload();\n });\n }\n\n // Make sure any unloaded relations on net new entities are marked as loaded. We should have already preloaded all\n // concrete references in a previous step. So we just need to load collections (plus o2os) if they haven't already\n // been preloaded by another step. Since nothing else preloaded them, they must have no data so we can just set\n // them to an empty array.\n #preloadUnloadedRelations(entityTodos: Record<string, Todo>) {\n const { em } = this;\n Object.entries(entityTodos).forEach(([, todo]) => {\n todo.inserts.forEach((newEntity) => {\n const oldEntity = em.findExistingInstance(newEntity.idTagged)!;\n getCollections(oldEntity)\n .filter((r) => !r.isLoaded && !r.isPreloaded)\n .forEach((r) => {\n getEmInternalApi(em).setPreloadedRelation(oldEntity.idTagged, r.fieldName, []);\n r.preload();\n });\n });\n });\n }\n}\n\n// References that represent one (or more) foreign keys directly on the entity\ntype ConcreteReference =\n | ManyToOneReferenceImpl<Entity, Entity, any>\n | ReactiveReferenceImpl<Entity, Entity, any, any>\n | PolymorphicReferenceImpl<Entity, Entity, any>;\n\ntype ManyToMany =\n | ManyToManyCollection<Entity, Entity>\n | ReactiveManyToManyImpl<any, any, any>\n | ReactiveManyToManyOtherSideImpl<any, any>;\n\n/** Preloads a mirrored lazy value without treating the database write as a test-entity mutation. */\nfunction preloadLazyField(entity: Entity, fieldName: string): void {\n const field = (entity as any)[fieldName] as LazyFieldImpl<Entity, unknown>;\n field.preload();\n}\n\nfunction preloadReference(em: EntityManager, fieldName: string, entity: Entity, other: Entity | undefined) {\n // Preload for concrete references doesn't make us of the global preloaded cache. It just looks at its owner's data\n // to get a key, then checks if that entity is already in the em and uses that if so. So we just need to set the\n // owner's data to have the correct key then we can call preload since all entities should already be in the original\n // em\n const reference = (entity as any)[fieldName] as ConcreteReference;\n (reference as any).unload();\n const { data } = getInstanceData(entity);\n data[fieldName] = other?.idTagged;\n if (!entity.isDeletedEntity) reference.preload();\n}\n\nfunction getOtherSide(fieldName: string, entity: Entity, other: Entity) {\n const meta = getMetadata(entity);\n const metas = new Set([meta, ...meta.baseTypes]);\n return getRelations(other)\n .values()\n .filter((r) => r instanceof OneToOneReferenceImpl || r instanceof OneToManyCollection)\n .find((r) => metas.has(r.otherMeta) && r.otherFieldName === fieldName);\n}\n\nfunction maybePreloadOtherSide(\n em: EntityManager,\n fieldName: string,\n entity: Entity,\n other: Entity,\n remove: boolean = false,\n): void {\n const meta = getMetadata(entity);\n const otherSide = getOtherSide(fieldName, entity, other);\n // If our other side is a large o2m then we can just ignore it, since it isn't loadable regardless\n if (!otherSide) return;\n // Since our preload scans the entire em, we only need to run it once per collection/o2o. We clear out preloads\n // when we start the afterWrite, so if anything is preloaded we know we put it there.\n if (otherSide.isPreloaded) return;\n let otherEntities: Entity[];\n if (otherSide instanceof OneToOneReferenceImpl) {\n otherEntities = remove ? [] : [entity];\n } else if (otherSide instanceof OneToManyCollection) {\n // Scan the entire em for (non-deleted) entities of our type that reference the other side\n otherEntities = em\n .getEntities(meta.cstr)\n .values()\n .filter((e) => !e.isDeletedEntity)\n .filter((e) => ((e as any)[otherSide.otherFieldName] as ConcreteReference).idTaggedMaybe === other.idTagged)\n .toArray();\n } else {\n assertNever(otherSide);\n }\n // We don't need to worry about order here because o2ms do their own sorting internally and o2os are inherently\n // unordered (since it's just a single entity)\n getEmInternalApi(em).setPreloadedRelation(other.idTagged, otherSide.fieldName, otherEntities);\n otherSide.preload();\n // This method is confusingly name, what it actually does is clear out the sorted caches that m2m uses to avoid\n // sorting on every `.get` call. Since we just preloaded the collection with new data, we know these caches need to\n // be cleared\n if (otherSide instanceof OneToManyCollection) otherSide.resetIsLoaded();\n}\n\n/**\n * Mirrors persisted join rows without deriving membership or queuing fixture reactions.\n *\n * Used only by RunPlugin to apply changes that the isolated EntityManager has already flushed.\n * Factory-created collections have complete membership in their index; other unloaded collections stay unloaded.\n */\nfunction processJoinRows(\n em: EntityManager,\n joinTable: string,\n rows: JoinRow[],\n toPreload: Set<ManyToMany>,\n add: boolean,\n): void {\n const api = getEmInternalApi(em);\n for (const row of rows) {\n // A join row's `columns` is always an object with two key/value pairs, one for each side of the m2m.\n // This only runs for entity-to-entity m2ms (enum m2ms are skipped by the caller), so both are entities.\n const [[col1, e1], [col2, e2]] = Object.entries(row.columns) as [[string, Entity], [string, Entity]];\n for (const [column, newEntity, newOther] of [\n // Each join row needs to append/remove from both sides of the m2m. So we need to do the same operation once for\n // each side.\n [col1, e1, e2],\n [col2, e2, e1],\n ] as const) {\n const { idTagged: id } = newEntity;\n const oldEntity = em.findExistingInstance(id)!;\n if (oldEntity.isDeletedEntity) continue;\n const newM2m = getManyToManys(newEntity).find((r) => r.joinTableName === joinTable && r.columnName === column)!;\n const { fieldName } = newM2m;\n const oldM2m = (oldEntity as any)[fieldName] as ManyToMany;\n const oldOther = em.findExistingInstance(newOther.idTagged)!;\n const joinRows = api.joinRows(oldM2m);\n let entities: Entity[] | undefined;\n if (toPreload.has(oldM2m)) {\n // If a previous join row has already preloaded this relation, then we can just append/remove from the\n // existing preloaded data.\n entities = api.getPreloadedRelation(id, fieldName) as Entity[];\n } else if (oldM2m.isLoaded) {\n // The order here is important. M2ms are returned in the order their join rows were inserted, so we need to\n // make sure we match that behavior here. So we get all the extant rows first and then append each new row\n // in order from there. Removals are fine since they'll modify the array in place and the correct order will\n // be preserved.\n // A reactive collection's getter can derive again; mirroring must use its stored value instead.\n entities = [...(oldM2m instanceof ReactiveManyToManyImpl ? oldM2m.current() : oldM2m.getWithDeleted)];\n } else if (newEntity.isNewEntity || getInstanceData(oldEntity).isOrWasNew) {\n // Newly-created mirrored entities have no membership from before this run. Factory-created entities\n // can also have an unloaded reactive inverse; their index contains all membership since creation.\n entities = joinRows.getOthers(column, oldEntity) as Entity[];\n }\n\n // Forked collections can have a stored snapshot without join rows in this EM. Seed that snapshot\n // before applying the mirrored delta so later derivations see the complete persisted membership.\n if (entities && !toPreload.has(oldM2m)) {\n for (const entity of entities) joinRows.addPreloadedRow(oldM2m, undefined, oldEntity, entity);\n }\n // Replace any completed deletion tombstone when a later run re-adds the same membership.\n joinRows.removePreloadedRow(oldM2m, oldEntity, oldOther);\n if (add) joinRows.addPreloadedRow(oldM2m, row.id, oldEntity, oldOther);\n api.isLoadedCache.resetIsLoaded(oldEntity, fieldName);\n\n // A persisted, unloaded collection may have other members we do not know about. Keep it unloaded;\n // its next load will read the full membership from the database instead of publishing a partial list.\n if (!entities) continue;\n if (add) {\n if (!entities.includes(oldOther)) entities.push(oldOther);\n } else {\n const index = entities.indexOf(oldOther);\n if (index !== -1) entities.splice(index, 1);\n }\n api.setPreloadedRelation(id, fieldName, entities);\n // We only need to preload the m2m once, but multiple join rows could reference it, so we keep track of which m2ms\n // need to be preloaded as we work, then actually call preload() at the end once we're done.\n toPreload.add(oldM2m);\n }\n }\n}\n\n/** Returns the lazy columns on an entity, including inherited fields. */\nfunction getLazyFields(entity: Entity): IteratorObject<PrimitiveField> {\n return Object.values(getMetadata(entity).allFields)\n .values()\n .filter((field) => field.kind === \"primitive\")\n .filter((field) => !!field.lazy);\n}\n\nfunction getReferences(entity: Entity): IteratorObject<ConcreteReference> {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToOneReferenceImpl ||\n r instanceof ReactiveReferenceImpl ||\n r instanceof PolymorphicReferenceImpl,\n );\n}\n\nfunction getManyToManys(entity: Entity): IteratorObject<ManyToMany> {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToManyCollection ||\n r instanceof ReactiveManyToManyImpl ||\n r instanceof ReactiveManyToManyOtherSideImpl,\n );\n}\n\nfunction getCollections(entity: Entity) {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToManyCollection ||\n r instanceof OneToManyCollection ||\n r instanceof OneToOneReferenceImpl ||\n r instanceof ReactiveManyToManyImpl ||\n r instanceof ReactiveManyToManyOtherSideImpl ||\n r instanceof EnumCollectionImpl,\n );\n}\n"],"mappings":";;;AAqCA,IAAa,YAAb,cAA+BA,WAAAA,OAAO;CAGR;CAA5B,YAAY,IAAmC;EAC7C,MAAM;EADoB,KAAA,KAAA;CAE5B;CAEA,qBAAqB;EACnB,OAAO;CACT;CAEA,WAAW,aAAmC,cAA2C;EACvF,MAAM,OAAA,GAAMC,WAAAA,iBAAAA,CAAiB,KAAK,EAAE;EAEpC,IAAI,wBAAwB;EAE5B,IAAI,iBAAiB;EACrB,KAAK,gBAAgB,WAAW;EAChC,KAAK,6BAA6B,WAAW;EAC7C,KAAK,iBAAiB,YAAY;EAClC,KAAK,qBAAqB,YAAY;EACtC,KAAK,0BAA0B,WAAW;CAC5C;CAEA,gBAAgB,aAAmC;EACjD,MAAM,EAAE,OAAO;EACf,MAAM,EAAE,mBAAA,GAAkBA,WAAAA,iBAAAA,CAAiB,EAAE;EAC7C,OAAO,OAAO,WAAW,CAAC,CAAC,SAAS,SAAS;GAC3C,KAAK,QAAQ,SAAS,cAAc;IAClC,MAAM,OAAA,GAAMC,WAAAA,w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AAA,CAAa,MAAM,CAAC,CACxB,OAAO,CAAC,CACR,QACE,MACC,aAAaM,WAAAA,wBACb,aAAaJ,WAAAA,0BACb,aAAaK,WAAAA,+BACjB;AACJ;AAEA,SAAS,eAAe,QAAgB;CACtC,QAAA,GAAOP,WAAAA,aAAAA,CAAa,MAAM,CAAC,CACxB,OAAO,CAAC,CACR,QACE,MACC,aAAaM,WAAAA,wBACb,aAAaR,WAAAA,uBACb,aAAaG,WAAAA,yBACb,aAAaC,WAAAA,0BACb,aAAaK,WAAAA,mCACb,aAAaC,WAAAA,kBACjB;AACJ"}
|
|
1
|
+
{"version":3,"file":"RunPlugin.cjs","names":["Plugin","getEmInternalApi","createRowFromEntityData","getInstanceData","getMetadata","PolymorphicKeySerde","PojoRowData","OneToManyCollection","isEntity","getRelations","OneToOneReferenceImpl","ReactiveManyToManyImpl","ManyToOneReferenceImpl","ReactiveReferenceImpl","PolymorphicReferenceImpl","ManyToManyCollection","ReactiveManyToManyOtherSideImpl","EnumCollectionImpl"],"sources":["../src/RunPlugin.ts"],"sourcesContent":["import {\n type Entity,\n type EntityManager,\n EnumCollectionImpl,\n type FieldColumn,\n type JoinRow,\n type JoinRowTodo,\n type LazyFieldImpl,\n ManyToManyCollection,\n ManyToOneReferenceImpl,\n type MaybeAbstractEntityConstructor,\n OneToManyCollection,\n OneToOneReferenceImpl,\n Plugin,\n PojoRowData,\n PolymorphicKeySerde,\n PolymorphicReferenceImpl,\n type PrimitiveField,\n ReactiveManyToManyImpl,\n ReactiveManyToManyOtherSideImpl,\n ReactiveReferenceImpl,\n type Todo,\n assertNever,\n createRowFromEntityData,\n fail,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getRelations,\n isEntity,\n} from \"joist-core\";\n\n/*\n * `run...` helpers use this plugin to mirror changes from their isolated entity manager to the original\n * entity manager they were passed. This allows changes to be synchronously reflected between the two entity managers\n * without needing to query the database.\n */\nexport class RunPlugin extends Plugin {\n // The em passed here is the target which we'll mirror changes to. The plugin should not be added to it, but rather\n // to the new em `run..` helpers create or by downstream ems created by implementation code\n constructor(public readonly em: EntityManager) {\n super();\n }\n\n maybeCloneForNewEm() {\n return this;\n }\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>) {\n const api = getEmInternalApi(this.em);\n // We don't want any old preloaded data leaking into our changes, so we clear it out before we start as a precaution\n api.clearPreloadedRelations();\n // Likewise, any data loaders in memory will have stale data, so we clear them out as well\n api.clearDataloaders();\n this.#syncEntityData(entityTodos);\n this.#syncReferencesAndLazyFields(entityTodos);\n this.#syncManyToManys(joinRowTodos);\n this.#syncEnumCollections(joinRowTodos);\n this.#preloadUnloadedRelations(entityTodos);\n }\n\n #syncEntityData(entityTodos: Record<string, Todo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n const { isLoadedCache } = api;\n Object.values(entityTodos).forEach((todo) => {\n todo.inserts.forEach((newEntity) => {\n const row = createRowFromEntityData(newEntity, { preferOriginalData: false });\n em.hydrate(newEntity.constructor as MaybeAbstractEntityConstructor<Entity>, [row]);\n });\n todo.updates.forEach((newEntity) => {\n const oldEntity = api.getEntity(newEntity.idTagged);\n // This fail shouldn't really be possible, since any entity should either have been created:\n // * via factory or em.create in the original em\n // * by the new em inside the `run` call, in which case it'd be an insert instead of an update\n // * by a previous afterWrite call, which would have already been an insert and added to the original em\n // * by a previous `run` call, which would have already been an insert as well\n if (!oldEntity) fail(`Expected to find existing entity for $ {e.idTagged}`);\n const { data: newData } = getInstanceData(newEntity);\n const { data: oldData } = getInstanceData(oldEntity);\n const meta = getMetadata(newEntity);\n (newEntity as any).changes.fields\n .values()\n .filter((fieldName: string) => fieldName in newData)\n .filter((fieldName: string) => !!meta.allFields[fieldName].serde)\n .forEach((fieldName: string) => {\n // We're imitating a round trip to the database here, so we use our field's serde to map the value back\n // and forth.\n const serde = meta.allFields[fieldName].serde!;\n let column: FieldColumn | undefined;\n let value: any;\n if (serde instanceof PolymorphicKeySerde) {\n [column, value] =\n serde.columns\n .values()\n .map((c) => [c, c.rowValue(newData)] as const)\n .find(([, v]) => v !== undefined) ?? [];\n } else {\n [column] = serde.columns;\n // the 2nd and 3rd arguments are only used if the 4th argument is defined, so it's OK to pass undefined here\n value = column.rowValue(newData);\n }\n oldData[fieldName] = serde.fromRow(new PojoRowData([column ? { [column.columnName]: value } : {}]), 0);\n // Mirror setField's cache invalidation for these changed fields without making test entities dirty\n // or queuing business reactions that the isolated EM has already processed.\n isLoadedCache.resetIsLoaded(oldEntity, fieldName);\n });\n });\n todo.deletes.forEach((newEntity) => {\n const existing = api.getEntity(newEntity.idTagged);\n // Again it shouldn't really be possible for a deletion to happen without the entity being present in the\n // original em, but just in case we'll skip if we don't find it\n if (!existing) fail(`Expected to find existing entity for $ {e.idTagged}`);\n getInstanceData(existing).markDeletedBecauseNotFound();\n });\n });\n }\n\n // Ensure m2o/rr/poly changes and known lazy values from the new em are loaded in the original em\n // Run is a test helper, so we eagerly preload the test entity graph for synchronous assertions. LazyFields are an\n // exception: they can hold large payloads, so we only preload values known from inserts or changed columns. Untouched\n // lazy fields keep their loaded state instead of fetching data that the production code did not write.\n #syncReferencesAndLazyFields(entityTodos: Record<string, Todo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n Object.values(entityTodos).forEach((todo) => {\n todo.inserts.forEach((newEntity) => {\n const oldEntity = api.getEntity(newEntity.idTagged)!;\n // New entities always have the lazy field's initial value, so always preload them\n for (const field of getLazyFields(newEntity)) {\n preloadLazyField(oldEntity, field.fieldName);\n }\n\n getReferences(newEntity).forEach((r) => {\n const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : undefined;\n preloadReference(em, r.fieldName, oldEntity, other);\n if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);\n });\n });\n todo.updates.forEach((newEntity) => {\n const oldEntity = api.getEntity(newEntity.idTagged)!;\n // Only preload lazy fields that were actively changed, b/c they're already available/loaded in the entity we're copying from\n for (const field of getLazyFields(newEntity)) {\n if ((newEntity as any).changes[field.fieldName].hasChanged) {\n preloadLazyField(oldEntity, field.fieldName);\n }\n }\n\n getReferences(newEntity)\n .filter((r) => (newEntity as any).changes[r.fieldName].hasChanged)\n .forEach((r) => {\n const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : undefined;\n preloadReference(em, r.fieldName, oldEntity, other);\n if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);\n const originalId = (newEntity as any).changes[r.fieldName].originalValue;\n const originalOther = originalId ? api.getEntity(originalId) : undefined;\n if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);\n });\n // If the entity was soft-deleted, then we need to clear out the caches for any o2m collections that contain it\n if (\"deletedAt\" in newEntity && (newEntity as any).changes.deletedAt.hasChanged) {\n getReferences(oldEntity).forEach((r) => {\n const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : undefined;\n if (other) {\n const otherSide = getOtherSide(r.fieldName, oldEntity, other);\n if (otherSide instanceof OneToManyCollection) otherSide.resetIsLoaded();\n }\n });\n }\n });\n todo.deletes.forEach((newEntity) => {\n const oldEntity = api.getEntity(newEntity.idTagged)!;\n getReferences(newEntity).forEach((r) => {\n // Since both old and new entities are marked as deleted, we can't just go looking through their relations\n // for the other side's id since this will error. Likewise, we only care about the collection that this\n // entity used to belong to in the old em so we can remove it. So just grab the other id directly from the\n // old entity's data and then preload its other side relation.\n const entityOrId = getInstanceData(oldEntity).data[r.fieldName];\n const originalOther = entityOrId\n ? api.getEntity(isEntity(entityOrId) ? entityOrId.idTagged : entityOrId)\n : undefined;\n if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);\n });\n });\n });\n }\n\n // Ensure m2m changes are propagated from the new em to the original em\n #syncManyToManys(joinRowTodos: Record<string, JoinRowTodo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n Object.entries(joinRowTodos).forEach(([joinTable, todo]) => {\n // Enum m2ms (EnumCollections) aren't entity-to-entity, so there's nothing to mirror between ems.\n if (todo.m2m.otherEnum) return;\n const toPreload = new Set<ManyToMany>();\n processJoinRows(em, joinTable, todo.newRows, toPreload, true);\n processJoinRows(em, joinTable, todo.deletedRows, toPreload, false);\n // Since multiple join rows could reference the same m2m, our processJoinRows doesn't actually call preload() so\n // we need to do it now\n toPreload.values().forEach((r) => {\n const id = r.entity.idTagged;\n const entities = api.getPreloadedRelation(id, r.fieldName) as Entity[];\n // unique our entities in case somehow an entity was inserted by multiple join rows\n api.setPreloadedRelation(id, r.fieldName, [...new Set(entities)]);\n r.preload();\n });\n });\n }\n\n // Ensure enum m2m (EnumCollection) membership changes are propagated from the new em to the original em\n #syncEnumCollections(joinRowTodos: Record<string, JoinRowTodo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n const touched = new Set<EnumCollectionImpl<Entity, any>>();\n Object.values(joinRowTodos).forEach((todo) => {\n // Only enum m2ms; entity-to-entity m2ms are handled by `#syncManyToManys`.\n if (!todo.m2m.otherEnum) return;\n const { columnName, otherColumnName, fieldName } = todo.m2m;\n const sync = (rows: JoinRow[], add: boolean) => {\n rows.forEach((row) => {\n const newEntity = row.columns[columnName] as Entity;\n const enumId = row.columns[otherColumnName] as number;\n const oldEntity = api.getEntity(newEntity.idTagged);\n if (!oldEntity || oldEntity.isDeletedEntity) return;\n const oldCollection = (oldEntity as any)[fieldName] as EnumCollectionImpl<Entity, any>;\n // Only mirror collections the original em has loaded (or new entities, whose rows are all\n // adds); otherwise a later `.load()` will read the (same-txn) db and see the change itself.\n if (!oldCollection.isLoaded && !newEntity.isNewEntity) return;\n const joinRows = api.joinRows(oldCollection);\n if (add) {\n joinRows.addPreloadedRow(oldCollection, undefined, oldEntity, enumId);\n } else {\n joinRows.removePreloadedRow(oldCollection, oldEntity, enumId);\n }\n touched.add(oldCollection);\n });\n };\n sync(todo.newRows, true);\n sync(todo.deletedRows, false);\n });\n // Re-publish each touched collection's codes and mark it loaded.\n touched.forEach((oldCollection) => {\n const joinRows = api.joinRows(oldCollection);\n const codes = (joinRows.getOthers(oldCollection.columnName, oldCollection.entity) as number[]).map(\n (id) => oldCollection.otherEnum!.findById(id)!.code,\n );\n api.setPreloadedRelation(oldCollection.entity.idTagged, oldCollection.fieldName, codes);\n oldCollection.preload();\n });\n }\n\n // Make sure any unloaded relations on net new entities are marked as loaded. We should have already preloaded all\n // concrete references in a previous step. So we just need to load collections (plus o2os) if they haven't already\n // been preloaded by another step. Since nothing else preloaded them, they must have no data so we can just set\n // them to an empty array.\n #preloadUnloadedRelations(entityTodos: Record<string, Todo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n Object.entries(entityTodos).forEach(([, todo]) => {\n todo.inserts.forEach((newEntity) => {\n const oldEntity = api.getEntity(newEntity.idTagged)!;\n getCollections(oldEntity)\n .filter((r) => !r.isLoaded && !r.isPreloaded)\n .forEach((r) => {\n api.setPreloadedRelation(oldEntity.idTagged, r.fieldName, []);\n r.preload();\n });\n });\n });\n }\n}\n\n// References that represent one (or more) foreign keys directly on the entity\ntype ConcreteReference =\n | ManyToOneReferenceImpl<Entity, Entity, any>\n | ReactiveReferenceImpl<Entity, Entity, any, any>\n | PolymorphicReferenceImpl<Entity, Entity, any>;\n\ntype ManyToMany =\n | ManyToManyCollection<Entity, Entity>\n | ReactiveManyToManyImpl<any, any, any>\n | ReactiveManyToManyOtherSideImpl<any, any>;\n\n/** Preloads a mirrored lazy value without treating the database write as a test-entity mutation. */\nfunction preloadLazyField(entity: Entity, fieldName: string): void {\n const field = (entity as any)[fieldName] as LazyFieldImpl<Entity, unknown>;\n field.preload();\n}\n\nfunction preloadReference(em: EntityManager, fieldName: string, entity: Entity, other: Entity | undefined) {\n // Preload for concrete references doesn't make us of the global preloaded cache. It just looks at its owner's data\n // to get a key, then checks if that entity is already in the em and uses that if so. So we just need to set the\n // owner's data to have the correct key then we can call preload since all entities should already be in the original\n // em\n const reference = (entity as any)[fieldName] as ConcreteReference;\n (reference as any).unload();\n const { data } = getInstanceData(entity);\n data[fieldName] = other?.idTagged;\n if (!entity.isDeletedEntity) reference.preload();\n}\n\nfunction getOtherSide(fieldName: string, entity: Entity, other: Entity) {\n const meta = getMetadata(entity);\n const metas = new Set([meta, ...meta.baseTypes]);\n return getRelations(other)\n .values()\n .filter((r) => r instanceof OneToOneReferenceImpl || r instanceof OneToManyCollection)\n .find((r) => metas.has(r.otherMeta) && r.otherFieldName === fieldName);\n}\n\nfunction maybePreloadOtherSide(\n em: EntityManager,\n fieldName: string,\n entity: Entity,\n other: Entity,\n remove: boolean = false,\n): void {\n const meta = getMetadata(entity);\n const otherSide = getOtherSide(fieldName, entity, other);\n // If our other side is a large o2m then we can just ignore it, since it isn't loadable regardless\n if (!otherSide) return;\n // Since our preload scans the entire em, we only need to run it once per collection/o2o. We clear out preloads\n // when we start the afterWrite, so if anything is preloaded we know we put it there.\n if (otherSide.isPreloaded) return;\n let otherEntities: Entity[];\n if (otherSide instanceof OneToOneReferenceImpl) {\n otherEntities = remove ? [] : [entity];\n } else if (otherSide instanceof OneToManyCollection) {\n // Scan the entire em for (non-deleted) entities of our type that reference the other side\n otherEntities = em\n .getEntities(meta.cstr)\n .values()\n .filter((e) => !e.isDeletedEntity)\n .filter((e) => ((e as any)[otherSide.otherFieldName] as ConcreteReference).idTaggedMaybe === other.idTagged)\n .toArray();\n } else {\n assertNever(otherSide);\n }\n // We don't need to worry about order here because o2ms do their own sorting internally and o2os are inherently\n // unordered (since it's just a single entity)\n getEmInternalApi(em).setPreloadedRelation(other.idTagged, otherSide.fieldName, otherEntities);\n otherSide.preload();\n // This method is confusingly name, what it actually does is clear out the sorted caches that m2m uses to avoid\n // sorting on every `.get` call. Since we just preloaded the collection with new data, we know these caches need to\n // be cleared\n if (otherSide instanceof OneToManyCollection) otherSide.resetIsLoaded();\n}\n\n/**\n * Mirrors persisted join rows without deriving membership or queuing fixture reactions.\n *\n * Used only by RunPlugin to apply changes that the isolated EntityManager has already flushed.\n * Factory-created collections have complete membership in their index; other unloaded collections stay unloaded.\n */\nfunction processJoinRows(\n em: EntityManager,\n joinTable: string,\n rows: JoinRow[],\n toPreload: Set<ManyToMany>,\n add: boolean,\n): void {\n const api = getEmInternalApi(em);\n for (const row of rows) {\n // A join row's `columns` is always an object with two key/value pairs, one for each side of the m2m.\n // This only runs for entity-to-entity m2ms (enum m2ms are skipped by the caller), so both are entities.\n const [[col1, e1], [col2, e2]] = Object.entries(row.columns) as [[string, Entity], [string, Entity]];\n for (const [column, newEntity, newOther] of [\n // Each join row needs to append/remove from both sides of the m2m. So we need to do the same operation once for\n // each side.\n [col1, e1, e2],\n [col2, e2, e1],\n ] as const) {\n const { idTagged: id } = newEntity;\n const oldEntity = api.getEntity(id)!;\n if (oldEntity.isDeletedEntity) continue;\n const newM2m = getManyToManys(newEntity).find((r) => r.joinTableName === joinTable && r.columnName === column)!;\n const { fieldName } = newM2m;\n const oldM2m = (oldEntity as any)[fieldName] as ManyToMany;\n const oldOther = api.getEntity(newOther.idTagged)!;\n const joinRows = api.joinRows(oldM2m);\n let entities: Entity[] | undefined;\n if (toPreload.has(oldM2m)) {\n // If a previous join row has already preloaded this relation, then we can just append/remove from the\n // existing preloaded data.\n entities = api.getPreloadedRelation(id, fieldName) as Entity[];\n } else if (oldM2m.isLoaded) {\n // The order here is important. M2ms are returned in the order their join rows were inserted, so we need to\n // make sure we match that behavior here. So we get all the extant rows first and then append each new row\n // in order from there. Removals are fine since they'll modify the array in place and the correct order will\n // be preserved.\n // A reactive collection's getter can derive again; mirroring must use its stored value instead.\n entities = [...(oldM2m instanceof ReactiveManyToManyImpl ? oldM2m.current() : oldM2m.getWithDeleted)];\n } else if (newEntity.isNewEntity || getInstanceData(oldEntity).isOrWasNew) {\n // Newly-created mirrored entities have no membership from before this run. Factory-created entities\n // can also have an unloaded reactive inverse; their index contains all membership since creation.\n entities = joinRows.getOthers(column, oldEntity) as Entity[];\n }\n\n // Forked collections can have a stored snapshot without join rows in this EM. Seed that snapshot\n // before applying the mirrored delta so later derivations see the complete persisted membership.\n if (entities && !toPreload.has(oldM2m)) {\n for (const entity of entities) joinRows.addPreloadedRow(oldM2m, undefined, oldEntity, entity);\n }\n // Replace any completed deletion tombstone when a later run re-adds the same membership.\n joinRows.removePreloadedRow(oldM2m, oldEntity, oldOther);\n if (add) joinRows.addPreloadedRow(oldM2m, row.id, oldEntity, oldOther);\n api.isLoadedCache.resetIsLoaded(oldEntity, fieldName);\n\n // A persisted, unloaded collection may have other members we do not know about. Keep it unloaded;\n // its next load will read the full membership from the database instead of publishing a partial list.\n if (!entities) continue;\n if (add) {\n if (!entities.includes(oldOther)) entities.push(oldOther);\n } else {\n const index = entities.indexOf(oldOther);\n if (index !== -1) entities.splice(index, 1);\n }\n api.setPreloadedRelation(id, fieldName, entities);\n // We only need to preload the m2m once, but multiple join rows could reference it, so we keep track of which m2ms\n // need to be preloaded as we work, then actually call preload() at the end once we're done.\n toPreload.add(oldM2m);\n }\n }\n}\n\n/** Returns the lazy columns on an entity, including inherited fields. */\nfunction getLazyFields(entity: Entity): IteratorObject<PrimitiveField> {\n return Object.values(getMetadata(entity).allFields)\n .values()\n .filter((field) => field.kind === \"primitive\")\n .filter((field) => !!field.lazy);\n}\n\nfunction getReferences(entity: Entity): IteratorObject<ConcreteReference> {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToOneReferenceImpl ||\n r instanceof ReactiveReferenceImpl ||\n r instanceof PolymorphicReferenceImpl,\n );\n}\n\nfunction getManyToManys(entity: Entity): IteratorObject<ManyToMany> {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToManyCollection ||\n r instanceof ReactiveManyToManyImpl ||\n r instanceof ReactiveManyToManyOtherSideImpl,\n );\n}\n\nfunction getCollections(entity: Entity) {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToManyCollection ||\n r instanceof OneToManyCollection ||\n r instanceof OneToOneReferenceImpl ||\n r instanceof ReactiveManyToManyImpl ||\n r instanceof ReactiveManyToManyOtherSideImpl ||\n r instanceof EnumCollectionImpl,\n );\n}\n"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C,SAAS,SAAS,QAAQ,GAAG,SAAS,KAAK,QAAQ;GAAA,OACnD;IACL,MAAM,QAAQ,SAAS,QAAQ,QAAQ;IACvC,IAAI,UAAU,IAAI,SAAS,OAAO,OAAO,CAAC;GAC5C;GACA,IAAI,qBAAqB,IAAI,WAAW,QAAQ;GAGhD,UAAU,IAAI,MAAM;EACtB;CACF;AACF;;AAGA,SAAS,cAAc,QAAgD;CACrE,OAAO,OAAO,QAAA,GAAOC,WAAAA,YAAAA,CAAY,MAAM,CAAC,CAAC,SAAS,CAAC,CAChD,OAAO,CAAC,CACR,QAAQ,UAAU,MAAM,SAAS,WAAW,CAAC,CAC7C,QAAQ,UAAU,CAAC,CAAC,MAAM,IAAI;AACnC;AAEA,SAAS,cAAc,QAAmD;CACxE,QAAA,GAAOK,WAAAA,aAAAA,CAAa,MAAM,CAAC,CACxB,OAAO,CAAC,CACR,QACE,MACC,aAAaG,WAAAA,0BACb,aAAaC,WAAAA,yBACb,aAAaC,WAAAA,wBACjB;AACJ;AAEA,SAAS,eAAe,QAA4C;CAClE,QAAA,GAAOL,WAAAA,aAAAA,CAAa,MAAM,CAAC,CACxB,OAAO,CAAC,CACR,QACE,MACC,aAAaM,WAAAA,wBACb,aAAaJ,WAAAA,0BACb,aAAaK,WAAAA,+BACjB;AACJ;AAEA,SAAS,eAAe,QAAgB;CACtC,QAAA,GAAOP,WAAAA,aAAAA,CAAa,MAAM,CAAC,CACxB,OAAO,CAAC,CACR,QACE,MACC,aAAaM,WAAAA,wBACb,aAAaR,WAAAA,uBACb,aAAaG,WAAAA,yBACb,aAAaC,WAAAA,0BACb,aAAaK,WAAAA,mCACb,aAAaC,WAAAA,kBACjB;AACJ"}
|
package/build/RunPlugin.js
CHANGED
|
@@ -21,14 +21,15 @@ var RunPlugin = class extends Plugin {
|
|
|
21
21
|
}
|
|
22
22
|
#syncEntityData(entityTodos) {
|
|
23
23
|
const { em } = this;
|
|
24
|
-
const
|
|
24
|
+
const api = getEmInternalApi(em);
|
|
25
|
+
const { isLoadedCache } = api;
|
|
25
26
|
Object.values(entityTodos).forEach((todo) => {
|
|
26
27
|
todo.inserts.forEach((newEntity) => {
|
|
27
28
|
const row = createRowFromEntityData(newEntity, { preferOriginalData: false });
|
|
28
29
|
em.hydrate(newEntity.constructor, [row]);
|
|
29
30
|
});
|
|
30
31
|
todo.updates.forEach((newEntity) => {
|
|
31
|
-
const oldEntity =
|
|
32
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
32
33
|
if (!oldEntity) fail(`Expected to find existing entity for $ {e.idTagged}`);
|
|
33
34
|
const { data: newData } = getInstanceData(newEntity);
|
|
34
35
|
const { data: oldData } = getInstanceData(oldEntity);
|
|
@@ -47,7 +48,7 @@ var RunPlugin = class extends Plugin {
|
|
|
47
48
|
});
|
|
48
49
|
});
|
|
49
50
|
todo.deletes.forEach((newEntity) => {
|
|
50
|
-
const existing =
|
|
51
|
+
const existing = api.getEntity(newEntity.idTagged);
|
|
51
52
|
if (!existing) fail(`Expected to find existing entity for $ {e.idTagged}`);
|
|
52
53
|
getInstanceData(existing).markDeletedBecauseNotFound();
|
|
53
54
|
});
|
|
@@ -55,29 +56,30 @@ var RunPlugin = class extends Plugin {
|
|
|
55
56
|
}
|
|
56
57
|
#syncReferencesAndLazyFields(entityTodos) {
|
|
57
58
|
const { em } = this;
|
|
59
|
+
const api = getEmInternalApi(em);
|
|
58
60
|
Object.values(entityTodos).forEach((todo) => {
|
|
59
61
|
todo.inserts.forEach((newEntity) => {
|
|
60
|
-
const oldEntity =
|
|
62
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
61
63
|
for (const field of getLazyFields(newEntity)) preloadLazyField(oldEntity, field.fieldName);
|
|
62
64
|
getReferences(newEntity).forEach((r) => {
|
|
63
|
-
const other = r.isSet ?
|
|
65
|
+
const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : void 0;
|
|
64
66
|
preloadReference(em, r.fieldName, oldEntity, other);
|
|
65
67
|
if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);
|
|
66
68
|
});
|
|
67
69
|
});
|
|
68
70
|
todo.updates.forEach((newEntity) => {
|
|
69
|
-
const oldEntity =
|
|
71
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
70
72
|
for (const field of getLazyFields(newEntity)) if (newEntity.changes[field.fieldName].hasChanged) preloadLazyField(oldEntity, field.fieldName);
|
|
71
73
|
getReferences(newEntity).filter((r) => newEntity.changes[r.fieldName].hasChanged).forEach((r) => {
|
|
72
|
-
const other = r.isSet ?
|
|
74
|
+
const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : void 0;
|
|
73
75
|
preloadReference(em, r.fieldName, oldEntity, other);
|
|
74
76
|
if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);
|
|
75
77
|
const originalId = newEntity.changes[r.fieldName].originalValue;
|
|
76
|
-
const originalOther = originalId ?
|
|
78
|
+
const originalOther = originalId ? api.getEntity(originalId) : void 0;
|
|
77
79
|
if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);
|
|
78
80
|
});
|
|
79
81
|
if ("deletedAt" in newEntity && newEntity.changes.deletedAt.hasChanged) getReferences(oldEntity).forEach((r) => {
|
|
80
|
-
const other = r.isSet ?
|
|
82
|
+
const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : void 0;
|
|
81
83
|
if (other) {
|
|
82
84
|
const otherSide = getOtherSide(r.fieldName, oldEntity, other);
|
|
83
85
|
if (otherSide instanceof OneToManyCollection) otherSide.resetIsLoaded();
|
|
@@ -85,10 +87,10 @@ var RunPlugin = class extends Plugin {
|
|
|
85
87
|
});
|
|
86
88
|
});
|
|
87
89
|
todo.deletes.forEach((newEntity) => {
|
|
88
|
-
const oldEntity =
|
|
90
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
89
91
|
getReferences(newEntity).forEach((r) => {
|
|
90
92
|
const entityOrId = getInstanceData(oldEntity).data[r.fieldName];
|
|
91
|
-
const originalOther = entityOrId ?
|
|
93
|
+
const originalOther = entityOrId ? api.getEntity(isEntity(entityOrId) ? entityOrId.idTagged : entityOrId) : void 0;
|
|
92
94
|
if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);
|
|
93
95
|
});
|
|
94
96
|
});
|
|
@@ -121,7 +123,7 @@ var RunPlugin = class extends Plugin {
|
|
|
121
123
|
rows.forEach((row) => {
|
|
122
124
|
const newEntity = row.columns[columnName];
|
|
123
125
|
const enumId = row.columns[otherColumnName];
|
|
124
|
-
const oldEntity =
|
|
126
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
125
127
|
if (!oldEntity || oldEntity.isDeletedEntity) return;
|
|
126
128
|
const oldCollection = oldEntity[fieldName];
|
|
127
129
|
if (!oldCollection.isLoaded && !newEntity.isNewEntity) return;
|
|
@@ -142,11 +144,12 @@ var RunPlugin = class extends Plugin {
|
|
|
142
144
|
}
|
|
143
145
|
#preloadUnloadedRelations(entityTodos) {
|
|
144
146
|
const { em } = this;
|
|
147
|
+
const api = getEmInternalApi(em);
|
|
145
148
|
Object.entries(entityTodos).forEach(([, todo]) => {
|
|
146
149
|
todo.inserts.forEach((newEntity) => {
|
|
147
|
-
const oldEntity =
|
|
150
|
+
const oldEntity = api.getEntity(newEntity.idTagged);
|
|
148
151
|
getCollections(oldEntity).filter((r) => !r.isLoaded && !r.isPreloaded).forEach((r) => {
|
|
149
|
-
|
|
152
|
+
api.setPreloadedRelation(oldEntity.idTagged, r.fieldName, []);
|
|
150
153
|
r.preload();
|
|
151
154
|
});
|
|
152
155
|
});
|
|
@@ -202,11 +205,11 @@ function processJoinRows(em, joinTable, rows, toPreload, add) {
|
|
|
202
205
|
e1
|
|
203
206
|
]]) {
|
|
204
207
|
const { idTagged: id } = newEntity;
|
|
205
|
-
const oldEntity =
|
|
208
|
+
const oldEntity = api.getEntity(id);
|
|
206
209
|
if (oldEntity.isDeletedEntity) continue;
|
|
207
210
|
const { fieldName } = getManyToManys(newEntity).find((r) => r.joinTableName === joinTable && r.columnName === column);
|
|
208
211
|
const oldM2m = oldEntity[fieldName];
|
|
209
|
-
const oldOther =
|
|
212
|
+
const oldOther = api.getEntity(newOther.idTagged);
|
|
210
213
|
const joinRows = api.joinRows(oldM2m);
|
|
211
214
|
let entities;
|
|
212
215
|
if (toPreload.has(oldM2m)) entities = api.getPreloadedRelation(id, fieldName);
|
package/build/RunPlugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RunPlugin.js","names":[],"sources":["../src/RunPlugin.ts"],"sourcesContent":["import {\n type Entity,\n type EntityManager,\n EnumCollectionImpl,\n type FieldColumn,\n type JoinRow,\n type JoinRowTodo,\n type LazyFieldImpl,\n ManyToManyCollection,\n ManyToOneReferenceImpl,\n type MaybeAbstractEntityConstructor,\n OneToManyCollection,\n OneToOneReferenceImpl,\n Plugin,\n PojoRowData,\n PolymorphicKeySerde,\n PolymorphicReferenceImpl,\n type PrimitiveField,\n ReactiveManyToManyImpl,\n ReactiveManyToManyOtherSideImpl,\n ReactiveReferenceImpl,\n type Todo,\n assertNever,\n createRowFromEntityData,\n fail,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getRelations,\n isEntity,\n} from \"joist-core\";\n\n/*\n * `run...` helpers use this plugin to mirror changes from their isolated entity manager to the original\n * entity manager they were passed. This allows changes to be synchronously reflected between the two entity managers\n * without needing to query the database.\n */\nexport class RunPlugin extends Plugin {\n // The em passed here is the target which we'll mirror changes to. The plugin should not be added to it, but rather\n // to the new em `run..` helpers create or by downstream ems created by implementation code\n constructor(public readonly em: EntityManager) {\n super();\n }\n\n maybeCloneForNewEm() {\n return this;\n }\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>) {\n const api = getEmInternalApi(this.em);\n // We don't want any old preloaded data leaking into our changes, so we clear it out before we start as a precaution\n api.clearPreloadedRelations();\n // Likewise, any data loaders in memory will have stale data, so we clear them out as well\n api.clearDataloaders();\n this.#syncEntityData(entityTodos);\n this.#syncReferencesAndLazyFields(entityTodos);\n this.#syncManyToManys(joinRowTodos);\n this.#syncEnumCollections(joinRowTodos);\n this.#preloadUnloadedRelations(entityTodos);\n }\n\n #syncEntityData(entityTodos: Record<string, Todo>) {\n const { em } = this;\n const { isLoadedCache } = getEmInternalApi(em);\n Object.values(entityTodos).forEach((todo) => {\n todo.inserts.forEach((newEntity) => {\n const row = createRowFromEntityData(newEntity, { preferOriginalData: false });\n em.hydrate(newEntity.constructor as MaybeAbstractEntityConstructor<Entity>, [row]);\n });\n todo.updates.forEach((newEntity) => {\n const oldEntity = em.findExistingInstance(newEntity.idTagged);\n // This fail shouldn't really be possible, since any entity should either have been created:\n // * via factory or em.create in the original em\n // * by the new em inside the `run` call, in which case it'd be an insert instead of an update\n // * by a previous afterWrite call, which would have already been an insert and added to the original em\n // * by a previous `run` call, which would have already been an insert as well\n if (!oldEntity) fail(`Expected to find existing entity for $ {e.idTagged}`);\n const { data: newData } = getInstanceData(newEntity);\n const { data: oldData } = getInstanceData(oldEntity);\n const meta = getMetadata(newEntity);\n (newEntity as any).changes.fields\n .values()\n .filter((fieldName: string) => fieldName in newData)\n .filter((fieldName: string) => !!meta.allFields[fieldName].serde)\n .forEach((fieldName: string) => {\n // We're imitating a round trip to the database here, so we use our field's serde to map the value back\n // and forth.\n const serde = meta.allFields[fieldName].serde!;\n let column: FieldColumn | undefined;\n let value: any;\n if (serde instanceof PolymorphicKeySerde) {\n [column, value] =\n serde.columns\n .values()\n .map((c) => [c, c.rowValue(newData)] as const)\n .find(([, v]) => v !== undefined) ?? [];\n } else {\n [column] = serde.columns;\n // the 2nd and 3rd arguments are only used if the 4th argument is defined, so it's OK to pass undefined here\n value = column.rowValue(newData);\n }\n oldData[fieldName] = serde.fromRow(new PojoRowData([column ? { [column.columnName]: value } : {}]), 0);\n // Mirror setField's cache invalidation for these changed fields without making test entities dirty\n // or queuing business reactions that the isolated EM has already processed.\n isLoadedCache.resetIsLoaded(oldEntity, fieldName);\n });\n });\n todo.deletes.forEach((newEntity) => {\n const existing = em.findExistingInstance(newEntity.idTagged);\n // Again it shouldn't really be possible for a deletion to happen without the entity being present in the\n // original em, but just in case we'll skip if we don't find it\n if (!existing) fail(`Expected to find existing entity for $ {e.idTagged}`);\n getInstanceData(existing).markDeletedBecauseNotFound();\n });\n });\n }\n\n // Ensure m2o/rr/poly changes and known lazy values from the new em are loaded in the original em\n // Run is a test helper, so we eagerly preload the test entity graph for synchronous assertions. LazyFields are an\n // exception: they can hold large payloads, so we only preload values known from inserts or changed columns. Untouched\n // lazy fields keep their loaded state instead of fetching data that the production code did not write.\n #syncReferencesAndLazyFields(entityTodos: Record<string, Todo>) {\n const { em } = this;\n Object.values(entityTodos).forEach((todo) => {\n todo.inserts.forEach((newEntity) => {\n const oldEntity = em.findExistingInstance(newEntity.idTagged)!;\n // New entities always have the lazy field's initial value, so always preload them\n for (const field of getLazyFields(newEntity)) {\n preloadLazyField(oldEntity, field.fieldName);\n }\n\n getReferences(newEntity).forEach((r) => {\n const other = r.isSet ? em.findExistingInstance(r.idTaggedMaybe) : undefined;\n preloadReference(em, r.fieldName, oldEntity, other);\n if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);\n });\n });\n todo.updates.forEach((newEntity) => {\n const oldEntity = em.findExistingInstance(newEntity.idTagged)!;\n // Only preload lazy fields that were actively changed, b/c they're already available/loaded in the entity we're copying from\n for (const field of getLazyFields(newEntity)) {\n if ((newEntity as any).changes[field.fieldName].hasChanged) {\n preloadLazyField(oldEntity, field.fieldName);\n }\n }\n\n getReferences(newEntity)\n .filter((r) => (newEntity as any).changes[r.fieldName].hasChanged)\n .forEach((r) => {\n const other = r.isSet ? em.findExistingInstance(r.idTaggedMaybe) : undefined;\n preloadReference(em, r.fieldName, oldEntity, other);\n if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);\n const originalId = (newEntity as any).changes[r.fieldName].originalValue;\n const originalOther = originalId ? em.findExistingInstance(originalId) : undefined;\n if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);\n });\n // If the entity was soft-deleted, then we need to clear out the caches for any o2m collections that contain it\n if (\"deletedAt\" in newEntity && (newEntity as any).changes.deletedAt.hasChanged) {\n getReferences(oldEntity).forEach((r) => {\n const other = r.isSet ? em.findExistingInstance(r.idTaggedMaybe) : undefined;\n if (other) {\n const otherSide = getOtherSide(r.fieldName, oldEntity, other);\n if (otherSide instanceof OneToManyCollection) otherSide.resetIsLoaded();\n }\n });\n }\n });\n todo.deletes.forEach((newEntity) => {\n const oldEntity = em.findExistingInstance(newEntity.idTagged)!;\n getReferences(newEntity).forEach((r) => {\n // Since both old and new entities are marked as deleted, we can't just go looking through their relations\n // for the other side's id since this will error. Likewise, we only care about the collection that this\n // entity used to belong to in the old em so we can remove it. So just grab the other id directly from the\n // old entity's data and then preload its other side relation.\n const entityOrId = getInstanceData(oldEntity).data[r.fieldName];\n const originalOther = entityOrId\n ? em.findExistingInstance(isEntity(entityOrId) ? entityOrId.idTagged : entityOrId)\n : undefined;\n if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);\n });\n });\n });\n }\n\n // Ensure m2m changes are propagated from the new em to the original em\n #syncManyToManys(joinRowTodos: Record<string, JoinRowTodo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n Object.entries(joinRowTodos).forEach(([joinTable, todo]) => {\n // Enum m2ms (EnumCollections) aren't entity-to-entity, so there's nothing to mirror between ems.\n if (todo.m2m.otherEnum) return;\n const toPreload = new Set<ManyToMany>();\n processJoinRows(em, joinTable, todo.newRows, toPreload, true);\n processJoinRows(em, joinTable, todo.deletedRows, toPreload, false);\n // Since multiple join rows could reference the same m2m, our processJoinRows doesn't actually call preload() so\n // we need to do it now\n toPreload.values().forEach((r) => {\n const id = r.entity.idTagged;\n const entities = api.getPreloadedRelation(id, r.fieldName) as Entity[];\n // unique our entities in case somehow an entity was inserted by multiple join rows\n api.setPreloadedRelation(id, r.fieldName, [...new Set(entities)]);\n r.preload();\n });\n });\n }\n\n // Ensure enum m2m (EnumCollection) membership changes are propagated from the new em to the original em\n #syncEnumCollections(joinRowTodos: Record<string, JoinRowTodo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n const touched = new Set<EnumCollectionImpl<Entity, any>>();\n Object.values(joinRowTodos).forEach((todo) => {\n // Only enum m2ms; entity-to-entity m2ms are handled by `#syncManyToManys`.\n if (!todo.m2m.otherEnum) return;\n const { columnName, otherColumnName, fieldName } = todo.m2m;\n const sync = (rows: JoinRow[], add: boolean) => {\n rows.forEach((row) => {\n const newEntity = row.columns[columnName] as Entity;\n const enumId = row.columns[otherColumnName] as number;\n const oldEntity = em.findExistingInstance(newEntity.idTagged);\n if (!oldEntity || oldEntity.isDeletedEntity) return;\n const oldCollection = (oldEntity as any)[fieldName] as EnumCollectionImpl<Entity, any>;\n // Only mirror collections the original em has loaded (or new entities, whose rows are all\n // adds); otherwise a later `.load()` will read the (same-txn) db and see the change itself.\n if (!oldCollection.isLoaded && !newEntity.isNewEntity) return;\n const joinRows = api.joinRows(oldCollection);\n if (add) {\n joinRows.addPreloadedRow(oldCollection, undefined, oldEntity, enumId);\n } else {\n joinRows.removePreloadedRow(oldCollection, oldEntity, enumId);\n }\n touched.add(oldCollection);\n });\n };\n sync(todo.newRows, true);\n sync(todo.deletedRows, false);\n });\n // Re-publish each touched collection's codes and mark it loaded.\n touched.forEach((oldCollection) => {\n const joinRows = api.joinRows(oldCollection);\n const codes = (joinRows.getOthers(oldCollection.columnName, oldCollection.entity) as number[]).map(\n (id) => oldCollection.otherEnum!.findById(id)!.code,\n );\n api.setPreloadedRelation(oldCollection.entity.idTagged, oldCollection.fieldName, codes);\n oldCollection.preload();\n });\n }\n\n // Make sure any unloaded relations on net new entities are marked as loaded. We should have already preloaded all\n // concrete references in a previous step. So we just need to load collections (plus o2os) if they haven't already\n // been preloaded by another step. Since nothing else preloaded them, they must have no data so we can just set\n // them to an empty array.\n #preloadUnloadedRelations(entityTodos: Record<string, Todo>) {\n const { em } = this;\n Object.entries(entityTodos).forEach(([, todo]) => {\n todo.inserts.forEach((newEntity) => {\n const oldEntity = em.findExistingInstance(newEntity.idTagged)!;\n getCollections(oldEntity)\n .filter((r) => !r.isLoaded && !r.isPreloaded)\n .forEach((r) => {\n getEmInternalApi(em).setPreloadedRelation(oldEntity.idTagged, r.fieldName, []);\n r.preload();\n });\n });\n });\n }\n}\n\n// References that represent one (or more) foreign keys directly on the entity\ntype ConcreteReference =\n | ManyToOneReferenceImpl<Entity, Entity, any>\n | ReactiveReferenceImpl<Entity, Entity, any, any>\n | PolymorphicReferenceImpl<Entity, Entity, any>;\n\ntype ManyToMany =\n | ManyToManyCollection<Entity, Entity>\n | ReactiveManyToManyImpl<any, any, any>\n | ReactiveManyToManyOtherSideImpl<any, any>;\n\n/** Preloads a mirrored lazy value without treating the database write as a test-entity mutation. */\nfunction preloadLazyField(entity: Entity, fieldName: string): void {\n const field = (entity as any)[fieldName] as LazyFieldImpl<Entity, unknown>;\n field.preload();\n}\n\nfunction preloadReference(em: EntityManager, fieldName: string, entity: Entity, other: Entity | undefined) {\n // Preload for concrete references doesn't make us of the global preloaded cache. It just looks at its owner's data\n // to get a key, then checks if that entity is already in the em and uses that if so. So we just need to set the\n // owner's data to have the correct key then we can call preload since all entities should already be in the original\n // em\n const reference = (entity as any)[fieldName] as ConcreteReference;\n (reference as any).unload();\n const { data } = getInstanceData(entity);\n data[fieldName] = other?.idTagged;\n if (!entity.isDeletedEntity) reference.preload();\n}\n\nfunction getOtherSide(fieldName: string, entity: Entity, other: Entity) {\n const meta = getMetadata(entity);\n const metas = new Set([meta, ...meta.baseTypes]);\n return getRelations(other)\n .values()\n .filter((r) => r instanceof OneToOneReferenceImpl || r instanceof OneToManyCollection)\n .find((r) => metas.has(r.otherMeta) && r.otherFieldName === fieldName);\n}\n\nfunction maybePreloadOtherSide(\n em: EntityManager,\n fieldName: string,\n entity: Entity,\n other: Entity,\n remove: boolean = false,\n): void {\n const meta = getMetadata(entity);\n const otherSide = getOtherSide(fieldName, entity, other);\n // If our other side is a large o2m then we can just ignore it, since it isn't loadable regardless\n if (!otherSide) return;\n // Since our preload scans the entire em, we only need to run it once per collection/o2o. We clear out preloads\n // when we start the afterWrite, so if anything is preloaded we know we put it there.\n if (otherSide.isPreloaded) return;\n let otherEntities: Entity[];\n if (otherSide instanceof OneToOneReferenceImpl) {\n otherEntities = remove ? [] : [entity];\n } else if (otherSide instanceof OneToManyCollection) {\n // Scan the entire em for (non-deleted) entities of our type that reference the other side\n otherEntities = em\n .getEntities(meta.cstr)\n .values()\n .filter((e) => !e.isDeletedEntity)\n .filter((e) => ((e as any)[otherSide.otherFieldName] as ConcreteReference).idTaggedMaybe === other.idTagged)\n .toArray();\n } else {\n assertNever(otherSide);\n }\n // We don't need to worry about order here because o2ms do their own sorting internally and o2os are inherently\n // unordered (since it's just a single entity)\n getEmInternalApi(em).setPreloadedRelation(other.idTagged, otherSide.fieldName, otherEntities);\n otherSide.preload();\n // This method is confusingly name, what it actually does is clear out the sorted caches that m2m uses to avoid\n // sorting on every `.get` call. Since we just preloaded the collection with new data, we know these caches need to\n // be cleared\n if (otherSide instanceof OneToManyCollection) otherSide.resetIsLoaded();\n}\n\n/**\n * Mirrors persisted join rows without deriving membership or queuing fixture reactions.\n *\n * Used only by RunPlugin to apply changes that the isolated EntityManager has already flushed.\n * Factory-created collections have complete membership in their index; other unloaded collections stay unloaded.\n */\nfunction processJoinRows(\n em: EntityManager,\n joinTable: string,\n rows: JoinRow[],\n toPreload: Set<ManyToMany>,\n add: boolean,\n): void {\n const api = getEmInternalApi(em);\n for (const row of rows) {\n // A join row's `columns` is always an object with two key/value pairs, one for each side of the m2m.\n // This only runs for entity-to-entity m2ms (enum m2ms are skipped by the caller), so both are entities.\n const [[col1, e1], [col2, e2]] = Object.entries(row.columns) as [[string, Entity], [string, Entity]];\n for (const [column, newEntity, newOther] of [\n // Each join row needs to append/remove from both sides of the m2m. So we need to do the same operation once for\n // each side.\n [col1, e1, e2],\n [col2, e2, e1],\n ] as const) {\n const { idTagged: id } = newEntity;\n const oldEntity = em.findExistingInstance(id)!;\n if (oldEntity.isDeletedEntity) continue;\n const newM2m = getManyToManys(newEntity).find((r) => r.joinTableName === joinTable && r.columnName === column)!;\n const { fieldName } = newM2m;\n const oldM2m = (oldEntity as any)[fieldName] as ManyToMany;\n const oldOther = em.findExistingInstance(newOther.idTagged)!;\n const joinRows = api.joinRows(oldM2m);\n let entities: Entity[] | undefined;\n if (toPreload.has(oldM2m)) {\n // If a previous join row has already preloaded this relation, then we can just append/remove from the\n // existing preloaded data.\n entities = api.getPreloadedRelation(id, fieldName) as Entity[];\n } else if (oldM2m.isLoaded) {\n // The order here is important. M2ms are returned in the order their join rows were inserted, so we need to\n // make sure we match that behavior here. So we get all the extant rows first and then append each new row\n // in order from there. Removals are fine since they'll modify the array in place and the correct order will\n // be preserved.\n // A reactive collection's getter can derive again; mirroring must use its stored value instead.\n entities = [...(oldM2m instanceof ReactiveManyToManyImpl ? oldM2m.current() : oldM2m.getWithDeleted)];\n } else if (newEntity.isNewEntity || getInstanceData(oldEntity).isOrWasNew) {\n // Newly-created mirrored entities have no membership from before this run. Factory-created entities\n // can also have an unloaded reactive inverse; their index contains all membership since creation.\n entities = joinRows.getOthers(column, oldEntity) as Entity[];\n }\n\n // Forked collections can have a stored snapshot without join rows in this EM. Seed that snapshot\n // before applying the mirrored delta so later derivations see the complete persisted membership.\n if (entities && !toPreload.has(oldM2m)) {\n for (const entity of entities) joinRows.addPreloadedRow(oldM2m, undefined, oldEntity, entity);\n }\n // Replace any completed deletion tombstone when a later run re-adds the same membership.\n joinRows.removePreloadedRow(oldM2m, oldEntity, oldOther);\n if (add) joinRows.addPreloadedRow(oldM2m, row.id, oldEntity, oldOther);\n api.isLoadedCache.resetIsLoaded(oldEntity, fieldName);\n\n // A persisted, unloaded collection may have other members we do not know about. Keep it unloaded;\n // its next load will read the full membership from the database instead of publishing a partial list.\n if (!entities) continue;\n if (add) {\n if (!entities.includes(oldOther)) entities.push(oldOther);\n } else {\n const index = entities.indexOf(oldOther);\n if (index !== -1) entities.splice(index, 1);\n }\n api.setPreloadedRelation(id, fieldName, entities);\n // We only need to preload the m2m once, but multiple join rows could reference it, so we keep track of which m2ms\n // need to be preloaded as we work, then actually call preload() at the end once we're done.\n toPreload.add(oldM2m);\n }\n }\n}\n\n/** Returns the lazy columns on an entity, including inherited fields. */\nfunction getLazyFields(entity: Entity): IteratorObject<PrimitiveField> {\n return Object.values(getMetadata(entity).allFields)\n .values()\n .filter((field) => field.kind === \"primitive\")\n .filter((field) => !!field.lazy);\n}\n\nfunction getReferences(entity: Entity): IteratorObject<ConcreteReference> {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToOneReferenceImpl ||\n r instanceof ReactiveReferenceImpl ||\n r instanceof PolymorphicReferenceImpl,\n );\n}\n\nfunction getManyToManys(entity: Entity): IteratorObject<ManyToMany> {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToManyCollection ||\n r instanceof ReactiveManyToManyImpl ||\n r instanceof ReactiveManyToManyOtherSideImpl,\n );\n}\n\nfunction getCollections(entity: Entity) {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToManyCollection ||\n r instanceof OneToManyCollection ||\n r instanceof OneToOneReferenceImpl ||\n r instanceof ReactiveManyToManyImpl ||\n r instanceof ReactiveManyToManyOtherSideImpl ||\n r instanceof EnumCollectionImpl,\n );\n}\n"],"mappings":";;AAqCA,IAAa,YAAb,cAA+B,OAAO;CAGR;CAA5B,YAAY,IAAmC;EAC7C,MAAM;EADoB,KAAA,KAAA;CAE5B;CAEA,qBAAqB;EACnB,OAAO;CACT;CAEA,WAAW,aAAmC,cAA2C;EACvF,MAAM,MAAM,iBAAiB,KAAK,EAAE;EAEpC,IAAI,wBAAwB;EAE5B,IAAI,iBAAiB;EACrB,KAAK,gBAAgB,WAAW;EAChC,KAAK,6B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../src/RunPlugin.ts"],"sourcesContent":["import {\n type Entity,\n type EntityManager,\n EnumCollectionImpl,\n type FieldColumn,\n type JoinRow,\n type JoinRowTodo,\n type LazyFieldImpl,\n ManyToManyCollection,\n ManyToOneReferenceImpl,\n type MaybeAbstractEntityConstructor,\n OneToManyCollection,\n OneToOneReferenceImpl,\n Plugin,\n PojoRowData,\n PolymorphicKeySerde,\n PolymorphicReferenceImpl,\n type PrimitiveField,\n ReactiveManyToManyImpl,\n ReactiveManyToManyOtherSideImpl,\n ReactiveReferenceImpl,\n type Todo,\n assertNever,\n createRowFromEntityData,\n fail,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getRelations,\n isEntity,\n} from \"joist-core\";\n\n/*\n * `run...` helpers use this plugin to mirror changes from their isolated entity manager to the original\n * entity manager they were passed. This allows changes to be synchronously reflected between the two entity managers\n * without needing to query the database.\n */\nexport class RunPlugin extends Plugin {\n // The em passed here is the target which we'll mirror changes to. The plugin should not be added to it, but rather\n // to the new em `run..` helpers create or by downstream ems created by implementation code\n constructor(public readonly em: EntityManager) {\n super();\n }\n\n maybeCloneForNewEm() {\n return this;\n }\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>) {\n const api = getEmInternalApi(this.em);\n // We don't want any old preloaded data leaking into our changes, so we clear it out before we start as a precaution\n api.clearPreloadedRelations();\n // Likewise, any data loaders in memory will have stale data, so we clear them out as well\n api.clearDataloaders();\n this.#syncEntityData(entityTodos);\n this.#syncReferencesAndLazyFields(entityTodos);\n this.#syncManyToManys(joinRowTodos);\n this.#syncEnumCollections(joinRowTodos);\n this.#preloadUnloadedRelations(entityTodos);\n }\n\n #syncEntityData(entityTodos: Record<string, Todo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n const { isLoadedCache } = api;\n Object.values(entityTodos).forEach((todo) => {\n todo.inserts.forEach((newEntity) => {\n const row = createRowFromEntityData(newEntity, { preferOriginalData: false });\n em.hydrate(newEntity.constructor as MaybeAbstractEntityConstructor<Entity>, [row]);\n });\n todo.updates.forEach((newEntity) => {\n const oldEntity = api.getEntity(newEntity.idTagged);\n // This fail shouldn't really be possible, since any entity should either have been created:\n // * via factory or em.create in the original em\n // * by the new em inside the `run` call, in which case it'd be an insert instead of an update\n // * by a previous afterWrite call, which would have already been an insert and added to the original em\n // * by a previous `run` call, which would have already been an insert as well\n if (!oldEntity) fail(`Expected to find existing entity for $ {e.idTagged}`);\n const { data: newData } = getInstanceData(newEntity);\n const { data: oldData } = getInstanceData(oldEntity);\n const meta = getMetadata(newEntity);\n (newEntity as any).changes.fields\n .values()\n .filter((fieldName: string) => fieldName in newData)\n .filter((fieldName: string) => !!meta.allFields[fieldName].serde)\n .forEach((fieldName: string) => {\n // We're imitating a round trip to the database here, so we use our field's serde to map the value back\n // and forth.\n const serde = meta.allFields[fieldName].serde!;\n let column: FieldColumn | undefined;\n let value: any;\n if (serde instanceof PolymorphicKeySerde) {\n [column, value] =\n serde.columns\n .values()\n .map((c) => [c, c.rowValue(newData)] as const)\n .find(([, v]) => v !== undefined) ?? [];\n } else {\n [column] = serde.columns;\n // the 2nd and 3rd arguments are only used if the 4th argument is defined, so it's OK to pass undefined here\n value = column.rowValue(newData);\n }\n oldData[fieldName] = serde.fromRow(new PojoRowData([column ? { [column.columnName]: value } : {}]), 0);\n // Mirror setField's cache invalidation for these changed fields without making test entities dirty\n // or queuing business reactions that the isolated EM has already processed.\n isLoadedCache.resetIsLoaded(oldEntity, fieldName);\n });\n });\n todo.deletes.forEach((newEntity) => {\n const existing = api.getEntity(newEntity.idTagged);\n // Again it shouldn't really be possible for a deletion to happen without the entity being present in the\n // original em, but just in case we'll skip if we don't find it\n if (!existing) fail(`Expected to find existing entity for $ {e.idTagged}`);\n getInstanceData(existing).markDeletedBecauseNotFound();\n });\n });\n }\n\n // Ensure m2o/rr/poly changes and known lazy values from the new em are loaded in the original em\n // Run is a test helper, so we eagerly preload the test entity graph for synchronous assertions. LazyFields are an\n // exception: they can hold large payloads, so we only preload values known from inserts or changed columns. Untouched\n // lazy fields keep their loaded state instead of fetching data that the production code did not write.\n #syncReferencesAndLazyFields(entityTodos: Record<string, Todo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n Object.values(entityTodos).forEach((todo) => {\n todo.inserts.forEach((newEntity) => {\n const oldEntity = api.getEntity(newEntity.idTagged)!;\n // New entities always have the lazy field's initial value, so always preload them\n for (const field of getLazyFields(newEntity)) {\n preloadLazyField(oldEntity, field.fieldName);\n }\n\n getReferences(newEntity).forEach((r) => {\n const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : undefined;\n preloadReference(em, r.fieldName, oldEntity, other);\n if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);\n });\n });\n todo.updates.forEach((newEntity) => {\n const oldEntity = api.getEntity(newEntity.idTagged)!;\n // Only preload lazy fields that were actively changed, b/c they're already available/loaded in the entity we're copying from\n for (const field of getLazyFields(newEntity)) {\n if ((newEntity as any).changes[field.fieldName].hasChanged) {\n preloadLazyField(oldEntity, field.fieldName);\n }\n }\n\n getReferences(newEntity)\n .filter((r) => (newEntity as any).changes[r.fieldName].hasChanged)\n .forEach((r) => {\n const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : undefined;\n preloadReference(em, r.fieldName, oldEntity, other);\n if (other) maybePreloadOtherSide(em, r.fieldName, oldEntity, other);\n const originalId = (newEntity as any).changes[r.fieldName].originalValue;\n const originalOther = originalId ? api.getEntity(originalId) : undefined;\n if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);\n });\n // If the entity was soft-deleted, then we need to clear out the caches for any o2m collections that contain it\n if (\"deletedAt\" in newEntity && (newEntity as any).changes.deletedAt.hasChanged) {\n getReferences(oldEntity).forEach((r) => {\n const other = r.isSet ? api.getEntity(r.idTaggedMaybe) : undefined;\n if (other) {\n const otherSide = getOtherSide(r.fieldName, oldEntity, other);\n if (otherSide instanceof OneToManyCollection) otherSide.resetIsLoaded();\n }\n });\n }\n });\n todo.deletes.forEach((newEntity) => {\n const oldEntity = api.getEntity(newEntity.idTagged)!;\n getReferences(newEntity).forEach((r) => {\n // Since both old and new entities are marked as deleted, we can't just go looking through their relations\n // for the other side's id since this will error. Likewise, we only care about the collection that this\n // entity used to belong to in the old em so we can remove it. So just grab the other id directly from the\n // old entity's data and then preload its other side relation.\n const entityOrId = getInstanceData(oldEntity).data[r.fieldName];\n const originalOther = entityOrId\n ? api.getEntity(isEntity(entityOrId) ? entityOrId.idTagged : entityOrId)\n : undefined;\n if (originalOther) maybePreloadOtherSide(em, r.fieldName, oldEntity, originalOther, true);\n });\n });\n });\n }\n\n // Ensure m2m changes are propagated from the new em to the original em\n #syncManyToManys(joinRowTodos: Record<string, JoinRowTodo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n Object.entries(joinRowTodos).forEach(([joinTable, todo]) => {\n // Enum m2ms (EnumCollections) aren't entity-to-entity, so there's nothing to mirror between ems.\n if (todo.m2m.otherEnum) return;\n const toPreload = new Set<ManyToMany>();\n processJoinRows(em, joinTable, todo.newRows, toPreload, true);\n processJoinRows(em, joinTable, todo.deletedRows, toPreload, false);\n // Since multiple join rows could reference the same m2m, our processJoinRows doesn't actually call preload() so\n // we need to do it now\n toPreload.values().forEach((r) => {\n const id = r.entity.idTagged;\n const entities = api.getPreloadedRelation(id, r.fieldName) as Entity[];\n // unique our entities in case somehow an entity was inserted by multiple join rows\n api.setPreloadedRelation(id, r.fieldName, [...new Set(entities)]);\n r.preload();\n });\n });\n }\n\n // Ensure enum m2m (EnumCollection) membership changes are propagated from the new em to the original em\n #syncEnumCollections(joinRowTodos: Record<string, JoinRowTodo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n const touched = new Set<EnumCollectionImpl<Entity, any>>();\n Object.values(joinRowTodos).forEach((todo) => {\n // Only enum m2ms; entity-to-entity m2ms are handled by `#syncManyToManys`.\n if (!todo.m2m.otherEnum) return;\n const { columnName, otherColumnName, fieldName } = todo.m2m;\n const sync = (rows: JoinRow[], add: boolean) => {\n rows.forEach((row) => {\n const newEntity = row.columns[columnName] as Entity;\n const enumId = row.columns[otherColumnName] as number;\n const oldEntity = api.getEntity(newEntity.idTagged);\n if (!oldEntity || oldEntity.isDeletedEntity) return;\n const oldCollection = (oldEntity as any)[fieldName] as EnumCollectionImpl<Entity, any>;\n // Only mirror collections the original em has loaded (or new entities, whose rows are all\n // adds); otherwise a later `.load()` will read the (same-txn) db and see the change itself.\n if (!oldCollection.isLoaded && !newEntity.isNewEntity) return;\n const joinRows = api.joinRows(oldCollection);\n if (add) {\n joinRows.addPreloadedRow(oldCollection, undefined, oldEntity, enumId);\n } else {\n joinRows.removePreloadedRow(oldCollection, oldEntity, enumId);\n }\n touched.add(oldCollection);\n });\n };\n sync(todo.newRows, true);\n sync(todo.deletedRows, false);\n });\n // Re-publish each touched collection's codes and mark it loaded.\n touched.forEach((oldCollection) => {\n const joinRows = api.joinRows(oldCollection);\n const codes = (joinRows.getOthers(oldCollection.columnName, oldCollection.entity) as number[]).map(\n (id) => oldCollection.otherEnum!.findById(id)!.code,\n );\n api.setPreloadedRelation(oldCollection.entity.idTagged, oldCollection.fieldName, codes);\n oldCollection.preload();\n });\n }\n\n // Make sure any unloaded relations on net new entities are marked as loaded. We should have already preloaded all\n // concrete references in a previous step. So we just need to load collections (plus o2os) if they haven't already\n // been preloaded by another step. Since nothing else preloaded them, they must have no data so we can just set\n // them to an empty array.\n #preloadUnloadedRelations(entityTodos: Record<string, Todo>) {\n const { em } = this;\n const api = getEmInternalApi(em);\n Object.entries(entityTodos).forEach(([, todo]) => {\n todo.inserts.forEach((newEntity) => {\n const oldEntity = api.getEntity(newEntity.idTagged)!;\n getCollections(oldEntity)\n .filter((r) => !r.isLoaded && !r.isPreloaded)\n .forEach((r) => {\n api.setPreloadedRelation(oldEntity.idTagged, r.fieldName, []);\n r.preload();\n });\n });\n });\n }\n}\n\n// References that represent one (or more) foreign keys directly on the entity\ntype ConcreteReference =\n | ManyToOneReferenceImpl<Entity, Entity, any>\n | ReactiveReferenceImpl<Entity, Entity, any, any>\n | PolymorphicReferenceImpl<Entity, Entity, any>;\n\ntype ManyToMany =\n | ManyToManyCollection<Entity, Entity>\n | ReactiveManyToManyImpl<any, any, any>\n | ReactiveManyToManyOtherSideImpl<any, any>;\n\n/** Preloads a mirrored lazy value without treating the database write as a test-entity mutation. */\nfunction preloadLazyField(entity: Entity, fieldName: string): void {\n const field = (entity as any)[fieldName] as LazyFieldImpl<Entity, unknown>;\n field.preload();\n}\n\nfunction preloadReference(em: EntityManager, fieldName: string, entity: Entity, other: Entity | undefined) {\n // Preload for concrete references doesn't make us of the global preloaded cache. It just looks at its owner's data\n // to get a key, then checks if that entity is already in the em and uses that if so. So we just need to set the\n // owner's data to have the correct key then we can call preload since all entities should already be in the original\n // em\n const reference = (entity as any)[fieldName] as ConcreteReference;\n (reference as any).unload();\n const { data } = getInstanceData(entity);\n data[fieldName] = other?.idTagged;\n if (!entity.isDeletedEntity) reference.preload();\n}\n\nfunction getOtherSide(fieldName: string, entity: Entity, other: Entity) {\n const meta = getMetadata(entity);\n const metas = new Set([meta, ...meta.baseTypes]);\n return getRelations(other)\n .values()\n .filter((r) => r instanceof OneToOneReferenceImpl || r instanceof OneToManyCollection)\n .find((r) => metas.has(r.otherMeta) && r.otherFieldName === fieldName);\n}\n\nfunction maybePreloadOtherSide(\n em: EntityManager,\n fieldName: string,\n entity: Entity,\n other: Entity,\n remove: boolean = false,\n): void {\n const meta = getMetadata(entity);\n const otherSide = getOtherSide(fieldName, entity, other);\n // If our other side is a large o2m then we can just ignore it, since it isn't loadable regardless\n if (!otherSide) return;\n // Since our preload scans the entire em, we only need to run it once per collection/o2o. We clear out preloads\n // when we start the afterWrite, so if anything is preloaded we know we put it there.\n if (otherSide.isPreloaded) return;\n let otherEntities: Entity[];\n if (otherSide instanceof OneToOneReferenceImpl) {\n otherEntities = remove ? [] : [entity];\n } else if (otherSide instanceof OneToManyCollection) {\n // Scan the entire em for (non-deleted) entities of our type that reference the other side\n otherEntities = em\n .getEntities(meta.cstr)\n .values()\n .filter((e) => !e.isDeletedEntity)\n .filter((e) => ((e as any)[otherSide.otherFieldName] as ConcreteReference).idTaggedMaybe === other.idTagged)\n .toArray();\n } else {\n assertNever(otherSide);\n }\n // We don't need to worry about order here because o2ms do their own sorting internally and o2os are inherently\n // unordered (since it's just a single entity)\n getEmInternalApi(em).setPreloadedRelation(other.idTagged, otherSide.fieldName, otherEntities);\n otherSide.preload();\n // This method is confusingly name, what it actually does is clear out the sorted caches that m2m uses to avoid\n // sorting on every `.get` call. Since we just preloaded the collection with new data, we know these caches need to\n // be cleared\n if (otherSide instanceof OneToManyCollection) otherSide.resetIsLoaded();\n}\n\n/**\n * Mirrors persisted join rows without deriving membership or queuing fixture reactions.\n *\n * Used only by RunPlugin to apply changes that the isolated EntityManager has already flushed.\n * Factory-created collections have complete membership in their index; other unloaded collections stay unloaded.\n */\nfunction processJoinRows(\n em: EntityManager,\n joinTable: string,\n rows: JoinRow[],\n toPreload: Set<ManyToMany>,\n add: boolean,\n): void {\n const api = getEmInternalApi(em);\n for (const row of rows) {\n // A join row's `columns` is always an object with two key/value pairs, one for each side of the m2m.\n // This only runs for entity-to-entity m2ms (enum m2ms are skipped by the caller), so both are entities.\n const [[col1, e1], [col2, e2]] = Object.entries(row.columns) as [[string, Entity], [string, Entity]];\n for (const [column, newEntity, newOther] of [\n // Each join row needs to append/remove from both sides of the m2m. So we need to do the same operation once for\n // each side.\n [col1, e1, e2],\n [col2, e2, e1],\n ] as const) {\n const { idTagged: id } = newEntity;\n const oldEntity = api.getEntity(id)!;\n if (oldEntity.isDeletedEntity) continue;\n const newM2m = getManyToManys(newEntity).find((r) => r.joinTableName === joinTable && r.columnName === column)!;\n const { fieldName } = newM2m;\n const oldM2m = (oldEntity as any)[fieldName] as ManyToMany;\n const oldOther = api.getEntity(newOther.idTagged)!;\n const joinRows = api.joinRows(oldM2m);\n let entities: Entity[] | undefined;\n if (toPreload.has(oldM2m)) {\n // If a previous join row has already preloaded this relation, then we can just append/remove from the\n // existing preloaded data.\n entities = api.getPreloadedRelation(id, fieldName) as Entity[];\n } else if (oldM2m.isLoaded) {\n // The order here is important. M2ms are returned in the order their join rows were inserted, so we need to\n // make sure we match that behavior here. So we get all the extant rows first and then append each new row\n // in order from there. Removals are fine since they'll modify the array in place and the correct order will\n // be preserved.\n // A reactive collection's getter can derive again; mirroring must use its stored value instead.\n entities = [...(oldM2m instanceof ReactiveManyToManyImpl ? oldM2m.current() : oldM2m.getWithDeleted)];\n } else if (newEntity.isNewEntity || getInstanceData(oldEntity).isOrWasNew) {\n // Newly-created mirrored entities have no membership from before this run. Factory-created entities\n // can also have an unloaded reactive inverse; their index contains all membership since creation.\n entities = joinRows.getOthers(column, oldEntity) as Entity[];\n }\n\n // Forked collections can have a stored snapshot without join rows in this EM. Seed that snapshot\n // before applying the mirrored delta so later derivations see the complete persisted membership.\n if (entities && !toPreload.has(oldM2m)) {\n for (const entity of entities) joinRows.addPreloadedRow(oldM2m, undefined, oldEntity, entity);\n }\n // Replace any completed deletion tombstone when a later run re-adds the same membership.\n joinRows.removePreloadedRow(oldM2m, oldEntity, oldOther);\n if (add) joinRows.addPreloadedRow(oldM2m, row.id, oldEntity, oldOther);\n api.isLoadedCache.resetIsLoaded(oldEntity, fieldName);\n\n // A persisted, unloaded collection may have other members we do not know about. Keep it unloaded;\n // its next load will read the full membership from the database instead of publishing a partial list.\n if (!entities) continue;\n if (add) {\n if (!entities.includes(oldOther)) entities.push(oldOther);\n } else {\n const index = entities.indexOf(oldOther);\n if (index !== -1) entities.splice(index, 1);\n }\n api.setPreloadedRelation(id, fieldName, entities);\n // We only need to preload the m2m once, but multiple join rows could reference it, so we keep track of which m2ms\n // need to be preloaded as we work, then actually call preload() at the end once we're done.\n toPreload.add(oldM2m);\n }\n }\n}\n\n/** Returns the lazy columns on an entity, including inherited fields. */\nfunction getLazyFields(entity: Entity): IteratorObject<PrimitiveField> {\n return Object.values(getMetadata(entity).allFields)\n .values()\n .filter((field) => field.kind === \"primitive\")\n .filter((field) => !!field.lazy);\n}\n\nfunction getReferences(entity: Entity): IteratorObject<ConcreteReference> {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToOneReferenceImpl ||\n r instanceof ReactiveReferenceImpl ||\n r instanceof PolymorphicReferenceImpl,\n );\n}\n\nfunction getManyToManys(entity: Entity): IteratorObject<ManyToMany> {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToManyCollection ||\n r instanceof ReactiveManyToManyImpl ||\n r instanceof ReactiveManyToManyOtherSideImpl,\n );\n}\n\nfunction getCollections(entity: Entity) {\n return getRelations(entity)\n .values()\n .filter(\n (r) =>\n r instanceof ManyToManyCollection ||\n r instanceof OneToManyCollection ||\n r instanceof OneToOneReferenceImpl ||\n r instanceof ReactiveManyToManyImpl ||\n r instanceof ReactiveManyToManyOtherSideImpl ||\n r instanceof EnumCollectionImpl,\n );\n}\n"],"mappings":";;AAqCA,IAAa,YAAb,cAA+B,OAAO;CAGR;CAA5B,YAAY,IAAmC;EAC7C,MAAM;EADoB,KAAA,KAAA;CAE5B;CAEA,qBAAqB;EACnB,OAAO;CACT;CAEA,WAAW,aAAmC,cAA2C;EACvF,MAAM,MAAM,iBAAiB,KAAK,EAAE;EAEpC,IAAI,wBAAwB;EAE5B,IAAI,iBAAiB;EACrB,KAAK,gBAAgB,WAAW;EAChC,KAAK,6BAA6B,WAAW;EAC7C,KAAK,iBAAiB,YAAY;EAClC,KAAK,qBAAqB,YAAY;EACtC,KAAK,0BAA0B,WAAW;CAC5C;CAEA,gBAAgB,aAAmC;EACjD,MAAM,EAAE,OAAO;EACf,MAAM,MAAM,iBAAiB,EAAE;EAC/B,MAAM,EAAE,kBAAkB;EAC1B,OAAO,OAAO,WAAW,CAAC,CAAC,SAAS,SAAS;GAC3C,KAAK,QAAQ,SAAS,cAAc;IAClC,MAAM,MAAM,wBAAwB,WAAW,EAAE,oBAAoB,MAAM,CAAC;IA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AC,SAAS,SAAS,QAAQ,GAAG,SAAS,KAAK,QAAQ;GAAA,OACnD;IACL,MAAM,QAAQ,SAAS,QAAQ,QAAQ;IACvC,IAAI,UAAU,IAAI,SAAS,OAAO,OAAO,CAAC;GAC5C;GACA,IAAI,qBAAqB,IAAI,WAAW,QAAQ;GAGhD,UAAU,IAAI,MAAM;EACtB;CACF;AACF;;AAGA,SAAS,cAAc,QAAgD;CACrE,OAAO,OAAO,OAAO,YAAY,MAAM,CAAC,CAAC,SAAS,CAAC,CAChD,OAAO,CAAC,CACR,QAAQ,UAAU,MAAM,SAAS,WAAW,CAAC,CAC7C,QAAQ,UAAU,CAAC,CAAC,MAAM,IAAI;AACnC;AAEA,SAAS,cAAc,QAAmD;CACxE,OAAO,aAAa,MAAM,CAAC,CACxB,OAAO,CAAC,CACR,QACE,MACC,aAAa,0BACb,aAAa,yBACb,aAAa,wBACjB;AACJ;AAEA,SAAS,eAAe,QAA4C;CAClE,OAAO,aAAa,MAAM,CAAC,CACxB,OAAO,CAAC,CACR,QACE,MACC,aAAa,wBACb,aAAa,0BACb,aAAa,+BACjB;AACJ;AAEA,SAAS,eAAe,QAAgB;CACtC,OAAO,aAAa,MAAM,CAAC,CACxB,OAAO,CAAC,CACR,QACE,MACC,aAAa,wBACb,aAAa,uBACb,aAAa,yBACb,aAAa,0BACb,aAAa,mCACb,aAAa,kBACjB;AACJ"}
|
package/build/run.cjs
CHANGED
|
@@ -51,7 +51,7 @@ function newContext(ctx) {
|
|
|
51
51
|
return newCtx;
|
|
52
52
|
}
|
|
53
53
|
function mapResultToOriginalEm(em, result) {
|
|
54
|
-
if ((0, joist_core.isEntity)(result)) return em.
|
|
54
|
+
if ((0, joist_core.isEntity)(result)) return (0, joist_core.getEmInternalApi)(em).getEntity(result.idTagged) ?? (0, joist_utils.fail)(`Could not find entity ${result.idTagged}`);
|
|
55
55
|
else if (Array.isArray(result)) return result.map((r) => mapResultToOriginalEm(em, r));
|
|
56
56
|
else if (result instanceof Map) {
|
|
57
57
|
const map = /* @__PURE__ */ new Map();
|
package/build/run.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.cjs","names":["RunPlugin","EntityManager","isEntity","fail"],"sources":["../src/run.ts"],"sourcesContent":["import { EntityManager, isEntity } from \"joist-core\";\nimport { fail } from \"joist-utils\";\n\nimport { type Context } from \"./context.ts\";\nimport { RunPlugin } from \"./RunPlugin.ts\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type ContextFn<C> = (ctx: C) => MaybePromise<C>;\n\n// Used to allow non-mutating run... calls to be run in parallel.\nlet flushPromise: Promise<any> | undefined;\nlet flushEm: EntityManager | undefined;\n\n/** Runs the `fn` in a dedicated / non-test Unit of Work . */\nexport async function run<C extends Context, T>(\n ctx: C,\n fn: (ctx: C) => MaybePromise<T>,\n contextFn: ContextFn<C> = newContext,\n): Promise<T> {\n const { em } = ctx;\n // Ensure any test data we've set up is flushed. If another invocation of `run` is already flushing, then we can just\n // wait on its promise. Otherwise, we will get flushLock errors.\n try {\n flushPromise ??= em.flush();\n flushEm ??= em;\n if (flushEm !== em) fail(\"cannot use run in parallel with multiple entity managers\");\n await flushPromise;\n } finally {\n flushPromise = undefined;\n flushEm = undefined;\n }\n const newCtx = await contextFn(ctx);\n const plugin = new RunPlugin(em);\n newCtx.em.addPlugin(plugin);\n const result = await fn(newCtx);\n // We expect `fn` (i.e. a resolver) to do its own UoW management, so don't flush.\n return mapResultToOriginalEm(em, result);\n}\n\n/** Creates a `run` with a custom `newContext` method. */\nexport function makeRun<C extends Context>(\n contextFn: ContextFn<C>,\n): <T>(ctx: C, fn: (ctx: C) => MaybePromise<T>) => Promise<T> {\n return (ctx, fn) => run(ctx, fn, contextFn);\n}\n\n/** Runs the `fn` in a dedicated / non-test Unit of Work for each value in `values */\nexport async function runEach<C extends Context, T, U>(\n ctx: C,\n valuesFn: () => U[],\n fn: (ctx: C, value: U) => MaybePromise<T>,\n contextFn: ContextFn<C> = newContext,\n): Promise<T[]> {\n const { em } = ctx;\n // Ensure any test data we've setup is flushed\n await em.flush();\n const plugin = new RunPlugin(em);\n const results = await Promise.all(\n valuesFn().map(async (value) => {\n const newCtx = await contextFn(ctx);\n newCtx.em.addPlugin(plugin);\n return fn(newCtx, value);\n }),\n );\n return mapResultToOriginalEm(em, results);\n}\n\n/** Creates a `runEach` with a custom `newContext` method. */\nexport function makeRunEach<C extends Context>(\n contextFn: ContextFn<C>,\n): <T, U>(ctx: C, valuesFn: () => U[], fn: (ctx: C, value: U) => MaybePromise<T>) => Promise<T[]> {\n return (ctx, valuesFn, fn) => runEach(ctx, valuesFn, fn, contextFn);\n}\n\n/** A default `newContext` that assumes `ctx.em` is where the `EntityManager` lives. */\nexport function newContext<C extends Context>(ctx: C): C {\n const { em } = ctx;\n const newCtx = { ...ctx };\n const newEm = new EntityManager(newCtx, em.driver);\n Object.assign(newCtx, { em: newEm });\n return newCtx;\n}\n\n/* Returns a copy of `result` with all entities replaced with their instance from the original `em`. We assume that\n * RunPlugin has been installed prior to this call, so any entities we encounter should be present in both ems. */\nfunction mapResultToOriginalEm<R>(em: EntityManager, result: R): R {\n if (isEntity(result)) {\n return (em.
|
|
1
|
+
{"version":3,"file":"run.cjs","names":["RunPlugin","EntityManager","isEntity","getEmInternalApi","fail"],"sources":["../src/run.ts"],"sourcesContent":["import { EntityManager, getEmInternalApi, isEntity } from \"joist-core\";\nimport { fail } from \"joist-utils\";\n\nimport { type Context } from \"./context.ts\";\nimport { RunPlugin } from \"./RunPlugin.ts\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type ContextFn<C> = (ctx: C) => MaybePromise<C>;\n\n// Used to allow non-mutating run... calls to be run in parallel.\nlet flushPromise: Promise<any> | undefined;\nlet flushEm: EntityManager | undefined;\n\n/** Runs the `fn` in a dedicated / non-test Unit of Work . */\nexport async function run<C extends Context, T>(\n ctx: C,\n fn: (ctx: C) => MaybePromise<T>,\n contextFn: ContextFn<C> = newContext,\n): Promise<T> {\n const { em } = ctx;\n // Ensure any test data we've set up is flushed. If another invocation of `run` is already flushing, then we can just\n // wait on its promise. Otherwise, we will get flushLock errors.\n try {\n flushPromise ??= em.flush();\n flushEm ??= em;\n if (flushEm !== em) fail(\"cannot use run in parallel with multiple entity managers\");\n await flushPromise;\n } finally {\n flushPromise = undefined;\n flushEm = undefined;\n }\n const newCtx = await contextFn(ctx);\n const plugin = new RunPlugin(em);\n newCtx.em.addPlugin(plugin);\n const result = await fn(newCtx);\n // We expect `fn` (i.e. a resolver) to do its own UoW management, so don't flush.\n return mapResultToOriginalEm(em, result);\n}\n\n/** Creates a `run` with a custom `newContext` method. */\nexport function makeRun<C extends Context>(\n contextFn: ContextFn<C>,\n): <T>(ctx: C, fn: (ctx: C) => MaybePromise<T>) => Promise<T> {\n return (ctx, fn) => run(ctx, fn, contextFn);\n}\n\n/** Runs the `fn` in a dedicated / non-test Unit of Work for each value in `values */\nexport async function runEach<C extends Context, T, U>(\n ctx: C,\n valuesFn: () => U[],\n fn: (ctx: C, value: U) => MaybePromise<T>,\n contextFn: ContextFn<C> = newContext,\n): Promise<T[]> {\n const { em } = ctx;\n // Ensure any test data we've setup is flushed\n await em.flush();\n const plugin = new RunPlugin(em);\n const results = await Promise.all(\n valuesFn().map(async (value) => {\n const newCtx = await contextFn(ctx);\n newCtx.em.addPlugin(plugin);\n return fn(newCtx, value);\n }),\n );\n return mapResultToOriginalEm(em, results);\n}\n\n/** Creates a `runEach` with a custom `newContext` method. */\nexport function makeRunEach<C extends Context>(\n contextFn: ContextFn<C>,\n): <T, U>(ctx: C, valuesFn: () => U[], fn: (ctx: C, value: U) => MaybePromise<T>) => Promise<T[]> {\n return (ctx, valuesFn, fn) => runEach(ctx, valuesFn, fn, contextFn);\n}\n\n/** A default `newContext` that assumes `ctx.em` is where the `EntityManager` lives. */\nexport function newContext<C extends Context>(ctx: C): C {\n const { em } = ctx;\n const newCtx = { ...ctx };\n const newEm = new EntityManager(newCtx, em.driver);\n Object.assign(newCtx, { em: newEm });\n return newCtx;\n}\n\n/* Returns a copy of `result` with all entities replaced with their instance from the original `em`. We assume that\n * RunPlugin has been installed prior to this call, so any entities we encounter should be present in both ems. */\nfunction mapResultToOriginalEm<R>(em: EntityManager, result: R): R {\n if (isEntity(result)) {\n return (getEmInternalApi(em).getEntity(result.idTagged) ?? fail(`Could not find entity ${result.idTagged}`)) as R;\n } else if (Array.isArray(result)) {\n return result.map((r) => mapResultToOriginalEm(em, r)) as any;\n } else if (result instanceof Map) {\n const map = new Map<any, any>();\n result\n .entries()\n .forEach(([key, value]) => map.set(mapResultToOriginalEm(em, key), mapResultToOriginalEm(em, value)));\n return map as R;\n } else if (result instanceof Set) {\n const set = new Set<any>();\n result.forEach((r) => set.add(mapResultToOriginalEm(em, r)));\n return set as R;\n } else if (typeof result === \"object\" && result?.constructor === Object) {\n const obj = {} as any;\n Object.entries(result).forEach(([key, value]: [string, any]) => (obj[key] = mapResultToOriginalEm(em, value)));\n return obj;\n } else {\n return result;\n }\n}\n"],"mappings":";;;;;;AAWA,IAAI;AACJ,IAAI;;AAGJ,eAAsB,IACpB,KACA,IACA,YAA0B,YACd;CACZ,MAAM,EAAE,OAAO;CAGf,IAAI;EACF,iBAAiB,GAAG,MAAM;EAC1B,YAAY;EACZ,IAAI,YAAY,IAAI,CAAA,GAAA,YAAA,KAAA,CAAK,0DAA0D;EACnF,MAAM;CACR,UAAU;EACR,eAAe,KAAA;EACf,UAAU,KAAA;CACZ;CACA,MAAM,SAAS,MAAM,UAAU,GAAG;CAClC,MAAM,SAAS,IAAIA,kBAAAA,UAAU,EAAE;CAC/B,OAAO,GAAG,UAAU,MAAM;CAG1B,OAAO,sBAAsB,IAAI,MAFZ,GAAG,MAAM,CAES;AACzC;;AAGA,SAAgB,QACd,WAC4D;CAC5D,QAAQ,KAAK,OAAO,IAAI,KAAK,IAAI,SAAS;AAC5C;;AAGA,eAAsB,QACpB,KACA,UACA,IACA,YAA0B,YACZ;CACd,MAAM,EAAE,O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AO;CACT,OAAO,IAAI,OAAO,WAAW,YAAY,QAAQ,gBAAgB,QAAQ;EACvE,MAAM,MAAM,CAAC;EACb,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,CAAC,KAAK,WAA2B,IAAI,OAAO,sBAAsB,IAAI,KAAK,CAAE;EAC7G,OAAO;CACT,OACE,OAAO;AAEX"}
|
package/build/run.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "./context.js";
|
|
2
2
|
import { RunPlugin } from "./RunPlugin.js";
|
|
3
|
-
import { EntityManager, isEntity } from "joist-core";
|
|
3
|
+
import { EntityManager, getEmInternalApi, isEntity } from "joist-core";
|
|
4
4
|
import { fail as fail$1 } from "joist-utils";
|
|
5
5
|
// src/run.ts
|
|
6
6
|
let flushPromise;
|
|
@@ -50,7 +50,7 @@ function newContext(ctx) {
|
|
|
50
50
|
return newCtx;
|
|
51
51
|
}
|
|
52
52
|
function mapResultToOriginalEm(em, result) {
|
|
53
|
-
if (isEntity(result)) return em.
|
|
53
|
+
if (isEntity(result)) return getEmInternalApi(em).getEntity(result.idTagged) ?? fail$1(`Could not find entity ${result.idTagged}`);
|
|
54
54
|
else if (Array.isArray(result)) return result.map((r) => mapResultToOriginalEm(em, r));
|
|
55
55
|
else if (result instanceof Map) {
|
|
56
56
|
const map = /* @__PURE__ */ new Map();
|
package/build/run.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.js","names":["fail"],"sources":["../src/run.ts"],"sourcesContent":["import { EntityManager, isEntity } from \"joist-core\";\nimport { fail } from \"joist-utils\";\n\nimport { type Context } from \"./context.ts\";\nimport { RunPlugin } from \"./RunPlugin.ts\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type ContextFn<C> = (ctx: C) => MaybePromise<C>;\n\n// Used to allow non-mutating run... calls to be run in parallel.\nlet flushPromise: Promise<any> | undefined;\nlet flushEm: EntityManager | undefined;\n\n/** Runs the `fn` in a dedicated / non-test Unit of Work . */\nexport async function run<C extends Context, T>(\n ctx: C,\n fn: (ctx: C) => MaybePromise<T>,\n contextFn: ContextFn<C> = newContext,\n): Promise<T> {\n const { em } = ctx;\n // Ensure any test data we've set up is flushed. If another invocation of `run` is already flushing, then we can just\n // wait on its promise. Otherwise, we will get flushLock errors.\n try {\n flushPromise ??= em.flush();\n flushEm ??= em;\n if (flushEm !== em) fail(\"cannot use run in parallel with multiple entity managers\");\n await flushPromise;\n } finally {\n flushPromise = undefined;\n flushEm = undefined;\n }\n const newCtx = await contextFn(ctx);\n const plugin = new RunPlugin(em);\n newCtx.em.addPlugin(plugin);\n const result = await fn(newCtx);\n // We expect `fn` (i.e. a resolver) to do its own UoW management, so don't flush.\n return mapResultToOriginalEm(em, result);\n}\n\n/** Creates a `run` with a custom `newContext` method. */\nexport function makeRun<C extends Context>(\n contextFn: ContextFn<C>,\n): <T>(ctx: C, fn: (ctx: C) => MaybePromise<T>) => Promise<T> {\n return (ctx, fn) => run(ctx, fn, contextFn);\n}\n\n/** Runs the `fn` in a dedicated / non-test Unit of Work for each value in `values */\nexport async function runEach<C extends Context, T, U>(\n ctx: C,\n valuesFn: () => U[],\n fn: (ctx: C, value: U) => MaybePromise<T>,\n contextFn: ContextFn<C> = newContext,\n): Promise<T[]> {\n const { em } = ctx;\n // Ensure any test data we've setup is flushed\n await em.flush();\n const plugin = new RunPlugin(em);\n const results = await Promise.all(\n valuesFn().map(async (value) => {\n const newCtx = await contextFn(ctx);\n newCtx.em.addPlugin(plugin);\n return fn(newCtx, value);\n }),\n );\n return mapResultToOriginalEm(em, results);\n}\n\n/** Creates a `runEach` with a custom `newContext` method. */\nexport function makeRunEach<C extends Context>(\n contextFn: ContextFn<C>,\n): <T, U>(ctx: C, valuesFn: () => U[], fn: (ctx: C, value: U) => MaybePromise<T>) => Promise<T[]> {\n return (ctx, valuesFn, fn) => runEach(ctx, valuesFn, fn, contextFn);\n}\n\n/** A default `newContext` that assumes `ctx.em` is where the `EntityManager` lives. */\nexport function newContext<C extends Context>(ctx: C): C {\n const { em } = ctx;\n const newCtx = { ...ctx };\n const newEm = new EntityManager(newCtx, em.driver);\n Object.assign(newCtx, { em: newEm });\n return newCtx;\n}\n\n/* Returns a copy of `result` with all entities replaced with their instance from the original `em`. We assume that\n * RunPlugin has been installed prior to this call, so any entities we encounter should be present in both ems. */\nfunction mapResultToOriginalEm<R>(em: EntityManager, result: R): R {\n if (isEntity(result)) {\n return (em.
|
|
1
|
+
{"version":3,"file":"run.js","names":["fail"],"sources":["../src/run.ts"],"sourcesContent":["import { EntityManager, getEmInternalApi, isEntity } from \"joist-core\";\nimport { fail } from \"joist-utils\";\n\nimport { type Context } from \"./context.ts\";\nimport { RunPlugin } from \"./RunPlugin.ts\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type ContextFn<C> = (ctx: C) => MaybePromise<C>;\n\n// Used to allow non-mutating run... calls to be run in parallel.\nlet flushPromise: Promise<any> | undefined;\nlet flushEm: EntityManager | undefined;\n\n/** Runs the `fn` in a dedicated / non-test Unit of Work . */\nexport async function run<C extends Context, T>(\n ctx: C,\n fn: (ctx: C) => MaybePromise<T>,\n contextFn: ContextFn<C> = newContext,\n): Promise<T> {\n const { em } = ctx;\n // Ensure any test data we've set up is flushed. If another invocation of `run` is already flushing, then we can just\n // wait on its promise. Otherwise, we will get flushLock errors.\n try {\n flushPromise ??= em.flush();\n flushEm ??= em;\n if (flushEm !== em) fail(\"cannot use run in parallel with multiple entity managers\");\n await flushPromise;\n } finally {\n flushPromise = undefined;\n flushEm = undefined;\n }\n const newCtx = await contextFn(ctx);\n const plugin = new RunPlugin(em);\n newCtx.em.addPlugin(plugin);\n const result = await fn(newCtx);\n // We expect `fn` (i.e. a resolver) to do its own UoW management, so don't flush.\n return mapResultToOriginalEm(em, result);\n}\n\n/** Creates a `run` with a custom `newContext` method. */\nexport function makeRun<C extends Context>(\n contextFn: ContextFn<C>,\n): <T>(ctx: C, fn: (ctx: C) => MaybePromise<T>) => Promise<T> {\n return (ctx, fn) => run(ctx, fn, contextFn);\n}\n\n/** Runs the `fn` in a dedicated / non-test Unit of Work for each value in `values */\nexport async function runEach<C extends Context, T, U>(\n ctx: C,\n valuesFn: () => U[],\n fn: (ctx: C, value: U) => MaybePromise<T>,\n contextFn: ContextFn<C> = newContext,\n): Promise<T[]> {\n const { em } = ctx;\n // Ensure any test data we've setup is flushed\n await em.flush();\n const plugin = new RunPlugin(em);\n const results = await Promise.all(\n valuesFn().map(async (value) => {\n const newCtx = await contextFn(ctx);\n newCtx.em.addPlugin(plugin);\n return fn(newCtx, value);\n }),\n );\n return mapResultToOriginalEm(em, results);\n}\n\n/** Creates a `runEach` with a custom `newContext` method. */\nexport function makeRunEach<C extends Context>(\n contextFn: ContextFn<C>,\n): <T, U>(ctx: C, valuesFn: () => U[], fn: (ctx: C, value: U) => MaybePromise<T>) => Promise<T[]> {\n return (ctx, valuesFn, fn) => runEach(ctx, valuesFn, fn, contextFn);\n}\n\n/** A default `newContext` that assumes `ctx.em` is where the `EntityManager` lives. */\nexport function newContext<C extends Context>(ctx: C): C {\n const { em } = ctx;\n const newCtx = { ...ctx };\n const newEm = new EntityManager(newCtx, em.driver);\n Object.assign(newCtx, { em: newEm });\n return newCtx;\n}\n\n/* Returns a copy of `result` with all entities replaced with their instance from the original `em`. We assume that\n * RunPlugin has been installed prior to this call, so any entities we encounter should be present in both ems. */\nfunction mapResultToOriginalEm<R>(em: EntityManager, result: R): R {\n if (isEntity(result)) {\n return (getEmInternalApi(em).getEntity(result.idTagged) ?? fail(`Could not find entity ${result.idTagged}`)) as R;\n } else if (Array.isArray(result)) {\n return result.map((r) => mapResultToOriginalEm(em, r)) as any;\n } else if (result instanceof Map) {\n const map = new Map<any, any>();\n result\n .entries()\n .forEach(([key, value]) => map.set(mapResultToOriginalEm(em, key), mapResultToOriginalEm(em, value)));\n return map as R;\n } else if (result instanceof Set) {\n const set = new Set<any>();\n result.forEach((r) => set.add(mapResultToOriginalEm(em, r)));\n return set as R;\n } else if (typeof result === \"object\" && result?.constructor === Object) {\n const obj = {} as any;\n Object.entries(result).forEach(([key, value]: [string, any]) => (obj[key] = mapResultToOriginalEm(em, value)));\n return obj;\n } else {\n return result;\n }\n}\n"],"mappings":";;;;;AAWA,IAAI;AACJ,IAAI;;AAGJ,eAAsB,IACpB,KACA,IACA,YAA0B,YACd;CACZ,MAAM,EAAE,OAAO;CAGf,IAAI;EACF,iBAAiB,GAAG,MAAM;EAC1B,YAAY;EACZ,IAAI,YAAY,IAAI,OAAK,0DAA0D;EACnF,MAAM;CACR,UAAU;EACR,eAAe,KAAA;EACf,UAAU,KAAA;CACZ;CACA,MAAM,SAAS,MAAM,UAAU,GAAG;CAClC,MAAM,SAAS,IAAI,UAAU,EAAE;CAC/B,OAAO,GAAG,UAAU,MAAM;CAG1B,OAAO,sBAAsB,IAAI,MAFZ,GAAG,MAAM,CAES;AACzC;;AAGA,SAAgB,QACd,WAC4D;CAC5D,QAAQ,KAAK,OAAO,IAAI,KAAK,IAAI,SAAS;AAC5C;;AAGA,eAAsB,QACpB,KACA,UACA,IACA,YAA0B,YACZ;CACd,MAAM,EAAE,OAAO;CAEf,MAAM,GAAG,MAAM;CACf,MAAM,SAAS,IAAI,UAAU,EAAE;CAQ/B,OAAO,sBAAsB,IAAI,MAPX,QAAQ,IAC5B,SAAS,CAAC,CAAC,IAAI,OAAO,UAAU;EAC9B,MAAM,SAAS,MAAM,UAAU,GAAG;EAClC,OAAO,GAAG,UAAU,MAAM;EAC1B,OAAO,GAAG,QAAQ,KAAK;CACzB,CAAC,CACH,CACwC;AAC1C;;AAGA,SAAgB,YACd,WACgG;CAChG,QAAQ,KAAK,UAAU,OAAO,QAAQ,KAAK,UAAU,IAAI,SAAS;AACpE;;AAGA,SAAgB,WAA8B,KAAW;CACvD,MAAM,EAAE,OAAO;CACf,MAAM,SAAS,EAAE,GAAG,IAAI;CACxB,MAAM,QAAQ,IAAI,cAAc,QAAQ,GAAG,MAAM;CACjD,OAAO,OAAO,QAAQ,EAAE,IAAI,MAAM,CAAC;CACnC,OAAO;AACT;AAIA,SAAS,sBAAyB,IAAmB,QAAc;CACjE,IAAI,SAAS,MAAM,GACjB,OAAQ,iBAAiB,EAAE,CAAC,CAAC,UAAU,OAAO,QAAQ,KAAKA,OAAK,yBAAyB,OAAO,UAAU;MACrG,IAAI,MAAM,QAAQ,MAAM,GAC7B,OAAO,OAAO,KAAK,MAAM,sBAAsB,IAAI,CAAC,CAAC;MAChD,IAAI,kBAAkB,KAAK;EAChC,MAAM,sBAAM,IAAI,IAAc;EAC9B,OACG,QAAQ,CAAC,CACT,SAAS,CAAC,KAAK,WAAW,IAAI,IAAI,sBAAsB,IAAI,GAAG,GAAG,sBAAsB,IAAI,KAAK,CAAC,CAAC;EACtG,OAAO;CACT,OAAO,IAAI,kBAAkB,KAAK;EAChC,MAAM,sBAAM,IAAI,IAAS;EACzB,OAAO,SAAS,MAAM,IAAI,IAAI,sBAAsB,IAAI,CAAC,CAAC,CAAC;EAC3D,OAAO;CACT,OAAO,IAAI,OAAO,WAAW,YAAY,QAAQ,gBAAgB,QAAQ;EACvE,MAAM,MAAM,CAAC;EACb,OAAO,QAAQ,MAAM,CAAC,CAAC,SAAS,CAAC,KAAK,WAA2B,IAAI,OAAO,sBAAsB,IAAI,KAAK,CAAE;EAC7G,OAAO;CACT,OACE,OAAO;AAEX"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "joist-test-utils",
|
|
3
|
-
"version": "2.5.0-next.
|
|
3
|
+
"version": "2.5.0-next.17",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "build/index.cjs",
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
"dotenv": "^18.0.9"
|
|
35
35
|
},
|
|
36
36
|
"peerDependencies": {
|
|
37
|
-
"joist-core": "2.5.0-next.
|
|
38
|
-
"joist-utils": "2.5.0-next.
|
|
37
|
+
"joist-core": "2.5.0-next.17",
|
|
38
|
+
"joist-utils": "2.5.0-next.17",
|
|
39
39
|
"pg": "^8.23.0"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|