@shaclmate/compiler 2.0.13 → 2.0.15

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 (210) hide show
  1. package/Compiler.d.ts +15 -0
  2. package/Compiler.js +20 -0
  3. package/ShapesGraphToAstTransformer.d.ts +18 -23
  4. package/ShapesGraphToAstTransformer.js +21 -447
  5. package/_ShapesGraphToAstTransformer/NodeShapeAstType.d.ts +3 -0
  6. package/_ShapesGraphToAstTransformer/NodeShapeAstType.js +2 -0
  7. package/_ShapesGraphToAstTransformer/index.d.ts +10 -0
  8. package/_ShapesGraphToAstTransformer/index.js +10 -0
  9. package/_ShapesGraphToAstTransformer/pickLiteral.d.ts +4 -0
  10. package/_ShapesGraphToAstTransformer/pickLiteral.js +18 -0
  11. package/_ShapesGraphToAstTransformer/propertyShapeNodeKinds.d.ts +4 -0
  12. package/_ShapesGraphToAstTransformer/propertyShapeNodeKinds.js +26 -0
  13. package/_ShapesGraphToAstTransformer/shapeAstName.d.ts +5 -0
  14. package/_ShapesGraphToAstTransformer/shapeAstName.js +28 -0
  15. package/_ShapesGraphToAstTransformer/transformNodeShapeToAstType.d.ts +6 -0
  16. package/_ShapesGraphToAstTransformer/transformNodeShapeToAstType.js +178 -0
  17. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstCompositeType.d.ts +13 -0
  18. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstCompositeType.js +200 -0
  19. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstIdentifierType.d.ts +12 -0
  20. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstIdentifierType.js +29 -0
  21. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstLiteralType.d.ts +12 -0
  22. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstLiteralType.js +43 -0
  23. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstObjectTypeProperty.d.ts +6 -0
  24. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstObjectTypeProperty.js +31 -0
  25. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstTermType.d.ts +14 -0
  26. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstTermType.js +21 -0
  27. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstType.d.ts +16 -0
  28. package/_ShapesGraphToAstTransformer/transformPropertyShapeToAstType.js +58 -0
  29. package/ast/Ast.d.ts +5 -0
  30. package/ast/CompositeType.d.ts +13 -0
  31. package/ast/CompositeType.js +2 -0
  32. package/ast/IdentifierType.d.ts +3 -6
  33. package/ast/IntersectionType.d.ts +2 -2
  34. package/ast/ListType.d.ts +53 -0
  35. package/ast/ListType.js +2 -0
  36. package/ast/LiteralType.d.ts +4 -3
  37. package/ast/Name.d.ts +1 -0
  38. package/ast/ObjectCompositeType.d.ts +22 -0
  39. package/ast/ObjectCompositeType.js +2 -0
  40. package/ast/ObjectIntersectionType.d.ts +8 -0
  41. package/ast/ObjectIntersectionType.js +2 -0
  42. package/ast/ObjectType.d.ts +91 -19
  43. package/ast/ObjectType.js +26 -1
  44. package/ast/ObjectUnionType.d.ts +19 -0
  45. package/ast/ObjectUnionType.js +2 -0
  46. package/ast/PlaceholderType.d.ts +7 -0
  47. package/ast/PlaceholderType.js +2 -0
  48. package/ast/SetType.d.ts +1 -1
  49. package/ast/TermType.d.ts +11 -0
  50. package/ast/TermType.js +2 -0
  51. package/ast/Type.d.ts +11 -3
  52. package/ast/UnionType.d.ts +3 -3
  53. package/ast/index.d.ts +6 -3
  54. package/ast/index.js +6 -3
  55. package/enums/MintingStrategy.d.ts +5 -0
  56. package/enums/MintingStrategy.js +2 -0
  57. package/enums/PropertyVisibility.d.ts +2 -0
  58. package/enums/PropertyVisibility.js +2 -0
  59. package/enums/TsFeature.d.ts +5 -0
  60. package/enums/TsFeature.js +16 -0
  61. package/enums/TsObjectDeclarationType.d.ts +5 -0
  62. package/enums/TsObjectDeclarationType.js +2 -0
  63. package/enums/index.d.ts +5 -0
  64. package/enums/index.js +5 -0
  65. package/generators/Generator.d.ts +5 -0
  66. package/generators/Generator.js +2 -0
  67. package/generators/index.d.ts +2 -2
  68. package/generators/index.js +2 -2
  69. package/generators/json/AstJsonGenerator.d.ts +4 -5
  70. package/generators/json/AstJsonGenerator.js +31 -22
  71. package/generators/ts/BooleanType.d.ts +7 -3
  72. package/generators/ts/BooleanType.js +58 -4
  73. package/generators/ts/DateTimeType.d.ts +19 -0
  74. package/generators/ts/DateTimeType.js +66 -0
  75. package/generators/ts/DeclaredType.d.ts +17 -0
  76. package/generators/ts/DeclaredType.js +10 -0
  77. package/generators/ts/IdentifierType.d.ts +7 -17
  78. package/generators/ts/IdentifierType.js +69 -60
  79. package/generators/ts/Import.d.ts +17 -0
  80. package/generators/ts/Import.js +54 -0
  81. package/generators/ts/ListType.d.ts +19 -8
  82. package/generators/ts/ListType.js +206 -44
  83. package/generators/ts/LiteralType.d.ts +13 -11
  84. package/generators/ts/LiteralType.js +36 -51
  85. package/generators/ts/NumberType.d.ts +7 -3
  86. package/generators/ts/NumberType.js +55 -4
  87. package/generators/ts/ObjectType.d.ts +48 -25
  88. package/generators/ts/ObjectType.js +234 -50
  89. package/generators/ts/ObjectUnionType.d.ts +58 -0
  90. package/generators/ts/ObjectUnionType.js +450 -0
  91. package/generators/ts/OptionType.d.ts +14 -4
  92. package/generators/ts/OptionType.js +70 -20
  93. package/generators/ts/PrimitiveType.d.ts +15 -5
  94. package/generators/ts/PrimitiveType.js +27 -31
  95. package/generators/ts/SetType.d.ts +14 -4
  96. package/generators/ts/SetType.js +108 -30
  97. package/generators/ts/SnippetDeclarations.d.ts +11 -0
  98. package/generators/ts/SnippetDeclarations.js +215 -0
  99. package/generators/ts/StringType.d.ts +8 -3
  100. package/generators/ts/StringType.js +57 -3
  101. package/generators/ts/TermType.d.ts +54 -0
  102. package/generators/ts/TermType.js +242 -0
  103. package/generators/ts/TsGenerator.d.ts +4 -12
  104. package/generators/ts/TsGenerator.js +57 -99
  105. package/generators/ts/Type.d.ts +117 -46
  106. package/generators/ts/Type.js +93 -59
  107. package/generators/ts/TypeFactory.d.ts +4 -5
  108. package/generators/ts/TypeFactory.js +224 -91
  109. package/generators/ts/UnionType.d.ts +20 -6
  110. package/generators/ts/UnionType.js +230 -120
  111. package/generators/ts/_ObjectType/IdentifierProperty.d.ts +27 -8
  112. package/generators/ts/_ObjectType/IdentifierProperty.js +153 -32
  113. package/generators/ts/_ObjectType/Property.d.ts +139 -9
  114. package/generators/ts/_ObjectType/Property.js +26 -3
  115. package/generators/ts/_ObjectType/ShaclProperty.d.ts +24 -5
  116. package/generators/ts/_ObjectType/ShaclProperty.js +103 -26
  117. package/generators/ts/_ObjectType/TypeDiscriminatorProperty.d.ts +23 -7
  118. package/generators/ts/_ObjectType/TypeDiscriminatorProperty.js +83 -14
  119. package/generators/ts/_ObjectType/classDeclaration.d.ts +2 -1
  120. package/generators/ts/_ObjectType/classDeclaration.js +79 -111
  121. package/generators/ts/_ObjectType/createFunctionDeclaration.d.ts +5 -0
  122. package/generators/ts/_ObjectType/createFunctionDeclaration.js +60 -0
  123. package/generators/ts/_ObjectType/equalsFunctionDeclaration.d.ts +2 -1
  124. package/generators/ts/_ObjectType/equalsFunctionDeclaration.js +12 -20
  125. package/generators/ts/_ObjectType/equalsFunctionOrMethodDeclaration.d.ts +11 -0
  126. package/generators/ts/_ObjectType/equalsFunctionOrMethodDeclaration.js +70 -0
  127. package/generators/ts/_ObjectType/fromJsonFunctionDeclarations.d.ts +4 -0
  128. package/generators/ts/_ObjectType/fromJsonFunctionDeclarations.js +78 -0
  129. package/generators/ts/_ObjectType/fromRdfFunctionDeclarations.d.ts +4 -0
  130. package/generators/ts/_ObjectType/fromRdfFunctionDeclarations.js +91 -0
  131. package/generators/ts/_ObjectType/hashFunctionDeclaration.d.ts +3 -3
  132. package/generators/ts/_ObjectType/hashFunctionDeclaration.js +11 -55
  133. package/generators/ts/_ObjectType/hashFunctionOrMethodDeclaration.d.ts +11 -0
  134. package/generators/ts/_ObjectType/hashFunctionOrMethodDeclaration.js +64 -0
  135. package/generators/ts/_ObjectType/index.d.ts +8 -2
  136. package/generators/ts/_ObjectType/index.js +8 -2
  137. package/generators/ts/_ObjectType/interfaceDeclaration.d.ts +3 -2
  138. package/generators/ts/_ObjectType/interfaceDeclaration.js +11 -2
  139. package/generators/ts/_ObjectType/jsonSchemaFunctionDeclaration.d.ts +5 -0
  140. package/generators/ts/_ObjectType/jsonSchemaFunctionDeclaration.js +19 -0
  141. package/generators/ts/_ObjectType/jsonUiSchemaFunctionDeclaration.d.ts +5 -0
  142. package/generators/ts/_ObjectType/jsonUiSchemaFunctionDeclaration.js +31 -0
  143. package/generators/ts/_ObjectType/jsonZodSchemaFunctionDeclaration.d.ts +5 -0
  144. package/generators/ts/_ObjectType/jsonZodSchemaFunctionDeclaration.js +37 -0
  145. package/generators/ts/_ObjectType/rdfjsTermExpression.d.ts +6 -0
  146. package/generators/ts/{rdfjsTermExpression.js → _ObjectType/rdfjsTermExpression.js} +3 -1
  147. package/generators/ts/_ObjectType/sparqlConstructQueryFunctionDeclaration.d.ts +5 -0
  148. package/generators/ts/_ObjectType/sparqlConstructQueryFunctionDeclaration.js +21 -0
  149. package/generators/ts/_ObjectType/sparqlConstructQueryStringFunctionDeclaration.d.ts +5 -0
  150. package/generators/ts/_ObjectType/sparqlConstructQueryStringFunctionDeclaration.js +20 -0
  151. package/generators/ts/_ObjectType/sparqlFunctionDeclarations.d.ts +4 -0
  152. package/generators/ts/_ObjectType/sparqlFunctionDeclarations.js +78 -0
  153. package/generators/ts/_ObjectType/toJsonFunctionDeclaration.d.ts +5 -0
  154. package/generators/ts/_ObjectType/toJsonFunctionDeclaration.js +19 -0
  155. package/generators/ts/_ObjectType/toJsonFunctionOrMethodDeclaration.d.ts +10 -0
  156. package/generators/ts/_ObjectType/toJsonFunctionOrMethodDeclaration.js +59 -0
  157. package/generators/ts/_ObjectType/toJsonReturnType.d.ts +3 -0
  158. package/generators/ts/_ObjectType/toJsonReturnType.js +19 -0
  159. package/generators/ts/_ObjectType/toRdfFunctionDeclaration.d.ts +3 -2
  160. package/generators/ts/_ObjectType/toRdfFunctionDeclaration.js +11 -45
  161. package/generators/ts/_ObjectType/toRdfFunctionOrMethodDeclaration.d.ts +10 -0
  162. package/generators/ts/_ObjectType/toRdfFunctionOrMethodDeclaration.js +67 -0
  163. package/generators/ts/objectInitializer.d.ts +2 -0
  164. package/generators/ts/objectInitializer.js +14 -0
  165. package/generators/ts/tsComment.d.ts +5 -0
  166. package/generators/ts/tsComment.js +11 -0
  167. package/generators/ts/tsName.d.ts +1 -1
  168. package/generators/ts/tsName.js +1 -0
  169. package/index.d.ts +1 -1
  170. package/index.js +1 -1
  171. package/input/NodeShape.d.ts +46 -0
  172. package/input/NodeShape.js +165 -0
  173. package/input/Ontology.d.ts +13 -0
  174. package/input/Ontology.js +30 -0
  175. package/input/PropertyShape.d.ts +15 -0
  176. package/input/PropertyShape.js +34 -0
  177. package/input/Shape.d.ts +4 -0
  178. package/input/Shape.js +2 -0
  179. package/input/ShapesGraph.d.ts +9 -0
  180. package/input/ShapesGraph.js +50 -0
  181. package/input/ancestorClassIris.d.ts +4 -0
  182. package/input/ancestorClassIris.js +21 -0
  183. package/input/descendantClassIris.d.ts +4 -0
  184. package/input/descendantClassIris.js +21 -0
  185. package/input/generated.d.ts +275 -0
  186. package/input/generated.js +1436 -0
  187. package/input/index.d.ts +7 -0
  188. package/input/index.js +7 -0
  189. package/input/tsFeatures.d.ts +10 -0
  190. package/input/tsFeatures.js +46 -0
  191. package/package.json +15 -9
  192. package/ast/MintingStrategy.d.ts +0 -8
  193. package/ast/MintingStrategy.js +0 -9
  194. package/generators/ts/Configuration.d.ts +0 -29
  195. package/generators/ts/Configuration.js +0 -40
  196. package/generators/ts/IntersectionType.d.ts +0 -14
  197. package/generators/ts/IntersectionType.js +0 -26
  198. package/generators/ts/RdfjsTermType.d.ts +0 -25
  199. package/generators/ts/RdfjsTermType.js +0 -46
  200. package/generators/ts/_ObjectType/fromRdfFunctionDeclaration.d.ts +0 -4
  201. package/generators/ts/_ObjectType/fromRdfFunctionDeclaration.js +0 -72
  202. package/generators/ts/_ObjectType/sparqlGraphPatternsClassDeclaration.d.ts +0 -4
  203. package/generators/ts/_ObjectType/sparqlGraphPatternsClassDeclaration.js +0 -46
  204. package/generators/ts/rdfjsTermExpression.d.ts +0 -5
  205. package/vocabularies/dashDataset.d.ts +0 -3
  206. package/vocabularies/dashDataset.js +0 -2370
  207. package/vocabularies/index.d.ts +0 -2
  208. package/vocabularies/index.js +0 -2
  209. package/vocabularies/shaclmate.d.ts +0 -15
  210. package/vocabularies/shaclmate.js +0 -6
@@ -0,0 +1,242 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { xsd } from "@tpluscode/rdf-ns-builders";
8
+ import { Maybe } from "purify-ts";
9
+ import { invariant } from "ts-invariant";
10
+ import { Memoize } from "typescript-memoize";
11
+ import { Import } from "./Import.js";
12
+ import { SnippetDeclarations } from "./SnippetDeclarations.js";
13
+ import { Type } from "./Type.js";
14
+ import { objectInitializer } from "./objectInitializer.js";
15
+ /**
16
+ * Abstract base class for IdentifierType and LiteralType.
17
+ */
18
+ export class TermType extends Type {
19
+ constructor({ defaultValue, hasValues, in_, nodeKinds, ...superParameters }) {
20
+ super(superParameters);
21
+ this.equalsFunction = "booleanEquals";
22
+ this.mutable = false;
23
+ this.defaultValue = defaultValue;
24
+ this.hasValues = hasValues;
25
+ this.in_ = in_;
26
+ this.nodeKinds = new Set([...nodeKinds]);
27
+ invariant(this.nodeKinds.size > 0);
28
+ }
29
+ get conversions() {
30
+ const conversions = [];
31
+ if (this.nodeKinds.has("Literal")) {
32
+ conversions.push({
33
+ conversionExpression: (value) => `rdfLiteral.toRdf(${value})`,
34
+ sourceTypeCheckExpression: (value) => `typeof ${value} === "boolean"`,
35
+ sourceTypeName: "boolean",
36
+ }, {
37
+ conversionExpression: (value) => `rdfLiteral.toRdf(${value})`,
38
+ sourceTypeCheckExpression: (value) => `typeof ${value} === "object" && ${value} instanceof Date`,
39
+ sourceTypeName: "Date",
40
+ }, {
41
+ conversionExpression: (value) => `rdfLiteral.toRdf(${value})`,
42
+ sourceTypeCheckExpression: (value) => `typeof ${value} === "number"`,
43
+ sourceTypeName: "number",
44
+ }, {
45
+ conversionExpression: (value) => `${this.dataFactoryVariable}.literal(${value})`,
46
+ sourceTypeCheckExpression: (value) => `typeof ${value} === "string"`,
47
+ sourceTypeName: "string",
48
+ });
49
+ }
50
+ this.defaultValue.ifJust((defaultValue) => {
51
+ conversions.push({
52
+ conversionExpression: () => this.rdfjsTermExpression(defaultValue),
53
+ sourceTypeCheckExpression: (value) => `typeof ${value} === "undefined"`,
54
+ sourceTypeName: "undefined",
55
+ });
56
+ });
57
+ conversions.push({
58
+ conversionExpression: (value) => value,
59
+ sourceTypeCheckExpression: (value) => `typeof ${value} === "object"`,
60
+ sourceTypeName: this.name,
61
+ });
62
+ return conversions;
63
+ }
64
+ get discriminatorProperty() {
65
+ return Maybe.of({
66
+ name: "termType",
67
+ type: "string",
68
+ values: [...this.nodeKinds],
69
+ });
70
+ }
71
+ get jsonName() {
72
+ invariant(this.nodeKinds.has("Literal") &&
73
+ (this.nodeKinds.has("BlankNode") || this.nodeKinds.has("NamedNode")), "IdentifierType and LiteralType should override");
74
+ return `{ readonly "@id": string, readonly termType: ${[...this.nodeKinds]
75
+ .filter((nodeKind) => nodeKind !== "Literal")
76
+ .map((nodeKind) => `"${nodeKind}"`)
77
+ .join(" | ")} } | { readonly "@language": string | undefined, readonly "@type": string | undefined, readonly "@value": string, readonly termType: "Literal" }`;
78
+ }
79
+ get name() {
80
+ return `(${[...this.nodeKinds]
81
+ .map((nodeKind) => `rdfjs.${nodeKind}`)
82
+ .join(" | ")})`;
83
+ }
84
+ fromJsonExpression({ variables, }) {
85
+ invariant(this.nodeKinds.has("Literal") &&
86
+ (this.nodeKinds.has("BlankNode") || this.nodeKinds.has("NamedNode")), "IdentifierType and LiteralType should override");
87
+ return [...this.nodeKinds].reduce((expression, nodeKind) => {
88
+ let valueToNodeKind;
89
+ switch (nodeKind) {
90
+ case "BlankNode":
91
+ valueToNodeKind = `${this.dataFactoryVariable}.blankNode(${variables.value}["@id"].substring(2))`;
92
+ break;
93
+ case "Literal":
94
+ valueToNodeKind = `${this.dataFactoryVariable}.literal(${variables.value}["@value"], typeof ${variables.value}["@language"] !== "undefined" ? ${variables.value}["@language"] : (typeof ${variables.value}["@type"] !== "undefined" ? dataFactory.namedNode(${variables.value}["@type"]) : undefined))`;
95
+ break;
96
+ case "NamedNode":
97
+ valueToNodeKind = `${this.dataFactoryVariable}.namedNode(${variables.value}["@id"])`;
98
+ break;
99
+ default:
100
+ throw new RangeError(nodeKind);
101
+ }
102
+ return expression.length === 0
103
+ ? valueToNodeKind
104
+ : `((${variables.value}.termType === "${nodeKind}") ? (${valueToNodeKind}) : (${expression}))`;
105
+ }, "");
106
+ }
107
+ fromRdfExpression({ variables, }) {
108
+ const chain = [
109
+ this.propertyFilterRdfResourceValuesExpression({ variables }),
110
+ ];
111
+ // Have an rdfjsResource.Resource.Values here
112
+ if (this.hasValues.length === 1) {
113
+ chain.push(`find(_value => _value.toTerm().equals(${this.rdfjsTermExpression(this.hasValues[0])}))`);
114
+ }
115
+ else {
116
+ chain.push("head()");
117
+ }
118
+ // Have an rdfjsResource.Resource.Value here
119
+ this.defaultValue.ifJust((defaultValue) => {
120
+ // alt the default value before trying to convert the rdfjsResource.Resource.Value to the type
121
+ chain.push(`alt(purify.Either.of(new rdfjsResource.Resource.Value(${objectInitializer({ subject: variables.resource, predicate: variables.predicate, object: this.rdfjsTermExpression(defaultValue) })})))`);
122
+ });
123
+ // Last step: convert the rdfjsResource.Resource.Value to the type
124
+ chain.push(`chain(_value => ${this.propertyFromRdfResourceValueExpression({
125
+ variables: {
126
+ predicate: variables.predicate,
127
+ resource: variables.resource,
128
+ resourceValue: "_value",
129
+ },
130
+ })})`);
131
+ return chain.join(".");
132
+ }
133
+ hashStatements({ variables, }) {
134
+ return [
135
+ `${variables.hasher}.update(${variables.value}.termType);`,
136
+ `${variables.hasher}.update(${variables.value}.value);`,
137
+ ];
138
+ }
139
+ jsonZodSchema({ variables, }) {
140
+ invariant(this.nodeKinds.has("Literal") &&
141
+ (this.nodeKinds.has("BlankNode") || this.nodeKinds.has("NamedNode")), "IdentifierType and LiteralType should override");
142
+ return `${variables.zod}.discriminatedUnion("termType", [${[
143
+ ...this.nodeKinds,
144
+ ]
145
+ .map((nodeKind) => {
146
+ switch (nodeKind) {
147
+ case "BlankNode":
148
+ case "NamedNode":
149
+ return `${variables.zod}.object({ "@id": ${variables.zod}.string().min(1), termType: ${variables.zod}.literal("${nodeKind}") })`;
150
+ case "Literal":
151
+ return `${variables.zod}.object({ "@language": ${variables.zod}.string().optional(), "@type": ${variables.zod}.string().optional(), "@value": ${variables.zod}.string(), termType: ${variables.zod}.literal("Literal") })`;
152
+ default:
153
+ throw new RangeError(nodeKind);
154
+ }
155
+ })
156
+ .join(", ")}])`;
157
+ }
158
+ snippetDeclarations(features) {
159
+ const snippetDeclarations = [];
160
+ if (features.has("equals")) {
161
+ snippetDeclarations.push(SnippetDeclarations.booleanEquals);
162
+ }
163
+ return snippetDeclarations;
164
+ }
165
+ sparqlWherePatterns(parameters) {
166
+ switch (parameters.context) {
167
+ case "property":
168
+ return this.defaultValue
169
+ .map(() => [
170
+ `{ patterns: [${super.sparqlWherePatterns(parameters).join(", ")}], type: "optional" }`,
171
+ ])
172
+ .orDefault(super.sparqlWherePatterns(parameters));
173
+ case "type":
174
+ return super.sparqlWherePatterns(parameters);
175
+ }
176
+ }
177
+ toJsonExpression({ variables, }) {
178
+ invariant(this.nodeKinds.has("Literal") &&
179
+ (this.nodeKinds.has("BlankNode") || this.nodeKinds.has("NamedNode")), "IdentifierType and LiteralType should override");
180
+ return [...this.nodeKinds].reduce((expression, nodeKind) => {
181
+ let valueToNodeKind;
182
+ switch (nodeKind) {
183
+ case "BlankNode":
184
+ valueToNodeKind = `{ "@id": \`_:\${${variables.value}.value}\`, termType: "${nodeKind}" as const }`;
185
+ break;
186
+ case "Literal":
187
+ valueToNodeKind = `{ "@language": ${variables.value}.language.length > 0 ? ${variables.value}.language : undefined, "@type": ${variables.value}.datatype.value !== "${xsd.string.value}" ? ${variables.value}.datatype.value : undefined, "@value": ${variables.value}.value, termType: "${nodeKind}" as const }`;
188
+ break;
189
+ case "NamedNode":
190
+ valueToNodeKind = `{ "@id": ${variables.value}.value, termType: "${nodeKind}" as const }`;
191
+ break;
192
+ default:
193
+ throw new RangeError(nodeKind);
194
+ }
195
+ return expression.length === 0
196
+ ? valueToNodeKind
197
+ : `(${variables.value}.termType === "${nodeKind}") ? ${valueToNodeKind} : ${expression}`;
198
+ }, "");
199
+ }
200
+ toRdfExpression({ variables, }) {
201
+ return this.defaultValue
202
+ .map((defaultValue) => `!${variables.value}.equals(${this.rdfjsTermExpression(defaultValue)}) ? ${variables.value} : undefined`)
203
+ .orDefault(variables.value);
204
+ }
205
+ useImports() {
206
+ const imports = [Import.RDFJS_TYPES];
207
+ if (this.nodeKinds.has("Literal")) {
208
+ imports.push(Import.RDF_LITERAL);
209
+ }
210
+ return imports;
211
+ }
212
+ /**
213
+ * Filter the rdfjsResource.Resource.Values to those that are relevant to the type.
214
+ *
215
+ * This is done before
216
+ */
217
+ propertyFilterRdfResourceValuesExpression({ variables, }) {
218
+ return variables.resourceValues;
219
+ }
220
+ /**
221
+ * Convert an rdfjsResource.Resource.Value to a value of this type.
222
+ * @param variables
223
+ * @protected
224
+ */
225
+ propertyFromRdfResourceValueExpression({ variables, }) {
226
+ invariant(this.nodeKinds.has("Literal") &&
227
+ (this.nodeKinds.has("BlankNode") || this.nodeKinds.has("NamedNode")), "IdentifierType and LiteralType should override");
228
+ let expression = `purify.Either.of(${variables.resourceValue}.toTerm())`;
229
+ if (this.nodeKinds.size < 3) {
230
+ expression = `${expression}.chain(term => {
231
+ switch (term.termType) {
232
+ ${[...this.nodeKinds].map((nodeKind) => `case "${nodeKind}":`).join("\n")} return purify.Either.of(term);
233
+ default: return purify.Left(new rdfjsResource.Resource.MistypedValueError(${objectInitializer({ actualValue: "term", expectedValueType: JSON.stringify(this.name), focusResource: variables.resource, predicate: variables.predicate })}));
234
+ }})`;
235
+ }
236
+ return expression;
237
+ }
238
+ }
239
+ __decorate([
240
+ Memoize()
241
+ ], TermType.prototype, "name", null);
242
+ //# sourceMappingURL=TermType.js.map
@@ -1,15 +1,7 @@
1
- import type * as ast from "../../ast";
2
- import { Configuration as GlobalConfiguration } from "./Configuration.js";
3
- export declare class TsGenerator {
4
- private ast;
5
- protected readonly configuration: TsGenerator.Configuration;
6
- constructor(ast: ast.Ast, configuration?: TsGenerator.Configuration);
7
- generate(): string;
1
+ import * as ast from "../../ast/index.js";
2
+ import type { Generator } from "../Generator.js";
3
+ export declare class TsGenerator implements Generator {
4
+ generate(ast_: ast.Ast): string;
8
5
  private addDeclarations;
9
- private addImportDeclarations;
10
- }
11
- export declare namespace TsGenerator {
12
- const Configuration: typeof GlobalConfiguration;
13
- type Configuration = GlobalConfiguration;
14
6
  }
15
7
  //# sourceMappingURL=TsGenerator.d.ts.map
@@ -1,119 +1,77 @@
1
- import { Project, StructureKind, } from "ts-morph";
2
- import { Configuration as GlobalConfiguration } from "./Configuration.js";
1
+ import { Project, } from "ts-morph";
2
+ import * as ast from "../../ast/index.js";
3
+ import { ObjectType } from "./ObjectType.js";
4
+ import { ObjectUnionType } from "./ObjectUnionType.js";
3
5
  import { TypeFactory } from "./TypeFactory.js";
4
- import { tsName } from "./tsName.js";
5
6
  export class TsGenerator {
6
- constructor(ast, configuration) {
7
- this.ast = ast;
8
- this.configuration = configuration ?? new TsGenerator.Configuration();
9
- }
10
- generate() {
11
- const astObjectTypes = this.ast.objectTypes.concat();
12
- astObjectTypes.sort((left, right) => {
13
- if (left.ancestorObjectTypes.some((ancestorObjectType) => ancestorObjectType.name.identifier.equals(right.name.identifier))) {
14
- // Right is an ancestor of left, right must come first
15
- return 1;
16
- }
17
- if (right.ancestorObjectTypes.some((ancestorObjectType) => ancestorObjectType.name.identifier.equals(left.name.identifier))) {
18
- // Left is an ancestor of right, left must come first
19
- return -1;
20
- }
21
- // Neither is an ancestor of the other, sort by name
22
- return tsName(left.name).localeCompare(tsName(right.name));
23
- });
7
+ generate(ast_) {
8
+ const sortedAstObjectTypes = ast.ObjectType.toposort(ast_.objectTypes);
24
9
  const project = new Project({
25
10
  useInMemoryFileSystem: true,
26
11
  });
27
12
  const sourceFile = project.createSourceFile("generated.ts");
28
- const typeFactory = new TypeFactory({ configuration: this.configuration });
29
- const objectTypes = astObjectTypes.flatMap((astObjectType) => {
30
- const type = typeFactory.createTypeFromAstType(astObjectType);
31
- return type.kind === "ObjectType" ? [type] : [];
13
+ const typeFactory = new TypeFactory({
14
+ dataFactoryVariable: ast_.tsDataFactoryVariable,
15
+ });
16
+ this.addDeclarations({
17
+ objectTypes: sortedAstObjectTypes.flatMap((astObjectType) => {
18
+ const type = typeFactory.createTypeFromAstType(astObjectType);
19
+ return type instanceof ObjectType ? [type] : [];
20
+ }),
21
+ objectUnionTypes: ast_.objectUnionTypes.flatMap((astObjectUnionType) => {
22
+ const type = typeFactory.createTypeFromAstType(astObjectUnionType);
23
+ return type instanceof ObjectUnionType ? [type] : [];
24
+ }),
25
+ sourceFile,
32
26
  });
33
- this.addDeclarations(objectTypes, sourceFile);
34
27
  sourceFile.saveSync();
35
28
  return project.getFileSystem().readFileSync(sourceFile.getFilePath());
36
29
  }
37
- addDeclarations(objectTypes, sourceFile) {
38
- this.addImportDeclarations(objectTypes, sourceFile);
39
- for (const objectType of objectTypes) {
40
- switch (this.configuration.objectTypeDeclarationType) {
41
- case "class":
42
- sourceFile.addClass(objectType.classDeclaration());
43
- break;
44
- case "interface":
45
- sourceFile.addInterface(objectType.interfaceDeclaration());
46
- break;
47
- }
48
- const moduleStatements = [];
49
- if (this.configuration.features.has("equals") &&
50
- this.configuration.objectTypeDeclarationType === "interface") {
51
- moduleStatements.push(objectType.equalsFunctionDeclaration());
52
- }
53
- if (this.configuration.features.has("fromRdf")) {
54
- moduleStatements.push(objectType.fromRdfFunctionDeclaration());
55
- }
56
- if (this.configuration.features.has("hash")) {
57
- moduleStatements.push(objectType.hashFunctionDeclaration());
58
- }
59
- if (this.configuration.features.has("sparql-graph-patterns")) {
60
- if (objectType.parentObjectTypes.length > 1) {
61
- throw new RangeError(`object type '${objectType.name}' has multiple super object types, can't use with SPARQL graph patterns`);
30
+ addDeclarations({ objectTypes, objectUnionTypes, sourceFile, }) {
31
+ // sourceFile.addStatements(this.configuration.dataFactoryImport);
32
+ sourceFile.addStatements('import { DataFactory as dataFactory } from "n3"');
33
+ const declaredTypes = [
34
+ ...objectTypes,
35
+ ...objectUnionTypes,
36
+ ];
37
+ // Gather imports
38
+ const imports = [];
39
+ for (const declaredType of declaredTypes) {
40
+ imports.push(...declaredType.declarationImports);
41
+ }
42
+ // Deduplicate and add imports
43
+ const addedStringImports = new Set();
44
+ const addedStructureImports = [];
45
+ for (const import_ of imports) {
46
+ if (typeof import_ === "string") {
47
+ if (!addedStringImports.has(import_)) {
48
+ sourceFile.addStatements([import_]);
62
49
  }
63
- moduleStatements.push(objectType.sparqlGraphPatternsClassDeclaration());
50
+ addedStringImports.add(import_);
51
+ continue;
64
52
  }
65
- if (this.configuration.features.has("toRdf") &&
66
- this.configuration.objectTypeDeclarationType === "interface") {
67
- moduleStatements.push(objectType.toRdfFunctionDeclaration());
53
+ if (!addedStructureImports.find((addedStructureImport) => addedStructureImport.moduleSpecifier === import_.moduleSpecifier)) {
54
+ sourceFile.addStatements([import_]);
55
+ addedStructureImports.push(import_);
68
56
  }
69
- sourceFile.addModule({
70
- isExported: objectType.export_,
71
- kind: StructureKind.Module,
72
- name: objectType.name,
73
- statements: moduleStatements,
74
- });
75
- }
76
- }
77
- addImportDeclarations(objectTypes, sourceFile) {
78
- sourceFile.addImportDeclaration({
79
- moduleSpecifier: "purify-ts",
80
- namespaceImport: "purify",
81
- });
82
- sourceFile.addImportDeclaration({
83
- isTypeOnly: true,
84
- moduleSpecifier: "@rdfjs/types",
85
- namespaceImport: "rdfjs",
86
- });
87
- sourceFile.addStatements(this.configuration.dataFactoryImport);
88
- if (this.configuration.features.has("equals")) {
89
- sourceFile.addImportDeclaration({
90
- moduleSpecifier: "purify-ts-helpers",
91
- namespaceImport: "purifyHelpers",
92
- });
93
57
  }
94
- if (this.configuration.features.has("fromRdf") ||
95
- this.configuration.features.has("toRdf")) {
96
- sourceFile.addImportDeclaration({
97
- moduleSpecifier: "rdfjs-resource",
98
- namespaceImport: "rdfjsResource",
99
- });
100
- }
101
- if (this.configuration.features.has("sparql-graph-patterns")) {
102
- sourceFile.addImportDeclaration({
103
- moduleSpecifier: "@kos-kit/sparql-builder",
104
- namespaceImport: "sparqlBuilder",
105
- });
58
+ // Deduplicate and add snippet declarations
59
+ const addedSnippetDeclarations = new Set();
60
+ for (const declaredType of declaredTypes) {
61
+ for (const snippetDeclaration of declaredType.snippetDeclarations(declaredType.features)) {
62
+ if (!addedSnippetDeclarations.has(snippetDeclaration)) {
63
+ sourceFile.addStatements([snippetDeclaration]);
64
+ addedSnippetDeclarations.add(snippetDeclaration);
65
+ }
66
+ }
106
67
  }
107
- const typeImportStatements = new Set();
68
+ // Add type declarations
108
69
  for (const objectType of objectTypes) {
109
- for (const importStatement of objectType.importStatements) {
110
- typeImportStatements.add(importStatement);
111
- }
70
+ sourceFile.addStatements(objectType.declarations);
71
+ }
72
+ for (const objectUnionType of objectUnionTypes) {
73
+ sourceFile.addStatements(objectUnionType.declarations);
112
74
  }
113
- sourceFile.addStatements([...typeImportStatements]);
114
75
  }
115
76
  }
116
- (function (TsGenerator) {
117
- TsGenerator.Configuration = GlobalConfiguration;
118
- })(TsGenerator || (TsGenerator = {}));
119
77
  //# sourceMappingURL=TsGenerator.js.map
@@ -1,73 +1,153 @@
1
+ import type { BlankNode, Literal, NamedNode, Variable } from "@rdfjs/types";
1
2
  import { Maybe } from "purify-ts";
2
- import type * as ast from "../../ast";
3
- import type { Configuration } from "./Configuration.js";
3
+ import type { TsFeature } from "../../enums/index.js";
4
+ import type { Import } from "./Import.js";
5
+ /**
6
+ * Abstract base class for generating TypeScript expressions and statemenst in the TypeScript generator.
7
+ *
8
+ * Subclasses are used for both property types (c.f., property* methods) and node/object types.
9
+ */
4
10
  export declare abstract class Type {
5
- abstract readonly kind: ast.Type["kind"] | "ListType";
6
- abstract readonly name: string;
7
- protected readonly configuration: Configuration;
8
- constructor({ configuration, }: {
9
- configuration: Configuration;
10
- });
11
11
  /**
12
12
  * Expressions that convert a source type or types to this type. It should include the type itself.
13
13
  */
14
- get conversions(): readonly Type.Conversion[];
14
+ abstract readonly conversions: readonly Type.Conversion[];
15
15
  /**
16
- * A property that discriminates sub-types of this type e.g., termType on RDF/JS terms.
16
+ * A function (reference or declaration) that compares two property values of this type, returning a
17
+ * EqualsResult.
17
18
  */
18
- get discriminatorProperty(): Maybe<Type.DiscriminatorProperty>;
19
+ abstract readonly equalsFunction: string;
19
20
  /**
20
- * Imports used by other methods on this type.
21
+ * JSON-compatible returned by propertyToJsonExpression.
21
22
  */
22
- get importStatements(): readonly string[];
23
+ abstract readonly jsonName: string;
23
24
  /**
24
- * An optional sparqlBuilder.GraphPattern expression that's chained to the object of another pattern, such as a list item.
25
- *
26
- * If the type is e.g., an RDF/JS term it won't have additional graph patterns beyond the basic (s, p, o), and this
27
- * method will return nothing.
25
+ * Is a value of this type mutable?
28
26
  */
29
- chainSparqlGraphPatternExpression(_: {
30
- variables: {
31
- subject: string;
32
- };
33
- }): Maybe<Type.SparqlGraphPatternExpression | Type.SparqlGraphPatternsExpression>;
27
+ abstract readonly mutable: boolean;
28
+ /**
29
+ * Name of the type.
30
+ */
31
+ abstract readonly name: string;
32
+ protected readonly dataFactoryVariable: string;
33
+ constructor({ dataFactoryVariable, }: {
34
+ dataFactoryVariable: string;
35
+ });
36
+ /**
37
+ * A property that discriminates sub-types of this type e.g., termType on RDF/JS terms.
38
+ */
39
+ get discriminatorProperty(): Maybe<Type.DiscriminatorProperty>;
34
40
  /**
35
- * A function (reference or declaration) that compares two values of this type, returning a
36
- * purifyHelpers.Equatable.EqualsResult.
41
+ * An expression that converts a JSON object in the same format as the propertyToJsonExpression to a value of this type.
37
42
  */
38
- abstract equalsFunction(): string;
43
+ abstract fromJsonExpression(parameters: {
44
+ variables: {
45
+ value: string;
46
+ };
47
+ }): string;
39
48
  /**
40
49
  * An expression that converts a rdfjsResource.Resource.Values to an Either of value/values
41
- * of this type.
50
+ * of this type for a property.
42
51
  */
43
52
  abstract fromRdfExpression(parameters: {
44
53
  variables: {
54
+ context: string;
55
+ languageIn: string;
45
56
  predicate: string;
46
57
  resource: string;
47
58
  resourceValues: string;
48
59
  };
49
60
  }): string;
50
61
  /**
51
- * Statements that use hasher.update to hash a value of this type.
62
+ * Statements that use hasher.update to hash a property value of this type.
52
63
  */
53
64
  abstract hashStatements(parameters: {
65
+ depth: number;
54
66
  variables: {
55
67
  hasher: string;
56
68
  value: string;
57
69
  };
58
70
  }): readonly string[];
59
71
  /**
60
- * An sparqlBuilder.GraphPattern expression for a property, typically building a basic graph pattern.
72
+ * Element object for a JSON Forms UI schema.
73
+ */
74
+ jsonUiSchemaElement(_parameters: {
75
+ variables: {
76
+ scopePrefix: string;
77
+ };
78
+ }): Maybe<string>;
79
+ /**
80
+ * Zod schema for the JSON version of the type (the result of propertyToJson).
81
+ */
82
+ abstract jsonZodSchema(parameters: {
83
+ variables: {
84
+ zod: string;
85
+ };
86
+ }): string;
87
+ /**
88
+ * Reusable function, type, and other declarations that are not particular to this type but that type-specific code
89
+ * relies on. For example, the equals function/method of ObjectType has a custom return type that's the same across all
90
+ * ObjectType's. Instead of re-declaring the return type anonymously on every equals function, declare a named type
91
+ * as a snippet and reference it.
92
+ *
93
+ * The generator deduplicates snippet declarations across all types before adding them to the source.
94
+ */
95
+ snippetDeclarations(_features: Set<TsFeature>): readonly string[];
96
+ /**
97
+ * An array of SPARQL.js CONSTRUCT template triples for a value of this type, as strings (so they can incorporate runtime calls).
98
+ *
99
+ * This method is called in two contexts:
100
+ * (1) By an ObjectType.Property. The property expects a basic graph pattern (subject, property path, property object). The property calls this method to get additional triples in which the propertyObject is the subject. For example, if the type is a nested object, it would include (propertyObject, nestedPredicate, nestedObject) triples.
101
+ * (2) By another Type. For example, ListType calls this method to with the item variable as a subject in order to chain additional patterns on items.
102
+ *
103
+ * Term types with no additional properties should return an empty array.
104
+ */
105
+ sparqlConstructTemplateTriples({ context, variables, }: {
106
+ context: "property";
107
+ variables: {
108
+ object: string;
109
+ predicate: string;
110
+ subject: string;
111
+ variablePrefix: string;
112
+ };
113
+ } | {
114
+ context: "type";
115
+ variables: {
116
+ subject: string;
117
+ variablePrefix: string;
118
+ };
119
+ }): readonly string[];
120
+ /**
121
+ * An array of SPARQL.js where patterns for a value of this type, as strings (so they can incorporate runtime calls).
122
+ *
123
+ * See note in sparqlConstructTemplateTriples re: how this method is used.
61
124
  */
62
- propertySparqlGraphPatternExpression({ variables, }: {
125
+ sparqlWherePatterns({ context, variables, }: {
126
+ context: "property";
63
127
  variables: {
64
128
  object: string;
65
129
  predicate: string;
66
130
  subject: string;
131
+ variablePrefix: string;
132
+ };
133
+ } | {
134
+ context: "type";
135
+ variables: {
136
+ subject: string;
137
+ variablePrefix: string;
67
138
  };
68
- }): Type.SparqlGraphPatternExpression | Type.SparqlGraphPatternsExpression;
139
+ }): readonly string[];
69
140
  /**
70
- * An expression that converts a value of this type to one that that can be .add'd to
141
+ * An expression that converts a value of this type to a JSON-LD compatible value. It can assume the presence
142
+ * of the correct JSON-LD context.
143
+ */
144
+ abstract toJsonExpression(parameters: {
145
+ variables: {
146
+ value: string;
147
+ };
148
+ }): string;
149
+ /**
150
+ * An expression that converts a property value of this type to one that that can be .add'd to
71
151
  * an rdfjsResource.Resource.
72
152
  */
73
153
  abstract toRdfExpression(parameters: {
@@ -79,30 +159,21 @@ export declare abstract class Type {
79
159
  value: string;
80
160
  };
81
161
  }): string;
162
+ /**
163
+ * Imports necessary to use this type.
164
+ */
165
+ useImports(_features: Set<TsFeature>): readonly Import[];
166
+ protected rdfjsTermExpression(rdfjsTerm: Omit<BlankNode, "equals"> | Omit<Literal, "equals"> | Omit<NamedNode, "equals"> | Omit<Variable, "equals">): string;
82
167
  }
83
168
  export declare namespace Type {
84
169
  interface Conversion {
85
170
  readonly conversionExpression: (value: string) => string;
86
- readonly sourceTypeCheckExpression?: (value: string) => string;
171
+ readonly sourceTypeCheckExpression: (value: string) => string;
87
172
  readonly sourceTypeName: string;
88
173
  }
89
174
  interface DiscriminatorProperty {
90
175
  readonly name: string;
91
176
  readonly values: readonly string[];
92
177
  }
93
- class SparqlGraphPatternExpression {
94
- private readonly value;
95
- constructor(value: string);
96
- toSparqlGraphPatternExpression(): this;
97
- toSparqlGraphPatternsExpression(): SparqlGraphPatternExpression;
98
- toString(): string;
99
- }
100
- class SparqlGraphPatternsExpression {
101
- private readonly value;
102
- constructor(value: string);
103
- toSparqlGraphPatternExpression(): SparqlGraphPatternExpression;
104
- toSparqlGraphPatternsExpression(): this;
105
- toString(): string;
106
- }
107
178
  }
108
179
  //# sourceMappingURL=Type.d.ts.map