joist-core 2.5.0-next.21 → 2.5.0-next.23

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.
Files changed (205) hide show
  1. package/build/BaseEntity.cjs +5 -2
  2. package/build/BaseEntity.cjs.map +1 -1
  3. package/build/BaseEntity.d.cts +2 -0
  4. package/build/BaseEntity.d.cts.map +1 -1
  5. package/build/BaseEntity.d.mts +2 -0
  6. package/build/BaseEntity.d.mts.map +1 -1
  7. package/build/BaseEntity.js +5 -2
  8. package/build/BaseEntity.js.map +1 -1
  9. package/build/Entity.cjs.map +1 -1
  10. package/build/Entity.d.cts +6 -0
  11. package/build/Entity.d.cts.map +1 -1
  12. package/build/Entity.d.mts +6 -0
  13. package/build/Entity.d.mts.map +1 -1
  14. package/build/Entity.js.map +1 -1
  15. package/build/EntityManager.cjs +83 -22
  16. package/build/EntityManager.cjs.map +1 -1
  17. package/build/EntityManager.d.cts +7 -4
  18. package/build/EntityManager.d.cts.map +1 -1
  19. package/build/EntityManager.d.mts +7 -4
  20. package/build/EntityManager.d.mts.map +1 -1
  21. package/build/EntityManager.js +83 -22
  22. package/build/EntityManager.js.map +1 -1
  23. package/build/InstanceData.cjs +2 -2
  24. package/build/InstanceData.cjs.map +1 -1
  25. package/build/InstanceData.d.cts +2 -2
  26. package/build/InstanceData.d.mts +2 -2
  27. package/build/InstanceData.js +2 -2
  28. package/build/InstanceData.js.map +1 -1
  29. package/build/PluginManager.cjs +6 -0
  30. package/build/PluginManager.cjs.map +1 -1
  31. package/build/PluginManager.d.cts +10 -0
  32. package/build/PluginManager.d.cts.map +1 -1
  33. package/build/PluginManager.d.mts +10 -0
  34. package/build/PluginManager.d.mts.map +1 -1
  35. package/build/PluginManager.js +6 -0
  36. package/build/PluginManager.js.map +1 -1
  37. package/build/clientIds.cjs +47 -0
  38. package/build/clientIds.cjs.map +1 -0
  39. package/build/clientIds.d.cts +26 -0
  40. package/build/clientIds.d.cts.map +1 -0
  41. package/build/clientIds.d.mts +26 -0
  42. package/build/clientIds.d.mts.map +1 -0
  43. package/build/clientIds.js +42 -0
  44. package/build/clientIds.js.map +1 -0
  45. package/build/configure.cjs +3 -0
  46. package/build/configure.cjs.map +1 -1
  47. package/build/configure.d.cts.map +1 -1
  48. package/build/configure.d.mts.map +1 -1
  49. package/build/configure.js +3 -0
  50. package/build/configure.js.map +1 -1
  51. package/build/getProperties.cjs +4 -1
  52. package/build/getProperties.cjs.map +1 -1
  53. package/build/getProperties.js +4 -1
  54. package/build/getProperties.js.map +1 -1
  55. package/build/index.cjs +15 -4
  56. package/build/index.cjs.map +1 -1
  57. package/build/index.d.cts +9 -7
  58. package/build/index.d.cts.map +1 -1
  59. package/build/index.d.mts +9 -7
  60. package/build/index.d.mts.map +1 -1
  61. package/build/index.js +11 -5
  62. package/build/index.js.map +1 -1
  63. package/build/keys.cjs +4 -0
  64. package/build/keys.cjs.map +1 -1
  65. package/build/keys.d.cts.map +1 -1
  66. package/build/keys.d.mts.map +1 -1
  67. package/build/keys.js +4 -0
  68. package/build/keys.js.map +1 -1
  69. package/build/newTestInstance.cjs +8 -8
  70. package/build/newTestInstance.cjs.map +1 -1
  71. package/build/newTestInstance.d.cts.map +1 -1
  72. package/build/newTestInstance.d.mts.map +1 -1
  73. package/build/newTestInstance.js +8 -8
  74. package/build/newTestInstance.js.map +1 -1
  75. package/build/queries/ConditionBuilder.cjs +2 -1
  76. package/build/queries/ConditionBuilder.cjs.map +1 -1
  77. package/build/queries/ConditionBuilder.d.cts +9 -1
  78. package/build/queries/ConditionBuilder.d.cts.map +1 -1
  79. package/build/queries/ConditionBuilder.d.mts +9 -1
  80. package/build/queries/ConditionBuilder.d.mts.map +1 -1
  81. package/build/queries/ConditionBuilder.js +2 -2
  82. package/build/queries/ConditionBuilder.js.map +1 -1
  83. package/build/queries/conditions.cjs.map +1 -1
  84. package/build/queries/conditions.d.cts +4 -1
  85. package/build/queries/conditions.d.cts.map +1 -1
  86. package/build/queries/conditions.d.mts +4 -1
  87. package/build/queries/conditions.d.mts.map +1 -1
  88. package/build/queries/conditions.js.map +1 -1
  89. package/build/queries/sql/Expr.cjs +79 -134
  90. package/build/queries/sql/Expr.cjs.map +1 -1
  91. package/build/queries/sql/Expr.d.cts +26 -34
  92. package/build/queries/sql/Expr.d.cts.map +1 -1
  93. package/build/queries/sql/Expr.d.mts +26 -34
  94. package/build/queries/sql/Expr.d.mts.map +1 -1
  95. package/build/queries/sql/Expr.js +80 -133
  96. package/build/queries/sql/Expr.js.map +1 -1
  97. package/build/queries/sql/ParsedQuery.cjs +119 -0
  98. package/build/queries/sql/ParsedQuery.cjs.map +1 -0
  99. package/build/queries/sql/ParsedQuery.d.cts +105 -0
  100. package/build/queries/sql/ParsedQuery.d.cts.map +1 -0
  101. package/build/queries/sql/ParsedQuery.d.mts +105 -0
  102. package/build/queries/sql/ParsedQuery.d.mts.map +1 -0
  103. package/build/queries/sql/ParsedQuery.js +116 -0
  104. package/build/queries/sql/ParsedQuery.js.map +1 -0
  105. package/build/queries/sql/ParsedSqlExpression.cjs +74 -0
  106. package/build/queries/sql/ParsedSqlExpression.cjs.map +1 -0
  107. package/build/queries/sql/ParsedSqlExpression.d.cts +65 -0
  108. package/build/queries/sql/ParsedSqlExpression.d.cts.map +1 -0
  109. package/build/queries/sql/ParsedSqlExpression.d.mts +65 -0
  110. package/build/queries/sql/ParsedSqlExpression.d.mts.map +1 -0
  111. package/build/queries/sql/ParsedSqlExpression.js +69 -0
  112. package/build/queries/sql/ParsedSqlExpression.js.map +1 -0
  113. package/build/queries/sql/Tables.cjs +61 -46
  114. package/build/queries/sql/Tables.cjs.map +1 -1
  115. package/build/queries/sql/Tables.d.cts.map +1 -1
  116. package/build/queries/sql/Tables.d.mts.map +1 -1
  117. package/build/queries/sql/Tables.js +61 -46
  118. package/build/queries/sql/Tables.js.map +1 -1
  119. package/build/queries/sql/execute.cjs +45 -62
  120. package/build/queries/sql/execute.cjs.map +1 -1
  121. package/build/queries/sql/execute.d.cts +4 -3
  122. package/build/queries/sql/execute.d.cts.map +1 -1
  123. package/build/queries/sql/execute.d.mts +4 -3
  124. package/build/queries/sql/execute.d.mts.map +1 -1
  125. package/build/queries/sql/execute.js +47 -64
  126. package/build/queries/sql/execute.js.map +1 -1
  127. package/build/queries/sql/expressions/arrayAgg.cjs +14 -15
  128. package/build/queries/sql/expressions/arrayAgg.cjs.map +1 -1
  129. package/build/queries/sql/expressions/arrayAgg.d.cts +3 -2
  130. package/build/queries/sql/expressions/arrayAgg.d.cts.map +1 -1
  131. package/build/queries/sql/expressions/arrayAgg.d.mts +3 -2
  132. package/build/queries/sql/expressions/arrayAgg.d.mts.map +1 -1
  133. package/build/queries/sql/expressions/arrayAgg.js +15 -16
  134. package/build/queries/sql/expressions/arrayAgg.js.map +1 -1
  135. package/build/queries/sql/expressions/case.cjs +11 -16
  136. package/build/queries/sql/expressions/case.cjs.map +1 -1
  137. package/build/queries/sql/expressions/case.d.cts +3 -2
  138. package/build/queries/sql/expressions/case.d.cts.map +1 -1
  139. package/build/queries/sql/expressions/case.d.mts +3 -2
  140. package/build/queries/sql/expressions/case.d.mts.map +1 -1
  141. package/build/queries/sql/expressions/case.js +11 -16
  142. package/build/queries/sql/expressions/case.js.map +1 -1
  143. package/build/queries/sql/expressions/coalesce.cjs.map +1 -1
  144. package/build/queries/sql/expressions/coalesce.d.cts +3 -2
  145. package/build/queries/sql/expressions/coalesce.d.cts.map +1 -1
  146. package/build/queries/sql/expressions/coalesce.d.mts +3 -2
  147. package/build/queries/sql/expressions/coalesce.d.mts.map +1 -1
  148. package/build/queries/sql/expressions/coalesce.js.map +1 -1
  149. package/build/queries/sql/expressions/expression.cjs +10 -12
  150. package/build/queries/sql/expressions/expression.cjs.map +1 -1
  151. package/build/queries/sql/expressions/expression.d.cts +4 -3
  152. package/build/queries/sql/expressions/expression.d.cts.map +1 -1
  153. package/build/queries/sql/expressions/expression.d.mts +4 -3
  154. package/build/queries/sql/expressions/expression.d.mts.map +1 -1
  155. package/build/queries/sql/expressions/expression.js +11 -13
  156. package/build/queries/sql/expressions/expression.js.map +1 -1
  157. package/build/queries/sql/expressions/greatest.cjs.map +1 -1
  158. package/build/queries/sql/expressions/greatest.d.cts +3 -2
  159. package/build/queries/sql/expressions/greatest.d.cts.map +1 -1
  160. package/build/queries/sql/expressions/greatest.d.mts +3 -2
  161. package/build/queries/sql/expressions/greatest.d.mts.map +1 -1
  162. package/build/queries/sql/expressions/greatest.js.map +1 -1
  163. package/build/queries/sql/expressions/least.cjs.map +1 -1
  164. package/build/queries/sql/expressions/least.d.cts +3 -2
  165. package/build/queries/sql/expressions/least.d.cts.map +1 -1
  166. package/build/queries/sql/expressions/least.d.mts +3 -2
  167. package/build/queries/sql/expressions/least.d.mts.map +1 -1
  168. package/build/queries/sql/expressions/least.js.map +1 -1
  169. package/build/queries/sql/expressions/nullIf.cjs.map +1 -1
  170. package/build/queries/sql/expressions/nullIf.d.cts +3 -2
  171. package/build/queries/sql/expressions/nullIf.d.cts.map +1 -1
  172. package/build/queries/sql/expressions/nullIf.d.mts +3 -2
  173. package/build/queries/sql/expressions/nullIf.d.mts.map +1 -1
  174. package/build/queries/sql/expressions/nullIf.js.map +1 -1
  175. package/build/queries/sql/query.cjs +168 -381
  176. package/build/queries/sql/query.cjs.map +1 -1
  177. package/build/queries/sql/query.d.cts +44 -45
  178. package/build/queries/sql/query.d.cts.map +1 -1
  179. package/build/queries/sql/query.d.mts +44 -45
  180. package/build/queries/sql/query.d.mts.map +1 -1
  181. package/build/queries/sql/query.js +172 -383
  182. package/build/queries/sql/query.js.map +1 -1
  183. package/build/queries/sql/renderSql.cjs +321 -0
  184. package/build/queries/sql/renderSql.cjs.map +1 -0
  185. package/build/queries/sql/renderSql.d.cts +14 -0
  186. package/build/queries/sql/renderSql.d.cts.map +1 -0
  187. package/build/queries/sql/renderSql.d.mts +14 -0
  188. package/build/queries/sql/renderSql.d.mts.map +1 -0
  189. package/build/queries/sql/renderSql.js +318 -0
  190. package/build/queries/sql/renderSql.js.map +1 -0
  191. package/build/resurrection.cjs +5 -3
  192. package/build/resurrection.cjs.map +1 -1
  193. package/build/resurrection.d.cts.map +1 -1
  194. package/build/resurrection.d.mts.map +1 -1
  195. package/build/resurrection.js +5 -3
  196. package/build/resurrection.js.map +1 -1
  197. package/build/upsert.cjs +6 -3
  198. package/build/upsert.cjs.map +1 -1
  199. package/build/upsert.d.cts +6 -3
  200. package/build/upsert.d.cts.map +1 -1
  201. package/build/upsert.d.mts +6 -3
  202. package/build/upsert.d.mts.map +1 -1
  203. package/build/upsert.js +6 -3
  204. package/build/upsert.js.map +1 -1
  205. package/package.json +2 -2
@@ -39,6 +39,10 @@ var BaseEntity = class {
39
39
  get fullNonReactiveAccess() {
40
40
  return this;
41
41
  }
42
+ /** The stable EM-local alias, independent of database identity and debug formatting. */
43
+ get $clientId() {
44
+ return this.__data.clientId;
45
+ }
42
46
  /** @returns the entity's id, always untagged, or a runtime error if it's unassigned. */
43
47
  get idUntagged() {
44
48
  return require_keys.deTagId(require_EntityMetadata.getMetadata(this), this.id);
@@ -94,8 +98,7 @@ var BaseEntity = class {
94
98
  function toStringWithPrefix(meta, entity, prefix) {
95
99
  let result = prefix;
96
100
  const data = getInstanceData(entity);
97
- const createId = data.createId;
98
- if (createId) result += `#${createId}`;
101
+ if (data.isOrWasNew && data.clientId) result += data.clientId.slice(meta.tagName.length);
99
102
  const dbId = entity.idTaggedMaybe;
100
103
  if (data.pendingOperation !== "insert" && dbId) result += `:${require_keys.keyToNumber(meta, dbId)}`;
101
104
  return result;
@@ -1 +1 @@
1
- {"version":3,"file":"BaseEntity.cjs","names":["deTagId","getMetadata","keyToNumber","InstanceData","hasVisibilityHook","isInTrustedContext"],"sources":["../src/BaseEntity.ts"],"sourcesContent":["import { type IdType } from \"src/Entity.ts\";\nimport { hasVisibilityHook } from \"src/EntityManager.ts\";\nimport {\n type Entity,\n type EntityManager,\n type EntityMetadata,\n InstanceData,\n type TaggedId,\n deTagId,\n getMetadata,\n keyToNumber,\n} from \"src/index.ts\";\nimport { isInTrustedContext } from \"src/trusted.ts\";\n\n// getProperties deletes its throwaway entity's own fields so callback access to `this` hits a guard proxy.\n// That includes these non-enumerable words, so they must be configurable (deletable).\nconst readWordDescriptor: PropertyDescriptor = { value: 0, enumerable: false, writable: true, configurable: true };\nconst trustedReadWordDescriptors: PropertyDescriptor[] = [];\n\n/**\n * Returns the internal `__data` tracking field for `entity`.\n *\n * This should be treated as an internal API and may change without notice.\n */\nexport function getInstanceData(entity: Entity): InstanceData {\n return BaseEntity.getInstanceData(entity);\n}\n\n/**\n * The base class for all entities.\n *\n * Currently, this just adds the `.load(lensFn)` method for declarative reference traversal.\n */\nexport abstract class BaseEntity<EM extends EntityManager, I extends IdType = IdType> implements Entity {\n public static getInstanceData(entity: Entity): InstanceData {\n return (entity as BaseEntity<any>).__data;\n }\n\n // We use a protected field so that subclass getters can easily access `this.__data.relations`.\n protected readonly __data!: InstanceData;\n /** First-read completion bits; extra words are declared by each generated root type as needed. */\n declare protected __readFields: number;\n\n /** The single-arg constructor is our psuedo-public API that can only be called by the EntityManager. */\n constructor(em: EntityManager);\n constructor(em: EntityManager, isNew?: boolean) {\n if (isNew === undefined) {\n throw new Error(\"Entities must be constructed by calling em.create or em.load\");\n }\n // This code path won't be reused for real entities, as they go through the `newEntity`\n // construction process that lazifies the relations.\n baseEntityCstr(em, this, isNew);\n }\n\n // This gives rules a way to access the fully typed object instead of their Reacted view.\n // And we make it public so that a function that takes Reacted<...> can accept a Loaded<...>\n // that sufficiently overlaps.\n get fullNonReactiveAccess(): this {\n return this;\n }\n\n /** @returns the entity's id, tagged/untagged based on your config, or a runtime error if it's new/unassigned. */\n abstract id: I;\n\n /** @returns the entity's, tagged/untagged based on your config, or undefined if it's new/unassigned. */\n abstract get idMaybe(): I | undefined;\n\n /** @returns the entity's id, always tagged, or a runtime error if it's new/unassigned. */\n abstract idTagged: TaggedId;\n\n /** @returns the entity's id, always tagged, or undefined if it's new/unassigned. */\n abstract get idTaggedMaybe(): TaggedId | undefined;\n\n /** @returns the entity's id, always untagged, or a runtime error if it's unassigned. */\n get idUntagged(): string {\n return deTagId(getMetadata(this), this.id);\n }\n\n abstract set(opts: unknown): void;\n\n /**\n * Similar to `set` but applies \"Partial API\" semantics, i.e. `null` means unset and `undefined` means don't change.\n */\n abstract setPartial(opts: unknown): void;\n\n /**\n * Similar to `set` but applies \"Partial API\" semantics, i.e. `null` means unset and `undefined` means don't change.\n */\n abstract setDeepPartial(opts: unknown): Promise<void>;\n\n /**\n * Returns whether the entity is new.\n *\n * This is not just `this.id === undefined`, because just assigning an id doesn't mean the entity\n * is no longer new; this only flips to `false` after the `flush` transaction has been committed.\n */\n get isNewEntity(): boolean {\n return this.__data.isNewEntity;\n }\n\n get isDeletedEntity(): boolean {\n return this.__data.isDeletedEntity;\n }\n\n get isDirtyEntity(): boolean {\n return this.__data.isDirtyEntity;\n }\n\n toString(): string {\n const meta = getMetadata(this);\n return toStringWithPrefix(meta, this, meta.type);\n }\n\n toTaggedString(): string {\n const meta = getMetadata(this);\n return toStringWithPrefix(meta, this, meta.tagName);\n }\n\n public get em(): EM {\n return this.__data.em as EM;\n }\n\n /**\n * A very simple toJSON that just returns the id.\n *\n * This is for security reasons, to avoid accidentally logging sensitive data; you\n * can specify more fields, and potentially nested return data, by using passing\n * a {@link JsonHint} to `toJSON`.\n */\n public toJSON(): object {\n return { id: this.idMaybe || null };\n }\n\n [Symbol.toStringTag](): string {\n return this.toString();\n }\n\n /**\n * Hooks into node's `console.log` to avoid sprawling output of our relations/internal state.\n *\n * See https://nodejs.org/api/util.html#custom-inspection-functions-on-objects.\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return this.toString();\n }\n\n /** A bag of non-persisted state, typically for flags that control business logic behavior. */\n declare readonly transientFields: Record<string, unknown>;\n}\n\nfunction toStringWithPrefix(meta: EntityMetadata, entity: Entity, prefix: string): string {\n // Start with `Author` or `a`, depending on the caller\n let result = prefix;\n // Add `#1` if this is an em.create-d entity\n const data = getInstanceData(entity);\n const createId = data.createId;\n if (createId) {\n result += `#${createId}`;\n }\n // Add the `:1` but only after our flush is complete, otherwise the id is\n // internally assigned but not really flushed/committed to the db yet\n const dbId = entity.idTaggedMaybe;\n if (data.pendingOperation !== \"insert\" && dbId) {\n // Strip the tag because we add back the entity prefix\n result += `:${keyToNumber(meta, dbId)}`;\n }\n return result;\n}\n\n/**\n * The constructor logic for `BaseEntity` but exposed so that `newEntity` can use it too\n * on its `Object.create`-d instances.\n */\nexport function baseEntityCstr(em: EntityManager, entity: BaseEntity<any, any>, isNew: boolean): void {\n const data = new InstanceData(em, entity, (entity.constructor as any).metadata, isNew);\n // This makes it non-enumerable to avoid Jest/recursive things tripping over it\n Object.defineProperty(entity, \"__data\", { value: data, enumerable: false, writable: false, configurable: false });\n // Constructors are bypassed for real entities, so initialize every needed word here,\n // in the same order for the entire inheritance family. Reusing the descriptor avoids per-entity descriptor objects.\n for (let word = 0; word < data.metadata.fieldReadWordCount; word++) {\n Object.defineProperty(entity, word === 0 ? \"__readFields\" : `__readFields${word}`, readWordDescriptor);\n }\n if (hasVisibilityHook(entity)) useTrustedReadCache(entity);\n}\n\n/** Replaces the __readFields fields with getters/setters that always return 0 for untrusted reads, so they are always access checked. */\nexport function useTrustedReadCache(entity: Entity): void {\n const data = getInstanceData(entity);\n if (data.trustedReadFields) return;\n data.trustedReadFields = [];\n for (let word = 0; word < data.metadata.fieldReadWordCount; word++) {\n const descriptor = (trustedReadWordDescriptors[word] ??= {\n configurable: true,\n enumerable: false,\n get: function (this: Entity): number {\n return isInTrustedContext() ? (getInstanceData(this).trustedReadFields![word] ?? 0) : 0;\n },\n set: function (this: Entity, value: number): void {\n if (isInTrustedContext()) getInstanceData(this).trustedReadFields![word] = value;\n },\n });\n Object.defineProperty(entity, word === 0 ? \"__readFields\" : `__readFields${word}`, descriptor);\n }\n}\n"],"mappings":";;;;;;;;;AAgBA,MAAM,qBAAyC;CAAE,OAAO;C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K;CACtB,IAAI,UACF,UAAU,IAAI;CAIhB,MAAM,OAAO,OAAO;CACpB,IAAI,KAAK,qBAAqB,YAAY,MAExC,UAAU,IAAIC,aAAAA,YAAY,MAAM,IAAI;CAEtC,OAAO;AACT;;;;;AAMA,SAAgB,eAAe,IAAmB,QAA8B,OAAsB;CACpG,MAAM,OAAO,IAAIC,qBAAAA,aAAa,IAAI,QAAS,OAAO,YAAoB,UAAU,KAAK;CAErF,OAAO,eAAe,QAAQ,UAAU;EAAE,OAAO;EAAM,YAAY;EAAO,UAAU;EAAO,cAAc;CAAM,CAAC;CAGhH,KAAK,IAAI,OAAO,GAAG,OAAO,KAAK,SAAS,oBAAoB,QAC1D,OAAO,eAAe,QAAQ,SAAS,IAAI,iBAAiB,eAAe,QAAQ,kBAAkB;CAEvG,IAAIC,sBAAAA,kBAAkB,MAAM,GAAG,oBAAoB,MAAM;AAC3D;;AAGA,SAAgB,oBAAoB,QAAsB;CACxD,MAAM,OAAO,gBAAgB,MAAM;CACnC,IAAI,KAAK,mBAAmB;CAC5B,KAAK,oBAAoB,CAAC;CAC1B,KAAK,IAAI,OAAO,GAAG,OAAO,KAAK,SAAS,oBAAoB,QAAQ;EAClE,MAAM,aAAc,2BAA2B,UAAU;GACvD,cAAc;GACd,YAAY;GACZ,KAAK,WAAgC;IACnC,OAAOC,gBAAAA,mBAAmB,IAAK,gBAAgB,IAAI,CAAC,CAAC,kBAAmB,SAAS,IAAK;GACxF;GACA,KAAK,SAAwB,OAAqB;IAChD,IAAIA,gBAAAA,mBAAmB,GAAG,gBAAgB,IAAI,CAAC,CAAC,kBAAmB,QAAQ;GAC7E;EACF;EACA,OAAO,eAAe,QAAQ,SAAS,IAAI,iBAAiB,eAAe,QAAQ,UAAU;CAC/F;AACF"}
1
+ {"version":3,"file":"BaseEntity.cjs","names":["deTagId","getMetadata","keyToNumber","InstanceData","hasVisibilityHook","isInTrustedContext"],"sources":["../src/BaseEntity.ts"],"sourcesContent":["import { type IdType } from \"src/Entity.ts\";\nimport { hasVisibilityHook } from \"src/EntityManager.ts\";\nimport {\n type Entity,\n type EntityManager,\n type EntityMetadata,\n InstanceData,\n type TaggedId,\n deTagId,\n getMetadata,\n keyToNumber,\n} from \"src/index.ts\";\nimport { isInTrustedContext } from \"src/trusted.ts\";\n\n// getProperties deletes its throwaway entity's own fields so callback access to `this` hits a guard proxy.\n// That includes these non-enumerable words, so they must be configurable (deletable).\nconst readWordDescriptor: PropertyDescriptor = { value: 0, enumerable: false, writable: true, configurable: true };\nconst trustedReadWordDescriptors: PropertyDescriptor[] = [];\n\n/**\n * Returns the internal `__data` tracking field for `entity`.\n *\n * This should be treated as an internal API and may change without notice.\n */\nexport function getInstanceData(entity: Entity): InstanceData {\n return BaseEntity.getInstanceData(entity);\n}\n\n/**\n * The base class for all entities.\n *\n * Currently, this just adds the `.load(lensFn)` method for declarative reference traversal.\n */\nexport abstract class BaseEntity<EM extends EntityManager, I extends IdType = IdType> implements Entity {\n public static getInstanceData(entity: Entity): InstanceData {\n return (entity as BaseEntity<any>).__data;\n }\n\n // We use a protected field so that subclass getters can easily access `this.__data.relations`.\n protected readonly __data!: InstanceData;\n /** First-read completion bits; extra words are declared by each generated root type as needed. */\n declare protected __readFields: number;\n\n /** The single-arg constructor is our psuedo-public API that can only be called by the EntityManager. */\n constructor(em: EntityManager);\n constructor(em: EntityManager, isNew?: boolean) {\n if (isNew === undefined) {\n throw new Error(\"Entities must be constructed by calling em.create or em.load\");\n }\n // This code path won't be reused for real entities, as they go through the `newEntity`\n // construction process that lazifies the relations.\n baseEntityCstr(em, this, isNew);\n }\n\n // This gives rules a way to access the fully typed object instead of their Reacted view.\n // And we make it public so that a function that takes Reacted<...> can accept a Loaded<...>\n // that sufficiently overlaps.\n get fullNonReactiveAccess(): this {\n return this;\n }\n\n /** @returns the entity's id, tagged/untagged based on your config, or a runtime error if it's new/unassigned. */\n abstract id: I;\n\n /** @returns the entity's, tagged/untagged based on your config, or undefined if it's new/unassigned. */\n abstract get idMaybe(): I | undefined;\n\n /** @returns the entity's id, always tagged, or a runtime error if it's new/unassigned. */\n abstract idTagged: TaggedId;\n\n /** @returns the entity's id, always tagged, or undefined if it's new/unassigned. */\n abstract get idTaggedMaybe(): TaggedId | undefined;\n\n /** The stable EM-local alias, independent of database identity and debug formatting. */\n get $clientId(): TaggedId | undefined {\n return this.__data.clientId;\n }\n\n /** @returns the entity's id, always untagged, or a runtime error if it's unassigned. */\n get idUntagged(): string {\n return deTagId(getMetadata(this), this.id);\n }\n\n abstract set(opts: unknown): void;\n\n /**\n * Similar to `set` but applies \"Partial API\" semantics, i.e. `null` means unset and `undefined` means don't change.\n */\n abstract setPartial(opts: unknown): void;\n\n /**\n * Similar to `set` but applies \"Partial API\" semantics, i.e. `null` means unset and `undefined` means don't change.\n */\n abstract setDeepPartial(opts: unknown): Promise<void>;\n\n /**\n * Returns whether the entity is new.\n *\n * This is not just `this.id === undefined`, because just assigning an id doesn't mean the entity\n * is no longer new; this only flips to `false` after the `flush` transaction has been committed.\n */\n get isNewEntity(): boolean {\n return this.__data.isNewEntity;\n }\n\n get isDeletedEntity(): boolean {\n return this.__data.isDeletedEntity;\n }\n\n get isDirtyEntity(): boolean {\n return this.__data.isDirtyEntity;\n }\n\n toString(): string {\n const meta = getMetadata(this);\n return toStringWithPrefix(meta, this, meta.type);\n }\n\n toTaggedString(): string {\n const meta = getMetadata(this);\n return toStringWithPrefix(meta, this, meta.tagName);\n }\n\n public get em(): EM {\n return this.__data.em as EM;\n }\n\n /**\n * A very simple toJSON that just returns the id.\n *\n * This is for security reasons, to avoid accidentally logging sensitive data; you\n * can specify more fields, and potentially nested return data, by using passing\n * a {@link JsonHint} to `toJSON`.\n */\n public toJSON(): object {\n return { id: this.idMaybe || null };\n }\n\n [Symbol.toStringTag](): string {\n return this.toString();\n }\n\n /**\n * Hooks into node's `console.log` to avoid sprawling output of our relations/internal state.\n *\n * See https://nodejs.org/api/util.html#custom-inspection-functions-on-objects.\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return this.toString();\n }\n\n /** A bag of non-persisted state, typically for flags that control business logic behavior. */\n declare readonly transientFields: Record<string, unknown>;\n}\n\nfunction toStringWithPrefix(meta: EntityMetadata, entity: Entity, prefix: string): string {\n // Start with `Author` or `a`, depending on the caller\n let result = prefix;\n // Add `#1` if this is an em.create-d entity\n const data = getInstanceData(entity);\n if (data.isOrWasNew && data.clientId) {\n result += data.clientId.slice(meta.tagName.length);\n }\n // Add the `:1` but only after our flush is complete, otherwise the id is\n // internally assigned but not really flushed/committed to the db yet\n const dbId = entity.idTaggedMaybe;\n if (data.pendingOperation !== \"insert\" && dbId) {\n // Strip the tag because we add back the entity prefix\n result += `:${keyToNumber(meta, dbId)}`;\n }\n return result;\n}\n\n/**\n * The constructor logic for `BaseEntity` but exposed so that `newEntity` can use it too\n * on its `Object.create`-d instances.\n */\nexport function baseEntityCstr(em: EntityManager, entity: BaseEntity<any, any>, isNew: boolean): void {\n const data = new InstanceData(em, entity, (entity.constructor as any).metadata, isNew);\n // This makes it non-enumerable to avoid Jest/recursive things tripping over it\n Object.defineProperty(entity, \"__data\", { value: data, enumerable: false, writable: false, configurable: false });\n // Constructors are bypassed for real entities, so initialize every needed word here,\n // in the same order for the entire inheritance family. Reusing the descriptor avoids per-entity descriptor objects.\n for (let word = 0; word < data.metadata.fieldReadWordCount; word++) {\n Object.defineProperty(entity, word === 0 ? \"__readFields\" : `__readFields${word}`, readWordDescriptor);\n }\n if (hasVisibilityHook(entity)) useTrustedReadCache(entity);\n}\n\n/** Replaces the __readFields fields with getters/setters that always return 0 for untrusted reads, so they are always access checked. */\nexport function useTrustedReadCache(entity: Entity): void {\n const data = getInstanceData(entity);\n if (data.trustedReadFields) return;\n data.trustedReadFields = [];\n for (let word = 0; word < data.metadata.fieldReadWordCount; word++) {\n const descriptor = (trustedReadWordDescriptors[word] ??= {\n configurable: true,\n enumerable: false,\n get: function (this: Entity): number {\n return isInTrustedContext() ? (getInstanceData(this).trustedReadFields![word] ?? 0) : 0;\n },\n set: function (this: Entity, value: number): void {\n if (isInTrustedContext()) getInstanceData(this).trustedReadFields![word] = value;\n },\n });\n Object.defineProperty(entity, word === 0 ? \"__readFields\" : `__readFields${word}`, descriptor);\n }\n}\n"],"mappings":";;;;;;;;;AAgBA,MAAM,qBAAyC;CAAE,OAAO;CAAG,YAAY;CAAO,UAAU;CAAM,cAAc;AAAK;AACjH,MAAM,6BAAmD,CAAC;;;;;;AAO1D,SAAgB,gBAAgB,QAA8B;CAC5D,OAAO,WAAW,gBAAgB,MAAM;AAC1C;;;;;;AAOA,IAAsB,aAAtB,MAAwG;CACtG,OAAc,gBAAgB,QAA8B;EAC1D,OAAQ,OAA2B;CACrC;CAGA;CAMA,YAAY,IAAmB,OAAiB;EAC9C,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,8DAA8D;EAIhF,eAAe,IAAI,MAAM,KAAK;CAChC;CAKA,IAAI,wBAA8B;EAChC,OAAO;CACT;;CAeA,IAAI,YAAkC;EACpC,OAAO,KAAK,OAAO;CACrB;;CAGA,IAAI,aAAqB;EACvB,OAAOA,aAAAA,QAAQC,uBAAAA,YAAY,IAAI,GAAG,KAAK,EAAE;CAC3C;;;;;;;CAoBA,IAAI,cAAuB;EACzB,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,kBAA2B;EAC7B,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,gBAAyB;EAC3B,OAAO,KAAK,OAAO;CACrB;CAEA,WAAmB;EACjB,MAAM,OAAOA,uBAAAA,YAAY,IAAI;EAC7B,OAAO,mBAAmB,MAAM,MAAM,KAAK,IAAI;CACjD;CAEA,iBAAyB;EACvB,MAAM,OAAOA,uBAAAA,YAAY,IAAI;EAC7B,OAAO,mBAAmB,MAAM,MAAM,KAAK,OAAO;CACpD;CAEA,IAAW,KAAS;EAClB,OAAO,KAAK,OAAO;CACrB;;;;;;;;CASA,SAAwB;EACtB,OAAO,EAAE,IAAI,KAAK,WAAW,KA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AAA,mBAAmB,GAAG,gBAAgB,IAAI,CAAC,CAAC,kBAAmB,QAAQ;GAC7E;EACF;EACA,OAAO,eAAe,QAAQ,SAAS,IAAI,iBAAiB,eAAe,QAAQ,UAAU;CAC/F;AACF"}
@@ -29,6 +29,8 @@ export declare abstract class BaseEntity<EM extends EntityManager, I extends IdT
29
29
  abstract idTagged: TaggedId;
30
30
  /** @returns the entity's id, always tagged, or undefined if it's new/unassigned. */
31
31
  abstract get idTaggedMaybe(): TaggedId | undefined;
32
+ /** The stable EM-local alias, independent of database identity and debug formatting. */
33
+ get $clientId(): TaggedId | undefined;
32
34
  /** @returns the entity's id, always untagged, or a runtime error if it's unassigned. */
33
35
  get idUntagged(): string;
34
36
  abstract set(opts: unknown): void;
@@ -1 +1 @@
1
- {"version":3,"file":"BaseEntity.d.cts","names":[],"sources":["../src/BaseEntity.ts"],"mappings":";;;;;;;;;wBAwBgB,gBAAgB,QAAQ,SAAS;;;;;;8BAS3B,WAAW,WAAW,eAAe,UAAU,SAAS,mBAAmB;SACjF,gBAAgB,QAAQ,SAAS;qBAK5B,QAAS;;YAEV;;EAGlB,YAAY,IAAI;MAaZ;;WAKK,IAAI;;eAGA,WAAW;;WAGf,UAAU;;eAGN,iBAAiB;;MAG1B;WAIK,IAAI;;;;WAKJ,WAAW;;;;WAKX,eAAe,gBAAgB;;;;;;;MAQpC;MAIA;MAIA;EAIJ;EAKA;MAKW,MAAM;;;;;;;;EAWV;GAIN,OAAO;;WAcS,iBAAiB;;;;;;wBA0BpB,eAAe,IAAI,eAAe,QAAQ,sBAAsB;;wBAahE,oBAAoB,QAAQ"}
1
+ {"version":3,"file":"BaseEntity.d.cts","names":[],"sources":["../src/BaseEntity.ts"],"mappings":";;;;;;;;;wBAwBgB,gBAAgB,QAAQ,SAAS;;;;;;8BAS3B,WAAW,WAAW,eAAe,UAAU,SAAS,mBAAmB;SACjF,gBAAgB,QAAQ,SAAS;qBAK5B,QAAS;;YAEV;;EAGlB,YAAY,IAAI;MAaZ;;WAKK,IAAI;;eAGA,WAAW;;WAGf,UAAU;;eAGN,iBAAiB;;MAG1B,aAAa;;MAKb;WAIK,IAAI;;;;WAKJ,WAAW;;;;WAKX,eAAe,gBAAgB;;;;;;;MAQpC;MAIA;MAIA;EAIJ;EAKA;MAKW,MAAM;;;;;;;;EAWV;GAIN,OAAO;;WAcS,iBAAiB;;;;;;wBAyBpB,eAAe,IAAI,eAAe,QAAQ,sBAAsB;;wBAahE,oBAAoB,QAAQ"}
@@ -29,6 +29,8 @@ export declare abstract class BaseEntity<EM extends EntityManager, I extends IdT
29
29
  abstract idTagged: TaggedId;
30
30
  /** @returns the entity's id, always tagged, or undefined if it's new/unassigned. */
31
31
  abstract get idTaggedMaybe(): TaggedId | undefined;
32
+ /** The stable EM-local alias, independent of database identity and debug formatting. */
33
+ get $clientId(): TaggedId | undefined;
32
34
  /** @returns the entity's id, always untagged, or a runtime error if it's unassigned. */
33
35
  get idUntagged(): string;
34
36
  abstract set(opts: unknown): void;
@@ -1 +1 @@
1
- {"version":3,"file":"BaseEntity.d.mts","names":[],"sources":["../src/BaseEntity.ts"],"mappings":";;;;;;;;;wBAwBgB,gBAAgB,QAAQ,SAAS;;;;;;8BAS3B,WAAW,WAAW,eAAe,UAAU,SAAS,mBAAmB;SACjF,gBAAgB,QAAQ,SAAS;qBAK5B,QAAS;;YAEV;;EAGlB,YAAY,IAAI;MAaZ;;WAKK,IAAI;;eAGA,WAAW;;WAGf,UAAU;;eAGN,iBAAiB;;MAG1B;WAIK,IAAI;;;;WAKJ,WAAW;;;;WAKX,eAAe,gBAAgB;;;;;;;MAQpC;MAIA;MAIA;EAIJ;EAKA;MAKW,MAAM;;;;;;;;EAWV;GAIN,OAAO;;WAcS,iBAAiB;;;;;;wBA0BpB,eAAe,IAAI,eAAe,QAAQ,sBAAsB;;wBAahE,oBAAoB,QAAQ"}
1
+ {"version":3,"file":"BaseEntity.d.mts","names":[],"sources":["../src/BaseEntity.ts"],"mappings":";;;;;;;;;wBAwBgB,gBAAgB,QAAQ,SAAS;;;;;;8BAS3B,WAAW,WAAW,eAAe,UAAU,SAAS,mBAAmB;SACjF,gBAAgB,QAAQ,SAAS;qBAK5B,QAAS;;YAEV;;EAGlB,YAAY,IAAI;MAaZ;;WAKK,IAAI;;eAGA,WAAW;;WAGf,UAAU;;eAGN,iBAAiB;;MAG1B,aAAa;;MAKb;WAIK,IAAI;;;;WAKJ,WAAW;;;;WAKX,eAAe,gBAAgB;;;;;;;MAQpC;MAIA;MAIA;EAIJ;EAKA;MAKW,MAAM;;;;;;;;EAWV;GAIN,OAAO;;WAcS,iBAAiB;;;;;;wBAyBpB,eAAe,IAAI,eAAe,QAAQ,sBAAsB;;wBAahE,oBAAoB,QAAQ"}
@@ -38,6 +38,10 @@ var BaseEntity = class {
38
38
  get fullNonReactiveAccess() {
39
39
  return this;
40
40
  }
41
+ /** The stable EM-local alias, independent of database identity and debug formatting. */
42
+ get $clientId() {
43
+ return this.__data.clientId;
44
+ }
41
45
  /** @returns the entity's id, always untagged, or a runtime error if it's unassigned. */
42
46
  get idUntagged() {
43
47
  return deTagId(getMetadata(this), this.id);
@@ -93,8 +97,7 @@ var BaseEntity = class {
93
97
  function toStringWithPrefix(meta, entity, prefix) {
94
98
  let result = prefix;
95
99
  const data = getInstanceData(entity);
96
- const createId = data.createId;
97
- if (createId) result += `#${createId}`;
100
+ if (data.isOrWasNew && data.clientId) result += data.clientId.slice(meta.tagName.length);
98
101
  const dbId = entity.idTaggedMaybe;
99
102
  if (data.pendingOperation !== "insert" && dbId) result += `:${keyToNumber(meta, dbId)}`;
100
103
  return result;
@@ -1 +1 @@
1
- {"version":3,"file":"BaseEntity.js","names":[],"sources":["../src/BaseEntity.ts"],"sourcesContent":["import { type IdType } from \"src/Entity.ts\";\nimport { hasVisibilityHook } from \"src/EntityManager.ts\";\nimport {\n type Entity,\n type EntityManager,\n type EntityMetadata,\n InstanceData,\n type TaggedId,\n deTagId,\n getMetadata,\n keyToNumber,\n} from \"src/index.ts\";\nimport { isInTrustedContext } from \"src/trusted.ts\";\n\n// getProperties deletes its throwaway entity's own fields so callback access to `this` hits a guard proxy.\n// That includes these non-enumerable words, so they must be configurable (deletable).\nconst readWordDescriptor: PropertyDescriptor = { value: 0, enumerable: false, writable: true, configurable: true };\nconst trustedReadWordDescriptors: PropertyDescriptor[] = [];\n\n/**\n * Returns the internal `__data` tracking field for `entity`.\n *\n * This should be treated as an internal API and may change without notice.\n */\nexport function getInstanceData(entity: Entity): InstanceData {\n return BaseEntity.getInstanceData(entity);\n}\n\n/**\n * The base class for all entities.\n *\n * Currently, this just adds the `.load(lensFn)` method for declarative reference traversal.\n */\nexport abstract class BaseEntity<EM extends EntityManager, I extends IdType = IdType> implements Entity {\n public static getInstanceData(entity: Entity): InstanceData {\n return (entity as BaseEntity<any>).__data;\n }\n\n // We use a protected field so that subclass getters can easily access `this.__data.relations`.\n protected readonly __data!: InstanceData;\n /** First-read completion bits; extra words are declared by each generated root type as needed. */\n declare protected __readFields: number;\n\n /** The single-arg constructor is our psuedo-public API that can only be called by the EntityManager. */\n constructor(em: EntityManager);\n constructor(em: EntityManager, isNew?: boolean) {\n if (isNew === undefined) {\n throw new Error(\"Entities must be constructed by calling em.create or em.load\");\n }\n // This code path won't be reused for real entities, as they go through the `newEntity`\n // construction process that lazifies the relations.\n baseEntityCstr(em, this, isNew);\n }\n\n // This gives rules a way to access the fully typed object instead of their Reacted view.\n // And we make it public so that a function that takes Reacted<...> can accept a Loaded<...>\n // that sufficiently overlaps.\n get fullNonReactiveAccess(): this {\n return this;\n }\n\n /** @returns the entity's id, tagged/untagged based on your config, or a runtime error if it's new/unassigned. */\n abstract id: I;\n\n /** @returns the entity's, tagged/untagged based on your config, or undefined if it's new/unassigned. */\n abstract get idMaybe(): I | undefined;\n\n /** @returns the entity's id, always tagged, or a runtime error if it's new/unassigned. */\n abstract idTagged: TaggedId;\n\n /** @returns the entity's id, always tagged, or undefined if it's new/unassigned. */\n abstract get idTaggedMaybe(): TaggedId | undefined;\n\n /** @returns the entity's id, always untagged, or a runtime error if it's unassigned. */\n get idUntagged(): string {\n return deTagId(getMetadata(this), this.id);\n }\n\n abstract set(opts: unknown): void;\n\n /**\n * Similar to `set` but applies \"Partial API\" semantics, i.e. `null` means unset and `undefined` means don't change.\n */\n abstract setPartial(opts: unknown): void;\n\n /**\n * Similar to `set` but applies \"Partial API\" semantics, i.e. `null` means unset and `undefined` means don't change.\n */\n abstract setDeepPartial(opts: unknown): Promise<void>;\n\n /**\n * Returns whether the entity is new.\n *\n * This is not just `this.id === undefined`, because just assigning an id doesn't mean the entity\n * is no longer new; this only flips to `false` after the `flush` transaction has been committed.\n */\n get isNewEntity(): boolean {\n return this.__data.isNewEntity;\n }\n\n get isDeletedEntity(): boolean {\n return this.__data.isDeletedEntity;\n }\n\n get isDirtyEntity(): boolean {\n return this.__data.isDirtyEntity;\n }\n\n toString(): string {\n const meta = getMetadata(this);\n return toStringWithPrefix(meta, this, meta.type);\n }\n\n toTaggedString(): string {\n const meta = getMetadata(this);\n return toStringWithPrefix(meta, this, meta.tagName);\n }\n\n public get em(): EM {\n return this.__data.em as EM;\n }\n\n /**\n * A very simple toJSON that just returns the id.\n *\n * This is for security reasons, to avoid accidentally logging sensitive data; you\n * can specify more fields, and potentially nested return data, by using passing\n * a {@link JsonHint} to `toJSON`.\n */\n public toJSON(): object {\n return { id: this.idMaybe || null };\n }\n\n [Symbol.toStringTag](): string {\n return this.toString();\n }\n\n /**\n * Hooks into node's `console.log` to avoid sprawling output of our relations/internal state.\n *\n * See https://nodejs.org/api/util.html#custom-inspection-functions-on-objects.\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return this.toString();\n }\n\n /** A bag of non-persisted state, typically for flags that control business logic behavior. */\n declare readonly transientFields: Record<string, unknown>;\n}\n\nfunction toStringWithPrefix(meta: EntityMetadata, entity: Entity, prefix: string): string {\n // Start with `Author` or `a`, depending on the caller\n let result = prefix;\n // Add `#1` if this is an em.create-d entity\n const data = getInstanceData(entity);\n const createId = data.createId;\n if (createId) {\n result += `#${createId}`;\n }\n // Add the `:1` but only after our flush is complete, otherwise the id is\n // internally assigned but not really flushed/committed to the db yet\n const dbId = entity.idTaggedMaybe;\n if (data.pendingOperation !== \"insert\" && dbId) {\n // Strip the tag because we add back the entity prefix\n result += `:${keyToNumber(meta, dbId)}`;\n }\n return result;\n}\n\n/**\n * The constructor logic for `BaseEntity` but exposed so that `newEntity` can use it too\n * on its `Object.create`-d instances.\n */\nexport function baseEntityCstr(em: EntityManager, entity: BaseEntity<any, any>, isNew: boolean): void {\n const data = new InstanceData(em, entity, (entity.constructor as any).metadata, isNew);\n // This makes it non-enumerable to avoid Jest/recursive things tripping over it\n Object.defineProperty(entity, \"__data\", { value: data, enumerable: false, writable: false, configurable: false });\n // Constructors are bypassed for real entities, so initialize every needed word here,\n // in the same order for the entire inheritance family. Reusing the descriptor avoids per-entity descriptor objects.\n for (let word = 0; word < data.metadata.fieldReadWordCount; word++) {\n Object.defineProperty(entity, word === 0 ? \"__readFields\" : `__readFields${word}`, readWordDescriptor);\n }\n if (hasVisibilityHook(entity)) useTrustedReadCache(entity);\n}\n\n/** Replaces the __readFields fields with getters/setters that always return 0 for untrusted reads, so they are always access checked. */\nexport function useTrustedReadCache(entity: Entity): void {\n const data = getInstanceData(entity);\n if (data.trustedReadFields) return;\n data.trustedReadFields = [];\n for (let word = 0; word < data.metadata.fieldReadWordCount; word++) {\n const descriptor = (trustedReadWordDescriptors[word] ??= {\n configurable: true,\n enumerable: false,\n get: function (this: Entity): number {\n return isInTrustedContext() ? (getInstanceData(this).trustedReadFields![word] ?? 0) : 0;\n },\n set: function (this: Entity, value: number): void {\n if (isInTrustedContext()) getInstanceData(this).trustedReadFields![word] = value;\n },\n });\n Object.defineProperty(entity, word === 0 ? \"__readFields\" : `__readFields${word}`, descriptor);\n }\n}\n"],"mappings":";;;;;;;;AAgBA,MAAM,qBAAyC;CAAE,OAAO;CAAG,YAAY;CAAO,UAA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CACpB,IAAI,KAAK,qBAAqB,YAAY,MAExC,UAAU,IAAI,YAAY,MAAM,IAAI;CAEtC,OAAO;AACT;;;;;AAMA,SAAgB,eAAe,IAAmB,QAA8B,OAAsB;CACpG,MAAM,OAAO,IAAI,aAAa,IAAI,QAAS,OAAO,YAAoB,UAAU,KAAK;CAErF,OAAO,eAAe,QAAQ,UAAU;EAAE,OAAO;EAAM,YAAY;EAAO,UAAU;EAAO,cAAc;CAAM,CAAC;CAGhH,KAAK,IAAI,OAAO,GAAG,OAAO,KAAK,SAAS,oBAAoB,QAC1D,OAAO,eAAe,QAAQ,SAAS,IAAI,iBAAiB,eAAe,QAAQ,kBAAkB;CAEvG,IAAI,kBAAkB,MAAM,GAAG,oBAAoB,MAAM;AAC3D;;AAGA,SAAgB,oBAAoB,QAAsB;CACxD,MAAM,OAAO,gBAAgB,MAAM;CACnC,IAAI,KAAK,mBAAmB;CAC5B,KAAK,oBAAoB,CAAC;CAC1B,KAAK,IAAI,OAAO,GAAG,OAAO,KAAK,SAAS,oBAAoB,QAAQ;EAClE,MAAM,aAAc,2BAA2B,UAAU;GACvD,cAAc;GACd,YAAY;GACZ,KAAK,WAAgC;IACnC,OAAO,mBAAmB,IAAK,gBAAgB,IAAI,CAAC,CAAC,kBAAmB,SAAS,IAAK;GACxF;GACA,KAAK,SAAwB,OAAqB;IAChD,IAAI,mBAAmB,GAAG,gBAAgB,IAAI,CAAC,CAAC,kBAAmB,QAAQ;GAC7E;EACF;EACA,OAAO,eAAe,QAAQ,SAAS,IAAI,iBAAiB,eAAe,QAAQ,UAAU;CAC/F;AACF"}
1
+ {"version":3,"file":"BaseEntity.js","names":[],"sources":["../src/BaseEntity.ts"],"sourcesContent":["import { type IdType } from \"src/Entity.ts\";\nimport { hasVisibilityHook } from \"src/EntityManager.ts\";\nimport {\n type Entity,\n type EntityManager,\n type EntityMetadata,\n InstanceData,\n type TaggedId,\n deTagId,\n getMetadata,\n keyToNumber,\n} from \"src/index.ts\";\nimport { isInTrustedContext } from \"src/trusted.ts\";\n\n// getProperties deletes its throwaway entity's own fields so callback access to `this` hits a guard proxy.\n// That includes these non-enumerable words, so they must be configurable (deletable).\nconst readWordDescriptor: PropertyDescriptor = { value: 0, enumerable: false, writable: true, configurable: true };\nconst trustedReadWordDescriptors: PropertyDescriptor[] = [];\n\n/**\n * Returns the internal `__data` tracking field for `entity`.\n *\n * This should be treated as an internal API and may change without notice.\n */\nexport function getInstanceData(entity: Entity): InstanceData {\n return BaseEntity.getInstanceData(entity);\n}\n\n/**\n * The base class for all entities.\n *\n * Currently, this just adds the `.load(lensFn)` method for declarative reference traversal.\n */\nexport abstract class BaseEntity<EM extends EntityManager, I extends IdType = IdType> implements Entity {\n public static getInstanceData(entity: Entity): InstanceData {\n return (entity as BaseEntity<any>).__data;\n }\n\n // We use a protected field so that subclass getters can easily access `this.__data.relations`.\n protected readonly __data!: InstanceData;\n /** First-read completion bits; extra words are declared by each generated root type as needed. */\n declare protected __readFields: number;\n\n /** The single-arg constructor is our psuedo-public API that can only be called by the EntityManager. */\n constructor(em: EntityManager);\n constructor(em: EntityManager, isNew?: boolean) {\n if (isNew === undefined) {\n throw new Error(\"Entities must be constructed by calling em.create or em.load\");\n }\n // This code path won't be reused for real entities, as they go through the `newEntity`\n // construction process that lazifies the relations.\n baseEntityCstr(em, this, isNew);\n }\n\n // This gives rules a way to access the fully typed object instead of their Reacted view.\n // And we make it public so that a function that takes Reacted<...> can accept a Loaded<...>\n // that sufficiently overlaps.\n get fullNonReactiveAccess(): this {\n return this;\n }\n\n /** @returns the entity's id, tagged/untagged based on your config, or a runtime error if it's new/unassigned. */\n abstract id: I;\n\n /** @returns the entity's, tagged/untagged based on your config, or undefined if it's new/unassigned. */\n abstract get idMaybe(): I | undefined;\n\n /** @returns the entity's id, always tagged, or a runtime error if it's new/unassigned. */\n abstract idTagged: TaggedId;\n\n /** @returns the entity's id, always tagged, or undefined if it's new/unassigned. */\n abstract get idTaggedMaybe(): TaggedId | undefined;\n\n /** The stable EM-local alias, independent of database identity and debug formatting. */\n get $clientId(): TaggedId | undefined {\n return this.__data.clientId;\n }\n\n /** @returns the entity's id, always untagged, or a runtime error if it's unassigned. */\n get idUntagged(): string {\n return deTagId(getMetadata(this), this.id);\n }\n\n abstract set(opts: unknown): void;\n\n /**\n * Similar to `set` but applies \"Partial API\" semantics, i.e. `null` means unset and `undefined` means don't change.\n */\n abstract setPartial(opts: unknown): void;\n\n /**\n * Similar to `set` but applies \"Partial API\" semantics, i.e. `null` means unset and `undefined` means don't change.\n */\n abstract setDeepPartial(opts: unknown): Promise<void>;\n\n /**\n * Returns whether the entity is new.\n *\n * This is not just `this.id === undefined`, because just assigning an id doesn't mean the entity\n * is no longer new; this only flips to `false` after the `flush` transaction has been committed.\n */\n get isNewEntity(): boolean {\n return this.__data.isNewEntity;\n }\n\n get isDeletedEntity(): boolean {\n return this.__data.isDeletedEntity;\n }\n\n get isDirtyEntity(): boolean {\n return this.__data.isDirtyEntity;\n }\n\n toString(): string {\n const meta = getMetadata(this);\n return toStringWithPrefix(meta, this, meta.type);\n }\n\n toTaggedString(): string {\n const meta = getMetadata(this);\n return toStringWithPrefix(meta, this, meta.tagName);\n }\n\n public get em(): EM {\n return this.__data.em as EM;\n }\n\n /**\n * A very simple toJSON that just returns the id.\n *\n * This is for security reasons, to avoid accidentally logging sensitive data; you\n * can specify more fields, and potentially nested return data, by using passing\n * a {@link JsonHint} to `toJSON`.\n */\n public toJSON(): object {\n return { id: this.idMaybe || null };\n }\n\n [Symbol.toStringTag](): string {\n return this.toString();\n }\n\n /**\n * Hooks into node's `console.log` to avoid sprawling output of our relations/internal state.\n *\n * See https://nodejs.org/api/util.html#custom-inspection-functions-on-objects.\n */\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return this.toString();\n }\n\n /** A bag of non-persisted state, typically for flags that control business logic behavior. */\n declare readonly transientFields: Record<string, unknown>;\n}\n\nfunction toStringWithPrefix(meta: EntityMetadata, entity: Entity, prefix: string): string {\n // Start with `Author` or `a`, depending on the caller\n let result = prefix;\n // Add `#1` if this is an em.create-d entity\n const data = getInstanceData(entity);\n if (data.isOrWasNew && data.clientId) {\n result += data.clientId.slice(meta.tagName.length);\n }\n // Add the `:1` but only after our flush is complete, otherwise the id is\n // internally assigned but not really flushed/committed to the db yet\n const dbId = entity.idTaggedMaybe;\n if (data.pendingOperation !== \"insert\" && dbId) {\n // Strip the tag because we add back the entity prefix\n result += `:${keyToNumber(meta, dbId)}`;\n }\n return result;\n}\n\n/**\n * The constructor logic for `BaseEntity` but exposed so that `newEntity` can use it too\n * on its `Object.create`-d instances.\n */\nexport function baseEntityCstr(em: EntityManager, entity: BaseEntity<any, any>, isNew: boolean): void {\n const data = new InstanceData(em, entity, (entity.constructor as any).metadata, isNew);\n // This makes it non-enumerable to avoid Jest/recursive things tripping over it\n Object.defineProperty(entity, \"__data\", { value: data, enumerable: false, writable: false, configurable: false });\n // Constructors are bypassed for real entities, so initialize every needed word here,\n // in the same order for the entire inheritance family. Reusing the descriptor avoids per-entity descriptor objects.\n for (let word = 0; word < data.metadata.fieldReadWordCount; word++) {\n Object.defineProperty(entity, word === 0 ? \"__readFields\" : `__readFields${word}`, readWordDescriptor);\n }\n if (hasVisibilityHook(entity)) useTrustedReadCache(entity);\n}\n\n/** Replaces the __readFields fields with getters/setters that always return 0 for untrusted reads, so they are always access checked. */\nexport function useTrustedReadCache(entity: Entity): void {\n const data = getInstanceData(entity);\n if (data.trustedReadFields) return;\n data.trustedReadFields = [];\n for (let word = 0; word < data.metadata.fieldReadWordCount; word++) {\n const descriptor = (trustedReadWordDescriptors[word] ??= {\n configurable: true,\n enumerable: false,\n get: function (this: Entity): number {\n return isInTrustedContext() ? (getInstanceData(this).trustedReadFields![word] ?? 0) : 0;\n },\n set: function (this: Entity, value: number): void {\n if (isInTrustedContext()) getInstanceData(this).trustedReadFields![word] = value;\n },\n });\n Object.defineProperty(entity, word === 0 ? \"__readFields\" : `__readFields${word}`, descriptor);\n }\n}\n"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Manager, type TaggedId } from \"src/EntityManager.ts\";\nimport { BaseEntity } from \"src/index.ts\";\n\nexport function isEntity(maybeEntity: unknown): maybeEntity is Entity {\n return maybeEntity instanceof BaseEntity;\n}\n\n/** All the types we support for entity `id` fields. */\nexport type IdType = number | string;\n\n/** A marker/base interface for all of our entity types. */\nexport interface Entity {\n /** The entity id, either tagged or untagged; the per-application `Entity` will specialize appropriately. */\n id: IdType;\n idMaybe: IdType | undefined;\n /** The entity id that is always tagged, regardless of the idType config. */\n idTagged: TaggedId;\n idTaggedMaybe: TaggedId | undefined;\n readonly em: EntityManager;\n readonly isNewEntity: boolean;\n readonly isDeletedEntity: boolean;\n readonly isDirtyEntity: boolean;\n readonly transientFields: Record<string, unknown>;\n set(opts: unknown): void;\n setPartial(opts: unknown): void;\n setDeepPartial(opts: unknown): Promise<void>;\n /**\n * Returns `type:id`, i.e. `Author:1` for persisted entities and `Author#1` for new entities.\n *\n * Once an entity is persisted, we'll return `Author#1:1` to denote \"the previously-new author #1\n * is now authors row id=1 in the database\".\n *\n * This is meant to be used for developer-facing logging and debugging, and not a user-facing\n * name / display name.\n */\n toString(): string;\n /**\n * Returns `tag:id`, i.e. `a:1` for persisted entities and `a#1` for new entities.\n *\n * This is meant to be used for developer-facing logging and debugging, and not a user-facing\n * name / display name.\n */\n toTaggedString(): string;\n}\n"],"mappings":";;;;;AAGA,SAAgB,SAAS,aAA6C;CACpE,OAAO,uBAAuBA,mBAAAA;AAChC"}
1
+ {"version":3,"file":"Entity.cjs","names":["BaseEntity"],"sources":["../src/Entity.ts"],"sourcesContent":["import { type EntityManager, type TaggedId } from \"src/EntityManager.ts\";\nimport { BaseEntity } from \"src/index.ts\";\n\nexport function isEntity(maybeEntity: unknown): maybeEntity is Entity {\n return maybeEntity instanceof BaseEntity;\n}\n\n/** All the types we support for entity `id` fields. */\nexport type IdType = number | string;\n\n/** A marker/base interface for all of our entity types. */\nexport interface Entity {\n /** The entity id, either tagged or untagged; the per-application `Entity` will specialize appropriately. */\n id: IdType;\n idMaybe: IdType | undefined;\n /** The entity id that is always tagged, regardless of the idType config. */\n idTagged: TaggedId;\n idTaggedMaybe: TaggedId | undefined;\n /**\n * An immutable EM-local alias, retained after database ID assignment and flush.\n *\n * Created entities always have one. This is undefined for entities loaded from the database.\n */\n readonly $clientId: TaggedId | undefined;\n readonly em: EntityManager;\n readonly isNewEntity: boolean;\n readonly isDeletedEntity: boolean;\n readonly isDirtyEntity: boolean;\n readonly transientFields: Record<string, unknown>;\n set(opts: unknown): void;\n setPartial(opts: unknown): void;\n setDeepPartial(opts: unknown): Promise<void>;\n /**\n * Returns `type:id`, i.e. `Author:1` for persisted entities and `Author#1` for new entities.\n *\n * Once an entity is persisted, we'll return `Author#1:1` to denote \"the previously-new author #1\n * is now authors row id=1 in the database\".\n *\n * This is meant to be used for developer-facing logging and debugging, and not a user-facing\n * name / display name.\n */\n toString(): string;\n /**\n * Returns `tag:id`, i.e. `a:1` for persisted entities and `a#1` for new entities.\n *\n * This is meant to be used for developer-facing logging and debugging, and not a user-facing\n * name / display name.\n */\n toTaggedString(): string;\n}\n"],"mappings":";;;;;AAGA,SAAgB,SAAS,aAA6C;CACpE,OAAO,uBAAuBA,mBAAAA;AAChC"}
@@ -10,6 +10,12 @@ export interface Entity {
10
10
  /** The entity id that is always tagged, regardless of the idType config. */
11
11
  idTagged: TaggedId;
12
12
  idTaggedMaybe: TaggedId | undefined;
13
+ /**
14
+ * An immutable EM-local alias, retained after database ID assignment and flush.
15
+ *
16
+ * Created entities always have one. This is undefined for entities loaded from the database.
17
+ */
18
+ readonly $clientId: TaggedId | undefined;
13
19
  readonly em: EntityManager;
14
20
  readonly isNewEntity: boolean;
15
21
  readonly isDeletedEntity: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"Entity.d.cts","names":[],"sources":["../src/Entity.ts"],"mappings":";wBAGgB,SAAS,uBAAuB,eAAe;;YAKnD;;iBAGK;;EAEf,IAAI;EACJ,SAAS;;EAET,UAAU;EACV,eAAe;WACN,IAAI;WACJ;WACA;WACA;WACA,iBAAiB;EAC1B,IAAI;EACJ,WAAW;EACX,eAAe,gBAAgB;;;;;;;;;;EAU/B;;;;;;;EAOA"}
1
+ {"version":3,"file":"Entity.d.cts","names":[],"sources":["../src/Entity.ts"],"mappings":";wBAGgB,SAAS,uBAAuB,eAAe;;YAKnD;;iBAGK;;EAEf,IAAI;EACJ,SAAS;;EAET,UAAU;EACV,eAAe;;;;;;WAMN,WAAW;WACX,IAAI;WACJ;WACA;WACA;WACA,iBAAiB;EAC1B,IAAI;EACJ,WAAW;EACX,eAAe,gBAAgB;;;;;;;;;;EAU/B;;;;;;;EAOA"}
@@ -10,6 +10,12 @@ export interface Entity {
10
10
  /** The entity id that is always tagged, regardless of the idType config. */
11
11
  idTagged: TaggedId;
12
12
  idTaggedMaybe: TaggedId | undefined;
13
+ /**
14
+ * An immutable EM-local alias, retained after database ID assignment and flush.
15
+ *
16
+ * Created entities always have one. This is undefined for entities loaded from the database.
17
+ */
18
+ readonly $clientId: TaggedId | undefined;
13
19
  readonly em: EntityManager;
14
20
  readonly isNewEntity: boolean;
15
21
  readonly isDeletedEntity: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"Entity.d.mts","names":[],"sources":["../src/Entity.ts"],"mappings":";wBAGgB,SAAS,uBAAuB,eAAe;;YAKnD;;iBAGK;;EAEf,IAAI;EACJ,SAAS;;EAET,UAAU;EACV,eAAe;WACN,IAAI;WACJ;WACA;WACA;WACA,iBAAiB;EAC1B,IAAI;EACJ,WAAW;EACX,eAAe,gBAAgB;;;;;;;;;;EAU/B;;;;;;;EAOA"}
1
+ {"version":3,"file":"Entity.d.mts","names":[],"sources":["../src/Entity.ts"],"mappings":";wBAGgB,SAAS,uBAAuB,eAAe;;YAKnD;;iBAGK;;EAEf,IAAI;EACJ,SAAS;;EAET,UAAU;EACV,eAAe;;;;;;WAMN,WAAW;WACX,IAAI;WACJ;WACA;WACA;WACA,iBAAiB;EAC1B,IAAI;EACJ,WAAW;EACX,eAAe,gBAAgB;;;;;;;;;;EAU/B;;;;;;;EAOA"}
@@ -1 +1 @@
1
- {"version":3,"file":"Entity.js","names":[],"sources":["../src/Entity.ts"],"sourcesContent":["import { type EntityManager, type TaggedId } from \"src/EntityManager.ts\";\nimport { BaseEntity } from \"src/index.ts\";\n\nexport function isEntity(maybeEntity: unknown): maybeEntity is Entity {\n return maybeEntity instanceof BaseEntity;\n}\n\n/** All the types we support for entity `id` fields. */\nexport type IdType = number | string;\n\n/** A marker/base interface for all of our entity types. */\nexport interface Entity {\n /** The entity id, either tagged or untagged; the per-application `Entity` will specialize appropriately. */\n id: IdType;\n idMaybe: IdType | undefined;\n /** The entity id that is always tagged, regardless of the idType config. */\n idTagged: TaggedId;\n idTaggedMaybe: TaggedId | undefined;\n readonly em: EntityManager;\n readonly isNewEntity: boolean;\n readonly isDeletedEntity: boolean;\n readonly isDirtyEntity: boolean;\n readonly transientFields: Record<string, unknown>;\n set(opts: unknown): void;\n setPartial(opts: unknown): void;\n setDeepPartial(opts: unknown): Promise<void>;\n /**\n * Returns `type:id`, i.e. `Author:1` for persisted entities and `Author#1` for new entities.\n *\n * Once an entity is persisted, we'll return `Author#1:1` to denote \"the previously-new author #1\n * is now authors row id=1 in the database\".\n *\n * This is meant to be used for developer-facing logging and debugging, and not a user-facing\n * name / display name.\n */\n toString(): string;\n /**\n * Returns `tag:id`, i.e. `a:1` for persisted entities and `a#1` for new entities.\n *\n * This is meant to be used for developer-facing logging and debugging, and not a user-facing\n * name / display name.\n */\n toTaggedString(): string;\n}\n"],"mappings":";;;;AAGA,SAAgB,SAAS,aAA6C;CACpE,OAAO,uBAAuB;AAChC"}
1
+ {"version":3,"file":"Entity.js","names":[],"sources":["../src/Entity.ts"],"sourcesContent":["import { type EntityManager, type TaggedId } from \"src/EntityManager.ts\";\nimport { BaseEntity } from \"src/index.ts\";\n\nexport function isEntity(maybeEntity: unknown): maybeEntity is Entity {\n return maybeEntity instanceof BaseEntity;\n}\n\n/** All the types we support for entity `id` fields. */\nexport type IdType = number | string;\n\n/** A marker/base interface for all of our entity types. */\nexport interface Entity {\n /** The entity id, either tagged or untagged; the per-application `Entity` will specialize appropriately. */\n id: IdType;\n idMaybe: IdType | undefined;\n /** The entity id that is always tagged, regardless of the idType config. */\n idTagged: TaggedId;\n idTaggedMaybe: TaggedId | undefined;\n /**\n * An immutable EM-local alias, retained after database ID assignment and flush.\n *\n * Created entities always have one. This is undefined for entities loaded from the database.\n */\n readonly $clientId: TaggedId | undefined;\n readonly em: EntityManager;\n readonly isNewEntity: boolean;\n readonly isDeletedEntity: boolean;\n readonly isDirtyEntity: boolean;\n readonly transientFields: Record<string, unknown>;\n set(opts: unknown): void;\n setPartial(opts: unknown): void;\n setDeepPartial(opts: unknown): Promise<void>;\n /**\n * Returns `type:id`, i.e. `Author:1` for persisted entities and `Author#1` for new entities.\n *\n * Once an entity is persisted, we'll return `Author#1:1` to denote \"the previously-new author #1\n * is now authors row id=1 in the database\".\n *\n * This is meant to be used for developer-facing logging and debugging, and not a user-facing\n * name / display name.\n */\n toString(): string;\n /**\n * Returns `tag:id`, i.e. `a:1` for persisted entities and `a#1` for new entities.\n *\n * This is meant to be used for developer-facing logging and debugging, and not a user-facing\n * name / display name.\n */\n toTaggedString(): string;\n}\n"],"mappings":";;;;AAGA,SAAgB,SAAS,aAA6C;CACpE,OAAO,uBAAuB;AAChC"}
@@ -4,17 +4,18 @@ const require_BaseEntity = require("./BaseEntity.cjs");
4
4
  const require_batchloaders_BatchLoader = require("./batchloaders/BatchLoader.cjs");
5
5
  require("./batchloaders/enumCollectionBatchLoader.cjs");
6
6
  const require_batchloaders_loadBatchLoader = require("./batchloaders/loadBatchLoader.cjs");
7
+ require("./batchloaders/manyToManyBatchLoader.cjs");
7
8
  const require_relations_CustomCollection = require("./relations/CustomCollection.cjs");
8
9
  const require_relations_CustomReference = require("./relations/CustomReference.cjs");
9
10
  const require_normalizeHints = require("./normalizeHints.cjs");
10
- require("./batchloaders/manyToManyBatchLoader.cjs");
11
11
  require("./batchloaders/oneToManyBatchLoader.cjs");
12
12
  require("./batchloaders/oneToOneBatchLoader.cjs");
13
- const require_relations_RecursiveCycleError = require("./relations/RecursiveCycleError.cjs");
14
13
  const require_batchloaders_populateBatchLoader = require("./batchloaders/populateBatchLoader.cjs");
14
+ const require_relations_RecursiveCycleError = require("./relations/RecursiveCycleError.cjs");
15
15
  require("./batchloaders/recursiveChildrenBatchLoader.cjs");
16
16
  require("./batchloaders/recursiveM2mBatchLoader.cjs");
17
17
  require("./batchloaders/recursiveParentsBatchLoader.cjs");
18
+ const require_clientIds = require("./clientIds.cjs");
18
19
  const require_config = require("./config.cjs");
19
20
  const require_keys = require("./keys.cjs");
20
21
  const require_configure = require("./configure.cjs");
@@ -58,6 +59,7 @@ require("./plugins/PreloadPlugin.cjs");
58
59
  const require_queries_find_scopes = require("./queries/find/scopes.cjs");
59
60
  const require_queries_sql_execute = require("./queries/sql/execute.cjs");
60
61
  const require_queries_sql_query = require("./queries/sql/query.cjs");
62
+ const require_queries_sql_renderSql = require("./queries/sql/renderSql.cjs");
61
63
  const require_reactivity_ReactionsManager = require("./reactivity/ReactionsManager.cjs");
62
64
  const require_reactivity_reactiveHints = require("./reactivity/reactiveHints.cjs");
63
65
  const require_relations_AsyncProperty = require("./relations/AsyncProperty.cjs");
@@ -343,9 +345,13 @@ var EntityManager = class EntityManager {
343
345
  this.#assertFindAllowed("query");
344
346
  const em = this;
345
347
  return (async function query() {
348
+ const plugins = em.__api.pluginManager;
346
349
  const plan = require_queries_sql_query.parseRootQuery(q);
347
350
  if (options?.populate && plan.output.kind !== "entity") require_utils.fail("em.query populate requires an entity selection");
348
- const { rows } = await em.driver.executeQuery(em, plan.sql, plan.bindings);
351
+ plugins.beforeQuery(plan.query);
352
+ const sql = require_queries_sql_renderSql.renderQuery(plan.query);
353
+ const { rows } = await em.driver.executeQuery(em, sql.sql, sql.bindings);
354
+ if (plugins.hasHook("afterQuery")) plugins.afterQuery(plan.query, new require_RowData.PojoRowData(rows));
349
355
  const result = plan.decodeRows(em.__api, rows);
350
356
  if (options?.populate) await em.populate(result, options.populate);
351
357
  return plan.output.kind === "entity" ? em.#filterVisible(result) : result;
@@ -360,12 +366,19 @@ var EntityManager = class EntityManager {
360
366
  if (em.mode === "read-only") throw new ReadOnlyError();
361
367
  if (em.mode === "in-memory-writes") require_utils.fail("SQL mutations do not support in-memory-writes mode");
362
368
  } else em.#assertFindAllowed("execute");
369
+ const plugins = em.__api.pluginManager;
363
370
  const plan = require_queries_sql_execute.parseStatement(statement);
364
- if (!plan) return {
371
+ const query = plan.query;
372
+ const read = query.kind === "select" || query.kind === "set" ? query : void 0;
373
+ if (query.kind === "select" || query.kind === "set") plugins.beforeQuery(query);
374
+ else plugins.beforeExecute(query);
375
+ if (query.kind === "insert" && query.values?.length === 0) return {
365
376
  rowCount: 0,
366
377
  rows: []
367
378
  };
368
- const result = await em.driver.executeQuery(em, plan.sql, plan.bindings);
379
+ const sql = require_queries_sql_renderSql.renderStatement(query);
380
+ const result = await em.driver.executeQuery(em, sql.sql, sql.bindings);
381
+ if (read && plugins.hasHook("afterQuery")) plugins.afterQuery(read, new require_RowData.PojoRowData(result.rows));
369
382
  const decoded = require_queries_sql_execute.decodeStatementResult(em.__api, plan, result);
370
383
  if (plan.output.kind === "entity") decoded.rows = em.#filterVisible(decoded.rows);
371
384
  return decoded;
@@ -557,6 +570,7 @@ var EntityManager = class EntityManager {
557
570
  * This supports upsert behavior, i.e.:
558
571
  *
559
572
  * - findOrCreate the primary entity being updated (based on the `id` key being provided),
573
+ * - `id` accepts a database ID or an already-registered client ID,
560
574
  * - upsert relation markers like `op`, `delete`, and `remove` are supported,
561
575
  * - deep input is supported, i.e. `{ firstName: "Bob", books: [{ title: "b1" } ] }`, and
562
576
  * - fields set to `undefined` will be skipped instead of unset
@@ -710,7 +724,7 @@ var EntityManager = class EntityManager {
710
724
  }
711
725
  async load(typeOrId, id, hint) {
712
726
  const entity = await this.#load(typeOrId, id, hint);
713
- if (!this.#canViewEntity(entity)) throw new NotFoundError(`${entity.idTagged} was not found`);
727
+ if (!this.#canViewEntity(entity)) throw new NotFoundError(`${id ?? typeOrId} was not found`);
714
728
  return entity;
715
729
  }
716
730
  /** Resolves identity and hydration without filtering internal relation targets. */
@@ -724,6 +738,13 @@ var EntityManager = class EntityManager {
724
738
  id = id || require_utils.fail(`Invalid ${typeOrId.name} id: ${id}`);
725
739
  }
726
740
  const meta = require_EntityMetadata.getMetadata(type);
741
+ if (require_clientIds.isClientId(id)) {
742
+ const entity = this.#getEntity(id);
743
+ if (!entity) throw new NotFoundError(`${id} was not found`);
744
+ if (!(entity instanceof type)) throw new Error(`${id} is ${entity.constructor.name} but should be ${type.name}`);
745
+ if (hint) await this.populate(entity, hint);
746
+ return entity;
747
+ }
727
748
  const taggedId = require_keys.toTaggedId(meta, id);
728
749
  let entity = this.#getEntity(taggedId);
729
750
  if (!entity) {
@@ -743,8 +764,8 @@ var EntityManager = class EntityManager {
743
764
  async loadAll(type, _ids, hint) {
744
765
  const entities = await this.#loadAll(type, _ids, hint);
745
766
  if (this.#hasVisibilityHook) {
746
- const hidden = entities.filter((entity) => !this.#canViewEntity(entity));
747
- if (hidden.length > 0) throw new NotFoundError(`${hidden.map((entity) => entity.idTagged).join(",")} were not found`);
767
+ const hidden = _ids.filter((_, i) => !this.#canViewEntity(entities[i]));
768
+ if (hidden.length > 0) throw new NotFoundError(`${hidden.join(",")} were not found`);
748
769
  }
749
770
  return entities;
750
771
  }
@@ -755,8 +776,12 @@ var EntityManager = class EntityManager {
755
776
  let idsToLoad;
756
777
  let positionsToLoad;
757
778
  for (let i = 0; i < _ids.length; i++) {
758
- const id = require_keys.tagId(meta, _ids[i]);
779
+ const input = _ids[i];
780
+ const client = require_clientIds.isClientId(input);
781
+ const id = client ? input : require_keys.tagId(meta, input);
759
782
  const entity = this.#getEntity(id);
783
+ if (client && !entity) throw new NotFoundError(`${id} was not found`);
784
+ if (client && entity && !(entity instanceof type)) throw new Error(`${id} is ${entity.constructor.name} but should be ${type.name}`);
760
785
  if (entity) entities[i] = entity;
761
786
  else {
762
787
  (idsToLoad ??= []).push(id);
@@ -791,16 +816,21 @@ var EntityManager = class EntityManager {
791
816
  const maybeEntities = new Array(_ids.length);
792
817
  let idsToLoad;
793
818
  let positionsToLoad;
819
+ let allFound = true;
794
820
  for (let i = 0; i < _ids.length; i++) {
795
- const id = require_keys.tagId(meta, _ids[i]);
821
+ const input = _ids[i];
822
+ const client = require_clientIds.isClientId(input);
823
+ const id = client ? input : require_keys.tagId(meta, input);
796
824
  const entity = this.#getEntity(id);
825
+ if (client && entity && !(entity instanceof type)) throw new Error(`${id} is ${entity.constructor.name} but should be ${type.name}`);
797
826
  if (entity) maybeEntities[i] = entity;
798
827
  else {
828
+ allFound = false;
829
+ if (client) continue;
799
830
  (idsToLoad ??= []).push(id);
800
831
  (positionsToLoad ??= []).push(i);
801
832
  }
802
833
  }
803
- let entities;
804
834
  if (idsToLoad) {
805
835
  await require_batchloaders_loadBatchLoader.loadBatchLoader(this, meta).loadAll(idsToLoad.map((id) => ({
806
836
  taggedId: id,
@@ -809,9 +839,13 @@ var EntityManager = class EntityManager {
809
839
  throw appendStack(err, /* @__PURE__ */ new Error());
810
840
  });
811
841
  for (let j = 0; j < positionsToLoad.length; j++) maybeEntities[positionsToLoad[j]] = this.#getEntity(idsToLoad[j]);
842
+ }
843
+ let entities;
844
+ if (allFound) entities = maybeEntities;
845
+ else {
812
846
  entities = [];
813
847
  for (const entity of maybeEntities) if (entity !== void 0) entities.push(entity);
814
- } else entities = maybeEntities;
848
+ }
815
849
  entities = this.#filterVisible(entities);
816
850
  if (hint) await this.populate(entities, hint);
817
851
  return entities;
@@ -1506,7 +1540,7 @@ var EntityManager = class EntityManager {
1506
1540
  for (const entity of entities) {
1507
1541
  const instanceData = entity.__data;
1508
1542
  if (!allowPendingChanges && instanceData.pendingOperation !== "none") require_utils.fail("Cannot fork an EntityManager with pending changes");
1509
- else if (instanceData.isNewEntity) newEm.create(entity.constructor, {});
1543
+ else if (instanceData.isNewEntity) newEm.create(entity.constructor, { $clientId: entity.$clientId });
1510
1544
  else {
1511
1545
  rows[i] = createRowFromEntityData(entity);
1512
1546
  i++;
@@ -1516,9 +1550,15 @@ var EntityManager = class EntityManager {
1516
1550
  newEm.#hydrateCanonical(baseCstr, rows);
1517
1551
  }
1518
1552
  function mapEntity(oldEntity) {
1519
- if (oldEntity.isNewEntity) return newEm.#entitiesById.get(oldEntity.toTaggedString());
1553
+ if (oldEntity.isNewEntity) return newEm.#entitiesById.get(oldEntity.$clientId);
1520
1554
  else return newEm.#entitiesById.get(oldEntity.idTagged);
1521
1555
  }
1556
+ for (const entity of oldEm.#entitiesArray) if (entity.$clientId) {
1557
+ const copy = mapEntity(entity);
1558
+ require_BaseEntity.getInstanceData(copy).clientId = entity.$clientId;
1559
+ newEm.#entitiesById.set(entity.$clientId, copy);
1560
+ }
1561
+ if (oldEm.#createCounter) newEm.#createCounter = new Map(oldEm.#createCounter);
1522
1562
  function mapEntities(v) {
1523
1563
  if (v === void 0) return void 0;
1524
1564
  const result = new Array(v.length);
@@ -1608,18 +1648,37 @@ var EntityManager = class EntityManager {
1608
1648
  }
1609
1649
  /** Creates a new `type` and marks it as loaded, i.e. we know its collections are all safe to access in memory. */
1610
1650
  #doCreate(type, opts, partial) {
1611
- const entity = require_newEntity.newEntity(this, type, true);
1612
1651
  const meta = require_EntityMetadata.getMetadata(type);
1613
- const counter = this.#createCounter ??= /* @__PURE__ */ new Map();
1614
- const i = (counter.get(meta.tagName) ?? 0) + 1;
1615
- counter.set(meta.tagName, i);
1616
- require_BaseEntity.getInstanceData(entity).createId = String(i);
1617
- this.#doRegister(entity, opts.id);
1652
+ const $clientId = opts.$clientId;
1653
+ let fields = opts;
1654
+ if ("$clientId" in opts) {
1655
+ fields = { ...opts };
1656
+ delete fields.$clientId;
1657
+ }
1658
+ if (require_clientIds.isClientId(fields.id)) throw new Error("id must be a database id; use $clientId for client identity");
1659
+ else if ($clientId !== void 0) {
1660
+ require_clientIds.assertClientId(meta, $clientId);
1661
+ if (this.#getEntity($clientId)) throw new Error(`Client id ${$clientId} is already registered`);
1662
+ this.__api.checkWritesAllowed();
1663
+ }
1664
+ let clientId = $clientId;
1665
+ if (clientId === void 0) {
1666
+ const counter = this.#createCounter ??= /* @__PURE__ */ new Map();
1667
+ let i = counter.get(meta.tagName) ?? 0;
1668
+ do
1669
+ clientId = `${meta.tagName}#${++i}`;
1670
+ while (this.#getEntity(clientId));
1671
+ counter.set(meta.tagName, i);
1672
+ }
1673
+ const entity = require_newEntity.newEntity(this, type, true);
1674
+ const data = require_BaseEntity.getInstanceData(entity);
1675
+ data.clientId = clientId;
1676
+ this.#doRegister(entity, fields.id);
1618
1677
  const baseMeta = require_EntityMetadata.getBaseMeta(require_EntityMetadata.getMetadata(entity));
1619
1678
  if (baseMeta.timestampFields) this.#assignTimestamps(entity, baseMeta);
1620
1679
  if (baseMeta.inheritanceType === "sti") setStiDiscriminatorValue(baseMeta, entity);
1621
1680
  getEmInternalApi(this)?.fieldLogger.logCreate(entity);
1622
- require_index.setOpts(entity, opts, {
1681
+ require_index.setOpts(entity, fields, {
1623
1682
  partial,
1624
1683
  calledFromConstructor: true
1625
1684
  });
@@ -1640,7 +1699,9 @@ var EntityManager = class EntityManager {
1640
1699
  if (maybeId) {
1641
1700
  if (!skipDuplicateCheck && this.#getEntity(maybeId) !== void 0) throw new Error(`Entity ${entity} has a duplicate instance already loaded`);
1642
1701
  this.#entitiesById.set(maybeId, entity);
1643
- } else this.#entitiesById.set(entity.toTaggedString(), entity);
1702
+ }
1703
+ const clientId = require_BaseEntity.getInstanceData(entity).clientId;
1704
+ if (clientId) this.#entitiesById.set(clientId, entity);
1644
1705
  require_BaseEntity.getInstanceData(entity).entityIndex = this.#entitiesArray.length;
1645
1706
  this.#entitiesArray.push(entity);
1646
1707
  meta ??= require_EntityMetadata.getMetadata(entity);