@contember/binding 1.2.0-alpha.8 → 1.2.0-beta.0

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 (49) hide show
  1. package/dist/development/accessors/EntityAccessor.js +66 -22
  2. package/dist/development/accessors/EntityAccessor.js.map +1 -1
  3. package/dist/development/core/operations/EntityOperations.js +13 -8
  4. package/dist/development/core/operations/EntityOperations.js.map +1 -1
  5. package/dist/development/dao/TreeNodeEnvironmentFactory.js +6 -76
  6. package/dist/development/dao/TreeNodeEnvironmentFactory.js.map +1 -1
  7. package/dist/development/markers/PlaceholderGenerator.js +5 -4
  8. package/dist/development/markers/PlaceholderGenerator.js.map +1 -1
  9. package/dist/development/markers/PlaceholderParametersGenerator.js +62 -0
  10. package/dist/development/markers/PlaceholderParametersGenerator.js.map +1 -0
  11. package/dist/development/utils/Hashing.js +2 -56
  12. package/dist/development/utils/Hashing.js.map +1 -1
  13. package/dist/development/utils/TreeNodeUtils.js +77 -0
  14. package/dist/development/utils/TreeNodeUtils.js.map +1 -0
  15. package/dist/production/accessors/EntityAccessor.js +66 -22
  16. package/dist/production/accessors/EntityAccessor.js.map +1 -1
  17. package/dist/production/core/operations/EntityOperations.js +13 -8
  18. package/dist/production/core/operations/EntityOperations.js.map +1 -1
  19. package/dist/production/dao/TreeNodeEnvironmentFactory.js +6 -76
  20. package/dist/production/dao/TreeNodeEnvironmentFactory.js.map +1 -1
  21. package/dist/production/markers/PlaceholderGenerator.js +5 -4
  22. package/dist/production/markers/PlaceholderGenerator.js.map +1 -1
  23. package/dist/production/markers/PlaceholderParametersGenerator.js +62 -0
  24. package/dist/production/markers/PlaceholderParametersGenerator.js.map +1 -0
  25. package/dist/production/utils/Hashing.js +2 -56
  26. package/dist/production/utils/Hashing.js.map +1 -1
  27. package/dist/production/utils/TreeNodeUtils.js +77 -0
  28. package/dist/production/utils/TreeNodeUtils.js.map +1 -0
  29. package/dist/types/accessors/EntityAccessor.d.ts +9 -4
  30. package/dist/types/accessors/EntityAccessor.d.ts.map +1 -1
  31. package/dist/types/core/operations/EntityOperations.d.ts.map +1 -1
  32. package/dist/types/dao/TreeNodeEnvironmentFactory.d.ts +0 -8
  33. package/dist/types/dao/TreeNodeEnvironmentFactory.d.ts.map +1 -1
  34. package/dist/types/markers/PlaceholderGenerator.d.ts.map +1 -1
  35. package/dist/types/markers/PlaceholderParametersGenerator.d.ts +9 -0
  36. package/dist/types/markers/PlaceholderParametersGenerator.d.ts.map +1 -0
  37. package/dist/types/tsconfig.tsbuildinfo +1 -1
  38. package/dist/types/utils/Hashing.d.ts +1 -7
  39. package/dist/types/utils/Hashing.d.ts.map +1 -1
  40. package/dist/types/utils/TreeNodeUtils.d.ts +13 -0
  41. package/dist/types/utils/TreeNodeUtils.d.ts.map +1 -0
  42. package/package.json +5 -5
  43. package/src/accessors/EntityAccessor.ts +96 -28
  44. package/src/core/operations/EntityOperations.ts +16 -11
  45. package/src/dao/TreeNodeEnvironmentFactory.ts +6 -92
  46. package/src/markers/PlaceholderGenerator.ts +6 -5
  47. package/src/markers/PlaceholderParametersGenerator.ts +79 -0
  48. package/src/utils/Hashing.ts +2 -68
  49. package/src/utils/TreeNodeUtils.ts +92 -0
@@ -1,60 +1,6 @@
1
1
  class Hashing {
2
- static hashHasOneRelation(relation) {
3
- const where = [
4
- "upToOne",
5
- relation.field,
6
- relation.filter,
7
- relation.reducedBy
8
- ];
9
- return Hashing.hashArray(where);
10
- }
11
- static hashHasManyRelation(relation) {
12
- const where = [
13
- "possiblyMany",
14
- relation.field,
15
- relation.filter,
16
- "offset" in relation ? relation.offset : void 0,
17
- "limit" in relation ? relation.limit : void 0,
18
- "orderBy" in relation ? relation.orderBy : void 0
19
- ];
20
- return Hashing.hashArray(where);
21
- }
22
- static hashEntityListSubTreeParameters(parameters, environment) {
23
- if (parameters.isCreating) {
24
- return Hashing.hashArray([
25
- parameters.isCreating,
26
- parameters.entityName,
27
- environment.getAllVariables()
28
- ]);
29
- }
30
- return Hashing.hashArray([
31
- parameters.isCreating,
32
- parameters.entityName,
33
- parameters.filter,
34
- parameters.orderBy,
35
- parameters.offset,
36
- parameters.limit,
37
- environment.getAllVariables()
38
- ]);
39
- }
40
- static hashEntitySubTreeParameters(parameters, environment) {
41
- if (parameters.isCreating) {
42
- return Hashing.hashArray([
43
- parameters.isCreating,
44
- parameters.entityName,
45
- environment.getAllVariables()
46
- ]);
47
- }
48
- return Hashing.hashArray([
49
- parameters.isCreating,
50
- parameters.where,
51
- parameters.entityName,
52
- parameters.filter,
53
- environment.getAllVariables()
54
- ]);
55
- }
56
- static hashArray(array) {
57
- const json = array.map((item) => JSON.stringify(item)).join("_");
2
+ static hashAny(array) {
3
+ const json = JSON.stringify(array);
58
4
  return Hashing.hash(json);
59
5
  }
60
6
  // Taken from Java
@@ -1 +1 @@
1
- {"version":3,"file":"Hashing.js","sources":["../../../src/utils/Hashing.ts"],"sourcesContent":["import type {\n\tHasManyRelation,\n\tHasOneRelation,\n\tQualifiedEntityList,\n\tQualifiedSingleEntity,\n\tUnconstrainedQualifiedEntityList,\n\tUnconstrainedQualifiedSingleEntity,\n} from '../treeParameters'\nimport { Environment } from '../dao'\n\n// TODO update hashing so that for offset, 0 == undefined\nexport class Hashing {\n\tpublic static hashHasOneRelation(relation: HasOneRelation): number {\n\t\tconst where = [\n\t\t\t'upToOne',\n\t\t\trelation.field,\n\t\t\trelation.filter,\n\t\t\trelation.reducedBy,\n\t\t]\n\n\t\treturn Hashing.hashArray(where)\n\t}\n\n\tpublic static hashHasManyRelation(relation: HasManyRelation): number {\n\t\tconst where = [\n\t\t\t'possiblyMany',\n\t\t\trelation.field,\n\t\t\trelation.filter,\n\t\t\t'offset' in relation ? relation.offset : undefined,\n\t\t\t'limit' in relation ? relation.limit : undefined,\n\t\t\t'orderBy' in relation ? relation.orderBy : undefined,\n\t\t]\n\n\t\treturn Hashing.hashArray(where)\n\t}\n\n\tpublic static hashEntityListSubTreeParameters(\n\t\tparameters: QualifiedEntityList | UnconstrainedQualifiedEntityList,\n\t\tenvironment: Environment,\n\t): number {\n\t\tif (parameters.isCreating) {\n\t\t\treturn Hashing.hashArray([\n\t\t\t\tparameters.isCreating,\n\t\t\t\tparameters.entityName,\n\t\t\t\tenvironment.getAllVariables(),\n\t\t\t])\n\t\t}\n\t\treturn Hashing.hashArray([\n\t\t\tparameters.isCreating,\n\t\t\tparameters.entityName,\n\t\t\tparameters.filter,\n\t\t\tparameters.orderBy,\n\t\t\tparameters.offset,\n\t\t\tparameters.limit,\n\t\t\tenvironment.getAllVariables(),\n\t\t])\n\t}\n\n\tpublic static hashEntitySubTreeParameters(\n\t\tparameters: QualifiedSingleEntity | UnconstrainedQualifiedSingleEntity,\n\t\tenvironment: Environment,\n\t): number {\n\t\tif (parameters.isCreating) {\n\t\t\treturn Hashing.hashArray([\n\t\t\t\tparameters.isCreating,\n\t\t\t\tparameters.entityName,\n\t\t\t\tenvironment.getAllVariables(),\n\t\t\t])\n\t\t}\n\t\treturn Hashing.hashArray([\n\t\t\tparameters.isCreating,\n\t\t\tparameters.where,\n\t\t\tparameters.entityName,\n\t\t\tparameters.filter,\n\t\t\tenvironment.getAllVariables(),\n\t\t])\n\t}\n\n\tprivate static hashArray(array: any[]): number {\n\t\tconst json = array.map(item => JSON.stringify(item)).join('_')\n\t\treturn Hashing.hash(json)\n\t}\n\n\t// Taken from Java\n\tpublic static hash(str: string): number {\n\t\tlet hash = 0\n\t\tif (str.length === 0) {\n\t\t\treturn hash\n\t\t}\n\t\tfor (let i = 0; i < str.length; i++) {\n\t\t\thash = (hash << 5) - hash + str.charCodeAt(i)\n\t\t\thash = hash & hash // Convert to 32bit integer\n\t\t}\n\t\treturn Math.abs(hash)\n\t}\n}\n"],"names":[],"mappings":"AAWO,MAAM,QAAQ;AAAA,EACpB,OAAc,mBAAmB,UAAkC;AAClE,UAAM,QAAQ;AAAA,MACb;AAAA,MACA,SAAS;AAAA,MACT,SAAS;AAAA,MACT,SAAS;AAAA,IAA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ACd,aAAA;AAAA,IACR;AACA,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACpC,cAAQ,QAAQ,KAAK,OAAO,IAAI,WAAW,CAAC;AAC5C,aAAO,OAAO;AAAA,IACf;AACO,WAAA,KAAK,IAAI,IAAI;AAAA,EACrB;AACD;"}
1
+ {"version":3,"file":"Hashing.js","sources":["../../../src/utils/Hashing.ts"],"sourcesContent":["import type {\n\tHasManyRelation,\n\tHasOneRelation,\n\tQualifiedEntityList,\n\tQualifiedSingleEntity,\n\tUnconstrainedQualifiedEntityList,\n\tUnconstrainedQualifiedSingleEntity,\n} from '../treeParameters'\nimport { Environment } from '../dao'\n\n// TODO update hashing so that for offset, 0 == undefined\nexport class Hashing {\n\tpublic static hashAny(array: any[]): number {\n\t\tconst json = JSON.stringify(array)\n\t\treturn Hashing.hash(json)\n\t}\n\n\t// Taken from Java\n\tpublic static hash(str: string): number {\n\t\tlet hash = 0\n\t\tif (str.length === 0) {\n\t\t\treturn hash\n\t\t}\n\t\tfor (let i = 0; i < str.length; i++) {\n\t\t\thash = (hash << 5) - hash + str.charCodeAt(i)\n\t\t\thash = hash & hash // Convert to 32bit integer\n\t\t}\n\t\treturn Math.abs(hash)\n\t}\n}\n"],"names":[],"mappings":"AAWO,MAAM,QAAQ;AAAA,EACpB,OAAc,QAAQ,OAAsB;AACrC,UAAA,OAAO,KAAK,UAAU,KAAK;AAC1B,WAAA,QAAQ,KAAK,IAAI;AAAA,EACzB;AAAA;AAAA,EAGA,OAAc,KAAK,KAAqB;AACvC,QAAI,OAAO;AACP,QAAA,IAAI,WAAW,GAAG;AACd,aAAA;AAAA,IACR;AACA,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACpC,cAAQ,QAAQ,KAAK,OAAO,IAAI,WAAW,CAAC;AAC5C,aAAO,OAAO;AAAA,IACf;AACO,WAAA,KAAK,IAAI,IAAI;AAAA,EACrB;AACD;"}
@@ -0,0 +1,77 @@
1
+ import { BindingError } from "../BindingError.js";
2
+ import levenshtein from "js-levenshtein";
3
+ class TreeNodeUtils {
4
+ static resolveEntity(schema, entityName, type) {
5
+ const entity = schema.getEntityOrUndefined(entityName);
6
+ if (!entity) {
7
+ const alternative = this.recommendAlternative(entityName, schema.getEntityNames());
8
+ const didYouMean = alternative ? `Did you mean '${alternative}'?` : "";
9
+ throw new BindingError(`Invalid ${type} sub tree: Entity '${entityName}' doesn't exist. ${didYouMean}`);
10
+ }
11
+ return entity;
12
+ }
13
+ static resolveHasOneRelation(environment, field, isReduced) {
14
+ if (isReduced) {
15
+ return this.resolveRelation(environment, field, "reduced has-one relation", ["ManyHasMany", "OneHasMany"]);
16
+ }
17
+ return this.resolveRelation(environment, field, "a has-one relation", ["ManyHasOne", "OneHasOne"]);
18
+ }
19
+ static resolveHasManyRelation(environment, field) {
20
+ return this.resolveRelation(environment, field, "a has-many relation", ["ManyHasMany", "OneHasMany"]);
21
+ }
22
+ static resolveRelation(environment, field, relationDescription, expectedRelationType) {
23
+ return this.resolveField(environment, field, (field2) => {
24
+ return field2.__typename === "_Relation" && expectedRelationType.includes(field2.type);
25
+ }, relationDescription);
26
+ }
27
+ static resolveColumn(environment, fieldName) {
28
+ return this.resolveField(environment, fieldName, (field) => field.__typename === "_Column", "an ordinary field");
29
+ }
30
+ static resolveField(environment, fieldName, matcher, expectedDescription) {
31
+ const treeLocation = environment.getSubTreeNode();
32
+ const entity = treeLocation.entity;
33
+ const field = entity.fields.get(fieldName);
34
+ if (!field) {
35
+ const alternative = this.recommendAlternative(
36
+ fieldName,
37
+ Array.from(entity.fields).filter(([, field2]) => matcher(field2)).map(([fieldName2]) => fieldName2)
38
+ );
39
+ const didYouMean = alternative ? `Did you mean '${alternative}'?` : "";
40
+ throw new BindingError(`Field '${fieldName}' doesn't exist on ${this.describeLocation(environment)}. ${didYouMean}`);
41
+ }
42
+ if (!matcher(field)) {
43
+ const actual = field.__typename === "_Column" ? "an ordinary field" : `a ${field.type} relation`;
44
+ throw new BindingError(
45
+ `Invalid field: the name '${field.name}' on ${this.describeLocation(environment)} refers to ${actual} but is being used as a ${expectedDescription}.`
46
+ );
47
+ }
48
+ return field;
49
+ }
50
+ static describeLocation(environment) {
51
+ const path = [];
52
+ const loc = environment.getSubTreeNode();
53
+ for (let env = environment; ; env = env.getParent()) {
54
+ const node = env.getSubTreeNode();
55
+ if (node.type === "subtree-entity" || node.type === "subtree-entity-list") {
56
+ return `entity '${loc.entity.name}' in path '${[node.entity.name, ...path.reverse()].join(".")}'`;
57
+ }
58
+ path.push(node.field.name);
59
+ }
60
+ }
61
+ static recommendAlternative(original, possibleAlternatives) {
62
+ let bestAlternative = void 0;
63
+ let bestAlternativeDistance = Number.MAX_SAFE_INTEGER;
64
+ for (const alternative of possibleAlternatives) {
65
+ const distance = levenshtein(original, alternative);
66
+ if (distance < bestAlternativeDistance) {
67
+ bestAlternative = alternative;
68
+ bestAlternativeDistance = distance;
69
+ }
70
+ }
71
+ return bestAlternative;
72
+ }
73
+ }
74
+ export {
75
+ TreeNodeUtils
76
+ };
77
+ //# sourceMappingURL=TreeNodeUtils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TreeNodeUtils.js","sources":["../../../src/utils/TreeNodeUtils.ts"],"sourcesContent":["import { Environment } from '../dao'\nimport { BaseRelation, Schema, SchemaColumn, SchemaEntity, SchemaField, SchemaRelation } from '../core'\nimport { BindingError } from '../BindingError'\nimport levenshtein from 'js-levenshtein'\n\nexport class TreeNodeUtils {\n\n\tpublic static resolveEntity(schema: Schema, entityName: string, type: 'entity' | 'entity list'): SchemaEntity {\n\t\tconst entity = schema.getEntityOrUndefined(entityName)\n\t\tif (!entity) {\n\t\t\tconst alternative = this.recommendAlternative(entityName, schema.getEntityNames())\n\t\t\tconst didYouMean = alternative ? `Did you mean '${alternative}'?` : ''\n\t\t\tthrow new BindingError(`Invalid ${type} sub tree: Entity '${entityName}' doesn't exist. ${didYouMean}`)\n\t\t}\n\t\treturn entity\n\t}\n\n\tpublic static resolveHasOneRelation(environment: Environment, field: string, isReduced: boolean): SchemaRelation {\n\t\tif (isReduced) {\n\t\t\treturn this.resolveRelation(environment, field, 'reduced has-one relation', ['ManyHasMany', 'OneHasMany'])\n\t\t}\n\t\treturn this.resolveRelation(environment, field, 'a has-one relation', ['ManyHasOne', 'OneHasOne'])\n\t}\n\n\n\tpublic static resolveHasManyRelation(environment: Environment, field: string): SchemaRelation {\n\t\treturn this.resolveRelation(environment, field, 'a has-many relation', ['ManyHasMany', 'OneHasMany'])\n\t}\n\n\tprivate static resolveRelation(environment: Environment, field: string, relationDescription: string, expectedRelationType: BaseRelation['type'][]): SchemaRelation {\n\t\treturn this.resolveField(environment, field, (field): field is SchemaRelation => {\n\t\t\treturn field.__typename === '_Relation' && expectedRelationType.includes(field.type)\n\t\t}, relationDescription)\n\t}\n\n\tpublic static resolveColumn(environment: Environment, fieldName: string): SchemaColumn {\n\t\treturn this.resolveField(environment, fieldName, (field): field is SchemaColumn => field.__typename === '_Column', 'an ordinary field')\n\t\t// TODO check that defaultValue matches the type\n\t\t// TODO run custom validators\n\t}\n\n\tprivate static resolveField<T extends SchemaField>(environment: Environment, fieldName: string, matcher: (field: SchemaField) => field is T, expectedDescription: string): T {\n\t\tconst treeLocation = environment.getSubTreeNode()\n\t\tconst entity = treeLocation.entity\n\t\tconst field = entity.fields.get(fieldName)\n\t\tif (!field) {\n\t\t\tconst alternative = this.recommendAlternative(\n\t\t\t\tfieldName,\n\t\t\t\tArray.from(entity.fields)\n\t\t\t\t\t.filter(([, field]) => matcher(field))\n\t\t\t\t\t.map(([fieldName]) => fieldName),\n\t\t\t)\n\t\t\tconst didYouMean = alternative ? `Did you mean '${alternative}'?` : ''\n\t\t\tthrow new BindingError(`Field '${fieldName}' doesn't exist on ${this.describeLocation(environment)}. ${didYouMean}`)\n\t\t}\n\t\tif (!matcher(field)) {\n\t\t\tconst actual = field.__typename === '_Column' ? 'an ordinary field' : `a ${field.type} relation`\n\t\t\tthrow new BindingError(\n\t\t\t\t`Invalid field: the name '${field.name}' on ${this.describeLocation(environment)} ` +\n\t\t\t\t`refers to ${actual} but is being used as a ${expectedDescription}.`,\n\t\t\t)\n\t\t}\n\t\treturn field\n\t}\n\n\tpublic static describeLocation(environment: Environment): string {\n\t\tconst path = []\n\t\tconst loc = environment.getSubTreeNode()\n\t\tfor (let env = environment; ; env = env.getParent()) {\n\t\t\tconst node = env.getSubTreeNode()\n\t\t\tif (node.type === 'subtree-entity' || node.type === 'subtree-entity-list') {\n\t\t\t\treturn `entity '${loc.entity.name}' in path '${[node.entity.name, ...path.reverse()].join('.')}'`\n\t\t\t}\n\t\t\tpath.push(node.field.name)\n\t\t}\n\t}\n\n\tpublic static recommendAlternative(original: string, possibleAlternatives: Iterable<string>): string | undefined {\n\t\tlet bestAlternative: string | undefined = undefined\n\t\tlet bestAlternativeDistance = Number.MAX_SAFE_INTEGER\n\n\t\tfor (const alternative of possibleAlternatives) {\n\t\t\tconst distance = levenshtein(original, alternative)\n\n\t\t\tif (distance < bestAlternativeDistance) {\n\t\t\t\tbestAlternative = alternative\n\t\t\t\tbestAlternativeDistance = distance\n\t\t\t}\n\t\t}\n\t\treturn bestAlternative\n\t}\n}\n"],"names":["field","fieldName"],"mappings":";;AAKO,MAAM,cAAc;AAAA,EAE1B,OAAc,cAAc,QAAgB,YAAoB,MAA8C;AACvG,UAAA,SAAS,OAAO,qBAAqB,UAAU;AACrD,QAAI,CAAC,QAAQ;AACZ,YAAM,cAAc,KAAK,qBAAqB,YAAY,OAAO,gBAAgB;AAC3E,YAAA,aAAa,cAAc,iBAAiB,kBAAkB;AACpE,YAAM,IAAI,aAAa,WAAW,0BAA0B,8BAA8B,YAAY;AAAA,IACvG;AACO,WAAA;AAAA,EACR;AAAA,EAEA,OAAc,sBAAsB,aAA0B,OAAe,WAAoC;AAChH,QAAI,WAAW;AACP,aAAA,KAAK,gBAAgB,aAAa,OAAO,4BAA4B,CAAC,eAAe,YAAY,CAAC;AAAA,IAC1G;AACO,WA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,EAEA,OAAc,iBAAiB,aAAkC;AAChE,UAAM,OAAO,CAAA;AACP,UAAA,MAAM,YAAY;AACxB,aAAS,MAAM,eAAe,MAAM,IAAI,aAAa;AAC9C,YAAA,OAAO,IAAI;AACjB,UAAI,KAAK,SAAS,oBAAoB,KAAK,SAAS,uBAAuB;AAC1E,eAAO,WAAW,IAAI,OAAO,kBAAkB,CAAC,KAAK,OAAO,MAAM,GAAG,KAAK,QAAS,CAAA,EAAE,KAAK,GAAG;AAAA,MAC9F;AACK,WAAA,KAAK,KAAK,MAAM,IAAI;AAAA,IAC1B;AAAA,EACD;AAAA,EAEA,OAAc,qBAAqB,UAAkB,sBAA4D;AAChH,QAAI,kBAAsC;AAC1C,QAAI,0BAA0B,OAAO;AAErC,eAAW,eAAe,sBAAsB;AACzC,YAAA,WAAW,YAAY,UAAU,WAAW;AAElD,UAAI,WAAW,yBAAyB;AACrB,0BAAA;AACQ,kCAAA;AAAA,MAC3B;AAAA,IACD;AACO,WAAA;AAAA,EACR;AACD;"}
@@ -1,8 +1,12 @@
1
1
  import { BindingError } from "../BindingError.js";
2
2
  import { ErrorAccessor } from "./ErrorAccessor.js";
3
+ import { TreeNodeUtils } from "../utils/TreeNodeUtils.js";
4
+ import { PlaceholderParametersGenerator } from "../markers/PlaceholderParametersGenerator.js";
3
5
  import { QueryLanguage } from "../queryLanguage/QueryLanguage.js";
4
6
  import { PlaceholderGenerator } from "../markers/PlaceholderGenerator.js";
5
7
  import { getEntityMarker } from "../core/state/getEntityMarker.js";
8
+ import { HasOneRelationMarker } from "../markers/HasOneRelationMarker.js";
9
+ import { HasManyRelationMarker } from "../markers/HasManyRelationMarker.js";
6
10
  class EntityAccessor {
7
11
  constructor(state, operations, runtimeId, key, name, fieldData, dataFromServer, hasUnpersistedChanges, errors, environment, getAccessor) {
8
12
  this.state = state;
@@ -75,24 +79,79 @@ class EntityAccessor {
75
79
  * @see EntityAccessor.getField
76
80
  */
77
81
  getRelativeSingleField(field) {
78
- return this.getRelativeSingleEntity(field).getAccessorByPlaceholder(
79
- PlaceholderGenerator.getFieldPlaceholder(field.field)
82
+ const entity = this.getRelativeSingleEntity(field);
83
+ const fieldPlaceholder = PlaceholderGenerator.getFieldPlaceholder(field.field);
84
+ const accessor = entity.fieldData.get(fieldPlaceholder);
85
+ if (accessor) {
86
+ return accessor.getAccessor();
87
+ }
88
+ TreeNodeUtils.resolveColumn(entity.environment, field.field);
89
+ throw new BindingError(
90
+ `EntityAccessor: cannot access field '${field.field}' on ${TreeNodeUtils.describeLocation(entity.environment)}.
91
+ The cause of the error is that this relation has not been registered during the static rendering process. As a result, it lacks a required marker and accessor.`
80
92
  );
81
93
  }
82
94
  getRelativeSingleEntity(relativeSingleEntity) {
83
95
  let relativeTo = this;
84
96
  for (const hasOneRelation of relativeSingleEntity.hasOneRelationPath) {
85
- relativeTo = relativeTo.getAccessorByPlaceholder(
86
- PlaceholderGenerator.getHasOneRelationPlaceholder(hasOneRelation)
87
- );
97
+ const fieldPlaceholder = PlaceholderGenerator.getHasOneRelationPlaceholder(hasOneRelation);
98
+ const accessor = relativeTo.fieldData.get(fieldPlaceholder);
99
+ if (!accessor) {
100
+ return this.raiseInvalidHasOneRelationError(relativeTo, hasOneRelation);
101
+ }
102
+ relativeTo = accessor.getAccessor();
88
103
  }
89
104
  return relativeTo;
90
105
  }
91
106
  getRelativeEntityList(entityList) {
92
- return this.getRelativeSingleEntity(entityList).getAccessorByPlaceholder(
93
- PlaceholderGenerator.getHasManyRelationPlaceholder(entityList.hasManyRelation)
107
+ const entity = this.getRelativeSingleEntity(entityList);
108
+ const fieldPlaceholder = PlaceholderGenerator.getHasManyRelationPlaceholder(entityList.hasManyRelation);
109
+ const accessor = entity.fieldData.get(fieldPlaceholder);
110
+ if (!accessor) {
111
+ return this.raiseInvalidHasManyRelationError(entity, entityList.hasManyRelation);
112
+ }
113
+ return accessor.getAccessor();
114
+ }
115
+ raiseInvalidHasOneRelationError(relativeTo, hasOneRelation) {
116
+ TreeNodeUtils.resolveHasOneRelation(relativeTo.environment, hasOneRelation.field, !!hasOneRelation.reducedBy);
117
+ const entityMarker = relativeTo.getMarker();
118
+ const possibleMarkers = this.getMarkersOfType(entityMarker.fields.markers, HasOneRelationMarker, hasOneRelation.field);
119
+ const markerParams = possibleMarkers.map((it) => PlaceholderParametersGenerator.createHasOneRelationParameters(it.parameters));
120
+ const relationParams = PlaceholderParametersGenerator.createHasOneRelationParameters(hasOneRelation);
121
+ this.raiseUndefinedRelationError(hasOneRelation.field, relativeTo.environment, relationParams, markerParams);
122
+ }
123
+ raiseInvalidHasManyRelationError(entity, hasManyRelation) {
124
+ TreeNodeUtils.resolveHasManyRelation(entity.environment, hasManyRelation.field);
125
+ const entityMarker = entity.getMarker();
126
+ const possibleMarkers = this.getMarkersOfType(entityMarker.fields.markers, HasManyRelationMarker, hasManyRelation.field);
127
+ const markerParams = possibleMarkers.map((it) => PlaceholderParametersGenerator.createHasManyRelationParameters(it.parameters));
128
+ const relationParams = PlaceholderParametersGenerator.createHasManyRelationParameters(hasManyRelation);
129
+ this.raiseUndefinedRelationError(hasManyRelation.field, entity.environment, relationParams, markerParams);
130
+ }
131
+ raiseUndefinedRelationError(field, environment, relationParams, otherMarkersParams) {
132
+ const hint = this.createHintMessage(otherMarkersParams);
133
+ throw new BindingError(
134
+ `EntityAccessor: cannot access relation '${field}' on ${TreeNodeUtils.describeLocation(environment)}.
135
+ The cause of the error is that this relation has not been registered during the static rendering process. As a result, it lacks a required marker and accessor.
136
+
137
+ Provided parameters:
138
+ ` + JSON.stringify(relationParams) + hint
94
139
  );
95
140
  }
141
+ createHintMessage(params) {
142
+ if (params.length === 0) {
143
+ return "";
144
+ }
145
+ const serializedParams = params.map((it) => JSON.stringify(it)).join("\n");
146
+ const message = params.length === 1 ? "However, there is existing marker for the same field, but it have different parameters:" : "However, there are existing markers for the same field, but they have different parameters:";
147
+ return `
148
+
149
+ ${message}
150
+ ${serializedParams}`;
151
+ }
152
+ getMarkersOfType(markers, markerConstructor, fieldName) {
153
+ return Array.from(markers.values()).filter((it) => it instanceof markerConstructor && it.parameters.field === fieldName);
154
+ }
96
155
  getParent() {
97
156
  const blueprint = this.state.blueprint;
98
157
  if (blueprint.type === "subTree") {
@@ -103,21 +162,6 @@ class EntityAccessor {
103
162
  getMarker() {
104
163
  return getEntityMarker(this.state);
105
164
  }
106
- getAccessorByPlaceholder(placeholderName) {
107
- const record = this.fieldData.get(placeholderName);
108
- if (record === void 0) {
109
- throw new BindingError(
110
- `EntityAccessor: unknown field placeholder '${placeholderName} on ${this.name}'. Unless this is just a typo, this is typically caused by one of the following:
111
- • Trying to access a field that has not been registered during static render, and thus lacks a marker and an accessor.
112
- • Misusing an EntityAccessor getter. If you used one of the getRelative[…] family, please make sure all parameters match the marker tree exactly.
113
-
114
- For more information, please consult the documentation.
115
-
116
- `
117
- );
118
- }
119
- return record.getAccessor();
120
- }
121
165
  }
122
166
  export {
123
167
  EntityAccessor
@@ -1 +1 @@
1
- {"version":3,"file":"EntityAccessor.js","sources":["../../../src/accessors/EntityAccessor.ts"],"sourcesContent":["import { RuntimeId, SingleEntityPersistedData } from '../accessorTree'\nimport { BindingError } from '../BindingError'\nimport type { EntityOperations } from '../core/operations'\nimport type { Environment } from '../dao'\nimport { PlaceholderGenerator } from '../markers'\nimport { QueryLanguage } from '../queryLanguage'\nimport type {\n\tEntityId,\n\tEntityName,\n\tEntityRealmKey,\n\tFieldName,\n\tFieldValue,\n\tRelativeEntityList,\n\tRelativeSingleEntity,\n\tRelativeSingleField,\n\tSugaredRelativeEntityList,\n\tSugaredRelativeSingleEntity,\n\tSugaredRelativeSingleField,\n} from '../treeParameters'\nimport type { AsyncBatchUpdatesOptions } from './AsyncBatchUpdatesOptions'\nimport type { BatchUpdatesOptions } from './BatchUpdatesOptions'\nimport type { EntityListAccessor } from './EntityListAccessor'\nimport type { Errorable } from './Errorable'\nimport { ErrorAccessor } from './ErrorAccessor'\nimport type { FieldAccessor } from './FieldAccessor'\nimport type { PersistErrorOptions } from './PersistErrorOptions'\nimport type { PersistSuccessOptions } from './PersistSuccessOptions'\nimport type { EntityRealmState } from '../core/state'\nimport { getEntityMarker } from '../core/state'\n\nclass EntityAccessor implements Errorable {\n\tpublic constructor(\n\t\tprivate readonly state: EntityRealmState,\n\t\tprivate readonly operations: EntityOperations,\n\t\tprivate readonly runtimeId: RuntimeId,\n\t\tpublic readonly key: EntityRealmKey, // ⚠️ This is *NOT* the id! ⚠️\n\t\tpublic readonly name: EntityName,\n\t\tprivate readonly fieldData: EntityAccessor.FieldData,\n\t\tprivate readonly dataFromServer: SingleEntityPersistedData | undefined,\n\t\tpublic readonly hasUnpersistedChanges: boolean,\n\t\tpublic readonly errors: ErrorAccessor | undefined,\n\t\tpublic readonly environment: Environment,\n\t\tpublic readonly getAccessor: EntityAccessor.GetEntityAccessor,\n\t) {}\n\n\tpublic get idOnServer(): EntityId | undefined {\n\t\treturn this.runtimeId.existsOnServer ? this.runtimeId.value : undefined\n\t}\n\n\t/**\n\t * Note that for entities that don't yet exist on server this will return a dummy id.\n\t */\n\tpublic get id(): EntityId {\n\t\treturn this.runtimeId.value\n\t}\n\n\tpublic get existsOnServer(): boolean {\n\t\treturn this.runtimeId.existsOnServer\n\t}\n\n\t//\n\n\tpublic addError(error: ErrorAccessor.Error | string): () => void {\n\t\treturn this.operations.addError(this.state, ErrorAccessor.normalizeError(error))\n\t}\n\n\tpublic addEventListener<Type extends keyof EntityAccessor.RuntimeEntityEventListenerMap>(\n\t\tevent: { type: Type; key?: string },\n\t\tlistener: EntityAccessor.EntityEventListenerMap[Type],\n\t): () => void {\n\t\treturn this.operations.addEventListener(this.state, event, listener)\n\t}\n\n\tpublic batchUpdates(performUpdates: EntityAccessor.BatchUpdatesHandler): void {\n\t\tthis.operations.batchUpdates(this.state, performUpdates)\n\t}\n\n\tpublic connectEntityAtField(field: FieldName, entityToConnect: EntityAccessor): void {\n\t\tthis.operations.connectEntityAtField(this.state, field, entityToConnect)\n\t}\n\n\tpublic disconnectEntityAtField(field: FieldName, initializeReplacement?: EntityAccessor.BatchUpdatesHandler): void {\n\t\tthis.operations.disconnectEntityAtField(this.state, field, initializeReplacement)\n\t}\n\n\tpublic deleteEntity(): void {\n\t\tthis.operations.deleteEntity(this.state)\n\t}\n\n\t//\n\n\tpublic updateValues(fieldValuePairs: EntityAccessor.FieldValuePairs): void {\n\t\tthis.batchUpdates(getAccessor => {\n\t\t\tconst entries = Array.isArray(fieldValuePairs) ? fieldValuePairs : Object.entries(fieldValuePairs)\n\n\t\t\tfor (const [field, value] of entries) {\n\t\t\t\tgetAccessor().getField(field).updateValue(value)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Please keep in mind that this method signature is literally impossible to implement safely. The generic parameter\n\t * is really just a way to succinctly write a type cast. Nothing more, really.\n\t */\n\tpublic getField<Value extends FieldValue = FieldValue>(\n\t\tfield: SugaredRelativeSingleField | string,\n\t): FieldAccessor<Value> {\n\t\treturn this.getRelativeSingleField<Value>(QueryLanguage.desugarRelativeSingleField(field, this.environment))\n\t}\n\n\tpublic getEntity(entity: SugaredRelativeSingleEntity | string): EntityAccessor {\n\t\treturn this.getRelativeSingleEntity(QueryLanguage.desugarRelativeSingleEntity(entity, this.environment))\n\t}\n\n\tpublic getEntityList(entityList: SugaredRelativeEntityList | string): EntityListAccessor {\n\t\treturn this.getRelativeEntityList(QueryLanguage.desugarRelativeEntityList(entityList, this.environment))\n\t}\n\n\t//\n\n\t/**\n\t * @see EntityAccessor.getField\n\t */\n\tpublic getRelativeSingleField<Value extends FieldValue = FieldValue>(field: RelativeSingleField): FieldAccessor<Value> {\n\t\treturn this.getRelativeSingleEntity(field).getAccessorByPlaceholder(\n\t\t\tPlaceholderGenerator.getFieldPlaceholder(field.field),\n\t\t) as unknown as FieldAccessor<Value>\n\t}\n\n\tpublic getRelativeSingleEntity(relativeSingleEntity: RelativeSingleEntity): EntityAccessor {\n\t\tlet relativeTo: EntityAccessor = this\n\n\t\tfor (const hasOneRelation of relativeSingleEntity.hasOneRelationPath) {\n\t\t\trelativeTo = relativeTo.getAccessorByPlaceholder(\n\t\t\t\tPlaceholderGenerator.getHasOneRelationPlaceholder(hasOneRelation),\n\t\t\t) as EntityAccessor\n\t\t}\n\t\treturn relativeTo\n\t}\n\n\tpublic getRelativeEntityList(entityList: RelativeEntityList): EntityListAccessor {\n\t\treturn this.getRelativeSingleEntity(entityList).getAccessorByPlaceholder(\n\t\t\tPlaceholderGenerator.getHasManyRelationPlaceholder(entityList.hasManyRelation),\n\t\t) as EntityListAccessor\n\t}\n\n\tpublic getParent(): EntityAccessor | EntityListAccessor | undefined {\n\t\tconst blueprint = this.state.blueprint\n\t\tif (blueprint.type === 'subTree') {\n\t\t\treturn undefined\n\t\t}\n\t\treturn blueprint.parent.getAccessor()\n\t}\n\n\tpublic getMarker() {\n\t\treturn getEntityMarker(this.state)\n\t}\n\n\tprivate getAccessorByPlaceholder(placeholderName: FieldName): EntityAccessor.NestedAccessor {\n\t\tconst record = this.fieldData.get(placeholderName)\n\t\tif (record === undefined) {\n\t\t\tthrow new BindingError(\n\t\t\t\t`EntityAccessor: unknown field placeholder '${placeholderName} on ${this.name}'. Unless this is just a typo, this is ` +\n\t\t\t\t\t`typically caused by one of the following:\\n` +\n\t\t\t\t\t`\\t• Trying to access a field that has not been registered during static render, and thus lacks a marker and an accessor.\\n` +\n\t\t\t\t\t`\\t• Misusing an EntityAccessor getter. If you used one of the getRelative[…] family, please make sure all ` +\n\t\t\t\t\t`parameters match the marker tree exactly.` +\n\t\t\t\t\t`\\n\\nFor more information, please consult the documentation.\\n\\n`,\n\t\t\t)\n\t\t}\n\t\treturn record.getAccessor()\n\t}\n}\n\nnamespace EntityAccessor {\n\texport interface FieldDatum {\n\t\tgetAccessor(): NestedAccessor\n\t}\n\texport type NestedAccessor = EntityAccessor | EntityListAccessor | FieldAccessor\n\n\texport type FieldValuePairs =\n\t\t| {\n\t\t\t\t[field: string]: FieldValue\n\t\t }\n\t\t| Iterable<[SugaredRelativeSingleField | string, FieldValue]>\n\n\texport type FieldData = Map<FieldName, FieldDatum>\n\n\texport type GetEntityAccessor = () => EntityAccessor\n\texport type BatchUpdatesHandler = (getAccessor: GetEntityAccessor, options: BatchUpdatesOptions) => void\n\texport type UpdateListener = (accessor: EntityAccessor) => void\n\n\texport type BeforePersistHandler = (\n\t\tgetAccessor: GetEntityAccessor,\n\t\toptions: AsyncBatchUpdatesOptions,\n\t) => void | Promise<void | BeforePersistHandler>\n\n\texport type PersistErrorHandler = (\n\t\tgetAccessor: GetEntityAccessor,\n\t\toptions: PersistErrorOptions,\n\t) => void | Promise<void>\n\n\texport type PersistSuccessHandler = (\n\t\tgetAccessor: GetEntityAccessor,\n\t\toptions: PersistSuccessOptions,\n\t) => void | Promise<void | PersistSuccessHandler>\n\n\texport interface RuntimeEntityEventListenerMap {\n\t\tbeforePersist: BeforePersistHandler\n\t\tbeforeUpdate: BatchUpdatesHandler\n\t\tconnectionUpdate: UpdateListener\n\t\tpersistError: PersistErrorHandler\n\t\tpersistSuccess: PersistSuccessHandler\n\t\tupdate: UpdateListener\n\t}\n\texport interface EntityEventListenerMap extends RuntimeEntityEventListenerMap {\n\t\tinitialize: BatchUpdatesHandler\n\t}\n\texport type EntityEventType = keyof EntityEventListenerMap\n}\n\nexport { EntityAccessor }\n"],"names":[],"mappings":";;;;;AA8BA,MAAM,eAAoC;AAAA,EAClC,YACW,OACA,YACA,WACD,KACA,MACC,WACA,gBACD,uBACA,QACA,aACA,aACf;AAXgB,SAAA,QAAA;AACA,SAAA,aAAA;AACA,SAAA,YAAA;AACD,SAAA,MAAA;AACA,SAAA,OAAA;AACC,SAAA,YAAA;AACA,SAAA,iBAAA;AACD,SAAA,wBAAA;AACA,SAAA,SAAA;AACA,SAAA,cAAA;AACA,SAAA,cAAA;AAAA,EACd;AAAA,EAEH,IAAW,aAAmC;AAC7C,WAAO,KAAK,UAAU,iBAAiB,KAAK,UAAU,QAAQ;AAAA,EAC/D;AAAA;AAAA;AAAA;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Ac,0BAA0B,YAAY,KAAK,WAAW,CAAC;AAAA,EACxG;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,uBAA8D,OAAkD;AAC/G,WAAA,KAAK,wBAAwB,KAAK,EAAE;AAAA,MAC1C,qBAAqB,oBAAoB,MAAM,KAAK;AAAA,IAAA;AAAA,EAEtD;AAAA,EAEO,wBAAwB,sBAA4D;AAC1F,QAAI,aAA6B;AAEtB,eAAA,kBAAkB,qBAAqB,oBAAoB;AACrE,mBAAa,WAAW;AAAA,QACvB,qBAAqB,6BAA6B,cAAc;AAAA,MAAA;AAAA,IAElE;AACO,WAAA;AAAA,EACR;AAAA,EAEO,sBAAsB,YAAoD;AACzE,WAAA,KAAK,wBAAwB,UAAU,EAAE;AAAA,MAC/C,qBAAqB,8BAA8B,WAAW,eAAe;AAAA,IAAA;AAAA,EAE/E;AAAA,EAEO,YAA6D;AAC7D,UAAA,YAAY,KAAK,MAAM;AACzB,QAAA,UAAU,SAAS,WAAW;AAC1B,aAAA;AAAA,IACR;AACO,WAAA,UAAU,OAAO;EACzB;AAAA,EAEO,YAAY;AACX,WAAA,gBAAgB,KAAK,KAAK;AAAA,EAClC;AAAA,EAEQ,yBAAyB,iBAA2D;AAC3F,UAAM,SAAS,KAAK,UAAU,IAAI,eAAe;AACjD,QAAI,WAAW,QAAW;AACzB,YAAM,IAAI;AAAA,QACT,8CAA8C,sBAAsB,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAAA;AAAA,IAO3E;AACA,WAAO,OAAO;EACf;AACD;"}
1
+ {"version":3,"file":"EntityAccessor.js","sources":["../../../src/accessors/EntityAccessor.ts"],"sourcesContent":["import { RuntimeId, SingleEntityPersistedData } from '../accessorTree'\nimport { BindingError } from '../BindingError'\nimport type { EntityOperations } from '../core/operations'\nimport type { Environment } from '../dao'\nimport { EntityFieldMarkers, HasManyRelationMarker, HasOneRelationMarker, PlaceholderGenerator } from '../markers'\nimport { QueryLanguage } from '../queryLanguage'\nimport type {\n\tEntityId,\n\tEntityName,\n\tEntityRealmKey,\n\tFieldName,\n\tFieldValue,\n\tHasManyRelation,\n\tHasOneRelation,\n\tRelativeEntityList,\n\tRelativeSingleEntity,\n\tRelativeSingleField,\n\tSugaredRelativeEntityList,\n\tSugaredRelativeSingleEntity,\n\tSugaredRelativeSingleField,\n} from '../treeParameters'\nimport type { AsyncBatchUpdatesOptions } from './AsyncBatchUpdatesOptions'\nimport type { BatchUpdatesOptions } from './BatchUpdatesOptions'\nimport { EntityListAccessor } from './EntityListAccessor'\nimport type { Errorable } from './Errorable'\nimport { ErrorAccessor } from './ErrorAccessor'\nimport type { FieldAccessor } from './FieldAccessor'\nimport type { PersistErrorOptions } from './PersistErrorOptions'\nimport type { PersistSuccessOptions } from './PersistSuccessOptions'\nimport type { EntityRealmState } from '../core/state'\nimport { getEntityMarker } from '../core/state'\nimport { TreeNodeUtils } from '../utils/TreeNodeUtils'\nimport { PlaceholderParametersGenerator } from '../markers/PlaceholderParametersGenerator'\n\nclass EntityAccessor implements Errorable {\n\tpublic constructor(\n\t\tprivate readonly state: EntityRealmState,\n\t\tprivate readonly operations: EntityOperations,\n\t\tprivate readonly runtimeId: RuntimeId,\n\t\tpublic readonly key: EntityRealmKey, // ⚠️ This is *NOT* the id! ⚠️\n\t\tpublic readonly name: EntityName,\n\t\tprivate readonly fieldData: EntityAccessor.FieldData,\n\t\tprivate readonly dataFromServer: SingleEntityPersistedData | undefined,\n\t\tpublic readonly hasUnpersistedChanges: boolean,\n\t\tpublic readonly errors: ErrorAccessor | undefined,\n\t\tpublic readonly environment: Environment,\n\t\tpublic readonly getAccessor: EntityAccessor.GetEntityAccessor,\n\t) {\n\t}\n\n\tpublic get idOnServer(): EntityId | undefined {\n\t\treturn this.runtimeId.existsOnServer ? this.runtimeId.value : undefined\n\t}\n\n\t/**\n\t * Note that for entities that don't yet exist on server this will return a dummy id.\n\t */\n\tpublic get id(): EntityId {\n\t\treturn this.runtimeId.value\n\t}\n\n\tpublic get existsOnServer(): boolean {\n\t\treturn this.runtimeId.existsOnServer\n\t}\n\n\t//\n\n\tpublic addError(error: ErrorAccessor.Error | string): () => void {\n\t\treturn this.operations.addError(this.state, ErrorAccessor.normalizeError(error))\n\t}\n\n\tpublic addEventListener<Type extends keyof EntityAccessor.RuntimeEntityEventListenerMap>(\n\t\tevent: { type: Type; key?: string },\n\t\tlistener: EntityAccessor.EntityEventListenerMap[Type],\n\t): () => void {\n\t\treturn this.operations.addEventListener(this.state, event, listener)\n\t}\n\n\tpublic batchUpdates(performUpdates: EntityAccessor.BatchUpdatesHandler): void {\n\t\tthis.operations.batchUpdates(this.state, performUpdates)\n\t}\n\n\tpublic connectEntityAtField(field: FieldName, entityToConnect: EntityAccessor): void {\n\t\tthis.operations.connectEntityAtField(this.state, field, entityToConnect)\n\t}\n\n\tpublic disconnectEntityAtField(field: FieldName, initializeReplacement?: EntityAccessor.BatchUpdatesHandler): void {\n\t\tthis.operations.disconnectEntityAtField(this.state, field, initializeReplacement)\n\t}\n\n\tpublic deleteEntity(): void {\n\t\tthis.operations.deleteEntity(this.state)\n\t}\n\n\t//\n\n\tpublic updateValues(fieldValuePairs: EntityAccessor.FieldValuePairs): void {\n\t\tthis.batchUpdates(getAccessor => {\n\t\t\tconst entries = Array.isArray(fieldValuePairs) ? fieldValuePairs : Object.entries(fieldValuePairs)\n\n\t\t\tfor (const [field, value] of entries) {\n\t\t\t\tgetAccessor().getField(field).updateValue(value)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Please keep in mind that this method signature is literally impossible to implement safely. The generic parameter\n\t * is really just a way to succinctly write a type cast. Nothing more, really.\n\t */\n\tpublic getField<Value extends FieldValue = FieldValue>(\n\t\tfield: SugaredRelativeSingleField | string,\n\t): FieldAccessor<Value> {\n\t\treturn this.getRelativeSingleField<Value>(QueryLanguage.desugarRelativeSingleField(field, this.environment))\n\t}\n\n\tpublic getEntity(entity: SugaredRelativeSingleEntity | string): EntityAccessor {\n\t\treturn this.getRelativeSingleEntity(QueryLanguage.desugarRelativeSingleEntity(entity, this.environment))\n\t}\n\n\tpublic getEntityList(entityList: SugaredRelativeEntityList | string): EntityListAccessor {\n\t\treturn this.getRelativeEntityList(QueryLanguage.desugarRelativeEntityList(entityList, this.environment))\n\t}\n\n\t//\n\n\t/**\n\t * @see EntityAccessor.getField\n\t */\n\tpublic getRelativeSingleField<Value extends FieldValue = FieldValue>(field: RelativeSingleField): FieldAccessor<Value> {\n\t\tconst entity = this.getRelativeSingleEntity(field)\n\t\tconst fieldPlaceholder = PlaceholderGenerator.getFieldPlaceholder(field.field)\n\t\tconst accessor = entity.fieldData.get(fieldPlaceholder)\n\t\tif (accessor) {\n\t\t\treturn accessor.getAccessor() as FieldAccessor<Value>\n\t\t}\n\n\t\tTreeNodeUtils.resolveColumn(entity.environment, field.field)\n\n\t\tthrow new BindingError(''\n\t\t\t+ 'EntityAccessor: cannot access field '\n\t\t\t+ `'${field.field}' on ${TreeNodeUtils.describeLocation(entity.environment)}.\\n`\n\t\t\t+ 'The cause of the error is that this relation has not been registered during the static rendering process. As a result, it lacks a required marker and accessor.',\n\t\t)\n\t}\n\n\tpublic getRelativeSingleEntity(relativeSingleEntity: RelativeSingleEntity): EntityAccessor {\n\t\tlet relativeTo: EntityAccessor = this\n\n\t\tfor (const hasOneRelation of relativeSingleEntity.hasOneRelationPath) {\n\t\t\tconst fieldPlaceholder = PlaceholderGenerator.getHasOneRelationPlaceholder(hasOneRelation)\n\t\t\tconst accessor = relativeTo.fieldData.get(fieldPlaceholder)\n\t\t\tif (!accessor) {\n\t\t\t\treturn this.raiseInvalidHasOneRelationError(relativeTo, hasOneRelation)\n\t\t\t}\n\n\t\t\trelativeTo = accessor.getAccessor() as EntityAccessor\n\t\t}\n\t\treturn relativeTo\n\t}\n\n\tpublic getRelativeEntityList(entityList: RelativeEntityList): EntityListAccessor {\n\t\tconst entity = this.getRelativeSingleEntity(entityList)\n\t\tconst fieldPlaceholder = PlaceholderGenerator.getHasManyRelationPlaceholder(entityList.hasManyRelation)\n\t\tconst accessor = entity.fieldData.get(fieldPlaceholder)\n\t\tif (!accessor) {\n\t\t\treturn this.raiseInvalidHasManyRelationError(entity, entityList.hasManyRelation)\n\t\t}\n\n\t\treturn accessor.getAccessor() as EntityListAccessor\n\t}\n\n\tprivate raiseInvalidHasOneRelationError(relativeTo: EntityAccessor, hasOneRelation: HasOneRelation): never {\n\t\tTreeNodeUtils.resolveHasOneRelation(relativeTo.environment, hasOneRelation.field, !!hasOneRelation.reducedBy)\n\n\t\tconst entityMarker = relativeTo.getMarker()\n\t\tconst possibleMarkers = this.getMarkersOfType(entityMarker.fields.markers, HasOneRelationMarker, hasOneRelation.field)\n\t\tconst markerParams = possibleMarkers.map(it => PlaceholderParametersGenerator.createHasOneRelationParameters(it.parameters))\n\n\t\tconst relationParams = PlaceholderParametersGenerator.createHasOneRelationParameters(hasOneRelation)\n\n\t\tthis.raiseUndefinedRelationError(hasOneRelation.field, relativeTo.environment, relationParams, markerParams)\n\t}\n\n\tprivate raiseInvalidHasManyRelationError(entity: EntityAccessor, hasManyRelation: HasManyRelation): never {\n\t\tTreeNodeUtils.resolveHasManyRelation(entity.environment, hasManyRelation.field)\n\n\t\tconst entityMarker = entity.getMarker()\n\t\tconst possibleMarkers = this.getMarkersOfType(entityMarker.fields.markers, HasManyRelationMarker, hasManyRelation.field)\n\t\tconst markerParams = possibleMarkers.map(it => PlaceholderParametersGenerator.createHasManyRelationParameters(it.parameters))\n\n\t\tconst relationParams = PlaceholderParametersGenerator.createHasManyRelationParameters(hasManyRelation)\n\n\t\tthis.raiseUndefinedRelationError(hasManyRelation.field, entity.environment, relationParams, markerParams)\n\t}\n\n\tprivate raiseUndefinedRelationError(field: string, environment: Environment, relationParams: any, otherMarkersParams: any[]): never {\n\t\tconst hint = this.createHintMessage(otherMarkersParams)\n\t\tthrow new BindingError(''\n\t\t\t+ `EntityAccessor: cannot access relation `\n\t\t\t+ `'${field}' on ${TreeNodeUtils.describeLocation(environment)}.\\n`\n\t\t\t+ 'The cause of the error is that this relation has not been registered during the static rendering process. As a result, it lacks a required marker and accessor.\\n\\n'\n\t\t\t+ 'Provided parameters:\\n'\n\t\t\t+ JSON.stringify(relationParams)\n\t\t\t+ hint,\n\t\t)\n\t}\n\n\tprivate createHintMessage(params: any[]): string {\n\t\tif (params.length === 0) {\n\t\t\treturn ''\n\t\t}\n\n\t\tconst serializedParams = params.map(it => JSON.stringify(it)).join('\\n')\n\t\tconst message = params.length === 1\n\t\t\t? 'However, there is existing marker for the same field, but it have different parameters:'\n\t\t\t: 'However, there are existing markers for the same field, but they have different parameters:'\n\n\t\treturn `\\n\\n${message}\\n${serializedParams}`\n\t}\n\n\tprivate getMarkersOfType<T extends { new(...args: any[]): HasManyRelationMarker | HasOneRelationMarker }>(\n\t\tmarkers: EntityFieldMarkers,\n\t\tmarkerConstructor: T,\n\t\tfieldName: string,\n\t): InstanceType<T>[] {\n\t\treturn Array.from(markers.values())\n\t\t\t.filter((it): it is InstanceType<T> => (it instanceof markerConstructor) && it.parameters.field === fieldName)\n\t}\n\n\tpublic getParent(): EntityAccessor | EntityListAccessor | undefined {\n\t\tconst blueprint = this.state.blueprint\n\t\tif (blueprint.type === 'subTree') {\n\t\t\treturn undefined\n\t\t}\n\t\treturn blueprint.parent.getAccessor()\n\t}\n\n\tpublic getMarker() {\n\t\treturn getEntityMarker(this.state)\n\t}\n}\n\nnamespace EntityAccessor {\n\texport interface FieldDatum {\n\t\tgetAccessor(): NestedAccessor\n\t}\n\texport type NestedAccessor = EntityAccessor | EntityListAccessor | FieldAccessor<any>\n\n\texport type FieldValuePairs =\n\t\t| {\n\t\t\t\t[field: string]: FieldValue\n\t\t }\n\t\t| Iterable<[SugaredRelativeSingleField | string, FieldValue]>\n\n\texport type FieldData = Map<FieldName, FieldDatum>\n\n\texport type GetEntityAccessor = () => EntityAccessor\n\texport type BatchUpdatesHandler = (getAccessor: GetEntityAccessor, options: BatchUpdatesOptions) => void\n\texport type UpdateListener = (accessor: EntityAccessor) => void\n\n\texport type BeforePersistHandler = (\n\t\tgetAccessor: GetEntityAccessor,\n\t\toptions: AsyncBatchUpdatesOptions,\n\t) => void | Promise<void | BeforePersistHandler>\n\n\texport type PersistErrorHandler = (\n\t\tgetAccessor: GetEntityAccessor,\n\t\toptions: PersistErrorOptions,\n\t) => void | Promise<void>\n\n\texport type PersistSuccessHandler = (\n\t\tgetAccessor: GetEntityAccessor,\n\t\toptions: PersistSuccessOptions,\n\t) => void | Promise<void | PersistSuccessHandler>\n\n\texport interface RuntimeEntityEventListenerMap {\n\t\tbeforePersist: BeforePersistHandler\n\t\tbeforeUpdate: BatchUpdatesHandler\n\t\tconnectionUpdate: UpdateListener\n\t\tpersistError: PersistErrorHandler\n\t\tpersistSuccess: PersistSuccessHandler\n\t\tupdate: UpdateListener\n\t}\n\texport interface EntityEventListenerMap extends RuntimeEntityEventListenerMap {\n\t\tinitialize: BatchUpdatesHandler\n\t}\n\texport type EntityEventType = keyof EntityEventListenerMap\n}\n\nexport { EntityAccessor }\n"],"names":[],"mappings":";;;;;;;;;AAkCA,MAAM,eAAoC;AAAA,EAClC,YACW,OACA,YACA,WACD,KACA,MACC,WACA,gBACD,uBACA,QACA,aACA,aACf;AAXgB,SAAA,QAAA;AACA,SAAA,aAAA;AACA,SAAA,YAAA;AACD,SAAA,MAAA;AACA,SAAA,OAAA;AACC,SAAA,YAAA;AACA,SAAA,iBAAA;AACD,SAAA,wBAAA;AACA,SAAA,SAAA;AACA,SAAA,cAAA;AACA,SAAA,cAAA;AAAA,EAEjB;AAAA,EAEA,IAAW,aAAmC;AAC7C,WAAO,KAAK,UAAU,iBAAiB,KAAK,UAAU,QAAQ;AAAA,EAC/D;AAAA;AAAA;AAAA;AAAA,EAKA,IAAW,KAAe;AACzB,WAAO,KAAK,UAAU;AAAA,EACvB;AAAA,EAEA,IAAW,iBAA0B;AACpC,WAAO,KAAK,UAAU;AAAA,EACvB;AAAA;AAAA,EAIO,SAAS,OAAiD;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AAK,KAAK;AAAA,EAClC;AACD;"}
@@ -197,18 +197,23 @@ ${error.message}
197
197
  );
198
198
  this.eventManager.registerUpdatedConnection(parent, placeholderName);
199
199
  } else if (realmToDelete.blueprint.type === "subTree") {
200
- throw new BindingError("Deleting top-level entities is not yet implemented.");
200
+ parent = void 0;
201
+ if (realmToDelete.type === "entityRealm") {
202
+ this.eventManager.registerJustUpdated(realmToDelete, 1);
203
+ }
201
204
  } else {
202
205
  return assertNever(realmToDelete.blueprint);
203
206
  }
204
- if (realmToDelete.type === "entityRealm") {
205
- changesDelta -= realmToDelete.unpersistedChangesCount;
206
- }
207
- this.eventManager.registerJustUpdated(parent, changesDelta);
208
- if (realmToDelete.type === "entityRealm") {
209
- parent.childrenWithPendingUpdates?.delete(realmToDelete);
207
+ if (parent) {
208
+ if (realmToDelete.type === "entityRealm") {
209
+ changesDelta -= realmToDelete.unpersistedChangesCount;
210
+ }
211
+ this.eventManager.registerJustUpdated(parent, changesDelta);
212
+ if (realmToDelete.type === "entityRealm") {
213
+ parent.childrenWithPendingUpdates?.delete(realmToDelete);
214
+ }
215
+ this.treeStore.disposeOfRealm(realmToDelete);
210
216
  }
211
- this.treeStore.disposeOfRealm(realmToDelete);
212
217
  }
213
218
  });
214
219
  }
@@ -1 +1 @@
1
- {"version":3,"file":"EntityOperations.js","sources":["../../../../src/core/operations/EntityOperations.ts"],"sourcesContent":["import type { BatchUpdatesOptions, EntityAccessor, ErrorAccessor } from '../../accessors'\nimport { ServerId, UnpersistedEntityDummyId } from '../../accessorTree'\nimport { BindingError } from '../../BindingError'\nimport { EntityFieldMarkersContainer, HasOneRelationMarker } from '../../markers'\nimport type { FieldName } from '../../treeParameters'\nimport { assertNever } from '../../utils'\nimport type { AccessorErrorManager } from '../AccessorErrorManager'\nimport type { EventManager } from '../EventManager'\nimport { ErrorLocator, LocalizedBindingError } from '../exceptions'\nimport { MarkerComparator } from '../MarkerComparator'\nimport { EntityListState, EntityRealmState, EntityRealmStateStub, getEntityMarker, StateIterator } from '../state'\nimport type { StateInitializer } from '../StateInitializer'\nimport type { TreeStore } from '../TreeStore'\nimport { OperationsHelpers } from './OperationsHelpers'\nimport { EventListenersStore } from '../../treeParameters'\n\nexport class EntityOperations {\n\tpublic constructor(\n\t\tprivate readonly accessorErrorManager: AccessorErrorManager,\n\t\tprivate readonly batchUpdatesOptions: BatchUpdatesOptions,\n\t\tprivate readonly eventManager: EventManager,\n\t\tprivate readonly stateInitializer: StateInitializer,\n\t\tprivate readonly treeStore: TreeStore,\n\t) {}\n\n\tpublic addError(entityRealm: EntityRealmState, error: ErrorAccessor.Error): () => void {\n\t\treturn this.accessorErrorManager.addError(entityRealm, error)\n\t}\n\n\tpublic addEventListener<Type extends keyof EntityAccessor.RuntimeEntityEventListenerMap>(\n\t\tstate: EntityRealmState,\n\t\tevent: { type: Type; key?: string },\n\t\tlistener: EntityAccessor.EntityEventListenerMap[Type],\n\t) {\n\t\tif (state.eventListeners === undefined) {\n\t\t\tstate.eventListeners = new EventListenersStore()\n\t\t}\n\t\treturn state.eventListeners.add(event, listener)\n\t}\n\n\tpublic batchUpdates(state: EntityRealmState, performUpdates: EntityAccessor.BatchUpdatesHandler) {\n\t\tthis.eventManager.syncOperation(() => {\n\t\t\tperformUpdates(state.getAccessor, this.batchUpdatesOptions)\n\t\t})\n\t}\n\n\tpublic connectEntityAtField(outerState: EntityRealmState, fieldName: FieldName, entityToConnect: EntityAccessor) {\n\t\tthis.eventManager.syncOperation(() => {\n\t\t\tconst stateToConnect = OperationsHelpers.resolveAndPrepareEntityToConnect(this.treeStore, entityToConnect)\n\t\t\tconst fieldsToConnect = getEntityMarker(stateToConnect).fields\n\t\t\tconst persistedData = this.treeStore.persistedEntityData.get(outerState.entity.id.uniqueValue)\n\n\t\t\tconst entityName = outerState.entity.entityName\n\t\t\tconst fieldSchema = this.treeStore.schema.getEntityFieldOrUndefined(entityName, fieldName)\n\n\t\t\tif (fieldSchema === undefined) {\n\t\t\t\tthrow new BindingError(\n\t\t\t\t\t`EntityAccessor.connectEntityAtField: Unknown field ${entityName}.${fieldName}.\\n\\n` +\n\t\t\t\t\t\t`Entity located at: ${ErrorLocator.locateInternalState(outerState)}.`,\n\t\t\t\t)\n\t\t\t} else if (fieldSchema.__typename === '_Column') {\n\t\t\t\tthrow new BindingError(\n\t\t\t\t\t`EntityAccessor.connectEntityAtField: Cannot connect at field ${entityName}.${fieldName} because ` +\n\t\t\t\t\t\t`it's not a has-one relation.\\n\\n` +\n\t\t\t\t\t\t`Entity located at: ${ErrorLocator.locateInternalState(outerState)}.`,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tfor (const state of StateIterator.eachSiblingRealm(outerState)) {\n\t\t\t\tconst targetHasOneMarkers = this.resolveHasOneRelationMarkers(\n\t\t\t\t\tgetEntityMarker(state).fields,\n\t\t\t\t\tfieldName,\n\t\t\t\t\t`Cannot connect at field '${fieldName}' as it doesn't refer to a has one relation.`,\n\t\t\t\t)\n\t\t\t\tfor (const targetHasOneMarker of targetHasOneMarkers) {\n\t\t\t\t\tconst previouslyConnectedState = state.children.get(targetHasOneMarker.placeholderName)\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tpreviouslyConnectedState === undefined ||\n\t\t\t\t\t\tpreviouslyConnectedState.type === 'field' ||\n\t\t\t\t\t\tpreviouslyConnectedState.type === 'entityList'\n\t\t\t\t\t) {\n\t\t\t\t\t\tOperationsHelpers.rejectInvalidAccessorTree()\n\t\t\t\t\t}\n\n\t\t\t\t\tif (previouslyConnectedState.entity.entityName !== stateToConnect.entity.entityName) {\n\t\t\t\t\t\tthrow new BindingError(\n\t\t\t\t\t\t\t`EntityAccessor.connectEntityAtField: Attempting to connect at field ${entityName}.${fieldName} ` +\n\t\t\t\t\t\t\t\t`an entity of type '${stateToConnect.entity.entityName}' but ` +\n\t\t\t\t\t\t\t\t`'${previouslyConnectedState.entity.entityName}' is expected.\\n\\n` +\n\t\t\t\t\t\t\t\t`Entity located at: ${ErrorLocator.locateInternalState(outerState)}.`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tMarkerComparator.assertEntityMarkersSubsetOf(targetHasOneMarker.fields, fieldsToConnect)\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (error instanceof LocalizedBindingError) {\n\t\t\t\t\t\t\tthrow new BindingError(\n\t\t\t\t\t\t\t\t`EntityAccessor: cannot connect entity with key '${entityToConnect.key}' because its fields are` +\n\t\t\t\t\t\t\t\t\t`incompatible with entities found at field '${fieldName}'. Make sure both trees are equivalent.\\n\\n` +\n\t\t\t\t\t\t\t\t\t`${error.message}\\n\\n` +\n\t\t\t\t\t\t\t\t\t(error.markerPath.length > 1\n\t\t\t\t\t\t\t\t\t\t? `Incompatibility found at: ${ErrorLocator.locateMarkerPath(error.markerPath)}.\\n\\n`\n\t\t\t\t\t\t\t\t\t\t: '') +\n\t\t\t\t\t\t\t\t\t`Entity located at: ${ErrorLocator.locateInternalState(state)}.`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tpreviouslyConnectedState === stateToConnect ||\n\t\t\t\t\t\tpreviouslyConnectedState.entity.id.value === stateToConnect.entity.id.value\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontinue // Do nothing.\n\t\t\t\t\t}\n\n\t\t\t\t\t// TODO remove from planned deletions if appropriate\n\n\t\t\t\t\tthis.treeStore.disposeOfRealm(previouslyConnectedState)\n\n\t\t\t\t\tlet changesDelta = 0\n\n\t\t\t\t\tif (previouslyConnectedState.type === 'entityRealm') {\n\t\t\t\t\t\tchangesDelta -= previouslyConnectedState.unpersistedChangesCount\n\t\t\t\t\t}\n\n\t\t\t\t\tconst persistedId = persistedData?.get(targetHasOneMarker.placeholderName)\n\t\t\t\t\tif (persistedId instanceof ServerId && persistedId.value === stateToConnect.entity.id.value) {\n\t\t\t\t\t\tchangesDelta-- // It was removed from the list but now we're adding it back.\n\t\t\t\t\t} else if (persistedId instanceof ServerId && persistedId.value === previouslyConnectedState.entity.id.value) {\n\t\t\t\t\t\tchangesDelta++ // We're changing it from the persisted id.\n\t\t\t\t\t} else if (!previouslyConnectedState.entity.id.existsOnServer) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tpersistedId === null || // We're updating.\n\t\t\t\t\t\t\t(persistedId === undefined && // We're creating.\n\t\t\t\t\t\t\t\t(!fieldsToConnect.hasAtLeastOneBearingField || !targetHasOneMarker.parameters.isNonbearing))\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tchangesDelta++\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (stateToConnect.type === 'entityRealm') {\n\t\t\t\t\t\t\tchangesDelta += stateToConnect.unpersistedChangesCount\n\t\t\t\t\t}\n\n\t\t\t\t\t// TODO do something about the existing state…\n\n\t\t\t\t\tthis.stateInitializer.initializeEntityRealm(\n\t\t\t\t\t\tstateToConnect.entity.id,\n\t\t\t\t\t\tstateToConnect.entity.entityName,\n\t\t\t\t\t\tpreviouslyConnectedState.blueprint,\n\t\t\t\t\t\tstateToConnect,\n\t\t\t\t\t)\n\n\t\t\t\t\tthis.eventManager.registerUpdatedConnection(state, targetHasOneMarker.placeholderName)\n\t\t\t\t\tthis.eventManager.registerJustUpdated(state, changesDelta)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tpublic disconnectEntityAtField(\n\t\touterState: EntityRealmState,\n\t\tfieldName: FieldName,\n\t\tinitializeReplacement: EntityAccessor.BatchUpdatesHandler | undefined,\n\t) {\n\t\tthis.eventManager.syncOperation(() => {\n\t\t\tconst persistedData = this.treeStore.persistedEntityData.get(outerState.entity.id.uniqueValue)\n\n\t\t\tfor (const state of StateIterator.eachSiblingRealm(outerState)) {\n\t\t\t\tconst targetHasOneMarkers = this.resolveHasOneRelationMarkers(\n\t\t\t\t\tgetEntityMarker(state).fields,\n\t\t\t\t\tfieldName,\n\t\t\t\t\t`Cannot disconnect at field '${fieldName}' as it doesn't refer to a has one relation.`,\n\t\t\t\t)\n\t\t\t\tfor (const targetHasOneMarker of targetHasOneMarkers) {\n\t\t\t\t\tconst stateToDisconnect = state.children.get(targetHasOneMarker.placeholderName)\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tstateToDisconnect === undefined ||\n\t\t\t\t\t\t(stateToDisconnect.type !== 'entityRealm' && stateToDisconnect.type !== 'entityRealmStub')\n\t\t\t\t\t) {\n\t\t\t\t\t\tOperationsHelpers.rejectInvalidAccessorTree()\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.treeStore.disposeOfRealm(stateToDisconnect)\n\n\t\t\t\t\tlet changesDelta = 0\n\n\t\t\t\t\tif (stateToDisconnect.type === 'entityRealm') {\n\t\t\t\t\t\tchangesDelta -= stateToDisconnect.unpersistedChangesCount\n\t\t\t\t\t}\n\t\t\t\t\tconst persistedId = persistedData?.get(targetHasOneMarker.placeholderName)\n\n\t\t\t\t\tif (persistedId instanceof ServerId) {\n\t\t\t\t\t\tif (persistedId.value === stateToDisconnect.entity.id.value) {\n\t\t\t\t\t\t\tchangesDelta++ // Disconnecting the persisted entity.\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Do nothing. The entity that is being disconnected is already different from the one that is persisted,\n\t\t\t\t\t\t\t// and so we must have already accounted for this change.\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (persistedId === undefined || persistedId === null) {\n\t\t\t\t\t\tif (stateToDisconnect.entity.id.existsOnServer) {\n\t\t\t\t\t\t\t// We had connected a persisted entity, which increased the changes count,\n\t\t\t\t\t\t\t// but now are disconnecting it again.\n\t\t\t\t\t\t\tchangesDelta--\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Do nothing. Disconnecting unpersisted entities doesn't change the count.\n\t\t\t\t\t}\n\n\t\t\t\t\tconst newEntity = this.stateInitializer.initializeEntityRealm(\n\t\t\t\t\t\tnew UnpersistedEntityDummyId(),\n\t\t\t\t\t\tstateToDisconnect.entity.entityName,\n\t\t\t\t\t\tstateToDisconnect.blueprint,\n\t\t\t\t\t)\n\t\t\t\t\tthis.stateInitializer.runImmediateUserInitialization(newEntity, initializeReplacement)\n\n\t\t\t\t\tthis.eventManager.registerUpdatedConnection(state, targetHasOneMarker.placeholderName)\n\t\t\t\t\tthis.eventManager.registerJustUpdated(state, changesDelta)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tpublic deleteEntity(realm: EntityRealmState) {\n\t\tthis.eventManager.syncOperation(() => {\n\t\t\tconst outerState = realm.entity\n\t\t\touterState.isScheduledForDeletion = true\n\n\t\t\tconst entityId = outerState.id\n\n\t\t\tfor (const realmToDelete of outerState.realms.values()) {\n\t\t\t\tlet parent: EntityRealmState | EntityRealmStateStub | EntityListState\n\t\t\t\tlet changesDelta = 0\n\n\t\t\t\tif (realmToDelete.blueprint.type === 'listEntity') {\n\t\t\t\t\tparent = realmToDelete.blueprint.parent\n\t\t\t\t\tparent.children.delete(entityId.value)\n\n\t\t\t\t\tif (entityId.existsOnServer) {\n\t\t\t\t\t\tif (parent.plannedRemovals === undefined) {\n\t\t\t\t\t\t\tparent.plannedRemovals = new Map()\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchangesDelta++\n\t\t\t\t\t\tparent.plannedRemovals.set(entityId.value, 'delete')\n\t\t\t\t\t}\n\t\t\t\t} else if (realmToDelete.blueprint.type === 'hasOne') {\n\t\t\t\t\tparent = realmToDelete.blueprint.parent\n\t\t\t\t\tconst placeholderName = realmToDelete.blueprint.marker.placeholderName\n\n\t\t\t\t\tif (entityId.existsOnServer) {\n\t\t\t\t\t\tif (parent.plannedHasOneDeletions === undefined) {\n\t\t\t\t\t\t\tparent.plannedHasOneDeletions = new Map()\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchangesDelta++\n\t\t\t\t\t\tparent.plannedHasOneDeletions.set(placeholderName, realmToDelete)\n\t\t\t\t\t}\n\t\t\t\t\tthis.stateInitializer.initializeEntityRealm(\n\t\t\t\t\t\tnew UnpersistedEntityDummyId(),\n\t\t\t\t\t\touterState.entityName,\n\t\t\t\t\t\trealmToDelete.blueprint,\n\t\t\t\t\t)\n\n\t\t\t\t\tthis.eventManager.registerUpdatedConnection(parent, placeholderName)\n\t\t\t\t} else if (realmToDelete.blueprint.type === 'subTree') {\n\t\t\t\t\tthrow new BindingError('Deleting top-level entities is not yet implemented.')\n\t\t\t\t} else {\n\t\t\t\t\treturn assertNever(realmToDelete.blueprint)\n\t\t\t\t}\n\n\t\t\t\tif (realmToDelete.type === 'entityRealm') {\n\t\t\t\t\t// Undoing whatever this had caused\n\t\t\t\t\tchangesDelta -= realmToDelete.unpersistedChangesCount\n\t\t\t\t}\n\t\t\t\tthis.eventManager.registerJustUpdated(parent, changesDelta)\n\n\t\t\t\tif (realmToDelete.type === 'entityRealm') {\n\t\t\t\t\tparent.childrenWithPendingUpdates?.delete(realmToDelete)\n\t\t\t\t}\n\n\t\t\t\tthis.treeStore.disposeOfRealm(realmToDelete)\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate *resolveHasOneRelationMarkers(\n\t\tcontainer: EntityFieldMarkersContainer,\n\t\tfield: FieldName,\n\t\tmessage: string,\n\t): IterableIterator<HasOneRelationMarker> {\n\t\tconst placeholders = container.placeholders.get(field)\n\n\t\tif (placeholders === undefined) {\n\t\t\treturn\n\t\t}\n\t\tconst normalizedPlaceholders = placeholders instanceof Set ? placeholders : [placeholders]\n\n\t\tfor (const placeholderName of normalizedPlaceholders) {\n\t\t\tconst hasOneRelation = container.markers.get(placeholderName)\n\n\t\t\tif (!(hasOneRelation instanceof HasOneRelationMarker)) {\n\t\t\t\tthrow new BindingError(message)\n\t\t\t}\n\t\t\tyield hasOneRelation\n\t\t}\n\t}\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAgBO,MAAM,iBAAiB;AAAA,EACtB,YACW,sBACA,qBACA,cACA,kBACA,WAChB;AALgB,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,aAAa,qDAAqD;AAAA,QAAA,OACtE;AACC,iBAAA,YAAY,cAAc,SAAS;AAAA,QAC3C;AAEI,YAAA,cAAc,SAAS,eAAe;AAEzC,0BAAgB,cAAc;AAAA,QAC/B;AACK,aAAA,aAAa,oBAAoB,QAAQ,YAAY;AAEtD,YAAA,cAAc,SAAS,eAAe;AAClC,iBAAA,4BAA4B,OAAO,aAAa;AAAA,QACxD;AAEK,aAAA,UAAU,eAAe,aAAa;AAAA,MAC5C;AAAA,IAAA,CACA;AAAA,EACF;AAAA,EAEA,CAAS,6BACR,WACA,OACA,SACyC;AACzC,UAAM,eAAe,UAAU,aAAa,IAAI,KAAK;AAErD,QAAI,iBAAiB,QAAW;AAC/B;AAAA,IACD;AACA,UAAM,yBAAyB,wBAAwB,MAAM,eAAe,CAAC,YAAY;AAEzF,eAAW,mBAAmB,wBAAwB;AACrD,YAAM,iBAAiB,UAAU,QAAQ,IAAI,eAAe;AAExD,UAAA,EAAE,0BAA0B,uBAAuB;AAChD,cAAA,IAAI,aAAa,OAAO;AAAA,MAC/B;AACM,YAAA;AAAA,IACP;AAAA,EACD;AACD;"}
1
+ {"version":3,"file":"EntityOperations.js","sources":["../../../../src/core/operations/EntityOperations.ts"],"sourcesContent":["import type { BatchUpdatesOptions, EntityAccessor, ErrorAccessor } from '../../accessors'\nimport { ServerId, UnpersistedEntityDummyId } from '../../accessorTree'\nimport { BindingError } from '../../BindingError'\nimport { EntityFieldMarkersContainer, HasOneRelationMarker } from '../../markers'\nimport type { FieldName } from '../../treeParameters'\nimport { assertNever } from '../../utils'\nimport type { AccessorErrorManager } from '../AccessorErrorManager'\nimport type { EventManager } from '../EventManager'\nimport { ErrorLocator, LocalizedBindingError } from '../exceptions'\nimport { MarkerComparator } from '../MarkerComparator'\nimport { EntityListState, EntityRealmState, EntityRealmStateStub, getEntityMarker, StateIterator } from '../state'\nimport type { StateInitializer } from '../StateInitializer'\nimport type { TreeStore } from '../TreeStore'\nimport { OperationsHelpers } from './OperationsHelpers'\nimport { EventListenersStore } from '../../treeParameters'\n\nexport class EntityOperations {\n\tpublic constructor(\n\t\tprivate readonly accessorErrorManager: AccessorErrorManager,\n\t\tprivate readonly batchUpdatesOptions: BatchUpdatesOptions,\n\t\tprivate readonly eventManager: EventManager,\n\t\tprivate readonly stateInitializer: StateInitializer,\n\t\tprivate readonly treeStore: TreeStore,\n\t) {}\n\n\tpublic addError(entityRealm: EntityRealmState, error: ErrorAccessor.Error): () => void {\n\t\treturn this.accessorErrorManager.addError(entityRealm, error)\n\t}\n\n\tpublic addEventListener<Type extends keyof EntityAccessor.RuntimeEntityEventListenerMap>(\n\t\tstate: EntityRealmState,\n\t\tevent: { type: Type; key?: string },\n\t\tlistener: EntityAccessor.EntityEventListenerMap[Type],\n\t) {\n\t\tif (state.eventListeners === undefined) {\n\t\t\tstate.eventListeners = new EventListenersStore()\n\t\t}\n\t\treturn state.eventListeners.add(event, listener)\n\t}\n\n\tpublic batchUpdates(state: EntityRealmState, performUpdates: EntityAccessor.BatchUpdatesHandler) {\n\t\tthis.eventManager.syncOperation(() => {\n\t\t\tperformUpdates(state.getAccessor, this.batchUpdatesOptions)\n\t\t})\n\t}\n\n\tpublic connectEntityAtField(outerState: EntityRealmState, fieldName: FieldName, entityToConnect: EntityAccessor) {\n\t\tthis.eventManager.syncOperation(() => {\n\t\t\tconst stateToConnect = OperationsHelpers.resolveAndPrepareEntityToConnect(this.treeStore, entityToConnect)\n\t\t\tconst fieldsToConnect = getEntityMarker(stateToConnect).fields\n\t\t\tconst persistedData = this.treeStore.persistedEntityData.get(outerState.entity.id.uniqueValue)\n\n\t\t\tconst entityName = outerState.entity.entityName\n\t\t\tconst fieldSchema = this.treeStore.schema.getEntityFieldOrUndefined(entityName, fieldName)\n\n\t\t\tif (fieldSchema === undefined) {\n\t\t\t\tthrow new BindingError(\n\t\t\t\t\t`EntityAccessor.connectEntityAtField: Unknown field ${entityName}.${fieldName}.\\n\\n` +\n\t\t\t\t\t\t`Entity located at: ${ErrorLocator.locateInternalState(outerState)}.`,\n\t\t\t\t)\n\t\t\t} else if (fieldSchema.__typename === '_Column') {\n\t\t\t\tthrow new BindingError(\n\t\t\t\t\t`EntityAccessor.connectEntityAtField: Cannot connect at field ${entityName}.${fieldName} because ` +\n\t\t\t\t\t\t`it's not a has-one relation.\\n\\n` +\n\t\t\t\t\t\t`Entity located at: ${ErrorLocator.locateInternalState(outerState)}.`,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tfor (const state of StateIterator.eachSiblingRealm(outerState)) {\n\t\t\t\tconst targetHasOneMarkers = this.resolveHasOneRelationMarkers(\n\t\t\t\t\tgetEntityMarker(state).fields,\n\t\t\t\t\tfieldName,\n\t\t\t\t\t`Cannot connect at field '${fieldName}' as it doesn't refer to a has one relation.`,\n\t\t\t\t)\n\t\t\t\tfor (const targetHasOneMarker of targetHasOneMarkers) {\n\t\t\t\t\tconst previouslyConnectedState = state.children.get(targetHasOneMarker.placeholderName)\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tpreviouslyConnectedState === undefined ||\n\t\t\t\t\t\tpreviouslyConnectedState.type === 'field' ||\n\t\t\t\t\t\tpreviouslyConnectedState.type === 'entityList'\n\t\t\t\t\t) {\n\t\t\t\t\t\tOperationsHelpers.rejectInvalidAccessorTree()\n\t\t\t\t\t}\n\n\t\t\t\t\tif (previouslyConnectedState.entity.entityName !== stateToConnect.entity.entityName) {\n\t\t\t\t\t\tthrow new BindingError(\n\t\t\t\t\t\t\t`EntityAccessor.connectEntityAtField: Attempting to connect at field ${entityName}.${fieldName} ` +\n\t\t\t\t\t\t\t\t`an entity of type '${stateToConnect.entity.entityName}' but ` +\n\t\t\t\t\t\t\t\t`'${previouslyConnectedState.entity.entityName}' is expected.\\n\\n` +\n\t\t\t\t\t\t\t\t`Entity located at: ${ErrorLocator.locateInternalState(outerState)}.`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tMarkerComparator.assertEntityMarkersSubsetOf(targetHasOneMarker.fields, fieldsToConnect)\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (error instanceof LocalizedBindingError) {\n\t\t\t\t\t\t\tthrow new BindingError(\n\t\t\t\t\t\t\t\t`EntityAccessor: cannot connect entity with key '${entityToConnect.key}' because its fields are` +\n\t\t\t\t\t\t\t\t\t`incompatible with entities found at field '${fieldName}'. Make sure both trees are equivalent.\\n\\n` +\n\t\t\t\t\t\t\t\t\t`${error.message}\\n\\n` +\n\t\t\t\t\t\t\t\t\t(error.markerPath.length > 1\n\t\t\t\t\t\t\t\t\t\t? `Incompatibility found at: ${ErrorLocator.locateMarkerPath(error.markerPath)}.\\n\\n`\n\t\t\t\t\t\t\t\t\t\t: '') +\n\t\t\t\t\t\t\t\t\t`Entity located at: ${ErrorLocator.locateInternalState(state)}.`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tpreviouslyConnectedState === stateToConnect ||\n\t\t\t\t\t\tpreviouslyConnectedState.entity.id.value === stateToConnect.entity.id.value\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontinue // Do nothing.\n\t\t\t\t\t}\n\n\t\t\t\t\t// TODO remove from planned deletions if appropriate\n\n\t\t\t\t\tthis.treeStore.disposeOfRealm(previouslyConnectedState)\n\n\t\t\t\t\tlet changesDelta = 0\n\n\t\t\t\t\tif (previouslyConnectedState.type === 'entityRealm') {\n\t\t\t\t\t\tchangesDelta -= previouslyConnectedState.unpersistedChangesCount\n\t\t\t\t\t}\n\n\t\t\t\t\tconst persistedId = persistedData?.get(targetHasOneMarker.placeholderName)\n\t\t\t\t\tif (persistedId instanceof ServerId && persistedId.value === stateToConnect.entity.id.value) {\n\t\t\t\t\t\tchangesDelta-- // It was removed from the list but now we're adding it back.\n\t\t\t\t\t} else if (persistedId instanceof ServerId && persistedId.value === previouslyConnectedState.entity.id.value) {\n\t\t\t\t\t\tchangesDelta++ // We're changing it from the persisted id.\n\t\t\t\t\t} else if (!previouslyConnectedState.entity.id.existsOnServer) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tpersistedId === null || // We're updating.\n\t\t\t\t\t\t\t(persistedId === undefined && // We're creating.\n\t\t\t\t\t\t\t\t(!fieldsToConnect.hasAtLeastOneBearingField || !targetHasOneMarker.parameters.isNonbearing))\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tchangesDelta++\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (stateToConnect.type === 'entityRealm') {\n\t\t\t\t\t\t\tchangesDelta += stateToConnect.unpersistedChangesCount\n\t\t\t\t\t}\n\n\t\t\t\t\t// TODO do something about the existing state…\n\n\t\t\t\t\tthis.stateInitializer.initializeEntityRealm(\n\t\t\t\t\t\tstateToConnect.entity.id,\n\t\t\t\t\t\tstateToConnect.entity.entityName,\n\t\t\t\t\t\tpreviouslyConnectedState.blueprint,\n\t\t\t\t\t\tstateToConnect,\n\t\t\t\t\t)\n\n\t\t\t\t\tthis.eventManager.registerUpdatedConnection(state, targetHasOneMarker.placeholderName)\n\t\t\t\t\tthis.eventManager.registerJustUpdated(state, changesDelta)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tpublic disconnectEntityAtField(\n\t\touterState: EntityRealmState,\n\t\tfieldName: FieldName,\n\t\tinitializeReplacement: EntityAccessor.BatchUpdatesHandler | undefined,\n\t) {\n\t\tthis.eventManager.syncOperation(() => {\n\t\t\tconst persistedData = this.treeStore.persistedEntityData.get(outerState.entity.id.uniqueValue)\n\n\t\t\tfor (const state of StateIterator.eachSiblingRealm(outerState)) {\n\t\t\t\tconst targetHasOneMarkers = this.resolveHasOneRelationMarkers(\n\t\t\t\t\tgetEntityMarker(state).fields,\n\t\t\t\t\tfieldName,\n\t\t\t\t\t`Cannot disconnect at field '${fieldName}' as it doesn't refer to a has one relation.`,\n\t\t\t\t)\n\t\t\t\tfor (const targetHasOneMarker of targetHasOneMarkers) {\n\t\t\t\t\tconst stateToDisconnect = state.children.get(targetHasOneMarker.placeholderName)\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tstateToDisconnect === undefined ||\n\t\t\t\t\t\t(stateToDisconnect.type !== 'entityRealm' && stateToDisconnect.type !== 'entityRealmStub')\n\t\t\t\t\t) {\n\t\t\t\t\t\tOperationsHelpers.rejectInvalidAccessorTree()\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.treeStore.disposeOfRealm(stateToDisconnect)\n\n\t\t\t\t\tlet changesDelta = 0\n\n\t\t\t\t\tif (stateToDisconnect.type === 'entityRealm') {\n\t\t\t\t\t\tchangesDelta -= stateToDisconnect.unpersistedChangesCount\n\t\t\t\t\t}\n\t\t\t\t\tconst persistedId = persistedData?.get(targetHasOneMarker.placeholderName)\n\n\t\t\t\t\tif (persistedId instanceof ServerId) {\n\t\t\t\t\t\tif (persistedId.value === stateToDisconnect.entity.id.value) {\n\t\t\t\t\t\t\tchangesDelta++ // Disconnecting the persisted entity.\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Do nothing. The entity that is being disconnected is already different from the one that is persisted,\n\t\t\t\t\t\t\t// and so we must have already accounted for this change.\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (persistedId === undefined || persistedId === null) {\n\t\t\t\t\t\tif (stateToDisconnect.entity.id.existsOnServer) {\n\t\t\t\t\t\t\t// We had connected a persisted entity, which increased the changes count,\n\t\t\t\t\t\t\t// but now are disconnecting it again.\n\t\t\t\t\t\t\tchangesDelta--\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Do nothing. Disconnecting unpersisted entities doesn't change the count.\n\t\t\t\t\t}\n\n\t\t\t\t\tconst newEntity = this.stateInitializer.initializeEntityRealm(\n\t\t\t\t\t\tnew UnpersistedEntityDummyId(),\n\t\t\t\t\t\tstateToDisconnect.entity.entityName,\n\t\t\t\t\t\tstateToDisconnect.blueprint,\n\t\t\t\t\t)\n\t\t\t\t\tthis.stateInitializer.runImmediateUserInitialization(newEntity, initializeReplacement)\n\n\t\t\t\t\tthis.eventManager.registerUpdatedConnection(state, targetHasOneMarker.placeholderName)\n\t\t\t\t\tthis.eventManager.registerJustUpdated(state, changesDelta)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tpublic deleteEntity(realm: EntityRealmState) {\n\t\tthis.eventManager.syncOperation(() => {\n\t\t\tconst outerState = realm.entity\n\t\t\touterState.isScheduledForDeletion = true\n\n\t\t\tconst entityId = outerState.id\n\n\t\t\tfor (const realmToDelete of outerState.realms.values()) {\n\t\t\t\tlet parent: EntityRealmState | EntityRealmStateStub | EntityListState | undefined\n\t\t\t\tlet changesDelta = 0\n\n\t\t\t\tif (realmToDelete.blueprint.type === 'listEntity') {\n\t\t\t\t\tparent = realmToDelete.blueprint.parent\n\t\t\t\t\tparent.children.delete(entityId.value)\n\n\t\t\t\t\tif (entityId.existsOnServer) {\n\t\t\t\t\t\tif (parent.plannedRemovals === undefined) {\n\t\t\t\t\t\t\tparent.plannedRemovals = new Map()\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchangesDelta++\n\t\t\t\t\t\tparent.plannedRemovals.set(entityId.value, 'delete')\n\t\t\t\t\t}\n\t\t\t\t} else if (realmToDelete.blueprint.type === 'hasOne') {\n\t\t\t\t\tparent = realmToDelete.blueprint.parent\n\t\t\t\t\tconst placeholderName = realmToDelete.blueprint.marker.placeholderName\n\n\t\t\t\t\tif (entityId.existsOnServer) {\n\t\t\t\t\t\tif (parent.plannedHasOneDeletions === undefined) {\n\t\t\t\t\t\t\tparent.plannedHasOneDeletions = new Map()\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchangesDelta++\n\t\t\t\t\t\tparent.plannedHasOneDeletions.set(placeholderName, realmToDelete)\n\t\t\t\t\t}\n\t\t\t\t\tthis.stateInitializer.initializeEntityRealm(\n\t\t\t\t\t\tnew UnpersistedEntityDummyId(),\n\t\t\t\t\t\touterState.entityName,\n\t\t\t\t\t\trealmToDelete.blueprint,\n\t\t\t\t\t)\n\n\t\t\t\t\tthis.eventManager.registerUpdatedConnection(parent, placeholderName)\n\t\t\t\t} else if (realmToDelete.blueprint.type === 'subTree') {\n\t\t\t\t\tparent = undefined\n\t\t\t\t\tif (realmToDelete.type === 'entityRealm') {\n\t\t\t\t\t\tthis.eventManager.registerJustUpdated(realmToDelete, 1)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn assertNever(realmToDelete.blueprint)\n\t\t\t\t}\n\n\t\t\t\tif (parent) {\n\t\t\t\t\tif (realmToDelete.type === 'entityRealm') {\n\t\t\t\t\t\t// Undoing whatever this had caused\n\t\t\t\t\t\tchangesDelta -= realmToDelete.unpersistedChangesCount\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.eventManager.registerJustUpdated(parent, changesDelta)\n\n\t\t\t\t\tif (realmToDelete.type === 'entityRealm') {\n\t\t\t\t\t\tparent.childrenWithPendingUpdates?.delete(realmToDelete)\n\t\t\t\t\t}\n\t\t\t\t\tthis.treeStore.disposeOfRealm(realmToDelete)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate *resolveHasOneRelationMarkers(\n\t\tcontainer: EntityFieldMarkersContainer,\n\t\tfield: FieldName,\n\t\tmessage: string,\n\t): IterableIterator<HasOneRelationMarker> {\n\t\tconst placeholders = container.placeholders.get(field)\n\n\t\tif (placeholders === undefined) {\n\t\t\treturn\n\t\t}\n\t\tconst normalizedPlaceholders = placeholders instanceof Set ? placeholders : [placeholders]\n\n\t\tfor (const placeholderName of normalizedPlaceholders) {\n\t\t\tconst hasOneRelation = container.markers.get(placeholderName)\n\n\t\t\tif (!(hasOneRelation instanceof HasOneRelationMarker)) {\n\t\t\t\tthrow new BindingError(message)\n\t\t\t}\n\t\t\tyield hasOneRelation\n\t\t}\n\t}\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAgBO,MAAM,iBAAiB;AAAA,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AA,cAAc,UAAU,SAAS,WAAW;AAC7C,mBAAA;AACL,cAAA,cAAc,SAAS,eAAe;AACpC,iBAAA,aAAa,oBAAoB,eAAe,CAAC;AAAA,UACvD;AAAA,QAAA,OACM;AACC,iBAAA,YAAY,cAAc,SAAS;AAAA,QAC3C;AAEA,YAAI,QAAQ;AACP,cAAA,cAAc,SAAS,eAAe;AAEzC,4BAAgB,cAAc;AAAA,UAC/B;AAEK,eAAA,aAAa,oBAAoB,QAAQ,YAAY;AAEtD,cAAA,cAAc,SAAS,eAAe;AAClC,mBAAA,4BAA4B,OAAO,aAAa;AAAA,UACxD;AACK,eAAA,UAAU,eAAe,aAAa;AAAA,QAC5C;AAAA,MACD;AAAA,IAAA,CACA;AAAA,EACF;AAAA,EAEA,CAAS,6BACR,WACA,OACA,SACyC;AACzC,UAAM,eAAe,UAAU,aAAa,IAAI,KAAK;AAErD,QAAI,iBAAiB,QAAW;AAC/B;AAAA,IACD;AACA,UAAM,yBAAyB,wBAAwB,MAAM,eAAe,CAAC,YAAY;AAEzF,eAAW,mBAAmB,wBAAwB;AACrD,YAAM,iBAAiB,UAAU,QAAQ,IAAI,eAAe;AAExD,UAAA,EAAE,0BAA0B,uBAAuB;AAChD,cAAA,IAAI,aAAa,OAAO;AAAA,MAC/B;AACM,YAAA;AAAA,IACP;AAAA,EACD;AACD;"}
@@ -1,6 +1,5 @@
1
- import { BindingError } from "../BindingError.js";
2
1
  import { whereToFilter } from "@contember/client";
3
- import levenshtein from "js-levenshtein";
2
+ import { TreeNodeUtils } from "../utils/TreeNodeUtils.js";
4
3
  import { QueryLanguage } from "../queryLanguage/QueryLanguage.js";
5
4
  class TreeNodeEnvironmentFactory {
6
5
  static createEnvironmentForEntityListSubtree(environment, sugaredEntityList) {
@@ -16,7 +15,7 @@ class TreeNodeEnvironmentFactory {
16
15
  rootWhere = entityList.filter ?? {};
17
16
  expectedCardinality = "zero-to-many";
18
17
  }
19
- const entitySchema = this.resolveEntity(environment.getSchema(), entityList.entityName, "entity list");
18
+ const entitySchema = TreeNodeUtils.resolveEntity(environment.getSchema(), entityList.entityName, "entity list");
20
19
  return environment.withSubTree({
21
20
  type: "subtree-entity-list",
22
21
  entity: entitySchema,
@@ -37,7 +36,7 @@ class TreeNodeEnvironmentFactory {
37
36
  rootWhere = whereToFilter(entity.where);
38
37
  expectedCardinality = entity.setOnCreate ? "zero-or-one" : "one";
39
38
  }
40
- const entitySchema = this.resolveEntity(environment.getSchema(), entity.entityName, "entity");
39
+ const entitySchema = TreeNodeUtils.resolveEntity(environment.getSchema(), entity.entityName, "entity");
41
40
  return environment.withSubTree({
42
41
  type: "subtree-entity",
43
42
  entity: entitySchema,
@@ -49,7 +48,7 @@ class TreeNodeEnvironmentFactory {
49
48
  const relativeEntityList = QueryLanguage.desugarRelativeEntityList(sugaredRelativeEntityList, environment);
50
49
  const hasOneEnvironment = this.traverseHasOnePath(environment, relativeEntityList.hasOneRelationPath);
51
50
  const hasManyField = relativeEntityList.hasManyRelation.field;
52
- const field = this.assertHasManyRelation(hasOneEnvironment, hasManyField);
51
+ const field = TreeNodeUtils.resolveHasManyRelation(hasOneEnvironment, hasManyField);
53
52
  const targetEntity = environment.getSchema().getEntity(field.targetEntity);
54
53
  return hasOneEnvironment.withSubTreeChild({
55
54
  type: "entity-list",
@@ -64,7 +63,7 @@ class TreeNodeEnvironmentFactory {
64
63
  static createEnvironmentForField(environment, sugaredRelativeSingleField) {
65
64
  const relativeSingleField = QueryLanguage.desugarRelativeSingleField(sugaredRelativeSingleField, environment);
66
65
  const hasOneEnvironment = this.traverseHasOnePath(environment, relativeSingleField.hasOneRelationPath);
67
- const field = this.resolveColumn(hasOneEnvironment, relativeSingleField.field);
66
+ const field = TreeNodeUtils.resolveColumn(hasOneEnvironment, relativeSingleField.field);
68
67
  return hasOneEnvironment.withSubTreeChild({
69
68
  type: "column",
70
69
  entity: environment.getSubTreeNode().entity,
@@ -73,7 +72,7 @@ class TreeNodeEnvironmentFactory {
73
72
  }
74
73
  static traverseHasOnePath(environment, hasOneRelationPath) {
75
74
  for (const pathItem of hasOneRelationPath) {
76
- const field = this.resolveHasOneRelation(environment, pathItem.field, !!pathItem.reducedBy);
75
+ const field = TreeNodeUtils.resolveHasOneRelation(environment, pathItem.field, !!pathItem.reducedBy);
77
76
  const targetEntity = environment.getSchema().getEntity(field.targetEntity);
78
77
  environment = environment.withSubTreeChild({
79
78
  type: "entity",
@@ -83,75 +82,6 @@ class TreeNodeEnvironmentFactory {
83
82
  }
84
83
  return environment;
85
84
  }
86
- static resolveHasOneRelation(environment, field, isReduced) {
87
- if (isReduced) {
88
- return this.resolveRelation(environment, field, "reduced has-one relation", ["ManyHasMany", "OneHasMany"]);
89
- }
90
- return this.resolveRelation(environment, field, "a has-one relation", ["ManyHasOne", "OneHasOne"]);
91
- }
92
- static assertHasManyRelation(environment, field) {
93
- return this.resolveRelation(environment, field, "a has-many relation", ["ManyHasMany", "OneHasMany"]);
94
- }
95
- static resolveRelation(environment, field, relationDescription, expectedRelationType) {
96
- return this.resolveField(environment, field, (field2) => {
97
- return field2.__typename === "_Relation" && expectedRelationType.includes(field2.type);
98
- }, relationDescription);
99
- }
100
- static resolveEntity(schema, entityName, type) {
101
- const entity = schema.getEntityOrUndefined(entityName);
102
- if (!entity) {
103
- const alternative = this.recommendAlternative(entityName, schema.getEntityNames());
104
- const didYouMean = alternative ? `Did you mean '${alternative}'?` : "";
105
- throw new BindingError(`Invalid ${type} sub tree: Entity '${entityName}' doesn't exist. ${didYouMean}`);
106
- }
107
- return entity;
108
- }
109
- static resolveColumn(environment, fieldName) {
110
- return this.resolveField(environment, fieldName, (field) => field.__typename === "_Column", "an ordinary field");
111
- }
112
- static resolveField(environment, fieldName, matcher, expectedDescription) {
113
- const treeLocation = environment.getSubTreeNode();
114
- const entity = treeLocation.entity;
115
- const field = entity.fields.get(fieldName);
116
- if (!field) {
117
- const alternative = this.recommendAlternative(
118
- fieldName,
119
- Array.from(entity.fields).filter(([, field2]) => matcher(field2)).map(([fieldName2]) => fieldName2)
120
- );
121
- const didYouMean = alternative ? `Did you mean '${alternative}'?` : "";
122
- throw new BindingError(`Field '${fieldName}' doesn't exist on ${this.describeLocation(environment)}. ${didYouMean}`);
123
- }
124
- if (!matcher(field)) {
125
- const actual = field.__typename === "_Column" ? "an ordinary field" : `a ${field.type} relation`;
126
- throw new BindingError(
127
- `Invalid field: the name '${field.name}' on ${this.describeLocation(environment)} refers to ${actual} but is being used as a ${expectedDescription}.`
128
- );
129
- }
130
- return field;
131
- }
132
- static describeLocation(environment) {
133
- const path = [];
134
- const loc = environment.getSubTreeNode();
135
- for (let env = environment; ; env = env.getParent()) {
136
- const node = env.getSubTreeNode();
137
- if (node.type === "subtree-entity" || node.type === "subtree-entity-list") {
138
- return `entity '${loc.entity.name}' in path '${[node.entity.name, ...path.reverse()].join(".")}'`;
139
- }
140
- path.push(node.field.name);
141
- }
142
- }
143
- static recommendAlternative(original, possibleAlternatives) {
144
- let bestAlternative = void 0;
145
- let bestAlternativeDistance = Number.MAX_SAFE_INTEGER;
146
- for (const alternative of possibleAlternatives) {
147
- const distance = levenshtein(original, alternative);
148
- if (distance < bestAlternativeDistance) {
149
- bestAlternative = alternative;
150
- bestAlternativeDistance = distance;
151
- }
152
- }
153
- return bestAlternative;
154
- }
155
85
  }
156
86
  export {
157
87
  TreeNodeEnvironmentFactory