joist-core 2.5.0-next.11 → 2.5.0-next.12
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/InstanceData.cjs +7 -1
- package/build/InstanceData.cjs.map +1 -1
- package/build/InstanceData.d.cts +7 -1
- package/build/InstanceData.d.cts.map +1 -1
- package/build/InstanceData.d.mts +7 -1
- package/build/InstanceData.d.mts.map +1 -1
- package/build/InstanceData.js +7 -1
- package/build/InstanceData.js.map +1 -1
- package/build/PluginManager.cjs +10 -3
- package/build/PluginManager.cjs.map +1 -1
- package/build/PluginManager.d.cts +8 -3
- package/build/PluginManager.d.cts.map +1 -1
- package/build/PluginManager.d.mts +8 -3
- package/build/PluginManager.d.mts.map +1 -1
- package/build/PluginManager.js +10 -3
- package/build/PluginManager.js.map +1 -1
- package/build/fields.cjs +12 -6
- package/build/fields.cjs.map +1 -1
- package/build/fields.d.cts +3 -2
- package/build/fields.d.cts.map +1 -1
- package/build/fields.d.mts +3 -2
- package/build/fields.d.mts.map +1 -1
- package/build/fields.js +12 -6
- package/build/fields.js.map +1 -1
- package/package.json +2 -2
package/build/InstanceData.cjs
CHANGED
|
@@ -21,7 +21,13 @@ var InstanceData = class {
|
|
|
21
21
|
rowIndex = 0;
|
|
22
22
|
/** The domain-value of fields, lazily converted (if needed) on read from the database columns. */
|
|
23
23
|
data;
|
|
24
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* Tracks which fields have been passed to plugins, so we can skip plugins on subsequent field accesses.
|
|
26
|
+
*
|
|
27
|
+
* Note that we also set the bit temporarily during plugin evaluation to keep plugins internally
|
|
28
|
+
* re-accessing the field from recursing into themselves. We only keep a field marked as "plugin read"
|
|
29
|
+
* after all plugins return "always" (or void), i.e. plugins can vote "allow" to be invoked again.
|
|
30
|
+
*/
|
|
25
31
|
pluginReadFields = 0;
|
|
26
32
|
pluginReadFieldsExtra = void 0;
|
|
27
33
|
/** Number/untagged ID conversions are cached once; assigned entity IDs never change. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InstanceData.cjs","names":["emptyRowData","hasAnyKey"],"sources":["../src/InstanceData.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport { type RowData, emptyRowData } from \"src/RowData.ts\";\nimport { hasAnyKey } from \"src/utils.ts\";\n\n/** The `#orm` metadata field we track on each instance. */\nexport class InstanceData {\n /** The entity this instance data belongs to. */\n readonly entity: Entity;\n /** All entities must be associated to an `EntityManager` to handle lazy loading/etc. */\n readonly em: EntityManager;\n /** A pointer to our entity type's metadata. */\n readonly metadata: EntityMetadata;\n /** A bag for our lazy-initialized relations, allocated on first relation access. */\n relations: Record<any, any> | undefined = undefined;\n /** The as-loaded database row, i.e. our `rowIndex`-th row within our query's `RowData` result. */\n rowData: RowData = emptyRowData;\n /** Our row's index within `rowData`; see {@link RowData}. */\n rowIndex: number = 0;\n /** The domain-value of fields, lazily converted (if needed) on read from the database columns. */\n data: Record<string, any>;\n /** Tracks which fields have triggered plugin callbacks, including internal reads that do not enroll read protection. */\n pluginReadFields = 0;\n pluginReadFieldsExtra: number[] | undefined = undefined;\n /** Number/untagged ID conversions are cached once; assigned entity IDs never change. */\n idCache: string | number | undefined = undefined;\n /** A bag to keep the original values, allocated on first mutation (most entities are never mutated). */\n #originalData: Record<any, any> | undefined = undefined;\n /** Reference values that were set during this unit of work, allocated on first m2o/poly change. */\n #referenceHistory: Record<string, any[]> | undefined = undefined;\n /** A bag to keep the flushed-to-database values, only for AsyncReactiveField reactivity. */\n flushedData: Record<any, any> | undefined;\n /** Packs the new/deleted `Operation`s + isTouched into one slot; see the accessors below. */\n #flags: number = 0;\n /** The `a#1`, `a#2` index if we're an em.create-d entity. We never unset this, to keep ids stable across flushes. */\n createId: string | undefined;\n /** The zero-based order this entity was registered with its EntityManager. */\n entityIndex: number = -1;\n\n /** Whether our entity is new or not. */\n get #new(): Operation | undefined {\n const value = this.#flags & 0b11;\n return value === 0 ? undefined : value;\n }\n\n set #new(op: Operation | undefined) {\n this.#flags = (this.#flags & ~0b11) | (op ?? 0);\n }\n\n /**\n * Whether our entity has been deleted or not.\n *\n * - `pending` means we've been marked for deletion via `em.delete` but not issued a `DELETE`\n * - `flushed` means we've flushed a `DELETE` but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `deleted` means we've been flushed and `em.flush` has completed\n */\n get #deleted(): Operation | undefined {\n const value = (this.#flags >> 2) & 0b11;\n return value === 0 ? undefined : value;\n }\n\n set #deleted(op: Operation | undefined) {\n this.#flags = (this.#flags & ~0b1100) | ((op ?? 0) << 2);\n }\n\n /** Whether our entity should flush regardless of any other changes. */\n get isTouched(): boolean {\n return (this.#flags & 0b10000) !== 0;\n }\n\n set isTouched(value: boolean) {\n this.#flags = value ? this.#flags | 0b10000 : this.#flags & ~0b10000;\n }\n\n /** Creates the `#orm` field. */\n constructor(em: EntityManager, entity: Entity, metadata: EntityMetadata, isNew: boolean) {\n this.entity = entity;\n this.em = em;\n this.metadata = metadata;\n if (isNew) {\n this.#new = Operation.Pending;\n this.data = {};\n this.flushedData = undefined;\n if (em) this.markMaybePending();\n } else {\n this.#new = undefined;\n this.data = {};\n this.flushedData = undefined;\n }\n }\n\n /**\n * Returns the as-loaded value of `columnName`, i.e. `getColumn(\"rank\")`.\n *\n * This saves callers from knowing that `rowData`/`rowIndex` are a pair, but note it is\n * a snapshot of the query that loaded us, and specifically:\n *\n * - The value is driver-level, i.e. numeric enum ids, untagged foreign keys, and temporals\n * as strings; use `getField` if you want the domain value, and\n * - The value is not updated by `em.flush`, so after a flush it is the pre-flush value, and\n * - New entities have no row, so every column is `undefined`.\n */\n getColumn(columnName: string): any {\n return this.rowData.get(this.rowIndex, columnName);\n }\n\n /** If `em.flush` has detected a dirty RQF, reset our internal dirty state, w/o reseting our external-dirty state. */\n resetForRqfLoop() {\n this.flushedData = {};\n if (this.#new === Operation.Pending) this.#new = Operation.Flushed;\n if (this.#deleted === Operation.Pending) this.#deleted = Operation.Flushed;\n }\n\n resetAfterFlushed() {\n this.#originalData = undefined;\n this.#referenceHistory = undefined;\n this.flushedData = undefined;\n this.isTouched = false;\n if (this.#new === Operation.Pending || this.#new === Operation.Flushed) {\n this.#new = Operation.Complete;\n }\n if (this.#deleted === Operation.Pending || this.#deleted === Operation.Flushed) {\n this.#deleted = Operation.Complete;\n }\n this.unmarkMaybePending();\n }\n\n /** Our public-facing `isNewEntity`. */\n get isNewEntity(): boolean {\n return this.#new !== undefined && this.#new !== Operation.Complete;\n }\n\n /** Our public-facing `isDeletedEntity`. */\n get isDeletedEntity(): boolean {\n return this.#deleted !== undefined;\n }\n\n /** The original values of mutated fields; a shared empty object until the entity is actually mutated. */\n get originalData(): Record<any, any> {\n return this.#originalData ?? emptyObject;\n }\n\n /** Our public-facing `isDirtyEntity`. */\n get isDirtyEntity(): boolean {\n return hasAnyKey(this.#originalData);\n }\n\n /** This is our internal \"is pending flush\", which is aware of RQF micro-flush loops. */\n get pendingOperation(): \"insert\" | \"update\" | \"delete\" | \"none\" | \"created-then-deleted\" {\n if (this.#deleted !== undefined) {\n // Mark entities that were created and them immediately `em.delete`-d; granted this is\n // probably rare, but we shouldn't run hooks or have the driver try and delete these.\n // Note that we return them, instead of skipping entirely, so that fixupCreatedThenDeleted\n // can later be called.\n return this.#deleted === Operation.Pending && this.#new === Operation.Pending\n ? \"created-then-deleted\"\n : this.#deleted === Operation.Pending\n ? \"delete\"\n : \"none\";\n } else if (this.#new === Operation.Pending) {\n // Per ^, if `#new === flushed`, we fall through to check if micro-flush UPDATEs are required\n return \"insert\";\n } else if (this.flushedData) {\n return hasAnyKey(this.flushedData) ? \"update\" : \"none\";\n } else {\n return this.isTouched || hasAnyKey(this.#originalData) ? \"update\" : \"none\";\n }\n }\n\n get changedFields(): string[] {\n return Object.keys(this.changedData);\n }\n\n /** The changed-fields bag (flushedData during RQF loops, else originalData) without allocating a keys array. */\n get changedData(): Record<any, any> {\n return this.flushedData ?? this.#originalData ?? emptyObject;\n }\n\n /** Called when an `em.load` tries to find the entity and it's just gone from the db. */\n markDeletedBecauseNotFound(): void {\n this.#deleted = Operation.Complete;\n }\n\n /** Called by `em.delete`, returns true if this is new information. */\n markDeleted(): boolean {\n if (this.#deleted === undefined) {\n // Let any OneToManyCollection/ReactiveField/ReactiveReference.get caches know that they should recalc\n // (i.e. their filterDeleted logic) by asserting the `deleteBook.author` field is changing.\n for (const field of Object.values(this.metadata.allFields)) {\n // We only do reference/collection fields and skip the primitives, b/c we assume something like\n // `{ books: \"title\" }` doesn't need `resetIsLoaded(..., \"title\")` b/c the same hint will also\n // be watching \"did books change\", and so get reset that way.\n if (field.kind === \"m2o\" || field.kind === \"poly\" || field.kind === \"m2m\" || field.kind === \"m2mEnum\") {\n getEmInternalApi(this.em).isLoadedCache.resetIsLoaded(this.entity, field.fieldName);\n } else if (field.kind === \"primitive\" || field.kind === \"enum\" || field.kind === \"primaryKey\") {\n // Any reactable watching these fields will also be watching reference/collection\n } else if (field.kind === \"o2m\" || field.kind === \"o2o\") {\n // Any reactable watching these actually gets triggered by the primary m2o/poly side changing\n } else if (field.kind === \"lo2m\") {\n // Doesn't support reactivity\n } else {\n throw new Error(`Unhandled field kind ${field}`);\n }\n }\n this.#deleted = Operation.Pending;\n this.markMaybePending();\n return true;\n }\n return false;\n }\n\n fixupCreatedThenDeleted(): void {\n // Ideally we could do this via `resetAfterFlushed`?\n this.#deleted = Operation.Complete;\n this.unmarkMaybePending();\n }\n\n /** Marks this entity as needing a flush even if no fields changed. */\n markTouched(): void {\n this.isTouched = true;\n this.markMaybePending();\n }\n\n /** Marks a field as dirty with its pre-mutation value. */\n markFieldDirty(fieldName: string, value: any): void {\n (this.#originalData ??= {})[fieldName] = value;\n this.markMaybePending();\n }\n\n /** Marks a reverted field as clean again. */\n markFieldClean(fieldName: string): void {\n if (this.#originalData) delete this.#originalData[fieldName];\n this.markMaybePending();\n }\n\n /** Marks this entity as a possible flush candidate. */\n markMaybePending(): void {\n getEmInternalApi(this.em).markMaybePending(this.entity);\n }\n\n /** Removes this entity from the possible flush candidate set. */\n private unmarkMaybePending(): void {\n getEmInternalApi(this.em).unmarkMaybePending(this.entity);\n }\n\n /** Remembers a reference value that may need to be reverse-walked later. */\n rememberReferenceValue(fieldName: string, value: any): void {\n if (value === undefined) return;\n const values = ((this.#referenceHistory ??= {})[fieldName] ??= []);\n if (!values.includes(value)) values.push(value);\n }\n\n /** Returns reference values that may need to be reverse-walked later. */\n getReferenceHistory(fieldName: string): readonly any[] {\n return this.#referenceHistory?.[fieldName] ?? emptyArray;\n }\n\n get isDeletedAndFlushed(): boolean {\n return this.#deleted === Operation.Complete;\n }\n\n /**\n * Returns true if the entity is new or was new in this EM.\n *\n * This is primarily used for lazy-initializing relations, i.e. if:\n *\n * - A new `Author` is created\n * - We `em.flush` the author to the database\n * - Then `a1.books` is accessed for the first time\n *\n * We can have a high-confidence that `a1` has no books, because we just\n * created it, so we can set the OneToManyCollection to loaded.\n */\n get isOrWasNew(): boolean {\n // #new will be left as `complete`\n return this.#new !== undefined;\n }\n}\n\n/** An enum to track our insert/delete state progression. */\nenum Operation {\n Pending = 1,\n Flushed = 2,\n Complete = 3,\n}\n\n/** A shared frozen bag for un-mutated entities; strict mode makes accidental writes throw. */\nconst emptyObject: Record<any, any> = Object.freeze({});\n\n/** A shared frozen array for fields with no remembered reference values. */\nconst emptyArray: readonly any[] = Object.freeze([]);\n"],"mappings":";;;;;;;;AAOA,IAAa,eAAb,MAA0B;;CAExB;;CAEA;;CAEA;;CAEA,YAA0C,KAAA;;CAE1C,UAAmBA,gBAAAA;;CAEnB,WAAmB;;CAEnB;;CAEA,mBAAmB;CACnB,wBAA8C,KAAA;;CAE9C,UAAuC,KAAA;;CAEvC,gBAA8C,KAAA;;CAE9C,oBAAuD,KAAA;;CAEvD;;CAEA,SAAiB;;CAEjB;;CAEA,cA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AAI,MAAM,wBAAwB,OAAO;GAGnD,KAAK,WAAA;GACL,KAAK,iBAAiB;GACtB,OAAO;EACT;EACA,OAAO;CACT;CAEA,0BAAgC;EAE9B,KAAK,WAAA;EACL,KAAK,mBAAmB;CAC1B;;CAGA,cAAoB;EAClB,KAAK,YAAY;EACjB,KAAK,iBAAiB;CACxB;;CAGA,eAAe,WAAmB,OAAkB;EAClD,CAAC,KAAK,kBAAkB,CAAC,EAAA,CAAG,aAAa;EACzC,KAAK,iBAAiB;CACxB;;CAGA,eAAe,WAAyB;EACtC,IAAI,KAAK,eAAe,OAAO,KAAK,cAAc;EAClD,KAAK,iBAAiB;CACxB;;CAGA,mBAAyB;EACvB,sBAAA,iBAAiB,KAAK,EAAE,CAAC,CAAC,iBAAiB,KAAK,MAAM;CACxD;;CAGA,qBAAmC;EACjC,sBAAA,iBAAiB,KAAK,EAAE,CAAC,CAAC,mBAAmB,KAAK,MAAM;CAC1D;;CAGA,uBAAuB,WAAmB,OAAkB;EAC1D,IAAI,UAAU,KAAA,GAAW;EACzB,MAAM,SAAU,CAAC,KAAK,sBAAsB,CAAC,EAAA,CAAG,eAAe,CAAC;EAChE,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO,KAAK,KAAK;CAChD;;CAGA,oBAAoB,WAAmC;EACrD,OAAO,KAAK,oBAAoB,cAAc;CAChD;CAEA,IAAI,sBAA+B;EACjC,OAAO,KAAK,aAAA;CACd;;;;;;;;;;;;;CAcA,IAAI,aAAsB;EAExB,OAAO,KAAK,SAAS,KAAA;CACvB;AACF;;AAUA,MAAM,cAAgC,OAAO,OAAO,CAAC,CAAC;;AAGtD,MAAM,aAA6B,OAAO,OAAO,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"InstanceData.cjs","names":["emptyRowData","hasAnyKey"],"sources":["../src/InstanceData.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport { type RowData, emptyRowData } from \"src/RowData.ts\";\nimport { hasAnyKey } from \"src/utils.ts\";\n\n/** The `#orm` metadata field we track on each instance. */\nexport class InstanceData {\n /** The entity this instance data belongs to. */\n readonly entity: Entity;\n /** All entities must be associated to an `EntityManager` to handle lazy loading/etc. */\n readonly em: EntityManager;\n /** A pointer to our entity type's metadata. */\n readonly metadata: EntityMetadata;\n /** A bag for our lazy-initialized relations, allocated on first relation access. */\n relations: Record<any, any> | undefined = undefined;\n /** The as-loaded database row, i.e. our `rowIndex`-th row within our query's `RowData` result. */\n rowData: RowData = emptyRowData;\n /** Our row's index within `rowData`; see {@link RowData}. */\n rowIndex: number = 0;\n /** The domain-value of fields, lazily converted (if needed) on read from the database columns. */\n data: Record<string, any>;\n /**\n * Tracks which fields have been passed to plugins, so we can skip plugins on subsequent field accesses.\n *\n * Note that we also set the bit temporarily during plugin evaluation to keep plugins internally\n * re-accessing the field from recursing into themselves. We only keep a field marked as \"plugin read\"\n * after all plugins return \"always\" (or void), i.e. plugins can vote \"allow\" to be invoked again.\n */\n pluginReadFields = 0;\n pluginReadFieldsExtra: number[] | undefined = undefined;\n /** Number/untagged ID conversions are cached once; assigned entity IDs never change. */\n idCache: string | number | undefined = undefined;\n /** A bag to keep the original values, allocated on first mutation (most entities are never mutated). */\n #originalData: Record<any, any> | undefined = undefined;\n /** Reference values that were set during this unit of work, allocated on first m2o/poly change. */\n #referenceHistory: Record<string, any[]> | undefined = undefined;\n /** A bag to keep the flushed-to-database values, only for AsyncReactiveField reactivity. */\n flushedData: Record<any, any> | undefined;\n /** Packs the new/deleted `Operation`s + isTouched into one slot; see the accessors below. */\n #flags: number = 0;\n /** The `a#1`, `a#2` index if we're an em.create-d entity. We never unset this, to keep ids stable across flushes. */\n createId: string | undefined;\n /** The zero-based order this entity was registered with its EntityManager. */\n entityIndex: number = -1;\n\n /** Whether our entity is new or not. */\n get #new(): Operation | undefined {\n const value = this.#flags & 0b11;\n return value === 0 ? undefined : value;\n }\n\n set #new(op: Operation | undefined) {\n this.#flags = (this.#flags & ~0b11) | (op ?? 0);\n }\n\n /**\n * Whether our entity has been deleted or not.\n *\n * - `pending` means we've been marked for deletion via `em.delete` but not issued a `DELETE`\n * - `flushed` means we've flushed a `DELETE` but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `deleted` means we've been flushed and `em.flush` has completed\n */\n get #deleted(): Operation | undefined {\n const value = (this.#flags >> 2) & 0b11;\n return value === 0 ? undefined : value;\n }\n\n set #deleted(op: Operation | undefined) {\n this.#flags = (this.#flags & ~0b1100) | ((op ?? 0) << 2);\n }\n\n /** Whether our entity should flush regardless of any other changes. */\n get isTouched(): boolean {\n return (this.#flags & 0b10000) !== 0;\n }\n\n set isTouched(value: boolean) {\n this.#flags = value ? this.#flags | 0b10000 : this.#flags & ~0b10000;\n }\n\n /** Creates the `#orm` field. */\n constructor(em: EntityManager, entity: Entity, metadata: EntityMetadata, isNew: boolean) {\n this.entity = entity;\n this.em = em;\n this.metadata = metadata;\n if (isNew) {\n this.#new = Operation.Pending;\n this.data = {};\n this.flushedData = undefined;\n if (em) this.markMaybePending();\n } else {\n this.#new = undefined;\n this.data = {};\n this.flushedData = undefined;\n }\n }\n\n /**\n * Returns the as-loaded value of `columnName`, i.e. `getColumn(\"rank\")`.\n *\n * This saves callers from knowing that `rowData`/`rowIndex` are a pair, but note it is\n * a snapshot of the query that loaded us, and specifically:\n *\n * - The value is driver-level, i.e. numeric enum ids, untagged foreign keys, and temporals\n * as strings; use `getField` if you want the domain value, and\n * - The value is not updated by `em.flush`, so after a flush it is the pre-flush value, and\n * - New entities have no row, so every column is `undefined`.\n */\n getColumn(columnName: string): any {\n return this.rowData.get(this.rowIndex, columnName);\n }\n\n /** If `em.flush` has detected a dirty RQF, reset our internal dirty state, w/o reseting our external-dirty state. */\n resetForRqfLoop() {\n this.flushedData = {};\n if (this.#new === Operation.Pending) this.#new = Operation.Flushed;\n if (this.#deleted === Operation.Pending) this.#deleted = Operation.Flushed;\n }\n\n resetAfterFlushed() {\n this.#originalData = undefined;\n this.#referenceHistory = undefined;\n this.flushedData = undefined;\n this.isTouched = false;\n if (this.#new === Operation.Pending || this.#new === Operation.Flushed) {\n this.#new = Operation.Complete;\n }\n if (this.#deleted === Operation.Pending || this.#deleted === Operation.Flushed) {\n this.#deleted = Operation.Complete;\n }\n this.unmarkMaybePending();\n }\n\n /** Our public-facing `isNewEntity`. */\n get isNewEntity(): boolean {\n return this.#new !== undefined && this.#new !== Operation.Complete;\n }\n\n /** Our public-facing `isDeletedEntity`. */\n get isDeletedEntity(): boolean {\n return this.#deleted !== undefined;\n }\n\n /** The original values of mutated fields; a shared empty object until the entity is actually mutated. */\n get originalData(): Record<any, any> {\n return this.#originalData ?? emptyObject;\n }\n\n /** Our public-facing `isDirtyEntity`. */\n get isDirtyEntity(): boolean {\n return hasAnyKey(this.#originalData);\n }\n\n /** This is our internal \"is pending flush\", which is aware of RQF micro-flush loops. */\n get pendingOperation(): \"insert\" | \"update\" | \"delete\" | \"none\" | \"created-then-deleted\" {\n if (this.#deleted !== undefined) {\n // Mark entities that were created and them immediately `em.delete`-d; granted this is\n // probably rare, but we shouldn't run hooks or have the driver try and delete these.\n // Note that we return them, instead of skipping entirely, so that fixupCreatedThenDeleted\n // can later be called.\n return this.#deleted === Operation.Pending && this.#new === Operation.Pending\n ? \"created-then-deleted\"\n : this.#deleted === Operation.Pending\n ? \"delete\"\n : \"none\";\n } else if (this.#new === Operation.Pending) {\n // Per ^, if `#new === flushed`, we fall through to check if micro-flush UPDATEs are required\n return \"insert\";\n } else if (this.flushedData) {\n return hasAnyKey(this.flushedData) ? \"update\" : \"none\";\n } else {\n return this.isTouched || hasAnyKey(this.#originalData) ? \"update\" : \"none\";\n }\n }\n\n get changedFields(): string[] {\n return Object.keys(this.changedData);\n }\n\n /** The changed-fields bag (flushedData during RQF loops, else originalData) without allocating a keys array. */\n get changedData(): Record<any, any> {\n return this.flushedData ?? this.#originalData ?? emptyObject;\n }\n\n /** Called when an `em.load` tries to find the entity and it's just gone from the db. */\n markDeletedBecauseNotFound(): void {\n this.#deleted = Operation.Complete;\n }\n\n /** Called by `em.delete`, returns true if this is new information. */\n markDeleted(): boolean {\n if (this.#deleted === undefined) {\n // Let any OneToManyCollection/ReactiveField/ReactiveReference.get caches know that they should recalc\n // (i.e. their filterDeleted logic) by asserting the `deleteBook.author` field is changing.\n for (const field of Object.values(this.metadata.allFields)) {\n // We only do reference/collection fields and skip the primitives, b/c we assume something like\n // `{ books: \"title\" }` doesn't need `resetIsLoaded(..., \"title\")` b/c the same hint will also\n // be watching \"did books change\", and so get reset that way.\n if (field.kind === \"m2o\" || field.kind === \"poly\" || field.kind === \"m2m\" || field.kind === \"m2mEnum\") {\n getEmInternalApi(this.em).isLoadedCache.resetIsLoaded(this.entity, field.fieldName);\n } else if (field.kind === \"primitive\" || field.kind === \"enum\" || field.kind === \"primaryKey\") {\n // Any reactable watching these fields will also be watching reference/collection\n } else if (field.kind === \"o2m\" || field.kind === \"o2o\") {\n // Any reactable watching these actually gets triggered by the primary m2o/poly side changing\n } else if (field.kind === \"lo2m\") {\n // Doesn't support reactivity\n } else {\n throw new Error(`Unhandled field kind ${field}`);\n }\n }\n this.#deleted = Operation.Pending;\n this.markMaybePending();\n return true;\n }\n return false;\n }\n\n fixupCreatedThenDeleted(): void {\n // Ideally we could do this via `resetAfterFlushed`?\n this.#deleted = Operation.Complete;\n this.unmarkMaybePending();\n }\n\n /** Marks this entity as needing a flush even if no fields changed. */\n markTouched(): void {\n this.isTouched = true;\n this.markMaybePending();\n }\n\n /** Marks a field as dirty with its pre-mutation value. */\n markFieldDirty(fieldName: string, value: any): void {\n (this.#originalData ??= {})[fieldName] = value;\n this.markMaybePending();\n }\n\n /** Marks a reverted field as clean again. */\n markFieldClean(fieldName: string): void {\n if (this.#originalData) delete this.#originalData[fieldName];\n this.markMaybePending();\n }\n\n /** Marks this entity as a possible flush candidate. */\n markMaybePending(): void {\n getEmInternalApi(this.em).markMaybePending(this.entity);\n }\n\n /** Removes this entity from the possible flush candidate set. */\n private unmarkMaybePending(): void {\n getEmInternalApi(this.em).unmarkMaybePending(this.entity);\n }\n\n /** Remembers a reference value that may need to be reverse-walked later. */\n rememberReferenceValue(fieldName: string, value: any): void {\n if (value === undefined) return;\n const values = ((this.#referenceHistory ??= {})[fieldName] ??= []);\n if (!values.includes(value)) values.push(value);\n }\n\n /** Returns reference values that may need to be reverse-walked later. */\n getReferenceHistory(fieldName: string): readonly any[] {\n return this.#referenceHistory?.[fieldName] ?? emptyArray;\n }\n\n get isDeletedAndFlushed(): boolean {\n return this.#deleted === Operation.Complete;\n }\n\n /**\n * Returns true if the entity is new or was new in this EM.\n *\n * This is primarily used for lazy-initializing relations, i.e. if:\n *\n * - A new `Author` is created\n * - We `em.flush` the author to the database\n * - Then `a1.books` is accessed for the first time\n *\n * We can have a high-confidence that `a1` has no books, because we just\n * created it, so we can set the OneToManyCollection to loaded.\n */\n get isOrWasNew(): boolean {\n // #new will be left as `complete`\n return this.#new !== undefined;\n }\n}\n\n/** An enum to track our insert/delete state progression. */\nenum Operation {\n Pending = 1,\n Flushed = 2,\n Complete = 3,\n}\n\n/** A shared frozen bag for un-mutated entities; strict mode makes accidental writes throw. */\nconst emptyObject: Record<any, any> = Object.freeze({});\n\n/** A shared frozen array for fields with no remembered reference values. */\nconst emptyArray: readonly any[] = Object.freeze([]);\n"],"mappings":";;;;;;;;AAOA,IAAa,eAAb,MAA0B;;CAExB;;CAEA;;CAEA;;CAEA,YAA0C,KAAA;;CAE1C,UAAmBA,gBAAAA;;CAEnB,WAAmB;;CAEnB;;;;;;;;CAQA,mBAAmB;CACnB,wBAA8C,KAAA;;CAE9C,UAAuC,KAAA;;CAEvC,gBAA8C,KAAA;;CAE9C,oBAAuD,KAAA;;CAEvD;;CAEA,SAAiB;;CAEjB;;CAEA,cAAsB;;CAGtB,IAAI,OAA8B;EAChC,MAAM,QAAQ,KAAK,S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K,iBAAiB;GACtB,OAAO;EACT;EACA,OAAO;CACT;CAEA,0BAAgC;EAE9B,KAAK,WAAA;EACL,KAAK,mBAAmB;CAC1B;;CAGA,cAAoB;EAClB,KAAK,YAAY;EACjB,KAAK,iBAAiB;CACxB;;CAGA,eAAe,WAAmB,OAAkB;EAClD,CAAC,KAAK,kBAAkB,CAAC,EAAA,CAAG,aAAa;EACzC,KAAK,iBAAiB;CACxB;;CAGA,eAAe,WAAyB;EACtC,IAAI,KAAK,eAAe,OAAO,KAAK,cAAc;EAClD,KAAK,iBAAiB;CACxB;;CAGA,mBAAyB;EACvB,sBAAA,iBAAiB,KAAK,EAAE,CAAC,CAAC,iBAAiB,KAAK,MAAM;CACxD;;CAGA,qBAAmC;EACjC,sBAAA,iBAAiB,KAAK,EAAE,CAAC,CAAC,mBAAmB,KAAK,MAAM;CAC1D;;CAGA,uBAAuB,WAAmB,OAAkB;EAC1D,IAAI,UAAU,KAAA,GAAW;EACzB,MAAM,SAAU,CAAC,KAAK,sBAAsB,CAAC,EAAA,CAAG,eAAe,CAAC;EAChE,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO,KAAK,KAAK;CAChD;;CAGA,oBAAoB,WAAmC;EACrD,OAAO,KAAK,oBAAoB,cAAc;CAChD;CAEA,IAAI,sBAA+B;EACjC,OAAO,KAAK,aAAA;CACd;;;;;;;;;;;;;CAcA,IAAI,aAAsB;EAExB,OAAO,KAAK,SAAS,KAAA;CACvB;AACF;;AAUA,MAAM,cAAgC,OAAO,OAAO,CAAC,CAAC;;AAGtD,MAAM,aAA6B,OAAO,OAAO,CAAC,CAAC"}
|
package/build/InstanceData.d.cts
CHANGED
|
@@ -19,7 +19,13 @@ export declare class InstanceData {
|
|
|
19
19
|
rowIndex: number;
|
|
20
20
|
/** The domain-value of fields, lazily converted (if needed) on read from the database columns. */
|
|
21
21
|
data: Record<string, any>;
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Tracks which fields have been passed to plugins, so we can skip plugins on subsequent field accesses.
|
|
24
|
+
*
|
|
25
|
+
* Note that we also set the bit temporarily during plugin evaluation to keep plugins internally
|
|
26
|
+
* re-accessing the field from recursing into themselves. We only keep a field marked as "plugin read"
|
|
27
|
+
* after all plugins return "always" (or void), i.e. plugins can vote "allow" to be invoked again.
|
|
28
|
+
*/
|
|
23
29
|
pluginReadFields: number;
|
|
24
30
|
pluginReadFieldsExtra: number[] | undefined;
|
|
25
31
|
/** Number/untagged ID conversions are cached once; assigned entity IDs never change. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InstanceData.d.cts","names":[],"sources":["../src/InstanceData.ts"],"mappings":";;;;;qBAOa;;;WAEF,QAAQ;;WAER,IAAI;;WAEJ,UAAU;;EAEnB,WAAW;;EAEX,SAAS;;EAET;;EAEA,MAAM
|
|
1
|
+
{"version":3,"file":"InstanceData.d.cts","names":[],"sources":["../src/InstanceData.ts"],"mappings":";;;;;qBAOa;;;WAEF,QAAQ;;WAER,IAAI;;WAEJ,UAAU;;EAEnB,WAAW;;EAEX,SAAS;;EAET;;EAEA,MAAM;;;;;;;;EAQN;EACA;;EAEA;;EAMA,aAAa;;EAIb;;EAEA;;MA6BI;MAIA,UAAU;;EAKd,YAAY,IAAI,eAAe,QAAQ,QAAQ,UAAU,gBAAgB;;;;;;;;;;;;EA2BzE,UAAU;;EAKV;EAMA;;MAeI;;MAKA;;MAKA,gBAAgB;;MAKhB;;MAKA;MAqBA;;MAKA,eAAe;;EAKnB;;EAKA;EA2BA;;EAOA;;EAMA,eAAe,mBAAmB;;EAMlC,eAAe;;EAMf;;UAKQ;;EAKR,uBAAuB,mBAAmB;;EAO1C,oBAAoB;MAIhB;;;;;;;;;;;;;MAgBA"}
|
package/build/InstanceData.d.mts
CHANGED
|
@@ -19,7 +19,13 @@ export declare class InstanceData {
|
|
|
19
19
|
rowIndex: number;
|
|
20
20
|
/** The domain-value of fields, lazily converted (if needed) on read from the database columns. */
|
|
21
21
|
data: Record<string, any>;
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Tracks which fields have been passed to plugins, so we can skip plugins on subsequent field accesses.
|
|
24
|
+
*
|
|
25
|
+
* Note that we also set the bit temporarily during plugin evaluation to keep plugins internally
|
|
26
|
+
* re-accessing the field from recursing into themselves. We only keep a field marked as "plugin read"
|
|
27
|
+
* after all plugins return "always" (or void), i.e. plugins can vote "allow" to be invoked again.
|
|
28
|
+
*/
|
|
23
29
|
pluginReadFields: number;
|
|
24
30
|
pluginReadFieldsExtra: number[] | undefined;
|
|
25
31
|
/** Number/untagged ID conversions are cached once; assigned entity IDs never change. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InstanceData.d.mts","names":[],"sources":["../src/InstanceData.ts"],"mappings":";;;;;qBAOa;;;WAEF,QAAQ;;WAER,IAAI;;WAEJ,UAAU;;EAEnB,WAAW;;EAEX,SAAS;;EAET;;EAEA,MAAM
|
|
1
|
+
{"version":3,"file":"InstanceData.d.mts","names":[],"sources":["../src/InstanceData.ts"],"mappings":";;;;;qBAOa;;;WAEF,QAAQ;;WAER,IAAI;;WAEJ,UAAU;;EAEnB,WAAW;;EAEX,SAAS;;EAET;;EAEA,MAAM;;;;;;;;EAQN;EACA;;EAEA;;EAMA,aAAa;;EAIb;;EAEA;;MA6BI;MAIA,UAAU;;EAKd,YAAY,IAAI,eAAe,QAAQ,QAAQ,UAAU,gBAAgB;;;;;;;;;;;;EA2BzE,UAAU;;EAKV;EAMA;;MAeI;;MAKA;;MAKA,gBAAgB;;MAKhB;;MAKA;MAqBA;;MAKA,eAAe;;EAKnB;;EAKA;EA2BA;;EAOA;;EAMA,eAAe,mBAAmB;;EAMlC,eAAe;;EAMf;;UAKQ;;EAKR,uBAAuB,mBAAmB;;EAO1C,oBAAoB;MAIhB;;;;;;;;;;;;;MAgBA"}
|
package/build/InstanceData.js
CHANGED
|
@@ -20,7 +20,13 @@ var InstanceData = class {
|
|
|
20
20
|
rowIndex = 0;
|
|
21
21
|
/** The domain-value of fields, lazily converted (if needed) on read from the database columns. */
|
|
22
22
|
data;
|
|
23
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* Tracks which fields have been passed to plugins, so we can skip plugins on subsequent field accesses.
|
|
25
|
+
*
|
|
26
|
+
* Note that we also set the bit temporarily during plugin evaluation to keep plugins internally
|
|
27
|
+
* re-accessing the field from recursing into themselves. We only keep a field marked as "plugin read"
|
|
28
|
+
* after all plugins return "always" (or void), i.e. plugins can vote "allow" to be invoked again.
|
|
29
|
+
*/
|
|
24
30
|
pluginReadFields = 0;
|
|
25
31
|
pluginReadFieldsExtra = void 0;
|
|
26
32
|
/** Number/untagged ID conversions are cached once; assigned entity IDs never change. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InstanceData.js","names":[],"sources":["../src/InstanceData.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport { type RowData, emptyRowData } from \"src/RowData.ts\";\nimport { hasAnyKey } from \"src/utils.ts\";\n\n/** The `#orm` metadata field we track on each instance. */\nexport class InstanceData {\n /** The entity this instance data belongs to. */\n readonly entity: Entity;\n /** All entities must be associated to an `EntityManager` to handle lazy loading/etc. */\n readonly em: EntityManager;\n /** A pointer to our entity type's metadata. */\n readonly metadata: EntityMetadata;\n /** A bag for our lazy-initialized relations, allocated on first relation access. */\n relations: Record<any, any> | undefined = undefined;\n /** The as-loaded database row, i.e. our `rowIndex`-th row within our query's `RowData` result. */\n rowData: RowData = emptyRowData;\n /** Our row's index within `rowData`; see {@link RowData}. */\n rowIndex: number = 0;\n /** The domain-value of fields, lazily converted (if needed) on read from the database columns. */\n data: Record<string, any>;\n /** Tracks which fields have triggered plugin callbacks, including internal reads that do not enroll read protection. */\n pluginReadFields = 0;\n pluginReadFieldsExtra: number[] | undefined = undefined;\n /** Number/untagged ID conversions are cached once; assigned entity IDs never change. */\n idCache: string | number | undefined = undefined;\n /** A bag to keep the original values, allocated on first mutation (most entities are never mutated). */\n #originalData: Record<any, any> | undefined = undefined;\n /** Reference values that were set during this unit of work, allocated on first m2o/poly change. */\n #referenceHistory: Record<string, any[]> | undefined = undefined;\n /** A bag to keep the flushed-to-database values, only for AsyncReactiveField reactivity. */\n flushedData: Record<any, any> | undefined;\n /** Packs the new/deleted `Operation`s + isTouched into one slot; see the accessors below. */\n #flags: number = 0;\n /** The `a#1`, `a#2` index if we're an em.create-d entity. We never unset this, to keep ids stable across flushes. */\n createId: string | undefined;\n /** The zero-based order this entity was registered with its EntityManager. */\n entityIndex: number = -1;\n\n /** Whether our entity is new or not. */\n get #new(): Operation | undefined {\n const value = this.#flags & 0b11;\n return value === 0 ? undefined : value;\n }\n\n set #new(op: Operation | undefined) {\n this.#flags = (this.#flags & ~0b11) | (op ?? 0);\n }\n\n /**\n * Whether our entity has been deleted or not.\n *\n * - `pending` means we've been marked for deletion via `em.delete` but not issued a `DELETE`\n * - `flushed` means we've flushed a `DELETE` but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `deleted` means we've been flushed and `em.flush` has completed\n */\n get #deleted(): Operation | undefined {\n const value = (this.#flags >> 2) & 0b11;\n return value === 0 ? undefined : value;\n }\n\n set #deleted(op: Operation | undefined) {\n this.#flags = (this.#flags & ~0b1100) | ((op ?? 0) << 2);\n }\n\n /** Whether our entity should flush regardless of any other changes. */\n get isTouched(): boolean {\n return (this.#flags & 0b10000) !== 0;\n }\n\n set isTouched(value: boolean) {\n this.#flags = value ? this.#flags | 0b10000 : this.#flags & ~0b10000;\n }\n\n /** Creates the `#orm` field. */\n constructor(em: EntityManager, entity: Entity, metadata: EntityMetadata, isNew: boolean) {\n this.entity = entity;\n this.em = em;\n this.metadata = metadata;\n if (isNew) {\n this.#new = Operation.Pending;\n this.data = {};\n this.flushedData = undefined;\n if (em) this.markMaybePending();\n } else {\n this.#new = undefined;\n this.data = {};\n this.flushedData = undefined;\n }\n }\n\n /**\n * Returns the as-loaded value of `columnName`, i.e. `getColumn(\"rank\")`.\n *\n * This saves callers from knowing that `rowData`/`rowIndex` are a pair, but note it is\n * a snapshot of the query that loaded us, and specifically:\n *\n * - The value is driver-level, i.e. numeric enum ids, untagged foreign keys, and temporals\n * as strings; use `getField` if you want the domain value, and\n * - The value is not updated by `em.flush`, so after a flush it is the pre-flush value, and\n * - New entities have no row, so every column is `undefined`.\n */\n getColumn(columnName: string): any {\n return this.rowData.get(this.rowIndex, columnName);\n }\n\n /** If `em.flush` has detected a dirty RQF, reset our internal dirty state, w/o reseting our external-dirty state. */\n resetForRqfLoop() {\n this.flushedData = {};\n if (this.#new === Operation.Pending) this.#new = Operation.Flushed;\n if (this.#deleted === Operation.Pending) this.#deleted = Operation.Flushed;\n }\n\n resetAfterFlushed() {\n this.#originalData = undefined;\n this.#referenceHistory = undefined;\n this.flushedData = undefined;\n this.isTouched = false;\n if (this.#new === Operation.Pending || this.#new === Operation.Flushed) {\n this.#new = Operation.Complete;\n }\n if (this.#deleted === Operation.Pending || this.#deleted === Operation.Flushed) {\n this.#deleted = Operation.Complete;\n }\n this.unmarkMaybePending();\n }\n\n /** Our public-facing `isNewEntity`. */\n get isNewEntity(): boolean {\n return this.#new !== undefined && this.#new !== Operation.Complete;\n }\n\n /** Our public-facing `isDeletedEntity`. */\n get isDeletedEntity(): boolean {\n return this.#deleted !== undefined;\n }\n\n /** The original values of mutated fields; a shared empty object until the entity is actually mutated. */\n get originalData(): Record<any, any> {\n return this.#originalData ?? emptyObject;\n }\n\n /** Our public-facing `isDirtyEntity`. */\n get isDirtyEntity(): boolean {\n return hasAnyKey(this.#originalData);\n }\n\n /** This is our internal \"is pending flush\", which is aware of RQF micro-flush loops. */\n get pendingOperation(): \"insert\" | \"update\" | \"delete\" | \"none\" | \"created-then-deleted\" {\n if (this.#deleted !== undefined) {\n // Mark entities that were created and them immediately `em.delete`-d; granted this is\n // probably rare, but we shouldn't run hooks or have the driver try and delete these.\n // Note that we return them, instead of skipping entirely, so that fixupCreatedThenDeleted\n // can later be called.\n return this.#deleted === Operation.Pending && this.#new === Operation.Pending\n ? \"created-then-deleted\"\n : this.#deleted === Operation.Pending\n ? \"delete\"\n : \"none\";\n } else if (this.#new === Operation.Pending) {\n // Per ^, if `#new === flushed`, we fall through to check if micro-flush UPDATEs are required\n return \"insert\";\n } else if (this.flushedData) {\n return hasAnyKey(this.flushedData) ? \"update\" : \"none\";\n } else {\n return this.isTouched || hasAnyKey(this.#originalData) ? \"update\" : \"none\";\n }\n }\n\n get changedFields(): string[] {\n return Object.keys(this.changedData);\n }\n\n /** The changed-fields bag (flushedData during RQF loops, else originalData) without allocating a keys array. */\n get changedData(): Record<any, any> {\n return this.flushedData ?? this.#originalData ?? emptyObject;\n }\n\n /** Called when an `em.load` tries to find the entity and it's just gone from the db. */\n markDeletedBecauseNotFound(): void {\n this.#deleted = Operation.Complete;\n }\n\n /** Called by `em.delete`, returns true if this is new information. */\n markDeleted(): boolean {\n if (this.#deleted === undefined) {\n // Let any OneToManyCollection/ReactiveField/ReactiveReference.get caches know that they should recalc\n // (i.e. their filterDeleted logic) by asserting the `deleteBook.author` field is changing.\n for (const field of Object.values(this.metadata.allFields)) {\n // We only do reference/collection fields and skip the primitives, b/c we assume something like\n // `{ books: \"title\" }` doesn't need `resetIsLoaded(..., \"title\")` b/c the same hint will also\n // be watching \"did books change\", and so get reset that way.\n if (field.kind === \"m2o\" || field.kind === \"poly\" || field.kind === \"m2m\" || field.kind === \"m2mEnum\") {\n getEmInternalApi(this.em).isLoadedCache.resetIsLoaded(this.entity, field.fieldName);\n } else if (field.kind === \"primitive\" || field.kind === \"enum\" || field.kind === \"primaryKey\") {\n // Any reactable watching these fields will also be watching reference/collection\n } else if (field.kind === \"o2m\" || field.kind === \"o2o\") {\n // Any reactable watching these actually gets triggered by the primary m2o/poly side changing\n } else if (field.kind === \"lo2m\") {\n // Doesn't support reactivity\n } else {\n throw new Error(`Unhandled field kind ${field}`);\n }\n }\n this.#deleted = Operation.Pending;\n this.markMaybePending();\n return true;\n }\n return false;\n }\n\n fixupCreatedThenDeleted(): void {\n // Ideally we could do this via `resetAfterFlushed`?\n this.#deleted = Operation.Complete;\n this.unmarkMaybePending();\n }\n\n /** Marks this entity as needing a flush even if no fields changed. */\n markTouched(): void {\n this.isTouched = true;\n this.markMaybePending();\n }\n\n /** Marks a field as dirty with its pre-mutation value. */\n markFieldDirty(fieldName: string, value: any): void {\n (this.#originalData ??= {})[fieldName] = value;\n this.markMaybePending();\n }\n\n /** Marks a reverted field as clean again. */\n markFieldClean(fieldName: string): void {\n if (this.#originalData) delete this.#originalData[fieldName];\n this.markMaybePending();\n }\n\n /** Marks this entity as a possible flush candidate. */\n markMaybePending(): void {\n getEmInternalApi(this.em).markMaybePending(this.entity);\n }\n\n /** Removes this entity from the possible flush candidate set. */\n private unmarkMaybePending(): void {\n getEmInternalApi(this.em).unmarkMaybePending(this.entity);\n }\n\n /** Remembers a reference value that may need to be reverse-walked later. */\n rememberReferenceValue(fieldName: string, value: any): void {\n if (value === undefined) return;\n const values = ((this.#referenceHistory ??= {})[fieldName] ??= []);\n if (!values.includes(value)) values.push(value);\n }\n\n /** Returns reference values that may need to be reverse-walked later. */\n getReferenceHistory(fieldName: string): readonly any[] {\n return this.#referenceHistory?.[fieldName] ?? emptyArray;\n }\n\n get isDeletedAndFlushed(): boolean {\n return this.#deleted === Operation.Complete;\n }\n\n /**\n * Returns true if the entity is new or was new in this EM.\n *\n * This is primarily used for lazy-initializing relations, i.e. if:\n *\n * - A new `Author` is created\n * - We `em.flush` the author to the database\n * - Then `a1.books` is accessed for the first time\n *\n * We can have a high-confidence that `a1` has no books, because we just\n * created it, so we can set the OneToManyCollection to loaded.\n */\n get isOrWasNew(): boolean {\n // #new will be left as `complete`\n return this.#new !== undefined;\n }\n}\n\n/** An enum to track our insert/delete state progression. */\nenum Operation {\n Pending = 1,\n Flushed = 2,\n Complete = 3,\n}\n\n/** A shared frozen bag for un-mutated entities; strict mode makes accidental writes throw. */\nconst emptyObject: Record<any, any> = Object.freeze({});\n\n/** A shared frozen array for fields with no remembered reference values. */\nconst emptyArray: readonly any[] = Object.freeze([]);\n"],"mappings":";;;;;;;AAOA,IAAa,eAAb,MAA0B;;CAExB;;CAEA;;CAEA;;CAEA,YAA0C,KAAA;;CAE1C,UAAmB;;CAEnB,WAAmB;;CAEnB;;CAEA,mBAAmB;CACnB,wBAA8C,KAAA;;CAE9C,UAAuC,KAAA;;CAEvC,gBAA8C,KAAA;;CAE9C,oBAAuD,KAAA;;CAEvD;;CAEA,SAAiB;;CAEjB;;CAEA,cAAsB;;CAGtB,IAAI,OAA8B;EAChC,MAAM,QAAQ,KAAK,SAAS;EAC5B,OAAO,UAAU,IAAI,KAAA,IAAY;CACnC;CAEA,IAAI,KAAK,IAA2B;EAClC,KAAK,SAAU,KAAK,SAAS,MAAU,MAAM;CAC/C;;;;;;;;CASA,IAAI,WAAkC;EACpC,MAAM,QAAS,KAAK,UAAU,IAAK;EACnC,OAAO,UAAU,IAAI,KAAA,IAAY;CACnC;CAEA,IAAI,SAAS,IAA2B;EACtC,KAAK,SAAU,KAAK,SAAS,OAAa,MAAM,MAAM;CACxD;;CAGA,IAAI,YAAqB;EACvB,QAAQ,KAAK,SAAS,QAAa;CACrC;CAEA,IAAI,UAAU,OAAgB;EAC5B,KAAK,SAAS,QAAQ,KAAK,SAAS,KAAU,KAAK,SAAS;CAC9D;;CAGA,YAAY,IAAmB,QAAgB,UAA0B,OAAgB;EACvF,KAAK,SAAS;EACd,KAAK,KAAK;EACV,KAAK,WAAW;EAChB,IAAI,OAAO;GACT,KAAK,OAAA;GACL,KAAK,OAAO,CAAC;GACb,KAAK,cAAc,KAAA;GACnB,IAAI,IAAI,KAAK,iBAAiB;EAChC,OAAO;GACL,KAAK,OAAO,KAAA;GACZ,KAAK,OAAO,CAAC;GACb,KAAK,cAAc,KAAA;EACrB;CACF;;;;;;;;;;;;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jC,OAAO,KAAK,aAAA;CACd;;;;;;;;;;;;;CAcA,IAAI,aAAsB;EAExB,OAAO,KAAK,SAAS,KAAA;CACvB;AACF;;AAUA,MAAM,cAAgC,OAAO,OAAO,CAAC,CAAC;;AAGtD,MAAM,aAA6B,OAAO,OAAO,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"InstanceData.js","names":[],"sources":["../src/InstanceData.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport { type RowData, emptyRowData } from \"src/RowData.ts\";\nimport { hasAnyKey } from \"src/utils.ts\";\n\n/** The `#orm` metadata field we track on each instance. */\nexport class InstanceData {\n /** The entity this instance data belongs to. */\n readonly entity: Entity;\n /** All entities must be associated to an `EntityManager` to handle lazy loading/etc. */\n readonly em: EntityManager;\n /** A pointer to our entity type's metadata. */\n readonly metadata: EntityMetadata;\n /** A bag for our lazy-initialized relations, allocated on first relation access. */\n relations: Record<any, any> | undefined = undefined;\n /** The as-loaded database row, i.e. our `rowIndex`-th row within our query's `RowData` result. */\n rowData: RowData = emptyRowData;\n /** Our row's index within `rowData`; see {@link RowData}. */\n rowIndex: number = 0;\n /** The domain-value of fields, lazily converted (if needed) on read from the database columns. */\n data: Record<string, any>;\n /**\n * Tracks which fields have been passed to plugins, so we can skip plugins on subsequent field accesses.\n *\n * Note that we also set the bit temporarily during plugin evaluation to keep plugins internally\n * re-accessing the field from recursing into themselves. We only keep a field marked as \"plugin read\"\n * after all plugins return \"always\" (or void), i.e. plugins can vote \"allow\" to be invoked again.\n */\n pluginReadFields = 0;\n pluginReadFieldsExtra: number[] | undefined = undefined;\n /** Number/untagged ID conversions are cached once; assigned entity IDs never change. */\n idCache: string | number | undefined = undefined;\n /** A bag to keep the original values, allocated on first mutation (most entities are never mutated). */\n #originalData: Record<any, any> | undefined = undefined;\n /** Reference values that were set during this unit of work, allocated on first m2o/poly change. */\n #referenceHistory: Record<string, any[]> | undefined = undefined;\n /** A bag to keep the flushed-to-database values, only for AsyncReactiveField reactivity. */\n flushedData: Record<any, any> | undefined;\n /** Packs the new/deleted `Operation`s + isTouched into one slot; see the accessors below. */\n #flags: number = 0;\n /** The `a#1`, `a#2` index if we're an em.create-d entity. We never unset this, to keep ids stable across flushes. */\n createId: string | undefined;\n /** The zero-based order this entity was registered with its EntityManager. */\n entityIndex: number = -1;\n\n /** Whether our entity is new or not. */\n get #new(): Operation | undefined {\n const value = this.#flags & 0b11;\n return value === 0 ? undefined : value;\n }\n\n set #new(op: Operation | undefined) {\n this.#flags = (this.#flags & ~0b11) | (op ?? 0);\n }\n\n /**\n * Whether our entity has been deleted or not.\n *\n * - `pending` means we've been marked for deletion via `em.delete` but not issued a `DELETE`\n * - `flushed` means we've flushed a `DELETE` but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `deleted` means we've been flushed and `em.flush` has completed\n */\n get #deleted(): Operation | undefined {\n const value = (this.#flags >> 2) & 0b11;\n return value === 0 ? undefined : value;\n }\n\n set #deleted(op: Operation | undefined) {\n this.#flags = (this.#flags & ~0b1100) | ((op ?? 0) << 2);\n }\n\n /** Whether our entity should flush regardless of any other changes. */\n get isTouched(): boolean {\n return (this.#flags & 0b10000) !== 0;\n }\n\n set isTouched(value: boolean) {\n this.#flags = value ? this.#flags | 0b10000 : this.#flags & ~0b10000;\n }\n\n /** Creates the `#orm` field. */\n constructor(em: EntityManager, entity: Entity, metadata: EntityMetadata, isNew: boolean) {\n this.entity = entity;\n this.em = em;\n this.metadata = metadata;\n if (isNew) {\n this.#new = Operation.Pending;\n this.data = {};\n this.flushedData = undefined;\n if (em) this.markMaybePending();\n } else {\n this.#new = undefined;\n this.data = {};\n this.flushedData = undefined;\n }\n }\n\n /**\n * Returns the as-loaded value of `columnName`, i.e. `getColumn(\"rank\")`.\n *\n * This saves callers from knowing that `rowData`/`rowIndex` are a pair, but note it is\n * a snapshot of the query that loaded us, and specifically:\n *\n * - The value is driver-level, i.e. numeric enum ids, untagged foreign keys, and temporals\n * as strings; use `getField` if you want the domain value, and\n * - The value is not updated by `em.flush`, so after a flush it is the pre-flush value, and\n * - New entities have no row, so every column is `undefined`.\n */\n getColumn(columnName: string): any {\n return this.rowData.get(this.rowIndex, columnName);\n }\n\n /** If `em.flush` has detected a dirty RQF, reset our internal dirty state, w/o reseting our external-dirty state. */\n resetForRqfLoop() {\n this.flushedData = {};\n if (this.#new === Operation.Pending) this.#new = Operation.Flushed;\n if (this.#deleted === Operation.Pending) this.#deleted = Operation.Flushed;\n }\n\n resetAfterFlushed() {\n this.#originalData = undefined;\n this.#referenceHistory = undefined;\n this.flushedData = undefined;\n this.isTouched = false;\n if (this.#new === Operation.Pending || this.#new === Operation.Flushed) {\n this.#new = Operation.Complete;\n }\n if (this.#deleted === Operation.Pending || this.#deleted === Operation.Flushed) {\n this.#deleted = Operation.Complete;\n }\n this.unmarkMaybePending();\n }\n\n /** Our public-facing `isNewEntity`. */\n get isNewEntity(): boolean {\n return this.#new !== undefined && this.#new !== Operation.Complete;\n }\n\n /** Our public-facing `isDeletedEntity`. */\n get isDeletedEntity(): boolean {\n return this.#deleted !== undefined;\n }\n\n /** The original values of mutated fields; a shared empty object until the entity is actually mutated. */\n get originalData(): Record<any, any> {\n return this.#originalData ?? emptyObject;\n }\n\n /** Our public-facing `isDirtyEntity`. */\n get isDirtyEntity(): boolean {\n return hasAnyKey(this.#originalData);\n }\n\n /** This is our internal \"is pending flush\", which is aware of RQF micro-flush loops. */\n get pendingOperation(): \"insert\" | \"update\" | \"delete\" | \"none\" | \"created-then-deleted\" {\n if (this.#deleted !== undefined) {\n // Mark entities that were created and them immediately `em.delete`-d; granted this is\n // probably rare, but we shouldn't run hooks or have the driver try and delete these.\n // Note that we return them, instead of skipping entirely, so that fixupCreatedThenDeleted\n // can later be called.\n return this.#deleted === Operation.Pending && this.#new === Operation.Pending\n ? \"created-then-deleted\"\n : this.#deleted === Operation.Pending\n ? \"delete\"\n : \"none\";\n } else if (this.#new === Operation.Pending) {\n // Per ^, if `#new === flushed`, we fall through to check if micro-flush UPDATEs are required\n return \"insert\";\n } else if (this.flushedData) {\n return hasAnyKey(this.flushedData) ? \"update\" : \"none\";\n } else {\n return this.isTouched || hasAnyKey(this.#originalData) ? \"update\" : \"none\";\n }\n }\n\n get changedFields(): string[] {\n return Object.keys(this.changedData);\n }\n\n /** The changed-fields bag (flushedData during RQF loops, else originalData) without allocating a keys array. */\n get changedData(): Record<any, any> {\n return this.flushedData ?? this.#originalData ?? emptyObject;\n }\n\n /** Called when an `em.load` tries to find the entity and it's just gone from the db. */\n markDeletedBecauseNotFound(): void {\n this.#deleted = Operation.Complete;\n }\n\n /** Called by `em.delete`, returns true if this is new information. */\n markDeleted(): boolean {\n if (this.#deleted === undefined) {\n // Let any OneToManyCollection/ReactiveField/ReactiveReference.get caches know that they should recalc\n // (i.e. their filterDeleted logic) by asserting the `deleteBook.author` field is changing.\n for (const field of Object.values(this.metadata.allFields)) {\n // We only do reference/collection fields and skip the primitives, b/c we assume something like\n // `{ books: \"title\" }` doesn't need `resetIsLoaded(..., \"title\")` b/c the same hint will also\n // be watching \"did books change\", and so get reset that way.\n if (field.kind === \"m2o\" || field.kind === \"poly\" || field.kind === \"m2m\" || field.kind === \"m2mEnum\") {\n getEmInternalApi(this.em).isLoadedCache.resetIsLoaded(this.entity, field.fieldName);\n } else if (field.kind === \"primitive\" || field.kind === \"enum\" || field.kind === \"primaryKey\") {\n // Any reactable watching these fields will also be watching reference/collection\n } else if (field.kind === \"o2m\" || field.kind === \"o2o\") {\n // Any reactable watching these actually gets triggered by the primary m2o/poly side changing\n } else if (field.kind === \"lo2m\") {\n // Doesn't support reactivity\n } else {\n throw new Error(`Unhandled field kind ${field}`);\n }\n }\n this.#deleted = Operation.Pending;\n this.markMaybePending();\n return true;\n }\n return false;\n }\n\n fixupCreatedThenDeleted(): void {\n // Ideally we could do this via `resetAfterFlushed`?\n this.#deleted = Operation.Complete;\n this.unmarkMaybePending();\n }\n\n /** Marks this entity as needing a flush even if no fields changed. */\n markTouched(): void {\n this.isTouched = true;\n this.markMaybePending();\n }\n\n /** Marks a field as dirty with its pre-mutation value. */\n markFieldDirty(fieldName: string, value: any): void {\n (this.#originalData ??= {})[fieldName] = value;\n this.markMaybePending();\n }\n\n /** Marks a reverted field as clean again. */\n markFieldClean(fieldName: string): void {\n if (this.#originalData) delete this.#originalData[fieldName];\n this.markMaybePending();\n }\n\n /** Marks this entity as a possible flush candidate. */\n markMaybePending(): void {\n getEmInternalApi(this.em).markMaybePending(this.entity);\n }\n\n /** Removes this entity from the possible flush candidate set. */\n private unmarkMaybePending(): void {\n getEmInternalApi(this.em).unmarkMaybePending(this.entity);\n }\n\n /** Remembers a reference value that may need to be reverse-walked later. */\n rememberReferenceValue(fieldName: string, value: any): void {\n if (value === undefined) return;\n const values = ((this.#referenceHistory ??= {})[fieldName] ??= []);\n if (!values.includes(value)) values.push(value);\n }\n\n /** Returns reference values that may need to be reverse-walked later. */\n getReferenceHistory(fieldName: string): readonly any[] {\n return this.#referenceHistory?.[fieldName] ?? emptyArray;\n }\n\n get isDeletedAndFlushed(): boolean {\n return this.#deleted === Operation.Complete;\n }\n\n /**\n * Returns true if the entity is new or was new in this EM.\n *\n * This is primarily used for lazy-initializing relations, i.e. if:\n *\n * - A new `Author` is created\n * - We `em.flush` the author to the database\n * - Then `a1.books` is accessed for the first time\n *\n * We can have a high-confidence that `a1` has no books, because we just\n * created it, so we can set the OneToManyCollection to loaded.\n */\n get isOrWasNew(): boolean {\n // #new will be left as `complete`\n return this.#new !== undefined;\n }\n}\n\n/** An enum to track our insert/delete state progression. */\nenum Operation {\n Pending = 1,\n Flushed = 2,\n Complete = 3,\n}\n\n/** A shared frozen bag for un-mutated entities; strict mode makes accidental writes throw. */\nconst emptyObject: Record<any, any> = Object.freeze({});\n\n/** A shared frozen array for fields with no remembered reference values. */\nconst emptyArray: readonly any[] = Object.freeze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O,CAAC,CAAC;;AAGtD,MAAM,aAA6B,OAAO,OAAO,CAAC,CAAC"}
|
package/build/PluginManager.cjs
CHANGED
|
@@ -57,9 +57,16 @@ var PluginManager = class {
|
|
|
57
57
|
plugin[emsSymbol].push(new WeakRef(this.em));
|
|
58
58
|
for (const method of syncPluginMethods) if (method in plugin) {
|
|
59
59
|
(this.#pluginsByCallback[method] ??= []).push(plugin);
|
|
60
|
-
if (!Object.hasOwn(this, method))
|
|
61
|
-
|
|
62
|
-
|
|
60
|
+
if (!Object.hasOwn(this, method)) {
|
|
61
|
+
if (method === "beforeGetField") this.beforeGetField = function(entity, field) {
|
|
62
|
+
let result = "always";
|
|
63
|
+
for (const plugin of this.#pluginsByCallback.beforeGetField) if (plugin.beforeGetField(entity, field) === "allow") result = "allow";
|
|
64
|
+
return result;
|
|
65
|
+
};
|
|
66
|
+
else this[method] = function(...args) {
|
|
67
|
+
for (const plugin of this.#pluginsByCallback[method]) plugin[method](...args);
|
|
68
|
+
};
|
|
69
|
+
}
|
|
63
70
|
}
|
|
64
71
|
for (const method of asyncPluginMethods) if (method in plugin) {
|
|
65
72
|
(this.#pluginsByCallback[method] ??= []).push(plugin);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PluginManager.cjs","names":["isDefined"],"sources":["../src/PluginManager.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, type FindOperation, isDefined } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport type { JoinRowTodo, Todo } from \"src/flush/Todo.ts\";\nimport type { ParsedFindQuery } from \"src/queries/find/QueryParser.ts\";\nimport { type RowData } from \"src/RowData.ts\";\n\ninterface PluginMethods {\n /**\n * Called on the first read of each entity field, including ORM-internal reads.\n *\n * Install plugins before reading entities. Cached reads, including reads after a flush\n * or refresh, do not invoke this callback again. A throwing callback can be retried.\n *\n * @param entity The entity instance being accessed\n * @param field The field name being retrieved\n */\n beforeGetField?(entity: Entity, field: string): void;\n /**\n * Called before a field value is set on an entity via setField.\n *\n * @param entity The entity instance being modified\n * @param field The field name being set\n * @param newValue The new value being assigned to the field\n */\n beforeSetField?(entity: Entity, field: string, newValue: any): void;\n /**\n * Called before a find operation is executed.\n *\n * @param meta Metadata for the entity type being queried\n * @param operation The type of find operation being performed\n * @param query The parsed query conditions\n * @param settings Query settings including limit and offset\n */\n beforeFind?(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void;\n /**\n * Called after a find operation has been executed to observe the raw database rows.\n *\n * The result is an observation-only {@link RowData} view — i.e. `rows.rowCount` for metrics,\n * `rows.get(i, columnName)` for specific cells, or `rows.toRows()` to materialize POJO rows.\n * For lazy results, cells decode on access, so a hook that only counts rows costs nothing;\n * materializing via `toRows()` decodes every cell of every row. Mutating materialized rows is\n * unsupported and is not guaranteed to affect entity hydration.\n *\n * @param meta Metadata for the entity type that was queried\n * @param operation The type of find operation that was performed\n * @param rows A read-only view of the raw database rows returned from the query\n */\n afterFind?(meta: EntityMetadata, operation: FindOperation, rows: RowData): void;\n\n beforeValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void;\n}\n\nconst syncPluginMethods = [\n \"beforeGetField\",\n \"beforeSetField\",\n \"beforeFind\",\n \"afterFind\",\n \"afterWrite\",\n] as const satisfies readonly (keyof PluginMethods)[];\nconst asyncPluginMethods = [\"beforeValidate\", \"afterValidate\"] as const satisfies readonly (keyof PluginMethods)[];\nconst emsSymbol = Symbol(\"ems\");\n/**\n * Base class for plugins that hook into entity lifecycle events.\n *\n * Plugins can implement any of the PluginMethods to intercept entity operations\n * and are automatically registered with the EntityManager when added via PluginManager.\n */\nexport abstract class Plugin {\n // We need to store the EntityManager references in a WeakRef array so that they can be garbage collected. If we\n // didn't do this, then multiple EMs with the same plugin instance could keep each other from being garbage collected.\n [emsSymbol]: WeakRef<EntityManager>[] = [];\n\n maybeCloneForNewEm(): this | undefined {\n return undefined;\n }\n\n get ems(): readonly EntityManager[] {\n return this[emsSymbol]\n .values()\n .map((wr) => wr.deref())\n .filter(isDefined)\n .toArray();\n }\n}\n\nexport interface Plugin extends PluginMethods {}\n\n/**\n * Manages plugin lifecycle and dispatches plugin callbacks to registered plugins.\n *\n * The PluginManager optimizes callback dispatch by only creating dispatcher methods\n * for callbacks that have at least one registered plugin, making unused plugin hooks\n * zero-cost at runtime.\n */\nexport class PluginManager implements Required<PluginMethods> {\n #plugins = new Set<Plugin>();\n readonly #pluginsByCallback: Partial<Record<keyof Plugin, Plugin[]>> = {};\n constructor(public readonly em: EntityManager) {}\n\n /** Returns whether any registered plugin implements `method`, i.e. so callers can skip building its args. */\n hasHook(method: keyof PluginMethods): boolean {\n return this.#pluginsByCallback[method] !== undefined;\n }\n\n /**\n * Registers a plugin with this EntityManager.\n *\n * Dynamically creates dispatcher methods for any plugin callbacks implemented by this plugin,\n * enabling lazy initialization of only the hooks that are actually used.\n *\n * @throws Error if the plugin is already registered with another EntityManager\n */\n addPlugin(plugin: Plugin) {\n if (this.#plugins.has(plugin)) return; // if we're already added, then we can just early exit\n this.#plugins.add(plugin);\n plugin[emsSymbol].push(new WeakRef(this.em));\n for (const method of syncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // As a performance optimization, we only create the actual implementation for each method on the plugin manager\n // once we have at least one plugin using that method. This is to make it so any unused plugin methods are\n // effectively no-ops when called from within the em.\n if (!Object.hasOwn(this, method)) {\n this[method] = function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n (plugin[method] as (...args: any[]) => unknown)(...args);\n }\n };\n }\n }\n }\n for (const method of asyncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // Validate-phase plugin hooks are intentionally awaited without making hot-path hooks async.\n if (!Object.hasOwn(this, method)) {\n this[method] = async function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n await (plugin[method] as (...args: any[]) => Promise<void> | void)(...args);\n }\n };\n }\n }\n }\n }\n\n get plugins(): readonly Plugin[] {\n return [...this.#plugins];\n }\n\n cloneTo(other: PluginManager) {\n this.#plugins\n .values()\n .map((plugin) => plugin.maybeCloneForNewEm())\n .filter(isDefined)\n .forEach((plugin) => other.addPlugin(plugin));\n }\n\n // Defined as no-op functions initially instead of using optional chaining for performance reasons, see:\n // https://adventures.nodeland.dev/archive/noop-functions-vs-optional-chaining-a-performance/\n\n beforeGetField(entity: Entity, field: string): void {}\n beforeSetField(entity: Entity, field: string, newValue: any): void {}\n beforeFind(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void {}\n afterFind(meta: EntityMetadata, operation: FindOperation, rows: RowData) {}\n beforeValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void {}\n}\n"],"mappings":";;;;;AAqEA,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,qBAAqB,CAAC,kBAAkB,eAAe;AAC7D,MAAM,YAAY,OAAO,KAAK;;;;;;;AAO9B,IAAsB,SAAtB,MAA6B;CAG3B,CAAC,aAAuC,CAAC;CAEzC,qBAAuC,CAEvC;CAEA,IAAI,MAAgC;EAClC,OAAO,KAAK,UAAU,CACnB,OAAO,CAAC,CACR,KAAK,OAAO,GAAG,MAAM,CAAC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W,MAAM,UAAU,MAAM,CAAC;CAChD;CAKA,eAAe,QAAgB,OAAqB,CAAC;CACrD,eAAe,QAAgB,OAAe,UAAqB,CAAC;CACpE,WACE,MACA,WACA,OACA,UAQM,CAAC;CACT,UAAU,MAAsB,WAA0B,MAAe,CAAC;CAC1E,eAAe,UAAmD,CAAC;CACnE,cAAc,UAAmD,CAAC;CAClE,WAAW,aAAmC,cAAiD,CAAC;AAClG"}
|
|
1
|
+
{"version":3,"file":"PluginManager.cjs","names":["isDefined"],"sources":["../src/PluginManager.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, type FindOperation, isDefined } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport type { JoinRowTodo, Todo } from \"src/flush/Todo.ts\";\nimport type { ParsedFindQuery } from \"src/queries/find/QueryParser.ts\";\nimport { type RowData } from \"src/RowData.ts\";\n\ninterface PluginMethods {\n /**\n * Called before the first read of each entity field, and again if any plugin returns `\"allow\"`.\n * Includes ORM-internal reads.\n *\n * Return `\"allow\"` to allow only this access and check again on the next read. Return\n * `\"always\"` or nothing to allow all subsequent accesses, regardless of trusted context.\n * Throw to deny access. Any plugin returning `\"allow\"` prevents caching for all plugins.\n *\n * Install plugins before reading entities. Cached reads, including reads after a flush\n * or refresh, do not invoke this callback again. A throwing callback can be retried.\n *\n * @param entity The entity instance being accessed\n * @param field The field name being retrieved\n */\n beforeGetField?(entity: Entity, field: string): \"allow\" | \"always\" | void;\n /**\n * Called before a field value is set on an entity via setField.\n *\n * @param entity The entity instance being modified\n * @param field The field name being set\n * @param newValue The new value being assigned to the field\n */\n beforeSetField?(entity: Entity, field: string, newValue: any): void;\n /**\n * Called before a find operation is executed.\n *\n * @param meta Metadata for the entity type being queried\n * @param operation The type of find operation being performed\n * @param query The parsed query conditions\n * @param settings Query settings including limit and offset\n */\n beforeFind?(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void;\n /**\n * Called after a find operation has been executed to observe the raw database rows.\n *\n * The result is an observation-only {@link RowData} view — i.e. `rows.rowCount` for metrics,\n * `rows.get(i, columnName)` for specific cells, or `rows.toRows()` to materialize POJO rows.\n * For lazy results, cells decode on access, so a hook that only counts rows costs nothing;\n * materializing via `toRows()` decodes every cell of every row. Mutating materialized rows is\n * unsupported and is not guaranteed to affect entity hydration.\n *\n * @param meta Metadata for the entity type that was queried\n * @param operation The type of find operation that was performed\n * @param rows A read-only view of the raw database rows returned from the query\n */\n afterFind?(meta: EntityMetadata, operation: FindOperation, rows: RowData): void;\n\n beforeValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void;\n}\n\nconst syncPluginMethods = [\n \"beforeGetField\",\n \"beforeSetField\",\n \"beforeFind\",\n \"afterFind\",\n \"afterWrite\",\n] as const satisfies readonly (keyof PluginMethods)[];\nconst asyncPluginMethods = [\"beforeValidate\", \"afterValidate\"] as const satisfies readonly (keyof PluginMethods)[];\nconst emsSymbol = Symbol(\"ems\");\n/**\n * Base class for plugins that hook into entity lifecycle events.\n *\n * Plugins can implement any of the PluginMethods to intercept entity operations\n * and are automatically registered with the EntityManager when added via PluginManager.\n */\nexport abstract class Plugin {\n // We need to store the EntityManager references in a WeakRef array so that they can be garbage collected. If we\n // didn't do this, then multiple EMs with the same plugin instance could keep each other from being garbage collected.\n [emsSymbol]: WeakRef<EntityManager>[] = [];\n\n maybeCloneForNewEm(): this | undefined {\n return undefined;\n }\n\n get ems(): readonly EntityManager[] {\n return this[emsSymbol]\n .values()\n .map((wr) => wr.deref())\n .filter(isDefined)\n .toArray();\n }\n}\n\nexport interface Plugin extends PluginMethods {}\n\n/**\n * Manages plugin lifecycle and dispatches plugin callbacks to registered plugins.\n *\n * The PluginManager optimizes callback dispatch by only creating dispatcher methods\n * for callbacks that have at least one registered plugin, making unused plugin hooks\n * zero-cost at runtime.\n */\nexport class PluginManager implements Required<PluginMethods> {\n #plugins = new Set<Plugin>();\n readonly #pluginsByCallback: Partial<Record<keyof Plugin, Plugin[]>> = {};\n constructor(public readonly em: EntityManager) {}\n\n /** Returns whether any registered plugin implements `method`, i.e. so callers can skip building its args. */\n hasHook(method: keyof PluginMethods): boolean {\n return this.#pluginsByCallback[method] !== undefined;\n }\n\n /**\n * Registers a plugin with this EntityManager.\n *\n * Dynamically creates dispatcher methods for any plugin callbacks implemented by this plugin,\n * enabling lazy initialization of only the hooks that are actually used.\n *\n * @throws Error if the plugin is already registered with another EntityManager\n */\n addPlugin(plugin: Plugin) {\n if (this.#plugins.has(plugin)) return; // if we're already added, then we can just early exit\n this.#plugins.add(plugin);\n plugin[emsSymbol].push(new WeakRef(this.em));\n for (const method of syncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // As a performance optimization, we only create the actual implementation for each method on the plugin manager\n // once we have at least one plugin using that method. This is to make it so any unused plugin methods are\n // effectively no-ops when called from within the em.\n if (!Object.hasOwn(this, method)) {\n if (method === \"beforeGetField\") {\n // Other hooks return nothing; beforeGetField must combine the plugins' caching votes.\n this.beforeGetField = function (this: PluginManager, entity: Entity, field: string): \"allow\" | \"always\" {\n // Start cacheable: both \"always\" and void permit caching.\n let result: \"allow\" | \"always\" = \"always\";\n\n // A cache veto must not skip later plugins: they may still deny this access.\n for (const plugin of this.#pluginsByCallback.beforeGetField!) {\n // Once a plugin votes \"allow\", later \"always\" or void votes cannot restore caching.\n if (plugin.beforeGetField!(entity, field) === \"allow\") result = \"allow\";\n }\n return result;\n };\n } else {\n this[method] = function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n (plugin[method] as (...args: any[]) => unknown)(...args);\n }\n };\n }\n }\n }\n }\n for (const method of asyncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // Validate-phase plugin hooks are intentionally awaited without making hot-path hooks async.\n if (!Object.hasOwn(this, method)) {\n this[method] = async function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n await (plugin[method] as (...args: any[]) => Promise<void> | void)(...args);\n }\n };\n }\n }\n }\n }\n\n get plugins(): readonly Plugin[] {\n return [...this.#plugins];\n }\n\n cloneTo(other: PluginManager) {\n this.#plugins\n .values()\n .map((plugin) => plugin.maybeCloneForNewEm())\n .filter(isDefined)\n .forEach((plugin) => other.addPlugin(plugin));\n }\n\n // Defined as no-op functions initially instead of using optional chaining for performance reasons, see:\n // https://adventures.nodeland.dev/archive/noop-functions-vs-optional-chaining-a-performance/\n\n beforeGetField(entity: Entity, field: string): \"allow\" | \"always\" | void {}\n beforeSetField(entity: Entity, field: string, newValue: any): void {}\n beforeFind(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void {}\n afterFind(meta: EntityMetadata, operation: FindOperation, rows: RowData) {}\n beforeValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void {}\n}\n"],"mappings":";;;;;AA0EA,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,qBAAqB,CAAC,kBAAkB,eAAe;AAC7D,MAAM,YAAY,OAAO,KAAK;;;;;;;AAO9B,IAAsB,SAAtB,MAA6B;CAG3B,CAAC,aAAuC,CAAC;CAEzC,qBAAuC,CAEvC;CAEA,IAAI,MAAgC;EAClC,OAAO,KAAK,UAAU,CACnB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AO,CAA8C,GAAG,IAAI;GAE9E;EAEJ;CAEJ;CAEA,IAAI,UAA6B;EAC/B,OAAO,CAAC,GAAG,KAAK,QAAQ;CAC1B;CAEA,QAAQ,OAAsB;EAC5B,KAAK,SACF,OAAO,CAAC,CACR,KAAK,WAAW,OAAO,mBAAmB,CAAC,CAAC,CAC5C,OAAOA,sBAAAA,SAAS,CAAC,CACjB,SAAS,WAAW,MAAM,UAAU,MAAM,CAAC;CAChD;CAKA,eAAe,QAAgB,OAA0C,CAAC;CAC1E,eAAe,QAAgB,OAAe,UAAqB,CAAC;CACpE,WACE,MACA,WACA,OACA,UAQM,CAAC;CACT,UAAU,MAAsB,WAA0B,MAAe,CAAC;CAC1E,eAAe,UAAmD,CAAC;CACnE,cAAc,UAAmD,CAAC;CAClE,WAAW,aAAmC,cAAiD,CAAC;AAClG"}
|
|
@@ -6,7 +6,12 @@ import { ParsedFindQuery } from "./queries/find/QueryParser.cjs";
|
|
|
6
6
|
import { RowData } from "./RowData.cjs";
|
|
7
7
|
interface PluginMethods {
|
|
8
8
|
/**
|
|
9
|
-
* Called
|
|
9
|
+
* Called before the first read of each entity field, and again if any plugin returns `"allow"`.
|
|
10
|
+
* Includes ORM-internal reads.
|
|
11
|
+
*
|
|
12
|
+
* Return `"allow"` to allow only this access and check again on the next read. Return
|
|
13
|
+
* `"always"` or nothing to allow all subsequent accesses, regardless of trusted context.
|
|
14
|
+
* Throw to deny access. Any plugin returning `"allow"` prevents caching for all plugins.
|
|
10
15
|
*
|
|
11
16
|
* Install plugins before reading entities. Cached reads, including reads after a flush
|
|
12
17
|
* or refresh, do not invoke this callback again. A throwing callback can be retried.
|
|
@@ -14,7 +19,7 @@ interface PluginMethods {
|
|
|
14
19
|
* @param entity The entity instance being accessed
|
|
15
20
|
* @param field The field name being retrieved
|
|
16
21
|
*/
|
|
17
|
-
beforeGetField?(entity: Entity, field: string): void;
|
|
22
|
+
beforeGetField?(entity: Entity, field: string): "allow" | "always" | void;
|
|
18
23
|
/**
|
|
19
24
|
* Called before a field value is set on an entity via setField.
|
|
20
25
|
*
|
|
@@ -94,7 +99,7 @@ export declare class PluginManager implements Required<PluginMethods> {
|
|
|
94
99
|
addPlugin(plugin: Plugin): void;
|
|
95
100
|
get plugins(): readonly Plugin[];
|
|
96
101
|
cloneTo(other: PluginManager): void;
|
|
97
|
-
beforeGetField(entity: Entity, field: string): void;
|
|
102
|
+
beforeGetField(entity: Entity, field: string): "allow" | "always" | void;
|
|
98
103
|
beforeSetField(entity: Entity, field: string, newValue: any): void;
|
|
99
104
|
beforeFind(meta: EntityMetadata, operation: FindOperation, query: ParsedFindQuery, settings: {
|
|
100
105
|
limit?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PluginManager.d.cts","names":[],"sources":["../src/PluginManager.ts"],"mappings":";;;;;;UAOU
|
|
1
|
+
{"version":3,"file":"PluginManager.d.cts","names":[],"sources":["../src/PluginManager.ts"],"mappings":";;;;;;UAOU;;;;;;;;;;;;;;;EAeR,gBAAgB,QAAQ,QAAQ;;;;;;;;EAQhC,gBAAgB,QAAQ,QAAQ,eAAe;;;;;;;;;EAS/C,YACE,MAAM,gBACN,WAAW,eACX,OAAO,iBACP;IACE;IACA;IACA;IACA;IACA;IACA;;;;;;;;;;;;;;;EAgBJ,WAAW,MAAM,gBAAgB,WAAW,eAAe,MAAM;EAEjE,gBAAgB,mBAAmB,WAAW;EAE9C,eAAe,mBAAmB,WAAW;EAE7C,WAAW,aAAa,eAAe,OAAO,cAAc,eAAe;;cAWvE;;;;;;;8BAOgB;GAGnB,YAAY,QAAQ;EAErB;MAII,gBAAgB;;iBASL,eAAe;;;;;;;;qBASnB,yBAAyB,SAAS;;WAGjB,IAAI;EAAhC,YAA4B,IAAI;;EAGhC,QAAQ,cAAc;;;;;;;;;EAYtB,UAAU,QAAQ;MAiDd,oBAAoB;EAIxB,QAAQ,OAAO;EAWf,eAAe,QAAQ,QAAQ;EAC/B,eAAe,QAAQ,QAAQ,eAAe;EAC9C,WACE,MAAM,gBACN,WAAW,eACX,OAAO,iBACP;IACE;IACA;IACA;IACA;IACA;IACA;;EAGJ,UAAU,MAAM,gBAAgB,WAAW,eAAe,MAAM;EAChE,eAAe,mBAAmB,WAAW;EAC7C,cAAc,mBAAmB,WAAW;EAC5C,WAAW,aAAa,eAAe,OAAO,cAAc,eAAe"}
|
|
@@ -6,7 +6,12 @@ import { ParsedFindQuery } from "./queries/find/QueryParser.mjs";
|
|
|
6
6
|
import { RowData } from "./RowData.mjs";
|
|
7
7
|
interface PluginMethods {
|
|
8
8
|
/**
|
|
9
|
-
* Called
|
|
9
|
+
* Called before the first read of each entity field, and again if any plugin returns `"allow"`.
|
|
10
|
+
* Includes ORM-internal reads.
|
|
11
|
+
*
|
|
12
|
+
* Return `"allow"` to allow only this access and check again on the next read. Return
|
|
13
|
+
* `"always"` or nothing to allow all subsequent accesses, regardless of trusted context.
|
|
14
|
+
* Throw to deny access. Any plugin returning `"allow"` prevents caching for all plugins.
|
|
10
15
|
*
|
|
11
16
|
* Install plugins before reading entities. Cached reads, including reads after a flush
|
|
12
17
|
* or refresh, do not invoke this callback again. A throwing callback can be retried.
|
|
@@ -14,7 +19,7 @@ interface PluginMethods {
|
|
|
14
19
|
* @param entity The entity instance being accessed
|
|
15
20
|
* @param field The field name being retrieved
|
|
16
21
|
*/
|
|
17
|
-
beforeGetField?(entity: Entity, field: string): void;
|
|
22
|
+
beforeGetField?(entity: Entity, field: string): "allow" | "always" | void;
|
|
18
23
|
/**
|
|
19
24
|
* Called before a field value is set on an entity via setField.
|
|
20
25
|
*
|
|
@@ -94,7 +99,7 @@ export declare class PluginManager implements Required<PluginMethods> {
|
|
|
94
99
|
addPlugin(plugin: Plugin): void;
|
|
95
100
|
get plugins(): readonly Plugin[];
|
|
96
101
|
cloneTo(other: PluginManager): void;
|
|
97
|
-
beforeGetField(entity: Entity, field: string): void;
|
|
102
|
+
beforeGetField(entity: Entity, field: string): "allow" | "always" | void;
|
|
98
103
|
beforeSetField(entity: Entity, field: string, newValue: any): void;
|
|
99
104
|
beforeFind(meta: EntityMetadata, operation: FindOperation, query: ParsedFindQuery, settings: {
|
|
100
105
|
limit?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PluginManager.d.mts","names":[],"sources":["../src/PluginManager.ts"],"mappings":";;;;;;UAOU
|
|
1
|
+
{"version":3,"file":"PluginManager.d.mts","names":[],"sources":["../src/PluginManager.ts"],"mappings":";;;;;;UAOU;;;;;;;;;;;;;;;EAeR,gBAAgB,QAAQ,QAAQ;;;;;;;;EAQhC,gBAAgB,QAAQ,QAAQ,eAAe;;;;;;;;;EAS/C,YACE,MAAM,gBACN,WAAW,eACX,OAAO,iBACP;IACE;IACA;IACA;IACA;IACA;IACA;;;;;;;;;;;;;;;EAgBJ,WAAW,MAAM,gBAAgB,WAAW,eAAe,MAAM;EAEjE,gBAAgB,mBAAmB,WAAW;EAE9C,eAAe,mBAAmB,WAAW;EAE7C,WAAW,aAAa,eAAe,OAAO,cAAc,eAAe;;cAWvE;;;;;;;8BAOgB;GAGnB,YAAY,QAAQ;EAErB;MAII,gBAAgB;;iBASL,eAAe;;;;;;;;qBASnB,yBAAyB,SAAS;;WAGjB,IAAI;EAAhC,YAA4B,IAAI;;EAGhC,QAAQ,cAAc;;;;;;;;;EAYtB,UAAU,QAAQ;MAiDd,oBAAoB;EAIxB,QAAQ,OAAO;EAWf,eAAe,QAAQ,QAAQ;EAC/B,eAAe,QAAQ,QAAQ,eAAe;EAC9C,WACE,MAAM,gBACN,WAAW,eACX,OAAO,iBACP;IACE;IACA;IACA;IACA;IACA;IACA;;EAGJ,UAAU,MAAM,gBAAgB,WAAW,eAAe,MAAM;EAChE,eAAe,mBAAmB,WAAW;EAC7C,cAAc,mBAAmB,WAAW;EAC5C,WAAW,aAAa,eAAe,OAAO,cAAc,eAAe"}
|
package/build/PluginManager.js
CHANGED
|
@@ -56,9 +56,16 @@ var PluginManager = class {
|
|
|
56
56
|
plugin[emsSymbol].push(new WeakRef(this.em));
|
|
57
57
|
for (const method of syncPluginMethods) if (method in plugin) {
|
|
58
58
|
(this.#pluginsByCallback[method] ??= []).push(plugin);
|
|
59
|
-
if (!Object.hasOwn(this, method))
|
|
60
|
-
|
|
61
|
-
|
|
59
|
+
if (!Object.hasOwn(this, method)) {
|
|
60
|
+
if (method === "beforeGetField") this.beforeGetField = function(entity, field) {
|
|
61
|
+
let result = "always";
|
|
62
|
+
for (const plugin of this.#pluginsByCallback.beforeGetField) if (plugin.beforeGetField(entity, field) === "allow") result = "allow";
|
|
63
|
+
return result;
|
|
64
|
+
};
|
|
65
|
+
else this[method] = function(...args) {
|
|
66
|
+
for (const plugin of this.#pluginsByCallback[method]) plugin[method](...args);
|
|
67
|
+
};
|
|
68
|
+
}
|
|
62
69
|
}
|
|
63
70
|
for (const method of asyncPluginMethods) if (method in plugin) {
|
|
64
71
|
(this.#pluginsByCallback[method] ??= []).push(plugin);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PluginManager.js","names":[],"sources":["../src/PluginManager.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, type FindOperation, isDefined } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport type { JoinRowTodo, Todo } from \"src/flush/Todo.ts\";\nimport type { ParsedFindQuery } from \"src/queries/find/QueryParser.ts\";\nimport { type RowData } from \"src/RowData.ts\";\n\ninterface PluginMethods {\n /**\n * Called on the first read of each entity field, including ORM-internal reads.\n *\n * Install plugins before reading entities. Cached reads, including reads after a flush\n * or refresh, do not invoke this callback again. A throwing callback can be retried.\n *\n * @param entity The entity instance being accessed\n * @param field The field name being retrieved\n */\n beforeGetField?(entity: Entity, field: string): void;\n /**\n * Called before a field value is set on an entity via setField.\n *\n * @param entity The entity instance being modified\n * @param field The field name being set\n * @param newValue The new value being assigned to the field\n */\n beforeSetField?(entity: Entity, field: string, newValue: any): void;\n /**\n * Called before a find operation is executed.\n *\n * @param meta Metadata for the entity type being queried\n * @param operation The type of find operation being performed\n * @param query The parsed query conditions\n * @param settings Query settings including limit and offset\n */\n beforeFind?(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void;\n /**\n * Called after a find operation has been executed to observe the raw database rows.\n *\n * The result is an observation-only {@link RowData} view — i.e. `rows.rowCount` for metrics,\n * `rows.get(i, columnName)` for specific cells, or `rows.toRows()` to materialize POJO rows.\n * For lazy results, cells decode on access, so a hook that only counts rows costs nothing;\n * materializing via `toRows()` decodes every cell of every row. Mutating materialized rows is\n * unsupported and is not guaranteed to affect entity hydration.\n *\n * @param meta Metadata for the entity type that was queried\n * @param operation The type of find operation that was performed\n * @param rows A read-only view of the raw database rows returned from the query\n */\n afterFind?(meta: EntityMetadata, operation: FindOperation, rows: RowData): void;\n\n beforeValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void;\n}\n\nconst syncPluginMethods = [\n \"beforeGetField\",\n \"beforeSetField\",\n \"beforeFind\",\n \"afterFind\",\n \"afterWrite\",\n] as const satisfies readonly (keyof PluginMethods)[];\nconst asyncPluginMethods = [\"beforeValidate\", \"afterValidate\"] as const satisfies readonly (keyof PluginMethods)[];\nconst emsSymbol = Symbol(\"ems\");\n/**\n * Base class for plugins that hook into entity lifecycle events.\n *\n * Plugins can implement any of the PluginMethods to intercept entity operations\n * and are automatically registered with the EntityManager when added via PluginManager.\n */\nexport abstract class Plugin {\n // We need to store the EntityManager references in a WeakRef array so that they can be garbage collected. If we\n // didn't do this, then multiple EMs with the same plugin instance could keep each other from being garbage collected.\n [emsSymbol]: WeakRef<EntityManager>[] = [];\n\n maybeCloneForNewEm(): this | undefined {\n return undefined;\n }\n\n get ems(): readonly EntityManager[] {\n return this[emsSymbol]\n .values()\n .map((wr) => wr.deref())\n .filter(isDefined)\n .toArray();\n }\n}\n\nexport interface Plugin extends PluginMethods {}\n\n/**\n * Manages plugin lifecycle and dispatches plugin callbacks to registered plugins.\n *\n * The PluginManager optimizes callback dispatch by only creating dispatcher methods\n * for callbacks that have at least one registered plugin, making unused plugin hooks\n * zero-cost at runtime.\n */\nexport class PluginManager implements Required<PluginMethods> {\n #plugins = new Set<Plugin>();\n readonly #pluginsByCallback: Partial<Record<keyof Plugin, Plugin[]>> = {};\n constructor(public readonly em: EntityManager) {}\n\n /** Returns whether any registered plugin implements `method`, i.e. so callers can skip building its args. */\n hasHook(method: keyof PluginMethods): boolean {\n return this.#pluginsByCallback[method] !== undefined;\n }\n\n /**\n * Registers a plugin with this EntityManager.\n *\n * Dynamically creates dispatcher methods for any plugin callbacks implemented by this plugin,\n * enabling lazy initialization of only the hooks that are actually used.\n *\n * @throws Error if the plugin is already registered with another EntityManager\n */\n addPlugin(plugin: Plugin) {\n if (this.#plugins.has(plugin)) return; // if we're already added, then we can just early exit\n this.#plugins.add(plugin);\n plugin[emsSymbol].push(new WeakRef(this.em));\n for (const method of syncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // As a performance optimization, we only create the actual implementation for each method on the plugin manager\n // once we have at least one plugin using that method. This is to make it so any unused plugin methods are\n // effectively no-ops when called from within the em.\n if (!Object.hasOwn(this, method)) {\n this[method] = function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n (plugin[method] as (...args: any[]) => unknown)(...args);\n }\n };\n }\n }\n }\n for (const method of asyncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // Validate-phase plugin hooks are intentionally awaited without making hot-path hooks async.\n if (!Object.hasOwn(this, method)) {\n this[method] = async function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n await (plugin[method] as (...args: any[]) => Promise<void> | void)(...args);\n }\n };\n }\n }\n }\n }\n\n get plugins(): readonly Plugin[] {\n return [...this.#plugins];\n }\n\n cloneTo(other: PluginManager) {\n this.#plugins\n .values()\n .map((plugin) => plugin.maybeCloneForNewEm())\n .filter(isDefined)\n .forEach((plugin) => other.addPlugin(plugin));\n }\n\n // Defined as no-op functions initially instead of using optional chaining for performance reasons, see:\n // https://adventures.nodeland.dev/archive/noop-functions-vs-optional-chaining-a-performance/\n\n beforeGetField(entity: Entity, field: string): void {}\n beforeSetField(entity: Entity, field: string, newValue: any): void {}\n beforeFind(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void {}\n afterFind(meta: EntityMetadata, operation: FindOperation, rows: RowData) {}\n beforeValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void {}\n}\n"],"mappings":";;;;AAqEA,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,qBAAqB,CAAC,kBAAkB,eAAe;AAC7D,MAAM,YAAY,OAAO,KAAK;;;;;;;AAO9B,IAAsB,SAAtB,MAA6B;CAG3B,CAAC,aAAuC,CAAC;CAEzC,qBAAuC,CAEvC;CAEA,IAAI,MAAgC;EAClC,OAAO,KAAK,UAAU,CACnB,OAAO,CAAC,CACR,KAAK,OAAO,GAAG,MAAM,CAAC,CAAC,CACvB,OAAO,SAAS,CAAC,CACjB,QAAQ;CACb;AACF;;;;;;;;AAWA,IAAa,gBAAb,MAA8D;CAGhC;CAF5B,2BAAW,IAAI,IAAY;CAC3B,qBAAuE,CAAC;C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,MAAe,CAAC;CAC1E,eAAe,UAAmD,CAAC;CACnE,cAAc,UAAmD,CAAC;CAClE,WAAW,aAAmC,cAAiD,CAAC;AAClG"}
|
|
1
|
+
{"version":3,"file":"PluginManager.js","names":[],"sources":["../src/PluginManager.ts"],"sourcesContent":["import { type Entity } from \"src/Entity.ts\";\nimport { type EntityManager, type FindOperation, isDefined } from \"src/EntityManager.ts\";\nimport { type EntityMetadata } from \"src/EntityMetadata.ts\";\nimport type { JoinRowTodo, Todo } from \"src/flush/Todo.ts\";\nimport type { ParsedFindQuery } from \"src/queries/find/QueryParser.ts\";\nimport { type RowData } from \"src/RowData.ts\";\n\ninterface PluginMethods {\n /**\n * Called before the first read of each entity field, and again if any plugin returns `\"allow\"`.\n * Includes ORM-internal reads.\n *\n * Return `\"allow\"` to allow only this access and check again on the next read. Return\n * `\"always\"` or nothing to allow all subsequent accesses, regardless of trusted context.\n * Throw to deny access. Any plugin returning `\"allow\"` prevents caching for all plugins.\n *\n * Install plugins before reading entities. Cached reads, including reads after a flush\n * or refresh, do not invoke this callback again. A throwing callback can be retried.\n *\n * @param entity The entity instance being accessed\n * @param field The field name being retrieved\n */\n beforeGetField?(entity: Entity, field: string): \"allow\" | \"always\" | void;\n /**\n * Called before a field value is set on an entity via setField.\n *\n * @param entity The entity instance being modified\n * @param field The field name being set\n * @param newValue The new value being assigned to the field\n */\n beforeSetField?(entity: Entity, field: string, newValue: any): void;\n /**\n * Called before a find operation is executed.\n *\n * @param meta Metadata for the entity type being queried\n * @param operation The type of find operation being performed\n * @param query The parsed query conditions\n * @param settings Query settings including limit and offset\n */\n beforeFind?(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void;\n /**\n * Called after a find operation has been executed to observe the raw database rows.\n *\n * The result is an observation-only {@link RowData} view — i.e. `rows.rowCount` for metrics,\n * `rows.get(i, columnName)` for specific cells, or `rows.toRows()` to materialize POJO rows.\n * For lazy results, cells decode on access, so a hook that only counts rows costs nothing;\n * materializing via `toRows()` decodes every cell of every row. Mutating materialized rows is\n * unsupported and is not guaranteed to affect entity hydration.\n *\n * @param meta Metadata for the entity type that was queried\n * @param operation The type of find operation that was performed\n * @param rows A read-only view of the raw database rows returned from the query\n */\n afterFind?(meta: EntityMetadata, operation: FindOperation, rows: RowData): void;\n\n beforeValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterValidate?(entities: readonly Entity[]): Promise<void> | void;\n\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void;\n}\n\nconst syncPluginMethods = [\n \"beforeGetField\",\n \"beforeSetField\",\n \"beforeFind\",\n \"afterFind\",\n \"afterWrite\",\n] as const satisfies readonly (keyof PluginMethods)[];\nconst asyncPluginMethods = [\"beforeValidate\", \"afterValidate\"] as const satisfies readonly (keyof PluginMethods)[];\nconst emsSymbol = Symbol(\"ems\");\n/**\n * Base class for plugins that hook into entity lifecycle events.\n *\n * Plugins can implement any of the PluginMethods to intercept entity operations\n * and are automatically registered with the EntityManager when added via PluginManager.\n */\nexport abstract class Plugin {\n // We need to store the EntityManager references in a WeakRef array so that they can be garbage collected. If we\n // didn't do this, then multiple EMs with the same plugin instance could keep each other from being garbage collected.\n [emsSymbol]: WeakRef<EntityManager>[] = [];\n\n maybeCloneForNewEm(): this | undefined {\n return undefined;\n }\n\n get ems(): readonly EntityManager[] {\n return this[emsSymbol]\n .values()\n .map((wr) => wr.deref())\n .filter(isDefined)\n .toArray();\n }\n}\n\nexport interface Plugin extends PluginMethods {}\n\n/**\n * Manages plugin lifecycle and dispatches plugin callbacks to registered plugins.\n *\n * The PluginManager optimizes callback dispatch by only creating dispatcher methods\n * for callbacks that have at least one registered plugin, making unused plugin hooks\n * zero-cost at runtime.\n */\nexport class PluginManager implements Required<PluginMethods> {\n #plugins = new Set<Plugin>();\n readonly #pluginsByCallback: Partial<Record<keyof Plugin, Plugin[]>> = {};\n constructor(public readonly em: EntityManager) {}\n\n /** Returns whether any registered plugin implements `method`, i.e. so callers can skip building its args. */\n hasHook(method: keyof PluginMethods): boolean {\n return this.#pluginsByCallback[method] !== undefined;\n }\n\n /**\n * Registers a plugin with this EntityManager.\n *\n * Dynamically creates dispatcher methods for any plugin callbacks implemented by this plugin,\n * enabling lazy initialization of only the hooks that are actually used.\n *\n * @throws Error if the plugin is already registered with another EntityManager\n */\n addPlugin(plugin: Plugin) {\n if (this.#plugins.has(plugin)) return; // if we're already added, then we can just early exit\n this.#plugins.add(plugin);\n plugin[emsSymbol].push(new WeakRef(this.em));\n for (const method of syncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // As a performance optimization, we only create the actual implementation for each method on the plugin manager\n // once we have at least one plugin using that method. This is to make it so any unused plugin methods are\n // effectively no-ops when called from within the em.\n if (!Object.hasOwn(this, method)) {\n if (method === \"beforeGetField\") {\n // Other hooks return nothing; beforeGetField must combine the plugins' caching votes.\n this.beforeGetField = function (this: PluginManager, entity: Entity, field: string): \"allow\" | \"always\" {\n // Start cacheable: both \"always\" and void permit caching.\n let result: \"allow\" | \"always\" = \"always\";\n\n // A cache veto must not skip later plugins: they may still deny this access.\n for (const plugin of this.#pluginsByCallback.beforeGetField!) {\n // Once a plugin votes \"allow\", later \"always\" or void votes cannot restore caching.\n if (plugin.beforeGetField!(entity, field) === \"allow\") result = \"allow\";\n }\n return result;\n };\n } else {\n this[method] = function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n (plugin[method] as (...args: any[]) => unknown)(...args);\n }\n };\n }\n }\n }\n }\n for (const method of asyncPluginMethods) {\n if (method in plugin) {\n (this.#pluginsByCallback[method] ??= []).push(plugin);\n // Validate-phase plugin hooks are intentionally awaited without making hot-path hooks async.\n if (!Object.hasOwn(this, method)) {\n this[method] = async function (this: PluginManager, ...args: any[]) {\n for (const plugin of this.#pluginsByCallback[method]!) {\n await (plugin[method] as (...args: any[]) => Promise<void> | void)(...args);\n }\n };\n }\n }\n }\n }\n\n get plugins(): readonly Plugin[] {\n return [...this.#plugins];\n }\n\n cloneTo(other: PluginManager) {\n this.#plugins\n .values()\n .map((plugin) => plugin.maybeCloneForNewEm())\n .filter(isDefined)\n .forEach((plugin) => other.addPlugin(plugin));\n }\n\n // Defined as no-op functions initially instead of using optional chaining for performance reasons, see:\n // https://adventures.nodeland.dev/archive/noop-functions-vs-optional-chaining-a-performance/\n\n beforeGetField(entity: Entity, field: string): \"allow\" | \"always\" | void {}\n beforeSetField(entity: Entity, field: string, newValue: any): void {}\n beforeFind(\n meta: EntityMetadata,\n operation: FindOperation,\n query: ParsedFindQuery,\n settings: {\n limit?: number;\n offset?: number;\n allowMultipleLeftJoins?: boolean;\n optimizeJoinsToExists?: boolean;\n pruneJoins?: boolean;\n keepAliases?: string[];\n },\n ): void {}\n afterFind(meta: EntityMetadata, operation: FindOperation, rows: RowData) {}\n beforeValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterValidate(entities: readonly Entity[]): Promise<void> | void {}\n afterWrite(entityTodos: Record<string, Todo>, joinRowTodos: Record<string, JoinRowTodo>): void {}\n}\n"],"mappings":";;;;AA0EA,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,qBAAqB,CAAC,kBAAkB,eAAe;AAC7D,MAAM,YAAY,OAAO,KAAK;;;;;;;AAO9B,IAAsB,SAAtB,MAA6B;CAG3B,CAAC,aAAuC,CAAC;CAEzC,qBAAuC,CAEvC;CAEA,IAAI,MAAgC;EAClC,OAAO,KAAK,UAAU,CACnB,OAAO,CAAC,CACR,KAAK,OAAO,GAAG,MAAM,CAAC,CAAC,CACvB,OAAO,SAAS,CAAC,CACjB,QAAQ;CACb;AACF;;;;;;;;AAWA,IAAa,gBAAb,MAA8D;CAGhC;CAF5B,2BAAW,IAAI,IAAY;CAC3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BAAmB,CAAC,CAAC,CAC5C,OAAO,SAAS,CAAC,CACjB,SAAS,WAAW,MAAM,UAAU,MAAM,CAAC;CAChD;CAKA,eAAe,QAAgB,OAA0C,CAAC;CAC1E,eAAe,QAAgB,OAAe,UAAqB,CAAC;CACpE,WACE,MACA,WACA,OACA,UAQM,CAAC;CACT,UAAU,MAAsB,WAA0B,MAAe,CAAC;CAC1E,eAAe,UAAmD,CAAC;CACnE,cAAc,UAAmD,CAAC;CAClE,WAAW,aAAmC,cAAiD,CAAC;AAClG"}
|
package/build/fields.cjs
CHANGED
|
@@ -11,8 +11,9 @@ const require_utils = require("./utils.cjs");
|
|
|
11
11
|
/**
|
|
12
12
|
* Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.
|
|
13
13
|
*
|
|
14
|
-
* Plugins observe
|
|
15
|
-
*
|
|
14
|
+
* Plugins observe the first read, including internal reads, and subsequent reads if any plugin returns `"allow"`.
|
|
15
|
+
*
|
|
16
|
+
* Install plugins before reading entities; adding one later does not replay cached reads.
|
|
16
17
|
* Generated getters and direct application calls are protected by default. Only ORM
|
|
17
18
|
* housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.
|
|
18
19
|
* The field name is a string because generated getters and ORM internals know its type.
|
|
@@ -116,18 +117,23 @@ function equal(a, b) {
|
|
|
116
117
|
return false;
|
|
117
118
|
}
|
|
118
119
|
/**
|
|
119
|
-
* Performs
|
|
120
|
+
* Performs read callbacks, protection, and lazy conversion before publishing the warm-read bit.
|
|
120
121
|
*
|
|
121
122
|
* The plugin bit is set before invoking hooks so a hook may read or change its own field,
|
|
122
123
|
* reentering this function without invoking the hook again.
|
|
123
|
-
* A throwing
|
|
124
|
+
* A hook returning `"allow"` or throwing clears both bits, so later accesses check again.
|
|
124
125
|
*/
|
|
125
126
|
function readField(entity, instanceData, fieldName, isInternal, index) {
|
|
126
127
|
const { em, metadata } = instanceData;
|
|
128
|
+
let canCache = true;
|
|
127
129
|
if (!hasReadField(instanceData.pluginReadFields, instanceData.pluginReadFieldsExtra, index)) {
|
|
128
130
|
markPluginReadField(instanceData, index, true);
|
|
129
131
|
try {
|
|
130
|
-
require_EntityManager.getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName);
|
|
132
|
+
canCache = require_EntityManager.getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName) !== "allow";
|
|
133
|
+
if (!canCache) {
|
|
134
|
+
markPluginReadField(instanceData, index, false);
|
|
135
|
+
markApplicationReadField(entity, index, false);
|
|
136
|
+
}
|
|
131
137
|
} catch (error) {
|
|
132
138
|
markPluginReadField(instanceData, index, false);
|
|
133
139
|
markApplicationReadField(entity, index, false);
|
|
@@ -139,7 +145,7 @@ function readField(entity, instanceData, fieldName, isInternal, index) {
|
|
|
139
145
|
if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);
|
|
140
146
|
const { data } = instanceData;
|
|
141
147
|
if (!(fieldName in data) && !instanceData.isNewEntity) data[fieldName] = (field?.serde ?? require_utils.fail(`Missing serde for ${fieldName}`)).fromRow(instanceData.rowData, instanceData.rowIndex);
|
|
142
|
-
if ((fieldName === "id" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) markApplicationReadField(entity, index, true);
|
|
148
|
+
if (canCache && (fieldName === "id" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) markApplicationReadField(entity, index, true);
|
|
143
149
|
return data[fieldName];
|
|
144
150
|
}
|
|
145
151
|
/** Tests a field bit without allocating the extra words for small entity types. */
|
package/build/fields.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.cjs","names":["getInstanceData","getMetadata","getEmInternalApi","cleanStringValue","isEntity","maybeResolveReferenceToId","maybeRequireTemporal","fail"],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Plugins observe only the first read of each field, including internal reads. Install\n * plugins before reading entities; adding one later does not replay earlier reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs first-read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * The plugin bit is set before invoking hooks so a hook may read or change its own field,\n * reentering this function without invoking the hook again.\n * A throwing hook clears both bits for this field, allowing a later access to retry it.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n if (!hasReadField(instanceData.pluginReadFields, instanceData.pluginReadFieldsExtra, index)) {\n markPluginReadField(instanceData, index, true);\n try {\n getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName);\n } catch (error) {\n markPluginReadField(instanceData, index, false);\n markApplicationReadField(entity, index, false);\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n }\n }\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if ((fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes one cold-path plugin bit, preserving other reads completed inside the callback. */\nfunction markPluginReadField(data: InstanceData, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n if (index < 32) {\n data.pluginReadFields = read ? data.pluginReadFields | bit : data.pluginReadFields & ~bit;\n } else {\n const extra = (data.pluginReadFieldsExtra ??= []);\n const word = (index >>> 5) - 1;\n extra[word] = read ? (extra[word] ?? 0) | bit : (extra[word] ?? 0) & ~bit;\n }\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,SAAS,QAAgB,WAAmB,aAA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AAiB,QAAgB,MAAsB;CAC9D,OAAQ,OAA2B,aAAa,IAAI;AACtD;;AAGA,SAAS,iBAAiB,QAAgB,MAAc,OAAqB;CAC3E,OAA4B,aAAa,IAAI,KAAK;AACpD;;AAGA,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
|
|
1
|
+
{"version":3,"file":"fields.cjs","names":["getInstanceData","getMetadata","getEmInternalApi","cleanStringValue","isEntity","maybeResolveReferenceToId","maybeRequireTemporal","fail"],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Plugins observe the first read, including internal reads, and subsequent reads if any plugin returns `\"allow\"`.\n *\n * Install plugins before reading entities; adding one later does not replay cached reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * The plugin bit is set before invoking hooks so a hook may read or change its own field,\n * reentering this function without invoking the hook again.\n * A hook returning `\"allow\"` or throwing clears both bits, so later accesses check again.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n let canCache = true;\n if (!hasReadField(instanceData.pluginReadFields, instanceData.pluginReadFieldsExtra, index)) {\n markPluginReadField(instanceData, index, true);\n try {\n canCache = getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName) !== \"allow\";\n if (!canCache) {\n markPluginReadField(instanceData, index, false);\n // A reentrant getter may have published a warm bit before the hook vetoed caching.\n markApplicationReadField(entity, index, false);\n }\n } catch (error) {\n markPluginReadField(instanceData, index, false);\n markApplicationReadField(entity, index, false);\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n }\n }\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if (canCache && (fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes one cold-path plugin bit, preserving other reads completed inside the callback. */\nfunction markPluginReadField(data: InstanceData, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n if (index < 32) {\n data.pluginReadFields = read ? data.pluginReadFields | bit : data.pluginReadFields & ~bit;\n } else {\n const extra = (data.pluginReadFieldsExtra ??= []);\n const word = (index >>> 5) - 1;\n extra[word] = read ? (extra[word] ?? 0) | bit : (extra[word] ?? 0) & ~bit;\n }\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,SAAS,QAAgB,WAAmB,aAAa,OAAY;CACnF,MAAM,eAAeA,mBAAAA,gBAAgB,MAAM;CAC3C,MAAM,QAAQ,aAAa,SAAS,iBAAiB;CACrD,IAAI,OAAO,UAAU,UAAU,cAAA,KAAK,iBAAiB,aAAa,SAAS,KAAK,GAAG,WAAW;CAE9F,KAAK,iBAAiB,QAAQ,UAAU,CAAC,IAAK,MAAM,QAAQ,SAAU,GACpE,OAAO,aAAa,KAAK;CAE3B,OAAO,UAAU,QAAQ,cAAc,WAAW,YAAY,KAAK;AACrE;;AAGA,SAAgB,kBAAkB,QAAgB,WAA4B;CAC5E,OAAO,CAAC,CAACC,uBAAAA,YAAY,MAAM,CAAC,CAAC,UAAU,UAAU,EAAE;AACrD;;AAGA,SAAgB,WAAW,QAAgB,WAA4B;CACrE,MAAM,EAAE,SAASD,mBAAAA,gBAAgB,MAAM;CACvC,IAAI,aAAa,MAAM,OAAO;CAE9B,IAAI,OAAO,aAAa,OAAO;CA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c,QAAQ,aAAa,UAAU,CAAC,cAAc,CAAC,OAAO,kBACnF,yBAAyB,QAAQ,OAAO,IAAI;CAE9C,OAAO,KAAK;AACd;;AAGA,SAAS,aAAa,OAAe,OAAsC,OAAwB;CAEjG,SADa,QAAQ,KAAK,QAAS,SAAS,UAAU,KAAK,MAAM,KACjD,MAAM,QAAQ,SAAU;AAC1C;;AAGA,SAAS,oBAAoB,MAAoB,OAAe,MAAqB;CACnF,MAAM,MAAM,MAAM,QAAQ;CAC1B,IAAI,QAAQ,IACV,KAAK,mBAAmB,OAAO,KAAK,mBAAmB,MAAM,KAAK,mBAAmB,CAAC;MACjF;EACL,MAAM,QAAS,KAAK,0BAA0B,CAAC;EAC/C,MAAM,QAAQ,UAAU,KAAK;EAC7B,MAAM,QAAQ,QAAQ,MAAM,SAAS,KAAK,OAAO,MAAM,SAAS,KAAK,CAAC;CACxE;AACF;;AAGA,SAAS,yBAAyB,QAAgB,OAAe,MAAqB;CACpF,MAAM,MAAM,MAAM,QAAQ;CAC1B,MAAM,OAAO,UAAU;CACvB,MAAM,QAAQ,iBAAiB,QAAQ,IAAI;CAC3C,iBAAiB,QAAQ,MAAM,OAAO,QAAQ,MAAM,QAAQ,CAAC,GAAG;AAClE;;AAGA,SAAS,iBAAiB,QAAgB,MAAsB;CAC9D,OAAQ,OAA2B,aAAa,IAAI;AACtD;;AAGA,SAAS,iBAAiB,QAAgB,MAAc,OAAqB;CAC3E,OAA4B,aAAa,IAAI,KAAK;AACpD;;AAGA,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
|
package/build/fields.d.cts
CHANGED
|
@@ -2,8 +2,9 @@ import { Entity } from "./Entity.cjs";
|
|
|
2
2
|
/**
|
|
3
3
|
* Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.
|
|
4
4
|
*
|
|
5
|
-
* Plugins observe
|
|
6
|
-
*
|
|
5
|
+
* Plugins observe the first read, including internal reads, and subsequent reads if any plugin returns `"allow"`.
|
|
6
|
+
*
|
|
7
|
+
* Install plugins before reading entities; adding one later does not replay cached reads.
|
|
7
8
|
* Generated getters and direct application calls are protected by default. Only ORM
|
|
8
9
|
* housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.
|
|
9
10
|
* The field name is a string because generated getters and ORM internals know its type.
|
package/build/fields.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.d.cts","names":[],"sources":["../src/fields.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"fields.d.cts","names":[],"sources":["../src/fields.ts"],"mappings":";;;;;;;;;;;wBAsBgB,SAAS,QAAQ,QAAQ,mBAAmB;;wBAY5C,kBAAkB,QAAQ,QAAQ;;wBAKlC,WAAW,QAAQ,QAAQ;;;;;;;;;;wBAmB3B,SAAS,QAAQ,QAAQ,mBAAmB;wBAwH5C,YAAY,UAAU;wBAMtB,MAAM,QAAQ"}
|
package/build/fields.d.mts
CHANGED
|
@@ -2,8 +2,9 @@ import { Entity } from "./Entity.mjs";
|
|
|
2
2
|
/**
|
|
3
3
|
* Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.
|
|
4
4
|
*
|
|
5
|
-
* Plugins observe
|
|
6
|
-
*
|
|
5
|
+
* Plugins observe the first read, including internal reads, and subsequent reads if any plugin returns `"allow"`.
|
|
6
|
+
*
|
|
7
|
+
* Install plugins before reading entities; adding one later does not replay cached reads.
|
|
7
8
|
* Generated getters and direct application calls are protected by default. Only ORM
|
|
8
9
|
* housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.
|
|
9
10
|
* The field name is a string because generated getters and ORM internals know its type.
|
package/build/fields.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.d.mts","names":[],"sources":["../src/fields.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"fields.d.mts","names":[],"sources":["../src/fields.ts"],"mappings":";;;;;;;;;;;wBAsBgB,SAAS,QAAQ,QAAQ,mBAAmB;;wBAY5C,kBAAkB,QAAQ,QAAQ;;wBAKlC,WAAW,QAAQ,QAAQ;;;;;;;;;;wBAmB3B,SAAS,QAAQ,QAAQ,mBAAmB;wBAwH5C,YAAY,UAAU;wBAMtB,MAAM,QAAQ"}
|
package/build/fields.js
CHANGED
|
@@ -10,8 +10,9 @@ import { cleanStringValue, fail } from "./utils.js";
|
|
|
10
10
|
/**
|
|
11
11
|
* Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.
|
|
12
12
|
*
|
|
13
|
-
* Plugins observe
|
|
14
|
-
*
|
|
13
|
+
* Plugins observe the first read, including internal reads, and subsequent reads if any plugin returns `"allow"`.
|
|
14
|
+
*
|
|
15
|
+
* Install plugins before reading entities; adding one later does not replay cached reads.
|
|
15
16
|
* Generated getters and direct application calls are protected by default. Only ORM
|
|
16
17
|
* housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.
|
|
17
18
|
* The field name is a string because generated getters and ORM internals know its type.
|
|
@@ -115,18 +116,23 @@ function equal(a, b) {
|
|
|
115
116
|
return false;
|
|
116
117
|
}
|
|
117
118
|
/**
|
|
118
|
-
* Performs
|
|
119
|
+
* Performs read callbacks, protection, and lazy conversion before publishing the warm-read bit.
|
|
119
120
|
*
|
|
120
121
|
* The plugin bit is set before invoking hooks so a hook may read or change its own field,
|
|
121
122
|
* reentering this function without invoking the hook again.
|
|
122
|
-
* A throwing
|
|
123
|
+
* A hook returning `"allow"` or throwing clears both bits, so later accesses check again.
|
|
123
124
|
*/
|
|
124
125
|
function readField(entity, instanceData, fieldName, isInternal, index) {
|
|
125
126
|
const { em, metadata } = instanceData;
|
|
127
|
+
let canCache = true;
|
|
126
128
|
if (!hasReadField(instanceData.pluginReadFields, instanceData.pluginReadFieldsExtra, index)) {
|
|
127
129
|
markPluginReadField(instanceData, index, true);
|
|
128
130
|
try {
|
|
129
|
-
getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName);
|
|
131
|
+
canCache = getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName) !== "allow";
|
|
132
|
+
if (!canCache) {
|
|
133
|
+
markPluginReadField(instanceData, index, false);
|
|
134
|
+
markApplicationReadField(entity, index, false);
|
|
135
|
+
}
|
|
130
136
|
} catch (error) {
|
|
131
137
|
markPluginReadField(instanceData, index, false);
|
|
132
138
|
markApplicationReadField(entity, index, false);
|
|
@@ -138,7 +144,7 @@ function readField(entity, instanceData, fieldName, isInternal, index) {
|
|
|
138
144
|
if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);
|
|
139
145
|
const { data } = instanceData;
|
|
140
146
|
if (!(fieldName in data) && !instanceData.isNewEntity) data[fieldName] = (field?.serde ?? fail(`Missing serde for ${fieldName}`)).fromRow(instanceData.rowData, instanceData.rowIndex);
|
|
141
|
-
if ((fieldName === "id" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) markApplicationReadField(entity, index, true);
|
|
147
|
+
if (canCache && (fieldName === "id" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) markApplicationReadField(entity, index, true);
|
|
142
148
|
return data[fieldName];
|
|
143
149
|
}
|
|
144
150
|
/** Tests a field bit without allocating the extra words for small entity types. */
|
package/build/fields.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.js","names":[],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Plugins observe only the first read of each field, including internal reads. Install\n * plugins before reading entities; adding one later does not replay earlier reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs first-read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * The plugin bit is set before invoking hooks so a hook may read or change its own field,\n * reentering this function without invoking the hook again.\n * A throwing hook clears both bits for this field, allowing a later access to retry it.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n if (!hasReadField(instanceData.pluginReadFields, instanceData.pluginReadFieldsExtra, index)) {\n markPluginReadField(instanceData, index, true);\n try {\n getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName);\n } catch (error) {\n markPluginReadField(instanceData, index, false);\n markApplicationReadField(entity, index, false);\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n }\n }\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if ((fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes one cold-path plugin bit, preserving other reads completed inside the callback. */\nfunction markPluginReadField(data: InstanceData, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n if (index < 32) {\n data.pluginReadFields = read ? data.pluginReadFields | bit : data.pluginReadFields & ~bit;\n } else {\n const extra = (data.pluginReadFieldsExtra ??= []);\n const word = (index >>> 5) - 1;\n extra[word] = read ? (extra[word] ?? 0) | bit : (extra[word] ?? 0) & ~bit;\n }\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,SAAgB,SAAS,QAAgB,WAAmB,aAAa,OAAY;CACnF,MAAM,eAAe,gBAAgB,MAAM;CAC3C,MAAM,QAAQ,aAAa,SAAS,iBAAiB;CACrD,IAAI,OAAO,UAAU,UAAU,KAAK,iBAAiB,aAAa,SAAS,KAAK,GAAG,WAAW;CAE9F,KAAK,iBAAiB,QAAQ,UAAU,CAAC,IAAK,MAAM,QAAQ,SAAU,GACpE,OAAO,aAAa,KAAK;CAE3B,OAAO,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,CAC3C,QAAQ,aAAa,SAAS,aAAa,QAAQ;CAK7E,KAAK,cAAc,QAAQ,aAAa,UAAU,CAAC,cAAc,CAAC,OAAO,kBACvE,yBAAyB,QAAQ,OAAO,IAAI;CAE9C,OAAO,KAAK;AACd;;AAGA,SAAS,aAAa,OAAe,OAAsC,OAAwB;CAEjG,SADa,QAAQ,KAAK,QAAS,SAAS,UAAU,KAAK,MAAM,KACjD,MAAM,QAAQ,SAAU;AAC1C;;AAGA,SAAS,oBAAoB,MAAoB,OAAe,MAAqB;CACnF,MAAM,MAAM,MAAM,QAAQ;CAC1B,IAAI,QAAQ,IACV,KAAK,mBAAmB,OAAO,KAAK,mBAAmB,MAAM,KAAK,mBAAmB,CAAC;MACjF;EACL,MAAM,QAAS,KAAK,0BAA0B,CAAC;EAC/C,MAAM,QAAQ,UAAU,KAAK;EAC7B,MAAM,QAAQ,QAAQ,MAAM,SAAS,KAAK,OAAO,MAAM,SAAS,KAAK,CAAC;CACxE;AACF;;AAGA,SAAS,yBAAyB,QAAgB,OAAe,MAAqB;CACpF,MAAM,MAAM,MAAM,QAAQ;CAC1B,MAAM,OAAO,UAAU;CACvB,MAAM,QAAQ,iBAAiB,QAAQ,IAAI;CAC3C,iBAAiB,QAAQ,MAAM,OAAO,QAAQ,MAAM,QAAQ,CAAC,GAAG;AAClE;;AAGA,SAAS,iBAAiB,QAAgB,MAAsB;CAC9D,OAAQ,OAA2B,aAAa,IAAI;AACtD;;AAGA,SAAS,iBAAiB,QAAgB,MAAc,OAAqB;CAC3E,OAA4B,aAAa,IAAI,KAAK;AACpD;;AAGA,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
|
|
1
|
+
{"version":3,"file":"fields.js","names":[],"sources":["../src/fields.ts"],"sourcesContent":["import { getInstanceData } from \"src/BaseEntity.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type Field, getMetadata } from \"src/EntityMetadata.ts\";\nimport { cleanStringValue, ensureNotDeleted, maybeResolveReferenceToId } from \"src/index.ts\";\nimport type { InstanceData } from \"src/InstanceData.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { fail } from \"src/utils.ts\";\n\ntype ReadWordName = \"__readFields\" | `__readFields${number}`;\ntype EntityReadWords = Entity & Record<ReadWordName, number>;\n\n/**\n * Returns the current value of `fieldName`, marking the entity for read locking if the field is configured.\n *\n * Plugins observe the first read, including internal reads, and subsequent reads if any plugin returns `\"allow\"`.\n *\n * Install plugins before reading entities; adding one later does not replay cached reads.\n * Generated getters and direct application calls are protected by default. Only ORM\n * housekeeping should pass `isInternal`, not domain logic in hooks, rules, or reactions.\n * The field name is a string because generated getters and ORM internals know its type.\n */\nexport function getField(entity: Entity, fieldName: string, isInternal = false): any {\n const instanceData = getInstanceData(entity);\n const index = instanceData.metadata.fieldReadIndexes[fieldName];\n if (typeof index !== \"number\") fail(`Unknown field ${instanceData.metadata.type}.${fieldName}`);\n // Direct getField calls use the same warm-read fast path as generated getters.\n if ((getFieldReadWord(entity, index >>> 5) & (1 << (index & 31))) !== 0) {\n return instanceData.data[fieldName];\n }\n return readField(entity, instanceData, fieldName, isInternal, index);\n}\n\n/** Returns whether `fieldName` is a field/column on `entity` that can be changed. */\nexport function isChangeableField(entity: Entity, fieldName: string): boolean {\n return !!getMetadata(entity).allFields[fieldName]?.serde;\n}\n\n/** Returns whether `fieldName` has been set, even if it's undefined, on `entity`. */\nexport function isFieldSet(entity: Entity, fieldName: string): boolean {\n const { data } = getInstanceData(entity);\n if (fieldName in data) return true;\n // Avoid calling `getField` on new entities because it populates the field as a side effect.\n if (entity.isNewEntity) return false;\n // We may not have converted the database column value into domain values yet.\n getField(entity, fieldName, true);\n return fieldName in data;\n}\n\n/**\n * Sets the current value of `fieldName`, this is an internal method that should\n * only be called by the code-generated setters.\n *\n * We skip any typing like `fieldName: keyof T` because this method should only be\n * called by trusted codegen anyway.\n *\n * Returns `true` if the value was changed, or `false` if it was a noop.\n */\nexport function setField(entity: Entity, fieldName: string, newValue: any): boolean {\n ensureNotDeleted(entity, \"pending\");\n const { em } = entity;\n const api = getEmInternalApi(em);\n const { rm, pluginManager, indexManager, fieldLogger, isLoadedCache } = api;\n\n // If we're flushing, only allow writes from hooks\n api.checkWritesAllowed();\n\n const instanceData = getInstanceData(entity);\n const { data, originalData, flushedData } = instanceData;\n\n // Do string sanitization\n const field = getMetadata(entity).allFields[fieldName];\n if (field.kind === \"primitive\" && field.type === \"string\" && field.sanitize !== false) {\n newValue = cleanStringValue(newValue);\n }\n\n const currentValue = getField(entity, fieldName, true);\n const isReference = field.kind === \"m2o\" || field.kind === \"poly\";\n const currentEqualsNew = fieldValueEquals(field, currentValue, newValue);\n\n // Tell any `#isLoaded` or `#value` caches that they might be stale, but only\n // after we've checked if the current value changed. Also we do it here,\n // before the \"reverting a dirty value to the original\" check below,\n // because caches might have already observed the dirty value, so would\n // still need to refresh.\n if (!currentEqualsNew) isLoadedCache.resetIsLoaded(entity, fieldName);\n\n // Check `config.setTransitions` tables while the change is still synchronous, before we change anything,\n // and record the transition for `em.flush` to run its (async) guards and reactions\n if (field.kind === \"enum\" && !currentEqualsNew) rm.queueTransition(entity, fieldName, currentValue, newValue);\n // Remember every prior reference value so `followReverseHint` can rewalk both original and transient owners.\n if (isReference && !currentEqualsNew) {\n instanceData.rememberReferenceValue(fieldName, currentValue);\n }\n\n // If a `set` occurs during the AsyncReactiveField-loop, copy the last-flushed value to flushedData.\n // Then our `pendingOperation` logic can tell \"do we need another micro-flush?\" separately\n // from our public-facing changed fields logic.\n if (flushedData) {\n if (fieldName in flushedData) {\n // We've already copied the last-micro-flush value into flushedData,\n // are we changing back to that? If so, we won't need another micro-flush.\n if (equalOrSameEntity(flushedData[fieldName], newValue)) {\n delete flushedData[fieldName];\n } else {\n // Otherwise just let data[fieldName] get the even-newer value, and keep\n // flushedData[fieldName] as the last-micro-flushed value.\n }\n } else if (!currentEqualsNew) {\n // This is the 1st rqf-loop change for this field, so let data[fieldName]\n // get the even newer value, but keep the last-micro-flushed value in flushedData.\n flushedData[fieldName] = currentValue;\n }\n }\n\n // \"Un-dirty\" our originalData if newValue is reverting to originalData\n if (fieldName in originalData) {\n if (fieldValueEquals(field, originalData[fieldName], newValue)) {\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n instanceData.markFieldClean(fieldName);\n\n fieldLogger.logSet(entity, fieldName, newValue);\n if (isReference && instanceData.getReferenceHistory(fieldName).length > 0) {\n rm.queueDownstreamReactables(entity, fieldName);\n } else {\n // For normal reverts, the field is clean again, so any pending downstream work can be removed.\n rm.dequeueDownstreamReactables(entity, fieldName);\n }\n\n return true;\n }\n }\n\n // Push this logic into a field serde type abstraction?\n if (currentEqualsNew) {\n // If we're doing `entity.field = undefined`, we'll be equal, but mark ourselves as \"set\"\n // so that defaults know to respect the intent of keeping this field undefined.\n if (!(fieldName in data)) data[fieldName] = undefined;\n return false;\n }\n\n // Only save the currentValue on the 1st change of this field\n if (!(fieldName in originalData)) {\n instanceData.markFieldDirty(fieldName, currentValue);\n }\n fieldLogger.logSet(entity, fieldName, newValue);\n rm.queueDownstreamReactables(entity, fieldName);\n\n indexManager.maybeUpdateFieldIndex(entity, fieldName, currentValue, newValue);\n\n pluginManager.beforeSetField(entity, fieldName, newValue);\n data[fieldName] = newValue;\n return true;\n}\n\nfunction fieldValueEquals(field: Field, a: unknown, b: unknown): boolean {\n // Primitive scalar sets are the common path, so avoid Date/Temporal/entity checks when both values cannot need them.\n if (field.kind !== \"m2o\" && field.kind !== \"poly\" && isNonObjectValue(a) && isNonObjectValue(b)) return a === b;\n return equalOrSameEntity(a, b);\n}\n\nfunction isNonObjectValue(value: unknown): boolean {\n return value === null || typeof value !== \"object\";\n}\n\nfunction equalOrSameEntity(a: any, b: any): boolean {\n return (\n equal(a, b) ||\n (Array.isArray(a) && Array.isArray(b) && equalArrays(a, b)) ||\n // This is kind of gross, but make sure not to compare two both-new entities\n (((isEntity(a) && !a.isNewEntity) || (isEntity(b) && !b.isNewEntity)) &&\n maybeResolveReferenceToId(a) === maybeResolveReferenceToId(b))\n );\n}\n\nexport function equalArrays(a: any[], b: any[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((_: any, i) => equal(a[i], b[i]));\n}\n\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport function equal(a: any, b: any): boolean {\n if (a === b) return true;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n if (Temporal) {\n if (a instanceof Temporal.ZonedDateTime && b instanceof Temporal.ZonedDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDateTime && b instanceof Temporal.PlainDateTime) return a.equals(b);\n if (a instanceof Temporal.PlainDate && b instanceof Temporal.PlainDate) return a.equals(b);\n }\n return false;\n}\n\n/**\n * Performs read callbacks, protection, and lazy conversion before publishing the warm-read bit.\n *\n * The plugin bit is set before invoking hooks so a hook may read or change its own field,\n * reentering this function without invoking the hook again.\n * A hook returning `\"allow\"` or throwing clears both bits, so later accesses check again.\n */\nfunction readField(\n entity: Entity,\n instanceData: InstanceData,\n fieldName: string,\n isInternal: boolean,\n index: number,\n): any {\n const { em, metadata } = instanceData;\n let canCache = true;\n if (!hasReadField(instanceData.pluginReadFields, instanceData.pluginReadFieldsExtra, index)) {\n markPluginReadField(instanceData, index, true);\n try {\n canCache = getEmInternalApi(em).pluginManager.beforeGetField(entity, fieldName) !== \"allow\";\n if (!canCache) {\n markPluginReadField(instanceData, index, false);\n // A reentrant getter may have published a warm bit before the hook vetoed caching.\n markApplicationReadField(entity, index, false);\n }\n } catch (error) {\n markPluginReadField(instanceData, index, false);\n markApplicationReadField(entity, index, false);\n // A reentrant ID getter may have cached a conversion before the outer hook failed.\n if (fieldName === \"id\") instanceData.idCache = undefined;\n throw error;\n }\n }\n\n const field = metadata.allFields[fieldName];\n if (!isInternal && field?.assertUnchanged) em.assertUnchanged(entity);\n // Hooks may replace a cached value, so inspect current storage only after they finish.\n const { data } = instanceData;\n if (!(fieldName in data) && !instanceData.isNewEntity) {\n // We may not have converted the database column value into domain values yet.\n const serde = field?.serde ?? fail(`Missing serde for ${fieldName}`);\n data[fieldName] = serde.fromRow(instanceData.rowData, instanceData.rowIndex);\n }\n // IDs are always assigned into data.id, so even their unassigned reads can stay warm.\n // Other unset new fields stay cold: inserts may supply defaults later, without a read\n // turning into an explicit `undefined` for defaults/isFieldSet.\n if (canCache && (fieldName === \"id\" || fieldName in data) && (!isInternal || !field?.assertUnchanged)) {\n markApplicationReadField(entity, index, true);\n }\n return data[fieldName];\n}\n\n/** Tests a field bit without allocating the extra words for small entity types. */\nfunction hasReadField(first: number, extra: readonly number[] | undefined, index: number): boolean {\n const word = index < 32 ? first : (extra?.[(index >>> 5) - 1] ?? 0);\n return (word & (1 << (index & 31))) !== 0;\n}\n\n/** Changes one cold-path plugin bit, preserving other reads completed inside the callback. */\nfunction markPluginReadField(data: InstanceData, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n if (index < 32) {\n data.pluginReadFields = read ? data.pluginReadFields | bit : data.pluginReadFields & ~bit;\n } else {\n const extra = (data.pluginReadFieldsExtra ??= []);\n const word = (index >>> 5) - 1;\n extra[word] = read ? (extra[word] ?? 0) | bit : (extra[word] ?? 0) & ~bit;\n }\n}\n\n/** Changes the entity's warm-read bit without disturbing other fields in that word. */\nfunction markApplicationReadField(entity: Entity, index: number, read: boolean): void {\n const bit = 1 << (index & 31);\n const word = index >>> 5;\n const value = getFieldReadWord(entity, word);\n setFieldReadWord(entity, word, read ? value | bit : value & ~bit);\n}\n\n/** Reads the same warm-read words used by generated getters. */\nfunction getFieldReadWord(entity: Entity, word: number): number {\n return (entity as EntityReadWords)[readWordName(word)];\n}\n\n/** Updates a warm-read word without exposing an entity API. */\nfunction setFieldReadWord(entity: Entity, word: number, value: number): void {\n (entity as EntityReadWords)[readWordName(word)] = value;\n}\n\n/** Matches the literal names emitted by codegen; only shared reads construct a word name. */\nfunction readWordName(word: number): ReadWordName {\n return word === 0 ? \"__readFields\" : `__readFields${word}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,SAAS,QAAgB,WAAmB,aAAa,OAAY;CACnF,MAAM,eAAe,gBAAgB,MAAM;CAC3C,MAAM,QAAQ,aAAa,SAAS,iBAAiB;CACrD,IAAI,OAAO,UAAU,UAAU,KAAK,iBAAiB,aAAa,SAAS,KAAK,GAAG,WAAW;CAE9F,KAAK,iBAAiB,QAAQ,UAAU,CAAC,IAAK,MAAM,QAAQ,SAAU,GACpE,OAAO,aAAa,KAAK;CAE3B,OAAO,UAAU,QAAQ,cAAc,WAAW,YAAY,KAAK;AACrE;;AAGA,SAAgB,kBAAkB,QAAgB,WAA4B;CAC5E,OAAO,CAAC,CAAC,YAAY,MAAM,CAAC,CAAC,UAAU,UAAU,EAAE;AACrD;;AAGA,SAAgB,WAAW,QAAgB,WAA4B;CACrE,MAAM,EAAE,SAAS,gBAAgB,MAAM;CACvC,IAAI,aAAa,MAAM,OAAO;CAE9B,IAAI,OAAO,aAAa,OAAO;CAE/B,SAAS,QAAQ,WAAW,IAAI;CAChC,OAAO,aAAa;AACtB;;;;;;;;;;AAWA,SAAgB,SAAS,QAAgB,WAAmB,UAAwB;CAClF,iBAAiB,QAAQ,SAAS;CAClC,MAAM,EAAE,OAAO;CACf,MAAM,MAAM,iBAAiB,EAAE;CAC/B,MAAM,EAAE,IAAI,eAAe,cAAc,aAAa,kBAAkB;CAGxE,IAAI,mBAAmB;CAEvB,MAAM,eAAe,gBAAgB,MAAM;CAC3C,MAAM,EAAE,MAAM,cAAc,gBAAgB;CAG5C,MAAM,QAAQ,YAAY,MAAM,CAAC,CAAC,UAAU;CAC5C,IAAI,MAAM,SAAS,eAAe,MAAM,SAAS,YAAY,MAAM,aAAa,OAC9E,WAAW,iBAAiB,QAAQ;CAGtC,MAAM,eAAe,SAAS,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AAM,MAAM,MAAM,QAAQ;CAC1B,MAAM,OAAO,UAAU;CACvB,MAAM,QAAQ,iBAAiB,QAAQ,IAAI;CAC3C,iBAAiB,QAAQ,MAAM,OAAO,QAAQ,MAAM,QAAQ,CAAC,GAAG;AAClE;;AAGA,SAAS,iBAAiB,QAAgB,MAAsB;CAC9D,OAAQ,OAA2B,aAAa,IAAI;AACtD;;AAGA,SAAS,iBAAiB,QAAgB,MAAc,OAAqB;CAC3E,OAA4B,aAAa,IAAI,KAAK;AACpD;;AAGA,SAAS,aAAa,MAA4B;CAChD,OAAO,SAAS,IAAI,iBAAiB,eAAe;AACtD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "joist-core",
|
|
3
|
-
"version": "2.5.0-next.
|
|
3
|
+
"version": "2.5.0-next.12",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"build"
|
|
43
43
|
],
|
|
44
44
|
"peerDependencies": {
|
|
45
|
-
"joist-utils": "2.5.0-next.
|
|
45
|
+
"joist-utils": "2.5.0-next.12"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
48
|
"ansis": "^4.4.0",
|