@kizenapps/engine 0.0.1-b1f3597

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 (74) hide show
  1. package/LICENSE.md +674 -0
  2. package/README.md +160 -0
  3. package/dist/ThirdPartyScript-DdrF7zh7.d.ts +459 -0
  4. package/dist/automation-C8hsM_Rc.d.ts +36 -0
  5. package/dist/chunk-2MW4AGSN.js +2415 -0
  6. package/dist/chunk-2MW4AGSN.js.map +1 -0
  7. package/dist/chunk-3LDUYA57.js +61 -0
  8. package/dist/chunk-3LDUYA57.js.map +1 -0
  9. package/dist/chunk-5WRI5ZAA.js +29 -0
  10. package/dist/chunk-5WRI5ZAA.js.map +1 -0
  11. package/dist/chunk-727AYMPR.js +120 -0
  12. package/dist/chunk-727AYMPR.js.map +1 -0
  13. package/dist/chunk-GGGXYD3K.js +40 -0
  14. package/dist/chunk-GGGXYD3K.js.map +1 -0
  15. package/dist/chunk-LGJYUPYZ.js +3 -0
  16. package/dist/chunk-LGJYUPYZ.js.map +1 -0
  17. package/dist/chunk-NXLAROEM.js +730 -0
  18. package/dist/chunk-NXLAROEM.js.map +1 -0
  19. package/dist/chunk-P7GQBCEH.js +172 -0
  20. package/dist/chunk-P7GQBCEH.js.map +1 -0
  21. package/dist/chunk-UOTNQL56.js +46 -0
  22. package/dist/chunk-UOTNQL56.js.map +1 -0
  23. package/dist/chunk-VYBEGZLN.js +319 -0
  24. package/dist/chunk-VYBEGZLN.js.map +1 -0
  25. package/dist/chunk-XKKZPZMB.js +121 -0
  26. package/dist/chunk-XKKZPZMB.js.map +1 -0
  27. package/dist/communication.d.ts +13 -0
  28. package/dist/communication.js +6 -0
  29. package/dist/communication.js.map +1 -0
  30. package/dist/contexts/base.d.ts +99 -0
  31. package/dist/contexts/base.js +7 -0
  32. package/dist/contexts/base.js.map +1 -0
  33. package/dist/contexts/floatingFrame.d.ts +18 -0
  34. package/dist/contexts/floatingFrame.js +8 -0
  35. package/dist/contexts/floatingFrame.js.map +1 -0
  36. package/dist/contexts/recordDetail.d.ts +32 -0
  37. package/dist/contexts/recordDetail.js +8 -0
  38. package/dist/contexts/recordDetail.js.map +1 -0
  39. package/dist/floatingFrames-BzaoL7cq.d.ts +8 -0
  40. package/dist/generic-RiEgdDAq.d.ts +19 -0
  41. package/dist/index.d.ts +19 -0
  42. package/dist/index.js +6 -0
  43. package/dist/index.js.map +1 -0
  44. package/dist/merge-translations.js +28 -0
  45. package/dist/react.d.ts +367 -0
  46. package/dist/react.js +2732 -0
  47. package/dist/react.js.map +1 -0
  48. package/dist/routeScript-kttY2YZh.d.ts +303 -0
  49. package/dist/translation.json +8 -0
  50. package/dist/types.d.ts +90 -0
  51. package/dist/types.js +3 -0
  52. package/dist/types.js.map +1 -0
  53. package/dist/util.d.ts +40 -0
  54. package/dist/util.js +87 -0
  55. package/dist/util.js.map +1 -0
  56. package/dist/vite.d.ts +11 -0
  57. package/dist/vite.js +19 -0
  58. package/dist/vite.js.map +1 -0
  59. package/dist/workers/calendarSource.worker.d.ts +2 -0
  60. package/dist/workers/calendarSource.worker.js +62 -0
  61. package/dist/workers/calendarSource.worker.js.map +1 -0
  62. package/dist/workers/expression.worker.d.ts +2 -0
  63. package/dist/workers/expression.worker.js +35 -0
  64. package/dist/workers/expression.worker.js.map +1 -0
  65. package/dist/workers/floatingFrame.worker.d.ts +2 -0
  66. package/dist/workers/floatingFrame.worker.js +57 -0
  67. package/dist/workers/floatingFrame.worker.js.map +1 -0
  68. package/dist/workers/generic.worker.d.ts +2 -0
  69. package/dist/workers/generic.worker.js +57 -0
  70. package/dist/workers/generic.worker.js.map +1 -0
  71. package/dist/workers/recordDetail.worker.d.ts +2 -0
  72. package/dist/workers/recordDetail.worker.js +59 -0
  73. package/dist/workers/recordDetail.worker.js.map +1 -0
  74. package/package.json +93 -0
@@ -0,0 +1,730 @@
1
+ import { cleanConfig } from './chunk-VYBEGZLN.js';
2
+ import { Communicate } from './chunk-GGGXYD3K.js';
3
+ import { RESPONSES, ACTIONS, ThirdPartyScript } from './chunk-P7GQBCEH.js';
4
+
5
+ // src/contexts/BaseWorkerContext.ts
6
+ var buildErrorResponse = async (result) => {
7
+ let errorJSON = null;
8
+ try {
9
+ errorJSON = await result.json();
10
+ } catch {
11
+ }
12
+ const error = {
13
+ status: result.status,
14
+ statusText: result.statusText,
15
+ body: errorJSON
16
+ };
17
+ return error;
18
+ };
19
+ var convertToSelfInvokingFunction = (fn, variable, args = {}, prepend = "") => {
20
+ const functionString = fn.toString();
21
+ const innner = `(${functionString})({ state: {{${variable}}}, args: ${JSON.stringify(args)}, utils: __kizen_utils })`;
22
+ const full = `(function() { ${prepend}
23
+ return ${innner}; })()`;
24
+ return full;
25
+ };
26
+ var BaseWorkerContext = class {
27
+ user;
28
+ teamMember;
29
+ business;
30
+ clientObject;
31
+ appPath;
32
+ dataCache = /* @__PURE__ */ new Map();
33
+ queryOptions = {};
34
+ api;
35
+ postFormData;
36
+ executionTimer = 0;
37
+ setupExecutions = 0;
38
+ cleanupExecutions = 0;
39
+ isDebug = false;
40
+ scriptBody;
41
+ internalState = { indicator: "none" /* NONE */ };
42
+ console = console;
43
+ instance;
44
+ breakOnException = false;
45
+ args;
46
+ communicate;
47
+ shouldPreserve = false;
48
+ uploadFileHandler;
49
+ internalSessionData;
50
+ pluginComponentId;
51
+ installThirdPartyScriptHandler;
52
+ promptHandler;
53
+ dynamicPromptHandler;
54
+ refreshEntityHandler;
55
+ openCreateRecordHandler;
56
+ openCreateRelatedRecordHandler;
57
+ runnerType;
58
+ pluginApiName;
59
+ tempPromptState = {};
60
+ partialLocation;
61
+ constructor({
62
+ user,
63
+ teamMember,
64
+ business,
65
+ clientObject,
66
+ appPath,
67
+ isDebug,
68
+ kizenRequest,
69
+ postFormData,
70
+ scriptBody,
71
+ instance,
72
+ args,
73
+ uploadFile,
74
+ sessionData,
75
+ pluginComponentId,
76
+ installThirdPartyScript,
77
+ prompt,
78
+ refreshEntity,
79
+ openCreateRecord,
80
+ openCreateRelatedRecord,
81
+ pluginApiName,
82
+ dynamicPrompt,
83
+ location
84
+ }) {
85
+ this.user = user;
86
+ this.teamMember = teamMember;
87
+ this.business = business;
88
+ this.clientObject = clientObject;
89
+ this.partialLocation = location;
90
+ this.appPath = appPath;
91
+ this.isDebug = isDebug ?? false;
92
+ this.api = {
93
+ get: kizenRequest("get"),
94
+ post: kizenRequest("post"),
95
+ put: kizenRequest("put"),
96
+ delete: kizenRequest("delete"),
97
+ patch: kizenRequest("patch")
98
+ };
99
+ this.postFormData = postFormData;
100
+ this.scriptBody = scriptBody;
101
+ this.instance = instance;
102
+ this.communicate = new Communicate(instance);
103
+ this.uploadFileHandler = uploadFile;
104
+ this.internalSessionData = sessionData ?? {};
105
+ this.pluginComponentId = pluginComponentId;
106
+ this.installThirdPartyScriptHandler = installThirdPartyScript;
107
+ this.promptHandler = prompt;
108
+ this.refreshEntityHandler = refreshEntity;
109
+ this.openCreateRecordHandler = openCreateRecord;
110
+ this.openCreateRelatedRecordHandler = openCreateRelatedRecord;
111
+ this.runnerType = "base";
112
+ this.pluginApiName = pluginApiName;
113
+ this.dynamicPromptHandler = dynamicPrompt;
114
+ try {
115
+ this.args = JSON.parse(args ?? "{}");
116
+ } catch {
117
+ this.args = {};
118
+ }
119
+ }
120
+ onError(error) {
121
+ if (this.breakOnException) {
122
+ debugger;
123
+ }
124
+ this.instance.postMessage(
125
+ JSON.stringify({
126
+ action: RESPONSES.ERROR,
127
+ error: error?.message
128
+ })
129
+ );
130
+ }
131
+ set debug(value) {
132
+ this.isDebug = value;
133
+ this.breakOnException = value;
134
+ }
135
+ set preserve(value) {
136
+ this.shouldPreserve = value;
137
+ }
138
+ get preserve() {
139
+ return this.shouldPreserve;
140
+ }
141
+ parseDate(date) {
142
+ return date.split("-");
143
+ }
144
+ parsePhone(phone) {
145
+ return phone.replace(/\+/g, "");
146
+ }
147
+ openWindow(url, target = "_blank") {
148
+ this.instance.postMessage(
149
+ JSON.stringify({
150
+ action: ACTIONS.OPEN_WINDOW,
151
+ url,
152
+ target,
153
+ features: "noopener noreferrer"
154
+ })
155
+ );
156
+ }
157
+ authorize(serviceName, config = {}) {
158
+ if (!serviceName) {
159
+ throw new Error("Service name is required to authorize");
160
+ }
161
+ this.instance.postMessage(
162
+ JSON.stringify({
163
+ action: ACTIONS.AUTHORIZE,
164
+ serviceName,
165
+ config: {
166
+ successRedirectPath: config.successRedirectPath ?? `/marketplace/${this.pluginApiName}/auth`,
167
+ errorRedirectPath: config.errorRedirectPath ?? `/marketplace/${this.pluginApiName}/auth`
168
+ }
169
+ })
170
+ );
171
+ }
172
+ getServiceUrl(serviceName, path) {
173
+ if (!serviceName) {
174
+ throw new Error("Service name is required to get a service url");
175
+ }
176
+ const base = `/external-integrations/proxy/${this.pluginApiName}/${serviceName}`;
177
+ if (path.startsWith("/")) {
178
+ return `${base}${path}`;
179
+ }
180
+ return `${base}/${path}`;
181
+ }
182
+ get currentBusiness() {
183
+ return this.business;
184
+ }
185
+ get applicationPath() {
186
+ return this.appPath;
187
+ }
188
+ get currentUser() {
189
+ return {
190
+ profile: {
191
+ id: this.teamMember?.id ?? "",
192
+ full_name: this.teamMember?.full_name ?? "",
193
+ first_name: this.teamMember?.first_name ?? "",
194
+ last_name: this.teamMember?.last_name ?? "",
195
+ email: this.teamMember?.email ?? "",
196
+ phone: this.teamMember?.phone ?? "",
197
+ created: this.teamMember?.created ?? "",
198
+ crm_client_id: this.user?.crm_client_id ?? ""
199
+ }
200
+ };
201
+ }
202
+ get sessionData() {
203
+ return this.internalSessionData;
204
+ }
205
+ get config() {
206
+ const hasCustomConfig = Boolean(this.args.__kizen_clean_config);
207
+ if (!hasCustomConfig) {
208
+ return {};
209
+ }
210
+ const manager = new Proxy(this.args.__kizen_clean_config ?? {}, {
211
+ get: (target, name) => {
212
+ if (Reflect.has(target, name)) {
213
+ return Reflect.get(target, name);
214
+ }
215
+ return void 0;
216
+ }
217
+ });
218
+ return manager;
219
+ }
220
+ get location() {
221
+ return new Proxy(this.partialLocation, {
222
+ get: (target, name) => {
223
+ if (name === "toJSON") {
224
+ return () => {
225
+ return this.partialLocation;
226
+ };
227
+ }
228
+ if (Reflect.has(target, name)) {
229
+ return Reflect.get(target, name);
230
+ }
231
+ throw new Error(
232
+ `Property ${String(name)} is not available on location object for plugin apps`
233
+ );
234
+ }
235
+ });
236
+ }
237
+ get userConfig() {
238
+ const customConfig = this.args.__kizen_user_config?.__kizen_clean_config;
239
+ if (!customConfig) {
240
+ return {};
241
+ }
242
+ const manager = new Proxy(customConfig, {
243
+ get: (target, name) => {
244
+ if (Reflect.has(target, name)) {
245
+ return Reflect.get(target, name);
246
+ }
247
+ return void 0;
248
+ }
249
+ });
250
+ return manager;
251
+ }
252
+ setSessionData(update) {
253
+ if (typeof update !== "object") {
254
+ throw new Error(`Invalid session update with type ${typeof update}`);
255
+ }
256
+ if (Array.isArray(update)) {
257
+ throw new Error(`Invalid session update with type array`);
258
+ }
259
+ this.internalSessionData = {
260
+ ...this.internalSessionData,
261
+ ...update
262
+ };
263
+ this.instance.postMessage(
264
+ JSON.stringify({
265
+ action: ACTIONS.UPDATE_SESSION_DATA,
266
+ update
267
+ })
268
+ );
269
+ }
270
+ async get(url, options) {
271
+ try {
272
+ if (this.isRelativeUrl(url)) {
273
+ const cachedResult = this.dataCache.get(url);
274
+ if (cachedResult && !options?.ignoreCache) {
275
+ if (options?.returnErrors) {
276
+ return [cachedResult.data, null];
277
+ }
278
+ return cachedResult.data;
279
+ }
280
+ const { data } = await this.api.get(url, {
281
+ ...this.queryOptions,
282
+ headers: this.buildHeaders(options?.headers)
283
+ });
284
+ this.dataCache.set(url, { ts: Date.now(), data });
285
+ if (options?.returnErrors) {
286
+ return [data, null];
287
+ }
288
+ return data;
289
+ } else {
290
+ const res = await fetch(url, {
291
+ method: "GET",
292
+ headers: new Headers(options?.headers),
293
+ credentials: options?.credentials ?? "same-origin"
294
+ });
295
+ if (!res.ok) {
296
+ const err = await buildErrorResponse(res);
297
+ throw err;
298
+ }
299
+ const json = await res.json();
300
+ if (options?.returnErrors) {
301
+ return [json, null];
302
+ }
303
+ return json;
304
+ }
305
+ } catch (ex) {
306
+ if (options?.returnErrors) {
307
+ return [null, ex];
308
+ } else {
309
+ this.onError(ex);
310
+ }
311
+ }
312
+ }
313
+ async getWithErrors(url, options) {
314
+ return this.get(url, {
315
+ ...options,
316
+ returnErrors: true
317
+ });
318
+ }
319
+ async getUserConfig() {
320
+ if (!this.args.pluginId || !this.pluginComponentId) {
321
+ throw new Error(
322
+ "User config is not available for scripts not associated to a plugin or plugin component"
323
+ );
324
+ }
325
+ const configResult = await this.get(`/employee/mine/configs/plugins/${this.args.pluginId}`, {
326
+ ignoreCache: true
327
+ });
328
+ return configResult.config?.[this.pluginComponentId] ?? {};
329
+ }
330
+ async setUserConfig(config) {
331
+ if (!this.args.pluginId || !this.pluginComponentId) {
332
+ throw new Error(
333
+ "User config is not available for scripts not associated to a plugin or plugin component"
334
+ );
335
+ }
336
+ const oldConfig = await this.get(`/employee/mine/configs/plugins/${this.args.pluginId}`, {
337
+ ignoreCache: true
338
+ });
339
+ const mutationResult = await this.post(`/employee/mine/configs/plugins/${this.args.pluginId}`, {
340
+ config: {
341
+ ...oldConfig?.config,
342
+ [this.pluginComponentId]: {
343
+ ...oldConfig?.config?.[this.pluginComponentId],
344
+ ...config
345
+ }
346
+ }
347
+ });
348
+ return mutationResult;
349
+ }
350
+ async patch(url, body, options) {
351
+ try {
352
+ if (this.isRelativeUrl(url)) {
353
+ const { data } = await this.api.patch(url, body, {
354
+ ...this.queryOptions,
355
+ headers: options?.headers
356
+ });
357
+ if (options?.returnErrors) {
358
+ return [data, null];
359
+ }
360
+ return data;
361
+ } else {
362
+ const res = await fetch(url, {
363
+ method: "PATCH",
364
+ body: body ? JSON.stringify(body) : null,
365
+ headers: new Headers(options?.headers),
366
+ credentials: options?.credentials ?? "same-origin"
367
+ });
368
+ if (!res.ok) {
369
+ const err = await buildErrorResponse(res);
370
+ throw err;
371
+ }
372
+ const json = await res.json();
373
+ if (options?.returnErrors) {
374
+ return [json, null];
375
+ }
376
+ return json;
377
+ }
378
+ } catch (ex) {
379
+ if (options?.returnErrors) {
380
+ return [null, ex];
381
+ } else {
382
+ this.onError(ex);
383
+ }
384
+ }
385
+ }
386
+ async patchWithErrors(url, body, options) {
387
+ return this.patch(url, body, {
388
+ ...options,
389
+ returnErrors: true
390
+ });
391
+ }
392
+ async post(url, body, options) {
393
+ try {
394
+ if (this.isRelativeUrl(url)) {
395
+ const { data } = await this.api.post(url, body, {
396
+ ...this.queryOptions,
397
+ headers: this.buildHeaders(options?.headers)
398
+ });
399
+ if (options?.returnErrors) {
400
+ return [data, null];
401
+ }
402
+ return data;
403
+ } else {
404
+ const res = await fetch(url, {
405
+ method: "POST",
406
+ body: body ? JSON.stringify(body) : null,
407
+ headers: new Headers(options?.headers),
408
+ credentials: options?.credentials ?? "same-origin"
409
+ });
410
+ if (!res.ok) {
411
+ const err = await buildErrorResponse(res);
412
+ throw err;
413
+ }
414
+ const json = await res.json();
415
+ if (options?.returnErrors) {
416
+ return [json, null];
417
+ }
418
+ return json;
419
+ }
420
+ } catch (ex) {
421
+ if (options?.returnErrors) {
422
+ return [null, ex];
423
+ } else {
424
+ this.onError(ex);
425
+ }
426
+ }
427
+ }
428
+ async postWithErrors(url, body, options) {
429
+ return this.post(url, body, {
430
+ ...options,
431
+ returnErrors: true
432
+ });
433
+ }
434
+ async delete(url, options) {
435
+ try {
436
+ if (this.isRelativeUrl(url)) {
437
+ const { data } = await this.api.delete(url, {
438
+ ...this.queryOptions,
439
+ headers: this.buildHeaders(options?.headers)
440
+ });
441
+ if (options?.returnErrors) {
442
+ return [data, null];
443
+ }
444
+ return data;
445
+ } else {
446
+ const res = await fetch(url, {
447
+ method: "DELETE",
448
+ headers: new Headers(options?.headers),
449
+ credentials: options?.credentials ?? "same-origin"
450
+ });
451
+ if (!res.ok) {
452
+ const err = await buildErrorResponse(res);
453
+ throw err;
454
+ }
455
+ let json = null;
456
+ if (res.status !== 204) {
457
+ json = await res.json();
458
+ }
459
+ if (options?.returnErrors) {
460
+ return [json, null];
461
+ }
462
+ return json;
463
+ }
464
+ } catch (ex) {
465
+ if (options?.returnErrors) {
466
+ return [null, ex];
467
+ } else {
468
+ this.onError(ex);
469
+ }
470
+ }
471
+ }
472
+ async deleteWithErrors(url, options) {
473
+ return this.delete(url, {
474
+ ...options,
475
+ returnErrors: true
476
+ });
477
+ }
478
+ async openCreateRecordModal(objectId) {
479
+ return this.openCreateRecordHandler(objectId);
480
+ }
481
+ async openCreateRelatedRecordModal(objectId, relatedEntityId) {
482
+ return this.openCreateRelatedRecordHandler(objectId, relatedEntityId);
483
+ }
484
+ showToast(message, toastOptions) {
485
+ this.instance.postMessage(
486
+ JSON.stringify({
487
+ action: ACTIONS.SHOW_TOAST,
488
+ message,
489
+ toastOptions
490
+ })
491
+ );
492
+ }
493
+ clearToasts() {
494
+ this.instance.postMessage(
495
+ JSON.stringify({
496
+ action: ACTIONS.CLEAR_TOASTS
497
+ })
498
+ );
499
+ }
500
+ outputUI(markup) {
501
+ this.instance.postMessage(
502
+ JSON.stringify({
503
+ action: ACTIONS.UI_OUTPUT,
504
+ markup
505
+ })
506
+ );
507
+ }
508
+ prompt(config) {
509
+ return this.promptHandler(config);
510
+ }
511
+ async dynamicPrompt(_config) {
512
+ const replacementVar = "__kizen_state";
513
+ let prepend = "const __kizen_utils = {};\n";
514
+ if (_config.registerUtils) {
515
+ const utils = Object.keys(_config.registerUtils);
516
+ prepend += utils.map((u) => {
517
+ const body = _config.registerUtils?.[u];
518
+ if (typeof body !== "function") {
519
+ throw new Error(`Registered util ${u} is not a function, got ${typeof body}`);
520
+ }
521
+ return `__kizen_utils["${u}"] = (${body.toString()});`;
522
+ }).join("\n");
523
+ }
524
+ const configContentResult = _config.content?.map((f) => {
525
+ let optionMapper = "";
526
+ if ("optionMapper" in f) {
527
+ optionMapper = convertToSelfInvokingFunction(
528
+ f.optionMapper,
529
+ replacementVar,
530
+ f.args,
531
+ prepend
532
+ );
533
+ }
534
+ let getFetchUrl = "";
535
+ if ("getFetchUrl" in f) {
536
+ getFetchUrl = convertToSelfInvokingFunction(f.getFetchUrl, replacementVar, f.args, prepend);
537
+ }
538
+ let getHeaders = "";
539
+ if ("getHeaders" in f) {
540
+ getHeaders = convertToSelfInvokingFunction(f.getHeaders, replacementVar, f.args, prepend);
541
+ }
542
+ let getBody = "";
543
+ if ("getBody" in f) {
544
+ getBody = convertToSelfInvokingFunction(f.getBody, replacementVar, f.args, prepend);
545
+ }
546
+ return {
547
+ ...f,
548
+ optionMapper,
549
+ getFetchUrl,
550
+ getHeaders,
551
+ getBody
552
+ };
553
+ });
554
+ const config = {
555
+ ..._config,
556
+ content: configContentResult
557
+ };
558
+ const setupAssistantConfig = {
559
+ fields: config.content
560
+ };
561
+ const result = await this.dynamicPromptHandler(config);
562
+ const cleanConfigValue = cleanConfig(setupAssistantConfig, result.values);
563
+ return {
564
+ ...result,
565
+ values: cleanConfigValue
566
+ };
567
+ }
568
+ outputIframe(url, allow, sandbox) {
569
+ this.instance.postMessage(
570
+ JSON.stringify({
571
+ action: ACTIONS.IFRAME_OUTPUT,
572
+ url,
573
+ allow,
574
+ sandbox,
575
+ preserve: this.preserve
576
+ })
577
+ );
578
+ }
579
+ getBase64EncodedBlob(data) {
580
+ return new Promise((resolve, reject) => {
581
+ const reader = new FileReader();
582
+ reader.readAsDataURL(data);
583
+ reader.onload = () => {
584
+ resolve(reader.result);
585
+ };
586
+ reader.onerror = (error) => {
587
+ reject(error);
588
+ };
589
+ });
590
+ }
591
+ async uploadFile(data, fileName, isPublic = false) {
592
+ const encoded = await this.getBase64EncodedBlob(data);
593
+ const res = await this.uploadFileHandler({
594
+ file: encoded,
595
+ fileName: fileName ?? "file_" + String(Date.now()),
596
+ isPublic
597
+ });
598
+ return res;
599
+ }
600
+ afterSetup() {
601
+ }
602
+ __setup() {
603
+ if (this.setupExecutions !== 0) {
604
+ throw new Error(
605
+ "Setup must be called exactly once, and should never be called by a script directly."
606
+ );
607
+ }
608
+ if (this.cleanupExecutions !== 0) {
609
+ throw new Error("Setup was called after cleanup");
610
+ }
611
+ if (this.isDebug) {
612
+ this.console.log(`Running script:
613
+
614
+ ${this.scriptBody}`);
615
+ }
616
+ this.setupExecutions++;
617
+ this.executionTimer = performance.now();
618
+ this.afterSetup();
619
+ }
620
+ __cleanup(result) {
621
+ if (this.cleanupExecutions !== 0) {
622
+ throw new Error(
623
+ "Cleanup must be called exactly once, and should never be called by a script directly."
624
+ );
625
+ }
626
+ if (this.setupExecutions !== 1) {
627
+ throw new Error("Cleanup was called before setup");
628
+ }
629
+ this.cleanupExecutions++;
630
+ this.setIndicator("none" /* NONE */);
631
+ const end = performance.now();
632
+ if (this.isDebug) {
633
+ this.console.log(`Script execution took ${String(end - this.executionTimer)}ms`);
634
+ }
635
+ this.done(this.preserve, result);
636
+ }
637
+ setIndicator(indicator = "none" /* NONE */) {
638
+ this.internalState.indicator = indicator;
639
+ this.setState({ indicator });
640
+ }
641
+ wait(ms) {
642
+ return new Promise((resolve) => setTimeout(resolve, ms));
643
+ }
644
+ done(preserve, result) {
645
+ this.instance.postMessage(
646
+ JSON.stringify({
647
+ action: ACTIONS.DONE,
648
+ result,
649
+ preserve
650
+ })
651
+ );
652
+ }
653
+ setState(state) {
654
+ this.instance.postMessage(
655
+ JSON.stringify({
656
+ action: ACTIONS.SETSTATE,
657
+ state
658
+ })
659
+ );
660
+ }
661
+ isRelativeUrl(url) {
662
+ return url.startsWith("/");
663
+ }
664
+ buildHeaders(headers = {}) {
665
+ return {
666
+ ...headers,
667
+ "X-Request-Type": "kizen-ui-scripting-api"
668
+ };
669
+ }
670
+ refreshTimelineForId(id) {
671
+ if (id) {
672
+ this.instance.postMessage(
673
+ JSON.stringify({
674
+ action: ACTIONS.REFRESH_TIMELINE,
675
+ entityId: id
676
+ })
677
+ );
678
+ }
679
+ }
680
+ refreshEntityForId(id) {
681
+ if (id) {
682
+ return this.refreshEntityHandler(id);
683
+ }
684
+ }
685
+ async installThirdPartyScript(scriptUrl) {
686
+ try {
687
+ const result = await this.installThirdPartyScriptHandler(scriptUrl, this.args);
688
+ const manager = new ThirdPartyScript(this.instance, result.url);
689
+ return manager;
690
+ } catch {
691
+ this.onError(new Error(`Third party script ${scriptUrl} could not be installed.`));
692
+ }
693
+ }
694
+ releaseBlockingScript() {
695
+ this.instance.postMessage(
696
+ JSON.stringify({
697
+ action: ACTIONS.RELEASE_BLOCKING_SCRIPT
698
+ })
699
+ );
700
+ }
701
+ copyToClipboard(text) {
702
+ this.instance.postMessage(
703
+ JSON.stringify({
704
+ action: ACTIONS.COPY_TO_CLIPBOARD,
705
+ text
706
+ })
707
+ );
708
+ }
709
+ createDateObject(dateString) {
710
+ if (typeof dateString !== "string") {
711
+ throw new Error(`Invalid date string ${String(dateString)}`);
712
+ }
713
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
714
+ throw new Error(`Date string ${dateString} is not in the format YYYY-MM-DD`);
715
+ }
716
+ const parts = dateString.split("-").map((part) => parseInt(part, 10));
717
+ if (parts.length < 3) {
718
+ throw new Error(`Date string ${dateString} could not be parsed into valid date parts`);
719
+ }
720
+ const dateObj = new Date(parts[0], parts[1] - 1, parts[2]);
721
+ return dateObj;
722
+ }
723
+ formatDateForResponse(date) {
724
+ return date.getTime();
725
+ }
726
+ };
727
+
728
+ export { BaseWorkerContext };
729
+ //# sourceMappingURL=chunk-NXLAROEM.js.map
730
+ //# sourceMappingURL=chunk-NXLAROEM.js.map