windmill-client 1.615.2 → 1.615.4

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.
package/dist/client.js DELETED
@@ -1,1291 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __asyncValues = (this && this.__asyncValues) || function (o) {
12
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
- var m = o[Symbol.asyncIterator], i;
14
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
- };
18
- Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.SHARED_FOLDER = exports.TeamsService = exports.WorkspaceService = exports.UserService = exports.SettingsService = exports.ScheduleService = exports.ScriptService = exports.VariableService = exports.ResourceService = exports.JobService = exports.GroupService = exports.GranularAclService = exports.FlowService = exports.AuditService = exports.AdminService = exports.ducklake = exports.datatable = void 0;
20
- exports.setClient = setClient;
21
- exports.getWorkspace = getWorkspace;
22
- exports.getResource = getResource;
23
- exports.getRootJobId = getRootJobId;
24
- exports.runScript = runScript;
25
- exports.runScriptByPath = runScriptByPath;
26
- exports.runScriptByHash = runScriptByHash;
27
- exports.appendToResultStream = appendToResultStream;
28
- exports.streamResult = streamResult;
29
- exports.runFlow = runFlow;
30
- exports.waitJob = waitJob;
31
- exports.getResult = getResult;
32
- exports.getResultMaybe = getResultMaybe;
33
- exports.task = task;
34
- exports.runScriptAsync = runScriptAsync;
35
- exports.runScriptByPathAsync = runScriptByPathAsync;
36
- exports.runScriptByHashAsync = runScriptByHashAsync;
37
- exports.runFlowAsync = runFlowAsync;
38
- exports.resolveDefaultResource = resolveDefaultResource;
39
- exports.getStatePath = getStatePath;
40
- exports.setResource = setResource;
41
- exports.setInternalState = setInternalState;
42
- exports.setState = setState;
43
- exports.setProgress = setProgress;
44
- exports.getProgress = getProgress;
45
- exports.setFlowUserState = setFlowUserState;
46
- exports.getFlowUserState = getFlowUserState;
47
- exports.getInternalState = getInternalState;
48
- exports.getState = getState;
49
- exports.getVariable = getVariable;
50
- exports.setVariable = setVariable;
51
- exports.databaseUrlFromResource = databaseUrlFromResource;
52
- exports.denoS3LightClientSettings = denoS3LightClientSettings;
53
- exports.loadS3File = loadS3File;
54
- exports.loadS3FileStream = loadS3FileStream;
55
- exports.writeS3File = writeS3File;
56
- exports.signS3Objects = signS3Objects;
57
- exports.signS3Object = signS3Object;
58
- exports.getPresignedS3PublicUrls = getPresignedS3PublicUrls;
59
- exports.getPresignedS3PublicUrl = getPresignedS3PublicUrl;
60
- exports.getResumeUrls = getResumeUrls;
61
- exports.getResumeEndpoints = getResumeEndpoints;
62
- exports.getIdToken = getIdToken;
63
- exports.base64ToUint8Array = base64ToUint8Array;
64
- exports.uint8ArrayToBase64 = uint8ArrayToBase64;
65
- exports.usernameToEmail = usernameToEmail;
66
- exports.requestInteractiveSlackApproval = requestInteractiveSlackApproval;
67
- exports.requestInteractiveTeamsApproval = requestInteractiveTeamsApproval;
68
- exports.parseS3Object = parseS3Object;
69
- const index_1 = require("./index");
70
- const index_2 = require("./index");
71
- var sqlUtils_1 = require("./sqlUtils");
72
- Object.defineProperty(exports, "datatable", { enumerable: true, get: function () { return sqlUtils_1.datatable; } });
73
- Object.defineProperty(exports, "ducklake", { enumerable: true, get: function () { return sqlUtils_1.ducklake; } });
74
- var index_3 = require("./index");
75
- Object.defineProperty(exports, "AdminService", { enumerable: true, get: function () { return index_3.AdminService; } });
76
- Object.defineProperty(exports, "AuditService", { enumerable: true, get: function () { return index_3.AuditService; } });
77
- Object.defineProperty(exports, "FlowService", { enumerable: true, get: function () { return index_3.FlowService; } });
78
- Object.defineProperty(exports, "GranularAclService", { enumerable: true, get: function () { return index_3.GranularAclService; } });
79
- Object.defineProperty(exports, "GroupService", { enumerable: true, get: function () { return index_3.GroupService; } });
80
- Object.defineProperty(exports, "JobService", { enumerable: true, get: function () { return index_3.JobService; } });
81
- Object.defineProperty(exports, "ResourceService", { enumerable: true, get: function () { return index_3.ResourceService; } });
82
- Object.defineProperty(exports, "VariableService", { enumerable: true, get: function () { return index_3.VariableService; } });
83
- Object.defineProperty(exports, "ScriptService", { enumerable: true, get: function () { return index_3.ScriptService; } });
84
- Object.defineProperty(exports, "ScheduleService", { enumerable: true, get: function () { return index_3.ScheduleService; } });
85
- Object.defineProperty(exports, "SettingsService", { enumerable: true, get: function () { return index_3.SettingsService; } });
86
- Object.defineProperty(exports, "UserService", { enumerable: true, get: function () { return index_3.UserService; } });
87
- Object.defineProperty(exports, "WorkspaceService", { enumerable: true, get: function () { return index_3.WorkspaceService; } });
88
- Object.defineProperty(exports, "TeamsService", { enumerable: true, get: function () { return index_3.TeamsService; } });
89
- exports.SHARED_FOLDER = "/shared";
90
- let mockedApi = undefined;
91
- /**
92
- * Initialize the Windmill client with authentication token and base URL
93
- * @param token - Authentication token (defaults to WM_TOKEN env variable)
94
- * @param baseUrl - API base URL (defaults to BASE_INTERNAL_URL or BASE_URL env variable)
95
- */
96
- function setClient(token, baseUrl) {
97
- var _a, _b, _c;
98
- if (baseUrl === undefined) {
99
- baseUrl =
100
- (_b = (_a = getEnv("BASE_INTERNAL_URL")) !== null && _a !== void 0 ? _a : getEnv("BASE_URL")) !== null && _b !== void 0 ? _b : "http://localhost:8000";
101
- }
102
- if (token === undefined) {
103
- token = (_c = getEnv("WM_TOKEN")) !== null && _c !== void 0 ? _c : "no_token";
104
- }
105
- index_2.OpenAPI.WITH_CREDENTIALS = true;
106
- index_2.OpenAPI.TOKEN = token;
107
- index_2.OpenAPI.BASE = baseUrl + "/api";
108
- }
109
- function getPublicBaseUrl() {
110
- var _a;
111
- return (_a = getEnv("WM_BASE_URL")) !== null && _a !== void 0 ? _a : "http://localhost:3000";
112
- }
113
- const getEnv = (key) => {
114
- var _a, _b, _c;
115
- if (typeof window === "undefined") {
116
- // node
117
- return (_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a[key];
118
- }
119
- // browser
120
- return (_c = (_b = window === null || window === void 0 ? void 0 : window.process) === null || _b === void 0 ? void 0 : _b.env) === null || _c === void 0 ? void 0 : _c[key];
121
- };
122
- /**
123
- * Create a client configuration from env variables
124
- * @returns client configuration
125
- */
126
- function getWorkspace() {
127
- var _a;
128
- return (_a = getEnv("WM_WORKSPACE")) !== null && _a !== void 0 ? _a : "no_workspace";
129
- }
130
- /**
131
- * Get a resource value by path
132
- * @param path path of the resource, default to internal state path
133
- * @param undefinedIfEmpty if the resource does not exist, return undefined instead of throwing an error
134
- * @returns resource value
135
- */
136
- function getResource(path, undefinedIfEmpty) {
137
- return __awaiter(this, void 0, void 0, function* () {
138
- var _a, _b;
139
- path = (_b = (_a = parseResourceSyntax(path)) !== null && _a !== void 0 ? _a : path) !== null && _b !== void 0 ? _b : getStatePath();
140
- const mockedApi = yield getMockedApi();
141
- if (mockedApi) {
142
- if (mockedApi.resources[path]) {
143
- return mockedApi.resources[path];
144
- }
145
- else {
146
- console.log(`MockedAPI present, but resource not found at ${path}, falling back to real API`);
147
- }
148
- }
149
- const workspace = getWorkspace();
150
- try {
151
- return yield index_1.ResourceService.getResourceValueInterpolated({
152
- workspace,
153
- path,
154
- });
155
- }
156
- catch (e) {
157
- if (undefinedIfEmpty && e.status === 404) {
158
- return undefined;
159
- }
160
- else {
161
- throw Error(`Resource not found at ${path} or not visible to you: ${e.body}`);
162
- }
163
- }
164
- });
165
- }
166
- /**
167
- * Get the true root job id
168
- * @param jobId job id to get the root job id from (default to current job)
169
- * @returns root job id
170
- */
171
- function getRootJobId(jobId) {
172
- return __awaiter(this, void 0, void 0, function* () {
173
- const workspace = getWorkspace();
174
- jobId = jobId !== null && jobId !== void 0 ? jobId : getEnv("WM_JOB_ID");
175
- if (jobId === undefined) {
176
- throw Error("Job ID not set");
177
- }
178
- return yield index_1.JobService.getRootJobId({ workspace, id: jobId });
179
- });
180
- }
181
- /**
182
- * @deprecated Use runScriptByPath or runScriptByHash instead
183
- */
184
- function runScript() {
185
- return __awaiter(this, arguments, void 0, function* (path = null, hash_ = null, args = null, verbose = false) {
186
- console.warn("runScript is deprecated. Use runScriptByPath or runScriptByHash instead.");
187
- if (path && hash_) {
188
- throw new Error("path and hash_ are mutually exclusive");
189
- }
190
- return _runScriptInternal(path, hash_, args, verbose);
191
- });
192
- }
193
- function _runScriptInternal() {
194
- return __awaiter(this, arguments, void 0, function* (path = null, hash_ = null, args = null, verbose = false) {
195
- args = args || {};
196
- if (verbose) {
197
- if (path) {
198
- console.info(`running \`${path}\` synchronously with args:`, args);
199
- }
200
- else if (hash_) {
201
- console.info(`running script with hash \`${hash_}\` synchronously with args:`, args);
202
- }
203
- }
204
- const jobId = yield _runScriptAsyncInternal(path, hash_, args);
205
- return yield waitJob(jobId, verbose);
206
- });
207
- }
208
- /**
209
- * Run a script synchronously by its path and wait for the result
210
- * @param path - Script path in Windmill
211
- * @param args - Arguments to pass to the script
212
- * @param verbose - Enable verbose logging
213
- * @returns Script execution result
214
- */
215
- function runScriptByPath(path_1) {
216
- return __awaiter(this, arguments, void 0, function* (path, args = null, verbose = false) {
217
- return _runScriptInternal(path, null, args, verbose);
218
- });
219
- }
220
- /**
221
- * Run a script synchronously by its hash and wait for the result
222
- * @param hash_ - Script hash in Windmill
223
- * @param args - Arguments to pass to the script
224
- * @param verbose - Enable verbose logging
225
- * @returns Script execution result
226
- */
227
- function runScriptByHash(hash_1) {
228
- return __awaiter(this, arguments, void 0, function* (hash_, args = null, verbose = false) {
229
- return _runScriptInternal(null, hash_, args, verbose);
230
- });
231
- }
232
- /**
233
- * Append a text to the result stream
234
- * @param text text to append to the result stream
235
- */
236
- function appendToResultStream(text) {
237
- console.log("WM_STREAM: " + text.replace(/\n/g, "\\n"));
238
- }
239
- /**
240
- * Stream to the result stream
241
- * @param stream stream to stream to the result stream
242
- */
243
- function streamResult(stream) {
244
- return __awaiter(this, void 0, void 0, function* () {
245
- var _a, stream_1, stream_1_1;
246
- var _b, e_1, _c, _d;
247
- try {
248
- for (_a = true, stream_1 = __asyncValues(stream); stream_1_1 = yield stream_1.next(), _b = stream_1_1.done, !_b; _a = true) {
249
- _d = stream_1_1.value;
250
- _a = false;
251
- const text = _d;
252
- appendToResultStream(text);
253
- }
254
- }
255
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
256
- finally {
257
- try {
258
- if (!_a && !_b && (_c = stream_1.return)) yield _c.call(stream_1);
259
- }
260
- finally { if (e_1) throw e_1.error; }
261
- }
262
- });
263
- }
264
- /**
265
- * Run a flow synchronously by its path and wait for the result
266
- * @param path - Flow path in Windmill
267
- * @param args - Arguments to pass to the flow
268
- * @param verbose - Enable verbose logging
269
- * @returns Flow execution result
270
- */
271
- function runFlow() {
272
- return __awaiter(this, arguments, void 0, function* (path = null, args = null, verbose = false) {
273
- args = args || {};
274
- if (verbose) {
275
- console.info(`running \`${path}\` synchronously with args:`, args);
276
- }
277
- const jobId = yield runFlowAsync(path, args, null, false);
278
- return yield waitJob(jobId, verbose);
279
- });
280
- }
281
- /**
282
- * Wait for a job to complete and return its result
283
- * @param jobId - ID of the job to wait for
284
- * @param verbose - Enable verbose logging
285
- * @returns Job result when completed
286
- */
287
- function waitJob(jobId_1) {
288
- return __awaiter(this, arguments, void 0, function* (jobId, verbose = false) {
289
- while (true) {
290
- // Implement your HTTP request logic here to get job result
291
- const resultRes = yield getResultMaybe(jobId);
292
- const started = resultRes.started;
293
- const completed = resultRes.completed;
294
- const success = resultRes.success;
295
- if (!started && verbose) {
296
- console.info(`job ${jobId} has not started yet`);
297
- }
298
- if (completed) {
299
- const result = resultRes.result;
300
- if (success) {
301
- return result;
302
- }
303
- else {
304
- const error = result.error;
305
- throw new Error(`Job ${jobId} was not successful: ${JSON.stringify(error)}`);
306
- }
307
- }
308
- if (verbose) {
309
- console.info(`sleeping 0.5 seconds for jobId: ${jobId}`);
310
- }
311
- yield new Promise((resolve) => setTimeout(resolve, 500));
312
- }
313
- });
314
- }
315
- /**
316
- * Get the result of a completed job
317
- * @param jobId - ID of the completed job
318
- * @returns Job result
319
- */
320
- function getResult(jobId) {
321
- return __awaiter(this, void 0, void 0, function* () {
322
- const workspace = getWorkspace();
323
- return yield index_1.JobService.getCompletedJobResult({ workspace, id: jobId });
324
- });
325
- }
326
- /**
327
- * Get the result of a job if completed, or its current status
328
- * @param jobId - ID of the job
329
- * @returns Object with started, completed, success, and result properties
330
- */
331
- function getResultMaybe(jobId) {
332
- return __awaiter(this, void 0, void 0, function* () {
333
- const workspace = getWorkspace();
334
- return yield index_1.JobService.getCompletedJobResultMaybe({ workspace, id: jobId });
335
- });
336
- }
337
- const STRIP_COMMENTS = /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\\'|[^'\r\n])*')|("(?:\\"|[^"\r\n])*"))|(\s*=[^,\)]*))/gm;
338
- const ARGUMENT_NAMES = /([^\s,]+)/g;
339
- function getParamNames(func) {
340
- const fnStr = func.toString().replace(STRIP_COMMENTS, "");
341
- let result = fnStr
342
- .slice(fnStr.indexOf("(") + 1, fnStr.indexOf(")"))
343
- .match(ARGUMENT_NAMES);
344
- if (result === null)
345
- result = [];
346
- return result;
347
- }
348
- /**
349
- * Wrap a function to execute as a Windmill task within a flow context
350
- * @param f - Function to wrap as a task
351
- * @returns Async wrapper function that executes as a Windmill job
352
- */
353
- function task(f) {
354
- return (...y) => __awaiter(this, void 0, void 0, function* () {
355
- const args = {};
356
- const paramNames = getParamNames(f);
357
- y.forEach((x, i) => (args[paramNames[i]] = x));
358
- let req = yield fetch(`${index_2.OpenAPI.BASE}/w/${getWorkspace()}/jobs/run/workflow_as_code/${getEnv("WM_JOB_ID")}/${f.name}`, {
359
- method: "POST",
360
- headers: {
361
- "Content-Type": "application/json",
362
- Authorization: `Bearer ${getEnv("WM_TOKEN")}`,
363
- },
364
- body: JSON.stringify({ args }),
365
- });
366
- let jobId = yield req.text();
367
- console.log(`Started task ${f.name} as job ${jobId}`);
368
- let r = yield waitJob(jobId);
369
- console.log(`Task ${f.name} (${jobId}) completed`);
370
- return r;
371
- });
372
- }
373
- /**
374
- * @deprecated Use runScriptByPathAsync or runScriptByHashAsync instead
375
- */
376
- function runScriptAsync(path_1, hash_1, args_1) {
377
- return __awaiter(this, arguments, void 0, function* (path, hash_, args, scheduledInSeconds = null) {
378
- console.warn("runScriptAsync is deprecated. Use runScriptByPathAsync or runScriptByHashAsync instead.");
379
- // Create a script job and return its job id.
380
- if (path && hash_) {
381
- throw new Error("path and hash_ are mutually exclusive");
382
- }
383
- return _runScriptAsyncInternal(path, hash_, args, scheduledInSeconds);
384
- });
385
- }
386
- function _runScriptAsyncInternal() {
387
- return __awaiter(this, arguments, void 0, function* (path = null, hash_ = null, args = null, scheduledInSeconds = null) {
388
- // Create a script job and return its job id.
389
- args = args || {};
390
- const params = {};
391
- if (scheduledInSeconds) {
392
- params["scheduled_in_secs"] = scheduledInSeconds;
393
- }
394
- let parentJobId = getEnv("WM_JOB_ID");
395
- if (parentJobId !== undefined) {
396
- params["parent_job"] = parentJobId;
397
- }
398
- let rootJobId = getEnv("WM_ROOT_FLOW_JOB_ID");
399
- if (rootJobId != undefined && rootJobId != "") {
400
- params["root_job"] = rootJobId;
401
- }
402
- let endpoint;
403
- if (path) {
404
- endpoint = `/w/${getWorkspace()}/jobs/run/p/${path}`;
405
- }
406
- else if (hash_) {
407
- endpoint = `/w/${getWorkspace()}/jobs/run/h/${hash_}`;
408
- }
409
- else {
410
- throw new Error("path or hash_ must be provided");
411
- }
412
- let url = new URL(index_2.OpenAPI.BASE + endpoint);
413
- url.search = new URLSearchParams(params).toString();
414
- return fetch(url, {
415
- method: "POST",
416
- headers: {
417
- "Content-Type": "application/json",
418
- Authorization: `Bearer ${index_2.OpenAPI.TOKEN}`,
419
- },
420
- body: JSON.stringify(args),
421
- }).then((res) => res.text());
422
- });
423
- }
424
- /**
425
- * Run a script asynchronously by its path
426
- * @param path - Script path in Windmill
427
- * @param args - Arguments to pass to the script
428
- * @param scheduledInSeconds - Schedule execution for a future time (in seconds)
429
- * @returns Job ID of the created job
430
- */
431
- function runScriptByPathAsync(path_1) {
432
- return __awaiter(this, arguments, void 0, function* (path, args = null, scheduledInSeconds = null) {
433
- return _runScriptAsyncInternal(path, null, args, scheduledInSeconds);
434
- });
435
- }
436
- /**
437
- * Run a script asynchronously by its hash
438
- * @param hash_ - Script hash in Windmill
439
- * @param args - Arguments to pass to the script
440
- * @param scheduledInSeconds - Schedule execution for a future time (in seconds)
441
- * @returns Job ID of the created job
442
- */
443
- function runScriptByHashAsync(hash_1) {
444
- return __awaiter(this, arguments, void 0, function* (hash_, args = null, scheduledInSeconds = null) {
445
- return _runScriptAsyncInternal(null, hash_, args, scheduledInSeconds);
446
- });
447
- }
448
- /**
449
- * Run a flow asynchronously by its path
450
- * @param path - Flow path in Windmill
451
- * @param args - Arguments to pass to the flow
452
- * @param scheduledInSeconds - Schedule execution for a future time (in seconds)
453
- * @param doNotTrackInParent - If false, tracks state in parent job (only use when fully awaiting the job)
454
- * @returns Job ID of the created job
455
- */
456
- function runFlowAsync(path_1, args_1) {
457
- return __awaiter(this, arguments, void 0, function* (path, args, scheduledInSeconds = null,
458
- // can only be set to false if this the job will be fully await and not concurrent with any other job
459
- // as otherwise the child flow and its own child will store their state in the parent job which will
460
- // lead to incorrectness and failures
461
- doNotTrackInParent = true) {
462
- // Create a script job and return its job id.
463
- args = args || {};
464
- const params = {};
465
- if (scheduledInSeconds) {
466
- params["scheduled_in_secs"] = scheduledInSeconds;
467
- }
468
- if (!doNotTrackInParent) {
469
- let parentJobId = getEnv("WM_JOB_ID");
470
- if (parentJobId !== undefined) {
471
- params["parent_job"] = parentJobId;
472
- }
473
- let rootJobId = getEnv("WM_ROOT_FLOW_JOB_ID");
474
- if (rootJobId != undefined && rootJobId != "") {
475
- params["root_job"] = rootJobId;
476
- }
477
- }
478
- let endpoint;
479
- if (path) {
480
- endpoint = `/w/${getWorkspace()}/jobs/run/f/${path}`;
481
- }
482
- else {
483
- throw new Error("path must be provided");
484
- }
485
- let url = new URL(index_2.OpenAPI.BASE + endpoint);
486
- url.search = new URLSearchParams(params).toString();
487
- return fetch(url, {
488
- method: "POST",
489
- headers: {
490
- "Content-Type": "application/json",
491
- Authorization: `Bearer ${index_2.OpenAPI.TOKEN}`,
492
- },
493
- body: JSON.stringify(args),
494
- }).then((res) => res.text());
495
- });
496
- }
497
- /**
498
- * Resolve a resource value in case the default value was picked because the input payload was undefined
499
- * @param obj resource value or path of the resource under the format `$res:path`
500
- * @returns resource value
501
- */
502
- function resolveDefaultResource(obj) {
503
- return __awaiter(this, void 0, void 0, function* () {
504
- if (typeof obj === "string" && obj.startsWith("$res:")) {
505
- return yield getResource(obj.substring(5), true);
506
- }
507
- else {
508
- return obj;
509
- }
510
- });
511
- }
512
- /**
513
- * Get the state file path from environment variables
514
- * @returns State path string
515
- */
516
- function getStatePath() {
517
- var _a;
518
- const state_path = (_a = getEnv("WM_STATE_PATH_NEW")) !== null && _a !== void 0 ? _a : getEnv("WM_STATE_PATH");
519
- if (state_path === undefined) {
520
- throw Error("State path not set");
521
- }
522
- return state_path;
523
- }
524
- /**
525
- * Set a resource value by path
526
- * @param path path of the resource to set, default to state path
527
- * @param value new value of the resource to set
528
- * @param initializeToTypeIfNotExist if the resource does not exist, initialize it with this type
529
- */
530
- function setResource(value, path, initializeToTypeIfNotExist) {
531
- return __awaiter(this, void 0, void 0, function* () {
532
- var _a, _b;
533
- path = (_b = (_a = parseResourceSyntax(path)) !== null && _a !== void 0 ? _a : path) !== null && _b !== void 0 ? _b : getStatePath();
534
- const mockedApi = yield getMockedApi();
535
- if (mockedApi) {
536
- mockedApi.resources[path] = value;
537
- return;
538
- }
539
- const workspace = getWorkspace();
540
- if (yield index_1.ResourceService.existsResource({ workspace, path })) {
541
- yield index_1.ResourceService.updateResourceValue({
542
- workspace,
543
- path,
544
- requestBody: { value },
545
- });
546
- }
547
- else if (initializeToTypeIfNotExist) {
548
- yield index_1.ResourceService.createResource({
549
- workspace,
550
- requestBody: { path, value, resource_type: initializeToTypeIfNotExist },
551
- });
552
- }
553
- else {
554
- throw Error(`Resource at path ${path} does not exist and no type was provided to initialize it`);
555
- }
556
- });
557
- }
558
- /**
559
- * Set the state
560
- * @param state state to set
561
- * @deprecated use setState instead
562
- */
563
- function setInternalState(state) {
564
- return __awaiter(this, void 0, void 0, function* () {
565
- yield setResource(state, undefined, "state");
566
- });
567
- }
568
- /**
569
- * Set the state
570
- * @param state state to set
571
- * @param path Optional state resource path override. Defaults to `getStatePath()`.
572
- */
573
- function setState(state, path) {
574
- return __awaiter(this, void 0, void 0, function* () {
575
- yield setResource(state, path !== null && path !== void 0 ? path : getStatePath(), "state");
576
- });
577
- }
578
- /**
579
- * Set the progress
580
- * Progress cannot go back and limited to 0% to 99% range
581
- * @param percent Progress to set in %
582
- * @param jobId? Job to set progress for
583
- */
584
- function setProgress(percent, jobId) {
585
- return __awaiter(this, void 0, void 0, function* () {
586
- var _a;
587
- const workspace = getWorkspace();
588
- let flowId = getEnv("WM_FLOW_JOB_ID");
589
- // If jobId specified we need to find if there is a parent/flow
590
- if (jobId) {
591
- const job = yield index_1.JobService.getJob({
592
- id: jobId !== null && jobId !== void 0 ? jobId : "NO_JOB_ID",
593
- workspace,
594
- noLogs: true,
595
- });
596
- // Could be actual flowId or undefined
597
- flowId = job.parent_job;
598
- }
599
- yield index_1.MetricsService.setJobProgress({
600
- id: (_a = jobId !== null && jobId !== void 0 ? jobId : getEnv("WM_JOB_ID")) !== null && _a !== void 0 ? _a : "NO_JOB_ID",
601
- workspace,
602
- requestBody: {
603
- // In case user inputs float, it should be converted to int
604
- percent: Math.floor(percent),
605
- flow_job_id: flowId == "" ? undefined : flowId,
606
- },
607
- });
608
- });
609
- }
610
- /**
611
- * Get the progress
612
- * @param jobId? Job to get progress from
613
- * @returns Optional clamped between 0 and 100 progress value
614
- */
615
- function getProgress(jobId) {
616
- return __awaiter(this, void 0, void 0, function* () {
617
- var _a;
618
- // TODO: Delete or set to 100 completed job metrics
619
- return yield index_1.MetricsService.getJobProgress({
620
- id: (_a = jobId !== null && jobId !== void 0 ? jobId : getEnv("WM_JOB_ID")) !== null && _a !== void 0 ? _a : "NO_JOB_ID",
621
- workspace: getWorkspace(),
622
- });
623
- });
624
- }
625
- /**
626
- * Set a flow user state
627
- * @param key key of the state
628
- * @param value value of the state
629
-
630
- */
631
- function setFlowUserState(key, value, errorIfNotPossible) {
632
- return __awaiter(this, void 0, void 0, function* () {
633
- if (value === undefined) {
634
- value = null;
635
- }
636
- const workspace = getWorkspace();
637
- try {
638
- yield index_1.JobService.setFlowUserState({
639
- workspace,
640
- id: yield getRootJobId(),
641
- key,
642
- requestBody: value,
643
- });
644
- }
645
- catch (e) {
646
- if (errorIfNotPossible) {
647
- throw Error(`Error setting flow user state at ${key}: ${e.body}`);
648
- }
649
- else {
650
- console.error(`Error setting flow user state at ${key}: ${e.body}`);
651
- }
652
- }
653
- });
654
- }
655
- /**
656
- * Get a flow user state
657
- * @param path path of the variable
658
-
659
- */
660
- function getFlowUserState(key, errorIfNotPossible) {
661
- return __awaiter(this, void 0, void 0, function* () {
662
- const workspace = getWorkspace();
663
- try {
664
- return yield index_1.JobService.getFlowUserState({
665
- workspace,
666
- id: yield getRootJobId(),
667
- key,
668
- });
669
- }
670
- catch (e) {
671
- if (errorIfNotPossible) {
672
- throw Error(`Error setting flow user state at ${key}: ${e.body}`);
673
- }
674
- else {
675
- console.error(`Error setting flow user state at ${key}: ${e.body}`);
676
- }
677
- }
678
- });
679
- }
680
- /**
681
- * Get the internal state
682
- * @deprecated use getState instead
683
- */
684
- function getInternalState() {
685
- return __awaiter(this, void 0, void 0, function* () {
686
- return yield getResource(getStatePath(), true);
687
- });
688
- }
689
- /**
690
- * Get the state shared across executions
691
- * @param path Optional state resource path override. Defaults to `getStatePath()`.
692
- */
693
- function getState(path) {
694
- return __awaiter(this, void 0, void 0, function* () {
695
- return yield getResource(path !== null && path !== void 0 ? path : getStatePath(), true);
696
- });
697
- }
698
- /**
699
- * Get a variable by path
700
- * @param path path of the variable
701
- * @returns variable value
702
- */
703
- function getVariable(path) {
704
- return __awaiter(this, void 0, void 0, function* () {
705
- var _a;
706
- path = (_a = parseVariableSyntax(path)) !== null && _a !== void 0 ? _a : path;
707
- const mockedApi = yield getMockedApi();
708
- if (mockedApi) {
709
- if (mockedApi.variables[path]) {
710
- return mockedApi.variables[path];
711
- }
712
- else {
713
- console.log(`MockedAPI present, but variable not found at ${path}, falling back to real API`);
714
- }
715
- }
716
- const workspace = getWorkspace();
717
- try {
718
- return yield index_1.VariableService.getVariableValue({ workspace, path });
719
- }
720
- catch (e) {
721
- throw Error(`Variable not found at ${path} or not visible to you: ${e.body}`);
722
- }
723
- });
724
- }
725
- /**
726
- * Set a variable by path, create if not exist
727
- * @param path path of the variable
728
- * @param value value of the variable
729
- * @param isSecretIfNotExist if the variable does not exist, create it as secret or not (default: false)
730
- * @param descriptionIfNotExist if the variable does not exist, create it with this description (default: "")
731
- */
732
- function setVariable(path, value, isSecretIfNotExist, descriptionIfNotExist) {
733
- return __awaiter(this, void 0, void 0, function* () {
734
- var _a;
735
- path = (_a = parseVariableSyntax(path)) !== null && _a !== void 0 ? _a : path;
736
- const mockedApi = yield getMockedApi();
737
- if (mockedApi) {
738
- mockedApi.variables[path] = value;
739
- return;
740
- }
741
- const workspace = getWorkspace();
742
- if (yield index_1.VariableService.existsVariable({ workspace, path })) {
743
- yield index_1.VariableService.updateVariable({
744
- workspace,
745
- path,
746
- requestBody: { value },
747
- });
748
- }
749
- else {
750
- yield index_1.VariableService.createVariable({
751
- workspace,
752
- requestBody: {
753
- path,
754
- value,
755
- is_secret: isSecretIfNotExist !== null && isSecretIfNotExist !== void 0 ? isSecretIfNotExist : false,
756
- description: descriptionIfNotExist !== null && descriptionIfNotExist !== void 0 ? descriptionIfNotExist : "",
757
- },
758
- });
759
- }
760
- });
761
- }
762
- /**
763
- * Build a PostgreSQL connection URL from a database resource
764
- * @param path - Path to the database resource
765
- * @returns PostgreSQL connection URL string
766
- */
767
- function databaseUrlFromResource(path) {
768
- return __awaiter(this, void 0, void 0, function* () {
769
- const resource = yield getResource(path);
770
- return `postgresql://${resource.user}:${resource.password}@${resource.host}:${resource.port}/${resource.dbname}?sslmode=${resource.sslmode}`;
771
- });
772
- }
773
- // TODO(gb): need to investigate more how Polars and DuckDB work in TS
774
- // export async function polarsConnectionSettings(s3_resource_path: string | undefined): Promise<any> {
775
- // const workspace = getWorkspace();
776
- // return await HelpersService.polarsConnectionSettingsV2({
777
- // workspace: workspace,
778
- // requestBody: {
779
- // s3_resource_path: s3_resource_path
780
- // }
781
- // });
782
- // }
783
- // export async function duckdbConnectionSettings(s3_resource_path: string | undefined): Promise<any> {
784
- // const workspace = getWorkspace();
785
- // return await HelpersService.duckdbConnectionSettingsV2({
786
- // workspace: workspace,
787
- // requestBody: {
788
- // s3_resource_path: s3_resource_path
789
- // }
790
- // });
791
- // }
792
- /**
793
- * Get S3 client settings from a resource or workspace default
794
- * @param s3_resource_path - Path to S3 resource (uses workspace default if undefined)
795
- * @returns S3 client configuration settings
796
- */
797
- function denoS3LightClientSettings(s3_resource_path) {
798
- return __awaiter(this, void 0, void 0, function* () {
799
- var _a;
800
- const workspace = getWorkspace();
801
- const s3Resource = yield index_1.HelpersService.s3ResourceInfo({
802
- workspace: workspace,
803
- requestBody: {
804
- s3_resource_path: (_a = parseResourceSyntax(s3_resource_path)) !== null && _a !== void 0 ? _a : s3_resource_path,
805
- },
806
- });
807
- let settings = Object.assign({}, s3Resource);
808
- return settings;
809
- });
810
- }
811
- /**
812
- * Load the content of a file stored in S3. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.
813
- *
814
- * ```typescript
815
- * let fileContent = await wmill.loadS3FileContent(inputFile)
816
- * // if the file is a raw text file, it can be decoded and printed directly:
817
- * const text = new TextDecoder().decode(fileContentStream)
818
- * console.log(text);
819
- * ```
820
- */
821
- function loadS3File(s3object_1) {
822
- return __awaiter(this, arguments, void 0, function* (s3object, s3ResourcePath = undefined) {
823
- const fileContentBlob = yield loadS3FileStream(s3object, s3ResourcePath);
824
- if (fileContentBlob === undefined) {
825
- return undefined;
826
- }
827
- // we read the stream until completion and put the content in an Uint8Array
828
- const reader = fileContentBlob.stream().getReader();
829
- const chunks = [];
830
- while (true) {
831
- const { value: chunk, done } = yield reader.read();
832
- if (done) {
833
- break;
834
- }
835
- chunks.push(chunk);
836
- }
837
- let fileContentLength = 0;
838
- chunks.forEach((item) => {
839
- fileContentLength += item.length;
840
- });
841
- let fileContent = new Uint8Array(fileContentLength);
842
- let offset = 0;
843
- chunks.forEach((chunk) => {
844
- fileContent.set(chunk, offset);
845
- offset += chunk.length;
846
- });
847
- return fileContent;
848
- });
849
- }
850
- /**
851
- * Load the content of a file stored in S3 as a stream. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.
852
- *
853
- * ```typescript
854
- * let fileContentBlob = await wmill.loadS3FileStream(inputFile)
855
- * // if the content is plain text, the blob can be read directly:
856
- * console.log(await fileContentBlob.text());
857
- * ```
858
- */
859
- function loadS3FileStream(s3object_1) {
860
- return __awaiter(this, arguments, void 0, function* (s3object, s3ResourcePath = undefined) {
861
- let s3Obj = s3object && parseS3Object(s3object);
862
- let params = {};
863
- params["file_key"] = s3Obj.s3;
864
- if (s3ResourcePath !== undefined) {
865
- params["s3_resource_path"] = s3ResourcePath;
866
- }
867
- if (s3Obj.storage !== undefined) {
868
- params["storage"] = s3Obj.storage;
869
- }
870
- const queryParams = new URLSearchParams(params);
871
- // We use raw fetch here b/c OpenAPI generated client doesn't handle Blobs nicely
872
- const response = yield fetch(`${index_2.OpenAPI.BASE}/w/${getWorkspace()}/job_helpers/download_s3_file?${queryParams}`, {
873
- method: "GET",
874
- headers: {
875
- Authorization: `Bearer ${index_2.OpenAPI.TOKEN}`,
876
- },
877
- });
878
- // Check if the response was successful
879
- if (!response.ok) {
880
- const errorText = yield response.text();
881
- throw new Error(`Failed to load S3 file: ${response.status} ${response.statusText} - ${errorText}`);
882
- }
883
- return response.blob();
884
- });
885
- }
886
- /**
887
- * Persist a file to the S3 bucket. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.
888
- *
889
- * ```typescript
890
- * const s3object = await writeS3File(s3Object, "Hello Windmill!")
891
- * const fileContentAsUtf8Str = (await s3object.toArray()).toString('utf-8')
892
- * console.log(fileContentAsUtf8Str)
893
- * ```
894
- */
895
- function writeS3File(s3object_1, fileContent_1) {
896
- return __awaiter(this, arguments, void 0, function* (s3object, fileContent, s3ResourcePath = undefined, contentType = undefined, contentDisposition = undefined) {
897
- let fileContentBlob;
898
- if (typeof fileContent === "string") {
899
- fileContentBlob = new Blob([fileContent], {
900
- type: "text/plain",
901
- });
902
- }
903
- else {
904
- fileContentBlob = fileContent;
905
- }
906
- let s3Obj = s3object && parseS3Object(s3object);
907
- const response = yield index_1.HelpersService.fileUpload({
908
- workspace: getWorkspace(),
909
- fileKey: s3Obj === null || s3Obj === void 0 ? void 0 : s3Obj.s3,
910
- fileExtension: undefined,
911
- s3ResourcePath: s3ResourcePath,
912
- requestBody: fileContentBlob,
913
- storage: s3Obj === null || s3Obj === void 0 ? void 0 : s3Obj.storage,
914
- contentType,
915
- contentDisposition,
916
- });
917
- return Object.assign({ s3: response.file_key }, ((s3Obj === null || s3Obj === void 0 ? void 0 : s3Obj.storage) && { storage: s3Obj === null || s3Obj === void 0 ? void 0 : s3Obj.storage }));
918
- });
919
- }
920
- /**
921
- * Sign S3 objects to be used by anonymous users in public apps
922
- * @param s3objects s3 objects to sign
923
- * @returns signed s3 objects
924
- */
925
- function signS3Objects(s3objects) {
926
- return __awaiter(this, void 0, void 0, function* () {
927
- const signedKeys = yield index_1.AppService.signS3Objects({
928
- workspace: getWorkspace(),
929
- requestBody: {
930
- s3_objects: s3objects.map(parseS3Object),
931
- },
932
- });
933
- return signedKeys;
934
- });
935
- }
936
- /**
937
- * Sign S3 object to be used by anonymous users in public apps
938
- * @param s3object s3 object to sign
939
- * @returns signed s3 object
940
- */
941
- function signS3Object(s3object) {
942
- return __awaiter(this, void 0, void 0, function* () {
943
- const [signedObject] = yield signS3Objects([s3object]);
944
- return signedObject;
945
- });
946
- }
947
- /**
948
- * Generate a presigned public URL for an array of S3 objects.
949
- * If an S3 object is not signed yet, it will be signed first.
950
- * @param s3Objects s3 objects to sign
951
- * @returns list of signed public URLs
952
- */
953
- function getPresignedS3PublicUrls(s3Objects_1) {
954
- return __awaiter(this, arguments, void 0, function* (s3Objects, { baseUrl } = {}) {
955
- baseUrl !== null && baseUrl !== void 0 ? baseUrl : (baseUrl = getPublicBaseUrl());
956
- const s3Objs = s3Objects.map(parseS3Object);
957
- // Sign all S3 objects that need to be signed in one go
958
- const s3ObjsToSign = s3Objs
959
- .map((s3Obj, index) => [s3Obj, index])
960
- .filter(([s3Obj, _]) => s3Obj.presigned === undefined);
961
- if (s3ObjsToSign.length > 0) {
962
- const signedS3Objs = yield signS3Objects(s3ObjsToSign.map(([s3Obj, _]) => s3Obj));
963
- for (let i = 0; i < s3ObjsToSign.length; i++) {
964
- const [_, originalIndex] = s3ObjsToSign[i];
965
- s3Objs[originalIndex] = parseS3Object(signedS3Objs[i]);
966
- }
967
- }
968
- const signedUrls = [];
969
- for (const s3Obj of s3Objs) {
970
- const { s3, presigned, storage = "_default_" } = s3Obj;
971
- const signedUrl = `${baseUrl}/api/w/${getWorkspace()}/s3_proxy/${storage}/${s3}?${presigned}`;
972
- signedUrls.push(signedUrl);
973
- }
974
- return signedUrls;
975
- });
976
- }
977
- /**
978
- * Generate a presigned public URL for an S3 object. If the S3 object is not signed yet, it will be signed first.
979
- * @param s3Object s3 object to sign
980
- * @returns signed public URL
981
- */
982
- function getPresignedS3PublicUrl(s3Objects_1) {
983
- return __awaiter(this, arguments, void 0, function* (s3Objects, { baseUrl } = {}) {
984
- const [s3Object] = yield getPresignedS3PublicUrls([s3Objects], { baseUrl });
985
- return s3Object;
986
- });
987
- }
988
- /**
989
- * Get URLs needed for resuming a flow after this step
990
- * @param approver approver name
991
- * @param flowLevel if true, generate resume URLs for the parent flow instead of the specific step.
992
- * This allows pre-approvals that can be consumed by any later suspend step in the same flow.
993
- * @returns approval page UI URL, resume and cancel API URLs for resuming the flow
994
- */
995
- function getResumeUrls(approver, flowLevel) {
996
- return __awaiter(this, void 0, void 0, function* () {
997
- var _a;
998
- const nonce = Math.floor(Math.random() * 4294967295);
999
- const workspace = getWorkspace();
1000
- return yield index_1.JobService.getResumeUrls({
1001
- workspace,
1002
- resumeId: nonce,
1003
- approver,
1004
- flowLevel,
1005
- id: (_a = getEnv("WM_JOB_ID")) !== null && _a !== void 0 ? _a : "NO_JOB_ID",
1006
- });
1007
- });
1008
- }
1009
- /**
1010
- * @deprecated use getResumeUrls instead
1011
- */
1012
- function getResumeEndpoints(approver) {
1013
- return getResumeUrls(approver);
1014
- }
1015
- /**
1016
- * Get an OIDC jwt token for auth to external services (e.g: Vault, AWS) (ee only)
1017
- * @param audience audience of the token
1018
- * @param expiresIn Optional number of seconds until the token expires
1019
- * @returns jwt token
1020
- */
1021
- function getIdToken(audience, expiresIn) {
1022
- return __awaiter(this, void 0, void 0, function* () {
1023
- const workspace = getWorkspace();
1024
- return yield index_1.OidcService.getOidcToken({
1025
- workspace,
1026
- audience,
1027
- expiresIn,
1028
- });
1029
- });
1030
- }
1031
- /**
1032
- * Convert a base64-encoded string to Uint8Array
1033
- * @param data - Base64-encoded string
1034
- * @returns Decoded Uint8Array
1035
- */
1036
- function base64ToUint8Array(data) {
1037
- return Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
1038
- }
1039
- /**
1040
- * Convert a Uint8Array to base64-encoded string
1041
- * @param arrayBuffer - Uint8Array to encode
1042
- * @returns Base64-encoded string
1043
- */
1044
- function uint8ArrayToBase64(arrayBuffer) {
1045
- let base64 = "";
1046
- const encodings = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1047
- const bytes = new Uint8Array(arrayBuffer);
1048
- const byteLength = bytes.byteLength;
1049
- const byteRemainder = byteLength % 3;
1050
- const mainLength = byteLength - byteRemainder;
1051
- let a, b, c, d;
1052
- let chunk;
1053
- // Main loop deals with bytes in chunks of 3
1054
- for (let i = 0; i < mainLength; i = i + 3) {
1055
- // Combine the three bytes into a single integer
1056
- chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
1057
- // Use bitmasks to extract 6-bit segments from the triplet
1058
- a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
1059
- b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
1060
- c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
1061
- d = chunk & 63; // 63 = 2^6 - 1
1062
- // Convert the raw binary segments to the appropriate ASCII encoding
1063
- base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
1064
- }
1065
- // Deal with the remaining bytes and padding
1066
- if (byteRemainder == 1) {
1067
- chunk = bytes[mainLength];
1068
- a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
1069
- // Set the 4 least significant bits to zero
1070
- b = (chunk & 3) << 4; // 3 = 2^2 - 1
1071
- base64 += encodings[a] + encodings[b] + "==";
1072
- }
1073
- else if (byteRemainder == 2) {
1074
- chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];
1075
- a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
1076
- b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
1077
- // Set the 2 least significant bits to zero
1078
- c = (chunk & 15) << 2; // 15 = 2^4 - 1
1079
- base64 += encodings[a] + encodings[b] + encodings[c] + "=";
1080
- }
1081
- return base64;
1082
- }
1083
- /**
1084
- * Get email from workspace username
1085
- * This method is particularly useful for apps that require the email address of the viewer.
1086
- * Indeed, in the viewer context, WM_USERNAME is set to the username of the viewer but WM_EMAIL is set to the email of the creator of the app.
1087
- * @param username
1088
- * @returns email address
1089
- */
1090
- function usernameToEmail(username) {
1091
- return __awaiter(this, void 0, void 0, function* () {
1092
- const workspace = getWorkspace();
1093
- return yield index_1.UserService.usernameToEmail({ username, workspace });
1094
- });
1095
- }
1096
- /**
1097
- * Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.
1098
- *
1099
- * **[Enterprise Edition Only]** To include form fields in the Slack approval request, go to **Advanced -> Suspend -> Form**
1100
- * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).
1101
- *
1102
- * @param {Object} options - The configuration options for the Slack approval request.
1103
- * @param {string} options.slackResourcePath - The path to the Slack resource in Windmill.
1104
- * @param {string} options.channelId - The Slack channel ID where the approval request will be sent.
1105
- * @param {string} [options.message] - Optional custom message to include in the Slack approval request.
1106
- * @param {string} [options.approver] - Optional user ID or name of the approver for the request.
1107
- * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.
1108
- * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.
1109
- *
1110
- * @returns {Promise<void>} Resolves when the Slack approval request is successfully sent.
1111
- *
1112
- * @throws {Error} If the function is not called within a flow or flow preview.
1113
- * @throws {Error} If the `JobService.getSlackApprovalPayload` call fails.
1114
- *
1115
- * **Usage Example:**
1116
- * ```typescript
1117
- * await requestInteractiveSlackApproval({
1118
- * slackResourcePath: "/u/alex/my_slack_resource",
1119
- * channelId: "admins-slack-channel",
1120
- * message: "Please approve this request",
1121
- * approver: "approver123",
1122
- * defaultArgsJson: { key1: "value1", key2: 42 },
1123
- * dynamicEnumsJson: { foo: ["choice1", "choice2"], bar: ["optionA", "optionB"] },
1124
- * });
1125
- * ```
1126
- *
1127
- * **Note:** This function requires execution within a Windmill flow or flow preview.
1128
- */
1129
- function requestInteractiveSlackApproval(_a) {
1130
- return __awaiter(this, arguments, void 0, function* ({ slackResourcePath, channelId, message, approver, defaultArgsJson, dynamicEnumsJson, }) {
1131
- var _b;
1132
- const workspace = getWorkspace();
1133
- const flowJobId = getEnv("WM_FLOW_JOB_ID");
1134
- if (!flowJobId) {
1135
- throw new Error("You can't use this function in a standalone script or flow step preview. Please use it in a flow or a flow preview.");
1136
- }
1137
- const flowStepId = getEnv("WM_FLOW_STEP_ID");
1138
- if (!flowStepId) {
1139
- throw new Error("This function can only be called as a flow step");
1140
- }
1141
- // Only include non-empty parameters
1142
- const params = {
1143
- slackResourcePath,
1144
- channelId,
1145
- flowStepId,
1146
- };
1147
- if (message) {
1148
- params.message = message;
1149
- }
1150
- if (approver) {
1151
- params.approver = approver;
1152
- }
1153
- if (defaultArgsJson) {
1154
- params.defaultArgsJson = JSON.stringify(defaultArgsJson);
1155
- }
1156
- if (dynamicEnumsJson) {
1157
- params.dynamicEnumsJson = JSON.stringify(dynamicEnumsJson);
1158
- }
1159
- yield index_1.JobService.getSlackApprovalPayload(Object.assign(Object.assign({ workspace }, params), { id: (_b = getEnv("WM_JOB_ID")) !== null && _b !== void 0 ? _b : "NO_JOB_ID" }));
1160
- });
1161
- }
1162
- /**
1163
- * Sends an interactive approval request via Teams, allowing optional customization of the message, approver, and form fields.
1164
- *
1165
- * **[Enterprise Edition Only]** To include form fields in the Teams approval request, go to **Advanced -> Suspend -> Form**
1166
- * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).
1167
- *
1168
- * @param {Object} options - The configuration options for the Teams approval request.
1169
- * @param {string} options.teamName - The Teams team name where the approval request will be sent.
1170
- * @param {string} options.channelName - The Teams channel name where the approval request will be sent.
1171
- * @param {string} [options.message] - Optional custom message to include in the Teams approval request.
1172
- * @param {string} [options.approver] - Optional user ID or name of the approver for the request.
1173
- * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.
1174
- * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.
1175
- *
1176
- * @returns {Promise<void>} Resolves when the Teams approval request is successfully sent.
1177
- *
1178
- * @throws {Error} If the function is not called within a flow or flow preview.
1179
- * @throws {Error} If the `JobService.getTeamsApprovalPayload` call fails.
1180
- *
1181
- * **Usage Example:**
1182
- * ```typescript
1183
- * await requestInteractiveTeamsApproval({
1184
- * teamName: "admins-teams",
1185
- * channelName: "admins-teams-channel",
1186
- * message: "Please approve this request",
1187
- * approver: "approver123",
1188
- * defaultArgsJson: { key1: "value1", key2: 42 },
1189
- * dynamicEnumsJson: { foo: ["choice1", "choice2"], bar: ["optionA", "optionB"] },
1190
- * });
1191
- * ```
1192
- *
1193
- * **Note:** This function requires execution within a Windmill flow or flow preview.
1194
- */
1195
- function requestInteractiveTeamsApproval(_a) {
1196
- return __awaiter(this, arguments, void 0, function* ({ teamName, channelName, message, approver, defaultArgsJson, dynamicEnumsJson, }) {
1197
- var _b;
1198
- const workspace = getWorkspace();
1199
- const flowJobId = getEnv("WM_FLOW_JOB_ID");
1200
- if (!flowJobId) {
1201
- throw new Error("You can't use this function in a standalone script or flow step preview. Please use it in a flow or a flow preview.");
1202
- }
1203
- const flowStepId = getEnv("WM_FLOW_STEP_ID");
1204
- if (!flowStepId) {
1205
- throw new Error("This function can only be called as a flow step");
1206
- }
1207
- // Only include non-empty parameters
1208
- const params = {
1209
- teamName,
1210
- channelName,
1211
- flowStepId,
1212
- };
1213
- if (message) {
1214
- params.message = message;
1215
- }
1216
- if (approver) {
1217
- params.approver = approver;
1218
- }
1219
- if (defaultArgsJson) {
1220
- params.defaultArgsJson = JSON.stringify(defaultArgsJson);
1221
- }
1222
- if (dynamicEnumsJson) {
1223
- params.dynamicEnumsJson = JSON.stringify(dynamicEnumsJson);
1224
- }
1225
- yield index_1.JobService.getTeamsApprovalPayload(Object.assign(Object.assign({ workspace }, params), { id: (_b = getEnv("WM_JOB_ID")) !== null && _b !== void 0 ? _b : "NO_JOB_ID" }));
1226
- });
1227
- }
1228
- function getMockedApi() {
1229
- return __awaiter(this, void 0, void 0, function* () {
1230
- if (mockedApi) {
1231
- return mockedApi;
1232
- }
1233
- const mockedPath = getEnv("WM_MOCKED_API_FILE");
1234
- if (mockedPath) {
1235
- console.info("Using mocked API from", mockedPath);
1236
- }
1237
- else {
1238
- return undefined;
1239
- }
1240
- try {
1241
- const fs = yield Promise.resolve().then(() => require("node:fs/promises"));
1242
- const file = yield fs.readFile(mockedPath, "utf-8");
1243
- try {
1244
- mockedApi = JSON.parse(file);
1245
- if (!mockedApi.variables) {
1246
- mockedApi.variables = {};
1247
- }
1248
- if (!mockedApi.resources) {
1249
- mockedApi.resources = {};
1250
- }
1251
- return mockedApi;
1252
- }
1253
- catch (_a) {
1254
- console.warn("Error parsing mocked API file at path", mockedPath);
1255
- }
1256
- }
1257
- catch (_b) {
1258
- console.warn("Error reading mocked API file at path", mockedPath);
1259
- }
1260
- if (!mockedApi) {
1261
- console.warn("No mocked API file path provided at env variable WM_MOCKED_API_FILE. Using empty mocked API.");
1262
- mockedApi = {
1263
- variables: {},
1264
- resources: {},
1265
- };
1266
- return mockedApi;
1267
- }
1268
- });
1269
- }
1270
- function parseResourceSyntax(s) {
1271
- if (s === null || s === void 0 ? void 0 : s.startsWith("$res:"))
1272
- return s.substring(5);
1273
- if (s === null || s === void 0 ? void 0 : s.startsWith("res://"))
1274
- return s.substring(6);
1275
- }
1276
- /**
1277
- * Parse an S3 object from URI string or record format
1278
- * @param s3Object - S3 object as URI string (s3://storage/key) or record
1279
- * @returns S3 object record with storage and s3 key
1280
- */
1281
- function parseS3Object(s3Object) {
1282
- var _a;
1283
- if (typeof s3Object === "object")
1284
- return s3Object;
1285
- const match = s3Object.match(/^s3:\/\/([^/]*)\/(.*)$/);
1286
- return { storage: (match === null || match === void 0 ? void 0 : match[1]) || undefined, s3: (_a = match === null || match === void 0 ? void 0 : match[2]) !== null && _a !== void 0 ? _a : "" };
1287
- }
1288
- function parseVariableSyntax(s) {
1289
- if (s.startsWith("var://"))
1290
- return s.substring(6);
1291
- }