@comake/skl-js-engine 1.5.4 → 1.5.6

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 (306) hide show
  1. package/dist/JsExecutor/PermissionBuilder.d.ts +14 -0
  2. package/dist/JsExecutor/PermissionBuilder.d.ts.map +1 -0
  3. package/dist/JsExecutor/PermissionBuilder.js +58 -0
  4. package/dist/JsExecutor/PermissionBuilder.js.map +1 -0
  5. package/dist/JsExecutor/constants.d.ts +27 -0
  6. package/dist/JsExecutor/constants.d.ts.map +1 -0
  7. package/dist/JsExecutor/constants.js +30 -0
  8. package/dist/JsExecutor/constants.js.map +1 -0
  9. package/dist/JsExecutor/denoUtils.d.ts +10 -0
  10. package/dist/JsExecutor/denoUtils.d.ts.map +1 -0
  11. package/dist/JsExecutor/denoUtils.js +24 -0
  12. package/dist/JsExecutor/denoUtils.js.map +1 -0
  13. package/dist/JsExecutor/errors.d.ts +40 -0
  14. package/dist/JsExecutor/errors.d.ts.map +1 -0
  15. package/dist/JsExecutor/errors.js +67 -0
  16. package/dist/JsExecutor/errors.js.map +1 -0
  17. package/dist/JsExecutor/examples/basic/index.d.ts +1 -0
  18. package/dist/JsExecutor/examples/basic/index.d.ts.map +1 -0
  19. package/dist/JsExecutor/examples/basic/index.js +46 -0
  20. package/dist/JsExecutor/examples/basic/index.js.map +1 -0
  21. package/dist/JsExecutor/examples/basic/process.d.ts +1 -0
  22. package/dist/JsExecutor/examples/basic/process.d.ts.map +1 -0
  23. package/dist/JsExecutor/examples/basic/process.js +34 -0
  24. package/dist/JsExecutor/examples/basic/process.js.map +1 -0
  25. package/dist/JsExecutor/examples/jsExecutor/index.d.ts +2 -0
  26. package/dist/JsExecutor/examples/jsExecutor/index.d.ts.map +1 -0
  27. package/dist/JsExecutor/examples/jsExecutor/index.js +47 -0
  28. package/dist/JsExecutor/examples/jsExecutor/index.js.map +1 -0
  29. package/dist/JsExecutor/examples/jsExecutor/process.d.ts +2 -0
  30. package/dist/JsExecutor/examples/jsExecutor/process.d.ts.map +1 -0
  31. package/dist/JsExecutor/examples/jsExecutor/process.js +58 -0
  32. package/dist/JsExecutor/examples/jsExecutor/process.js.map +1 -0
  33. package/dist/JsExecutor/index.d.ts +7 -0
  34. package/dist/JsExecutor/index.d.ts.map +1 -0
  35. package/dist/JsExecutor/index.js +36 -0
  36. package/dist/JsExecutor/index.js.map +1 -0
  37. package/dist/JsExecutor/jsExecutor.d.ts +68 -0
  38. package/dist/JsExecutor/jsExecutor.d.ts.map +1 -0
  39. package/dist/JsExecutor/jsExecutor.js +171 -0
  40. package/dist/JsExecutor/jsExecutor.js.map +1 -0
  41. package/dist/JsExecutor/jsonRpc/JsonRpcClient.d.ts +165 -0
  42. package/dist/JsExecutor/jsonRpc/JsonRpcClient.d.ts.map +1 -0
  43. package/dist/JsExecutor/jsonRpc/JsonRpcClient.js +335 -0
  44. package/dist/JsExecutor/jsonRpc/JsonRpcClient.js.map +1 -0
  45. package/dist/JsExecutor/jsonRpc/JsonRpcServer.d.ts +125 -0
  46. package/dist/JsExecutor/jsonRpc/JsonRpcServer.d.ts.map +1 -0
  47. package/dist/JsExecutor/jsonRpc/JsonRpcServer.js +391 -0
  48. package/dist/JsExecutor/jsonRpc/JsonRpcServer.js.map +1 -0
  49. package/dist/JsExecutor/jsonRpc/index.d.ts +4 -0
  50. package/dist/JsExecutor/jsonRpc/index.d.ts.map +1 -0
  51. package/dist/JsExecutor/jsonRpc/index.js +23 -0
  52. package/dist/JsExecutor/jsonRpc/index.js.map +1 -0
  53. package/dist/JsExecutor/jsonRpc/types.d.ts +193 -0
  54. package/dist/JsExecutor/jsonRpc/types.d.ts.map +1 -0
  55. package/dist/JsExecutor/jsonRpc/types.js +37 -0
  56. package/dist/JsExecutor/jsonRpc/types.js.map +1 -0
  57. package/dist/JsExecutor/transport/Transport.d.ts +74 -0
  58. package/dist/JsExecutor/transport/Transport.d.ts.map +1 -0
  59. package/dist/JsExecutor/transport/Transport.js +14 -0
  60. package/dist/JsExecutor/transport/Transport.js.map +1 -0
  61. package/dist/JsExecutor/transport/base/BaseTransport.d.ts +51 -0
  62. package/dist/JsExecutor/transport/base/BaseTransport.d.ts.map +1 -0
  63. package/dist/JsExecutor/transport/base/BaseTransport.js +68 -0
  64. package/dist/JsExecutor/transport/base/BaseTransport.js.map +1 -0
  65. package/dist/JsExecutor/transport/index.d.ts +13 -0
  66. package/dist/JsExecutor/transport/index.d.ts.map +1 -0
  67. package/dist/JsExecutor/transport/index.js +36 -0
  68. package/dist/JsExecutor/transport/index.js.map +1 -0
  69. package/dist/JsExecutor/transport/process/ProcessManager.d.ts +96 -0
  70. package/dist/JsExecutor/transport/process/ProcessManager.d.ts.map +1 -0
  71. package/dist/JsExecutor/transport/process/ProcessManager.js +219 -0
  72. package/dist/JsExecutor/transport/process/ProcessManager.js.map +1 -0
  73. package/dist/JsExecutor/transport/stdio/ChildStdioTransport.d.ts +87 -0
  74. package/dist/JsExecutor/transport/stdio/ChildStdioTransport.d.ts.map +1 -0
  75. package/dist/JsExecutor/transport/stdio/ChildStdioTransport.js +219 -0
  76. package/dist/JsExecutor/transport/stdio/ChildStdioTransport.js.map +1 -0
  77. package/dist/JsExecutor/transport/stdio/ParentStdioTransport.d.ts +81 -0
  78. package/dist/JsExecutor/transport/stdio/ParentStdioTransport.d.ts.map +1 -0
  79. package/dist/JsExecutor/transport/stdio/ParentStdioTransport.js +259 -0
  80. package/dist/JsExecutor/transport/stdio/ParentStdioTransport.js.map +1 -0
  81. package/dist/JsExecutor/transport/utils/MessageUtils.d.ts +68 -0
  82. package/dist/JsExecutor/transport/utils/MessageUtils.d.ts.map +1 -0
  83. package/dist/JsExecutor/transport/utils/MessageUtils.js +135 -0
  84. package/dist/JsExecutor/transport/utils/MessageUtils.js.map +1 -0
  85. package/dist/JsExecutor/transport/utils/PollingUtils.d.ts +53 -0
  86. package/dist/JsExecutor/transport/utils/PollingUtils.d.ts.map +1 -0
  87. package/dist/JsExecutor/transport/utils/PollingUtils.js +92 -0
  88. package/dist/JsExecutor/transport/utils/PollingUtils.js.map +1 -0
  89. package/dist/JsExecutor/types.d.ts +113 -0
  90. package/dist/JsExecutor/types.d.ts.map +1 -0
  91. package/dist/JsExecutor/types.js +3 -0
  92. package/dist/JsExecutor/types.js.map +1 -0
  93. package/dist/SklEngine.d.ts +132 -0
  94. package/dist/SklEngine.d.ts.map +1 -0
  95. package/dist/SklEngine.js +1514 -0
  96. package/dist/SklEngine.js.map +1 -0
  97. package/dist/SklEngineOptions.d.ts +58 -0
  98. package/dist/SklEngineOptions.d.ts.map +1 -0
  99. package/dist/SklEngineOptions.js +3 -0
  100. package/dist/SklEngineOptions.js.map +1 -0
  101. package/dist/constants.d.ts +96 -0
  102. package/dist/constants.d.ts.map +1 -0
  103. package/dist/constants.js +103 -0
  104. package/dist/constants.js.map +1 -0
  105. package/dist/customCapabilities.d.ts +22 -0
  106. package/dist/customCapabilities.d.ts.map +1 -0
  107. package/dist/customCapabilities.js +45 -0
  108. package/dist/customCapabilities.js.map +1 -0
  109. package/dist/examples/customCapabilitiesExample.d.ts +2 -0
  110. package/dist/examples/customCapabilitiesExample.d.ts.map +1 -0
  111. package/dist/examples/customCapabilitiesExample.js +59 -0
  112. package/dist/examples/customCapabilitiesExample.js.map +1 -0
  113. package/dist/executor.js +216 -0
  114. package/dist/hooks/globalHooks.d.ts +50 -0
  115. package/dist/hooks/globalHooks.d.ts.map +1 -0
  116. package/dist/hooks/globalHooks.js +164 -0
  117. package/dist/hooks/globalHooks.js.map +1 -0
  118. package/dist/hooks/types.d.ts +9 -0
  119. package/dist/hooks/types.d.ts.map +1 -0
  120. package/dist/hooks/types.js +3 -0
  121. package/dist/hooks/types.js.map +1 -0
  122. package/dist/index.d.ts +41 -0
  123. package/dist/index.d.ts.map +1 -0
  124. package/dist/index.js +68 -0
  125. package/dist/index.js.map +1 -0
  126. package/dist/logger.d.ts +35 -0
  127. package/dist/logger.d.ts.map +1 -0
  128. package/dist/logger.js +119 -0
  129. package/dist/logger.js.map +1 -0
  130. package/dist/mapping/Mapper.d.ts +13 -0
  131. package/dist/mapping/Mapper.d.ts.map +1 -0
  132. package/dist/mapping/Mapper.js +64 -0
  133. package/dist/mapping/Mapper.js.map +1 -0
  134. package/dist/storage/FindOperator.d.ts +19 -0
  135. package/dist/storage/FindOperator.d.ts.map +1 -0
  136. package/dist/storage/FindOperator.js +23 -0
  137. package/dist/storage/FindOperator.js.map +1 -0
  138. package/dist/storage/FindOptionsTypes.d.ts +79 -0
  139. package/dist/storage/FindOptionsTypes.d.ts.map +1 -0
  140. package/dist/storage/FindOptionsTypes.js +3 -0
  141. package/dist/storage/FindOptionsTypes.js.map +1 -0
  142. package/dist/storage/GroupOptionTypes.d.ts +29 -0
  143. package/dist/storage/GroupOptionTypes.d.ts.map +1 -0
  144. package/dist/storage/GroupOptionTypes.js +3 -0
  145. package/dist/storage/GroupOptionTypes.js.map +1 -0
  146. package/dist/storage/operator/And.d.ts +4 -0
  147. package/dist/storage/operator/And.d.ts.map +1 -0
  148. package/dist/storage/operator/And.js +13 -0
  149. package/dist/storage/operator/And.js.map +1 -0
  150. package/dist/storage/operator/Contains.d.ts +3 -0
  151. package/dist/storage/operator/Contains.d.ts.map +1 -0
  152. package/dist/storage/operator/Contains.js +13 -0
  153. package/dist/storage/operator/Contains.js.map +1 -0
  154. package/dist/storage/operator/Equal.d.ts +5 -0
  155. package/dist/storage/operator/Equal.d.ts.map +1 -0
  156. package/dist/storage/operator/Equal.js +13 -0
  157. package/dist/storage/operator/Equal.js.map +1 -0
  158. package/dist/storage/operator/Exists.d.ts +3 -0
  159. package/dist/storage/operator/Exists.d.ts.map +1 -0
  160. package/dist/storage/operator/Exists.js +10 -0
  161. package/dist/storage/operator/Exists.js.map +1 -0
  162. package/dist/storage/operator/GreaterThan.d.ts +4 -0
  163. package/dist/storage/operator/GreaterThan.d.ts.map +1 -0
  164. package/dist/storage/operator/GreaterThan.js +13 -0
  165. package/dist/storage/operator/GreaterThan.js.map +1 -0
  166. package/dist/storage/operator/GreaterThanOrEqual.d.ts +4 -0
  167. package/dist/storage/operator/GreaterThanOrEqual.d.ts.map +1 -0
  168. package/dist/storage/operator/GreaterThanOrEqual.js +13 -0
  169. package/dist/storage/operator/GreaterThanOrEqual.js.map +1 -0
  170. package/dist/storage/operator/In.d.ts +4 -0
  171. package/dist/storage/operator/In.d.ts.map +1 -0
  172. package/dist/storage/operator/In.js +13 -0
  173. package/dist/storage/operator/In.js.map +1 -0
  174. package/dist/storage/operator/Inverse.d.ts +3 -0
  175. package/dist/storage/operator/Inverse.d.ts.map +1 -0
  176. package/dist/storage/operator/Inverse.js +13 -0
  177. package/dist/storage/operator/Inverse.js.map +1 -0
  178. package/dist/storage/operator/InversePath.d.ts +7 -0
  179. package/dist/storage/operator/InversePath.d.ts.map +1 -0
  180. package/dist/storage/operator/InversePath.js +13 -0
  181. package/dist/storage/operator/InversePath.js.map +1 -0
  182. package/dist/storage/operator/InverseRelation.d.ts +9 -0
  183. package/dist/storage/operator/InverseRelation.d.ts.map +1 -0
  184. package/dist/storage/operator/InverseRelation.js +13 -0
  185. package/dist/storage/operator/InverseRelation.js.map +1 -0
  186. package/dist/storage/operator/InverseRelationOrder.d.ts +8 -0
  187. package/dist/storage/operator/InverseRelationOrder.d.ts.map +1 -0
  188. package/dist/storage/operator/InverseRelationOrder.js +13 -0
  189. package/dist/storage/operator/InverseRelationOrder.js.map +1 -0
  190. package/dist/storage/operator/LessThan.d.ts +4 -0
  191. package/dist/storage/operator/LessThan.d.ts.map +1 -0
  192. package/dist/storage/operator/LessThan.js +13 -0
  193. package/dist/storage/operator/LessThan.js.map +1 -0
  194. package/dist/storage/operator/LessThanOrEqual.d.ts +4 -0
  195. package/dist/storage/operator/LessThanOrEqual.d.ts.map +1 -0
  196. package/dist/storage/operator/LessThanOrEqual.js +13 -0
  197. package/dist/storage/operator/LessThanOrEqual.js.map +1 -0
  198. package/dist/storage/operator/Not.d.ts +3 -0
  199. package/dist/storage/operator/Not.d.ts.map +1 -0
  200. package/dist/storage/operator/Not.js +13 -0
  201. package/dist/storage/operator/Not.js.map +1 -0
  202. package/dist/storage/operator/OneOrMorePath.d.ts +7 -0
  203. package/dist/storage/operator/OneOrMorePath.d.ts.map +1 -0
  204. package/dist/storage/operator/OneOrMorePath.js +13 -0
  205. package/dist/storage/operator/OneOrMorePath.js.map +1 -0
  206. package/dist/storage/operator/Or.d.ts +4 -0
  207. package/dist/storage/operator/Or.d.ts.map +1 -0
  208. package/dist/storage/operator/Or.js +13 -0
  209. package/dist/storage/operator/Or.js.map +1 -0
  210. package/dist/storage/operator/Sequence.d.ts +3 -0
  211. package/dist/storage/operator/Sequence.d.ts.map +1 -0
  212. package/dist/storage/operator/Sequence.js +13 -0
  213. package/dist/storage/operator/Sequence.js.map +1 -0
  214. package/dist/storage/operator/SequencePath.d.ts +7 -0
  215. package/dist/storage/operator/SequencePath.d.ts.map +1 -0
  216. package/dist/storage/operator/SequencePath.js +13 -0
  217. package/dist/storage/operator/SequencePath.js.map +1 -0
  218. package/dist/storage/operator/ZeroOrMorePath.d.ts +7 -0
  219. package/dist/storage/operator/ZeroOrMorePath.d.ts.map +1 -0
  220. package/dist/storage/operator/ZeroOrMorePath.js +13 -0
  221. package/dist/storage/operator/ZeroOrMorePath.js.map +1 -0
  222. package/dist/storage/query-adapter/QueryAdapter.d.ts +99 -0
  223. package/dist/storage/query-adapter/QueryAdapter.d.ts.map +1 -0
  224. package/dist/storage/query-adapter/QueryAdapter.js +3 -0
  225. package/dist/storage/query-adapter/QueryAdapter.js.map +1 -0
  226. package/dist/storage/query-adapter/sparql/SparqlQueryAdapter.d.ts +40 -0
  227. package/dist/storage/query-adapter/sparql/SparqlQueryAdapter.d.ts.map +1 -0
  228. package/dist/storage/query-adapter/sparql/SparqlQueryAdapter.js +315 -0
  229. package/dist/storage/query-adapter/sparql/SparqlQueryAdapter.js.map +1 -0
  230. package/dist/storage/query-adapter/sparql/SparqlQueryAdapterOptions.d.ts +34 -0
  231. package/dist/storage/query-adapter/sparql/SparqlQueryAdapterOptions.d.ts.map +1 -0
  232. package/dist/storage/query-adapter/sparql/SparqlQueryAdapterOptions.js +3 -0
  233. package/dist/storage/query-adapter/sparql/SparqlQueryAdapterOptions.js.map +1 -0
  234. package/dist/storage/query-adapter/sparql/SparqlQueryBuilder.d.ts +104 -0
  235. package/dist/storage/query-adapter/sparql/SparqlQueryBuilder.d.ts.map +1 -0
  236. package/dist/storage/query-adapter/sparql/SparqlQueryBuilder.js +1210 -0
  237. package/dist/storage/query-adapter/sparql/SparqlQueryBuilder.js.map +1 -0
  238. package/dist/storage/query-adapter/sparql/SparqlUpdateBuilder.d.ts +44 -0
  239. package/dist/storage/query-adapter/sparql/SparqlUpdateBuilder.d.ts.map +1 -0
  240. package/dist/storage/query-adapter/sparql/SparqlUpdateBuilder.js +397 -0
  241. package/dist/storage/query-adapter/sparql/SparqlUpdateBuilder.js.map +1 -0
  242. package/dist/storage/query-adapter/sparql/VariableGenerator.d.ts +5 -0
  243. package/dist/storage/query-adapter/sparql/VariableGenerator.d.ts.map +1 -0
  244. package/dist/storage/query-adapter/sparql/VariableGenerator.js +14 -0
  245. package/dist/storage/query-adapter/sparql/VariableGenerator.js.map +1 -0
  246. package/dist/storage/query-adapter/sparql/query-executor/InMemorySparqlQueryExecutor.d.ts +19 -0
  247. package/dist/storage/query-adapter/sparql/query-executor/InMemorySparqlQueryExecutor.d.ts.map +1 -0
  248. package/dist/storage/query-adapter/sparql/query-executor/InMemorySparqlQueryExecutor.js +90 -0
  249. package/dist/storage/query-adapter/sparql/query-executor/InMemorySparqlQueryExecutor.js.map +1 -0
  250. package/dist/storage/query-adapter/sparql/query-executor/SparqlEndpointQueryExecutor.d.ts +27 -0
  251. package/dist/storage/query-adapter/sparql/query-executor/SparqlEndpointQueryExecutor.d.ts.map +1 -0
  252. package/dist/storage/query-adapter/sparql/query-executor/SparqlEndpointQueryExecutor.js +116 -0
  253. package/dist/storage/query-adapter/sparql/query-executor/SparqlEndpointQueryExecutor.js.map +1 -0
  254. package/dist/storage/query-adapter/sparql/query-executor/SparqlQueryExecutor.d.ts +34 -0
  255. package/dist/storage/query-adapter/sparql/query-executor/SparqlQueryExecutor.d.ts.map +1 -0
  256. package/dist/storage/query-adapter/sparql/query-executor/SparqlQueryExecutor.js +3 -0
  257. package/dist/storage/query-adapter/sparql/query-executor/SparqlQueryExecutor.js.map +1 -0
  258. package/dist/tools/explain-findall-sparql.d.ts +2 -0
  259. package/dist/tools/explain-findall-sparql.d.ts.map +1 -0
  260. package/dist/tools/explain-findall-sparql.js +303 -0
  261. package/dist/tools/explain-findall-sparql.js.map +1 -0
  262. package/dist/util/PerformanceLogger.d.ts +28 -0
  263. package/dist/util/PerformanceLogger.d.ts.map +1 -0
  264. package/dist/util/PerformanceLogger.js +223 -0
  265. package/dist/util/PerformanceLogger.js.map +1 -0
  266. package/dist/util/ReadCacheHelper.d.ts +14 -0
  267. package/dist/util/ReadCacheHelper.d.ts.map +1 -0
  268. package/dist/util/ReadCacheHelper.js +61 -0
  269. package/dist/util/ReadCacheHelper.js.map +1 -0
  270. package/dist/util/SparqlUtil.d.ts +72 -0
  271. package/dist/util/SparqlUtil.d.ts.map +1 -0
  272. package/dist/util/SparqlUtil.js +456 -0
  273. package/dist/util/SparqlUtil.js.map +1 -0
  274. package/dist/util/TripleUtil.d.ts +10 -0
  275. package/dist/util/TripleUtil.d.ts.map +1 -0
  276. package/dist/util/TripleUtil.js +431 -0
  277. package/dist/util/TripleUtil.js.map +1 -0
  278. package/dist/util/Types.d.ts +275 -0
  279. package/dist/util/Types.d.ts.map +1 -0
  280. package/dist/util/Types.js +3 -0
  281. package/dist/util/Types.js.map +1 -0
  282. package/dist/util/Util.d.ts +26 -0
  283. package/dist/util/Util.d.ts.map +1 -0
  284. package/dist/util/Util.js +138 -0
  285. package/dist/util/Util.js.map +1 -0
  286. package/dist/util/Vocabularies/Shared.d.ts +13 -0
  287. package/dist/util/Vocabularies/Shared.d.ts.map +1 -0
  288. package/dist/util/Vocabularies/Shared.js +96 -0
  289. package/dist/util/Vocabularies/Shared.js.map +1 -0
  290. package/dist/util/Vocabularies/helper.d.ts +5 -0
  291. package/dist/util/Vocabularies/helper.d.ts.map +1 -0
  292. package/dist/util/Vocabularies/helper.js +10 -0
  293. package/dist/util/Vocabularies/helper.js.map +1 -0
  294. package/dist/util/Vocabularies/index.d.ts +8 -0
  295. package/dist/util/Vocabularies/index.d.ts.map +1 -0
  296. package/dist/util/Vocabularies/index.js +114 -0
  297. package/dist/util/Vocabularies/index.js.map +1 -0
  298. package/dist/util/safeJsonStringify.d.ts +1 -0
  299. package/dist/util/safeJsonStringify.d.ts.map +1 -0
  300. package/dist/util/safeJsonStringify.js +19 -0
  301. package/dist/util/safeJsonStringify.js.map +1 -0
  302. package/package.json +1 -1
  303. package/src/SklEngine.ts +6 -0
  304. package/src/storage/query-adapter/sparql/SparqlUpdateBuilder.ts +106 -1
  305. package/src/util/TripleUtil.ts +19 -0
  306. package/src/util/Types.ts +6 -0
@@ -0,0 +1,1514 @@
1
+ "use strict";
2
+ /* eslint-disable no-div-regex */
3
+ /* eslint-disable line-comment-position */
4
+ var __importDefault = (this && this.__importDefault) || function (mod) {
5
+ return (mod && mod.__esModule) ? mod : { "default": mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.SKLEngine = void 0;
9
+ const openapi_operation_executor_1 = require("@comake/openapi-operation-executor");
10
+ const rmlmapper_js_1 = require("@comake/rmlmapper-js");
11
+ const axios_1 = __importDefault(require("axios"));
12
+ const jsonpath_plus_1 = require("jsonpath-plus");
13
+ const rdf_validate_shacl_1 = __importDefault(require("rdf-validate-shacl"));
14
+ const constants_1 = require("./constants");
15
+ const customCapabilities_1 = require("./customCapabilities");
16
+ const globalHooks_1 = require("./hooks/globalHooks");
17
+ const logger_1 = require("./logger");
18
+ const Mapper_1 = require("./mapping/Mapper");
19
+ const Exists_1 = require("./storage/operator/Exists");
20
+ const In_1 = require("./storage/operator/In");
21
+ const InversePath_1 = require("./storage/operator/InversePath");
22
+ const Not_1 = require("./storage/operator/Not");
23
+ const OneOrMorePath_1 = require("./storage/operator/OneOrMorePath");
24
+ const SequencePath_1 = require("./storage/operator/SequencePath");
25
+ const ZeroOrMorePath_1 = require("./storage/operator/ZeroOrMorePath");
26
+ const SparqlQueryAdapter_1 = require("./storage/query-adapter/sparql/SparqlQueryAdapter");
27
+ const PerformanceLogger_1 = require("./util/PerformanceLogger");
28
+ const ReadCacheHelper_1 = require("./util/ReadCacheHelper");
29
+ const Util_1 = require("./util/Util");
30
+ const Vocabularies_1 = require("./util/Vocabularies");
31
+ const DEFAULT_READ_CACHE_TTL_MS = 60000;
32
+ const READ_CACHE_ENVELOPE_MARKER = '__sklReadCacheEnvelopeV1';
33
+ class SKLEngine {
34
+ constructor(options) {
35
+ this.readCacheSingleflight = new ReadCacheHelper_1.ReadCacheSingleflight();
36
+ this.queryAdapter = new SparqlQueryAdapter_1.SparqlQueryAdapter(options);
37
+ this.disableValidation = options.disableValidation;
38
+ this.globalCallbacks = options.callbacks;
39
+ this.inputFiles = options.inputFiles;
40
+ this.skdsEndpointUrl = options.endpointUrl;
41
+ this.scriptPath = options.scriptPath;
42
+ this.readCache = options.readCache;
43
+ this.readCachePolicy = options.readCachePolicy;
44
+ this.readCacheNamespace = options.readCacheNamespace;
45
+ if (options.functions) {
46
+ this.functions = Object.fromEntries(Object.entries(options.functions).map(([key, func]) => [
47
+ key,
48
+ (data = {}) => {
49
+ // Add the SKL instance to the data object
50
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
51
+ data.skl = this;
52
+ // Call the original function
53
+ return func(data);
54
+ }
55
+ ]));
56
+ }
57
+ this.logger = logger_1.Logger.getInstance(options.debugMode);
58
+ // eslint-disable-next-line func-style
59
+ const getCapabilityHandler = (getTarget, property) => async (capabilityArgs, capabilityConfig) => this.executeCapabilityByName(property, capabilityArgs, capabilityConfig);
60
+ this.capability = new Proxy({}, { get: getCapabilityHandler });
61
+ }
62
+ setCodeExecutor(codeExecutor) {
63
+ this.codeExecutor = codeExecutor;
64
+ }
65
+ async executeRawQuery(query) {
66
+ return await this.queryAdapter.executeRawQuery(query);
67
+ }
68
+ async executeRawUpdate(query) {
69
+ return await this.queryAdapter.executeRawUpdate(query);
70
+ }
71
+ async executeRawConstructQuery(query, frame) {
72
+ return await this.queryAdapter.executeRawConstructQuery(query, frame);
73
+ }
74
+ cloneForReadCache(value) {
75
+ try {
76
+ return structuredClone(value);
77
+ }
78
+ catch {
79
+ return value;
80
+ }
81
+ }
82
+ wrapReadCacheValue(value) {
83
+ return {
84
+ [READ_CACHE_ENVELOPE_MARKER]: true,
85
+ value
86
+ };
87
+ }
88
+ isReadCacheEnvelope(value) {
89
+ if (!value || typeof value !== 'object') {
90
+ return false;
91
+ }
92
+ return value[READ_CACHE_ENVELOPE_MARKER] === true;
93
+ }
94
+ stripBypassCacheFromFindOneOptions(options) {
95
+ if (!options) {
96
+ return options;
97
+ }
98
+ const { bypassCache, ...rest } = options;
99
+ return rest;
100
+ }
101
+ stripBypassCacheFromFindAllOptions(options) {
102
+ if (!options) {
103
+ return options;
104
+ }
105
+ const { bypassCache, ...rest } = options;
106
+ return rest;
107
+ }
108
+ stripBypassCacheFromWhere(where) {
109
+ if (!where) {
110
+ return where;
111
+ }
112
+ const { bypassCache, ...rest } = where;
113
+ return rest;
114
+ }
115
+ async runReadWithCache(params) {
116
+ if (params.bypassCache) {
117
+ return await params.execute();
118
+ }
119
+ if (!this.readCache || !this.readCachePolicy) {
120
+ return await params.execute();
121
+ }
122
+ const policyDecision = this.readCachePolicy({
123
+ operation: params.operation,
124
+ args: params.args,
125
+ endpointUrl: this.skdsEndpointUrl,
126
+ namespace: this.readCacheNamespace
127
+ });
128
+ if (!policyDecision.cache) {
129
+ return await params.execute();
130
+ }
131
+ const ttlMs = policyDecision.ttlMs ?? DEFAULT_READ_CACHE_TTL_MS;
132
+ if (ttlMs <= 0) {
133
+ return await params.execute();
134
+ }
135
+ const cacheKey = (0, ReadCacheHelper_1.buildReadCacheKey)({
136
+ operation: params.operation,
137
+ args: params.args,
138
+ endpointUrl: this.skdsEndpointUrl,
139
+ namespace: this.readCacheNamespace,
140
+ keyHint: policyDecision.keyHint
141
+ });
142
+ return await this.readCacheSingleflight.do(cacheKey, async () => {
143
+ try {
144
+ const cached = await this.readCache?.get(cacheKey);
145
+ if (cached !== undefined) {
146
+ if (this.isReadCacheEnvelope(cached)) {
147
+ return this.cloneForReadCache(cached.value);
148
+ }
149
+ return this.cloneForReadCache(cached);
150
+ }
151
+ }
152
+ catch (error) {
153
+ this.logger.debug('Read cache lookup failed; continuing without cache', error);
154
+ }
155
+ const result = await params.execute();
156
+ try {
157
+ await this.readCache?.set(cacheKey, this.wrapReadCacheValue(this.cloneForReadCache(result)), ttlMs);
158
+ }
159
+ catch (error) {
160
+ this.logger.debug('Read cache write failed; continuing without cache', error);
161
+ }
162
+ return result;
163
+ });
164
+ }
165
+ async find(options) {
166
+ const bypassCache = options?.bypassCache;
167
+ const optionsWithoutBypass = this.stripBypassCacheFromFindOneOptions(options);
168
+ return PerformanceLogger_1.PerformanceLogger.withSpanRoot('SklEngine.find', async () => {
169
+ const context = {
170
+ entities: [],
171
+ operation: 'find',
172
+ operationParameters: { options: optionsWithoutBypass },
173
+ sklEngine: this
174
+ };
175
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.BEFORE, context);
176
+ try {
177
+ const entity = await this.runReadWithCache({
178
+ operation: 'find',
179
+ args: [optionsWithoutBypass],
180
+ bypassCache,
181
+ execute: async () => await this.queryAdapter.find(optionsWithoutBypass)
182
+ });
183
+ if (!entity) {
184
+ throw new Error(`No schema found with fields matching ${JSON.stringify(optionsWithoutBypass)}`);
185
+ }
186
+ const updatedContext = { ...context, entities: [entity] };
187
+ const afterHookResult = await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.AFTER, updatedContext, entity);
188
+ return afterHookResult || entity;
189
+ }
190
+ catch (error) {
191
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.ERROR, context, error);
192
+ throw error;
193
+ }
194
+ }, { options: optionsWithoutBypass });
195
+ }
196
+ async findBy(where, notFoundErrorMessage) {
197
+ const bypassCache = where?.bypassCache;
198
+ const whereWithoutBypass = this.stripBypassCacheFromWhere(where);
199
+ return PerformanceLogger_1.PerformanceLogger.withSpanRoot('SklEngine.findBy', async () => {
200
+ const context = {
201
+ entities: [],
202
+ operation: 'findBy',
203
+ operationParameters: { where: whereWithoutBypass },
204
+ sklEngine: this
205
+ };
206
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.BEFORE, context);
207
+ try {
208
+ const entity = await this.runReadWithCache({
209
+ operation: 'findBy',
210
+ args: [whereWithoutBypass, notFoundErrorMessage],
211
+ bypassCache,
212
+ execute: async () => await this.queryAdapter.findBy(whereWithoutBypass)
213
+ });
214
+ if (entity) {
215
+ const updatedContext = { ...context, entities: [entity] };
216
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.AFTER, updatedContext, entity);
217
+ return entity;
218
+ }
219
+ throw new Error(notFoundErrorMessage ?? `No schema found with fields matching ${JSON.stringify(whereWithoutBypass)}`);
220
+ }
221
+ catch (error) {
222
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.ERROR, context, error);
223
+ throw error;
224
+ }
225
+ }, { where: whereWithoutBypass });
226
+ }
227
+ async findByIfExists(options) {
228
+ try {
229
+ const entity = await this.findBy(options);
230
+ return entity;
231
+ }
232
+ catch {
233
+ return undefined;
234
+ }
235
+ }
236
+ async findAll(options) {
237
+ const bypassCache = options?.bypassCache;
238
+ const optionsWithoutBypass = this.stripBypassCacheFromFindAllOptions(options);
239
+ return PerformanceLogger_1.PerformanceLogger.withSpanRoot('SklEngine.findAll', async () => {
240
+ const context = {
241
+ entities: [],
242
+ operation: 'findAll',
243
+ operationParameters: { options: optionsWithoutBypass },
244
+ sklEngine: this
245
+ };
246
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.BEFORE, context);
247
+ try {
248
+ const entities = await this.runReadWithCache({
249
+ operation: 'findAll',
250
+ args: [optionsWithoutBypass],
251
+ bypassCache,
252
+ execute: async () => await this.queryAdapter.findAll(optionsWithoutBypass)
253
+ });
254
+ const updatedContext = { ...context, entities };
255
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.AFTER, updatedContext, entities);
256
+ return entities;
257
+ }
258
+ catch (error) {
259
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.ERROR, context, error);
260
+ throw error;
261
+ }
262
+ }, { options: optionsWithoutBypass });
263
+ }
264
+ async groupBy(options) {
265
+ return PerformanceLogger_1.PerformanceLogger.withSpanRoot('SklEngine.groupBy', async () => {
266
+ const context = {
267
+ entities: [],
268
+ operation: 'groupBy',
269
+ operationParameters: { options },
270
+ sklEngine: this
271
+ };
272
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.BEFORE, context);
273
+ try {
274
+ const result = await this.queryAdapter.groupBy(options);
275
+ const updatedContext = { ...context, result };
276
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.AFTER, updatedContext, result);
277
+ return result;
278
+ }
279
+ catch (error) {
280
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.ERROR, context, error);
281
+ throw error;
282
+ }
283
+ }, { options });
284
+ }
285
+ async findAllBy(where) {
286
+ return PerformanceLogger_1.PerformanceLogger.withSpanRoot('SklEngine.findAllBy', async () => {
287
+ const context = {
288
+ entities: [],
289
+ operation: 'findAllBy',
290
+ operationParameters: { where },
291
+ sklEngine: this
292
+ };
293
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.BEFORE, context);
294
+ try {
295
+ const entities = await this.queryAdapter.findAllBy(where);
296
+ const updatedContext = { ...context, entities };
297
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.AFTER, updatedContext, entities);
298
+ return entities;
299
+ }
300
+ catch (error) {
301
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.READ, globalHooks_1.HookStages.ERROR, context, error);
302
+ throw error;
303
+ }
304
+ }, { where });
305
+ }
306
+ async exists(options) {
307
+ return PerformanceLogger_1.PerformanceLogger.withSpanRoot('SklEngine.exists', async () => this.queryAdapter.exists(options), { options });
308
+ }
309
+ async count(options) {
310
+ const bypassCache = options?.bypassCache;
311
+ const optionsWithoutBypass = this.stripBypassCacheFromFindAllOptions(options);
312
+ return PerformanceLogger_1.PerformanceLogger.withSpanRoot('SklEngine.count', async () => await this.runReadWithCache({
313
+ operation: 'count',
314
+ args: [optionsWithoutBypass],
315
+ bypassCache,
316
+ execute: async () => await this.queryAdapter.count(optionsWithoutBypass)
317
+ }), { options: optionsWithoutBypass });
318
+ }
319
+ async save(entityOrEntities, options) {
320
+ return PerformanceLogger_1.PerformanceLogger.withSpanRoot('SklEngine.save', async () => {
321
+ const entityArray = Array.isArray(entityOrEntities) ? entityOrEntities : [entityOrEntities];
322
+ const isSingleEntity = !Array.isArray(entityOrEntities);
323
+ await globalHooks_1.globalHooks.executeBeforeCreate(entityArray, { sklEngine: this, bypassHooks: options?.bypassHooks });
324
+ try {
325
+ await this.validateEntitiesConformToObjectSchema(entityArray);
326
+ const savedEntities = await this.queryAdapter.save(entityArray);
327
+ await globalHooks_1.globalHooks.executeAfterCreate(savedEntities, { sklEngine: this, bypassHooks: options?.bypassHooks });
328
+ return isSingleEntity ? savedEntities[0] : savedEntities;
329
+ }
330
+ catch (error) {
331
+ await globalHooks_1.globalHooks.executeErrorCreate(entityArray, error, { sklEngine: this, bypassHooks: options?.bypassHooks });
332
+ throw error;
333
+ }
334
+ }, { entityCount: Array.isArray(entityOrEntities) ? entityOrEntities.length : 1 });
335
+ }
336
+ async update(idOrIds, attributes, options) {
337
+ return PerformanceLogger_1.PerformanceLogger.withSpanRoot('SklEngine.update', async () => {
338
+ const idArray = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
339
+ const isSingleEntity = !Array.isArray(idOrIds);
340
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.UPDATE, globalHooks_1.HookStages.BEFORE, {
341
+ entities: [],
342
+ operation: 'update',
343
+ operationParameters: { idArray, attributes },
344
+ sklEngine: this,
345
+ bypassHooks: options?.bypassHooks
346
+ });
347
+ try {
348
+ if (idArray.length > 1) {
349
+ await this.validateEntitiesWithIdsConformsToObjectSchemaForAttributes(idArray, attributes);
350
+ }
351
+ else {
352
+ await this.validateEntityWithIdConformsToObjectSchemaForAttributes(idArray[0], attributes);
353
+ }
354
+ await this.queryAdapter.update(isSingleEntity ? idArray[0] : idArray, attributes);
355
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.UPDATE, globalHooks_1.HookStages.AFTER, {
356
+ entities: [],
357
+ operation: 'update',
358
+ operationParameters: { idArray, attributes },
359
+ sklEngine: this,
360
+ bypassHooks: options?.bypassHooks
361
+ });
362
+ }
363
+ catch (error) {
364
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.UPDATE, globalHooks_1.HookStages.ERROR, {
365
+ entities: [],
366
+ operation: 'update',
367
+ operationParameters: { idArray, attributes },
368
+ sklEngine: this,
369
+ bypassHooks: options?.bypassHooks
370
+ }, error);
371
+ throw error;
372
+ }
373
+ }, { idCount: Array.isArray(idOrIds) ? idOrIds.length : 1 });
374
+ }
375
+ async validateEntitiesConformToObjectSchema(entities) {
376
+ const entitiesByType = this.groupEntitiesByType(entities);
377
+ for (const type of Object.keys(entitiesByType)) {
378
+ const object = await this.findByIfExists({ id: type });
379
+ if (object) {
380
+ const parentObjects = await this.getSuperClassesOfObject(type);
381
+ for (const currentObject of [object, ...parentObjects]) {
382
+ const entitiesOfType = entitiesByType[type];
383
+ const nounSchemaWithTarget = {
384
+ ...currentObject,
385
+ [constants_1.SHACL.targetNode]: entitiesOfType.map((entity) => ({ [constants_1.PROP_ENTITY_ID]: entity[constants_1.PROP_ENTITY_ID] }))
386
+ };
387
+ const report = await this.convertToQuadsAndValidateAgainstShape(entitiesOfType, nounSchemaWithTarget);
388
+ if (!report.conforms) {
389
+ const entityIds = entitiesOfType.map((entity) => entity[constants_1.PROP_ENTITY_ID]);
390
+ this.throwValidationReportError(report, `Entity ${entityIds.join(', ')} does not conform to the ${currentObject[constants_1.PROP_ENTITY_ID]} schema.`);
391
+ }
392
+ }
393
+ }
394
+ }
395
+ }
396
+ groupEntitiesByType(entities) {
397
+ return entities.reduce((groupedEntities, entity) => {
398
+ const entityTypes = Array.isArray(entity[constants_1.PROP_ENTITY_TYPE])
399
+ ? entity[constants_1.PROP_ENTITY_TYPE]
400
+ : [entity[constants_1.PROP_ENTITY_TYPE]];
401
+ for (const type of entityTypes) {
402
+ if (!groupedEntities[type]) {
403
+ groupedEntities[type] = [];
404
+ }
405
+ groupedEntities[type].push(entity);
406
+ }
407
+ return groupedEntities;
408
+ }, {});
409
+ }
410
+ async getSuperClassesOfObject(object) {
411
+ return await this.getParentsOfSelector(object);
412
+ }
413
+ async getSuperClassesOfObjects(nouns) {
414
+ return await this.getParentsOfSelector((0, In_1.In)(nouns));
415
+ }
416
+ async getParentsOfSelector(selector) {
417
+ return await this.findAll({
418
+ where: {
419
+ id: (0, InversePath_1.InversePath)({
420
+ subPath: (0, OneOrMorePath_1.OneOrMorePath)({ subPath: constants_1.RDFS.subClassOf }),
421
+ value: selector
422
+ })
423
+ }
424
+ });
425
+ }
426
+ async validateEntityConformsToObjectSchema(entity) {
427
+ const nounIds = Array.isArray(entity[constants_1.PROP_ENTITY_TYPE]) ? entity[constants_1.PROP_ENTITY_TYPE] : [entity[constants_1.PROP_ENTITY_TYPE]];
428
+ const directObjects = await this.findAllBy({ id: (0, In_1.In)(nounIds) });
429
+ if (directObjects.length > 0) {
430
+ const existingObjectIds = directObjects.map((object) => object[constants_1.PROP_ENTITY_ID]);
431
+ const parentObjects = await this.getSuperClassesOfObjects(existingObjectIds);
432
+ for (const currentObject of [...directObjects, ...parentObjects]) {
433
+ const nounSchemaWithTarget = {
434
+ ...currentObject,
435
+ [constants_1.SHACL.targetNode]: { [constants_1.PROP_ENTITY_ID]: entity[constants_1.PROP_ENTITY_ID] }
436
+ };
437
+ const report = await this.convertToQuadsAndValidateAgainstShape(entity, nounSchemaWithTarget);
438
+ if (!report.conforms) {
439
+ this.throwValidationReportError(report, `Entity ${entity[constants_1.PROP_ENTITY_ID]} does not conform to the ${currentObject[constants_1.PROP_ENTITY_ID]} schema.`);
440
+ }
441
+ }
442
+ }
443
+ }
444
+ async validateEntitiesWithIdsConformsToObjectSchemaForAttributes(ids, attributes) {
445
+ for (const id of ids) {
446
+ await this.validateEntityWithIdConformsToObjectSchemaForAttributes(id, attributes);
447
+ }
448
+ }
449
+ async getObjectsAndParentObjectsOfEntity(id) {
450
+ return await this.findAllBy({
451
+ id: (0, InversePath_1.InversePath)({
452
+ subPath: (0, SequencePath_1.SequencePath)({
453
+ subPath: [constants_1.RDF.type, (0, ZeroOrMorePath_1.ZeroOrMorePath)({ subPath: constants_1.RDFS.subClassOf })]
454
+ }),
455
+ value: id
456
+ })
457
+ });
458
+ }
459
+ async validateEntityWithIdConformsToObjectSchemaForAttributes(id, attributes) {
460
+ const nouns = await this.getObjectsAndParentObjectsOfEntity(id);
461
+ for (const currentObject of nouns) {
462
+ if (constants_1.SHACL.property in currentObject) {
463
+ const nounProperties = (0, Util_1.ensureArray)(currentObject[constants_1.SHACL.property]).filter((property) => {
464
+ const path = property[constants_1.SHACL.path];
465
+ if (typeof path === 'string' && path in attributes) {
466
+ return true;
467
+ }
468
+ if (typeof path === 'object' && constants_1.PROP_ENTITY_ID in path && path[constants_1.PROP_ENTITY_ID] in attributes) {
469
+ return true;
470
+ }
471
+ return false;
472
+ });
473
+ if (nounProperties.length > 0) {
474
+ const nounSchemaWithTarget = {
475
+ [constants_1.PROP_ENTITY_TYPE]: constants_1.SHACL.NodeShape,
476
+ [constants_1.SHACL.targetNode]: { [constants_1.PROP_ENTITY_ID]: id },
477
+ [constants_1.SHACL.property]: nounProperties
478
+ };
479
+ const attributesWithId = { ...attributes, [constants_1.PROP_ENTITY_ID]: id };
480
+ const report = await this.convertToQuadsAndValidateAgainstShape(attributesWithId, nounSchemaWithTarget);
481
+ if (!report.conforms) {
482
+ this.throwValidationReportError(report, `Entity ${id} does not conform to the ${currentObject[constants_1.PROP_ENTITY_ID]} schema.`);
483
+ }
484
+ }
485
+ }
486
+ }
487
+ }
488
+ async delete(idOrIds, options) {
489
+ return PerformanceLogger_1.PerformanceLogger.withSpanRoot('SklEngine.delete', async () => {
490
+ const idArray = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
491
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.DELETE, globalHooks_1.HookStages.BEFORE, {
492
+ entities: [],
493
+ operation: 'delete',
494
+ operationParameters: { idArray },
495
+ sklEngine: this,
496
+ bypassHooks: options?.bypassHooks
497
+ });
498
+ try {
499
+ await this.queryAdapter.delete(idArray);
500
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.DELETE, globalHooks_1.HookStages.AFTER, {
501
+ entities: [],
502
+ operation: 'delete',
503
+ operationParameters: { idArray },
504
+ sklEngine: this,
505
+ bypassHooks: options?.bypassHooks
506
+ });
507
+ }
508
+ catch (error) {
509
+ await globalHooks_1.globalHooks.execute(globalHooks_1.HookTypes.DELETE, globalHooks_1.HookStages.ERROR, {
510
+ entities: [],
511
+ operation: 'delete',
512
+ operationParameters: { idArray },
513
+ sklEngine: this,
514
+ bypassHooks: options?.bypassHooks
515
+ }, error);
516
+ throw error;
517
+ }
518
+ }, { idCount: Array.isArray(idOrIds) ? idOrIds.length : 1 });
519
+ }
520
+ async destroy(entityOrEntities) {
521
+ if (Array.isArray(entityOrEntities)) {
522
+ return await this.queryAdapter.destroy(entityOrEntities);
523
+ }
524
+ return await this.queryAdapter.destroy(entityOrEntities);
525
+ }
526
+ async destroyAll() {
527
+ return await this.queryAdapter.destroyAll();
528
+ }
529
+ async performMapping(args, mapping, frame, capabilityConfig, jsExecutionOptions) {
530
+ const mappingArray = (0, Util_1.ensureArray)(mapping);
531
+ const codeBlocks = mappingArray.filter((mappingItem) => mappingItem[constants_1.PROP_ENTITY_TYPE] === constants_1.EngineConstants.spec.codeBlock &&
532
+ this.isJavaScriptCode((0, Util_1.getValueIfDefined)(mappingItem[constants_1.EngineConstants.prop.codeBody])));
533
+ // FIXME: Handle if we can combine the codeb blocks with triples map.
534
+ // As of now if there is any code block, triples map does not get executed.
535
+ if (codeBlocks.length > 0) {
536
+ return await this.executeCodeBlocks(codeBlocks, args, jsExecutionOptions ?? {});
537
+ }
538
+ const functions = {
539
+ ...this.functions,
540
+ ...capabilityConfig?.functions
541
+ };
542
+ const mapper = new Mapper_1.Mapper({ functions });
543
+ return await mapper.apply(args, mapping, frame ?? {});
544
+ }
545
+ async executeTrigger(integration, payload) {
546
+ const triggerToCapabilityMapping = await this.findTriggerCapabilityMapping(integration);
547
+ const capabilityArgs = await this.performParameterMappingOnArgsIfDefined(payload, triggerToCapabilityMapping);
548
+ const capabilityId = await this.performCapabilityMappingWithArgs(payload, triggerToCapabilityMapping);
549
+ if (capabilityId) {
550
+ const mappedCapability = (await this.findBy({ id: capabilityId }));
551
+ await this.executeCapability(mappedCapability, capabilityArgs);
552
+ }
553
+ }
554
+ async findTriggerCapabilityMapping(integration) {
555
+ const triggerCapabilityMappingNew = (await this.findBy({
556
+ type: constants_1.EngineConstants.spec.capabilityMapping,
557
+ [constants_1.EngineConstants.prop.capability]: integration,
558
+ [constants_1.EngineConstants.prop.capabilityType]: constants_1.EngineConstants.spec.triggerCapabilityMapping
559
+ }, `Failed to find a Trigger Capability mapping for integration ${integration}`));
560
+ if (triggerCapabilityMappingNew) {
561
+ return triggerCapabilityMappingNew;
562
+ }
563
+ throw new Error(`Failed to find a Trigger Capability mapping for integration ${integration}`);
564
+ }
565
+ async executeCapabilityByName(capabilityName, capabilityArgs, capabilityConfig) {
566
+ const capability = await this.findCapabilityWithName(capabilityName);
567
+ return await this.executeCapability(capability, capabilityArgs, capabilityConfig);
568
+ }
569
+ async findCapabilityWithName(capabilityName) {
570
+ return (await this.findBy({ type: constants_1.EngineConstants.spec.capability, [constants_1.EngineConstants.prop.label]: capabilityName }, `Failed to find the capability ${capabilityName} in the schema.`));
571
+ }
572
+ async executeCapability(capability, capabilityArgs, capabilityConfig) {
573
+ this.globalCallbacks?.onCapabilityStart?.(capability[constants_1.PROP_ENTITY_ID], capabilityArgs);
574
+ if (capabilityConfig?.callbacks?.onCapabilityStart) {
575
+ this.logger.debug('Capability arguments', capabilityArgs);
576
+ capabilityConfig.callbacks.onCapabilityStart(capability[constants_1.PROP_ENTITY_ID], capabilityArgs);
577
+ }
578
+ const { mapping, account } = await this.findMappingForCapabilityContextually(capability[constants_1.PROP_ENTITY_ID], capabilityArgs);
579
+ this.logger.debug('Mapping', JSON.stringify(mapping));
580
+ const shouldValidate = this.shouldValidate(capabilityConfig);
581
+ if (shouldValidate) {
582
+ await this.assertCapabilityParamsMatchParameterSchemas(capabilityArgs, capability);
583
+ }
584
+ try {
585
+ // Execute capability mapping before hook if appropriate -
586
+ // works for any mapping that can be used as a verb mapping
587
+ if (mapping) {
588
+ await globalHooks_1.globalHooks.executeBeforeExecuteCapabilityMapping([capabilityArgs], mapping, { sklEngine: this });
589
+ }
590
+ const verbReturnValue = await this.executeMapping(mapping, capabilityArgs, capabilityConfig, account);
591
+ if (shouldValidate) {
592
+ await this.assertCapabilityReturnValueMatchesReturnTypeSchema(verbReturnValue, capability);
593
+ }
594
+ // Execute capability mapping after hook if appropriate
595
+ if (mapping) {
596
+ await globalHooks_1.globalHooks.executeAfterExecuteCapabilityMapping([capabilityArgs], mapping, verbReturnValue, { sklEngine: this });
597
+ }
598
+ this.globalCallbacks?.onCapabilityEnd?.(capability[constants_1.PROP_ENTITY_ID], verbReturnValue);
599
+ if (capabilityConfig?.callbacks?.onCapabilityEnd) {
600
+ capabilityConfig.callbacks.onCapabilityEnd(capability[constants_1.PROP_ENTITY_ID], verbReturnValue);
601
+ }
602
+ return verbReturnValue;
603
+ }
604
+ catch (error) {
605
+ // Execute capability mapping error hook if appropriate
606
+ if (mapping) {
607
+ await globalHooks_1.globalHooks.executeErrorExecuteCapabilityMapping([capabilityArgs], mapping, error, { sklEngine: this });
608
+ }
609
+ throw error;
610
+ }
611
+ }
612
+ async findMappingForCapabilityContextually(capabilityId, args) {
613
+ if (args.mapping) {
614
+ const mapping = await this.findByIfExists({ id: args.mapping });
615
+ if (!mapping) {
616
+ throw new Error(`Mapping ${args.mapping} not found.`);
617
+ }
618
+ return { mapping: mapping };
619
+ }
620
+ if (args.object) {
621
+ const mapping = await this.findCapabilityObjectMapping(capabilityId, args.object);
622
+ if (mapping) {
623
+ return { mapping };
624
+ }
625
+ }
626
+ if (args.account) {
627
+ const account = await this.findBy({ id: args.account });
628
+ const integratedProductId = account[constants_1.EngineConstants.prop.integration][constants_1.PROP_ENTITY_ID];
629
+ const mapping = await this.findCapabilityIntegrationMapping(capabilityId, integratedProductId);
630
+ if (mapping) {
631
+ return { mapping, account };
632
+ }
633
+ }
634
+ const mappings = await this.findAllBy({
635
+ type: constants_1.EngineConstants.spec.capabilityMapping,
636
+ [constants_1.EngineConstants.prop.capability]: capabilityId,
637
+ [constants_1.EngineConstants.prop.integration]: (0, Not_1.Not)((0, Exists_1.Exists)()),
638
+ [constants_1.EngineConstants.prop.object]: (0, Not_1.Not)((0, Exists_1.Exists)())
639
+ });
640
+ if (mappings.length === 1) {
641
+ return { mapping: mappings[0] };
642
+ }
643
+ if (mappings.length > 1) {
644
+ throw new Error('Multiple mappings found for capability, please specify one.');
645
+ }
646
+ if (args.object) {
647
+ throw new Error(`Mapping between object ${args.object} and capability ${capabilityId} not found.`);
648
+ }
649
+ if (args.account) {
650
+ throw new Error(`Mapping between account ${args.account} and capability ${capabilityId} not found.`);
651
+ }
652
+ throw new Error(`No mapping found.`);
653
+ }
654
+ async executeMapping(mapping, args, capabilityConfig, account) {
655
+ args = await this.addPreProcessingMappingToArgs(mapping, args, capabilityConfig);
656
+ let returnValue;
657
+ // If (EngineConstants.prop.capability in mapping || EngineConstants.prop.capabilityMapping in mapping) {
658
+ // const capabilityId = await this.performCapabilityMappingWithArgs(args, mapping, capabilityConfig);
659
+ // const mappedArgs = await this.performParameterMappingOnArgsIfDefined(
660
+ // { ...args, capabilityId },
661
+ // mapping as MappingWithInputs,
662
+ // capabilityConfig
663
+ // );
664
+ // Logger.getInstance().log('Mapped args', mappedArgs);
665
+ // returnValue = await this.executeCapabilityMapping(mapping, args, mappedArgs, capabilityConfig);
666
+ // } else {
667
+ const mappedArgs = await this.performParameterMappingOnArgsIfDefined(args, mapping, capabilityConfig);
668
+ this.logger.debug('Mapped args', mappedArgs);
669
+ if (constants_1.EngineConstants.prop.operationId in mapping || constants_1.EngineConstants.prop.operationMapping in mapping) {
670
+ returnValue = (await this.executeOperationMapping(mapping, mappedArgs, args, account, capabilityConfig));
671
+ }
672
+ else if (constants_1.EngineConstants.prop.series in mapping) {
673
+ returnValue = await this.executeSeriesMapping(mapping, mappedArgs, capabilityConfig);
674
+ }
675
+ else if (constants_1.EngineConstants.prop.parallel in mapping) {
676
+ returnValue = await this.executeParallelMapping(mapping, mappedArgs, capabilityConfig);
677
+ }
678
+ else {
679
+ returnValue = mappedArgs;
680
+ }
681
+ // }
682
+ return await this.performReturnValueMappingWithFrameIfDefined(returnValue, mapping, capabilityConfig);
683
+ }
684
+ shouldValidate(capabilityConfig) {
685
+ return capabilityConfig?.disableValidation === undefined
686
+ ? this.disableValidation !== true
687
+ : !capabilityConfig.disableValidation;
688
+ }
689
+ async executeOperationMapping(mapping, mappedArgs, originalArgs, account, capabilityConfig) {
690
+ const integration = mapping[constants_1.EngineConstants.prop.integration]?.[constants_1.PROP_ENTITY_ID];
691
+ // If the mapping has an integration, it means that the operation is an integration operation
692
+ if (integration) {
693
+ const operationInfo = await this.performOperationMappingWithArgs(originalArgs, mapping, capabilityConfig);
694
+ const response = await this.performOperation(operationInfo, mappedArgs, originalArgs, account, capabilityConfig);
695
+ if (!this.ifCapabilityStreaming(capabilityConfig)) {
696
+ this.logger.debug('Original response', JSON.stringify(response));
697
+ }
698
+ return response;
699
+ }
700
+ // If the mapping does not have an integration, it means that the operation is a capability operation
701
+ return await this.executeCapabilityMapping(mapping, originalArgs, mappedArgs, capabilityConfig);
702
+ }
703
+ async executeSeriesMapping(mapping, args, capabilityConfig) {
704
+ const seriesCapabilityMappingsList = this.rdfListToArray(mapping[constants_1.EngineConstants.prop.series]);
705
+ const seriesCapabilityArgs = {
706
+ originalCapabilityParameters: args,
707
+ previousCapabilityReturnValue: {},
708
+ allStepsResults: []
709
+ };
710
+ return await this.executeSeriesFromList(seriesCapabilityMappingsList, seriesCapabilityArgs, capabilityConfig);
711
+ }
712
+ rdfListToArray(list) {
713
+ if (!(constants_1.RML_LIST in list)) {
714
+ return [
715
+ list[constants_1.RDF.first],
716
+ ...(0, rmlmapper_js_1.getIdFromNodeObjectIfDefined)(list[constants_1.RDF.rest]) === constants_1.RDF.nil
717
+ ? []
718
+ : this.rdfListToArray(list[constants_1.RDF.rest])
719
+ ];
720
+ }
721
+ return list[constants_1.RML_LIST];
722
+ }
723
+ async executeSeriesFromList(list, args, capabilityConfig) {
724
+ const nextCapabilityMapping = list[0];
725
+ const returnValue = await this.executeMapping(nextCapabilityMapping, args, capabilityConfig);
726
+ if (list.length > 1) {
727
+ return await this.executeSeriesFromList(list.slice(1), {
728
+ ...args,
729
+ previousCapabilityReturnValue: returnValue,
730
+ allStepsResults: [...args.allStepsResults ?? [], returnValue]
731
+ }, capabilityConfig);
732
+ }
733
+ return returnValue;
734
+ }
735
+ async executeCapabilityMapping(capabilityMapping, originalArgs, mappedArgs, capabilityConfig) {
736
+ const capabilityId = await this.performCapabilityMappingWithArgs(originalArgs, capabilityMapping, capabilityConfig);
737
+ if (capabilityId) {
738
+ if (capabilityId === constants_1.EngineConstants.dataSource.update) {
739
+ await this.updateEntityFromcapabilityArgs(mappedArgs);
740
+ return {};
741
+ }
742
+ if (capabilityId === constants_1.EngineConstants.dataSource.save) {
743
+ return await this.saveEntityOrEntitiesFromcapabilityArgs(mappedArgs);
744
+ }
745
+ if (capabilityId === constants_1.EngineConstants.dataSource.destroy) {
746
+ return await this.destroyEntityOrEntitiesFromcapabilityArgs(mappedArgs);
747
+ }
748
+ if (capabilityId === constants_1.EngineConstants.dataSource.findAll) {
749
+ return await this.findAll(mappedArgs);
750
+ }
751
+ if (capabilityId === constants_1.EngineConstants.dataSource.find) {
752
+ return await this.find(mappedArgs);
753
+ }
754
+ if (capabilityId === constants_1.EngineConstants.dataSource.count) {
755
+ return await this.countAndWrapValueFromcapabilityArgs(mappedArgs);
756
+ }
757
+ if (capabilityId === constants_1.EngineConstants.dataSource.exists) {
758
+ return await this.existsAndWrapValueFromcapabilityArgs(mappedArgs);
759
+ }
760
+ if (capabilityId === 'https://skl.ai/capability/execute-code') {
761
+ const codeBlocks = (0, Util_1.ensureArray)(capabilityMapping[constants_1.EngineConstants.prop.codeBlocks] ?? []).filter((mappingItem) => mappingItem[constants_1.PROP_ENTITY_TYPE] === constants_1.EngineConstants.spec.codeBlock &&
762
+ this.isJavaScriptCode((0, Util_1.getValueIfDefined)(mappingItem[constants_1.EngineConstants.prop.codeBody])));
763
+ return await this.executeCodeBlocks(codeBlocks, mappedArgs, {});
764
+ }
765
+ // Check for custom capabilities
766
+ if (customCapabilities_1.globalCustomCapabilities.has(capabilityId)) {
767
+ return await customCapabilities_1.globalCustomCapabilities.execute(capabilityId, mappedArgs, this, capabilityConfig);
768
+ }
769
+ return await this.findAndExecuteCapability(capabilityId, mappedArgs, capabilityConfig);
770
+ }
771
+ return {};
772
+ }
773
+ async addPreProcessingMappingToArgs(capabilityMapping, args, capabilityConfig) {
774
+ if (constants_1.EngineConstants.prop.preProcessingMapping in capabilityMapping) {
775
+ const preMappingArgs = await this.performMapping(args, capabilityMapping[constants_1.EngineConstants.prop.preProcessingMapping], (0, Util_1.getValueIfDefined)(capabilityMapping[constants_1.EngineConstants.prop.preProcessingMappingFrame]), capabilityConfig);
776
+ return { ...args, preProcessedParameters: preMappingArgs };
777
+ }
778
+ return args;
779
+ }
780
+ replaceTypeAndId(entity) {
781
+ if (typeof entity !== 'object') {
782
+ throw new Error('Entity is not an object');
783
+ }
784
+ const clonedEntity = structuredClone(entity);
785
+ if (clonedEntity[constants_1.EngineConstants.prop.type]) {
786
+ clonedEntity[constants_1.PROP_ENTITY_TYPE] = clonedEntity[constants_1.EngineConstants.prop.type];
787
+ }
788
+ if (clonedEntity[constants_1.EngineConstants.prop.identifier]) {
789
+ clonedEntity[constants_1.PROP_ENTITY_ID] = Vocabularies_1.SKL_DATA_NAMESPACE + clonedEntity[constants_1.EngineConstants.prop.identifier];
790
+ }
791
+ return clonedEntity;
792
+ }
793
+ async updateEntityFromcapabilityArgs(args) {
794
+ let ids = args.id ?? args.ids;
795
+ if (!Array.isArray(ids)) {
796
+ ids = [ids];
797
+ }
798
+ // FIX: Temporary fix for the issue where the id always getting prefixed with the namespace
799
+ ids = ids.map((id) => (id.startsWith('http') ? id : `${Vocabularies_1.SKL_DATA_NAMESPACE}${id}`));
800
+ await this.update(ids, args.attributes);
801
+ }
802
+ async saveEntityOrEntitiesFromcapabilityArgs(args) {
803
+ if (args.entity && typeof args.entity === 'object') {
804
+ args.entity = this.replaceTypeAndId(args.entity);
805
+ }
806
+ if (args.entities && Array.isArray(args.entities)) {
807
+ args.entities = args.entities.map(this.replaceTypeAndId);
808
+ }
809
+ return await this.save(args.entity ?? args.entities);
810
+ }
811
+ async destroyEntityOrEntitiesFromcapabilityArgs(args) {
812
+ if (args.entity && typeof args.entity === 'object') {
813
+ args.entity = this.replaceTypeAndId(args.entity);
814
+ }
815
+ if (args.entities && Array.isArray(args.entities)) {
816
+ args.entities = args.entities.map(this.replaceTypeAndId);
817
+ }
818
+ return await this.destroy(args.entity ?? args.entities);
819
+ }
820
+ async countAndWrapValueFromcapabilityArgs(args) {
821
+ const count = await this.count(args);
822
+ return {
823
+ [constants_1.EngineConstants.dataSource.countResult]: {
824
+ [constants_1.PROP_ENTITY_VALUE]: count,
825
+ [constants_1.PROP_ENTITY_TYPE]: rmlmapper_js_1.XSD.integer
826
+ }
827
+ };
828
+ }
829
+ async existsAndWrapValueFromcapabilityArgs(args) {
830
+ const exists = await this.exists(args);
831
+ return {
832
+ [constants_1.EngineConstants.dataSource.existsResult]: {
833
+ [constants_1.PROP_ENTITY_VALUE]: exists,
834
+ [constants_1.PROP_ENTITY_TYPE]: rmlmapper_js_1.XSD.boolean
835
+ }
836
+ };
837
+ }
838
+ async findAndExecuteCapability(capabilityId, args, capabilityConfig) {
839
+ const capability = (await this.findBy({ id: capabilityId }));
840
+ return await this.executeCapability(capability, args, capabilityConfig);
841
+ }
842
+ async executeParallelMapping(mapping, args, capabilityConfig) {
843
+ const parallelCapabilityMappings = (0, Util_1.ensureArray)(mapping[constants_1.EngineConstants.prop.parallel]);
844
+ const nestedReturnValues = await Promise.all(parallelCapabilityMappings.map((capabilityMapping) => this.executeMapping(capabilityMapping, args, capabilityConfig)));
845
+ return nestedReturnValues.flat();
846
+ }
847
+ async findCapabilityIntegrationMapping(capabilityId, integratedProductId) {
848
+ return (await this.findByIfExists({
849
+ type: constants_1.EngineConstants.spec.capabilityMapping,
850
+ [constants_1.EngineConstants.prop.capability]: capabilityId,
851
+ [constants_1.EngineConstants.prop.integration]: integratedProductId
852
+ }));
853
+ }
854
+ async performOperationMappingWithArgs(args, mapping, capabilityConfig) {
855
+ if (mapping[constants_1.EngineConstants.prop.operationId]) {
856
+ return { [constants_1.EngineConstants.prop.operationId]: mapping[constants_1.EngineConstants.prop.operationId] };
857
+ }
858
+ if (mapping[constants_1.EngineConstants.prop.dataSource]) {
859
+ return { [constants_1.EngineConstants.prop.dataSource]: mapping[constants_1.EngineConstants.prop.dataSource] };
860
+ }
861
+ return await this.performMapping(args, mapping[constants_1.EngineConstants.prop.operationMapping], undefined, capabilityConfig);
862
+ }
863
+ async performOperation(operationInfo, operationArgs, originalArgs, account, capabilityConfig, securityCredentials) {
864
+ if (operationInfo[constants_1.EngineConstants.prop.schemeName]) {
865
+ return await this.performOauthSecuritySchemeStageWithCredentials(operationInfo, operationArgs, account, securityCredentials);
866
+ }
867
+ if (operationInfo[constants_1.EngineConstants.prop.dataSource]) {
868
+ return await this.getDataFromDataSource((0, rmlmapper_js_1.getIdFromNodeObjectIfDefined)(operationInfo[constants_1.EngineConstants.prop.dataSource]), capabilityConfig);
869
+ }
870
+ if (operationInfo[constants_1.EngineConstants.prop.operationId]) {
871
+ const response = await this.performOpenapiOperationWithCredentials((0, Util_1.getValueIfDefined)(operationInfo[constants_1.EngineConstants.prop.operationId]), operationArgs, account, capabilityConfig);
872
+ return this.axiosResponseAndParamsToOperationResponse(response, operationArgs, originalArgs);
873
+ }
874
+ throw new Error('Operation not supported.');
875
+ }
876
+ axiosResponseAndParamsToOperationResponse(response, operationParameters, originalArgs) {
877
+ return {
878
+ operationParameters,
879
+ originalCapabilityParameters: originalArgs,
880
+ data: response.data,
881
+ status: response.status,
882
+ statusText: response.statusText,
883
+ headers: response.headers,
884
+ config: {
885
+ headers: response.config.headers,
886
+ method: response.config.method,
887
+ url: response.config.url,
888
+ data: response.config.data
889
+ }
890
+ };
891
+ }
892
+ async performReturnValueMappingWithFrameIfDefined(returnValue, mapping, capabilityConfig) {
893
+ if (constants_1.EngineConstants.prop.outputsMapping in mapping) {
894
+ return await this.performMapping(returnValue, mapping[constants_1.EngineConstants.prop.outputsMapping], (0, Util_1.getValueIfDefined)(mapping[constants_1.EngineConstants.prop.outputsMappingFrame]), capabilityConfig);
895
+ }
896
+ return returnValue;
897
+ }
898
+ async performParameterMappingOnArgsIfDefined(args, mapping, capabilityConfig, convertToJsonDeep = false) {
899
+ if (constants_1.EngineConstants.prop.inputsReference in mapping) {
900
+ const reference = (0, Util_1.getValueIfDefined)(mapping[constants_1.EngineConstants.prop.inputsReference]);
901
+ return this.getDataAtReference(reference, args);
902
+ }
903
+ if (constants_1.EngineConstants.prop.inputsMappingRef in mapping) {
904
+ const reference = (0, Util_1.getValueIfDefined)(mapping[constants_1.EngineConstants.prop.inputsMappingRef]);
905
+ const referencedMapping = this.getDataAtReference(reference, args);
906
+ if (!referencedMapping || referencedMapping?.length === 0) {
907
+ return args;
908
+ }
909
+ // Handle inputsMappingFrameRef if present
910
+ let frame;
911
+ if (constants_1.EngineConstants.prop.inputsMappingFrameRef in mapping) {
912
+ const frameReference = (0, Util_1.getValueIfDefined)(mapping[constants_1.EngineConstants.prop.inputsMappingFrameRef]);
913
+ frame = this.getDataAtReference(frameReference, args);
914
+ }
915
+ else {
916
+ // Use direct frame if provided
917
+ frame = (0, Util_1.getValueIfDefined)(mapping[constants_1.EngineConstants.prop.inputsMappingFrame]);
918
+ }
919
+ // Perform mapping with the referenced mapping and frame
920
+ const mappedData = await this.performMapping(args, referencedMapping, frame, capabilityConfig);
921
+ return (0, Util_1.toJSON)(mappedData, convertToJsonDeep);
922
+ }
923
+ if (constants_1.EngineConstants.prop.inputsMapping in mapping) {
924
+ const mappedData = await this.performMapping(args, mapping[constants_1.EngineConstants.prop.inputsMapping], (0, Util_1.getValueIfDefined)(mapping[constants_1.EngineConstants.prop.inputsMappingFrame]), capabilityConfig);
925
+ return (0, Util_1.toJSON)(mappedData, convertToJsonDeep);
926
+ }
927
+ return args;
928
+ }
929
+ getDataAtReference(reference, data) {
930
+ const results = (0, jsonpath_plus_1.JSONPath)({
931
+ path: reference,
932
+ json: data,
933
+ resultType: 'value'
934
+ });
935
+ const isArrayOfLengthOne = Array.isArray(results) && results.length === 1;
936
+ let result = isArrayOfLengthOne ? results[0] : results;
937
+ if (result && typeof result === 'object' && constants_1.PROP_ENTITY_VALUE in result) {
938
+ result = result[constants_1.PROP_ENTITY_VALUE];
939
+ }
940
+ return result;
941
+ }
942
+ async getIntegrationInterface(integratedProductId, integrationType = constants_1.EngineConstants.spec.integrationInterface) {
943
+ if (integrationType === constants_1.EngineConstants.spec.integrationInterface) {
944
+ const integrationInterface = await this.findBy({
945
+ type: integrationType,
946
+ [constants_1.EngineConstants.prop.type]: constants_1.EngineConstants.spec.openApi,
947
+ [constants_1.EngineConstants.prop.integration]: integratedProductId
948
+ });
949
+ return integrationInterface;
950
+ }
951
+ // Add support for other integration types
952
+ return null;
953
+ }
954
+ async findSecurityCredentialsForAccountIfDefined(accountId) {
955
+ return await this.findByIfExists({
956
+ type: constants_1.EngineConstants.spec.integrationAuthenticationCredential,
957
+ [constants_1.EngineConstants.prop.accountOrUser]: accountId
958
+ });
959
+ }
960
+ async findgetOpenApiRuntimeAuthorizationCapabilityIfDefined() {
961
+ return (await this.findByIfExists({
962
+ type: constants_1.EngineConstants.spec.capability,
963
+ [constants_1.EngineConstants.prop.label]: constants_1.OPEN_API_RUNTIME_AUTHORIZATION
964
+ }));
965
+ }
966
+ async findRefreshCapabilityForIntegration(integrationId) {
967
+ const integration = await this.findByIfExists({ id: integrationId });
968
+ const configuredRefreshCapability = integration?.[constants_1.EngineConstants.prop.refreshCapability];
969
+ if (configuredRefreshCapability) {
970
+ const refreshCapabilityId = (0, rmlmapper_js_1.getIdFromNodeObjectIfDefined)(configuredRefreshCapability);
971
+ if (!refreshCapabilityId) {
972
+ throw new Error(`Integration ${integrationId} has an invalid refresh capability reference.`);
973
+ }
974
+ const refreshCapability = (await this.findByIfExists({ id: refreshCapabilityId }));
975
+ if (!refreshCapability) {
976
+ throw new Error(`Refresh capability ${refreshCapabilityId} configured for integration ${integrationId} was not found.`);
977
+ }
978
+ return refreshCapability;
979
+ }
980
+ return await this.findCapabilityWithName('getOauthTokens');
981
+ }
982
+ async getRuntimeCredentialsWithSecurityCredentials(securityCredentials, integrationId, openApiOperationInformation, operationArgs) {
983
+ const getOpenApiRuntimeAuthorizationCapability = await this.findgetOpenApiRuntimeAuthorizationCapabilityIfDefined();
984
+ if (!getOpenApiRuntimeAuthorizationCapability) {
985
+ return {};
986
+ }
987
+ const mapping = await this.findCapabilityIntegrationMapping(getOpenApiRuntimeAuthorizationCapability[constants_1.PROP_ENTITY_ID], integrationId);
988
+ if (!mapping) {
989
+ return {};
990
+ }
991
+ const args = {
992
+ securityCredentials,
993
+ openApiExecutorOperationWithPathInfo: openApiOperationInformation,
994
+ operationArgs
995
+ };
996
+ const operationInfoJsonLd = await this.performParameterMappingOnArgsIfDefined(args, mapping, undefined, true);
997
+ const headers = (0, Util_1.getValueIfDefined)(operationInfoJsonLd[constants_1.EngineConstants.prop.headers]);
998
+ return headers ?? {};
999
+ }
1000
+ async createOpenApiOperationExecutorWithSpec(openApiDescription) {
1001
+ const executor = new openapi_operation_executor_1.OpenApiOperationExecutor();
1002
+ await executor.setOpenapiSpec(openApiDescription);
1003
+ return executor;
1004
+ }
1005
+ async findCapabilityObjectMapping(capabilityId, object) {
1006
+ return (await this.findByIfExists({
1007
+ type: constants_1.EngineConstants.spec.capabilityMapping,
1008
+ [constants_1.EngineConstants.prop.capability]: capabilityId,
1009
+ [constants_1.EngineConstants.prop.object]: (0, InversePath_1.InversePath)({
1010
+ subPath: (0, ZeroOrMorePath_1.ZeroOrMorePath)({ subPath: constants_1.RDFS.subClassOf }),
1011
+ value: object
1012
+ })
1013
+ }));
1014
+ }
1015
+ async performCapabilityMappingWithArgs(args, mapping, capabilityConfig) {
1016
+ if (mapping[constants_1.EngineConstants.prop.operationId]) {
1017
+ return (0, Util_1.getValueIfDefined)(mapping[constants_1.EngineConstants.prop.operationId]);
1018
+ }
1019
+ if (mapping[constants_1.EngineConstants.prop.operationId]) {
1020
+ return (0, Util_1.getValueIfDefined)(mapping[constants_1.EngineConstants.prop.operationId]);
1021
+ }
1022
+ const capabilityInfoJsonLd = await this.performMapping(args, mapping[constants_1.EngineConstants.prop.operationMapping], undefined, capabilityConfig);
1023
+ return (0, Util_1.getValueIfDefined)(capabilityInfoJsonLd[constants_1.EngineConstants.prop.operationId]);
1024
+ }
1025
+ async assertCapabilityParamsMatchParameterSchemas(capabilityParams, capability) {
1026
+ let parametersSchemaObject = capability[constants_1.EngineConstants.prop.inputs];
1027
+ if (parametersSchemaObject?.[constants_1.PROP_ENTITY_ID] && Object.keys(parametersSchemaObject).length === 1) {
1028
+ parametersSchemaObject = await this.findBy({ id: parametersSchemaObject[constants_1.PROP_ENTITY_ID] });
1029
+ }
1030
+ if (capabilityParams && parametersSchemaObject) {
1031
+ const capabilityParamsAsJsonLd = {
1032
+ '@context': (0, Util_1.getValueIfDefined)(capability[constants_1.EngineConstants.prop.inputsContext]),
1033
+ [constants_1.PROP_ENTITY_TYPE]: constants_1.EngineConstants.spec.inputs,
1034
+ ...capabilityParams
1035
+ };
1036
+ const report = await this.convertToQuadsAndValidateAgainstShape(capabilityParamsAsJsonLd, parametersSchemaObject);
1037
+ if (!report.conforms) {
1038
+ this.throwValidationReportError(report, `${(0, Util_1.getValueIfDefined)(capability[constants_1.EngineConstants.prop.label])} parameters do not conform to the schema`);
1039
+ }
1040
+ }
1041
+ }
1042
+ async performOpenapiOperationWithCredentials(operationId, operationArgs, account, capabilityConfig) {
1043
+ const integratedProductId = account[constants_1.EngineConstants.prop.integration][constants_1.PROP_ENTITY_ID];
1044
+ const restAPIInterface = await this.getIntegrationInterface(integratedProductId);
1045
+ if (!restAPIInterface) {
1046
+ throw new Error(`No integration interface found for integrated product ${integratedProductId}`);
1047
+ }
1048
+ const openApiDescription = (0, Util_1.getValueIfDefined)(restAPIInterface[constants_1.EngineConstants.prop.declarativeApiDescription]);
1049
+ const openApiExecutor = await this.createOpenApiOperationExecutorWithSpec(openApiDescription);
1050
+ // eslint-disable-next-line @typescript-eslint/await-thenable
1051
+ const openApiOperationInformation = await openApiExecutor.getOperationWithPathInfoMatchingOperationId(operationId);
1052
+ const securityCredentials = await this.findSecurityCredentialsForAccountIfDefined(account[constants_1.PROP_ENTITY_ID]);
1053
+ let runtimeAuthorization = {};
1054
+ if (securityCredentials) {
1055
+ const generatedRuntimeCredentials = await this.getRuntimeCredentialsWithSecurityCredentials(securityCredentials, integratedProductId, openApiOperationInformation, operationArgs);
1056
+ if (generatedRuntimeCredentials && Object.keys(generatedRuntimeCredentials).length > 0) {
1057
+ runtimeAuthorization = generatedRuntimeCredentials;
1058
+ }
1059
+ }
1060
+ const apiKey = [
1061
+ (0, Util_1.getValueIfDefined)(securityCredentials?.[constants_1.EngineConstants.prop.apiKey]),
1062
+ this.getAuthorizationHeaderFromRuntimeCredentials(runtimeAuthorization)
1063
+ ].find(Boolean);
1064
+ const configuration = {
1065
+ accessToken: (0, Util_1.getValueIfDefined)(securityCredentials?.[constants_1.EngineConstants.prop.accessToken]),
1066
+ bearerToken: (0, Util_1.getValueIfDefined)(securityCredentials?.[constants_1.EngineConstants.prop.bearerToken]),
1067
+ apiKey,
1068
+ basePath: (0, Util_1.getValueIfDefined)(account[constants_1.EngineConstants.prop.overrideBasePath]),
1069
+ username: (0, Util_1.getValueIfDefined)(securityCredentials?.[constants_1.EngineConstants.prop.username]),
1070
+ password: (0, Util_1.getValueIfDefined)(securityCredentials?.[constants_1.EngineConstants.prop.password])
1071
+ };
1072
+ let response;
1073
+ let executeOperationOptions;
1074
+ try {
1075
+ const additionalHeaders = this.getHeadersFromRuntimeCredentials(runtimeAuthorization);
1076
+ if (additionalHeaders &&
1077
+ typeof additionalHeaders === 'object' &&
1078
+ !Array.isArray(additionalHeaders) &&
1079
+ Object.keys(additionalHeaders).length > 0) {
1080
+ executeOperationOptions = { headers: additionalHeaders };
1081
+ }
1082
+ if (this.ifCapabilityStreaming(capabilityConfig)) {
1083
+ executeOperationOptions = {
1084
+ ...executeOperationOptions,
1085
+ responseType: 'stream'
1086
+ };
1087
+ }
1088
+ else if (this.ifCapabilityBuffering(capabilityConfig)) {
1089
+ executeOperationOptions = {
1090
+ ...executeOperationOptions,
1091
+ responseType: 'arraybuffer'
1092
+ };
1093
+ }
1094
+ if (capabilityConfig?.axiosOptions && typeof capabilityConfig.axiosOptions === 'object' && Object.keys(capabilityConfig.axiosOptions).length > 0) {
1095
+ executeOperationOptions = {
1096
+ ...executeOperationOptions,
1097
+ ...capabilityConfig.axiosOptions
1098
+ };
1099
+ }
1100
+ response = await openApiExecutor.executeOperation(operationId, configuration, operationArgs, executeOperationOptions);
1101
+ }
1102
+ catch (error) {
1103
+ if (axios_1.default.isAxiosError(error) &&
1104
+ await this.isInvalidTokenError(error, integratedProductId) &&
1105
+ securityCredentials) {
1106
+ const refreshCapabilityConfig = capabilityConfig
1107
+ ? {
1108
+ ...capabilityConfig,
1109
+ stream: false,
1110
+ buffer: false
1111
+ }
1112
+ : undefined;
1113
+ const refreshedConfiguration = await this.refreshSecurityCredentials(securityCredentials, integratedProductId, account, refreshCapabilityConfig);
1114
+ response = await openApiExecutor.executeOperation(operationId, refreshedConfiguration, operationArgs, executeOperationOptions);
1115
+ }
1116
+ else {
1117
+ throw error;
1118
+ }
1119
+ }
1120
+ return response;
1121
+ }
1122
+ getHeadersFromRuntimeCredentials(runtimeCredentials) {
1123
+ let returnValue = {};
1124
+ if (runtimeCredentials.headers &&
1125
+ typeof runtimeCredentials.headers === 'object' &&
1126
+ Object.keys(runtimeCredentials.headers).length > 0 &&
1127
+ !Array.isArray(runtimeCredentials.headers)) {
1128
+ returnValue = runtimeCredentials.headers;
1129
+ }
1130
+ return returnValue;
1131
+ }
1132
+ getAuthorizationHeaderFromRuntimeCredentials(runtimeCredentials) {
1133
+ const headers = this.getHeadersFromRuntimeCredentials(runtimeCredentials);
1134
+ if (headers && 'Authorization' in headers) {
1135
+ const authorizationHeader = headers.Authorization;
1136
+ if (typeof authorizationHeader === 'string') {
1137
+ return authorizationHeader;
1138
+ }
1139
+ }
1140
+ return undefined;
1141
+ }
1142
+ async isInvalidTokenError(error, integratedProductId) {
1143
+ const integrationInterface = await this.getIntegrationInterface(integratedProductId);
1144
+ if (!integrationInterface) {
1145
+ return false;
1146
+ }
1147
+ const errorMatcher = integrationInterface[constants_1.EngineConstants.prop.invalidTokenErrorMatcher];
1148
+ const errorMatcherStatus = errorMatcher && (0, Util_1.getValueIfDefined)(errorMatcher[constants_1.EngineConstants.prop.invalidTokenErrorMatcherStatus]);
1149
+ const errorMatcherRegex = errorMatcher &&
1150
+ (0, Util_1.getValueIfDefined)(errorMatcher[constants_1.EngineConstants.prop.invalidTokenErrorMatcherMessageRegex]);
1151
+ if (errorMatcher && error.response?.status === errorMatcherStatus) {
1152
+ if (!errorMatcherRegex) {
1153
+ return true;
1154
+ }
1155
+ if (error.response?.statusText && new RegExp(errorMatcherRegex, 'u').test(error.response?.statusText)) {
1156
+ return true;
1157
+ }
1158
+ }
1159
+ return false;
1160
+ }
1161
+ async refreshSecurityCredentials(securityCredentials, integrationId, account, capabilityConfig) {
1162
+ const refreshCapability = await this.findRefreshCapabilityForIntegration(integrationId);
1163
+ const mapping = await this.findCapabilityIntegrationMapping(refreshCapability[constants_1.PROP_ENTITY_ID], integrationId);
1164
+ if (!mapping) {
1165
+ throw new Error(`No mapping found for capability ${refreshCapability[constants_1.PROP_ENTITY_ID]} and integration ${integrationId}`);
1166
+ }
1167
+ const args = {
1168
+ refreshToken: (0, Util_1.getValueIfDefined)(securityCredentials[constants_1.EngineConstants.prop.refreshToken]),
1169
+ jwtBearerOptions: (0, Util_1.getValueIfDefined)(securityCredentials[constants_1.EngineConstants.prop.jwtBearerOptions]),
1170
+ securityCredentials: securityCredentials,
1171
+ account: account,
1172
+ integrationId
1173
+ };
1174
+ const operationArgs = await this.performParameterMappingOnArgsIfDefined(args, mapping, capabilityConfig, true);
1175
+ const operationInfoJsonLd = await this.performOperationMappingWithArgs({}, mapping, capabilityConfig);
1176
+ const rawReturnValue = await this.performOperation(operationInfoJsonLd, operationArgs, args, account, capabilityConfig, securityCredentials);
1177
+ const mappedReturnValue = await this.performReturnValueMappingWithFrameIfDefined(rawReturnValue, mapping, capabilityConfig);
1178
+ await this.assertCapabilityReturnValueMatchesReturnTypeSchema(mappedReturnValue, refreshCapability);
1179
+ const bearerToken = (0, Util_1.getValueIfDefined)(mappedReturnValue[constants_1.EngineConstants.prop.bearerToken]);
1180
+ const accessToken = (0, Util_1.getValueIfDefined)(mappedReturnValue[constants_1.EngineConstants.prop.accessToken]);
1181
+ const refreshToken = (0, Util_1.getValueIfDefined)(mappedReturnValue[constants_1.EngineConstants.prop.refreshToken]);
1182
+ if (bearerToken) {
1183
+ securityCredentials[constants_1.EngineConstants.prop.bearerToken] = bearerToken;
1184
+ }
1185
+ if (accessToken) {
1186
+ securityCredentials[constants_1.EngineConstants.prop.accessToken] = accessToken;
1187
+ }
1188
+ if (refreshToken) {
1189
+ securityCredentials[constants_1.EngineConstants.prop.refreshToken] = refreshToken;
1190
+ }
1191
+ await this.save(securityCredentials);
1192
+ return { accessToken, bearerToken };
1193
+ }
1194
+ getOauthConfigurationFromSecurityCredentials(securityCredentialsSchema) {
1195
+ const username = (0, Util_1.getValueIfDefined)(securityCredentialsSchema[constants_1.EngineConstants.prop.username]);
1196
+ const password = (0, Util_1.getValueIfDefined)(securityCredentialsSchema[constants_1.EngineConstants.prop.password]);
1197
+ const accessToken = (0, Util_1.getValueIfDefined)(securityCredentialsSchema[constants_1.EngineConstants.prop.accessToken]);
1198
+ return { username, password, accessToken };
1199
+ }
1200
+ async assertCapabilityReturnValueMatchesReturnTypeSchema(returnValue, capability) {
1201
+ let returnTypeSchemaObject = capability[constants_1.EngineConstants.prop.outputs];
1202
+ if (returnTypeSchemaObject?.[constants_1.PROP_ENTITY_ID] && Object.keys(returnTypeSchemaObject).length === 1) {
1203
+ returnTypeSchemaObject = await this.findBy({ id: returnTypeSchemaObject[constants_1.PROP_ENTITY_ID] });
1204
+ }
1205
+ let report;
1206
+ if (returnValue && returnTypeSchemaObject) {
1207
+ if (Array.isArray(returnValue)) {
1208
+ if (returnValue.some((valueItem) => constants_1.PROP_ENTITY_ID in valueItem)) {
1209
+ returnTypeSchemaObject[constants_1.SHACL.targetNode] = returnValue.reduce((nodes, outputItem) => {
1210
+ if (outputItem[constants_1.PROP_ENTITY_ID]) {
1211
+ nodes.push({ [constants_1.PROP_ENTITY_ID]: outputItem[constants_1.PROP_ENTITY_ID] });
1212
+ }
1213
+ return nodes;
1214
+ }, []);
1215
+ }
1216
+ else {
1217
+ const targetClasses = returnValue.reduce((nodes, outputItem) => {
1218
+ if (outputItem[constants_1.PROP_ENTITY_TYPE]) {
1219
+ const type = Array.isArray(outputItem[constants_1.PROP_ENTITY_TYPE])
1220
+ ? outputItem[constants_1.PROP_ENTITY_TYPE][0]
1221
+ : outputItem[constants_1.PROP_ENTITY_TYPE];
1222
+ if (!nodes.includes({ [constants_1.PROP_ENTITY_ID]: type })) {
1223
+ nodes.push({ [constants_1.PROP_ENTITY_ID]: type });
1224
+ }
1225
+ }
1226
+ return nodes;
1227
+ }, []);
1228
+ if (targetClasses.length > 0) {
1229
+ returnTypeSchemaObject[constants_1.SHACL.targetClass] = targetClasses;
1230
+ }
1231
+ }
1232
+ report = await this.convertToQuadsAndValidateAgainstShape(returnValue, returnTypeSchemaObject);
1233
+ }
1234
+ else if (Object.keys(returnValue).length > 0) {
1235
+ if (returnValue[constants_1.PROP_ENTITY_ID]) {
1236
+ returnTypeSchemaObject[constants_1.SHACL.targetNode] = { [constants_1.PROP_ENTITY_ID]: returnValue[constants_1.PROP_ENTITY_ID] };
1237
+ }
1238
+ else if (returnValue[constants_1.PROP_ENTITY_TYPE]) {
1239
+ returnTypeSchemaObject[constants_1.SHACL.targetClass] = {
1240
+ [constants_1.PROP_ENTITY_ID]: Array.isArray(returnValue[constants_1.PROP_ENTITY_TYPE])
1241
+ ? returnValue[constants_1.PROP_ENTITY_TYPE][0]
1242
+ : returnValue[constants_1.PROP_ENTITY_TYPE]
1243
+ };
1244
+ }
1245
+ report = await this.convertToQuadsAndValidateAgainstShape(returnValue, returnTypeSchemaObject);
1246
+ }
1247
+ }
1248
+ if (report && !report?.conforms) {
1249
+ throw new Error(`Return value ${Array.isArray(returnValue) ? 'array' : returnValue[constants_1.PROP_ENTITY_ID]} does not conform to the schema`);
1250
+ }
1251
+ }
1252
+ async convertToQuadsAndValidateAgainstShape(value, shape) {
1253
+ const valueAsQuads = await (0, Util_1.convertJsonLdToQuads)(Array.isArray(value) ? value : [value]);
1254
+ const shapeQuads = await (0, Util_1.convertJsonLdToQuads)(shape);
1255
+ const validator = new rdf_validate_shacl_1.default(shapeQuads);
1256
+ return validator.validate(valueAsQuads);
1257
+ }
1258
+ async performOauthSecuritySchemeStageWithCredentials(operationInfo, operationParameters, account, securityCredentials) {
1259
+ const integratedProductId = account[constants_1.EngineConstants.prop.integration][constants_1.PROP_ENTITY_ID];
1260
+ const restAPIInterface = await this.getIntegrationInterface(integratedProductId);
1261
+ if (!restAPIInterface) {
1262
+ throw new Error(`No integration interface found for integrated product ${integratedProductId}`);
1263
+ }
1264
+ const openApiDescription = (0, Util_1.getValueIfDefined)(restAPIInterface[constants_1.EngineConstants.prop.declarativeApiDescription]);
1265
+ securityCredentials || (securityCredentials = await this.findSecurityCredentialsForAccountIfDefined(account[constants_1.PROP_ENTITY_ID]));
1266
+ let configuration;
1267
+ if (securityCredentials) {
1268
+ configuration = this.getOauthConfigurationFromSecurityCredentials(securityCredentials);
1269
+ operationParameters.client_id = (0, Util_1.getValueIfDefined)(securityCredentials[constants_1.EngineConstants.prop.username]);
1270
+ }
1271
+ else {
1272
+ configuration = {};
1273
+ }
1274
+ const openApiExecutor = await this.createOpenApiOperationExecutorWithSpec(openApiDescription);
1275
+ const response = await openApiExecutor.executeSecuritySchemeStage((0, Util_1.getValueIfDefined)(operationInfo[constants_1.EngineConstants.prop.schemeName]), (0, Util_1.getValueIfDefined)(operationInfo[constants_1.EngineConstants.prop.oauthFlow]), (0, Util_1.getValueIfDefined)(operationInfo[constants_1.EngineConstants.prop.stage]), configuration, operationParameters);
1276
+ if ('codeVerifier' in response && 'authorizationUrl' in response) {
1277
+ return {
1278
+ data: response,
1279
+ operationParameters
1280
+ };
1281
+ }
1282
+ return this.axiosResponseAndParamsToOperationResponse(response, operationParameters, operationParameters);
1283
+ }
1284
+ async getDataFromDataSource(dataSourceId, capabilityConfig) {
1285
+ const dataSource = await this.findBy({ id: dataSourceId });
1286
+ if (dataSource[constants_1.PROP_ENTITY_TYPE] === constants_1.EngineConstants.spec.jsonDataSource) {
1287
+ const data = this.getDataFromJsonDataSource(dataSource, capabilityConfig);
1288
+ return { data, operationParameters: {} };
1289
+ }
1290
+ throw new Error(`DataSource type ${dataSource[constants_1.PROP_ENTITY_TYPE]} is not supported.`);
1291
+ }
1292
+ getDataFromJsonDataSource(dataSource, capabilityConfig) {
1293
+ if (dataSource[constants_1.EngineConstants.prop.source]) {
1294
+ const sourceValue = (0, Util_1.getValueIfDefined)(dataSource[constants_1.EngineConstants.prop.source]);
1295
+ return this.getJsonDataFromSource(sourceValue, capabilityConfig);
1296
+ }
1297
+ return (0, Util_1.getValueIfDefined)(dataSource[constants_1.EngineConstants.prop.data]);
1298
+ }
1299
+ getJsonDataFromSource(source, capabilityConfig) {
1300
+ const inputFiles = {
1301
+ ...this.inputFiles,
1302
+ ...capabilityConfig?.inputFiles
1303
+ };
1304
+ if (source in inputFiles) {
1305
+ const file = inputFiles[source];
1306
+ if (typeof file === 'string') {
1307
+ return JSON.parse(file);
1308
+ }
1309
+ return file;
1310
+ }
1311
+ // eslint-disable-next-line unicorn/expiring-todo-comments
1312
+ // TODO add support for remote sources
1313
+ throw new Error(`Failed to get data from source ${source}`);
1314
+ }
1315
+ throwValidationReportError(report, errorMessage) {
1316
+ const reportMessages = this.validationReportToMessages(report);
1317
+ throw new Error(`${errorMessage}\n\n${reportMessages.join('\n')}`);
1318
+ }
1319
+ validationReportToMessages(report) {
1320
+ const reportMessages = [];
1321
+ for (const result of report.results) {
1322
+ const pathValue = result.path?.value;
1323
+ if (result.message.length === 0) {
1324
+ const message = `${pathValue}: Invalid due to ${result.sourceConstraintComponent?.value}`;
1325
+ reportMessages.push(message);
1326
+ }
1327
+ else {
1328
+ const resultMessages = result.message.map((message) => `${message.value}`).join(', ');
1329
+ const message = `${pathValue}: ${resultMessages}`;
1330
+ reportMessages.push(message);
1331
+ }
1332
+ }
1333
+ return reportMessages;
1334
+ }
1335
+ ifCapabilityStreaming(capabilityConfig) {
1336
+ return Boolean(capabilityConfig && 'stream' in capabilityConfig && capabilityConfig.stream);
1337
+ }
1338
+ ifCapabilityBuffering(capabilityConfig) {
1339
+ return Boolean(capabilityConfig && 'buffer' in capabilityConfig && capabilityConfig.buffer);
1340
+ }
1341
+ isJavaScriptCode(text) {
1342
+ if (!text) {
1343
+ return false;
1344
+ }
1345
+ // Trim the text to handle leading/trailing whitespace
1346
+ const trimmed = text.trim();
1347
+ // First, quickly check if it looks like JSON (starts with { or [)
1348
+ const looksLikeJson = /^\s*[[{]/.test(trimmed) && /[\]}]\s*$/.test(trimmed);
1349
+ if (looksLikeJson) {
1350
+ try {
1351
+ // If it can be parsed as JSON, it's likely an RML mapping
1352
+ JSON.parse(trimmed);
1353
+ return false;
1354
+ }
1355
+ catch {
1356
+ // If it looks like JSON but can't be parsed, it might be code
1357
+ // Continue with other checks
1358
+ }
1359
+ }
1360
+ // Check for common JavaScript patterns that wouldn't appear in JSON
1361
+ const jsPatterns = [
1362
+ /function\s+[$A-Z_a-z][\w$]*\s*\(/,
1363
+ /const\s+[$A-Z_a-z][\w$]*/,
1364
+ /let\s+[$A-Z_a-z][\w$]*/,
1365
+ /var\s+[$A-Z_a-z][\w$]*/,
1366
+ /if\s*\(/,
1367
+ /for\s*\(/,
1368
+ /while\s*\(/,
1369
+ /=>|return |console\./,
1370
+ /import\s+|export\s+/,
1371
+ /class\s+[$A-Z_a-z][\w$]*/,
1372
+ /\/\/|\/\*|\*\// // Comments
1373
+ ];
1374
+ // If it matches any JS pattern, it's likely code
1375
+ return jsPatterns.some(pattern => pattern.test(trimmed));
1376
+ }
1377
+ ensureNodeObject(result) {
1378
+ // Handle null/undefined results
1379
+ if (result === null || result === undefined) {
1380
+ return {};
1381
+ }
1382
+ // If it's already a NodeObject with proper formatting, return as is
1383
+ if (typeof result === 'object' &&
1384
+ !Array.isArray(result) &&
1385
+ (result[constants_1.PROP_ENTITY_ID] !== undefined ||
1386
+ result[constants_1.PROP_ENTITY_TYPE] !== undefined ||
1387
+ result['@context'] !== undefined ||
1388
+ result['@graph'] !== undefined)) {
1389
+ return result;
1390
+ }
1391
+ // Handle arrays - convert to @graph
1392
+ if (Array.isArray(result)) {
1393
+ // Check if items in array are already objects
1394
+ const convertedItems = result.map(item => {
1395
+ if (typeof item === 'object' && item !== null) {
1396
+ // Already object, but ensure it has @type if not present
1397
+ if (!item[constants_1.PROP_ENTITY_TYPE] && !item[constants_1.PROP_ENTITY_ID] && !item[constants_1.PROP_ENTITY_VALUE]) {
1398
+ return { [constants_1.PROP_ENTITY_TYPE]: 'skl:Result', ...item };
1399
+ }
1400
+ return item;
1401
+ }
1402
+ // Convert primitives to objects with @value
1403
+ return { [constants_1.PROP_ENTITY_VALUE]: item };
1404
+ });
1405
+ return {
1406
+ '@context': {
1407
+ skl: Vocabularies_1.SKL_NAMESPACE
1408
+ },
1409
+ '@graph': convertedItems
1410
+ };
1411
+ }
1412
+ // Handle primitive values (string, number, boolean)
1413
+ if (typeof result !== 'object') {
1414
+ return {
1415
+ [constants_1.PROP_ENTITY_VALUE]: result
1416
+ };
1417
+ }
1418
+ // Handle plain objects (not arrays, not null)
1419
+ // If it's a plain object but not in NodeObject format, add @type
1420
+ return {
1421
+ [constants_1.PROP_ENTITY_TYPE]: 'skl:Result',
1422
+ '@context': {
1423
+ skl: Vocabularies_1.SKL_NAMESPACE
1424
+ },
1425
+ ...result
1426
+ };
1427
+ }
1428
+ async executeCodeBlocks(codeBlocks, args, executionOptions) {
1429
+ const results = [];
1430
+ let updatedArgs = args || {};
1431
+ for (const codeBlock of codeBlocks) {
1432
+ const code = (0, Util_1.getValueIfDefined)(codeBlock[constants_1.EngineConstants.prop.codeBody]);
1433
+ if (code) {
1434
+ const result = await this.executeJavaScriptMapping(updatedArgs, code, executionOptions);
1435
+ updatedArgs = {
1436
+ ...updatedArgs,
1437
+ ...result
1438
+ };
1439
+ results.push(result);
1440
+ }
1441
+ }
1442
+ return results.length > 0 ? results[results.length - 1] : {};
1443
+ }
1444
+ async executeJavaScriptMapping(args, code, _executionOptions) {
1445
+ try {
1446
+ // Configure execution options
1447
+ const executionOptions = {
1448
+ timeout: 60 * 60 * 1000,
1449
+ functionName: 'main',
1450
+ allowNetwork: true,
1451
+ allowedDomains: [],
1452
+ allowEnv: true,
1453
+ debugMode: true,
1454
+ allowRead: true,
1455
+ ..._executionOptions
1456
+ };
1457
+ if (!this.codeExecutor) {
1458
+ throw new Error('Code executor not set. Please set a code executor using setCodeExecutor()');
1459
+ }
1460
+ // Execute the code
1461
+ const executionResult = await this.codeExecutor.execute(code, args, executionOptions);
1462
+ // Handle execution errors
1463
+ if (executionResult?.error) {
1464
+ throw new Error(`Code execution error: ${executionResult.error?.message ?? 'Unknown error'}`);
1465
+ }
1466
+ // This is a patch to return the output as it is without converting to NodeObject
1467
+ // This is needed for some api inputs. We can try doing this using the frame.
1468
+ if (executionResult?.result?.rawOutput) {
1469
+ return executionResult?.result?.rawOutput;
1470
+ }
1471
+ // Convert the result to a NodeObject
1472
+ return this.ensureNodeObject(executionResult?.result ?? executionResult);
1473
+ }
1474
+ catch (error) {
1475
+ throw new Error(`Failed to execute JavaScript mapping: ${error instanceof Error ? error.message : String(error)}`);
1476
+ }
1477
+ }
1478
+ // Expose global hooks to users
1479
+ // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
1480
+ get hooks() {
1481
+ return globalHooks_1.globalHooks;
1482
+ }
1483
+ async prepareContextForType(typeSpecOrId) {
1484
+ const typeSpecs = [];
1485
+ if (typeof typeSpecOrId === 'string') {
1486
+ typeSpecs.push(await this.getSuperClassesOfObject(typeSpecOrId), await this.findBy({ id: typeSpecOrId }));
1487
+ }
1488
+ else {
1489
+ typeSpecs.push(typeSpecOrId);
1490
+ }
1491
+ const context = {};
1492
+ for (const typeSpec of typeSpecs) {
1493
+ const properties = typeSpec[constants_1.SHACL.property] ?? [];
1494
+ for (const property of (0, Util_1.ensureArray)(properties)) {
1495
+ const dataType = property[constants_1.SHACL.datatype]?.['@id'];
1496
+ const nodeKind = property[constants_1.SHACL.nodeKind]?.['@id'];
1497
+ const path = property[constants_1.SHACL.path]?.['@id'];
1498
+ if (nodeKind === constants_1.SHACL.IRI) {
1499
+ context[path] = {
1500
+ '@type': '@id'
1501
+ };
1502
+ }
1503
+ else {
1504
+ context[path] = {
1505
+ '@type': dataType
1506
+ };
1507
+ }
1508
+ }
1509
+ }
1510
+ return context;
1511
+ }
1512
+ }
1513
+ exports.SKLEngine = SKLEngine;
1514
+ //# sourceMappingURL=SklEngine.js.map