@things-factory/integration-base 9.0.20 → 9.0.25

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 (98) hide show
  1. package/dist-server/engine/analyzer/analyze-integration.js +2 -2
  2. package/dist-server/engine/analyzer/analyze-integration.js.map +1 -1
  3. package/dist-server/engine/connection-manager.d.ts +13 -1
  4. package/dist-server/engine/connection-manager.js +105 -7
  5. package/dist-server/engine/connection-manager.js.map +1 -1
  6. package/dist-server/engine/connector/headless-connector.d.ts +8 -0
  7. package/dist-server/engine/connector/headless-connector.js +4 -2
  8. package/dist-server/engine/connector/headless-connector.js.map +1 -1
  9. package/dist-server/engine/connector/mqtt-connector.d.ts +1 -0
  10. package/dist-server/engine/connector/mqtt-connector.js +4 -2
  11. package/dist-server/engine/connector/mqtt-connector.js.map +1 -1
  12. package/dist-server/engine/connector/mssql-connector.d.ts +4 -0
  13. package/dist-server/engine/connector/mssql-connector.js +4 -2
  14. package/dist-server/engine/connector/mssql-connector.js.map +1 -1
  15. package/dist-server/engine/connector/mysql-connector.d.ts +10 -2
  16. package/dist-server/engine/connector/mysql-connector.js +23 -18
  17. package/dist-server/engine/connector/mysql-connector.js.map +1 -1
  18. package/dist-server/engine/connector/operato-connector.d.ts +8 -2
  19. package/dist-server/engine/connector/operato-connector.js +2 -1
  20. package/dist-server/engine/connector/operato-connector.js.map +1 -1
  21. package/dist-server/engine/connector/oracle-connector.d.ts +3 -0
  22. package/dist-server/engine/connector/oracle-connector.js +4 -2
  23. package/dist-server/engine/connector/oracle-connector.js.map +1 -1
  24. package/dist-server/engine/connector/postgresql-connector.d.ts +13 -2
  25. package/dist-server/engine/connector/postgresql-connector.js +14 -6
  26. package/dist-server/engine/connector/postgresql-connector.js.map +1 -1
  27. package/dist-server/engine/connector/pyrun-connector.d.ts +1 -0
  28. package/dist-server/engine/connector/pyrun-connector.js +3 -3
  29. package/dist-server/engine/connector/pyrun-connector.js.map +1 -1
  30. package/dist-server/engine/edge-client.d.ts +1 -1
  31. package/dist-server/engine/edge-client.js.map +1 -1
  32. package/dist-server/engine/task/database-query.js +1 -1
  33. package/dist-server/engine/task/database-query.js.map +1 -1
  34. package/dist-server/engine/task/echo-receive.js +1 -1
  35. package/dist-server/engine/task/echo-receive.js.map +1 -1
  36. package/dist-server/engine/task/echo-send.js +1 -1
  37. package/dist-server/engine/task/echo-send.js.map +1 -1
  38. package/dist-server/engine/task/graphql-mutate.js +1 -1
  39. package/dist-server/engine/task/graphql-mutate.js.map +1 -1
  40. package/dist-server/engine/task/graphql-query.js +1 -1
  41. package/dist-server/engine/task/graphql-query.js.map +1 -1
  42. package/dist-server/engine/task/headless-post.js +1 -1
  43. package/dist-server/engine/task/headless-post.js.map +1 -1
  44. package/dist-server/engine/task/headless-scrap.js +1 -1
  45. package/dist-server/engine/task/headless-scrap.js.map +1 -1
  46. package/dist-server/engine/task/http-get.js +1 -1
  47. package/dist-server/engine/task/http-get.js.map +1 -1
  48. package/dist-server/engine/task/http-post.js +1 -1
  49. package/dist-server/engine/task/http-post.js.map +1 -1
  50. package/dist-server/engine/task/mqtt-publish.js +1 -1
  51. package/dist-server/engine/task/mqtt-publish.js.map +1 -1
  52. package/dist-server/engine/task/mqtt-subscribe.js +1 -1
  53. package/dist-server/engine/task/mqtt-subscribe.js.map +1 -1
  54. package/dist-server/engine/task/mssql-procedure.js +1 -1
  55. package/dist-server/engine/task/mssql-procedure.js.map +1 -1
  56. package/dist-server/engine/task/oracle-procedure.js +1 -1
  57. package/dist-server/engine/task/oracle-procedure.js.map +1 -1
  58. package/dist-server/engine/task/pyrun-execute.js +1 -1
  59. package/dist-server/engine/task/pyrun-execute.js.map +1 -1
  60. package/dist-server/engine/task/socket-listener.js +1 -1
  61. package/dist-server/engine/task/socket-listener.js.map +1 -1
  62. package/dist-server/service/connection/connection-mutation.d.ts +3 -1
  63. package/dist-server/service/connection/connection-mutation.js +62 -22
  64. package/dist-server/service/connection/connection-mutation.js.map +1 -1
  65. package/dist-server/service/connection/connection-query.d.ts +2 -1
  66. package/dist-server/service/connection/connection-query.js +14 -13
  67. package/dist-server/service/connection/connection-query.js.map +1 -1
  68. package/dist-server/service/connection/connection-subscription.js +6 -4
  69. package/dist-server/service/connection/connection-subscription.js.map +1 -1
  70. package/dist-server/service/connection/connection-type.d.ts +10 -99
  71. package/dist-server/service/connection/connection-type.js +36 -182
  72. package/dist-server/service/connection/connection-type.js.map +1 -1
  73. package/dist-server/service/connection/connection.d.ts +119 -0
  74. package/dist-server/service/connection/connection.js +239 -0
  75. package/dist-server/service/connection/connection.js.map +1 -0
  76. package/dist-server/service/connection/index.d.ts +1 -1
  77. package/dist-server/service/connection/index.js +2 -2
  78. package/dist-server/service/connection/index.js.map +1 -1
  79. package/dist-server/service/connector/connector-query.js +2 -2
  80. package/dist-server/service/connector/connector-query.js.map +1 -1
  81. package/dist-server/service/index.d.ts +1 -0
  82. package/dist-server/service/index.js +1 -0
  83. package/dist-server/service/index.js.map +1 -1
  84. package/dist-server/service/property-spec.d.ts +1 -0
  85. package/dist-server/service/property-spec.js +8 -1
  86. package/dist-server/service/property-spec.js.map +1 -1
  87. package/dist-server/service/scenario/scenario-mutation.js +1 -1
  88. package/dist-server/service/scenario/scenario-mutation.js.map +1 -1
  89. package/dist-server/service/scenario/scenario-query.js +3 -3
  90. package/dist-server/service/scenario/scenario-query.js.map +1 -1
  91. package/dist-server/service/scenario/scenario-type.js +4 -1
  92. package/dist-server/service/scenario/scenario-type.js.map +1 -1
  93. package/dist-server/service/scenario/scenario.js +1 -1
  94. package/dist-server/service/scenario/scenario.js.map +1 -1
  95. package/dist-server/service/task-type/task-type-query.js +2 -2
  96. package/dist-server/service/task-type/task-type-query.js.map +1 -1
  97. package/dist-server/tsconfig.tsbuildinfo +1 -1
  98. package/package.json +8 -8
@@ -5,7 +5,7 @@ const tslib_1 = require("tslib");
5
5
  const uniq_1 = tslib_1.__importDefault(require("lodash/uniq"));
6
6
  const shell_1 = require("@things-factory/shell");
7
7
  const scenario_1 = require("../../service/scenario/scenario");
8
- const connection_type_1 = require("../../service/connection/connection-type");
8
+ const connection_1 = require("../../service/connection/connection");
9
9
  async function analyzeIntegration(domain) {
10
10
  const tagNames = [];
11
11
  const model = {
@@ -17,7 +17,7 @@ async function analyzeIntegration(domain) {
17
17
  where: { domain: { id: domain.id } },
18
18
  relations: ['steps']
19
19
  });
20
- const connections = await (0, shell_1.getRepository)(connection_type_1.Connection).find({
20
+ const connections = await (0, shell_1.getRepository)(connection_1.Connection).find({
21
21
  where: { domain: { id: domain.id } }
22
22
  });
23
23
  model.nodes = model.nodes.concat(scenarios.map(scenario => {
@@ -1 +1 @@
1
- {"version":3,"file":"analyze-integration.js","sourceRoot":"","sources":["../../../server/engine/analyzer/analyze-integration.ts"],"names":[],"mappings":";;AAMA,gDA4GC;;AAlHD,+DAA8B;AAE9B,iDAA6D;AAC7D,8DAA0D;AAC1D,8EAAqE;AAE9D,KAAK,UAAU,kBAAkB,CAAC,MAAc;IACrD,MAAM,QAAQ,GAAG,EAAE,CAAA;IAEnB,MAAM,KAAK,GAAG;QACZ,KAAK,EAAE,EAAE;QACT,aAAa,EAAE,EAAE;KAClB,CAAA;IAED,IAAI,EAAE,GAAG,CAAC,CAAA;IAEV,MAAM,SAAS,GAAG,MAAM,IAAA,qBAAa,EAAC,mBAAQ,CAAC,CAAC,IAAI,CAAC;QACnD,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE;QACpC,SAAS,EAAE,CAAC,OAAO,CAAC;KACrB,CAAC,CAAA;IAEF,MAAM,WAAW,GAAG,MAAM,IAAA,qBAAa,EAAC,4BAAU,CAAC,CAAC,IAAI,CAAC;QACvD,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE;KACrC,CAAC,CAAA;IAEF,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,M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O,GAAG,EAAE;gBACrB,UAAU,EAAE,EAAE;aACf,CAAA;QACH,CAAC,CAAC,CAAA;QAEF,KAAK,CAAC,aAAa,GAAG,KAAK,CAAC,aAAa,CAAC,MAAM,CAAC,aAAa,CAAC,CAAA;IACjE,CAAC,CAAC,CAAA;IAEF,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import uniq from 'lodash/uniq'\n\nimport { Domain, getRepository } from '@things-factory/shell'\nimport { Scenario } from '../../service/scenario/scenario'\nimport { Connection } from '../../service/connection/connection-type'\n\nexport async function analyzeIntegration(domain: Domain) {\n const tagNames = []\n\n const model = {\n nodes: [],\n relationships: []\n }\n\n var id = 0\n\n const scenarios = await getRepository(Scenario).find({\n where: { domain: { id: domain.id } },\n relations: ['steps']\n })\n\n const connections = await getRepository(Connection).find({\n where: { domain: { id: domain.id } }\n })\n\n model.nodes = model.nodes.concat(\n scenarios.map(scenario => {\n return {\n id: scenario.id,\n labels: ['Scenario'],\n text: scenario.name,\n icon: 'settings',\n properties: {\n name: scenario.name,\n description: scenario.description\n }\n }\n })\n )\n\n model.nodes = model.nodes.concat(\n connections.map(connection => {\n return {\n id: connection.id,\n labels: ['Connection'],\n text: connection.name,\n icon: 'link',\n properties: {\n name: connection.name,\n description: connection.description\n }\n }\n })\n )\n\n scenarios.forEach(scenario => {\n const connectionNames = uniq(scenario.steps.map(step => step.connection).filter(Boolean))\n const connectionList = connectionNames\n .map(connectionName => connections.find(connection => connection.name == connectionName))\n .filter(Boolean)\n\n const relationships = connectionList.map(connection => {\n return {\n id: ++id,\n type: 'using',\n startNode: scenario.id,\n endNode: connection.id,\n properties: {}\n }\n })\n\n model.relationships = model.relationships.concat(relationships)\n })\n\n scenarios.forEach(scenario => {\n const tags = uniq(\n scenario.steps\n .filter(step => !step.connection && step.task == 'publish')\n .map(step => step.params?.tag)\n .filter(Boolean)\n )\n\n for (const tag of tags) {\n if (tagNames.includes(tag)) {\n continue\n }\n\n model.nodes.push({\n id: `tag-${tag}`,\n labels: ['Tag'],\n text: tag,\n icon: 'label',\n properties: {\n tag\n }\n })\n\n tagNames.push(tag)\n }\n\n const relationships = tags.map(tag => {\n return {\n id: ++id,\n type: 'publish',\n startNode: scenario.id,\n endNode: `tag-${tag}`,\n properties: {}\n }\n })\n\n model.relationships = model.relationships.concat(relationships)\n })\n\n return model\n}\n"]}
1
+ {"version":3,"file":"analyze-integration.js","sourceRoot":"","sources":["../../../server/engine/analyzer/analyze-integration.ts"],"names":[],"mappings":";;AAMA,gDA4GC;;AAlHD,+DAA8B;AAE9B,iDAA6D;AAC7D,8DAA0D;AAC1D,oEAAgE;AAEzD,KAAK,UAAU,kBAAkB,CAAC,MAAc;IACrD,MAAM,QAAQ,GAAG,EAAE,CAAA;IAEnB,MAAM,KAAK,GAAG;QACZ,KAAK,EAAE,EAAE;QACT,aAAa,EAAE,EAAE;KAClB,CAAA;IAED,IAAI,EAAE,GAAG,CAAC,CAAA;IAEV,MAAM,SAAS,GAAG,MAAM,IAAA,qBAAa,EAAC,mBAAQ,CAAC,CAAC,IAAI,CAAC;QACnD,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE;QACpC,SAAS,EAAE,CAAC,OAAO,CAAC;KACrB,CAAC,CAAA;IAEF,MAAM,WAAW,GAAG,MAAM,IAAA,qBAAa,EAAC,uBAAU,CAAC,CAAC,IAAI,CAAC;QACvD,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,EAAE;KACrC,CAAC,CAAA;IAEF,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,CAC9B,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;QACvB,OAAO;YACL,EAAE,EAAE,QAAQ,CAAC,EAAE;YACf,MAAM,EAAE,CAAC,UAAU,CAAC;YACpB,IAAI,EAAE,QAAQ,CAAC,IAAI;YACnB,IAAI,EAAE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,KAAK,CAAA;AACd,CAAC","sourcesContent":["import uniq from 'lodash/uniq'\n\nimport { Domain, getRepository } from '@things-factory/shell'\nimport { Scenario } from '../../service/scenario/scenario'\nimport { Connection } from '../../service/connection/connection'\n\nexport async function analyzeIntegration(domain: Domain) {\n const tagNames = []\n\n const model = {\n nodes: [],\n relationships: []\n }\n\n var id = 0\n\n const scenarios = await getRepository(Scenario).find({\n where: { domain: { id: domain.id } },\n relations: ['steps']\n })\n\n const connections = await getRepository(Connection).find({\n where: { domain: { id: domain.id } }\n })\n\n model.nodes = model.nodes.concat(\n scenarios.map(scenario => {\n return {\n id: scenario.id,\n labels: ['Scenario'],\n text: scenario.name,\n icon: 'settings',\n properties: {\n name: scenario.name,\n description: scenario.description\n }\n }\n })\n )\n\n model.nodes = model.nodes.concat(\n connections.map(connection => {\n return {\n id: connection.id,\n labels: ['Connection'],\n text: connection.name,\n icon: 'link',\n properties: {\n name: connection.name,\n description: connection.description\n }\n }\n })\n )\n\n scenarios.forEach(scenario => {\n const connectionNames = uniq(scenario.steps.map(step => step.connection).filter(Boolean))\n const connectionList = connectionNames\n .map(connectionName => connections.find(connection => connection.name == connectionName))\n .filter(Boolean)\n\n const relationships = connectionList.map(connection => {\n return {\n id: ++id,\n type: 'using',\n startNode: scenario.id,\n endNode: connection.id,\n properties: {}\n }\n })\n\n model.relationships = model.relationships.concat(relationships)\n })\n\n scenarios.forEach(scenario => {\n const tags = uniq(\n scenario.steps\n .filter(step => !step.connection && step.task == 'publish')\n .map(step => step.params?.tag)\n .filter(Boolean)\n )\n\n for (const tag of tags) {\n if (tagNames.includes(tag)) {\n continue\n }\n\n model.nodes.push({\n id: `tag-${tag}`,\n labels: ['Tag'],\n text: tag,\n icon: 'label',\n properties: {\n tag\n }\n })\n\n tagNames.push(tag)\n }\n\n const relationships = tags.map(tag => {\n return {\n id: ++id,\n type: 'publish',\n startNode: scenario.id,\n endNode: `tag-${tag}`,\n properties: {}\n }\n })\n\n model.relationships = model.relationships.concat(relationships)\n })\n\n return model\n}\n"]}
@@ -21,8 +21,20 @@ export declare class ConnectionManager {
21
21
  };
22
22
  static getEntities(): {};
23
23
  static getConnectionInstance(connection: Connection): any;
24
- static getConnectionInstanceByName(domain: Domain, name: string): any;
24
+ static getConnectionInstanceByName(domain: Domain, name: string): Promise<any>;
25
+ static getConnectionEntityByName(domain: Domain, name: string): Promise<Connection | null>;
25
26
  static getConnectionInstanceEntityByName(domain: Domain, name: string): any;
27
+ /**
28
+ * Creates a connection on-demand and returns the instance.
29
+ * @param connection - The connection entity to create
30
+ * @returns The connection instance
31
+ */
32
+ static createOnDemandConnection(connection: Connection): Promise<any>;
33
+ /**
34
+ * Disconnects an on-demand connection.
35
+ * @param connection - The connection entity to disconnect
36
+ */
37
+ static disconnectOnDemandConnection(connection: Connection): Promise<void>;
26
38
  static getConnectionInstances(domain: Domain): {
27
39
  [connectionName: string]: any;
28
40
  };
@@ -52,15 +52,17 @@ class ConnectionManager {
52
52
  ]
53
53
  }); }
54
54
  static async ready() {
55
- const CONNECTIONS = (await (0, shell_1.getRepository)(service_1.Connection).find({
55
+ const CONNECTIONS = await Promise.all((await (0, shell_1.getRepository)(service_1.Connection).find({
56
56
  where: { active: true },
57
57
  relations: ['domain', 'edge', 'creator', 'updater']
58
- })).map(connection => {
58
+ })).map(async (connection) => {
59
+ // 🔐 해결된 파라미터 사용
60
+ const resolvedParams = await connection.getResolvedParameters();
59
61
  return {
60
62
  ...connection,
61
- params: connection.params || {}
63
+ params: resolvedParams
62
64
  };
63
- });
65
+ }));
64
66
  ConnectionManager.logger.info('Initializing ConnectionManager...');
65
67
  return await Promise.all([...Object.keys(ConnectionManager.connectors), 'proxy-connector'].map(type => {
66
68
  const connector = type == 'proxy-connector' ? proxy_connector_1.ProxyConnector.instance : ConnectionManager.getConnector(type);
@@ -112,21 +114,117 @@ class ConnectionManager {
112
114
  const { domain, name } = connection;
113
115
  return ConnectionManager.connections[domain.id]?.[name];
114
116
  }
115
- static getConnectionInstanceByName(domain, name) {
117
+ static async getConnectionInstanceByName(domain, name) {
116
118
  const connections = ConnectionManager.connections[domain.id];
117
119
  const connection = connections?.[name];
118
120
  if (!connection) {
119
- throw `The connection with the given name(${name}) cannot be found`;
121
+ // on-demand 커넥션인지 확인하고 생성
122
+ try {
123
+ const connectionEntity = await ConnectionManager.getConnectionEntityByName(domain, name);
124
+ if (connectionEntity?.onDemand) {
125
+ // on-demand 커넥션 생성
126
+ const onDemandInstance = await ConnectionManager.createOnDemandConnection(connectionEntity);
127
+ return onDemandInstance;
128
+ }
129
+ else {
130
+ throw `The connection with the given name(${name}) cannot be found`;
131
+ }
132
+ }
133
+ catch (error) {
134
+ throw `The connection with the given name(${name}) cannot be found: ${error}`;
135
+ }
120
136
  }
121
137
  return connection;
122
138
  }
139
+ static async getConnectionEntityByName(domain, name) {
140
+ // 1. 현재 도메인에서 메모리 조회 (우선)
141
+ const cachedEntity = ConnectionManager.entities[domain.id]?.[name];
142
+ if (cachedEntity) {
143
+ return cachedEntity;
144
+ }
145
+ // 2. 현재 도메인에서 데이터베이스 조회 (우선)
146
+ try {
147
+ let connection = await (0, shell_1.getRepository)(service_1.Connection).findOne({
148
+ where: {
149
+ domain: { id: domain.id },
150
+ name: name
151
+ },
152
+ relations: ['domain', 'edge', 'creator', 'updater']
153
+ });
154
+ if (connection) {
155
+ const resolvedParams = await connection.getResolvedParameters();
156
+ connection.params = resolvedParams;
157
+ return connection;
158
+ }
159
+ // 3. 현재 도메인에서 못 찾으면 부모 도메인에서 메모리 조회 - 안된다. connection정보를 수정해야 하므로 사용할 수 없다.
160
+ // if (domain.parentId) {
161
+ // const parentCachedEntity = ConnectionManager.entities[domain.parentId]?.[name]
162
+ // if (parentCachedEntity) {
163
+ // return parentCachedEntity
164
+ // }
165
+ // }
166
+ // 4. 부모 도메인에서 데이터베이스 조회 (fallback)
167
+ if (domain.parentId) {
168
+ connection = await (0, shell_1.getRepository)(service_1.Connection).findOne({
169
+ where: {
170
+ domain: { id: domain.parentId },
171
+ name: name
172
+ },
173
+ relations: ['domain', 'edge', 'creator', 'updater']
174
+ });
175
+ if (connection) {
176
+ const resolvedParams = await connection.getResolvedParameters();
177
+ connection.params = resolvedParams;
178
+ connection.domain = domain;
179
+ connection.domainId = domain.id;
180
+ return connection;
181
+ }
182
+ }
183
+ return null;
184
+ }
185
+ catch (error) {
186
+ ConnectionManager.logger.error(`Failed to get connection entity '${name}' from database:`, error);
187
+ return null;
188
+ }
189
+ }
123
190
  static getConnectionInstanceEntityByName(domain, name) {
124
191
  const connection = ConnectionManager.entities[domain.id]?.[name];
125
192
  if (connection) {
126
193
  return connection;
127
194
  }
128
195
  if (domain.parentId) {
129
- return ConnectionManager.entities[domain.id]?.[name];
196
+ return ConnectionManager.entities[domain.parentId]?.[name];
197
+ }
198
+ }
199
+ /**
200
+ * Creates a connection on-demand and returns the instance.
201
+ * @param connection - The connection entity to create
202
+ * @returns The connection instance
203
+ */
204
+ static async createOnDemandConnection(connection) {
205
+ try {
206
+ // 커넥션 생성
207
+ await connection.connect();
208
+ ConnectionManager.logger.info(`On-demand connection '${connection.name}' created successfully`);
209
+ return ConnectionManager.getConnectionInstance(connection);
210
+ }
211
+ catch (error) {
212
+ ConnectionManager.logger.error(`Failed to create on-demand connection '${connection.name}':`, error);
213
+ throw error;
214
+ }
215
+ }
216
+ /**
217
+ * Disconnects an on-demand connection.
218
+ * @param connection - The connection entity to disconnect
219
+ */
220
+ static async disconnectOnDemandConnection(connection) {
221
+ try {
222
+ await connection.disconnect();
223
+ // ConnectionManager.removeConnectionInstance(connection)
224
+ ConnectionManager.logger.info(`On-demand connection '${connection.name}' disconnected successfully`);
225
+ }
226
+ catch (error) {
227
+ ConnectionManager.logger.error(`Failed to disconnect on-demand connection '${connection.name}':`, error);
130
228
  }
131
229
  }
132
230
  static getConnectionInstances(domain) {
@@ -1 +1 @@
1
- {"version":3,"file":"connection-manager.js","sourceRoot":"","sources":["../../server/engine/connection-manager.ts"],"names":[],"mappings":";;;;AAAA,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I,EAAE,GAAG,UAAU,CAAA;QAEhE,cAAM,CAAC,OAAO,CAAC,kBAAkB,EAAE;YACjC,eAAe,EAAE;gBACf,MAAM;gBACN,EAAE;gBACF,IAAI;gBACJ,WAAW;gBACX,IAAI;gBACJ,IAAI;gBACJ,KAAK;gBACL,SAAS,EAAE,IAAI,IAAI,EAAE;aACtB;SACF,CAAC,CAAA;IACJ,CAAC;;AAvMH,8CAwMC","sourcesContent":["import moment from 'moment-timezone'\nimport { createLogger, format, transports } from 'winston'\n\nimport { Domain, getRepository, pubsub, PubSubLogTransport } from '@things-factory/shell'\n\nimport { Connection, ConnectionStatus } from '../service'\nimport { Connector } from './types'\nimport { ProxyConnector } from './connector/proxy-connector'\n\nconst { combine, splat, printf, errors } = format\nconst debug = require('debug')('things-factory:integration-base:connections')\n\nfunction getSystemTimeZone() {\n try {\n const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone\n if (!timeZone) {\n throw new Error('Unable to resolve timeZone')\n }\n return timeZone\n } catch (e) {\n console.warn('Failed to get system timeZone, falling back to UTC.', e)\n return 'UTC'\n }\n}\n\nconst SYSTEM_TZ = getSystemTimeZone()\nconst systemTimestamp = format((info, opts: { tz?: string }) => {\n if (opts.tz) info.timestamp = moment().tz(opts.tz).format()\n return info\n})\n\nexport class ConnectionManager {\n private static connectors: { [propName: string]: Connector } = {}\n private static connections: { [domainId: string]: { [name: string]: any } } = {}\n private static entities = {}\n private static logFormat = printf(({ level, message, timestamp, stack }) => {\n return `${timestamp} ${level}: ${stack || message}`\n })\n\n public static logger = createLogger({\n format: combine(errors({ stack: true }), systemTimestamp({ tz: SYSTEM_TZ }), splat(), ConnectionManager.logFormat),\n transports: [\n new (transports as any).DailyRotateFile({\n filename: `logs/connections-%DATE%.log`,\n datePattern: 'YYYY-MM-DD-HH',\n zippedArchive: false,\n maxSize: '20m',\n maxFiles: '14d',\n level: 'info'\n }),\n new PubSubLogTransport({\n topic: 'connection-log'\n })\n ]\n })\n\n static async ready() {\n const CONNECTIONS = (\n await getRepository(Connection).find({\n where: { active: true },\n relations: ['domain', 'edge', 'creator', 'updater']\n })\n ).map(connection => {\n return {\n ...connection,\n params: connection.params || {}\n }\n })\n\n ConnectionManager.logger.info('Initializing ConnectionManager...')\n\n return await Promise.all(\n [...Object.keys(ConnectionManager.connectors), 'proxy-connector'].map(type => {\n const connector = type == 'proxy-connector' ? ProxyConnector.instance : ConnectionManager.getConnector(type)\n\n ConnectionManager.logger.info(`Connector '${type}' started to ready`)\n\n return connector\n .ready(\n CONNECTIONS.filter(connection => {\n if (type == 'proxy-connector') {\n return !!connection.edge\n } else {\n return !connection.edge && connection.type == type\n }\n }) as any\n )\n .catch(error => {\n ConnectionManager.logger.error(error)\n })\n .then(() => {\n ConnectionManager.logger.info(`All connector for '${type}' ready`)\n })\n })\n ).then(() => {\n ConnectionManager.logger.info('ConnectionManager initialization done:')\n Object.keys(ConnectionManager.connections).forEach(key => {\n var connections = ConnectionManager.connections[key]\n ConnectionManager.logger.info('For domain(%s) : %s', key, JSON.stringify(Object.keys(connections)))\n })\n })\n }\n\n static registerConnector(type: string, connector: Connector) {\n ConnectionManager.connectors[type] = connector\n }\n\n static getConnector(type: string): Connector {\n return ConnectionManager.connectors[type]\n }\n\n static getConnectors(): { [connectorName: string]: Connector } {\n return {\n ...ConnectionManager.connectors\n }\n }\n\n static unregisterConnector(type: string) {\n delete ConnectionManager.connectors[type]\n }\n\n static getConnections() {\n return ConnectionManager.connections\n }\n\n static getEntities() {\n return ConnectionManager.entities\n }\n\n static getConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n return ConnectionManager.connections[domain.id]?.[name]\n }\n\n static getConnectionInstanceByName(domain: Domain, name: string) {\n const connections = ConnectionManager.connections[domain.id]\n const connection = connections?.[name]\n\n if (!connection) {\n throw `The connection with the given name(${name}) cannot be found`\n }\n\n return connection\n }\n\n static getConnectionInstanceEntityByName(domain: Domain, name: string): any {\n const connection = ConnectionManager.entities[domain.id]?.[name]\n if (connection) {\n return connection\n }\n\n if (domain.parentId) {\n return ConnectionManager.entities[domain.id]?.[name]\n }\n }\n\n static getConnectionInstances(domain: Domain): { [connectionName: string]: any } {\n const connections = ConnectionManager.connections[domain.id]\n const parentConnections = domain.parentId && ConnectionManager.connections[domain.parentId]\n\n return {\n ...parentConnections,\n ...connections\n }\n }\n\n static getConnectionInstanceEntities(domain: Domain): { [connectionName: string]: any } {\n const connections = ConnectionManager.entities[domain.id]\n\n return {\n ...connections\n }\n }\n\n static addConnectionInstance(connection: Connection, instance: any) {\n const { domain, name } = connection\n\n var connections = ConnectionManager.connections[domain.id]\n if (!connections) {\n connections = ConnectionManager.connections[domain.id] = {}\n }\n\n var entities = ConnectionManager.entities[domain.id]\n if (!entities) {\n entities = ConnectionManager.entities[domain.id] = {}\n }\n\n connections[name] = instance\n entities[name] = connection\n\n ConnectionManager.publishState(connection, ConnectionStatus.CONNECTED)\n debug('add-connection', domain.subdomain, name)\n }\n\n static removeConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n var connections = ConnectionManager.connections[domain.id]\n var entities = ConnectionManager.entities[domain.id]\n\n var instance = connections?.[name]\n\n if (!connections || !instance) {\n debug('remove-connection', `'${name}' connection not found in domain '${domain.subdomain}'`)\n return\n }\n\n delete connections[name]\n delete entities[name]\n\n ConnectionManager.publishState(connection, ConnectionStatus.DISCONNECTED)\n debug('remove-connection', `'${name}' connection is removed from domain '${domain.subdomain}'`)\n\n return instance\n }\n\n private static async publishState(connection: Connection, state) {\n const { domain, id, name, description, type, edge } = connection\n\n pubsub.publish('connection-state', {\n connectionState: {\n domain,\n id,\n name,\n description,\n type,\n edge,\n state,\n timestamp: new Date()\n }\n })\n }\n}\n"]}
1
+ {"version":3,"file":"connection-manager.js","sourceRoot":"","sources":["../../server/engine/connection-manager.ts"],"names":[],"mappings":";;;;AAAA,8EAAoC;AACpC,qCAA0D;AAE1D,iDAAyF;AAEzF,wCAAyD;AAEzD,iEAA4D;AAE5D,MAAM,EAAE,OAAO,EAAE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AAC,mBAAmB,EAAE,IAAI,IAAI,qCAAqC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAA;YAC5F,OAAM;QACR,CAAC;QAED,OAAO,WAAW,CAAC,IAAI,CAAC,CAAA;QACxB,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAA;QAErB,iBAAiB,CAAC,YAAY,CAAC,UAAU,EAAE,0BAAgB,CAAC,YAAY,CAAC,CAAA;QACzE,KAAK,CAAC,mBAAmB,EAAE,IAAI,IAAI,wCAAwC,MAAM,CAAC,SAAS,GAAG,CAAC,CAAA;QAE/F,OAAO,QAAQ,CAAA;IACjB,CAAC;IAEO,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,UAAsB,EAAE,KAAK;QAC7D,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,UAAU,CAAA;QAEhE,cAAM,CAAC,OAAO,CAAC,kBAAkB,EAAE;YACjC,eAAe,EAAE;gBACf,MAAM;gBACN,EAAE;gBACF,IAAI;gBACJ,WAAW;gBACX,IAAI;gBACJ,IAAI;gBACJ,KAAK;gBACL,SAAS,EAAE,IAAI,IAAI,EAAE;aACtB;SACF,CAAC,CAAA;IACJ,CAAC;;AAnTH,8CAoTC","sourcesContent":["import moment from 'moment-timezone'\nimport { createLogger, format, transports } from 'winston'\n\nimport { Domain, getRepository, pubsub, PubSubLogTransport } from '@things-factory/shell'\n\nimport { Connection, ConnectionStatus } from '../service'\nimport { Connector } from './types'\nimport { ProxyConnector } from './connector/proxy-connector'\n\nconst { combine, splat, printf, errors } = format\nconst debug = require('debug')('things-factory:integration-base:connections')\n\nfunction getSystemTimeZone() {\n try {\n const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone\n if (!timeZone) {\n throw new Error('Unable to resolve timeZone')\n }\n return timeZone\n } catch (e) {\n console.warn('Failed to get system timeZone, falling back to UTC.', e)\n return 'UTC'\n }\n}\n\nconst SYSTEM_TZ = getSystemTimeZone()\nconst systemTimestamp = format((info, opts: { tz?: string }) => {\n if (opts.tz) info.timestamp = moment().tz(opts.tz).format()\n return info\n})\n\nexport class ConnectionManager {\n private static connectors: { [propName: string]: Connector } = {}\n private static connections: { [domainId: string]: { [name: string]: any } } = {}\n private static entities = {}\n private static logFormat = printf(({ level, message, timestamp, stack }) => {\n return `${timestamp} ${level}: ${stack || message}`\n })\n\n public static logger = createLogger({\n format: combine(errors({ stack: true }), systemTimestamp({ tz: SYSTEM_TZ }), splat(), ConnectionManager.logFormat),\n transports: [\n new (transports as any).DailyRotateFile({\n filename: `logs/connections-%DATE%.log`,\n datePattern: 'YYYY-MM-DD-HH',\n zippedArchive: false,\n maxSize: '20m',\n maxFiles: '14d',\n level: 'info'\n }),\n new PubSubLogTransport({\n topic: 'connection-log'\n })\n ]\n })\n\n static async ready() {\n const CONNECTIONS = await Promise.all(\n (\n await getRepository(Connection).find({\n where: { active: true },\n relations: ['domain', 'edge', 'creator', 'updater']\n })\n ).map(async connection => {\n // 🔐 해결된 파라미터 사용\n const resolvedParams = await connection.getResolvedParameters()\n\n return {\n ...connection,\n params: resolvedParams\n }\n })\n )\n\n ConnectionManager.logger.info('Initializing ConnectionManager...')\n\n return await Promise.all(\n [...Object.keys(ConnectionManager.connectors), 'proxy-connector'].map(type => {\n const connector = type == 'proxy-connector' ? ProxyConnector.instance : ConnectionManager.getConnector(type)\n\n ConnectionManager.logger.info(`Connector '${type}' started to ready`)\n\n return connector\n .ready(\n CONNECTIONS.filter(connection => {\n if (type == 'proxy-connector') {\n return !!connection.edge\n } else {\n return !connection.edge && connection.type == type\n }\n }) as any\n )\n .catch(error => {\n ConnectionManager.logger.error(error)\n })\n .then(() => {\n ConnectionManager.logger.info(`All connector for '${type}' ready`)\n })\n })\n ).then(() => {\n ConnectionManager.logger.info('ConnectionManager initialization done:')\n Object.keys(ConnectionManager.connections).forEach(key => {\n var connections = ConnectionManager.connections[key]\n ConnectionManager.logger.info('For domain(%s) : %s', key, JSON.stringify(Object.keys(connections)))\n })\n })\n }\n\n static registerConnector(type: string, connector: Connector) {\n ConnectionManager.connectors[type] = connector\n }\n\n static getConnector(type: string): Connector {\n return ConnectionManager.connectors[type]\n }\n\n static getConnectors(): { [connectorName: string]: Connector } {\n return {\n ...ConnectionManager.connectors\n }\n }\n\n static unregisterConnector(type: string) {\n delete ConnectionManager.connectors[type]\n }\n\n static getConnections() {\n return ConnectionManager.connections\n }\n\n static getEntities() {\n return ConnectionManager.entities\n }\n\n static getConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n return ConnectionManager.connections[domain.id]?.[name]\n }\n\n static async getConnectionInstanceByName(domain: Domain, name: string) {\n const connections = ConnectionManager.connections[domain.id]\n const connection = connections?.[name]\n\n if (!connection) {\n // on-demand 커넥션인지 확인하고 생성\n try {\n const connectionEntity = await ConnectionManager.getConnectionEntityByName(domain, name)\n\n if (connectionEntity?.onDemand) {\n // on-demand 커넥션 생성\n const onDemandInstance = await ConnectionManager.createOnDemandConnection(connectionEntity)\n return onDemandInstance\n } else {\n throw `The connection with the given name(${name}) cannot be found`\n }\n } catch (error) {\n throw `The connection with the given name(${name}) cannot be found: ${error}`\n }\n }\n\n return connection\n }\n\n static async getConnectionEntityByName(domain: Domain, name: string): Promise<Connection | null> {\n // 1. 현재 도메인에서 메모리 조회 (우선)\n const cachedEntity = ConnectionManager.entities[domain.id]?.[name]\n if (cachedEntity) {\n return cachedEntity\n }\n\n // 2. 현재 도메인에서 데이터베이스 조회 (우선)\n try {\n let connection = await getRepository(Connection).findOne({\n where: {\n domain: { id: domain.id },\n name: name\n },\n relations: ['domain', 'edge', 'creator', 'updater']\n })\n\n if (connection) {\n const resolvedParams = await connection.getResolvedParameters()\n connection.params = resolvedParams\n return connection\n }\n\n // 3. 현재 도메인에서 못 찾으면 부모 도메인에서 메모리 조회 - 안된다. connection정보를 수정해야 하므로 사용할 수 없다.\n // if (domain.parentId) {\n // const parentCachedEntity = ConnectionManager.entities[domain.parentId]?.[name]\n // if (parentCachedEntity) {\n // return parentCachedEntity\n // }\n // }\n\n // 4. 부모 도메인에서 데이터베이스 조회 (fallback)\n if (domain.parentId) {\n connection = await getRepository(Connection).findOne({\n where: {\n domain: { id: domain.parentId },\n name: name\n },\n relations: ['domain', 'edge', 'creator', 'updater']\n })\n\n if (connection) {\n const resolvedParams = await connection.getResolvedParameters()\n connection.params = resolvedParams\n connection.domain = domain\n connection.domainId = domain.id\n\n return connection\n }\n }\n\n return null\n } catch (error) {\n ConnectionManager.logger.error(`Failed to get connection entity '${name}' from database:`, error)\n return null\n }\n }\n\n static getConnectionInstanceEntityByName(domain: Domain, name: string): any {\n const connection = ConnectionManager.entities[domain.id]?.[name]\n if (connection) {\n return connection\n }\n\n if (domain.parentId) {\n return ConnectionManager.entities[domain.parentId]?.[name]\n }\n }\n\n /**\n * Creates a connection on-demand and returns the instance.\n * @param connection - The connection entity to create\n * @returns The connection instance\n */\n static async createOnDemandConnection(connection: Connection): Promise<any> {\n try {\n // 커넥션 생성\n await connection.connect()\n\n ConnectionManager.logger.info(`On-demand connection '${connection.name}' created successfully`)\n return ConnectionManager.getConnectionInstance(connection)\n } catch (error) {\n ConnectionManager.logger.error(`Failed to create on-demand connection '${connection.name}':`, error)\n throw error\n }\n }\n\n /**\n * Disconnects an on-demand connection.\n * @param connection - The connection entity to disconnect\n */\n static async disconnectOnDemandConnection(connection: Connection): Promise<void> {\n try {\n await connection.disconnect()\n // ConnectionManager.removeConnectionInstance(connection)\n ConnectionManager.logger.info(`On-demand connection '${connection.name}' disconnected successfully`)\n } catch (error) {\n ConnectionManager.logger.error(`Failed to disconnect on-demand connection '${connection.name}':`, error)\n }\n }\n\n static getConnectionInstances(domain: Domain): { [connectionName: string]: any } {\n const connections = ConnectionManager.connections[domain.id]\n const parentConnections = domain.parentId && ConnectionManager.connections[domain.parentId]\n\n return {\n ...parentConnections,\n ...connections\n }\n }\n\n static getConnectionInstanceEntities(domain: Domain): { [connectionName: string]: any } {\n const connections = ConnectionManager.entities[domain.id]\n\n return {\n ...connections\n }\n }\n\n static addConnectionInstance(connection: Connection, instance: any) {\n const { domain, name } = connection\n\n var connections = ConnectionManager.connections[domain.id]\n if (!connections) {\n connections = ConnectionManager.connections[domain.id] = {}\n }\n\n var entities = ConnectionManager.entities[domain.id]\n if (!entities) {\n entities = ConnectionManager.entities[domain.id] = {}\n }\n\n connections[name] = instance\n entities[name] = connection\n\n ConnectionManager.publishState(connection, ConnectionStatus.CONNECTED)\n debug('add-connection', domain.subdomain, name)\n }\n\n static removeConnectionInstance(connection: Connection): any {\n const { domain, name } = connection\n var connections = ConnectionManager.connections[domain.id]\n var entities = ConnectionManager.entities[domain.id]\n\n var instance = connections?.[name]\n\n if (!connections || !instance) {\n debug('remove-connection', `'${name}' connection not found in domain '${domain.subdomain}'`)\n return\n }\n\n delete connections[name]\n delete entities[name]\n\n ConnectionManager.publishState(connection, ConnectionStatus.DISCONNECTED)\n debug('remove-connection', `'${name}' connection is removed from domain '${domain.subdomain}'`)\n\n return instance\n }\n\n private static async publishState(connection: Connection, state) {\n const { domain, id, name, description, type, edge } = connection\n\n pubsub.publish('connection-state', {\n connectionState: {\n domain,\n id,\n name,\n description,\n type,\n edge,\n state,\n timestamp: new Date()\n }\n })\n }\n}\n"]}
@@ -10,12 +10,20 @@ export declare class HeadlessConnector implements Connector {
10
10
  type: string;
11
11
  name: string;
12
12
  label: string;
13
+ useDomainAttribute: boolean;
14
+ value?: undefined;
15
+ } | {
16
+ type: string;
17
+ name: string;
18
+ label: string;
19
+ useDomainAttribute?: undefined;
13
20
  value?: undefined;
14
21
  } | {
15
22
  type: string;
16
23
  name: string;
17
24
  label: string;
18
25
  value: number;
26
+ useDomainAttribute?: undefined;
19
27
  })[];
20
28
  get taskPrefixes(): string[];
21
29
  get description(): string;
@@ -279,12 +279,14 @@ class HeadlessConnector {
279
279
  {
280
280
  type: 'string',
281
281
  name: 'username',
282
- label: 'username'
282
+ label: 'username',
283
+ useDomainAttribute: true
283
284
  },
284
285
  {
285
286
  type: 'password',
286
287
  name: 'password',
287
- label: 'password'
288
+ label: 'password',
289
+ useDomainAttribute: true
288
290
  },
289
291
  {
290
292
  type: 'string',
@@ -1 +1 @@
1
- {"version":3,"file":"headless-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/headless-connector.ts"],"names":[],"mappings":";;;AAAA,8DAAyD;AAEzD,kEAAgE;AAGhE;;;;;;;;;;EAUE;AAEF,MAAa,iBAAiB;IAC5B,KAAK,CAAC,KAAK,CAAC,iBAAiB;QAC3B,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QACjE,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,0CAA0C,CAAC,CAAA;IAC3E,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAAU;QACtB,MAAM,EACJ,QAAQ,EAAE,GAAG,GAAG,GAAG,EACnB,MAAM,EAAE,EACN,QAAQ,GAAG,EAAE,EACb,QAAQ,GAAG,EAAE,EACb,aAAa,GAAG,QAAQ,EACxB,WAAW,GAAG,IAAI,EAClB,gBAAgB,GAAG,WAAW,EAC9B,gBAAgB,GAAG,WAAW,EAC9B,cAAc,GAAG,SAAS,EAC1B,eAAe,GAAG,IAAI,EACtB,kBAAkB,GAAG,EAAE,EAAE,uCAAuC;QAChE,OAAO,GAAG,KAAK,EAAE,iCAAiC;QAClD,OAAO,GAAG,CAAC,CAAC,sDAAsD;UACnE,GAAG,EAAE,EACP,GAAG,UAAU,CAAA;QAEd,MAAM,SAAS,GAAG;YAChB,aAAa,EAAE,OAAO,CAAC,QAAQ,CAAC,EAAE,iCAAiC;YACnE,QAAQ;YACR,QAAQ;YACR,aAAa;YACb,WAAW;YACX,OAAO;YACP,OAAO;YACP,cAAc,EAAE;gBACd,gBAAgB;gBAChB,gBAAgB;gBAChB,cAAc;gBACd,eAAe;gBACf,kBAAkB,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C,oBAAoB,EAAE,IAAI,iBAAiB,EAAE,CAAC,CAAA;AAElF,SAAS,aAAa,CAAC,OAAO;IAC5B,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IAClD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,0BAA0B;IACxD,OAAO,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,GAAG,GAAG,CAAC,CAAA;AACvE,CAAC","sourcesContent":["import { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { getHeadlessPool } from '../resource-pool/headless-pool'\nimport { Browser, Page } from 'puppeteer'\n\n/*\n Functionality of the headless-connector:\n - Provides a mechanism to acquire an active session page.\n - Performs login when necessary to obtain valid cookies.\n - Applies these cookies to the page for session management.\n - Pages are acquired from the `headlessPool`, which manages browser instances.\n - During the login process, pages from the pool are used for actions like form filling and navigation.\n - Valid cookies are saved after login and reused for subsequent page acquisitions.\n - Users must explicitly release the page after use through the `releasePage` method.\n - Released pages are returned to the `headlessPool` for reuse.\n*/\n\nexport class HeadlessConnector implements Connector {\n async ready(connectionConfigs) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n ConnectionManager.logger.info('headless-connector connections are ready')\n }\n\n async connect(connection) {\n const {\n endpoint: uri = '1',\n params: {\n username = '',\n password = '',\n loginPagePath = '/login',\n loginApiUrl = null,\n usernameSelector = '#username',\n passwordSelector = '#password',\n submitSelector = '#submit',\n successSelector = null,\n shadowDomSelectors = '', // Comma separated shadow DOM selectors\n timeout = 15000, // Default timeout for operations\n retries = 3 // Default number of retries for login or page actions\n } = {}\n } = connection\n\n const loginInfo = {\n loginRequired: Boolean(username), // Determine if login is required\n username,\n password,\n loginPagePath,\n loginApiUrl,\n timeout,\n retries,\n loginSelectors: {\n usernameSelector,\n passwordSelector,\n submitSelector,\n successSelector,\n shadowDomSelectors: shadowDomSelectors\n .split(',')\n .map(selector => selector.trim())\n .filter(Boolean)\n }\n }\n\n async function acquireBrowser() {\n try {\n const pool = getHeadlessPool()\n const browser = await pool.acquire()\n return browser\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire browser:', error)\n throw error\n }\n }\n\n async function releaseBrowser(browser: Browser) {\n try {\n const pool = getHeadlessPool()\n await pool.release(browser)\n } catch (error) {\n ConnectionManager.logger.error('Failed to release browser:', error)\n }\n }\n\n ConnectionManager.addConnectionInstance(connection, {\n endpoint: connection.endpoint,\n params: connection.params,\n acquireSessionPage: async () => {\n const browser = await acquireBrowser()\n let page\n let cookies = connection.cookies\n\n try {\n page = await browser.newPage()\n\n await page.setRequestInterception(true)\n\n await page.setBypassCSP(true)\n\n await page.setUserAgent(\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.204 Safari/537.36'\n )\n\n await page.evaluateOnNewDocument(() => {\n Object.defineProperty(navigator, 'webdriver', { get: () => false })\n })\n\n await page.setExtraHTTPHeaders({\n 'Upgrade-Insecure-Requests': '0',\n 'accept-language': 'en-US,en;q=0.9',\n // 'upgrade-insecure-requests': '0',\n referer: uri\n })\n\n await page.setDefaultNavigationTimeout(timeout)\n\n page.on('console', async msg => {\n ConnectionManager.logger.info(`[browser ${msg.type()}] ${msg.text()}`)\n })\n\n page.on('request', request => {\n if (request.isInterceptResolutionHandled()) {\n return\n }\n\n const resourceType = request.resourceType()\n\n const headers = request.headers()\n if (headers['access-control-request-headers']) {\n const filteredHeaders = headers['access-control-request-headers']\n .split(',')\n .map(header => header.trim())\n .filter(header => header.toLowerCase() !== 'upgrade-insecure-requests') // 해당 헤더 제거\n\n if (filteredHeaders.length > 0) {\n headers['access-control-request-headers'] = filteredHeaders.join(', ')\n } else {\n delete headers['access-control-request-headers'] // 필요하면 전체 삭제\n }\n }\n\n // 일반적인 요청에서도 'upgrade-insecure-requests' 헤더 제거\n if (headers['upgrade-insecure-requests']) {\n delete headers['upgrade-insecure-requests']\n }\n\n if (['image', 'stylesheet', 'font'].includes(resourceType)) {\n request.abort() // 비필수 리소스 요청 차단\n } else {\n request.continue() // 나머지 요청은 진행\n }\n })\n\n page.on('requestfailed', request => {\n try {\n console.log('Request failed:')\n console.log(`- URL: ${request.url()}`)\n console.log(`- Method: ${request.method()}`)\n console.log(`- Failure Text: ${request.failure()?.errorText}`)\n console.log(`- Headers:`, request.headers())\n\n // POST 데이터 (필요한 경우)\n if (request.postData()) {\n console.log(`- Post Data: ${request.postData()}`)\n }\n } catch (error) {\n console.error('Error in requestfailed handler:', error)\n }\n })\n\n if (loginInfo.loginRequired) {\n // 현재 세션의 Authorization 헤더 확인\n const headers = await page.evaluate(() => {\n return fetch(window.location.href, { method: 'GET' })\n .then(response => response.headers.get('Authorization'))\n .catch(() => null)\n })\n\n if (headers) {\n ConnectionManager.logger.info('User is already logged in, skipping login process.')\n return page\n }\n\n if (cookies && isCookieValid(cookies)) {\n await this.applyCookiesAndVerifySession(page, cookies, loginInfo)\n return page\n }\n\n await this.performLogin(page, uri, loginInfo)\n cookies = await page.cookies()\n connection.cookies = cookies\n }\n\n return page\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire session page:', error)\n throw error\n }\n },\n releasePage: async (page: Page) => {\n try {\n if (page) {\n const browser = page.browser()\n await page.close()\n await releaseBrowser(browser)\n }\n } catch (error) {\n ConnectionManager.logger.error('Failed to release page:', error)\n }\n },\n acquireBrowser,\n releaseBrowser\n })\n\n ConnectionManager.logger.info(\n `headless-connector connection(${connection.name}:${connection.endpoint}) is connected`\n )\n }\n\n async applyCookiesAndVerifySession(page, cookies, loginInfo) {\n await page.setCookie(...cookies)\n await page.reload({ waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n if (loginInfo.loginRequired && loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Session invalid, login required')\n }\n }\n }\n\n async performLogin(page, uri, loginInfo) {\n for (let attempt = 1; attempt <= loginInfo.retries; attempt++) {\n try {\n await page.goto(`${uri}${loginInfo.loginPagePath}`, { waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n const usernameInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.usernameSelector\n )\n const passwordInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.passwordSelector\n )\n const submitButton = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.submitSelector\n )\n\n if (!usernameInput || !passwordInput || !submitButton) {\n throw new Error('Failed to locate input elements in shadow DOM')\n }\n\n await usernameInput.type(loginInfo.username)\n await passwordInput.type(loginInfo.password)\n\n var loginApiUrl =\n loginInfo.loginApiUrl ||\n (await page.evaluate(button => {\n const form = button.closest('form')\n return form ? form.action : null\n }, submitButton))\n\n if (loginApiUrl && !loginApiUrl.startsWith('http')) {\n loginApiUrl = `${uri}${loginApiUrl}`\n }\n\n if (!loginApiUrl) {\n throw new Error('❌ Unable to detect login API URL!')\n }\n\n console.log('✅ Detected login API URL:', loginApiUrl)\n\n const [response] = await Promise.all([\n page.waitForResponse(response => {\n const url = response.url()\n const method = response.request().method()\n\n return url === loginApiUrl && method === 'POST' && [200, 201, 204, 302, 304].includes(response.status())\n }),\n page.evaluate(button => button.click(), submitButton),\n page.waitForNavigation({ waitUntil: 'networkidle2', timeout: loginInfo.timeout }) // 로그인 후 리디렉션 감지\n ])\n\n if (response) {\n const status = response.status()\n if (status >= 200 && status < 400) {\n ConnectionManager.logger.info(`Login successful with status code: ${status}`)\n return\n } else if (status >= 400) {\n throw new Error(`Login failed with status code: ${status}`)\n }\n } else {\n throw new Error('No response received during login')\n }\n\n if (loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Login failed: Success selector not found')\n }\n }\n } catch (error) {\n ConnectionManager.logger.warn(`Login attempt ${attempt} failed:`, error)\n\n try {\n await page.screenshot({ path: `logs/login-failure-attempt-${attempt}.png` })\n } catch (error) {\n ConnectionManager.logger.error('Failed to capture screenshot:', error)\n }\n\n if (attempt === loginInfo.retries) {\n throw new Error(`Login failed after ${loginInfo.retries} attempts`)\n }\n }\n }\n }\n\n async resolveShadowDom(page, shadowSelectors, targetSelector) {\n let context\n\n if (!shadowSelectors || shadowSelectors.length === 0) {\n // No Shadow DOM path; use document root as the context\n context = page.mainFrame() // Puppeteer uses frames to represent document\n return context.$(targetSelector) // Search directly in the document root\n }\n\n context = page // Start with the page as the context\n for (const selector of shadowSelectors) {\n const shadowHost = await context.$(selector)\n if (!shadowHost) {\n throw new Error(`Shadow host not found: ${selector}`)\n }\n context = await page.evaluateHandle(host => host.shadowRoot, shadowHost)\n }\n return context.evaluateHandle((shadowRoot, selector) => shadowRoot.querySelector(selector), targetSelector)\n }\n\n async disconnect(connection) {\n ConnectionManager.removeConnectionInstance(connection)\n ConnectionManager.logger.info(`headless-connector connection(${connection.name}) is disconnected`)\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'username',\n label: 'username'\n },\n {\n type: 'password',\n name: 'password',\n label: 'password'\n },\n {\n type: 'string',\n name: 'loginPagePath',\n label: 'login-page-path'\n },\n {\n type: 'string',\n name: 'loginApiUrl',\n label: 'login-api-url'\n },\n {\n type: 'string',\n name: 'usernameSelector',\n label: 'username-selector'\n },\n {\n type: 'string',\n name: 'passwordSelector',\n label: 'password-selector'\n },\n {\n type: 'string',\n name: 'submitSelector',\n label: 'submit-selector'\n },\n {\n type: 'string',\n name: 'successSelector',\n label: 'success-selector'\n },\n {\n type: 'string',\n name: 'shadowDomSelectors',\n label: 'shadow-dom-selectors'\n },\n {\n type: 'number',\n name: 'timeout',\n label: 'timeout',\n value: 15000\n },\n {\n type: 'number',\n name: 'retries',\n label: 'maximum-retries',\n value: 3\n }\n ]\n }\n\n get taskPrefixes() {\n return ['headless']\n }\n\n get description() {\n return 'Headless Pool Connector with login capabilities'\n }\n\n get help() {\n return 'integration/connector/headless-connector'\n }\n}\n\nConnectionManager.registerConnector('headless-connector', new HeadlessConnector())\n\nfunction isCookieValid(cookies) {\n if (!cookies || cookies.length === 0) return false\n const now = Date.now() / 1000 // Current time in seconds\n return cookies.some(cookie => cookie.expires && cookie.expires > now)\n}\n"]}
1
+ {"version":3,"file":"headless-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/headless-connector.ts"],"names":[],"mappings":";;;AAAA,8DAAyD;AAEzD,kEAAgE;AAGhE;;;;;;;;;;EAUE;AAEF,MAAa,iBAAiB;IAC5B,KAAK,CAAC,KAAK,CAAC,iBAAiB;QAC3B,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QACjE,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,0CAA0C,CAAC,CAAA;IAC3E,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAAU;QACtB,MAAM,EACJ,QAAQ,EAAE,GAAG,GAAG,GAAG,EACnB,MAAM,EAAE,EACN,QAAQ,GAAG,EAAE,EACb,QAAQ,GAAG,EAAE,EACb,aAAa,GAAG,QAAQ,EACxB,WAAW,GAAG,IAAI,EAClB,gBAAgB,GAAG,WAAW,EAC9B,gBAAgB,GAAG,WAAW,EAC9B,cAAc,GAAG,SAAS,EAC1B,eAAe,GAAG,IAAI,EACtB,kBAAkB,GAAG,EAAE,EAAE,uCAAuC;QAChE,OAAO,GAAG,KAAK,EAAE,iCAAiC;QAClD,OAAO,GAAG,CAAC,CAAC,sDAAsD;UACnE,GAAG,EA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AI,EAAE,SAAS;gBACf,KAAK,EAAE,iBAAiB;gBACxB,KAAK,EAAE,CAAC;aACT;SACF,CAAA;IACH,CAAC;IAED,IAAI,YAAY;QACd,OAAO,CAAC,UAAU,CAAC,CAAA;IACrB,CAAC;IAED,IAAI,WAAW;QACb,OAAO,iDAAiD,CAAA;IAC1D,CAAC;IAED,IAAI,IAAI;QACN,OAAO,0CAA0C,CAAA;IACnD,CAAC;CACF;AAzZD,8CAyZC;AAED,sCAAiB,CAAC,iBAAiB,CAAC,oBAAoB,EAAE,IAAI,iBAAiB,EAAE,CAAC,CAAA;AAElF,SAAS,aAAa,CAAC,OAAO;IAC5B,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IAClD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAA,CAAC,0BAA0B;IACxD,OAAO,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,GAAG,GAAG,CAAC,CAAA;AACvE,CAAC","sourcesContent":["import { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { getHeadlessPool } from '../resource-pool/headless-pool'\nimport { Browser, Page } from 'puppeteer'\n\n/*\n Functionality of the headless-connector:\n - Provides a mechanism to acquire an active session page.\n - Performs login when necessary to obtain valid cookies.\n - Applies these cookies to the page for session management.\n - Pages are acquired from the `headlessPool`, which manages browser instances.\n - During the login process, pages from the pool are used for actions like form filling and navigation.\n - Valid cookies are saved after login and reused for subsequent page acquisitions.\n - Users must explicitly release the page after use through the `releasePage` method.\n - Released pages are returned to the `headlessPool` for reuse.\n*/\n\nexport class HeadlessConnector implements Connector {\n async ready(connectionConfigs) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n ConnectionManager.logger.info('headless-connector connections are ready')\n }\n\n async connect(connection) {\n const {\n endpoint: uri = '1',\n params: {\n username = '',\n password = '',\n loginPagePath = '/login',\n loginApiUrl = null,\n usernameSelector = '#username',\n passwordSelector = '#password',\n submitSelector = '#submit',\n successSelector = null,\n shadowDomSelectors = '', // Comma separated shadow DOM selectors\n timeout = 15000, // Default timeout for operations\n retries = 3 // Default number of retries for login or page actions\n } = {}\n } = connection\n\n const loginInfo = {\n loginRequired: Boolean(username), // Determine if login is required\n username,\n password,\n loginPagePath,\n loginApiUrl,\n timeout,\n retries,\n loginSelectors: {\n usernameSelector,\n passwordSelector,\n submitSelector,\n successSelector,\n shadowDomSelectors: shadowDomSelectors\n .split(',')\n .map(selector => selector.trim())\n .filter(Boolean)\n }\n }\n\n async function acquireBrowser() {\n try {\n const pool = getHeadlessPool()\n const browser = await pool.acquire()\n return browser\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire browser:', error)\n throw error\n }\n }\n\n async function releaseBrowser(browser: Browser) {\n try {\n const pool = getHeadlessPool()\n await pool.release(browser)\n } catch (error) {\n ConnectionManager.logger.error('Failed to release browser:', error)\n }\n }\n\n ConnectionManager.addConnectionInstance(connection, {\n endpoint: connection.endpoint,\n params: connection.params,\n acquireSessionPage: async () => {\n const browser = await acquireBrowser()\n let page\n let cookies = connection.cookies\n\n try {\n page = await browser.newPage()\n\n await page.setRequestInterception(true)\n\n await page.setBypassCSP(true)\n\n await page.setUserAgent(\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.204 Safari/537.36'\n )\n\n await page.evaluateOnNewDocument(() => {\n Object.defineProperty(navigator, 'webdriver', { get: () => false })\n })\n\n await page.setExtraHTTPHeaders({\n 'Upgrade-Insecure-Requests': '0',\n 'accept-language': 'en-US,en;q=0.9',\n // 'upgrade-insecure-requests': '0',\n referer: uri\n })\n\n await page.setDefaultNavigationTimeout(timeout)\n\n page.on('console', async msg => {\n ConnectionManager.logger.info(`[browser ${msg.type()}] ${msg.text()}`)\n })\n\n page.on('request', request => {\n if (request.isInterceptResolutionHandled()) {\n return\n }\n\n const resourceType = request.resourceType()\n\n const headers = request.headers()\n if (headers['access-control-request-headers']) {\n const filteredHeaders = headers['access-control-request-headers']\n .split(',')\n .map(header => header.trim())\n .filter(header => header.toLowerCase() !== 'upgrade-insecure-requests') // 해당 헤더 제거\n\n if (filteredHeaders.length > 0) {\n headers['access-control-request-headers'] = filteredHeaders.join(', ')\n } else {\n delete headers['access-control-request-headers'] // 필요하면 전체 삭제\n }\n }\n\n // 일반적인 요청에서도 'upgrade-insecure-requests' 헤더 제거\n if (headers['upgrade-insecure-requests']) {\n delete headers['upgrade-insecure-requests']\n }\n\n if (['image', 'stylesheet', 'font'].includes(resourceType)) {\n request.abort() // 비필수 리소스 요청 차단\n } else {\n request.continue() // 나머지 요청은 진행\n }\n })\n\n page.on('requestfailed', request => {\n try {\n console.log('Request failed:')\n console.log(`- URL: ${request.url()}`)\n console.log(`- Method: ${request.method()}`)\n console.log(`- Failure Text: ${request.failure()?.errorText}`)\n console.log(`- Headers:`, request.headers())\n\n // POST 데이터 (필요한 경우)\n if (request.postData()) {\n console.log(`- Post Data: ${request.postData()}`)\n }\n } catch (error) {\n console.error('Error in requestfailed handler:', error)\n }\n })\n\n if (loginInfo.loginRequired) {\n // 현재 세션의 Authorization 헤더 확인\n const headers = await page.evaluate(() => {\n return fetch(window.location.href, { method: 'GET' })\n .then(response => response.headers.get('Authorization'))\n .catch(() => null)\n })\n\n if (headers) {\n ConnectionManager.logger.info('User is already logged in, skipping login process.')\n return page\n }\n\n if (cookies && isCookieValid(cookies)) {\n await this.applyCookiesAndVerifySession(page, cookies, loginInfo)\n return page\n }\n\n await this.performLogin(page, uri, loginInfo)\n cookies = await page.cookies()\n connection.cookies = cookies\n }\n\n return page\n } catch (error) {\n ConnectionManager.logger.error('Failed to acquire session page:', error)\n throw error\n }\n },\n releasePage: async (page: Page) => {\n try {\n if (page) {\n const browser = page.browser()\n await page.close()\n await releaseBrowser(browser)\n }\n } catch (error) {\n ConnectionManager.logger.error('Failed to release page:', error)\n }\n },\n acquireBrowser,\n releaseBrowser\n })\n\n ConnectionManager.logger.info(\n `headless-connector connection(${connection.name}:${connection.endpoint}) is connected`\n )\n }\n\n async applyCookiesAndVerifySession(page, cookies, loginInfo) {\n await page.setCookie(...cookies)\n await page.reload({ waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n if (loginInfo.loginRequired && loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Session invalid, login required')\n }\n }\n }\n\n async performLogin(page, uri, loginInfo) {\n for (let attempt = 1; attempt <= loginInfo.retries; attempt++) {\n try {\n await page.goto(`${uri}${loginInfo.loginPagePath}`, { waitUntil: 'networkidle2', timeout: loginInfo.timeout })\n\n const usernameInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.usernameSelector\n )\n const passwordInput = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.passwordSelector\n )\n const submitButton = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.submitSelector\n )\n\n if (!usernameInput || !passwordInput || !submitButton) {\n throw new Error('Failed to locate input elements in shadow DOM')\n }\n\n await usernameInput.type(loginInfo.username)\n await passwordInput.type(loginInfo.password)\n\n var loginApiUrl =\n loginInfo.loginApiUrl ||\n (await page.evaluate(button => {\n const form = button.closest('form')\n return form ? form.action : null\n }, submitButton))\n\n if (loginApiUrl && !loginApiUrl.startsWith('http')) {\n loginApiUrl = `${uri}${loginApiUrl}`\n }\n\n if (!loginApiUrl) {\n throw new Error('❌ Unable to detect login API URL!')\n }\n\n console.log('✅ Detected login API URL:', loginApiUrl)\n\n const [response] = await Promise.all([\n page.waitForResponse(response => {\n const url = response.url()\n const method = response.request().method()\n\n return url === loginApiUrl && method === 'POST' && [200, 201, 204, 302, 304].includes(response.status())\n }),\n page.evaluate(button => button.click(), submitButton),\n page.waitForNavigation({ waitUntil: 'networkidle2', timeout: loginInfo.timeout }) // 로그인 후 리디렉션 감지\n ])\n\n if (response) {\n const status = response.status()\n if (status >= 200 && status < 400) {\n ConnectionManager.logger.info(`Login successful with status code: ${status}`)\n return\n } else if (status >= 400) {\n throw new Error(`Login failed with status code: ${status}`)\n }\n } else {\n throw new Error('No response received during login')\n }\n\n if (loginInfo.loginSelectors.successSelector) {\n const success = await this.resolveShadowDom(\n page,\n loginInfo.loginSelectors.shadowDomSelectors,\n loginInfo.loginSelectors.successSelector\n )\n if (!success) {\n throw new Error('Login failed: Success selector not found')\n }\n }\n } catch (error) {\n ConnectionManager.logger.warn(`Login attempt ${attempt} failed:`, error)\n\n try {\n await page.screenshot({ path: `logs/login-failure-attempt-${attempt}.png` })\n } catch (error) {\n ConnectionManager.logger.error('Failed to capture screenshot:', error)\n }\n\n if (attempt === loginInfo.retries) {\n throw new Error(`Login failed after ${loginInfo.retries} attempts`)\n }\n }\n }\n }\n\n async resolveShadowDom(page, shadowSelectors, targetSelector) {\n let context\n\n if (!shadowSelectors || shadowSelectors.length === 0) {\n // No Shadow DOM path; use document root as the context\n context = page.mainFrame() // Puppeteer uses frames to represent document\n return context.$(targetSelector) // Search directly in the document root\n }\n\n context = page // Start with the page as the context\n for (const selector of shadowSelectors) {\n const shadowHost = await context.$(selector)\n if (!shadowHost) {\n throw new Error(`Shadow host not found: ${selector}`)\n }\n context = await page.evaluateHandle(host => host.shadowRoot, shadowHost)\n }\n return context.evaluateHandle((shadowRoot, selector) => shadowRoot.querySelector(selector), targetSelector)\n }\n\n async disconnect(connection) {\n ConnectionManager.removeConnectionInstance(connection)\n ConnectionManager.logger.info(`headless-connector connection(${connection.name}) is disconnected`)\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'username',\n label: 'username',\n useDomainAttribute: true\n },\n {\n type: 'password',\n name: 'password',\n label: 'password',\n useDomainAttribute: true\n },\n {\n type: 'string',\n name: 'loginPagePath',\n label: 'login-page-path'\n },\n {\n type: 'string',\n name: 'loginApiUrl',\n label: 'login-api-url'\n },\n {\n type: 'string',\n name: 'usernameSelector',\n label: 'username-selector'\n },\n {\n type: 'string',\n name: 'passwordSelector',\n label: 'password-selector'\n },\n {\n type: 'string',\n name: 'submitSelector',\n label: 'submit-selector'\n },\n {\n type: 'string',\n name: 'successSelector',\n label: 'success-selector'\n },\n {\n type: 'string',\n name: 'shadowDomSelectors',\n label: 'shadow-dom-selectors'\n },\n {\n type: 'number',\n name: 'timeout',\n label: 'timeout',\n value: 15000\n },\n {\n type: 'number',\n name: 'retries',\n label: 'maximum-retries',\n value: 3\n }\n ]\n }\n\n get taskPrefixes() {\n return ['headless']\n }\n\n get description() {\n return 'Headless Pool Connector with login capabilities'\n }\n\n get help() {\n return 'integration/connector/headless-connector'\n }\n}\n\nConnectionManager.registerConnector('headless-connector', new HeadlessConnector())\n\nfunction isCookieValid(cookies) {\n if (!cookies || cookies.length === 0) return false\n const now = Date.now() / 1000 // Current time in seconds\n return cookies.some(cookie => cookie.expires && cookie.expires > now)\n}\n"]}
@@ -8,6 +8,7 @@ export declare class MqttConnector implements Connector {
8
8
  type: string;
9
9
  name: string;
10
10
  label: string;
11
+ useDomainAttribute: boolean;
11
12
  }[];
12
13
  get taskPrefixes(): string[];
13
14
  get help(): string;
@@ -41,12 +41,14 @@ class MqttConnector {
41
41
  {
42
42
  type: 'string',
43
43
  name: 'user',
44
- label: 'user'
44
+ label: 'user',
45
+ useDomainAttribute: true
45
46
  },
46
47
  {
47
48
  type: 'password',
48
49
  name: 'password',
49
- label: 'password'
50
+ label: 'password',
51
+ useDomainAttribute: true
50
52
  }
51
53
  ];
52
54
  }
@@ -1 +1 @@
1
- {"version":3,"file":"mqtt-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/mqtt-connector.ts"],"names":[],"mappings":";;;;AACA,8DAAyD;AAGzD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,cAAc,EACjF,GAAG,CACJ,CAAA;QACH,CAAC;IACH,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,UAA2B;QAC1C,MAAM,EAAE,MAAM,EAAE,GAAG,sCAAiB,CAAC,wBAAwB,CAAC,UAAU,CAAC,CAAA;QAEzE,MAAM,IAAI,CAAC,MAAM,MAAM,CAAC,GAAG,EAAE,CAAC,CAAA;IAChC,CAAC;IAED,IAAI,aAAa;QACf,OAAO;YACL;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,MAAM;gBACZ,KAAK,EAAE,MAAM;aACd;YACD;gBACE,IAAI,EAAE,UAAU;gBAChB,IAAI,EAAE,UAAU;gBAChB,KAAK,EAAE,UAAU;aAClB;SACF,CAAA;IACH,CAAC;IAED,IAAI,YAAY;QACd,OAAO,CAAC,MAAM,CAAC,CAAA;IACjB,CAAC;IAED,IAAI,IAAI;QACN,OAAO,sCAAsC,CAAA;IAC/C,CAAC;CACF;AArED,sCAqEC;AAED,sCAAiB,CAAC,iBAAiB,CAAC,gBAAgB,EAAE,IAAI,aAAa,EAAE,CAAC,CAAA","sourcesContent":["import { Connector } from '../types'\nimport { ConnectionManager } from '../connection-manager'\nimport { InputConnection } from '../../service/connection/connection-type'\n\nimport mqtt from 'async-mqtt'\n\nexport class MqttConnector implements Connector {\n async ready(connectionConfigs: InputConnection[]) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n\n ConnectionManager.logger.info('mqtt-connector connections are ready')\n }\n\n async connect(connection: InputConnection) {\n const {\n endpoint: uri,\n params: { user, password }\n } = connection\n\n try {\n var client = null\n if (user && password) {\n client = await mqtt.connectAsync(uri, { username: user, password: password })\n } else {\n client = await mqtt.connectAsync(uri)\n }\n\n if (!client) {\n throw new Error(\n `the initialization of mqtt connector is failed. uri: ${uri}, user: ${user} password: ${password}`\n )\n }\n\n ConnectionManager.addConnectionInstance(connection, {\n client,\n connection\n })\n\n ConnectionManager.logger.info(`mqtt-connector connection(${connection.name}:${connection.endpoint}) is connected`)\n } catch (err) {\n ConnectionManager.logger.error(\n `mqtt-connector connection(${connection.name}:${connection.endpoint}) is failed.`,\n err\n )\n }\n }\n\n async disconnect(connection: InputConnection) {\n const { client } = ConnectionManager.removeConnectionInstance(connection)\n\n client && (await client.end())\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'user',\n label: 'user'\n },\n {\n type: 'password',\n name: 'password',\n label: 'password'\n }\n ]\n }\n\n get taskPrefixes() {\n return ['mqtt']\n }\n\n get help() {\n return 'integration/connector/mqtt-connector'\n }\n}\n\nConnectionManager.registerConnector('mqtt-connector', new MqttConnector())\n"]}
1
+ {"version":3,"file":"mqtt-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/mqtt-connector.ts"],"names":[],"mappings":";;;;AACA,8DAAyD;AAGzD,oEAA6B;AAE7B,MAAa,aAAa;IACxB,KAAK,CAAC,KAAK,CAAC,iBAAoC;QAC9C,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;QAEjE,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAA;IACvE,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAA2B;QACvC,MAAM,EACJ,QAAQ,EAAE,GAAG,EACb,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,EAC3B,GAAG,UAAU,CAAA;QAEd,IAAI,CAAC;YACH,IAAI,MAAM,GAAG,IAAI,CAAA;YACjB,IAAI,IAAI,IAAI,QAAQ,EAAE,CAAC;gBACrB,MAAM,GAAG,MAAM,oBAAI,CAAC,YAAY,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,CAAA;YAC/E,CAAC;iBAAM,CAAC;gBACN,MAAM,GAAG,MAAM,oBAAI,CAAC,YAAY,CAAC,G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AE,CAAC,CAAA","sourcesContent":["import { Connector } from '../types'\nimport { ConnectionManager } from '../connection-manager'\nimport { InputConnection } from '../../service/connection/connection-type'\n\nimport mqtt from 'async-mqtt'\n\nexport class MqttConnector implements Connector {\n async ready(connectionConfigs: InputConnection[]) {\n await Promise.all(connectionConfigs.map(this.connect.bind(this)))\n\n ConnectionManager.logger.info('mqtt-connector connections are ready')\n }\n\n async connect(connection: InputConnection) {\n const {\n endpoint: uri,\n params: { user, password }\n } = connection\n\n try {\n var client = null\n if (user && password) {\n client = await mqtt.connectAsync(uri, { username: user, password: password })\n } else {\n client = await mqtt.connectAsync(uri)\n }\n\n if (!client) {\n throw new Error(\n `the initialization of mqtt connector is failed. uri: ${uri}, user: ${user} password: ${password}`\n )\n }\n\n ConnectionManager.addConnectionInstance(connection, {\n client,\n connection\n })\n\n ConnectionManager.logger.info(`mqtt-connector connection(${connection.name}:${connection.endpoint}) is connected`)\n } catch (err) {\n ConnectionManager.logger.error(\n `mqtt-connector connection(${connection.name}:${connection.endpoint}) is failed.`,\n err\n )\n }\n }\n\n async disconnect(connection: InputConnection) {\n const { client } = ConnectionManager.removeConnectionInstance(connection)\n\n client && (await client.end())\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'user',\n label: 'user',\n useDomainAttribute: true\n },\n {\n type: 'password',\n name: 'password',\n label: 'password',\n useDomainAttribute: true\n }\n ]\n }\n\n get taskPrefixes() {\n return ['mqtt']\n }\n\n get help() {\n return 'integration/connector/mqtt-connector'\n }\n}\n\nConnectionManager.registerConnector('mqtt-connector', new MqttConnector())\n"]}
@@ -8,6 +8,7 @@ export declare class MssqlConnector implements Connector {
8
8
  type: string;
9
9
  name: string;
10
10
  label: string;
11
+ useDomainAttribute: boolean;
11
12
  placeholder?: undefined;
12
13
  property?: undefined;
13
14
  value?: undefined;
@@ -16,6 +17,7 @@ export declare class MssqlConnector implements Connector {
16
17
  name: string;
17
18
  placeholder: string;
18
19
  label: string;
20
+ useDomainAttribute?: undefined;
19
21
  property?: undefined;
20
22
  value?: undefined;
21
23
  } | {
@@ -25,6 +27,7 @@ export declare class MssqlConnector implements Connector {
25
27
  property: {
26
28
  options: string[];
27
29
  };
30
+ useDomainAttribute?: undefined;
28
31
  placeholder?: undefined;
29
32
  value?: undefined;
30
33
  } | {
@@ -33,6 +36,7 @@ export declare class MssqlConnector implements Connector {
33
36
  placeholder: string;
34
37
  label: string;
35
38
  value: number;
39
+ useDomainAttribute?: undefined;
36
40
  property?: undefined;
37
41
  })[];
38
42
  get taskPrefixes(): string[];
@@ -80,12 +80,14 @@ class MssqlConnector {
80
80
  {
81
81
  type: 'string',
82
82
  name: 'user',
83
- label: 'user'
83
+ label: 'user',
84
+ useDomainAttribute: true
84
85
  },
85
86
  {
86
87
  type: 'password',
87
88
  name: 'password',
88
- label: 'password'
89
+ label: 'password',
90
+ useDomainAttribute: true
89
91
  },
90
92
  {
91
93
  type: 'string',
@@ -1 +1 @@
1
- {"version":3,"file":"mssql-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/mssql-connector.ts"],"names":[],"mappings":";;;AAAA,6CAA4C;AAE5C,8DAAyD;AAIzD,IAAI,CAAC;IACH,IAAI,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;AAC9B,CAAC;AAAC,OAAO,GAAG,EAAE,CAAC;IACb,YAAM,CAAC,KAAK,CAAC,6BAA6B,EAAE,GAAG,CAAC,CAAA;AAClD,CAAC;AAED,MAAa,cAAc;IACzB,KAAK,CAAC,KAAK,CAAC,iBAAoC;QAC9C,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAA;QAEtD,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,uCAAuC,CAAC,CAAA;IACxE,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAA2B;QACvC,MAAM,EACJ,QAAQ,EACR,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EA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CAAC,CAAA;IACxD,CAAC;IAED,IAAI,aAAa;QACf,OAAO;YACL;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,MAAM;gBACZ,KAAK,EAAE,MAAM;aACd;YACD;gBACE,IAAI,EAAE,UAAU;gBAChB,IAAI,EAAE,UAAU;gBAChB,KAAK,EAAE,UAAU;aAClB;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,UAAU;gBAChB,WAAW,EAAE,KAAK;gBAClB,KAAK,EAAE,UAAU;aAClB;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,SAAS;gBACf,KAAK,EAAE,SAAS;gBAChB,QAAQ,EAAE;oBACR,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;iBACpB;aACF;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,SAAS;gBACf,WAAW,EAAE,8BAA8B;gBAC3C,KAAK,EAAE,UAAU;gBACjB,KAAK,EAAE,CAAC;aACT;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,SAAS;gBACf,WAAW,EAAE,8BAA8B;gBAC3C,KAAK,EAAE,UAAU;gBACjB,KAAK,EAAE,CAAC;aACT;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,wBAAwB;gBAC9B,KAAK,EAAE,0BAA0B;gBACjC,QAAQ,EAAE;oBACR,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;iBACpB;aACF;SACF,CAAA;IACH,CAAC;IAED,IAAI,YAAY;QACd,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,CAAA;IAC9B,CAAC;IAED,IAAI,IAAI;QACN,OAAO,uCAAuC,CAAA;IAChD,CAAC;CACF;AAzID,wCAyIC;AAED,sCAAiB,CAAC,iBAAiB,CAAC,iBAAiB,EAAE,IAAI,cAAc,EAAE,CAAC,CAAA","sourcesContent":["import { logger } from '@things-factory/env'\n\nimport { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { InputConnection } from '../../service/connection/connection-type'\n\ntry {\n var mssql = require('mssql')\n} catch (err) {\n logger.error('mssql module loading failed', err)\n}\n\nexport class MssqlConnector implements Connector {\n async ready(connectionConfigs: InputConnection[]) {\n await Promise.all(connectionConfigs.map(this.connect))\n\n ConnectionManager.logger.info('mssql-connector connections are ready')\n }\n\n async connect(connection: InputConnection) {\n const {\n endpoint,\n params: { user, password, database, poolMin = 0, poolMax = 4, encrypt = 'Y', trustServerCertificate }\n } = connection\n\n const [host, port = 1433] = endpoint.split(':')\n\n if (!mssql) {\n throw new Error('mssql module loading failed')\n }\n\n const pool = await mssql.connect({\n user,\n password,\n server: host,\n port: Number(port),\n database,\n pool: {\n max: Math.max(2, poolMax),\n min: Math.max(0, poolMin),\n idleTimeoutMillis: 30000\n },\n options: {\n encrypt: encrypt === 'Y',\n trustServerCertificate: trustServerCertificate === 'Y'\n }\n })\n\n ConnectionManager.addConnectionInstance(connection, {\n query: async (query, params) => {\n var result = await pool.request().query(query)\n return result.recordset\n },\n execute: async (procedure, params) => {\n let request = pool.request()\n\n Object.keys(params).forEach(key => {\n let { dir, type, val } = params[key]\n\n if (dir === 'in' || dir === 'inout') {\n request.input(key, type, val)\n } else if (dir === 'out') {\n request.output(key, type)\n } else {\n console.error(`Invalid parameter direction(${dir}) for mssql stored procedure`)\n }\n })\n\n var result = await request.execute(procedure)\n return result\n },\n close: () => {\n pool.close()\n }\n })\n\n ConnectionManager.logger.info(`MSSql Database(${connection.name}:${database}) at ${endpoint} connected.`)\n }\n\n async disconnect(connection: InputConnection) {\n var client = ConnectionManager.getConnectionInstance(connection)\n try {\n await client.close()\n ConnectionManager.logger.info(`MSSql Database(${connection.name}) closed.`)\n } catch (e) {\n ConnectionManager.logger.error(e)\n }\n\n ConnectionManager.removeConnectionInstance(connection)\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'user',\n label: 'user'\n },\n {\n type: 'password',\n name: 'password',\n label: 'password'\n },\n {\n type: 'string',\n name: 'database',\n placeholder: 'SID',\n label: 'database'\n },\n {\n type: 'select',\n name: 'encrypt',\n label: 'encrypt',\n property: {\n options: ['Y', 'N']\n }\n },\n {\n type: 'number',\n name: 'poolMin',\n placeholder: 'minimum connection-pool size',\n label: 'pool-min',\n value: 0\n },\n {\n type: 'number',\n name: 'poolMax',\n placeholder: 'maximum connection-pool size',\n label: 'pool-max',\n value: 4\n },\n {\n type: 'select',\n name: 'trustServerCertificate',\n label: 'trust-server-certificate',\n property: {\n options: ['Y', 'N']\n }\n }\n ]\n }\n\n get taskPrefixes() {\n return ['database', 'mssql']\n }\n\n get help() {\n return 'integration/connector/mssql-connector'\n }\n}\n\nConnectionManager.registerConnector('mssql-connector', new MssqlConnector())\n"]}
1
+ {"version":3,"file":"mssql-connector.js","sourceRoot":"","sources":["../../../server/engine/connector/mssql-connector.ts"],"names":[],"mappings":";;;AAAA,6CAA4C;AAE5C,8DAAyD;AAIzD,IAAI,CAAC;IACH,IAAI,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;AAC9B,CAAC;AAAC,OAAO,GAAG,EAAE,CAAC;IACb,YAAM,CAAC,KAAK,CAAC,6BAA6B,EAAE,GAAG,CAAC,CAAA;AAClD,CAAC;AAED,MAAa,cAAc;IACzB,KAAK,CAAC,KAAK,CAAC,iBAAoC;QAC9C,MAAM,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAA;QAEtD,sCAAiB,CAAC,MAAM,CAAC,IAAI,CAAC,uCAAuC,CAAC,CAAA;IACxE,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,UAA2B;QACvC,MAAM,EACJ,QAAQ,EACR,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,GAAG,EAAE,sBAAsB,EAAE,EACt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BACZ,KAAK,EAAE,MAAM;gBACb,kBAAkB,EAAE,IAAI;aACzB;YACD;gBACE,IAAI,EAAE,UAAU;gBAChB,IAAI,EAAE,UAAU;gBAChB,KAAK,EAAE,UAAU;gBACjB,kBAAkB,EAAE,IAAI;aACzB;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,UAAU;gBAChB,WAAW,EAAE,KAAK;gBAClB,KAAK,EAAE,UAAU;aAClB;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,SAAS;gBACf,KAAK,EAAE,SAAS;gBAChB,QAAQ,EAAE;oBACR,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;iBACpB;aACF;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,SAAS;gBACf,WAAW,EAAE,8BAA8B;gBAC3C,KAAK,EAAE,UAAU;gBACjB,KAAK,EAAE,CAAC;aACT;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,SAAS;gBACf,WAAW,EAAE,8BAA8B;gBAC3C,KAAK,EAAE,UAAU;gBACjB,KAAK,EAAE,CAAC;aACT;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,wBAAwB;gBAC9B,KAAK,EAAE,0BAA0B;gBACjC,QAAQ,EAAE;oBACR,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;iBACpB;aACF;SACF,CAAA;IACH,CAAC;IAED,IAAI,YAAY;QACd,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,CAAA;IAC9B,CAAC;IAED,IAAI,IAAI;QACN,OAAO,uCAAuC,CAAA;IAChD,CAAC;CACF;AA3ID,wCA2IC;AAED,sCAAiB,CAAC,iBAAiB,CAAC,iBAAiB,EAAE,IAAI,cAAc,EAAE,CAAC,CAAA","sourcesContent":["import { logger } from '@things-factory/env'\n\nimport { ConnectionManager } from '../connection-manager'\nimport { Connector } from '../types'\nimport { InputConnection } from '../../service/connection/connection-type'\n\ntry {\n var mssql = require('mssql')\n} catch (err) {\n logger.error('mssql module loading failed', err)\n}\n\nexport class MssqlConnector implements Connector {\n async ready(connectionConfigs: InputConnection[]) {\n await Promise.all(connectionConfigs.map(this.connect))\n\n ConnectionManager.logger.info('mssql-connector connections are ready')\n }\n\n async connect(connection: InputConnection) {\n const {\n endpoint,\n params: { user, password, database, poolMin = 0, poolMax = 4, encrypt = 'Y', trustServerCertificate }\n } = connection\n\n const [host, port = 1433] = endpoint.split(':')\n\n if (!mssql) {\n throw new Error('mssql module loading failed')\n }\n\n const pool = await mssql.connect({\n user,\n password,\n server: host,\n port: Number(port),\n database,\n pool: {\n max: Math.max(2, poolMax),\n min: Math.max(0, poolMin),\n idleTimeoutMillis: 30000\n },\n options: {\n encrypt: encrypt === 'Y',\n trustServerCertificate: trustServerCertificate === 'Y'\n }\n })\n\n ConnectionManager.addConnectionInstance(connection, {\n query: async (query, params) => {\n var result = await pool.request().query(query)\n return result.recordset\n },\n execute: async (procedure, params) => {\n let request = pool.request()\n\n Object.keys(params).forEach(key => {\n let { dir, type, val } = params[key]\n\n if (dir === 'in' || dir === 'inout') {\n request.input(key, type, val)\n } else if (dir === 'out') {\n request.output(key, type)\n } else {\n console.error(`Invalid parameter direction(${dir}) for mssql stored procedure`)\n }\n })\n\n var result = await request.execute(procedure)\n return result\n },\n close: () => {\n pool.close()\n }\n })\n\n ConnectionManager.logger.info(`MSSql Database(${connection.name}:${database}) at ${endpoint} connected.`)\n }\n\n async disconnect(connection: InputConnection) {\n var client = ConnectionManager.getConnectionInstance(connection)\n try {\n await client.close()\n ConnectionManager.logger.info(`MSSql Database(${connection.name}) closed.`)\n } catch (e) {\n ConnectionManager.logger.error(e)\n }\n\n ConnectionManager.removeConnectionInstance(connection)\n }\n\n get parameterSpec() {\n return [\n {\n type: 'string',\n name: 'user',\n label: 'user',\n useDomainAttribute: true\n },\n {\n type: 'password',\n name: 'password',\n label: 'password',\n useDomainAttribute: true\n },\n {\n type: 'string',\n name: 'database',\n placeholder: 'SID',\n label: 'database'\n },\n {\n type: 'select',\n name: 'encrypt',\n label: 'encrypt',\n property: {\n options: ['Y', 'N']\n }\n },\n {\n type: 'number',\n name: 'poolMin',\n placeholder: 'minimum connection-pool size',\n label: 'pool-min',\n value: 0\n },\n {\n type: 'number',\n name: 'poolMax',\n placeholder: 'maximum connection-pool size',\n label: 'pool-max',\n value: 4\n },\n {\n type: 'select',\n name: 'trustServerCertificate',\n label: 'trust-server-certificate',\n property: {\n options: ['Y', 'N']\n }\n }\n ]\n }\n\n get taskPrefixes() {\n return ['database', 'mssql']\n }\n\n get help() {\n return 'integration/connector/mssql-connector'\n }\n}\n\nConnectionManager.registerConnector('mssql-connector', new MssqlConnector())\n"]}