codeapp-js 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/AI/skills/autoreview/SKILL.md +69 -0
  2. package/AI/skills/connections/SKILL.md +4 -4
  3. package/AI/skills/dataverse/SKILL.md +4 -2
  4. package/AI/skills/frontend-design/SKILL.md +32 -20
  5. package/AI/skills/keyvault/SKILL.md +139 -0
  6. package/AI/skills/office365-groups/SKILL.md +46 -25
  7. package/AI/skills/office365-outlook/SKILL.md +56 -25
  8. package/AI/skills/office365-users/SKILL.md +41 -36
  9. package/AI/skills/sharepoint/SKILL.md +174 -31
  10. package/AI/skills/start/SKILL.md +38 -30
  11. package/codeApp/dist/connectors/autoreview.js +1654 -0
  12. package/codeApp/dist/connectors/office365groups.js +2995 -432
  13. package/{examples/outlook Demo/.power/schemas/office365/office365.Schema.json → codeApp/dist/connectors/office365outlook.js} +7439 -16
  14. package/codeApp/dist/connectors/office365users.js +2990 -349
  15. package/codeApp/dist/connectors/sharepoint.js +529 -308
  16. package/examples/combined demo/dist/connectors/office365outlook.js +28521 -0
  17. package/examples/combined demo/dist/connectors/office365users.js +3154 -0
  18. package/examples/combined demo/dist/index.js +2 -6
  19. package/examples/combined demo/power.config.json +1 -1
  20. package/examples/groups Demo/{.power/schemas/office365groups/office365groups.Schema.json → dist/connectors/office365groups.js } +3205 -2204
  21. package/examples/groups Demo/dist/index.js +1 -5
  22. package/examples/groups Demo/power.config.json +1 -1
  23. package/examples/myProfile/dist/connectors/office365users.js +3154 -0
  24. package/examples/myProfile/dist/index.js +1 -5
  25. package/examples/myProfile/power.config.json +1 -1
  26. package/examples/outlook Demo/dist/connectors/office365outlook.js +28521 -0
  27. package/examples/outlook Demo/dist/index.js +2 -5
  28. package/examples/outlook Demo/power.config.json +1 -1
  29. package/examples/sharePoint Demo/dist/connectors/sharepoint.js +687 -0
  30. package/examples/sharePoint Demo/dist/index.js +86 -127
  31. package/examples/sharePoint Demo/power.config.json +1 -1
  32. package/package.json +1 -1
  33. package/codeApp/.power/schemas/appschemas/dataSourcesInfo.ts +0 -6275
  34. package/codeApp/.power/schemas/jira/jira.Schema.json +0 -6903
  35. package/codeApp/.power/schemas/keyvault/keyvault.Schema.json +0 -1600
  36. package/codeApp/.power/schemas/office365groups/office365groups.Schema.json +0 -2204
  37. package/codeApp/.power/schemas/teams/teams.Schema.json +0 -11112
  38. package/codeApp/dist/connectors/outlook.js +0 -1393
  39. package/codeApp/src/generated/index.ts +0 -12
  40. package/codeApp/src/generated/models/AzureKeyVaultModel.ts +0 -107
  41. package/codeApp/src/generated/models/JiraModel.ts +0 -501
  42. package/codeApp/src/generated/models/Office365GroupsModel.ts +0 -363
  43. package/codeApp/src/generated/models/Office365OutlookModel.ts +0 -2046
  44. package/codeApp/src/generated/models/Office365UsersModel.ts +0 -254
  45. package/codeApp/src/generated/services/AzureKeyVaultService.ts +0 -257
  46. package/codeApp/src/generated/services/JiraService.ts +0 -1124
  47. package/codeApp/src/generated/services/Office365GroupsService.ts +0 -326
  48. package/codeApp/src/generated/services/Office365OutlookService.ts +0 -2476
  49. package/codeApp/src/generated/services/Office365UsersService.ts +0 -358
  50. package/examples/apps/kanban/dist/dataverse.js +0 -94
  51. package/examples/apps/kanban/dist/environmentVar.js +0 -55
  52. package/examples/apps/kanban/dist/index.css +0 -605
  53. package/examples/apps/kanban/dist/index.html +0 -21
  54. package/examples/apps/kanban/dist/index.js +0 -860
  55. package/examples/apps/kanban/dist/office365groups.js +0 -97
  56. package/examples/apps/kanban/dist/office365users.js +0 -451
  57. package/examples/apps/kanban/dist/outlook.js +0 -162
  58. package/examples/apps/kanban/dist/power-apps-data.js +0 -2953
  59. package/examples/apps/kanban/dist/sharepoint.js +0 -435
  60. package/examples/apps/kanban/power.config.json +0 -35
  61. package/examples/apps/kanban/src/generated/index.ts +0 -14
  62. package/examples/apps/kanban/src/generated/models/Office365GroupsModel.ts +0 -363
  63. package/examples/apps/kanban/src/generated/models/Office365OutlookModel.ts +0 -2046
  64. package/examples/apps/kanban/src/generated/models/Office365UsersModel.ts +0 -254
  65. package/examples/apps/kanban/src/generated/services/Office365GroupsService.ts +0 -326
  66. package/examples/apps/kanban/src/generated/services/Office365OutlookService.ts +0 -2476
  67. package/examples/apps/kanban/src/generated/services/Office365UsersService.ts +0 -358
  68. package/examples/apps/planning Poker/additional files/AgilePoker_1_0_0_1.zip +0 -0
  69. package/examples/apps/planning Poker/additional files/PokerTables_1_0_0_1.zip +0 -0
  70. package/examples/apps/planning Poker/additional files/customizations (tables).xml +0 -6429
  71. package/examples/apps/planning Poker/additional files/dataverse-tables.json +0 -165
  72. package/examples/apps/planning Poker/additional files/readme.md +0 -122
  73. package/examples/apps/planning Poker/dist/dataverse.js +0 -78
  74. package/examples/apps/planning Poker/dist/index.html +0 -198
  75. package/examples/apps/planning Poker/dist/index.js +0 -955
  76. package/examples/apps/planning Poker/dist/power-apps-data.js +0 -2953
  77. package/examples/apps/planning Poker/dist/styles.css +0 -815
  78. package/examples/apps/planning Poker/power.config.json +0 -50
  79. package/examples/apps/solution explorer/dist/codeapp.js +0 -1098
  80. package/examples/apps/solution explorer/dist/icon-512.png +0 -0
  81. package/examples/apps/solution explorer/dist/index.html +0 -80
  82. package/examples/apps/solution explorer/dist/index.js +0 -735
  83. package/examples/apps/solution explorer/dist/power-apps-data.js +0 -3007
  84. package/examples/apps/solution explorer/dist/styles.css +0 -571
  85. package/examples/apps/solution explorer/power.config.json +0 -151
  86. package/examples/apps/todo/dist/dataverse.js +0 -64
  87. package/examples/apps/todo/dist/icon192.png +0 -0
  88. package/examples/apps/todo/dist/index.html +0 -75
  89. package/examples/apps/todo/dist/index.js +0 -9
  90. package/examples/apps/todo/dist/power-apps-data.js +0 -2953
  91. package/examples/apps/todo/dist/renderer.js +0 -375
  92. package/examples/apps/todo/dist/styles.css +0 -691
  93. package/examples/apps/todo/power.config.json +0 -35
  94. package/examples/combined demo/.power/schemas/appschemas/dataSourcesInfo.ts +0 -6275
  95. package/examples/combined demo/.power/schemas/jira/jira.Schema.json +0 -6903
  96. package/examples/combined demo/.power/schemas/keyvault/keyvault.Schema.json +0 -1600
  97. package/examples/combined demo/.power/schemas/teams/teams.Schema.json +0 -11112
  98. package/examples/combined demo/dist/office365users.js +0 -513
  99. package/examples/combined demo/dist/outlook.js +0 -1393
  100. package/examples/combined demo/src/generated/index.ts +0 -12
  101. package/examples/combined demo/src/generated/models/AzureKeyVaultModel.ts +0 -107
  102. package/examples/combined demo/src/generated/models/JiraModel.ts +0 -501
  103. package/examples/combined demo/src/generated/models/Office365GroupsModel.ts +0 -363
  104. package/examples/combined demo/src/generated/models/Office365OutlookModel.ts +0 -2046
  105. package/examples/combined demo/src/generated/models/Office365UsersModel.ts +0 -254
  106. package/examples/combined demo/src/generated/services/AzureKeyVaultService.ts +0 -257
  107. package/examples/combined demo/src/generated/services/JiraService.ts +0 -1124
  108. package/examples/combined demo/src/generated/services/Office365GroupsService.ts +0 -326
  109. package/examples/combined demo/src/generated/services/Office365OutlookService.ts +0 -2476
  110. package/examples/combined demo/src/generated/services/Office365UsersService.ts +0 -358
  111. package/examples/groups Demo/.power/schemas/appschemas/dataSourcesInfo.ts +0 -613
  112. package/examples/groups Demo/dist/office365groups.js +0 -642
  113. package/examples/groups Demo/src/generated/index.ts +0 -10
  114. package/examples/groups Demo/src/generated/models/Office365GroupsModel.ts +0 -363
  115. package/examples/groups Demo/src/generated/services/Office365GroupsService.ts +0 -326
  116. package/examples/myProfile/dist/office365users.js +0 -517
  117. package/examples/outlook Demo/.power/schemas/appschemas/dataSourcesInfo.ts +0 -6512
  118. package/examples/outlook Demo/dist/outlook.js +0 -1393
  119. package/examples/outlook Demo/src/generated/index.ts +0 -10
  120. package/examples/outlook Demo/src/generated/models/Office365OutlookModel.ts +0 -2046
  121. package/examples/outlook Demo/src/generated/services/Office365OutlookService.ts +0 -2476
  122. package/examples/sharePoint Demo/dist/sharepoint.js +0 -466
  123. package/examples/sharePoint Demo/src/generated/index.ts +0 -14
  124. package/examples/sharePoint Demo/src/generated/models/Office365GroupsModel.ts +0 -363
  125. package/examples/sharePoint Demo/src/generated/models/Office365OutlookModel.ts +0 -2046
  126. package/examples/sharePoint Demo/src/generated/models/Office365UsersModel.ts +0 -254
  127. package/examples/sharePoint Demo/src/generated/services/Office365GroupsService.ts +0 -326
  128. package/examples/sharePoint Demo/src/generated/services/Office365OutlookService.ts +0 -2476
  129. package/examples/sharePoint Demo/src/generated/services/Office365UsersService.ts +0 -358
  130. package/readme.md +0 -590
@@ -1,2953 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
-
5
- // node_modules/@microsoft/power-apps/lib/internal/plugins/DefaultPowerAppsBridge.js
6
- var DefaultPowerAppsBridge = class {
7
- constructor() {
8
- __publicField(this, "_antiCSRFToken");
9
- __publicField(this, "_callbacks", {});
10
- __publicField(this, "_currentCallbackId", 0);
11
- __publicField(this, "_instanceId", Date.now().toString());
12
- __publicField(this, "_messageChannel", new window.MessageChannel());
13
- __publicField(this, "_postMessageQueue", []);
14
- __publicField(this, "_postMessageSource");
15
- __publicField(this, "_handleMessageEvent", (messageEvent) => {
16
- const message = messageEvent.data;
17
- if (message && typeof message.isPluginCall === "boolean") {
18
- if (message.isPluginCall) {
19
- const callbackId = message.callbackId;
20
- const status = message.status;
21
- const args = message.args;
22
- const keepCallback = message.keepCallback;
23
- try {
24
- const callback = this._callbacks[callbackId];
25
- if (keepCallback) {
26
- if (callback && callback.onUpdate) {
27
- callback.onUpdate(message.args?.[0]);
28
- }
29
- } else {
30
- if (callback) {
31
- if (status === 1) {
32
- callback.resolve(args[0]);
33
- } else if (status !== 0) {
34
- callback.reject(args);
35
- }
36
- }
37
- if (!keepCallback) {
38
- delete this._callbacks[callbackId];
39
- }
40
- }
41
- } catch (error) {
42
- console.error(error);
43
- }
44
- }
45
- } else if (message && message.messageType === "initCommunication") {
46
- this._antiCSRFToken = message.antiCSRFToken;
47
- this._postMessageSource = this._messageChannel.port1;
48
- if (this._postMessageSource) {
49
- for (let i = 0; i < this._postMessageQueue.length; i++) {
50
- this._postMessageQueue[i].antiCSRFToken = this._antiCSRFToken;
51
- this._postMessageSource.postMessage(this._postMessageQueue[i]);
52
- }
53
- }
54
- }
55
- });
56
- }
57
- async initialize() {
58
- this._messageChannel.port1.onmessage = this._handleMessageEvent;
59
- window.parent.postMessage({
60
- messageType: "initCommunicationWithPort",
61
- instanceId: this._instanceId
62
- }, "*", [this._messageChannel.port2]);
63
- }
64
- async executePluginAsync(pluginName, pluginAction, params = [], onUpdate) {
65
- return new Promise((resolve, reject) => {
66
- const callbackId = this._getCallbackId(pluginName);
67
- this._callbacks[callbackId] = { resolve, reject, onUpdate };
68
- this._sendMessage({
69
- isPluginCall: true,
70
- callbackId,
71
- service: pluginName,
72
- action: pluginAction,
73
- actionArgs: params,
74
- antiCSRFToken: this._antiCSRFToken
75
- });
76
- });
77
- }
78
- _sendMessage(message) {
79
- if (!this._postMessageSource) {
80
- this._postMessageQueue.push(message);
81
- } else {
82
- this._postMessageSource.postMessage(message);
83
- }
84
- }
85
- _getCallbackId(pluginName) {
86
- return "instanceId=" + this._instanceId + "_" + pluginName + this._currentCallbackId++;
87
- }
88
- };
89
-
90
- // node_modules/@microsoft/power-apps/lib/internal/plugins/PluginBridge.js
91
- var bridgePromise;
92
- async function executePluginAsync(pluginName, pluginAction, params = [], update) {
93
- const powerAppsBridge = await getBridge();
94
- return powerAppsBridge.executePluginAsync(pluginName, pluginAction, params, update);
95
- }
96
- async function getBridge() {
97
- if (!bridgePromise) {
98
- bridgePromise = new Promise(async (resolve, reject) => {
99
- try {
100
- const bridge = window && window.powerAppsBridge ? window.powerAppsBridge : new DefaultPowerAppsBridge();
101
- await bridge.initialize();
102
- resolve(bridge);
103
- } catch (error) {
104
- reject(error);
105
- }
106
- });
107
- }
108
- return bridgePromise;
109
- }
110
-
111
- // node_modules/@microsoft/power-apps/lib/app/ContextProvider.js
112
- var context;
113
- async function getContext() {
114
- if (context) {
115
- return context;
116
- }
117
- context = await executePluginAsync("AppLifecycle", "getContext");
118
- return context;
119
- }
120
-
121
- // node_modules/@microsoft/power-apps/lib/internal/plugins/SendMessage/IncompatibleMessageReceiver.js
122
- var IncompatibleMessageReceiver = class {
123
- constructor(versionInfo, incompatibilityDescription) {
124
- __publicField(this, "versionInfo");
125
- __publicField(this, "incompatibilityDescription");
126
- __publicField(this, "isCompatible", false);
127
- this.versionInfo = versionInfo;
128
- this.incompatibilityDescription = incompatibilityDescription;
129
- }
130
- };
131
-
132
- // node_modules/@microsoft/power-apps/lib/internal/plugins/SendMessage/SendMessageOperation.js
133
- var SendMessageOperation = class {
134
- constructor(resultPromise, sendUpdate) {
135
- __publicField(this, "resultPromise");
136
- __publicField(this, "sendUpdate");
137
- /**
138
- * When completed is false onMessageReceived and sendUpdate will be visible.
139
- * When completed is true then these are hidden.
140
- */
141
- __publicField(this, "completed", false);
142
- __publicField(this, "onMessageReceived");
143
- this.resultPromise = resultPromise;
144
- this.sendUpdate = sendUpdate;
145
- }
146
- };
147
-
148
- // node_modules/@microsoft/power-apps/lib/internal/plugins/SendMessage/CompatibleMessageReceiver.js
149
- var CompatibleMessageReceiver = class {
150
- constructor(_receiverName, versionInfo) {
151
- __publicField(this, "_receiverName");
152
- __publicField(this, "versionInfo");
153
- __publicField(this, "isCompatible", true);
154
- this._receiverName = _receiverName;
155
- this.versionInfo = versionInfo;
156
- }
157
- async sendMessage(message, onMessageReceived) {
158
- let resolveOperationPromise;
159
- let rejectOperationPromise;
160
- const operationPromise = new Promise((resolve, reject) => {
161
- resolveOperationPromise = resolve;
162
- rejectOperationPromise = reject;
163
- });
164
- const correlationId = crypto.randomUUID();
165
- const handleMessage = (compatibleReceiverMessage) => {
166
- try {
167
- if (sendMessageOperation.completed) {
168
- return;
169
- }
170
- if (compatibleReceiverMessage) {
171
- if (compatibleReceiverMessage.isUpdate) {
172
- if (sendMessageOperation.onMessageReceived) {
173
- try {
174
- sendMessageOperation.onMessageReceived(compatibleReceiverMessage.message);
175
- } catch (error) {
176
- sendMessageOperation.completed = true;
177
- rejectOperationPromise(error);
178
- }
179
- } else {
180
- sendMessageOperation.completed = true;
181
- rejectOperationPromise(new Error(`Native receiver expected a message handler, but no handler was supplied. Message: ${compatibleReceiverMessage.message}`));
182
- }
183
- } else {
184
- sendMessageOperation.completed = true;
185
- resolveOperationPromise(compatibleReceiverMessage.message);
186
- }
187
- return;
188
- }
189
- } catch {
190
- }
191
- sendMessageOperation.completed = true;
192
- resolveOperationPromise(compatibleReceiverMessage.message);
193
- };
194
- const handleError = (error) => {
195
- sendMessageOperation.completed = true;
196
- rejectOperationPromise(error);
197
- };
198
- const sendUpdate = (updateMessage) => {
199
- if (sendMessageOperation.completed) {
200
- throw new Error("Tried to send update for completed operation.");
201
- }
202
- executePluginAsync("SendMessagePlugin", "sendMessage", [
203
- this._receiverName,
204
- updateMessage,
205
- correlationId
206
- ]);
207
- };
208
- const sendMessageOperation = new SendMessageOperation(operationPromise, sendUpdate);
209
- sendMessageOperation.onMessageReceived = onMessageReceived;
210
- try {
211
- await executePluginAsync("SendMessagePlugin", "sendMessage", [this._receiverName, message, correlationId], (response) => {
212
- handleMessage(response);
213
- });
214
- } catch (error) {
215
- handleError(error);
216
- }
217
- return sendMessageOperation;
218
- }
219
- };
220
-
221
- // node_modules/@microsoft/power-apps/lib/internal/plugins/SendMessage/SendMessage.js
222
- var SendMessage = class _SendMessage {
223
- static createInstanceAsync() {
224
- return Promise.resolve(new _SendMessage());
225
- }
226
- async getMessageReceiverAsync(receiverName, isCompatibleChecker) {
227
- const versionInfo = await this._getVersionInfo(receiverName);
228
- if (versionInfo) {
229
- const compatibilityCheckerResult = isCompatibleChecker(versionInfo);
230
- if (compatibilityCheckerResult.isCompatible === false) {
231
- return new IncompatibleMessageReceiver(versionInfo, compatibilityCheckerResult.incompatibilityDescription || "");
232
- } else {
233
- return new CompatibleMessageReceiver(receiverName, versionInfo);
234
- }
235
- } else {
236
- return new IncompatibleMessageReceiver(void 0, `No receiver ${receiverName} registered.`);
237
- }
238
- }
239
- async _getVersionInfo(receiverName) {
240
- const result = await executePluginAsync("SendMessagePlugin", "getVersionInfo", [receiverName]);
241
- return result;
242
- }
243
- };
244
-
245
- // node_modules/@microsoft/power-apps/lib/telemetry/LoggerManager.js
246
- var loggerInstance;
247
- async function initializeLogger(logger) {
248
- loggerInstance = logger;
249
- const sendMessagePlugin = await SendMessage.createInstanceAsync();
250
- const receiver = await sendMessagePlugin.getMessageReceiverAsync("PowerApps.AppMonitorReceiver", (versionInfo) => {
251
- let isCompatible = false;
252
- if (versionInfo === "1.0.0") {
253
- isCompatible = true;
254
- }
255
- return { isCompatible };
256
- });
257
- if (receiver.isCompatible) {
258
- await receiver.sendMessage("initialize", (message) => {
259
- const parsedMessage = JSON.parse(message);
260
- if (parsedMessage.metrics) {
261
- for (const metric of parsedMessage.metrics) {
262
- loggerInstance.logMetric?.(metric);
263
- }
264
- }
265
- });
266
- }
267
- }
268
-
269
- // node_modules/@microsoft/power-apps/lib/telemetry/Performance.js
270
- function getAppLoadedPerformanceData() {
271
- const performanceApi = new PerformanceApi();
272
- const perfData = {
273
- appTimeOrigin: performanceApi.timeOrigin
274
- };
275
- const navigationTimingEntries = performanceApi.getEntriesByType("navigation");
276
- const navigationTiming = navigationTimingEntries[0];
277
- if (navigationTiming) {
278
- perfData.appNavigateType = navigationTiming.type;
279
- perfData.appNavigationStart = navigationTiming.startTime;
280
- perfData.appNavigationDuration = navigationTiming.duration;
281
- perfData.appEncodedBodySize = navigationTiming.encodedBodySize;
282
- perfData.appNextHopProtocol = navigationTiming.nextHopProtocol;
283
- perfData.appDomainLookupStart = navigationTiming.domainLookupStart;
284
- perfData.appDomainLookupEnd = navigationTiming.domainLookupEnd;
285
- perfData.appConnectStart = navigationTiming.connectStart;
286
- perfData.appConnectEnd = navigationTiming.connectEnd;
287
- perfData.appSecureConnectionStart = navigationTiming.secureConnectionStart;
288
- perfData.appFetchStart = navigationTiming.fetchStart;
289
- perfData.appRequestStart = navigationTiming.requestStart;
290
- perfData.appResponseStart = navigationTiming.responseStart;
291
- perfData.appResponseEnd = navigationTiming.responseEnd;
292
- perfData.appLoadEventEnd = navigationTiming.loadEventEnd;
293
- perfData.appDomInteractive = navigationTiming.domInteractive;
294
- perfData.appDomContentLoadedEventStart = navigationTiming.domContentLoadedEventStart;
295
- }
296
- return perfData;
297
- }
298
- var PerformanceApi = class {
299
- constructor(targetWindow = window) {
300
- __publicField(this, "_performance");
301
- this._performance = targetWindow.performance;
302
- }
303
- get timeOrigin() {
304
- return this._performance?.timeOrigin;
305
- }
306
- getEntriesByType(type) {
307
- if (!this._performance?.getEntriesByType) {
308
- return [];
309
- }
310
- return this._performance.getEntriesByType(type);
311
- }
312
- };
313
-
314
- // node_modules/@microsoft/power-apps/lib/telemetry/index.js
315
- executePluginAsync("AppLifecycle", "notifyAppSdkLoaded", [getAppLoadedPerformanceData()]);
316
-
317
- // node_modules/@microsoft/power-apps/lib/app/Config.js
318
- function setConfig(config) {
319
- if (config.logger) {
320
- initializeLogger(config.logger);
321
- }
322
- }
323
-
324
- // node_modules/@microsoft/power-apps/lib/internal/data/core/common/types.js
325
- var HttpMethod;
326
- (function(HttpMethod2) {
327
- HttpMethod2["GET"] = "GET";
328
- HttpMethod2["POST"] = "POST";
329
- HttpMethod2["PUT"] = "PUT";
330
- HttpMethod2["DELETE"] = "DELETE";
331
- HttpMethod2["PATCH"] = "PATCH";
332
- })(HttpMethod || (HttpMethod = {}));
333
- var DataSources;
334
- (function(DataSources2) {
335
- DataSources2["Dataverse"] = "Dataverse";
336
- DataSources2["Connector"] = "Connector";
337
- })(DataSources || (DataSources = {}));
338
-
339
- // node_modules/@microsoft/power-apps/lib/internal/data/core/error/codes.js
340
- var ErrorCodes;
341
- (function(ErrorCodes2) {
342
- ErrorCodes2["InitializationFailed"] = "PDR_INIT_FAILED";
343
- ErrorCodes2["InvalidXrmInfo"] = "INVALID_XRM_INFO";
344
- ErrorCodes2["OperationsNotInitialized"] = "OPS_NOT_INITIALIZED";
345
- ErrorCodes2["InvalidOperationExecutor"] = "INVALID_OPERATION_EXECUTOR";
346
- ErrorCodes2["DataSourceNotFound"] = "CONNECTION_NOT_FOUND";
347
- ErrorCodes2["DuplicateDataSource"] = "DUPLICATE_DATA_SOURCE";
348
- ErrorCodes2["InitializationError"] = "RDSS_INIT_ERROR";
349
- ErrorCodes2["InvalidDataSource"] = "INVALID_DATA_SOURCE";
350
- ErrorCodes2["DataSourcesInfoNotFound"] = "DATA_SOURCES_INFO_NOT_FOUND";
351
- ErrorCodes2["DataClientInitFailed"] = "DATA_CLIENT_INIT_FAILED";
352
- ErrorCodes2["DataClientNotInitialized"] = "DATA_CLIENT_NOT_INITIALIZED";
353
- ErrorCodes2["MetadataClientInitFailed"] = "METADATA_CLIENT_INIT_FAILED";
354
- ErrorCodes2["MetadataClientNotInitialized"] = "METADATA_CLIENT_NOT_INITIALIZED";
355
- ErrorCodes2["ClientProviderNotAvailable"] = "CLIENT_PROVIDER_NOT_AVAILABLE";
356
- ErrorCodes2["ConnectionReferenceNotFound"] = "CONNECTION_REFERENCE_NOT_FOUND";
357
- ErrorCodes2["DataClientNotAvailable"] = "DATA_CLIENT_NOT_AVAILABLE";
358
- ErrorCodes2["DataSourceServiceNotAvailable"] = "DATA_SOURCE_SERVICE_NOT_AVAILABLE";
359
- ErrorCodes2["MetadataClientNotAvailable"] = "METADATA_CLIENT_NOT_AVAILABLE";
360
- ErrorCodes2["ConnectionConfigFetchFailed"] = "CONNECTION_CONFIG_FETCH_FAILED";
361
- ErrorCodes2["DataSourceConfigFetchFailed"] = "DATA_SOURCE_CONFIG_FETCH_FAILED";
362
- ErrorCodes2["InvalidMetadataResponse"] = "INVALID_METADATA_RESPONSE";
363
- ErrorCodes2["TokenAcquisitionFailed"] = "TOKEN_ACQUISITION_FAILED";
364
- })(ErrorCodes || (ErrorCodes = {}));
365
-
366
- // node_modules/@microsoft/power-apps/lib/internal/data/core/error/messages.js
367
- var UnknownErrorMessage = "An unknown error occurred";
368
- var ErrorMessages = {
369
- // PowerDataRuntime specific errors
370
- [ErrorCodes.InitializationFailed]: "Failed to initialize PowerDataRuntime",
371
- [ErrorCodes.InvalidXrmInfo]: "Xrm info is required",
372
- [ErrorCodes.OperationsNotInitialized]: "PowerDataRuntime is not initialized",
373
- // RuntimeDataSourceService specific errors
374
- [ErrorCodes.DataSourceNotFound]: "Data source not found",
375
- [ErrorCodes.DuplicateDataSource]: "Duplicate data source",
376
- [ErrorCodes.InitializationError]: "Failed to initialize RuntimeDataSourceService",
377
- [ErrorCodes.InvalidDataSource]: "Invalid data source",
378
- // PowerDataSourcesInfoProvider specific errors
379
- [ErrorCodes.DataSourcesInfoNotFound]: "DataSourcesInfo must be provided to initialize the singleton instance.",
380
- // DataClientProvider specific errors
381
- [ErrorCodes.DataClientInitFailed]: "Failed to initialize PowerDataClient",
382
- [ErrorCodes.DataClientNotInitialized]: "PowerDataClient is not initialized",
383
- [ErrorCodes.MetadataClientInitFailed]: "Failed to initialize PowerMetadataClient",
384
- [ErrorCodes.MetadataClientNotInitialized]: "PowerMetadataClient is not initialized",
385
- // DataOperation specific errors
386
- [ErrorCodes.ClientProviderNotAvailable]: "Client provider is not available",
387
- [ErrorCodes.ConnectionReferenceNotFound]: "Connection reference not found",
388
- [ErrorCodes.DataClientNotAvailable]: "PowerDataClient is not available",
389
- [ErrorCodes.DataSourceServiceNotAvailable]: "Data source service is not available",
390
- [ErrorCodes.MetadataClientNotAvailable]: "PowerMetadataClient is not available",
391
- // MetadataClient specific errors
392
- [ErrorCodes.ConnectionConfigFetchFailed]: "Failed to fetch connection configurations",
393
- [ErrorCodes.DataSourceConfigFetchFailed]: "Failed to fetch data source configurations",
394
- [ErrorCodes.InvalidMetadataResponse]: "Invalid metadata response format",
395
- // RuntimeDataClient specific errors
396
- [ErrorCodes.TokenAcquisitionFailed]: "Failed to acquire access token"
397
- };
398
- var DataOperationErrorMessages;
399
- (function(DataOperationErrorMessages2) {
400
- DataOperationErrorMessages2["CreateFailed"] = "Create operation failure";
401
- DataOperationErrorMessages2["DeleteFailed"] = "Delete operation failure";
402
- DataOperationErrorMessages2["ExecuteFailed"] = "Execute operation failure";
403
- DataOperationErrorMessages2["InvalidOperationParameters"] = "Invalid operation parameters";
404
- DataOperationErrorMessages2["InvalidRequest"] = "Invalid request";
405
- DataOperationErrorMessages2["InvalidResponse"] = "Invalid response format";
406
- DataOperationErrorMessages2["MissingConnectorOperation"] = "Connector operation is required";
407
- DataOperationErrorMessages2["MissingDataverseRequest"] = "Dataverse request is required";
408
- DataOperationErrorMessages2["MissingOperationName"] = "Operation name is required";
409
- DataOperationErrorMessages2["MissingRequestBody"] = "Request body is required";
410
- DataOperationErrorMessages2["RetrieveFailed"] = "Retrieve operation failure";
411
- DataOperationErrorMessages2["RetrieveMultipleFailed"] = "Retrieve multiple records operation failure";
412
- DataOperationErrorMessages2["UpdateFailed"] = "Update operation failure";
413
- })(DataOperationErrorMessages || (DataOperationErrorMessages = {}));
414
-
415
- // node_modules/@microsoft/power-apps/lib/internal/data/core/types/index.js
416
- function isOperationResult(result) {
417
- return result?.success !== void 0;
418
- }
419
-
420
- // node_modules/@microsoft/power-apps/lib/internal/data/core/telemetry/log.js
421
- var ServiceName = "PublishedAppTelemetry";
422
- var TelemetryActionNames;
423
- (function(TelemetryActionNames2) {
424
- TelemetryActionNames2["trackEvent"] = "trackEvent";
425
- TelemetryActionNames2["trackException"] = "trackException";
426
- TelemetryActionNames2["trackMetric"] = "trackMetric";
427
- TelemetryActionNames2["startScenario"] = "startScenario";
428
- TelemetryActionNames2["endScenario"] = "endScenario";
429
- TelemetryActionNames2["setDefaultProperties"] = "setDefaultProperties";
430
- })(TelemetryActionNames || (TelemetryActionNames = {}));
431
- var _Log = class _Log {
432
- constructor(_powerOperationExecutor) {
433
- __publicField(this, "_powerOperationExecutor");
434
- this._powerOperationExecutor = _powerOperationExecutor;
435
- }
436
- static createInstance(powerOperationExecutor) {
437
- if (!_Log._instance) {
438
- _Log._instance = new _Log(powerOperationExecutor);
439
- } else {
440
- _Log.trackEvent("TelemetryLogger", {
441
- message: "Attempted to create an instance when instance is already created."
442
- });
443
- }
444
- return _Log._instance;
445
- }
446
- // Since powerDataRuntime can be reset, we need to be able to reset the instance of Log as well.
447
- static resetInstance() {
448
- _Log._instance = null;
449
- }
450
- static async _sendMessage(actionName, ...args) {
451
- try {
452
- const instance = _Log._getInstance();
453
- const result = await instance._powerOperationExecutor.execute(ServiceName, actionName, args);
454
- if (!result.success) {
455
- console.error({
456
- message: `PowerDataRuntime.TelemetryLogger: Failed to send telemetry message.`,
457
- error: result.error,
458
- telemetryArgs: args
459
- });
460
- }
461
- } catch (error) {
462
- console.error({
463
- message: `PowerDataRuntime.TelemetryLogger: Failed to send telemetry message.`,
464
- error,
465
- telemetryArgs: args
466
- });
467
- }
468
- }
469
- static trackEvent(eventName, eventData) {
470
- const serializedData = eventData ? _Log._serializeErrors(eventData) : eventData;
471
- return _Log._sendMessage(TelemetryActionNames.trackEvent, `PowerDataRuntime.${eventName}`, serializedData);
472
- }
473
- static trackException(exception) {
474
- return _Log._sendMessage(TelemetryActionNames.trackException, exception);
475
- }
476
- static trackMetric(metricName, value) {
477
- return _Log._sendMessage(TelemetryActionNames.trackMetric, `PowerDataRuntime.${metricName}`, value);
478
- }
479
- static startScenario(scenarioName) {
480
- return _Log._sendMessage(TelemetryActionNames.startScenario, `PowerDataRuntime.${scenarioName}`);
481
- }
482
- static endScenario(scenarioName) {
483
- return _Log._sendMessage(TelemetryActionNames.endScenario, `PowerDataRuntime.${scenarioName}`);
484
- }
485
- static setDefaultProperties(properties) {
486
- return _Log._sendMessage(TelemetryActionNames.setDefaultProperties, properties);
487
- }
488
- static _getInstance() {
489
- if (!_Log._instance) {
490
- throw new Error("PowerDataRuntime.TelemetryLogger: Attempted to log telemetry prior to instantiation.");
491
- }
492
- return _Log._instance;
493
- }
494
- /**
495
- * Recursively serializes Error objects in an object to prevent empty object serialization
496
- * when passed through postMessage's structured clone algorithm.
497
- * @param obj - The object to process
498
- * @returns A new object with Error instances replaced by serializable objects
499
- */
500
- static _serializeErrors(obj) {
501
- if (obj === null || obj === void 0) {
502
- return obj;
503
- }
504
- if (obj instanceof Error) {
505
- return {
506
- errorMessage: obj.message,
507
- errorStack: obj.stack,
508
- errorType: obj.name
509
- };
510
- }
511
- if (Array.isArray(obj)) {
512
- return obj.map((item) => _Log._serializeErrors(item));
513
- }
514
- if (typeof obj === "object" && obj !== null && Object.getPrototypeOf(obj) === Object.prototype) {
515
- const serialized = {};
516
- for (const key in obj) {
517
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
518
- serialized[key] = _Log._serializeErrors(obj[key]);
519
- }
520
- }
521
- return serialized;
522
- }
523
- return obj;
524
- }
525
- };
526
- __publicField(_Log, "_instance", null);
527
- var Log = _Log;
528
-
529
- // node_modules/@microsoft/power-apps/lib/internal/data/core/error/types.js
530
- var PowerDataRuntimeError = class extends Error {
531
- /**
532
- * Creates an instance of PowerDataRuntimeError.
533
- * @param code - The error code associated with the error.
534
- * @param additionalInfo - Optional additional information to include in the error message.
535
- * @param messageOverride - Optional override for the default error message.
536
- */
537
- constructor(code, additionalInfo, messageOverride) {
538
- let message = messageOverride || ErrorMessages[code] || UnknownErrorMessage;
539
- if (additionalInfo) {
540
- message += `: ${additionalInfo}`;
541
- }
542
- super(message);
543
- __publicField(this, "code");
544
- this.code = code;
545
- this.name = "PowerDataRuntimeError";
546
- Log.trackException(this);
547
- }
548
- };
549
-
550
- // node_modules/@microsoft/power-apps/lib/internal/data/core/error/constants.js
551
- var HeaderNames;
552
- (function(HeaderNames2) {
553
- HeaderNames2["RequestId"] = "x-ms-client-request-id";
554
- })(HeaderNames || (HeaderNames = {}));
555
- var DataverseOperationName;
556
- (function(DataverseOperationName2) {
557
- DataverseOperationName2["CreateRecord"] = "dataverseDataOperation.createRecordAsync";
558
- DataverseOperationName2["UpdateRecord"] = "dataverseDataOperation.updateRecordAsync";
559
- DataverseOperationName2["DeleteRecord"] = "dataverseDataOperation.deleteRecordAsync";
560
- DataverseOperationName2["RetrieveRecord"] = "dataverseDataOperation.retrieveRecordAsync";
561
- DataverseOperationName2["RetrieveMultipleRecords"] = "dataverseDataOperation.retrieveMultipleRecordsAsync";
562
- })(DataverseOperationName || (DataverseOperationName = {}));
563
- var ConnectorOperationName;
564
- (function(ConnectorOperationName2) {
565
- ConnectorOperationName2["CreateRecord"] = "connectorDataOperation.createRecordAsync";
566
- ConnectorOperationName2["UpdateRecord"] = "connectorDataOperation.updateRecordAsync";
567
- ConnectorOperationName2["DeleteRecord"] = "connectorDataOperation.deleteRecordAsync";
568
- ConnectorOperationName2["RetrieveRecord"] = "connectorDataOperation.retrieveRecordAsync";
569
- ConnectorOperationName2["RetrieveMultipleRecords"] = "connectorDataOperation.retrieveMultipleRecordsAsync";
570
- })(ConnectorOperationName || (ConnectorOperationName = {}));
571
-
572
- // node_modules/@microsoft/power-apps/lib/internal/data/core/error/util.js
573
- function getErrorMessage(error) {
574
- if (typeof error === "string") {
575
- return error;
576
- }
577
- if (error instanceof Error || error instanceof PowerDataRuntimeError) {
578
- return error.message || UnknownErrorMessage;
579
- }
580
- if (isOperationResult(error)) {
581
- return error.error?.message || UnknownErrorMessage;
582
- }
583
- if (typeof error === "object") {
584
- return JSON.stringify(error);
585
- }
586
- return UnknownErrorMessage;
587
- }
588
- function createErrorResponse(error, friendlyMessage) {
589
- const message = getErrorMessage(error);
590
- let data;
591
- if (isOperationResult(error)) {
592
- data = error.data;
593
- }
594
- const errorData = new Error(`${friendlyMessage}: ${message}`);
595
- if (error instanceof Error) {
596
- errorData.stack = error.stack;
597
- }
598
- return {
599
- success: false,
600
- error: errorData,
601
- data
602
- };
603
- }
604
- function parseHttpPluginError(error) {
605
- let message = UnknownErrorMessage;
606
- let response;
607
- if (Array.isArray(error)) {
608
- if (Array.isArray(error[0])) {
609
- message = error[0][0] || UnknownErrorMessage;
610
- response = error[0][2];
611
- }
612
- }
613
- const status = response?.status;
614
- const requestId = response?.headers?.[HeaderNames.RequestId];
615
- return {
616
- message,
617
- status,
618
- requestId
619
- };
620
- }
621
-
622
- // node_modules/@microsoft/power-apps/lib/internal/data/core/data/defaultOperationOrchestrator.js
623
- var DefaultDataOperationOrchestrator = class {
624
- // Static identifiers for services and actions
625
- // Used to identify specific services and actions within the PowerApps environment
626
- constructor(_dataverseOperation, _connectorOperation, _connectionsService) {
627
- __publicField(this, "_dataverseOperation");
628
- __publicField(this, "_connectorOperation");
629
- __publicField(this, "_connectionsService");
630
- this._dataverseOperation = _dataverseOperation;
631
- this._connectorOperation = _connectorOperation;
632
- this._connectionsService = _connectionsService;
633
- }
634
- /**
635
- * Creates a new record in the specified data source.
636
- * @param tableName - The name of the table.
637
- * @param data - The record data to create.
638
- * @returns A promise that resolves to the operation result.
639
- * @throws DataOperationError if the operation fails.
640
- */
641
- async createRecordAsync(tableName, data) {
642
- try {
643
- this._validateParams({ tableName, data });
644
- const executor = await this._getExecutor(tableName);
645
- return await executor.createRecordAsync(tableName, data);
646
- } catch (error) {
647
- return createErrorResponse(error, "Create record operation failed");
648
- }
649
- }
650
- /**
651
- * Updates an existing record in the specified data source.
652
- * @param tableName - The name of the table.
653
- * @param id - The ID of the record to update.
654
- * @param data - The updated record data.
655
- * @returns A promise that resolves to the operation result.
656
- * @throws DataOperationError if the operation fails.
657
- */
658
- async updateRecordAsync(tableName, id, data) {
659
- try {
660
- this._validateParams({ tableName, id, data });
661
- const executor = await this._getExecutor(tableName);
662
- return await executor.updateRecordAsync(tableName, id, data);
663
- } catch (error) {
664
- return createErrorResponse(error, "Update record operation failed");
665
- }
666
- }
667
- /**
668
- * Deletes a record from the specified data source.
669
- * @param tableName - The name of the table.
670
- * @param id - The ID of the record to delete.
671
- * @returns A promise that resolves to the operation result.
672
- * @throws DataOperationError if the operation fails.
673
- */
674
- async deleteRecordAsync(tableName, id) {
675
- try {
676
- this._validateParams({ tableName, id });
677
- const executor = await this._getExecutor(tableName);
678
- return await executor.deleteRecordAsync(tableName, id);
679
- } catch (error) {
680
- return createErrorResponse(error, "Delete record operation failed");
681
- }
682
- }
683
- /**
684
- * Retrieves a record from the specified data source.
685
- * @param tableName - The name of the table.
686
- * @param id - The ID of the record to retrieve.
687
- * @param options - Optional operation options.
688
- * @returns A promise that resolves to the operation result.
689
- * @throws DataOperationError if the operation fails.
690
- */
691
- async retrieveRecordAsync(tableName, id, options) {
692
- try {
693
- this._validateParams({ tableName, id });
694
- const executor = await this._getExecutor(tableName);
695
- this._validateOptions(options);
696
- return await executor.retrieveRecordAsync(tableName, id, options);
697
- } catch (error) {
698
- return createErrorResponse(error, "Retrieve record operation failed");
699
- }
700
- }
701
- /**
702
- * Retrieves multiple records from the specified data source.
703
- * @param tableName - The name of the table.
704
- * @param options - Optional operation options.
705
- * @returns A promise that resolves to the operation result.
706
- * @throws DataOperationError if the operation fails.
707
- */
708
- async retrieveMultipleRecordsAsync(tableName, options) {
709
- try {
710
- this._validateParams({ tableName });
711
- const executor = await this._getExecutor(tableName);
712
- this._validateOptions(options);
713
- return await executor.retrieveMultipleRecordsAsync(tableName, options);
714
- } catch (error) {
715
- return createErrorResponse(error, "Retrieve multiple records operation failed");
716
- }
717
- }
718
- /**
719
- * Executes a data operation on the specified data source.
720
- * @param operation - The operation to execute
721
- * @returns A promise that resolves to the operation result.
722
- * @throws DataOperationError if the operation fails.
723
- */
724
- async executeAsync(operation) {
725
- try {
726
- this._validateParams({ operation });
727
- const executor = await this._getExecutor("", operation.connectorOperation ? DataSources.Connector : DataSources.Dataverse);
728
- return await executor.executeAsync(operation);
729
- } catch (error) {
730
- return createErrorResponse(error, "Execute operation failed");
731
- }
732
- }
733
- /**
734
- * Retrieves the appropriate executor based on the data source.
735
- * @param dataSource - The data source to retrieve the executor for.
736
- * @returns The corresponding executor instance.
737
- * @throws DataOperationError if the data source is invalid.
738
- * // TODO: Add Dataverse support
739
- */
740
- async _getExecutor(tableName, dataSource) {
741
- const dataOperationExecutorOverride = getDataOperationExecutor();
742
- if (dataOperationExecutorOverride) {
743
- return dataOperationExecutorOverride;
744
- }
745
- const dataSourceType = dataSource || (await this._connectionsService.getDataSource(tableName)).dataSourceType;
746
- switch (dataSourceType) {
747
- case DataSources.Dataverse:
748
- return this._dataverseOperation;
749
- case DataSources.Connector:
750
- return this._connectorOperation;
751
- default:
752
- return this._connectorOperation;
753
- }
754
- }
755
- /**
756
- * Validates the input parameters for data operations.
757
- * @param params - The parameters to validate.
758
- * @throws DataOperationError if validation fails.
759
- */
760
- _validateParams(params) {
761
- for (const [key, value] of Object.entries(params)) {
762
- if (!value) {
763
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: ${key} is required`);
764
- }
765
- }
766
- }
767
- /**
768
- * Validates the operation options.
769
- * @param options - The operation options to validate.
770
- * @throws Error if validation fails.
771
- */
772
- _validateOptions(options) {
773
- if (!options) {
774
- return;
775
- }
776
- if (options.maxPageSize && typeof options.maxPageSize !== "number") {
777
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: maxPageSize must be a number`);
778
- }
779
- if (options.select) {
780
- if (!Array.isArray(options.select)) {
781
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: select must be an array of strings`);
782
- }
783
- if (options.select.some((s) => typeof s !== "string" || s.trim() === "")) {
784
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: select must contain only non-empty strings`);
785
- }
786
- }
787
- if (options.filter && typeof options.filter !== "string") {
788
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: filter must be a string`);
789
- }
790
- if (options.orderBy) {
791
- if (!Array.isArray(options.orderBy)) {
792
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: orderBy must be an array of strings`);
793
- }
794
- if (options.orderBy.some((s) => typeof s !== "string" || s.trim() === "")) {
795
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: orderBy must contain only non-empty strings`);
796
- }
797
- }
798
- if (options.top && typeof options.top !== "number") {
799
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: top must be a number`);
800
- }
801
- if (options.skip && typeof options.skip !== "number") {
802
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: skip must be a number`);
803
- }
804
- if (options.count && typeof options.count !== "boolean") {
805
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: count must be a boolean`);
806
- }
807
- }
808
- };
809
-
810
- // node_modules/@microsoft/power-apps/lib/internal/data/core/metadata/runtimeMetadataOperations.js
811
- var RuntimeMetadataOperations = class {
812
- // Static identifiers for services and actions
813
- // Used to identify specific services and actions within the PowerApps environment
814
- constructor(_clientProvider) {
815
- __publicField(this, "_clientProvider");
816
- this._clientProvider = _clientProvider;
817
- }
818
- async getConnections(context2) {
819
- const client = await this._clientProvider.getMetadataClientAsync();
820
- const response = await client.getAppConnectionConfigsAsync(context2);
821
- return {
822
- success: response.success,
823
- data: response.data ? [response.data] : [],
824
- error: response.error
825
- };
826
- }
827
- async getConnectionApis(_connectionId, context2) {
828
- const client = await this._clientProvider.getMetadataClientAsync();
829
- const response = await client.getAppDataSourceConfigsAsync(context2);
830
- return {
831
- success: response.success,
832
- data: response.data ? [response.data] : [],
833
- error: response.error
834
- };
835
- }
836
- };
837
-
838
- // node_modules/@microsoft/power-apps/lib/internal/data/core/common/utils.js
839
- function arrayBufferToBase64(buffer) {
840
- return window.btoa(convertArrayBufferToString(buffer));
841
- }
842
- function convertArrayBufferToString(buf) {
843
- if (buf.byteLength <= 65535) {
844
- return String.fromCharCode(...new Uint8Array(buf));
845
- }
846
- let binary = "";
847
- for (let i = 0, bytes = new Uint8Array(buf); i < bytes.byteLength; i++) {
848
- binary += String.fromCharCode(bytes[i]);
849
- }
850
- return binary;
851
- }
852
- function strictEncode(str) {
853
- return encodeURIComponent(str).replace(/\(/g, "%28").replace(/\)/g, "%29");
854
- }
855
- function extractDataverseUrlParts(url) {
856
- const baseUrlMatch = url.match(/^(https?:\/\/[^/]+\/api\/data\/v9\.0)/);
857
- const baseUrl = baseUrlMatch ? baseUrlMatch[1] : "";
858
- const pathMatch = url.match(/\/api\/data\/v9\.0\/(.+)$/);
859
- const encodedPath = pathMatch ? strictEncode(pathMatch[1]) : "";
860
- return { baseUrl, encodedPath };
861
- }
862
-
863
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtimeClient/runtimeDataClient.js
864
- var _RuntimeDataClient = class _RuntimeDataClient {
865
- // Constructor for RuntimeDataClient
866
- // Accepts an IPowerOperationExecutor instance for executing operations
867
- constructor(_powerOperationExecutor) {
868
- __publicField(this, "_powerOperationExecutor");
869
- this._powerOperationExecutor = _powerOperationExecutor;
870
- }
871
- /**
872
- * Creates a new instance of RuntimeDataClient
873
- */
874
- static createInstanceAsync(powerOperationExecutor) {
875
- return Promise.resolve(new _RuntimeDataClient(powerOperationExecutor));
876
- }
877
- /**
878
- * Creates data using POST method
879
- * @param url - The URL for the request
880
- * @param apiId - The API ID for authentication
881
- * @param tableName - The name of the table to access
882
- * @param body - The request body for the POST method
883
- * @param operationName - Optional operation name for telemetry
884
- * @return Promise resolving to the response data
885
- * @throws Error if the request fails or the response is invalid
886
- * @throws Error if the request body is invalid
887
- */
888
- async createDataAsync(url, apiId, tableName, body, context2) {
889
- try {
890
- if (!body) {
891
- throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingRequestBody}`);
892
- }
893
- const config = {
894
- url,
895
- method: HttpMethod.POST,
896
- apiId,
897
- tableName,
898
- body: JSON.stringify(body)
899
- };
900
- context2 = this._ensureContext(context2, "runtimeDataClient.createDataAsync");
901
- return await this._executeRequest(config, context2);
902
- } catch (error) {
903
- if (isOperationResult(error)) {
904
- return error;
905
- } else {
906
- return createErrorResponse(error, DataOperationErrorMessages.CreateFailed);
907
- }
908
- }
909
- }
910
- /**
911
- * Updates data using PATCH method
912
- * @param url - The URL for the request
913
- * @param apiId - The API ID for authentication
914
- * @param tableName - The name of the table to access
915
- * @param body - The request body for the PATCH method
916
- * @param operationName - Optional operation name for telemetry
917
- * @return Promise resolving to the response data
918
- * @throws Error if the request fails or the response is invalid
919
- * @throws Error if the request body is invalid
920
- */
921
- async updateDataAsync(url, apiId, tableName, body, context2) {
922
- try {
923
- if (!body) {
924
- throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingRequestBody}`);
925
- }
926
- const config = {
927
- url,
928
- method: HttpMethod.PATCH,
929
- apiId,
930
- tableName,
931
- body: JSON.stringify(body)
932
- };
933
- context2 = this._ensureContext(context2, "runtimeDataClient.updateDataAsync");
934
- return await this._executeRequest(config, context2);
935
- } catch (error) {
936
- if (isOperationResult(error)) {
937
- return error;
938
- } else {
939
- return createErrorResponse(error, DataOperationErrorMessages.UpdateFailed);
940
- }
941
- }
942
- }
943
- /**
944
- * Deletes data using DELETE method
945
- * @param url - The URL for the request
946
- * @param connectionApi - The API ID for authentication
947
- * @param serviceNamespace - The name of the service namespace
948
- * @param operationName - Optional operation name for telemetry
949
- * @return Promise resolving to the response data
950
- * @throws Error if the request fails or the response is invalid
951
- */
952
- async deleteDataAsync(url, connectionApi, serviceNamespace, context2) {
953
- try {
954
- const config = {
955
- url,
956
- method: HttpMethod.DELETE,
957
- apiId: connectionApi,
958
- tableName: serviceNamespace
959
- };
960
- context2 = this._ensureContext(context2, "runtimeDataClient.deleteDataAsync");
961
- return await this._executeRequest(config, context2);
962
- } catch (error) {
963
- if (isOperationResult(error)) {
964
- return error;
965
- } else {
966
- return createErrorResponse(error, DataOperationErrorMessages.DeleteFailed);
967
- }
968
- }
969
- }
970
- /**
971
- * Retrieves data using GET or POST method
972
- * @param url - The URL for the request
973
- * @param apiId - The API ID for authentication
974
- * @param tableName - The name of the table to access
975
- * @param method - The HTTP method
976
- * @param body - Optional request body for POST method
977
- * @param context - Optional operation context
978
- * @param operationName - Optional operation name for telemetry
979
- * @return Promise resolving to the response data
980
- * @throws Error if the request fails or the response is invalid
981
- */
982
- async retrieveDataAsync(url, apiId, tableName, method, headers, body, context2) {
983
- try {
984
- const config = {
985
- url,
986
- method,
987
- apiId,
988
- tableName,
989
- headers,
990
- body: body ? typeof body === "string" ? body : JSON.stringify(body) : void 0
991
- };
992
- context2 = this._ensureContext(context2, "runtimeDataClient.retrieveDataAsync");
993
- return await this._executeRequest(config, context2);
994
- } catch (error) {
995
- if (isOperationResult(error)) {
996
- return error;
997
- } else {
998
- return createErrorResponse(error, DataOperationErrorMessages.RetrieveFailed);
999
- }
1000
- }
1001
- }
1002
- /**
1003
- * Gets an access token for the specified API.
1004
- * If the API is Dataverse, retrieves a dynamic resource token; otherwise, retrieves a standard appservice API token.
1005
- * @param apiId - The API ID for authentication
1006
- * @param datasetName - Optional dataset name for Dataverse
1007
- * @returns Promise resolving to the access token
1008
- * @throws Error if token acquisition fails
1009
- */
1010
- async _getAccessToken(apiId, datasetName) {
1011
- try {
1012
- let result;
1013
- if (apiId === DataSources.Dataverse) {
1014
- result = await this._powerOperationExecutor.execute(_RuntimeDataClient.SERVICES.identityService, _RuntimeDataClient.ACTIONS.getDynamicToken, [datasetName]);
1015
- } else {
1016
- result = await this._powerOperationExecutor.execute(_RuntimeDataClient.SERVICES.identityService, _RuntimeDataClient.ACTIONS.getToken, [apiId]);
1017
- }
1018
- return result.data;
1019
- } catch (error) {
1020
- throw new PowerDataRuntimeError(ErrorCodes.TokenAcquisitionFailed, getErrorMessage(error));
1021
- }
1022
- }
1023
- // Merge Prefer headers for Dataverse batch payloads
1024
- _mergePreferHeaders(configHeaders, method) {
1025
- let preferHeader = "";
1026
- if (configHeaders?.Prefer) {
1027
- preferHeader += configHeaders.Prefer;
1028
- }
1029
- if (method === HttpMethod.POST || method === HttpMethod.PATCH) {
1030
- const defaultPrefer = "return=representation,odata.include-annotations=*";
1031
- if (preferHeader) {
1032
- if (!preferHeader.includes("return=representation")) {
1033
- preferHeader += (preferHeader ? "," : "") + defaultPrefer;
1034
- }
1035
- } else {
1036
- preferHeader = defaultPrefer;
1037
- }
1038
- }
1039
- return preferHeader;
1040
- }
1041
- /**
1042
- * Creates headers for the HTTP request.
1043
- * Combines default headers with any custom headers provided in the config.
1044
- * Custom headers are optional and take precedence over default headers.
1045
- * @param token - The access token for authentication
1046
- * @param config - The HTTP request configuration
1047
- * @return The headers for the request
1048
- * @throws Error if header creation fails
1049
- */
1050
- _createHeaders(token, config, context2) {
1051
- const baseHeaders = {
1052
- Accept: "application/json",
1053
- "x-ms-protocol-semantics": "cdp",
1054
- ServiceNamespace: config.tableName,
1055
- Authorization: `paauth ${token}`,
1056
- "x-ms-pa-client-custom-headers-options": '{"addCustomHeaders":true}',
1057
- "x-ms-enable-selects": "true",
1058
- "x-ms-pa-client-telemetry-options": `paclient-telemetry {"operationName":"${context2?.operationName ?? "runtimeDataClient.executeRequest"}"}`,
1059
- "x-ms-pa-client-telemetry-additional-data": `{"apiId":"${config.apiId}"}`
1060
- };
1061
- if (config.apiId === DataSources.Dataverse) {
1062
- baseHeaders["x-ms-protocol-semantics"] = DataSources.Dataverse;
1063
- baseHeaders.Authorization = `dynamicauth ${token}`;
1064
- const { baseUrl, encodedPath } = extractDataverseUrlParts(config.url);
1065
- const batchId = context2?.batchId || "";
1066
- const preferHeader = this._mergePreferHeaders(config.headers, config.method);
1067
- baseHeaders.BatchInfo = JSON.stringify({
1068
- baseUrl,
1069
- encodedPath,
1070
- headers: {
1071
- Accept: "application/json",
1072
- ...preferHeader ? { Prefer: preferHeader } : {},
1073
- ...config.method === HttpMethod.POST || config.method === HttpMethod.PATCH ? { "Content-Type": "application/json" } : {}
1074
- },
1075
- batchId
1076
- });
1077
- }
1078
- if (config.headers) {
1079
- return { ...baseHeaders, ...config.headers };
1080
- }
1081
- return baseHeaders;
1082
- }
1083
- /**
1084
- * Executes an HTTP request with the given configuration
1085
- * @param config - The HTTP request configuration
1086
- * @param context - Optional operation context
1087
- * @return Promise resolving to the response data
1088
- * @throws Error if the request fails or the response is invalid
1089
- * @throws Error if the response content type is invalid
1090
- */
1091
- async _executeRequest(config, context2) {
1092
- const token = await this._getAccessToken(config.apiId, context2?.datasetName);
1093
- const headers = this._createHeaders(token, config, context2);
1094
- const requestBody = config.body ? new Blob([config.body], { type: "application/json" }) : "";
1095
- let result;
1096
- try {
1097
- result = await this._powerOperationExecutor.execute(_RuntimeDataClient.SERVICES.dataClient, _RuntimeDataClient.ACTIONS.sendHttp, [
1098
- {
1099
- url: config.url,
1100
- method: config.method,
1101
- requestSource: _RuntimeDataClient.REQUEST_SOURCE,
1102
- allowSessionStorage: true,
1103
- returnDirectResponse: true,
1104
- headers
1105
- },
1106
- requestBody,
1107
- "arraybuffer"
1108
- ]);
1109
- } catch (error) {
1110
- return {
1111
- success: false,
1112
- error: parseHttpPluginError(error),
1113
- data: void 0
1114
- };
1115
- }
1116
- const responseData = result.data;
1117
- const responseHeaders = responseData[0].headers;
1118
- const contentType = responseHeaders["Content-Type"];
1119
- if (!contentType) {
1120
- return {
1121
- success: true,
1122
- data: void 0
1123
- };
1124
- } else if (contentType.indexOf("application/json") !== -1) {
1125
- const data = result.data[1];
1126
- let text = this._decodeArrayBuffer(data);
1127
- if (!text) {
1128
- text = "{}";
1129
- }
1130
- const parsedResult = JSON.parse(text);
1131
- if (context2?.isDataVerseOperation || this._isDataverseCall(config.url)) {
1132
- return {
1133
- success: true,
1134
- data: parsedResult
1135
- };
1136
- } else if (!context2?.isExecuteAsync && "value" in parsedResult && Array.isArray(parsedResult.value)) {
1137
- return {
1138
- success: true,
1139
- data: parsedResult.value,
1140
- count: parsedResult["@odata.count"]
1141
- };
1142
- } else {
1143
- return {
1144
- success: true,
1145
- data: parsedResult
1146
- };
1147
- }
1148
- } else if (contentType.indexOf("image/") !== -1) {
1149
- const buffer = result.data[1];
1150
- if (buffer instanceof ArrayBuffer) {
1151
- const value = arrayBufferToBase64(buffer);
1152
- return {
1153
- success: true,
1154
- data: value
1155
- };
1156
- }
1157
- return {
1158
- success: true,
1159
- data: buffer
1160
- };
1161
- } else {
1162
- const buffer = result.data[1];
1163
- if (buffer instanceof ArrayBuffer) {
1164
- const value = convertArrayBufferToString(buffer);
1165
- const status = responseData[0].status;
1166
- const responseType = context2?.responseInfo?.[status];
1167
- if (responseType) {
1168
- let parsedValue;
1169
- try {
1170
- parsedValue = JSON.parse(value);
1171
- } catch (err) {
1172
- return {
1173
- success: false,
1174
- data: void 0,
1175
- error: new Error(DataOperationErrorMessages.InvalidResponse)
1176
- };
1177
- }
1178
- if (responseType.type === "array" && !Array.isArray(parsedValue)) {
1179
- return {
1180
- success: false,
1181
- data: void 0,
1182
- error: new Error(DataOperationErrorMessages.InvalidResponse)
1183
- };
1184
- }
1185
- if (responseType.type === "object" && (typeof parsedValue !== "object" || Array.isArray(parsedValue) || parsedValue === null)) {
1186
- return {
1187
- success: false,
1188
- data: void 0,
1189
- error: new Error(DataOperationErrorMessages.InvalidResponse)
1190
- };
1191
- }
1192
- return {
1193
- success: true,
1194
- data: parsedValue
1195
- };
1196
- } else {
1197
- return {
1198
- success: true,
1199
- data: value
1200
- };
1201
- }
1202
- }
1203
- return {
1204
- success: false,
1205
- data: responseData,
1206
- error: new Error(DataOperationErrorMessages.InvalidResponse)
1207
- };
1208
- }
1209
- }
1210
- _ensureContext(context2, defaultOperationName) {
1211
- if (!context2) {
1212
- context2 = {};
1213
- }
1214
- if (!context2.operationName) {
1215
- context2.operationName = defaultOperationName;
1216
- }
1217
- return context2;
1218
- }
1219
- /**
1220
- * Checks if the given URL is a Dataverse API call
1221
- * @param url - The URL to check
1222
- * @returns True if the URL is a Dataverse API call, false otherwise
1223
- */
1224
- _isDataverseCall(url) {
1225
- if (!url) {
1226
- return false;
1227
- }
1228
- const urlLower = decodeURIComponent(url).toLowerCase();
1229
- return urlLower.includes("/api/data/") && !urlLower.includes("/apim");
1230
- }
1231
- /**
1232
- * Decodes ArrayBuffer to string, handling both browser and Node.js environments
1233
- * @param buffer - The ArrayBuffer to decode
1234
- * @returns The decoded string
1235
- */
1236
- _decodeArrayBuffer(buffer) {
1237
- if (typeof TextDecoder !== "undefined") {
1238
- return new TextDecoder().decode(buffer);
1239
- }
1240
- const uint8Array = new Uint8Array(buffer);
1241
- const results = [];
1242
- const chunkSize = 8192;
1243
- for (let i = 0; i < uint8Array.length; i += chunkSize) {
1244
- const chunk = uint8Array.subarray(i, Math.min(i + chunkSize, uint8Array.length));
1245
- results.push(String.fromCharCode.apply(null, Array.from(chunk)));
1246
- }
1247
- try {
1248
- return results.join("");
1249
- } catch {
1250
- return results.join("");
1251
- }
1252
- }
1253
- };
1254
- // Static identifiers for services
1255
- // Used to identify specific services within the PowerApps environment
1256
- __publicField(_RuntimeDataClient, "SERVICES", {
1257
- dataClient: "AppHttpClientPlugin",
1258
- identityService: "AppIdentityServicePlugin"
1259
- });
1260
- // Static identifiers for service actions
1261
- // Used to identify specific actions within the service
1262
- // These actions are used to send HTTP requests and get access tokens
1263
- __publicField(_RuntimeDataClient, "ACTIONS", {
1264
- sendHttp: "sendHttpAsync",
1265
- getToken: "getAppAccessTokenAsync",
1266
- getDynamicToken: "getAppDynamicResourceAccessTokenAsync"
1267
- });
1268
- // Request source identifier for telemetry
1269
- // Used to identify the source of the request in telemetry data
1270
- __publicField(_RuntimeDataClient, "REQUEST_SOURCE", "PublishedApp");
1271
- var RuntimeDataClient = _RuntimeDataClient;
1272
-
1273
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtimeClient/runtimeMetadataClient.js
1274
- var _RuntimeMetadataClient = class _RuntimeMetadataClient {
1275
- // Private member for the PowerOperationExecutor
1276
- // The PowerOperationExecutor is used to execute operations on the clients
1277
- constructor(_powerOperationExecutor) {
1278
- __publicField(this, "_powerOperationExecutor");
1279
- this._powerOperationExecutor = _powerOperationExecutor;
1280
- }
1281
- /**
1282
- * Creates a new instance of RuntimeMetadataClient
1283
- * @param powerOperationExecutor - The powerOperationExecutor instance
1284
- * @returns Promise resolving to IRuntimeMetadataClient
1285
- */
1286
- static createInstanceAsync(powerOperationExecutor) {
1287
- return Promise.resolve(new _RuntimeMetadataClient(powerOperationExecutor));
1288
- }
1289
- /**
1290
- * Fetches app connection configurations
1291
- * @returns Promise resolving to connection reference details
1292
- * @throws Error if the operation fails
1293
- */
1294
- async getAppConnectionConfigsAsync() {
1295
- try {
1296
- const config = {
1297
- service: _RuntimeMetadataClient.SERVICES.powerAppsClient,
1298
- action: _RuntimeMetadataClient.ACTIONS.getConnectionConfigs,
1299
- params: []
1300
- };
1301
- const result = await this._executeOperation(config);
1302
- return { success: true, data: result };
1303
- } catch (error) {
1304
- throw new PowerDataRuntimeError(ErrorCodes.ConnectionConfigFetchFailed, getErrorMessage(error));
1305
- }
1306
- }
1307
- /**
1308
- * Fetches app data source configurations
1309
- * @returns Promise resolving to connection reference details
1310
- * @throws Error if the operation fails
1311
- */
1312
- async getAppDataSourceConfigsAsync() {
1313
- try {
1314
- const config = {
1315
- service: _RuntimeMetadataClient.SERVICES.powerAppsClient,
1316
- action: _RuntimeMetadataClient.ACTIONS.getDataSourceConfigs,
1317
- params: []
1318
- };
1319
- const result = await this._executeOperation(config);
1320
- return { success: true, data: result };
1321
- } catch (error) {
1322
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceConfigFetchFailed, getErrorMessage(error));
1323
- }
1324
- }
1325
- /**
1326
- * Executes a metadata operation with the given configuration
1327
- * @param config - The operation configuration
1328
- * @returns Promise resolving to the operation result
1329
- * @throws Error if the operation fails
1330
- */
1331
- async _executeOperation(config) {
1332
- try {
1333
- const result = await this._powerOperationExecutor.execute(config.service, config.action, config.params || []);
1334
- const lowerCaseResult = Object.keys(result.data).reduce((acc, key) => {
1335
- acc[key.toLowerCase()] = (result.data ?? {})[key];
1336
- return acc;
1337
- }, {});
1338
- return lowerCaseResult;
1339
- } catch {
1340
- throw new PowerDataRuntimeError(ErrorCodes.InvalidMetadataResponse);
1341
- }
1342
- }
1343
- };
1344
- // Static identifiers for services and actions
1345
- // Used to identify specific services and actions within the PowerApps environment
1346
- // These identifiers are used to execute operations through the PowerOperationExecutor
1347
- // The services provide the functionality for the operations
1348
- __publicField(_RuntimeMetadataClient, "SERVICES", {
1349
- powerAppsClient: "AppPowerAppsClientPlugin"
1350
- });
1351
- // The actions define the specific operations to be performed
1352
- __publicField(_RuntimeMetadataClient, "ACTIONS", {
1353
- getConnectionConfigs: "loadAppConnectionsAsync_v2",
1354
- getDataSourceConfigs: "getAppCdsDataSourceConfigsAsync"
1355
- });
1356
- var RuntimeMetadataClient = _RuntimeMetadataClient;
1357
-
1358
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtimeClient/runtimeClientProvider.js
1359
- var RuntimeClientProvider = class {
1360
- // Constructor for RuntimeClientProvider
1361
- // Accepts an optional IPowerOperationExecutor instance for executing operations
1362
- // If not provided, uses the default PowerOperationExecutor instance
1363
- constructor(powerOperationExecutor) {
1364
- // Private members for data and metadata clients
1365
- // The data client is responsible for handling data operations
1366
- __publicField(this, "_dataClient");
1367
- // The metadata client is responsible for handling metadata operations
1368
- __publicField(this, "_metadataClient");
1369
- // The operation executor is used to execute operations on the clients
1370
- // It is an instance of IPowerOperationExecutor, which provides the necessary methods for executing operations
1371
- __publicField(this, "_operationExecutor");
1372
- this._operationExecutor = powerOperationExecutor;
1373
- }
1374
- /**
1375
- * Gets or initializes the data client
1376
- * @throws Error if client initialization fails
1377
- * @returns Promise resolving to IRuntimeDataClient
1378
- */
1379
- async getDataClientAsync() {
1380
- try {
1381
- if (!this._dataClient) {
1382
- this._dataClient = await this._initializeDataClient();
1383
- }
1384
- if (!this._dataClient) {
1385
- throw new PowerDataRuntimeError(ErrorCodes.DataClientNotInitialized);
1386
- }
1387
- return this._dataClient;
1388
- } catch (error) {
1389
- throw new PowerDataRuntimeError(ErrorCodes.DataClientInitFailed, getErrorMessage(error));
1390
- }
1391
- }
1392
- /**
1393
- * Gets or initializes the metadata client
1394
- * @throws Error if client initialization fails
1395
- * @returns Promise resolving to IRuntimeMetadataClient
1396
- */
1397
- async getMetadataClientAsync() {
1398
- try {
1399
- if (!this._metadataClient) {
1400
- this._metadataClient = await this._initializeMetadataClient();
1401
- }
1402
- if (!this._metadataClient) {
1403
- throw new PowerDataRuntimeError(ErrorCodes.MetadataClientNotInitialized);
1404
- }
1405
- return this._metadataClient;
1406
- } catch (error) {
1407
- throw new PowerDataRuntimeError(ErrorCodes.MetadataClientInitFailed, getErrorMessage(error));
1408
- }
1409
- }
1410
- /**
1411
- * Initializes the data client
1412
- * @returns Promise resolving to IRuntimeDataClient
1413
- */
1414
- async _initializeDataClient() {
1415
- return RuntimeDataClient.createInstanceAsync(this._operationExecutor);
1416
- }
1417
- /**
1418
- * Initializes the metadata client
1419
- * @returns Promise resolving to IRuntimeMetadataClient
1420
- */
1421
- async _initializeMetadataClient() {
1422
- return RuntimeMetadataClient.createInstanceAsync(this._operationExecutor);
1423
- }
1424
- /**
1425
- * Resets both clients, forcing re-initialization on next use
1426
- * Useful for testing or recovering from error states
1427
- */
1428
- reset() {
1429
- this._dataClient = void 0;
1430
- this._metadataClient = void 0;
1431
- }
1432
- };
1433
-
1434
- // node_modules/@microsoft/power-apps/lib/internal/data/core/data/executors/shared/stringQueryOptions.js
1435
- function convertOptionsToQueryString(options) {
1436
- if (!options) {
1437
- return "";
1438
- }
1439
- const parts = [];
1440
- if (options.select && options.select.length > 0) {
1441
- parts.push(`$select=${encodeURIComponent(options.select.map((s) => s.trim().replace(/%20/g, "+").replace(/'/g, "%27")).join(","))}`);
1442
- }
1443
- if (options.filter) {
1444
- const encodedFilter = encodeURIComponent(options.filter.trim()).replace(/%20/g, "+").replace(/'/g, "%27");
1445
- parts.push(`$filter=${encodedFilter}`);
1446
- }
1447
- if (options.orderBy && options.orderBy.length > 0) {
1448
- parts.push(`$orderby=${encodeURIComponent(options.orderBy.map((s) => s.trim().replace(/%20/g, "+").replace(/'/g, "%27")).join(","))}`);
1449
- }
1450
- if (options.top !== void 0 && options.top !== null) {
1451
- parts.push(`$top=${options.top}`);
1452
- }
1453
- if (options.skip !== void 0 && options.skip !== null) {
1454
- parts.push(`$skip=${options.skip}`);
1455
- }
1456
- if (options.count !== void 0 && options.count !== null) {
1457
- parts.push(`$count=${options.count}`);
1458
- }
1459
- if (options.skipToken && options.skipToken.trim() !== "") {
1460
- parts.push(`$skiptoken=${encodeURIComponent(options.skipToken.trim())}`);
1461
- }
1462
- return parts.length ? `?${parts.join("&")}` : "";
1463
- }
1464
-
1465
- // node_modules/@microsoft/power-apps/lib/internal/data/core/data/executors/dataverseDataOperationExecutor.js
1466
- var ODATA_NEXT_LINK = "@odata.nextLink";
1467
- var DataverseDataOperationExecutor = class {
1468
- constructor(clientProvider) {
1469
- // Static identifiers for services and actions
1470
- // Used to identify specific services and actions within the PowerApps environment
1471
- __publicField(this, "_clientProvider");
1472
- __publicField(this, "_databaseReferences");
1473
- this._clientProvider = clientProvider;
1474
- }
1475
- /**
1476
- * Creates a new record in Dataverse
1477
- * @param tableName - The name of the table
1478
- * @param data - The record data to create
1479
- * @returns Promise resolving to operation result
1480
- */
1481
- async createRecordAsync(tableName, data) {
1482
- return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName), async (dataClient, requestUrl, dataSourceInfo) => {
1483
- const dataverseResponse = await dataClient.createDataAsync(
1484
- requestUrl,
1485
- DataSources.Dataverse,
1486
- // Use environment name for Dataverse authentication
1487
- tableName,
1488
- data,
1489
- {
1490
- operationName: DataverseOperationName.CreateRecord,
1491
- datasetName: dataSourceInfo.datasetName,
1492
- isDataVerseOperation: true
1493
- }
1494
- );
1495
- const returnValue = {
1496
- success: dataverseResponse.success,
1497
- data: dataverseResponse.data,
1498
- error: dataverseResponse.error
1499
- };
1500
- return returnValue;
1501
- }, DataOperationErrorMessages.CreateFailed);
1502
- }
1503
- /**
1504
- * Updates an existing record in Dataverse
1505
- * @param tableName - The name of the table
1506
- * @param id - The record identifier
1507
- * @param data - The updated record data
1508
- * @returns Promise resolving to operation result
1509
- */
1510
- async updateRecordAsync(tableName, id, data) {
1511
- return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, `(${id})`), async (dataClient, requestUrl, dataSourceInfo) => {
1512
- const dataverseResponse = await dataClient.updateDataAsync(requestUrl, DataSources.Dataverse, tableName, data, {
1513
- operationName: DataverseOperationName.UpdateRecord,
1514
- datasetName: dataSourceInfo.datasetName,
1515
- isDataVerseOperation: true
1516
- });
1517
- const returnValue = {
1518
- success: dataverseResponse.success,
1519
- data: dataverseResponse.data,
1520
- error: dataverseResponse.error
1521
- };
1522
- return returnValue;
1523
- }, DataOperationErrorMessages.UpdateFailed);
1524
- }
1525
- /**
1526
- * Deletes a record from Dataverse
1527
- * @param tableName - The name of the table
1528
- * @param id - The record identifier
1529
- * @returns Promise resolving to operation result
1530
- */
1531
- async deleteRecordAsync(tableName, id) {
1532
- return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, `(${id})`), async (dataClient, requestUrl, dataSourceInfo) => {
1533
- const dataverseResponse = await dataClient.deleteDataAsync(requestUrl, DataSources.Dataverse, tableName, {
1534
- operationName: DataverseOperationName.DeleteRecord,
1535
- datasetName: dataSourceInfo.datasetName,
1536
- isDataVerseOperation: true
1537
- });
1538
- const returnValue = {
1539
- success: dataverseResponse.success,
1540
- data: dataverseResponse.data,
1541
- error: dataverseResponse.error
1542
- };
1543
- return returnValue;
1544
- }, DataOperationErrorMessages.DeleteFailed);
1545
- }
1546
- /**
1547
- * Retrieves a single record from Dataverse
1548
- * @param tableName - The name of the table
1549
- * @param id - The record identifier
1550
- * @param options - The retrieval options
1551
- * @returns Promise resolving to operation result
1552
- */
1553
- async retrieveRecordAsync(tableName, id, options) {
1554
- const { maxPageSize = 500, ...rest } = options || {};
1555
- const optionsString = convertOptionsToQueryString(rest);
1556
- const headers = { Prefer: `odata.maxpagesize=${maxPageSize},odata.include-annotations=*` };
1557
- return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, `(${id})${optionsString}`), async (dataClient, requestUrl, dataSourceInfo) => {
1558
- const dataverseResponse = await dataClient.retrieveDataAsync(
1559
- requestUrl,
1560
- DataSources.Dataverse,
1561
- tableName,
1562
- HttpMethod.GET,
1563
- headers,
1564
- void 0,
1565
- // No body for GET requests
1566
- {
1567
- operationName: DataverseOperationName.RetrieveRecord,
1568
- datasetName: dataSourceInfo.datasetName,
1569
- isDataVerseOperation: true
1570
- }
1571
- );
1572
- const returnValue = {
1573
- success: dataverseResponse.success,
1574
- data: dataverseResponse.data,
1575
- error: dataverseResponse.error
1576
- };
1577
- return returnValue;
1578
- }, DataOperationErrorMessages.RetrieveFailed);
1579
- }
1580
- /**
1581
- * Retrieves multiple records from Dataverse
1582
- * @param tableName - The name of the table
1583
- * @param options - The retrieval options
1584
- * @param maxPageSize - Optional maximum page size
1585
- * @returns Promise resolving to operation result
1586
- */
1587
- async retrieveMultipleRecordsAsync(tableName, options) {
1588
- const { maxPageSize = 500, ...rest } = options || {};
1589
- const optionsString = convertOptionsToQueryString(rest);
1590
- const headers = { Prefer: `odata.maxpagesize=${maxPageSize},odata.include-annotations=*` };
1591
- return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, optionsString), async (dataClient, requestUrl, dataSourceInfo) => {
1592
- const dataverseResponse = await dataClient.retrieveDataAsync(
1593
- requestUrl,
1594
- DataSources.Dataverse,
1595
- tableName,
1596
- HttpMethod.GET,
1597
- headers,
1598
- void 0,
1599
- // No body for GET requests
1600
- {
1601
- operationName: DataverseOperationName.RetrieveMultipleRecords,
1602
- datasetName: dataSourceInfo.datasetName,
1603
- isDataVerseOperation: true
1604
- }
1605
- );
1606
- const returnValue = {
1607
- success: dataverseResponse.success,
1608
- data: dataverseResponse?.data?.value || [],
1609
- skipToken: extractSkipToken(dataverseResponse?.data?.[ODATA_NEXT_LINK]),
1610
- error: dataverseResponse.error
1611
- };
1612
- return returnValue;
1613
- }, DataOperationErrorMessages.RetrieveMultipleFailed);
1614
- }
1615
- /**
1616
- * Executes a custom Dataverse operation
1617
- * @param operation - The operation to execute
1618
- * @returns Promise resolving to operation result
1619
- */
1620
- async executeAsync(operation) {
1621
- const { dataverseRequest } = operation;
1622
- if (!dataverseRequest) {
1623
- return {
1624
- success: false,
1625
- data: null,
1626
- error: { message: "Dataverse request details are required for Dataverse operations." }
1627
- };
1628
- }
1629
- const { action, parameters } = dataverseRequest;
1630
- switch (action) {
1631
- // Future custom actions can be handled here
1632
- case "getEntityMetadata":
1633
- const { tableName, options } = parameters;
1634
- if (!tableName) {
1635
- return {
1636
- success: false,
1637
- data: null,
1638
- error: { message: "Table name is required for getEntityMetadata action." }
1639
- };
1640
- }
1641
- return this._getEntityMetadata(tableName, options ?? {});
1642
- default:
1643
- Log.trackEvent("DataverseDataOperation.UnsupportedAction", {
1644
- message: `Unsupported Dataverse action: ${action}`
1645
- });
1646
- return {
1647
- success: false,
1648
- data: null,
1649
- error: { message: `Unsupported Dataverse action: "${action}"` }
1650
- };
1651
- }
1652
- }
1653
- async _getEntityMetadata(tableName, options) {
1654
- const client = await this._getDataClient();
1655
- const dataSourceInfo = await this._getDataverseDataSourceInfo(tableName);
1656
- const url = this._generateMetadataRequestUrl(dataSourceInfo, options);
1657
- return client.retrieveDataAsync(url, DataSources.Dataverse, "EntityDefinitions", HttpMethod.GET, {
1658
- Consistency: "Strong"
1659
- // Force CDS to return latest metadata
1660
- }, void 0, {
1661
- operationName: DataverseOperationName.RetrieveRecord,
1662
- datasetName: dataSourceInfo.datasetName,
1663
- isDataVerseOperation: true
1664
- });
1665
- }
1666
- /**
1667
- * Returns the database references for Dataverse, grouped by environment/database.
1668
- * These come from the launch app response via runtime metadata client.
1669
- */
1670
- async getDatabaseReferences() {
1671
- if (this._databaseReferences) {
1672
- return this._databaseReferences;
1673
- }
1674
- const runtimeDatabaseReferences = await this._loadDatabaseReferencesFromRuntime();
1675
- if (runtimeDatabaseReferences && Object.keys(runtimeDatabaseReferences).length > 0) {
1676
- this._databaseReferences = runtimeDatabaseReferences;
1677
- return this._databaseReferences;
1678
- }
1679
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, "Failed to load Dataverse database references from runtime.");
1680
- }
1681
- /**
1682
- * Loads database references from runtime metadata client (launch app response).
1683
- */
1684
- async _loadDatabaseReferencesFromRuntime() {
1685
- try {
1686
- const metadataClient = await this._getMetadataClient();
1687
- const response = await metadataClient.getAppDataSourceConfigsAsync();
1688
- if (!response.success || !response.data) {
1689
- return void 0;
1690
- }
1691
- const cdsDataSources = Object.values(response.data);
1692
- if (cdsDataSources.length === 0) {
1693
- return void 0;
1694
- }
1695
- const databaseReferences = {};
1696
- for (const cdsDataSource of cdsDataSources) {
1697
- const cdsConfig = cdsDataSource;
1698
- const instanceUrl = this._extractInstanceUrlFromRuntimeUrl(cdsConfig.runtimeUrl);
1699
- const envName = "default.cds";
1700
- if (!databaseReferences[envName]) {
1701
- databaseReferences[envName] = {
1702
- databaseDetails: {
1703
- referenceType: "Environmental",
1704
- environmentName: envName,
1705
- overrideValues: {
1706
- status: "NotSpecified",
1707
- environmentVariableName: ""
1708
- },
1709
- linkedEnvironmentMetadata: {
1710
- resourceId: "",
1711
- friendlyName: "",
1712
- uniqueName: "",
1713
- domainName: "",
1714
- version: cdsConfig.version || "9.2",
1715
- instanceUrl,
1716
- instanceApiUrl: cdsConfig.runtimeUrl,
1717
- baseLanguage: 1033,
1718
- instanceState: "Ready",
1719
- createdTime: "",
1720
- platformSku: ""
1721
- }
1722
- },
1723
- dataSources: {}
1724
- };
1725
- }
1726
- const dataSourceName = cdsConfig.entitySetName || cdsConfig.logicalName;
1727
- databaseReferences[envName].dataSources[dataSourceName] = {
1728
- entitySetName: cdsConfig.entitySetName,
1729
- logicalName: cdsConfig.logicalName,
1730
- isHidden: false
1731
- };
1732
- }
1733
- return databaseReferences;
1734
- } catch (error) {
1735
- Log.trackEvent("DataverseDataOperation.FailedToLoadDatabaseReferences", {
1736
- message: "[DataverseDataOperation] Failed to load database references from runtime",
1737
- error
1738
- });
1739
- return void 0;
1740
- }
1741
- }
1742
- _extractInstanceUrlFromRuntimeUrl(runtimeUrl) {
1743
- try {
1744
- const matches = runtimeUrl.match(/^(https?:\/\/[^\/]+)/);
1745
- return matches ? matches[1] : runtimeUrl;
1746
- } catch (error) {
1747
- Log.trackEvent("DataverseDataOperation.FailedToExtractInstanceUrl", {
1748
- message: "[DataverseDataOperation] Failed to extract instance URL from runtime URL",
1749
- error
1750
- });
1751
- return runtimeUrl;
1752
- }
1753
- }
1754
- /**
1755
- * Helper to get a native data client and database reference
1756
- */
1757
- async _getDataClient() {
1758
- const dataClient = await this._clientProvider.getDataClientAsync();
1759
- if (!dataClient) {
1760
- Log.trackEvent("DataverseDataOperation.DataClientNotAvailable", {
1761
- message: "[DataverseDataOperation] Data client is not available"
1762
- });
1763
- throw new PowerDataRuntimeError(ErrorCodes.DataClientNotAvailable, "Data client is not available.");
1764
- }
1765
- return dataClient;
1766
- }
1767
- /**
1768
- * Gets the metadata client instance
1769
- */
1770
- async _getMetadataClient() {
1771
- const metadataClient = await this._clientProvider.getMetadataClientAsync();
1772
- if (!metadataClient) {
1773
- Log.trackEvent("DataverseDataOperation.MetadataClientNotAvailable", {
1774
- message: "[DataverseDataOperation] Metadata client is not available"
1775
- });
1776
- throw new PowerDataRuntimeError(ErrorCodes.MetadataClientNotAvailable);
1777
- }
1778
- return metadataClient;
1779
- }
1780
- /**
1781
- * Template method for connector-style CRUD operations to reduce duplication.
1782
- * Handles client, dataSourceInfo, requestUrl, and error handling.
1783
- */
1784
- async _executeNativeDataverseOperation(tableName, buildUrl, operation, errorMessage) {
1785
- try {
1786
- const dataClient = await this._getDataClient();
1787
- const dataSourceInfo = await this._getDataverseDataSourceInfo(tableName);
1788
- const requestUrl = buildUrl(dataSourceInfo, tableName);
1789
- return operation(dataClient, requestUrl, dataSourceInfo);
1790
- } catch (error) {
1791
- return createErrorResponse(error, errorMessage);
1792
- }
1793
- }
1794
- /**
1795
- * Helper to get the Dataverse datasourceinfo from databaseReferences
1796
- */
1797
- async _getDataverseDataSourceInfo(tableName) {
1798
- let dbRefs;
1799
- try {
1800
- dbRefs = await this.getDatabaseReferences();
1801
- } catch (error) {
1802
- Log.trackEvent("DataverseDataOperation.GetDataSourceInfoFailed", {
1803
- message: "[DataverseDataOperation] Failed to get database references",
1804
- tableName,
1805
- error
1806
- });
1807
- const errorMessage = error instanceof Error ? error.message : String(error);
1808
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, `Failed to get Dataverse data source info for table '${tableName}': ${errorMessage}`);
1809
- }
1810
- for (const dbKey of Object.keys(dbRefs)) {
1811
- const db = dbRefs[dbKey];
1812
- if (db.dataSources[tableName]) {
1813
- const ds = db.dataSources[tableName];
1814
- return {
1815
- datasetName: db.databaseDetails?.environmentName,
1816
- referenceType: db.databaseDetails?.referenceType,
1817
- linkedEnvironmentMetadata: db.databaseDetails?.linkedEnvironmentMetadata,
1818
- entitySetName: ds?.entitySetName,
1819
- logicalName: ds?.logicalName,
1820
- isHidden: ds?.isHidden,
1821
- tableId: ds?.logicalName,
1822
- apis: {}
1823
- };
1824
- }
1825
- }
1826
- const notFoundMsg = `No Dataverse data source found for table: ${tableName}`;
1827
- Log.trackEvent("DataverseDataOperation.DataSourceNotFound", {
1828
- message: notFoundMsg,
1829
- tableName
1830
- });
1831
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, notFoundMsg);
1832
- }
1833
- /**
1834
- * Helper to construct the Dataverse API URL using instanceUrl if available, otherwise fallback to runtimeUrl.
1835
- */
1836
- _getInstanceUrl(dataSourceInfo) {
1837
- const instanceUrl = dataSourceInfo.linkedEnvironmentMetadata?.instanceUrl;
1838
- if (!instanceUrl) {
1839
- throw new PowerDataRuntimeError(ErrorCodes.DataClientInitFailed, "No instanceUrl found for Dataverse table.");
1840
- }
1841
- const baseUrl = instanceUrl.endsWith("/") ? instanceUrl : `${instanceUrl}/`;
1842
- return baseUrl;
1843
- }
1844
- /**
1845
- * Helper to construct the Dataverse API URL using instanceUrl if available, otherwise fallback to runtimeUrl.
1846
- */
1847
- _getDataverseRequestUrl(dataSourceInfo, tableName, urlPath = "") {
1848
- const baseUrl = this._getInstanceUrl(dataSourceInfo);
1849
- return `${baseUrl}api/data/v9.0/${tableName}${urlPath}`;
1850
- }
1851
- /**
1852
- * Constructs GET request URL for fetching metadata using options object.
1853
- * @param dataSourceInfo - The data source information for the Dataverse table.
1854
- * @param options - The options for the metadata request.
1855
- * @returns The constructed metadata request URL.
1856
- */
1857
- _generateMetadataRequestUrl(dataSourceInfo, options) {
1858
- const { logicalName } = dataSourceInfo;
1859
- if (!logicalName) {
1860
- throw new PowerDataRuntimeError(ErrorCodes.DataClientInitFailed, "No logicalName found for Dataverse table.");
1861
- }
1862
- const url = new URL(`${this._getInstanceUrl(dataSourceInfo)}api/data/v9.0/EntityDefinitions(LogicalName='${logicalName}')`);
1863
- const { metadata, schema } = options;
1864
- const selects = new Set(Array.isArray(metadata) ? metadata : []);
1865
- selects.add("LogicalName");
1866
- const expands = [];
1867
- if (schema?.manyToOne) {
1868
- expands.push("ManyToOneRelationships");
1869
- }
1870
- if (schema?.oneToMany) {
1871
- expands.push("OneToManyRelationships");
1872
- }
1873
- if (schema?.manyToMany) {
1874
- expands.push("ManyToManyRelationships");
1875
- }
1876
- if (schema?.columns === "all") {
1877
- expands.push("Attributes");
1878
- } else if (schema && Array.isArray(schema.columns) && schema.columns.length > 0) {
1879
- const attributesCollection = schema.columns.map((a) => `'${a}'`).join(",");
1880
- expands.push(`Attributes($filter=Microsoft.Dynamics.CRM.In(PropertyName='LogicalName',PropertyValues=[${attributesCollection}]))`);
1881
- }
1882
- url.search = new URLSearchParams({
1883
- $select: [...selects].join(","),
1884
- $expand: expands.join(",")
1885
- }).toString();
1886
- return url.toString();
1887
- }
1888
- };
1889
- function extractSkipToken(nextLink) {
1890
- if (!nextLink?.trim()) {
1891
- return void 0;
1892
- }
1893
- const match = nextLink.match(/[\?&]\$?skiptoken=([^&#]+)/i);
1894
- return match ? decodeURIComponent(match[1]) : void 0;
1895
- }
1896
-
1897
- // node_modules/@microsoft/power-apps/lib/internal/data/core/data/executors/connectorDataOperationExecutor.js
1898
- var ConnectorDataOperationExecutor = class {
1899
- // =====================================
1900
- // Constructor
1901
- // =====================================
1902
- constructor(clientProvider, connectionsService) {
1903
- // =====================================
1904
- // Private Members
1905
- // =====================================
1906
- __publicField(this, "_clientProvider");
1907
- __publicField(this, "_connectionsService");
1908
- __publicField(this, "_databaseReferences");
1909
- __publicField(this, "_connectionReferences");
1910
- this._validateConstructorParams(clientProvider, connectionsService);
1911
- this._clientProvider = clientProvider;
1912
- this._connectionsService = connectionsService;
1913
- }
1914
- // =====================================
1915
- // Public Methods
1916
- // =====================================
1917
- /**
1918
- * Creates a new record in the specified table
1919
- */
1920
- async createRecordAsync(tableName, data) {
1921
- try {
1922
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1923
- const requestUrl = await this._buildTableUrl(tableName, connectionReference);
1924
- const result = await dataClient.createDataAsync(requestUrl, connectionReference.apiId, tableName, data, { operationName: ConnectorOperationName.CreateRecord });
1925
- return result;
1926
- } catch (error) {
1927
- return createErrorResponse(error, DataOperationErrorMessages.CreateFailed);
1928
- }
1929
- }
1930
- /**
1931
- * Updates an existing record in the specified table
1932
- */
1933
- async updateRecordAsync(tableName, id, data) {
1934
- try {
1935
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1936
- const requestUrl = await this._buildTableUrl(tableName, connectionReference, `/${id}`);
1937
- const result = await dataClient.updateDataAsync(requestUrl, connectionReference.apiId, tableName, data, { operationName: ConnectorOperationName.UpdateRecord });
1938
- return result;
1939
- } catch (error) {
1940
- return createErrorResponse(error, DataOperationErrorMessages.UpdateFailed);
1941
- }
1942
- }
1943
- /**
1944
- * Deletes a record from the specified table
1945
- */
1946
- async deleteRecordAsync(tableName, id) {
1947
- try {
1948
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1949
- const requestUrl = await this._buildTableUrl(tableName, connectionReference, `/${id}`);
1950
- const result = await dataClient.deleteDataAsync(requestUrl, connectionReference.apiId, tableName, { operationName: ConnectorOperationName.DeleteRecord });
1951
- return result;
1952
- } catch (error) {
1953
- return createErrorResponse(error, DataOperationErrorMessages.DeleteFailed);
1954
- }
1955
- }
1956
- /**
1957
- * Retrieves a single record from the specified table
1958
- */
1959
- async retrieveRecordAsync(tableName, id, options) {
1960
- try {
1961
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1962
- const requestUrl = await this._buildTableUrl(tableName, connectionReference, `/${id}${convertOptionsToQueryString(options)}`);
1963
- const result = await dataClient.retrieveDataAsync(
1964
- requestUrl,
1965
- connectionReference.apiId,
1966
- tableName,
1967
- HttpMethod.GET,
1968
- void 0,
1969
- // body
1970
- { operationName: ConnectorOperationName.RetrieveRecord }
1971
- );
1972
- return result;
1973
- } catch (error) {
1974
- return createErrorResponse(error, DataOperationErrorMessages.RetrieveFailed);
1975
- }
1976
- }
1977
- /**
1978
- * Retrieves multiple records from the specified table
1979
- */
1980
- async retrieveMultipleRecordsAsync(tableName, options) {
1981
- try {
1982
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1983
- const requestUrl = await this._buildTableUrl(tableName, connectionReference, convertOptionsToQueryString(options), false);
1984
- const result = await dataClient.retrieveDataAsync(
1985
- requestUrl,
1986
- connectionReference.apiId,
1987
- tableName,
1988
- HttpMethod.GET,
1989
- void 0,
1990
- // body
1991
- { operationName: ConnectorOperationName.RetrieveMultipleRecords }
1992
- );
1993
- return result;
1994
- } catch (error) {
1995
- return createErrorResponse(error, DataOperationErrorMessages.RetrieveMultipleFailed);
1996
- }
1997
- }
1998
- /**
1999
- * Executes a custom operation on the data source
2000
- */
2001
- async executeAsync(operation) {
2002
- try {
2003
- if (!operation?.connectorOperation) {
2004
- throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingConnectorOperation}`);
2005
- }
2006
- const tableName = operation.connectorOperation.tableName;
2007
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
2008
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
2009
- const config = await this._getOperationConfig(operation, connectionReference, tableName);
2010
- const requestUrl = await this._buildOperationUrl(operation, config);
2011
- const bodyParam = await this._buildOperationBody(operation, tableName);
2012
- const headers = await this._buildOperationHeader(operation, tableName);
2013
- const httpMethod = this._getHttpMethod(requestUrl, dataSourceInfo, operation.connectorOperation.operationName);
2014
- const responseInfo = dataSourceInfo.apis[operation.connectorOperation.operationName]?.responseInfo;
2015
- const result = await dataClient.retrieveDataAsync(requestUrl, config.apiId, tableName, httpMethod, headers, bodyParam, {
2016
- isExecuteAsync: true,
2017
- // Use the connector operation name for telemetry, may be a better idea to use executeAsync
2018
- // here and just log the connector operation name in the custom dimensions leaving comment for PR.
2019
- operationName: `connectorDataOperation.${operation.connectorOperation.operationName}`,
2020
- responseInfo
2021
- });
2022
- return result;
2023
- } catch (error) {
2024
- return createErrorResponse(error, DataOperationErrorMessages.ExecuteFailed);
2025
- }
2026
- }
2027
- // =====================================
2028
- // Private Methods
2029
- // =====================================
2030
- /**
2031
- * Determines the appropriate HTTP method for a request
2032
- * @param requestUrl - The URL for the request
2033
- * @param dataSourceInfo - The data source information
2034
- * @param operation - The operation name
2035
- * @returns The HTTP method to use
2036
- */
2037
- _getHttpMethod(requestUrl, dataSourceInfo, operation) {
2038
- const isSqlStoredProcedure = requestUrl.indexOf("apim/sql") > -1;
2039
- if (isSqlStoredProcedure) {
2040
- return HttpMethod.POST;
2041
- }
2042
- const method = dataSourceInfo.apis[operation]?.method;
2043
- if (method) {
2044
- return method;
2045
- }
2046
- return HttpMethod.GET;
2047
- }
2048
- /**
2049
- * Builds the operation body parameters
2050
- */
2051
- async _buildOperationBody(operation, tableName) {
2052
- const operationName = operation?.connectorOperation?.operationName;
2053
- if (operationName) {
2054
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
2055
- const hasBodyParameter = dataSourceInfo?.apis?.[operationName]?.parameters?.some((param) => param.in === "body");
2056
- if (hasBodyParameter) {
2057
- return await this._buildOperationBodyParam(operation, tableName);
2058
- }
2059
- }
2060
- return void 0;
2061
- }
2062
- /**
2063
- * Builds operation body parameters from the operation and data source info
2064
- */
2065
- async _buildOperationBodyParam(operation, tableName) {
2066
- const operationName = operation.connectorOperation?.operationName;
2067
- if (!operationName) {
2068
- return "{}";
2069
- }
2070
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
2071
- const apiParams = dataSourceInfo?.apis?.[operationName]?.parameters || [];
2072
- const rawParams = operation.connectorOperation?.parameters || [];
2073
- if (typeof rawParams !== "object" || rawParams === null) {
2074
- return "{}";
2075
- }
2076
- const bodyParam = apiParams.find((param) => param.in === "body");
2077
- if (bodyParam) {
2078
- const value = rawParams[bodyParam.name];
2079
- if (value !== void 0 && value !== null) {
2080
- return JSON.stringify(value);
2081
- }
2082
- }
2083
- return "{}";
2084
- }
2085
- /**
2086
- * Builds the operation header for a given data operation if required.
2087
- *
2088
- * @template TRequest - The type of the request payload for the data operation.
2089
- * @param dataOperationRequest - The data operation containing details about the connector operation.
2090
- * @param tableName - The name of the table associated with the data operation.
2091
- * @returns A promise that resolves to the operation header as a string if a header parameter is required,
2092
- * or `undefined` if no header parameter is needed.
2093
- */
2094
- async _buildOperationHeader(dataOperationRequest, tableName) {
2095
- const operationName = dataOperationRequest.connectorOperation?.operationName;
2096
- if (operationName) {
2097
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
2098
- const hasHeaderParameter = dataSourceInfo?.apis?.[operationName]?.parameters?.some((param) => param.in === "header");
2099
- if (hasHeaderParameter) {
2100
- return await this._buildOperationHeaderParam(dataOperationRequest, tableName);
2101
- }
2102
- }
2103
- return void 0;
2104
- }
2105
- /**
2106
- * Builds the operation header parameters as a JSON string for a given data operation.
2107
- *
2108
- * @template TRequest - The type of the request object for the data operation.
2109
- * @param dataOperationRequest - The data operation containing connector operation details and parameters.
2110
- * @param tableName - The name of the table associated with the data operation.
2111
- * @returns A promise that resolves to a JSON string representing the header parameters,
2112
- * or `undefined` if no `header` parameters are available.
2113
- */
2114
- async _buildOperationHeaderParam(dataOperationRequest, tableName) {
2115
- const operationName = dataOperationRequest.connectorOperation?.operationName;
2116
- if (!operationName) {
2117
- return {};
2118
- }
2119
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
2120
- const apiParamSpec = dataSourceInfo?.apis?.[operationName]?.parameters || [];
2121
- const inputParams = dataOperationRequest.connectorOperation?.parameters;
2122
- const headers = {};
2123
- if (!inputParams) {
2124
- return void 0;
2125
- }
2126
- if (typeof inputParams === "string") {
2127
- if (apiParamSpec.length === 1 && apiParamSpec[0].in === "header") {
2128
- headers[apiParamSpec[0].name] = inputParams;
2129
- }
2130
- }
2131
- if (typeof inputParams === "object" && !Array.isArray(inputParams)) {
2132
- apiParamSpec.forEach((param) => {
2133
- if (param.in === "header" && param.name in inputParams) {
2134
- headers[param.name] = inputParams[param.name];
2135
- }
2136
- });
2137
- }
2138
- if (Array.isArray(inputParams)) {
2139
- apiParamSpec.forEach((param, index) => {
2140
- if (param.in === "header" && inputParams[index] !== void 0) {
2141
- headers[param.name] = inputParams[index];
2142
- }
2143
- });
2144
- }
2145
- return headers;
2146
- }
2147
- /**
2148
- * Constructs the request URL for table operations
2149
- * @param tableName - The name of the table
2150
- * @param connectionReference - The connection reference
2151
- * @param options - Optional URL parameters
2152
- * @param encodeOptions - Whether to encode the options
2153
- * @returns The constructed URL
2154
- */
2155
- async _buildTableUrl(tableName, connectionReference, options = "", encodeOptions = true) {
2156
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
2157
- const isSharedSql = (connectionReference.apiId ?? "").indexOf("shared_sql") > -1;
2158
- const isSharePoint = (connectionReference.apiId ?? "").indexOf("shared_sharepointonline") > -1;
2159
- const urlBuilder = {
2160
- runtimeUrl: connectionReference.runtimeUrl ?? "",
2161
- connectionName: connectionReference.connectionName ?? "",
2162
- datasetName: connectionReference.datasetName ? isSharedSql ? connectionReference.datasetNameOverride : isSharePoint ? encodeURIComponent(encodeURIComponent(connectionReference.datasetName)) : encodeURIComponent(connectionReference.datasetName) : "",
2163
- tableId: isSharedSql ? encodeURIComponent(encodeURIComponent(dataSourceInfo.tableId)) : dataSourceInfo.tableId,
2164
- version: dataSourceInfo.version,
2165
- isSharedSql
2166
- };
2167
- return this._constructUrl(urlBuilder, options, encodeOptions);
2168
- }
2169
- /**
2170
- * Builds the operation URL
2171
- */
2172
- async _buildOperationUrl(operation, config) {
2173
- const operationName = operation.connectorOperation?.operationName;
2174
- if (!operationName) {
2175
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: ${DataOperationErrorMessages.MissingOperationName}`);
2176
- }
2177
- const dataSourceInfo = await this._connectionsService.getDataSource(config.tableName);
2178
- const isSharedSql = (config.apiId ?? "").indexOf("shared_sql") > -1;
2179
- const path = dataSourceInfo.apis[operationName].path;
2180
- if (isSharedSql) {
2181
- return this._buildSharedSqlOperationUrl(config, path);
2182
- }
2183
- return this._buildStandardOperationUrl(operation, config, operationName, path);
2184
- }
2185
- /**
2186
- * Gets the connection references
2187
- */
2188
- async _getConnectionReferencesAsync() {
2189
- if (this._connectionReferences) {
2190
- return this._connectionReferences;
2191
- }
2192
- const metadataClient = await this._getMetadataClient();
2193
- const response = await metadataClient.getAppConnectionConfigsAsync();
2194
- this._connectionReferences = response.data;
2195
- return this._connectionReferences;
2196
- }
2197
- /**
2198
- * Gets the database references
2199
- */
2200
- async _getDatabaseReferencesAsync() {
2201
- if (this._databaseReferences) {
2202
- return this._databaseReferences;
2203
- }
2204
- const metadataClient = await this._getMetadataClient();
2205
- const response = await metadataClient.getAppDataSourceConfigsAsync();
2206
- this._databaseReferences = response.data;
2207
- return this._databaseReferences;
2208
- }
2209
- /**
2210
- * Gets the metadata client instance
2211
- */
2212
- async _getMetadataClient() {
2213
- const metadataClient = await this._clientProvider.getMetadataClientAsync();
2214
- if (!metadataClient) {
2215
- throw new PowerDataRuntimeError(ErrorCodes.MetadataClientNotAvailable);
2216
- }
2217
- return metadataClient;
2218
- }
2219
- /**
2220
- * Gets the connection reference for a table
2221
- */
2222
- _getConnectionReference(tableName) {
2223
- const connectionReference = this._connectionReferences?.[tableName];
2224
- if (!connectionReference) {
2225
- throw new PowerDataRuntimeError(ErrorCodes.ConnectionReferenceNotFound, tableName);
2226
- }
2227
- return connectionReference;
2228
- }
2229
- /**
2230
- * Gets both the data client and connection reference
2231
- */
2232
- async _getClientsAndConnection(tableName) {
2233
- await this._getReferences();
2234
- const dataClient = await this._clientProvider.getDataClientAsync();
2235
- if (!dataClient) {
2236
- throw new PowerDataRuntimeError(ErrorCodes.DataClientNotAvailable);
2237
- }
2238
- const connectionReference = this._getConnectionReference(tableName);
2239
- return { dataClient, connectionReference };
2240
- }
2241
- /**
2242
- * Builds the URL for shared SQL operations
2243
- */
2244
- _buildSharedSqlOperationUrl(config, path) {
2245
- const version = config.version ? `/${config.version}/` : "/";
2246
- return `${config.runtimeUrl}/${config.connectionName}${version}datasets/${config.datasetName}/procedures${path}`;
2247
- }
2248
- /**
2249
- * Builds the URL for standard operations
2250
- * Assumptions / Invariants:
2251
- * - The connector always defines a required path parameter for the connection id named 'connectionId'.
2252
- * - When a dataset is applicable, the parameter name is 'dataset'.
2253
- * - When a table is applicable, the parameter name is 'tableName'.
2254
- * - A lone string parameter maps to the first remaining (non-synthetic) required API parameter.
2255
- * - Array parameters map positionally to the remaining API parameters after filtering.
2256
- * - Object parameters map by (case-insensitive, hyphen/underscore agnostic) key.
2257
- * @param operation - The data operation containing connector operation details from runtime
2258
- * @param config - The connector operation configuration
2259
- * @param operationName - The name of the operation to be performed
2260
- * @param path - The path template for the operation
2261
- */
2262
- async _buildStandardOperationUrl(operation, config, operationName, path) {
2263
- const dataSourceInfo = await this._connectionsService.getDataSource(config.tableName);
2264
- let apiParams = dataSourceInfo.apis[operationName]?.parameters || [];
2265
- if (apiParams.length > 0) {
2266
- apiParams = apiParams.filter((param) => param.name !== "connectionId" && param.name !== "dataset" && param.name !== "tableName");
2267
- }
2268
- const operationParams = operation.connectorOperation?.parameters;
2269
- const rawParamValues = {
2270
- connectionId: config.connectionName,
2271
- dataset: (
2272
- // The dataset name needs to be double encoded for sharepoint, once here and then once in the HTTP pipeline
2273
- // CRUD operations already handle this, so we need to do the same here
2274
- config.apiId.indexOf("shared_sharepointonline") !== -1 && config.datasetName ? encodeURIComponent(config.datasetName) : config.datasetName
2275
- ),
2276
- tableName: config.tableName
2277
- };
2278
- if (operationParams !== void 0) {
2279
- if (typeof operationParams === "string") {
2280
- if (apiParams.length > 0) {
2281
- const requiredParams = apiParams.filter((param) => param.required);
2282
- rawParamValues[requiredParams?.[0]?.name ?? apiParams[0].name] = operationParams;
2283
- }
2284
- } else if (typeof operationParams === "object" && !Array.isArray(operationParams)) {
2285
- apiParams.forEach((param) => {
2286
- if (operationParams) {
2287
- const value = this._getNormalizedParamValue(operationParams, param.name);
2288
- if (value !== void 0) {
2289
- rawParamValues[param.name] = value;
2290
- }
2291
- }
2292
- });
2293
- } else if (Array.isArray(operationParams)) {
2294
- apiParams.forEach((param, index) => {
2295
- rawParamValues[param.name] = operationParams[index];
2296
- });
2297
- }
2298
- }
2299
- const { processedPath, queryParams } = this._processParameters(
2300
- // deliberately pass the unfiltered list to _processParameters so path placeholders still see synthetic params.
2301
- dataSourceInfo.apis[operationName]?.parameters || [],
2302
- rawParamValues,
2303
- path
2304
- );
2305
- const separator = queryParams ? processedPath.includes("?") ? "&" : "?" : "";
2306
- return `${config.runtimeUrl}${processedPath}${separator}${queryParams}`;
2307
- }
2308
- /**
2309
- * Normalizes the parameter name by replacing hyphens with underscores and performs case-insensitive matching
2310
- */
2311
- _getNormalizedParamValue(obj, paramName) {
2312
- const normalizedParamName = paramName.replace(/-/g, "_").toLowerCase();
2313
- const foundKey = Object.keys(obj).find((key) => key.replace(/-/g, "_").toLowerCase() === normalizedParamName);
2314
- return foundKey !== void 0 ? obj[foundKey] : void 0;
2315
- }
2316
- /**
2317
- * Processes operation parameters into path and query parameters
2318
- * @param apiParams - The API parameter specifications from the data source info
2319
- * @param rawParamValues - The raw parameter values provided in the operation at runtime
2320
- * @param path - The initial path template
2321
- * @returns An object containing the processed path and query parameters
2322
- */
2323
- _processParameters(apiParams, rawParamValues, path) {
2324
- const usedParams = /* @__PURE__ */ new Set();
2325
- let processedPath = path;
2326
- const queryParams = [];
2327
- apiParams.forEach((param, index) => {
2328
- const paramValue = rawParamValues[param.name];
2329
- if (paramValue === void 0) {
2330
- return;
2331
- }
2332
- if (param.in === "path") {
2333
- const placeholder = `{${param.name}}`;
2334
- if (processedPath.includes(placeholder)) {
2335
- processedPath = processedPath.replace(placeholder, encodeURIComponent(String(paramValue)));
2336
- usedParams.add(param.name);
2337
- }
2338
- } else if (param.in === "query") {
2339
- queryParams.push(`${encodeURIComponent(param.name)}=${encodeURIComponent(String(paramValue))}`);
2340
- usedParams.add(param.name);
2341
- }
2342
- });
2343
- return {
2344
- processedPath,
2345
- queryParams: queryParams.join("&")
2346
- };
2347
- }
2348
- /**
2349
- * Gets the operation configuration
2350
- */
2351
- async _getOperationConfig(operation, connectionReference, tableName) {
2352
- if (!operation.connectorOperation) {
2353
- throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingConnectorOperation}`);
2354
- }
2355
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
2356
- const config = {
2357
- tableName,
2358
- apiId: connectionReference.apiId ?? "",
2359
- runtimeUrl: connectionReference.runtimeUrl ?? "",
2360
- connectionName: connectionReference.connectionName ?? "",
2361
- datasetName: connectionReference.datasetName ?? "",
2362
- tableId: dataSourceInfo.tableId,
2363
- version: dataSourceInfo.version
2364
- };
2365
- return config;
2366
- }
2367
- /**
2368
- * Initializes the clients
2369
- */
2370
- async _getReferences() {
2371
- await this._getConnectionReferencesAsync();
2372
- await this._getDatabaseReferencesAsync();
2373
- }
2374
- /**
2375
- * Validates constructor parameters
2376
- */
2377
- _validateConstructorParams(clientProvider, connectionsService) {
2378
- if (!clientProvider) {
2379
- throw new PowerDataRuntimeError(ErrorCodes.ClientProviderNotAvailable);
2380
- }
2381
- if (!connectionsService) {
2382
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceServiceNotAvailable);
2383
- }
2384
- }
2385
- /**
2386
- * Constructs the final URL
2387
- */
2388
- _constructUrl(urlBuilder, options = "", encodeOptions = true) {
2389
- const apiVersion = urlBuilder.version ? `/${urlBuilder.version}/` : "/";
2390
- const encodedOptions = encodeOptions && options ? options.charAt(0) + encodeURIComponent(options.slice(1)) : options;
2391
- if (urlBuilder.datasetName) {
2392
- return `${urlBuilder.runtimeUrl}/${urlBuilder.connectionName}${apiVersion}datasets/${urlBuilder.datasetName}/tables/${urlBuilder.tableId}/items${encodedOptions}`;
2393
- }
2394
- return `${urlBuilder.runtimeUrl}/${urlBuilder.connectionName}/tables/${urlBuilder.tableId}/items${encodedOptions}`;
2395
- }
2396
- };
2397
-
2398
- // node_modules/@microsoft/power-apps/lib/internal/data/core/metadata/runtimeDataSourceService.js
2399
- var DataSourceServiceError;
2400
- /* @__PURE__ */ (function(DataSourceServiceError2) {
2401
- })(DataSourceServiceError || (DataSourceServiceError = {}));
2402
- var RuntimeDataSourceService = class {
2403
- /**
2404
- * Creates a new instance of RuntimeDataSourceService
2405
- */
2406
- constructor(_powerDataSourcesInfoProvider) {
2407
- __publicField(this, "_powerDataSourcesInfoProvider");
2408
- /**
2409
- * Data source information
2410
- */
2411
- __publicField(this, "_dataSourcesInfo");
2412
- /**
2413
- * Indicates whether the service has been initialized
2414
- */
2415
- __publicField(this, "_isInitialized");
2416
- this._powerDataSourcesInfoProvider = _powerDataSourcesInfoProvider;
2417
- this._dataSourcesInfo = {};
2418
- this._isInitialized = false;
2419
- }
2420
- /**
2421
- * Initializes the service by loading user data sources
2422
- * @throws PowerDataRuntimeError if initialization fails
2423
- */
2424
- async initialize() {
2425
- try {
2426
- const userDataSources = await this._getUserDataSources();
2427
- this._dataSourcesInfo = {};
2428
- Object.keys(userDataSources).forEach((key) => {
2429
- this._dataSourcesInfo[key] = userDataSources[key];
2430
- });
2431
- this._isInitialized = true;
2432
- } catch (error) {
2433
- throw new PowerDataRuntimeError(ErrorCodes.InitializationError, getErrorMessage(error));
2434
- }
2435
- }
2436
- /**
2437
- * Gets all user data sources
2438
- * @returns Array of data source information
2439
- * @throws PowerDataRuntimeError if service is not initialized
2440
- */
2441
- async getUserDataSources() {
2442
- await this._ensureInitialized();
2443
- return this._dataSourcesInfo;
2444
- }
2445
- /**
2446
- * Gets information for a specific data source
2447
- * @param dataSource - The ID of the data source
2448
- * @returns Data source information
2449
- * @throws PowerDataRuntimeError if data source is not found or service is not initialized
2450
- */
2451
- async getDataSource(dataSource) {
2452
- await this._ensureInitialized();
2453
- const dataSourceInfo = this._dataSourcesInfo[dataSource];
2454
- if (!dataSourceInfo) {
2455
- const errorMessage = `Unable to find data source: ${dataSource} in data sources info.`;
2456
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, errorMessage);
2457
- }
2458
- return dataSourceInfo;
2459
- }
2460
- /**
2461
- * Checks if a data source exists
2462
- * @param dataSourceId - The ID of the data source to check
2463
- * @returns True if the data source exists, false otherwise
2464
- * @throws PowerDataRuntimeError if service is not initialized
2465
- */
2466
- async hasDataSource(dataSource) {
2467
- await this._ensureInitialized();
2468
- return dataSource in this._dataSourcesInfo;
2469
- }
2470
- /**
2471
- * Ensures the service is initialized
2472
- * @throws PowerDataRuntimeError if service is not initialized
2473
- */
2474
- async _ensureInitialized() {
2475
- if (!this._isInitialized) {
2476
- await this.initialize();
2477
- }
2478
- }
2479
- /**
2480
- * Gets user data sources from the provided data source schemas
2481
- * @returns Promise resolving to array of data source information
2482
- */
2483
- async _getUserDataSources() {
2484
- const dataSourcesInfo = await this._powerDataSourcesInfoProvider.getDataSourcesInfo();
2485
- return Promise.resolve(dataSourcesInfo);
2486
- }
2487
- };
2488
-
2489
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/powerDataRuntime.js
2490
- var PowerDataRuntime = class {
2491
- /**
2492
- * Creates a new instance of PowerDataRuntime
2493
- * @param params - Initialization parameters
2494
- * @throws DataRuntimeError if initialization fails
2495
- */
2496
- constructor(params) {
2497
- __publicField(this, "_clientProvider");
2498
- __publicField(this, "_dataSourceService");
2499
- __publicField(this, "_dataOperations");
2500
- __publicField(this, "_metadataOperations");
2501
- __publicField(this, "_isInitialized");
2502
- try {
2503
- Log.createInstance(params.powerOperationExecutor);
2504
- this._clientProvider = new RuntimeClientProvider(params.powerOperationExecutor);
2505
- this._dataSourceService = new RuntimeDataSourceService(params.powerDataSourcesInfoProvider);
2506
- this._isInitialized = false;
2507
- this._initialize();
2508
- } catch (error) {
2509
- if (error instanceof Error) {
2510
- Log.trackException(error);
2511
- }
2512
- throw error;
2513
- }
2514
- }
2515
- /**
2516
- * Gets the Data operations interface
2517
- * @throws PowerDataRuntimeError if operations are not initialized
2518
- */
2519
- get Data() {
2520
- this._ensureInitialized();
2521
- if (!this._dataOperations) {
2522
- this._dataOperations = this._createDataOperations();
2523
- }
2524
- return this._dataOperations;
2525
- }
2526
- /**
2527
- * Gets the Metadata operations interface
2528
- * @throws PowerDataRuntimeError if operations are not initialized
2529
- */
2530
- get Metadata() {
2531
- this._ensureInitialized();
2532
- if (!this._metadataOperations) {
2533
- this._metadataOperations = this._createMetadataOperations();
2534
- }
2535
- return this._metadataOperations;
2536
- }
2537
- /**
2538
- * Ensures the PowerDataRuntime is initialized
2539
- * @throws PowerDataRuntimeError if not initialized
2540
- */
2541
- _ensureInitialized() {
2542
- if (!this._isInitialized) {
2543
- throw new PowerDataRuntimeError(ErrorCodes.OperationsNotInitialized);
2544
- }
2545
- }
2546
- /**
2547
- * Initializes the PowerDataRuntime components
2548
- * @throws PowerDataRuntimeError if initialization fails
2549
- */
2550
- _initialize() {
2551
- try {
2552
- this._dataOperations = this._createDataOperations();
2553
- this._metadataOperations = this._createMetadataOperations();
2554
- this._isInitialized = true;
2555
- } catch (error) {
2556
- throw new PowerDataRuntimeError(ErrorCodes.InitializationFailed, getErrorMessage(error));
2557
- }
2558
- }
2559
- /**
2560
- * Creates a new instance of DataOperations
2561
- */
2562
- _createDataOperations() {
2563
- const dataverseOperation = new DataverseDataOperationExecutor(this._clientProvider);
2564
- const connectorOperation = new ConnectorDataOperationExecutor(this._clientProvider, this._dataSourceService);
2565
- return new DefaultDataOperationOrchestrator(dataverseOperation, connectorOperation, this._dataSourceService);
2566
- }
2567
- /**
2568
- * Creates a new instance of MetadataOperations
2569
- */
2570
- _createMetadataOperations() {
2571
- return new RuntimeMetadataOperations(this._clientProvider);
2572
- }
2573
- };
2574
-
2575
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/powerDataRuntimeInstance.js
2576
- var powerDataRuntimeInstance;
2577
- function getPowerDataRuntime(powerDataSourcesInfoProvider, powerOperationExecutor) {
2578
- if (!powerDataRuntimeInstance) {
2579
- powerDataRuntimeInstance = new PowerDataRuntime({
2580
- powerDataSourcesInfoProvider,
2581
- powerOperationExecutor
2582
- });
2583
- }
2584
- return powerDataRuntimeInstance;
2585
- }
2586
-
2587
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/powerDataSourcesInfoProvider.js
2588
- var _PowerDataSourcesInfoProvider = class _PowerDataSourcesInfoProvider {
2589
- /**
2590
- * Private constructor to enforce the singleton pattern.
2591
- * @param dataSourcesInfo The data sources information to initialize the provider with.
2592
- */
2593
- constructor(dataSourcesInfo) {
2594
- __publicField(this, "dataSourcesInfo");
2595
- this.dataSourcesInfo = dataSourcesInfo;
2596
- }
2597
- /**
2598
- * Retrieves the singleton instance of PowerDataSourcesInfoProvider.
2599
- * If the instance does not exist, it initializes it with the provided data sources info.
2600
- *
2601
- * @param dataSourcesInfo Optional parameter to initialize the instance if it doesn't exist.
2602
- * @returns The singleton instance of PowerDataSourcesInfoProvider.
2603
- * @throws Error if the instance is not initialized and no dataSourcesInfo is provided.
2604
- */
2605
- static getInstance(dataSourcesInfo) {
2606
- if (!this.instance) {
2607
- if (!dataSourcesInfo) {
2608
- throw new PowerDataRuntimeError(ErrorCodes.DataSourcesInfoNotFound);
2609
- }
2610
- this.instance = new _PowerDataSourcesInfoProvider(dataSourcesInfo);
2611
- }
2612
- return this.instance;
2613
- }
2614
- /**
2615
- * Retrieves the data sources information.
2616
- *
2617
- * @returns A promise resolving to the data sources information.
2618
- */
2619
- async getDataSourcesInfo() {
2620
- return this.dataSourcesInfo;
2621
- }
2622
- };
2623
- __publicField(_PowerDataSourcesInfoProvider, "instance", null);
2624
- var PowerDataSourcesInfoProvider = _PowerDataSourcesInfoProvider;
2625
- var powerDataSourcesInfoProvider_default = PowerDataSourcesInfoProvider;
2626
-
2627
- // node_modules/@microsoft/power-apps/lib/internal/data/ConnectionUtils.js
2628
- var connectionsLoaded = false;
2629
- async function loadConnections() {
2630
- if (connectionsLoaded) {
2631
- return;
2632
- }
2633
- connectionsLoaded = true;
2634
- await loadNonCompositeConnectionsAsync();
2635
- await resolveCompositeConnectionsAsync();
2636
- }
2637
- async function loadNonCompositeConnectionsAsync() {
2638
- return executePluginAsync("AppPowerAppsClientPlugin", "loadNonCompositeConnectionsAsync", []);
2639
- }
2640
- async function resolveCompositeConnectionsAsync() {
2641
- return executePluginAsync("AppPowerAppsClientPlugin", "resolveCompositeConnectionsAsync", []);
2642
- }
2643
-
2644
- // node_modules/@microsoft/power-apps/lib/internal/data/OperationExecutor.js
2645
- var loadConnectionsPromise;
2646
- var OperationExecutor = class {
2647
- /**
2648
- * Executes an operation using the plugin.
2649
- * @param operationName The name of the operation.
2650
- * @param action The action to perform.
2651
- * @param params The parameters for the operation.
2652
- * @returns A promise resolving to the operation result.
2653
- */
2654
- async execute(operationName, action, params) {
2655
- try {
2656
- if (!loadConnectionsPromise) {
2657
- loadConnectionsPromise = loadConnections();
2658
- }
2659
- await loadConnectionsPromise;
2660
- const result = await executePluginAsync(operationName, action, params);
2661
- return {
2662
- success: true,
2663
- data: result
2664
- };
2665
- } catch (error) {
2666
- throw error;
2667
- }
2668
- }
2669
- };
2670
-
2671
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/getRuntimeContext.js
2672
- var _executor;
2673
- function getExecutor() {
2674
- if (!_executor) {
2675
- _executor = new OperationExecutor();
2676
- }
2677
- return _executor;
2678
- }
2679
- async function getPowerSdkInstance(dataSourcesInfo) {
2680
- const executor = getExecutor();
2681
- const provider = powerDataSourcesInfoProvider_default.getInstance(dataSourcesInfo);
2682
- return getPowerDataRuntime(provider, executor);
2683
- }
2684
-
2685
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/createRecord.js
2686
- async function createRecordAsync(dataSourcesInfo, tableName, record) {
2687
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.createRecordAsync(tableName, record);
2688
- }
2689
-
2690
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/updateRecord.js
2691
- async function updateRecordAsync(dataSourcesInfo, tableName, recordId, changes) {
2692
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.updateRecordAsync(tableName, recordId, changes);
2693
- }
2694
-
2695
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/deleteRecord.js
2696
- async function deleteRecordAsync(dataSourcesInfo, tableName, recordId) {
2697
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.deleteRecordAsync(tableName, recordId);
2698
- }
2699
-
2700
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/retrieveRecord.js
2701
- async function retrieveRecordAsync(dataSourcesInfo, tableName, recordId, options) {
2702
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.retrieveRecordAsync(tableName, recordId, options);
2703
- }
2704
-
2705
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/retrieveMultipleRecords.js
2706
- async function retrieveMultipleRecordsAsync(dataSourcesInfo, tableName, options) {
2707
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.retrieveMultipleRecordsAsync(tableName, options);
2708
- }
2709
-
2710
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/execute.js
2711
- async function executeAsync(dataSourcesInfo, operation) {
2712
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.executeAsync(operation);
2713
- }
2714
-
2715
- // node_modules/@microsoft/power-apps/lib/data/powerAppsData.js
2716
- var _dataOperationExecutor;
2717
- function getDataOperationExecutor() {
2718
- return _dataOperationExecutor;
2719
- }
2720
- function setDataOperationExecutor(dataOperationExecutorOverride) {
2721
- _dataOperationExecutor = dataOperationExecutorOverride;
2722
- }
2723
- function getClient(dataSourcesInfo) {
2724
- return {
2725
- createRecordAsync: (tableName, record) => {
2726
- return createRecordAsync(dataSourcesInfo, tableName, record);
2727
- },
2728
- deleteRecordAsync: (tableName, recordId) => {
2729
- return deleteRecordAsync(dataSourcesInfo, tableName, recordId);
2730
- },
2731
- executeAsync: (operation) => {
2732
- return executeAsync(dataSourcesInfo, operation);
2733
- },
2734
- retrieveMultipleRecordsAsync: (tableName, options) => {
2735
- return retrieveMultipleRecordsAsync(dataSourcesInfo, tableName, options);
2736
- },
2737
- retrieveRecordAsync: (tableName, recordId, options) => {
2738
- return retrieveRecordAsync(dataSourcesInfo, tableName, recordId, options);
2739
- },
2740
- updateRecordAsync: (tableName, recordId, changes) => {
2741
- return updateRecordAsync(dataSourcesInfo, tableName, recordId, changes);
2742
- }
2743
- };
2744
- }
2745
-
2746
- // node_modules/@microsoft/power-apps/lib/internal/data/core/data/executors/mockDataOperationExecutor.js
2747
- var MockDataOperationExecutor = class {
2748
- constructor(data) {
2749
- __publicField(this, "_dataStore");
2750
- this._dataStore = data;
2751
- }
2752
- async createRecordAsync(tableName, data) {
2753
- return {
2754
- success: false,
2755
- error: { message: "createRecordAsync is not supported by MockDataOperationExecutor" },
2756
- data: null
2757
- };
2758
- }
2759
- async updateRecordAsync(tableName, id, data) {
2760
- return {
2761
- success: false,
2762
- error: { message: "updateRecordAsync is not supported by MockDataOperationExecutor" },
2763
- data: null
2764
- };
2765
- }
2766
- async deleteRecordAsync(tableName, id) {
2767
- return {
2768
- success: false,
2769
- error: { message: "deleteRecordAsync is not supported by MockDataOperationExecutor" },
2770
- data: void 0
2771
- };
2772
- }
2773
- async retrieveRecordAsync(tableName, id, options) {
2774
- if (!this._dataStore[tableName]) {
2775
- return {
2776
- success: false,
2777
- error: { message: `table <${tableName}> not found` },
2778
- data: null
2779
- };
2780
- }
2781
- const record = this._dataStore[tableName][id];
2782
- if (!record) {
2783
- return {
2784
- success: false,
2785
- error: { message: `record with id "${id}" not found in table <${tableName}>` },
2786
- data: null
2787
- };
2788
- }
2789
- return {
2790
- success: true,
2791
- data: record
2792
- };
2793
- }
2794
- async retrieveMultipleRecordsAsync(tableName, options) {
2795
- if (!this._dataStore[tableName]) {
2796
- return {
2797
- success: false,
2798
- error: { message: `table <${tableName}> not found` },
2799
- data: []
2800
- };
2801
- }
2802
- return {
2803
- success: true,
2804
- data: Object.values(this._dataStore[tableName])
2805
- };
2806
- }
2807
- async executeAsync(operation) {
2808
- return {
2809
- success: false,
2810
- error: { message: "executeAsync is not supported by MockDataOperationExecutor" },
2811
- data: null
2812
- };
2813
- }
2814
- };
2815
- function createMockDataExecutor(data) {
2816
- return new MockDataOperationExecutor(data);
2817
- }
2818
-
2819
- // node_modules/@microsoft/power-apps/lib/internal/data/core/types/dataverseMetadata.js
2820
- var entityClusterModeEnum = {
2821
- 0: "Partitioned",
2822
- 1: "Replicated",
2823
- 2: "Local"
2824
- };
2825
- function getEntityClusterModeName(value) {
2826
- return entityClusterModeEnum[value];
2827
- }
2828
- var ownershipTypeEnum = {
2829
- 0: "None",
2830
- 1: "UserOwned",
2831
- 2: "TeamOwned",
2832
- 4: "BusinessOwned",
2833
- 8: "OrganizationOwned",
2834
- 16: "BusinessParented",
2835
- 32: "Filtered"
2836
- };
2837
- function getOwnershipTypeName(value) {
2838
- return ownershipTypeEnum[value];
2839
- }
2840
- var privilegeTypeEnum = {
2841
- 0: "None",
2842
- 1: "Create",
2843
- 2: "Read",
2844
- 3: "Write",
2845
- 4: "Delete",
2846
- 5: "Assign",
2847
- 6: "Share",
2848
- 7: "Append",
2849
- 8: "AppendTo"
2850
- };
2851
- function getPrivilegeTypeName(value) {
2852
- return privilegeTypeEnum[value];
2853
- }
2854
- var attributeTypeCodeEnum = {
2855
- 0: "Boolean",
2856
- 1: "Customer",
2857
- 2: "DateTime",
2858
- 3: "Decimal",
2859
- 4: "Double",
2860
- 5: "Integer",
2861
- 6: "Lookup",
2862
- 7: "Memo",
2863
- 8: "Money",
2864
- 9: "Owner",
2865
- 10: "PartyList",
2866
- 11: "Picklist",
2867
- 12: "State",
2868
- 13: "Status",
2869
- 14: "String",
2870
- 15: "Uniqueidentifier",
2871
- 16: "CalendarRules",
2872
- 17: "Virtual",
2873
- 18: "BigInt",
2874
- 19: "ManagedProperty",
2875
- 20: "EntityName"
2876
- };
2877
- function getAttributeTypeCodeName(value) {
2878
- return attributeTypeCodeEnum[value];
2879
- }
2880
- var attributeRequiredLevelEnum = {
2881
- 0: "None",
2882
- 1: "SystemRequired",
2883
- 2: "ApplicationRequired",
2884
- 3: "Recommended"
2885
- };
2886
- function getAttributeRequiredLevelName(value) {
2887
- return attributeRequiredLevelEnum[value];
2888
- }
2889
- var relationshipTypeEnum = {
2890
- 0: "OneToManyRelationship",
2891
- 1: "ManyToManyRelationship"
2892
- };
2893
- function getRelationshipTypeName(value) {
2894
- return relationshipTypeEnum[value];
2895
- }
2896
- var securityTypesEnum = {
2897
- 0: "None",
2898
- 1: "Append",
2899
- 2: "ParentChild",
2900
- 8: "Pointer",
2901
- 16: "Inheritance"
2902
- // The referencing entity record inherits security from the referenced security record.
2903
- };
2904
- function getSecurityTypesName(value) {
2905
- return securityTypesEnum[value];
2906
- }
2907
- var associatedMenuBehaviorEnum = {
2908
- 0: "UseCollectionName",
2909
- 1: "UseLabel",
2910
- 2: "DoNotDisplay"
2911
- };
2912
- function getAssociatedMenuBehaviorName(value) {
2913
- return associatedMenuBehaviorEnum[value];
2914
- }
2915
- var associatedMenuGroupEnum = {
2916
- 0: "Details",
2917
- 1: "Sales",
2918
- 2: "Service",
2919
- 3: "Marketing"
2920
- };
2921
- function getAssociatedMenuGroupName(value) {
2922
- return associatedMenuGroupEnum[value];
2923
- }
2924
- var cascadeTypeEnum = {
2925
- 0: "NoCascade",
2926
- 1: "Cascade",
2927
- 2: "Active",
2928
- 3: "UserOwned",
2929
- 4: "RemoveLink",
2930
- 5: "Restrict"
2931
- // Prevent the Referenced entity record from being deleted when referencing entities exist.
2932
- };
2933
- function getCascadeTypeName(value) {
2934
- return cascadeTypeEnum[value];
2935
- }
2936
- export {
2937
- createMockDataExecutor,
2938
- getAssociatedMenuBehaviorName,
2939
- getAssociatedMenuGroupName,
2940
- getAttributeRequiredLevelName,
2941
- getAttributeTypeCodeName,
2942
- getCascadeTypeName,
2943
- getClient,
2944
- getContext,
2945
- getEntityClusterModeName,
2946
- getOwnershipTypeName,
2947
- getPrivilegeTypeName,
2948
- getRelationshipTypeName,
2949
- getSecurityTypesName,
2950
- initializeLogger,
2951
- setConfig,
2952
- setDataOperationExecutor
2953
- };