-
Notifications
You must be signed in to change notification settings - Fork 0
/
drafts-type-definitions.js
4929 lines (4470 loc) · 169 KB
/
drafts-type-definitions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// NOTE: This file must be opened next to the script file such that VSCode detects the
// types defined in this file correctly!
// Current version of Drafts types definition is available at
// https://github.com/agiletortoise/drafts-script-reference/blob/main/docs/drafts-definitions.js
// Forum Discussion: https://forums.getdrafts.com/t/developing-outside-of-drafts/9578/10?u=jaybe
/**
*
*
* In addition to being able to lookup an action using the find method, a single global `action` object is created and available in scripts to inquire about the current action and control flow.
*
* ### Example: Queuing an action to run
*
* ```javascript
* // find action by name
* let otherAction = Action.find("Copy");
*
* // queue to action to run after the current action, on the same draft
* app.queueAction(otherAction, draft);
* ```
*
* ### Example: Branching based on current action
* ```javascript
* // use global `action` to branch logic in a script reused in multiple actions
* if (action.name == "Copy") {
* // do something
* }
* else {
* // do something else
* }
* ```
*/
declare class Action {
private constructor()
/**
* Search for action matching the name passed and return it if found. Useful to lookup and action and queue it to be run using the {@link App.queueAction} function of the {@link App} object. This method will return only the first found action with the given name, be sure to avoid duplicate names in your action list.
* @category Query
* @param name Name of a valid, installed action.
*/
static find(name: string): Action | undefined
/**
* The display name of the action as displayed in the action list.
* @category Identification
*/
readonly name: string
/**
* URL which can be used to install this Action in another installation of Drafts. Useful for sharing and backups.
* @category Identification
*/
readonly installURL: string
/**
* The unique identifier of the action group.
* @category Identification
*/
readonly uuid: string
/**
* If true, the action is a separator.
* @category Identification
*/
readonly isSeparator: boolean
}
/**
* The current running action. This can be used in script to branch based on action name.
*/
declare const action: Action
/**
* Represents an action group. Can be used to inquire and load action groups in the action list and action bar using methods on the {@link App} object.
*
* ### Examples: Loading action group in action list
*
* ```javascript
* let group = ActionGroup.find("Basic");
* app.loadActionGroup(group);
* ```
*
*/
declare class ActionGroup {
private constructor()
/**
* Get list of all available action groups.
* @category Query
*/
static getAll(): ActionGroup[]
/**
* Search for action group matching the name passed and return it if found. Returns `undefined` if not found.
* @param name The display name of the action group.
* @category Query
*/
static find(name: string): ActionGroup | undefined
/**
* The display name of the action group.
* @category Identification
*/
readonly name: string
/**
* The unique identifier of the action group.
* @category Identification
*/
readonly uuid: string
/**
* URL which can be used to install this Action Group in another installation of Drafts. Useful for sharing and backups.
* @category Identification
*/
readonly installURL: string
/**
* The actions contained in the action group.
* @category Content
*/
readonly actions: Action[]
}
/**
* ActionLog objects represent entries in the [action log](). ActionLog objects are accessed using the `actionLogs` property of the {@link Draft} object.
*
* ### Example
*
* ```javascript
* // loop over log entries, deleting any more than 100 days old
* for(let log of draft.actionLogs) {
* if (log.executedAt < Date.today.addDays(-100)) {
* log.delete();
* }
* }
* ```
*/
declare class ActionLog {
private constructor()
/**
* Unique identifier
* @category Identification
*/
readonly uuid: string
/**
* The content of the log
* @category Content
*/
readonly log: string
/**
* Status of the log. "failed" indicates the action ended in an error, "completed" indicates successful completion of the action.
* @category Content
*/
readonly status: "pending" | "in-progress" | "completed" | "failed" | "cancelled"
/**
* Timestamp for the creation of the log entry
* @category Content
*/
readonly executedAt: Date
/**
* The {@link Draft} object related to the log. This value may be nil if the action was performed without a draft in context, or if the related draft no longer exists.
* @category Identification
*/
readonly draft?: Draft
/**
* The {@link Action} object related to the log. This value may be nil if the action no longer exists.
* @category Identification
*/
readonly action?: Action
/**
* The longitude portion of the location recorded when action was executed, if location services are enabled.
* @category Content
*/
readonly executedLongitude: number
/**
* The latitude portion of the location recorded when action was executed, if location services are enabled.
* @category Content
*/
readonly executedLatitude: number
/**
* Which device the action was performed on, typically 'iPhone', 'iPad', or 'Mac'
* @category Content
*/
readonly executedDevice: string
/**
* Delete the action log. This is permanent and should be used with caution
*/
delete()
}
/**
* Alarms are alerts which can be attached to {@link Reminder} and [[Event objects.
*
* ### Examples
*
* ```javascript
* let list = ReminderList.findOrCreate("Errands");
* let reminder = list.createReminder();
* reminder.title = "Get more paper towels";
*
* let alarm = Alarm.alarmWithDate((3).days().fromNow());
* reminder.addAlarm(alarm);
* reminder.update();
* ```
*/
declare class Alarm {
/**
* Alarm set to remind at a specific date/time.
* @param date: Date
*/
static alarmWithDate(date: Date): Alarm
/**
* Alarm set to remind at a specific number of seconds relative to the start date of the event. Note that alarms created with this methods are only supported on {@link Event} objects, not [[Reminder objects.
* @param seconds: Number seconds from now
*/
static alarmWithOffset(seconds: Number): Alarm
}
/**
* Drafts defines a single global `app` object which provides access to application level functions.
*
* ### Examples
*
* ```javascript
* // toggle dark-light mode
* if (app.currentThemeMode == 'dark') {
* app.themeMode = 'light';
* }
* else {
* app.themeMode = 'dark';
* }
* ```
*/
declare class App {
private constructor()
/**
* Returns true if app has an active Drafts Pro subscription.
* @category System
*/
readonly isPro: boolean
/**
* Version number of current installation of Drafts.
* @category System
*/
readonly version: string
/**
* Get or set themeMode.
* @category Theme
*/
themeMode: 'light' | 'dark' | 'automatic'
/**
* The current light mode theme.
* @category Theme
*/
lightTheme: Theme
/**
* The current dark mode theme.
* @category Theme
*/
darkTheme: Theme
/**
* Returns the active theme mode, light or dark, taking into account automatic switching of themes if active. If writing scripts to branch logic based on the current mode, this is the best property to use.
* @category Theme
*/
readonly currentThemeMode: 'light' | 'dark'
/**
* Is the draft list side panel is visible.
* @category Interface
*/
readonly isDraftListVisible: boolean
/**
* Is the action list side panel is visible.
* @category Interface
*/
readonly isActionListVisible: boolean
/**
* Is system sleep timer disabled preventing screen dimming/sleep.
* @category System
*/
isIdleDisabled: boolean
/**
* Request system opens the URL passed. Returns true if URL was opened, false if the URL was invalid or no available app can open the URL on the device.
* @param url url to open
* @param useSafari whether to use the Safari View Controller (true) or default browser (false).
* @category Utility
*/
openURL(url: string, useSafari?: boolean): boolean
/**
* Queues an action to run on a draft after the current action is complete.
* ```javascript
* // lookup action and draft, and queue the action to run
* let a = Action.find("Copy");
* let d = Draft.find("UUID");
* app.queueAction(a, d);
* ```
* @category Utility
* @param action Actions can be obtained using the `Action.find(name)` method.
* @param draft A draft object.
*/
queueAction(action: Action, draft: Draft): boolean
/**
* Open draft selection interface and wait for user to select a draft. Returns the select draft object, or `undefined` if user cancelled.
* @category Interface
* @param workspace If provided, the workspace will define the default filtering, display, and sort options for the selection window.
*/
selectDraft(workspace?: Workspace): Draft | undefined
// UI FUNCTIONS
/**
* Open draft list side bar.
* @category Interface
*/
showDraftList(): void
/**
* Close draft list side bar.
* @category Interface
*/
hideDraftList(): void
/**
* Open quick search window, optionally providing a initial query value.
* @category Interface
*/
showQuickSearch(initialQuery?: string): void
/**
* Open the "Get Info" view for a draft. If no draft is passed, the current active draft in the editor will be used.
* @category Interface
*/
showDraftInfo(draft?: Draft): void
/**
* If able, open the requested draft in a new window. This method only functions on iPad and Mac. The ability to open new windows is not available on iPhone.
* @returns `true` if successful. `false` if unable to open a new window (as on iPhone).
* @category Interface
*/
openInNewWindow(draft: Draft): boolean
/**
* Open action list side bar.
* @category Interface
*/
showActionList(): void
/**
* Close action list side bar.
* @category Interface
*/
hideActionList(): void
/**
* Apply the Workspace as if it was selected in draft list. Calling this function with no arguments will clear filters and apply the default workspace.
* @category Interface
**/
applyWorkspace(workspace?: Workspace): boolean
/**
* Returns a workspace object configured like the workspace currently loaded in the draft list of the active window. Useful when creating logic which reacts contextually to the workspace loaded.
* @category Interface
*/
currentWorkspace: Workspace
/**
* Load the ActionGroup in the action list side bar.
* @category Interface
*/
loadActionGroup(actionGroup: ActionGroup): boolean
/**
* Load the ActionGroup in the action bar below editor.
* @category Interface
*/
loadActionBarGroup(actionGroup: ActionGroup): boolean
/**
* @deprecated replaced by `loadActionBarGroup`.
* @category Deprecated
*/
loadKeyboardActionGroup(actionGroup: ActionGroup): boolean
/**
* Enable and disable the iOS system sleep timer to prevent screen dimming/sleep.
* @category Utility
*/
setIdleDisabled(isDisabled: boolean): void
// CLIPBOARD FUNCTIONS
/**
* Get current contents of the system clipboard.
* @category Utility
*/
getClipboard(): string
/**
* Set the contents of the system clipboard.
* @param string the data to set
* @category Utility
*/
setClipboard(contents: string): void
/**
* Takes HTML string and converts it to rich-text and places it in the system clipboard. Returns true if successful, false if an error occurred in conversion.
* @param html a possibly-valid html string
* @category Utility
*/
htmlToClipboard(html: string): boolean
// MESSAGES FUNCTIONS
/**
* Show success banner notification with the message passed.
* @category Interface
*/
displaySuccessMessage(message: string): void
/**
* Show info banner notification with the message passed.
* @category Messages
*/
displayInfoMessage(message: string): void
/**
* Show warning banner notification with the message passed.
* @category Messages
*/
displayWarningMessage(message: string): void
/**
* Show error banner notification with the message passed.
* @category Messages
*/
displayErrorMessage(message: string): void
}
/**
* Reference to current app object.
*/
declare const app: App
/**
* > _**macOS only**. Requires Drafts 19 or greater._
*
* AppleScript objects can be used to execute AppleScripts. It is highly recommended AppleScripts be developed and tested in Apple's Script Editor or similar AppleScript editor, and loaded in Drafts when completed.
*
* ### Example
*
* ```javascript
* // create a local file in App documents
* let method = "execute";
* let script = `on execute(bodyHTML)
* tell application "Safari"
* activate
* end tell
* return "Yeah!"
* end execute`;
*
* let html = draft.processTemplate("%%[[draft]]%%");
* let runner = AppleScript.create(script);
* if (runner.execute(method, [html])) {
* // the AppleScript ran without error
* // if the script returned a result, it's available...
* alert(runner.lastResult);
* }
* else {
* alert(runner.lastError);
* }
* ```
*
* **Note:** When executed, AppleScripts are saved to temporary files in the Drafts' script directory at `~/Library/Application Scripts/com.agiletortoise.Drafts-OSX` and run. The first time a script is executed, the user will be asked to grant permissions to the script directory.
*/
declare class AppleScript {
/**
* If a function fails, this property will contain the last error as a string message, otherwise it will be `undefined`.
*/
lastError?: string | undefined
/**
* If a the AppleScript subroutine called returns a value and it can be converted to a JavaScript object, it will be stored here. Most basic data types (string, date, numbers), as well as list and records containing those data types, can be returned.
*/
lastResult?: object | undefined
/**
* Convenience method to create an AppleScript object.
* @param script A string containing the AppleScript code. This code will be compiled and executed when the `execute` function is called.
*/
static create(script: string): AppleScript
/**
* Create new instance.
*/
constructor(script: string)
/**
* Compiles and executes the AppleScript code, calling the subroutine passed with the arguments.
* @param subroutine The name of a subroutine in the AppleScript to call. [Subroutines](http://www.macosxautomation.com/applescript/sbrt/) are defined using `on subroutineName()` syntax in the AppleScript.
* @param arguments An array of arguments to pass to the subroutine. Most basic Javascript data types, and objects and arrays of those data types, can be passed and will be translated to the proper AppleScript types.
* @returns `true` if the AppleScript was compiled and executed without error, `false` if not. If `false`, the `lastError` property will contain details regarding the error.
*/
execute(subroutine: string, arguments: object[]): boolean
}
/**
* Create and update entries in the Editor's [global autocomplete system](https://docs.getdrafts.com/docs/editor/autocomplete)
*
* ### Examples
*
* ```javascript
* // work with the default system autocomplete
* let autocomplete = Autocomplete.getDefault();
* // object with all autocomplete items, using label as key
* let items = autocomplete.getAll();
* // add new autocomplete item
* autocomplete.add("label", "template value");
* ```
*
*/
declare class Autocomplete {
private constructor()
/**
* Get the default system global autocomplete object
* @category Constructors
*/
static getDefault(): Autocomplete
/**
* Get all existing autocomplete items as an object with the item lobels as keys, and templates as values.
* @category Query
*/
getAll(): object
/**
* Create a new autocomplete item
* @param label The label used in the autocomplete drop-down
* @param template The template value used to insert text
* @category Update
*/
add(label: string, template: string): boolean
/**
* Deletes aa autocomplete item. Returns true if successful, false if item with label does not exist.
* @param label The label used in the autocomplete drop-down
* @category Update
*/
remove(label: string): boolean
}
/**
* Helper methods to encode and decode [Base64](https://en.wikipedia.org/wiki/Base64) strings.
*
* ### Examples
*
* ```javascript
* let s = "My String";
* let encoded = Base64.encode(s);
* let decoded = Base64.decode(encoded);
* ```
*/
declare class Base64 {
private constructor()
/**
* Base64 encode a string.
* @param data the string to encode
*/
static encode(data: string): string
/**
* Base64 decode a string.
* @param data the string to decode
*/
static decode(data: string): string
}
/**
* Bookmark objects are used to work with folder bookmarks and the {@link FileManager} object to provide access to folders outside the Drafts App Sandbox. Bookmarks are unique by name. A user-friendly name should be used, as the first time a bookmark is required, the user is prompted to select the folder in their file system to associate with the bookmark, and a useful name can help guide them to selecting the correct folder.
*
* _Learn more about [Bookmarks in the User Guide](https://docs.getdrafts.com/docs/settings/bookmarks)_
*
* ### Example
*
* ```javascript
* // find or create a named Bookmark
* let bookmark = Bookmark.findOrCreate("My-Folder");
* let fm = FileManager.createForBookmark(bookmark);
*
* // write to a file at the root of the bookmark folder
* let success = fm.writeString("/ScriptedFile.txt", "This is the file * content");
*
* // read from file in bookmarked folder
* let content = fm.readString("/Test Folder/Test.txt")
* ```
*/
declare class Bookmark {
private constructor()
/**
* Get a bookmark object with the specified name. If no bookmark with the specified name exists, a new one will be created.
*/
static findOrCreate(name: string): Bookmark
/**
* The name of the bookmark.
*/
readonly name: string
/**
* Forget the bookmark, resetting any associated permissions. Generally, this would be a function the user performs in the user interface, but could be useful in the case of an action which wishes to request and use a one-time bookmark and revoke permissions on completion of an action.
*/
forget()
}
/**
* Box objects can be used to work with files in a Box.com account.
*
* ### Examples
*
* ```javascript
* // create Box object
* var drive = Box.create();
*
* // setup variables
* var path = "/test/file.txt";
* var content = "text to place in file";
*
* // write to file on Box
* var success = drive.write(path, content, false);
*
* if (success) { // write worked!
* var driveContent = drive.read(path);
* if (driveContent) { // read worked!
* if (driveContent == content) {
* alert("File contents match!");
* }
* else {
* console.log("File did not match");
* context.fail();
* }
* }
* else { // read failed, log error
* console.log(drive.lastError);
* context.fail();
* }
* }
* else { // write failed, log error
* console.log(drive.lastError);
* context.fail();
* }
* ```
*/
declare class Box {
readonly lastError?: string
/**
* Reads the contents of the file at the path as a string. Returns `undefined` value if the file does not exist or could not be read. Paths should begin with a `/` and be relative to the root directory of your Box.com account.
* @param path
*/
read(path: string): string
/**
* Write the contents of the file at the path. Returns true if successful, false if the file could not be written successfully. This will override existing files!
* @param path Paths should begin with a `/` and be relative to the root directory of your Box
* @param content Text to place in the file.
* @param overwrite If false, an existing file will not be overwritten.
*/
write(path: string, content: string, overwrite?: boolean): boolean
/**
* Creates a new Box object. Identifier is a optional string value used to identify a Box.com account. Typically this can be omitted if you only work with one Box.com account in Drafts.
*/
static create(identifier?: string): Box
/**
* Create new instance.
*/
constructor(identifier?: string)
}
/**
* Calendar objects are used to manipulate and create calendars in the built-in Calendars app and its associated accounts.
*
* ### Example: Event Creation
*
* ```javascript
* var calendar = Calendar.findOrCreate("Activities");
* var event = calendar.createEvent();
* event.title = "Dinner Party";
* event.notes = "Bring side dish.";
* event.startDate = Date.parse("7pm next friday");
* event.endDate = Date.parse("10pm next friday");
* event.isAllDay = false;
* if (!event.update()) {
* console.log(event.lastError);
* }
* ```
*
* ### Example: Reading Calendar Events
*
* ```javascript
* // load a calendar
* let cal = Calendar.find("Test");
* // loop over events in the last 30 days and alert the name of each.
* if (cal) {
* let events = cal.events((30).days().ago(), new Date());
* for (let event of events) {
* alert(event.title);
* }
* }
* ```
*/
declare class Calendar {
title: string
/**
* A Boolean value that indicates whether you can add, edit, and delete items in the calendar.
*/
allowsContentModificationx: boolean
/**
* A Boolean value indicating whether the calendar’s properties can be edited or deleted.
*/
isImmutable: boolean
/**
* Save changes to the calendar.
*/
update(): boolean
/**
* Create a new Event object in this calendar.
*/
createEvent(): Event
/**
* Returns array of events on the calendar between the start and end dates specified.
*/
events(startDate: Date, endDate: Date): Event[]
/**
* Searches for a calendar matching the title. If none is found, creates a new list with that title in your default calendars account. If more than one calendar with the same name exist in Calendars, the first found will be returned.
*/
static findOrCreate(title: string): Calendar
/**
* Searches for a calendar matching the title. If none is found, return `undefined`.
*/
static find(title: string): Calendar | undefined
/**
* Get an array all known calendars on the device.
*/
static getAllCalendars(): Calendar[]
/**
* Returns the system default calendar configured for new events.
*/
static default(): Calendar
}
/**
* CallbackURL objects can be used to open x-callback-url requests and wait for a response from the target app.
*
* > **NOTE**: If you want to open a URL in Safari or another app and do not need a response or x-callback-url support, use the {@link App.openURL} method on the {@link App} object.
*
* ### Example
*
* ```javascript
* // Open callback URL for each line in a draft
* // Setup base Fantastical URL, with no parameters
* declare const baseURL = "fantastical2://x-callback-url/parse/";
*
* // split draft and loop over lines
* var lines = draft.content.split("\n");
* for (var line of lines) {
* // create and configure callback object
* var cb = CallbackURL.create();
* cb.baseURL = baseURL;
* cb.addParameter("sentence", line);
* // open and wait for result
* var success = cb.open();
* if (success) {
* console.log("Event created");
* }
* else { // something went wrong or was cancelled
* console.log(cb.status);
* if (cb.status == "cancelled") {
* context.cancel();
* }
* else {
* context.fail();
* }
* }
* }
* ```
*/
declare class CallbackURL {
/**
* The baseURL of the request. This should include the x-callback-url base URL and action, typically something like `app-scheme://x-callback-url/actionName`
*/
baseURL: string
/**
* The current URL. This is provided as a debugging property, and will output the URL including the baseURL property with any configured parameters added. This property will differ from the actual URL opened when calling `open()` in that it will not contain the `x-success`, `x-error` and `x-cancel` parameters which are added dynamically at the time `open()` is called.
*/
url: string
/**
* If true, the script will pause and wait for the `x-success`, `x-error` or `x-cancel` response from the app being targeted by the URL. If false, execution of the script/action will continue immediately and no response/results will be available.
*/
waitForResponse: boolean
/**
* Object containing string keys and values to be appended to the base url as query parameters. Values should not be pre-encoded, but will be encoded and added to the base URL automatically. Do not include x-callback parameters (`x-success`, `x-error`, `x-cancel`) as these will be generated by Drafts.
*/
parameters: { [x: string]: any }
/**
* The current status of the callback. Used to check outcome after open is called. Possible values:
* * created: open has not yet been called.
* * success: x-success callback was received from target app.
* * cancelled: x-cancel callback was received from target app.
* * error: x-error callback was received from target app.
* * timeout: Waiting for the response timed out without receiving a callback URL from the target app.
* * invalid: The URL was invalid and could not be opened.
*/
status: 'created' | 'success' | 'cancelled' | 'error' | 'timeout' | 'invalid'
/**
* An object contain and URL query parameters returned by the target app along with it’s callback response. For example, if the target app called x-success with the query parameters `result=MyTestText`, callbackResponse would contain `{"result": "MyTestText"}`.
*/
callbackResponse: { [x: string]: any }
/**
* Opens the URL with associated parameters, and waits for a callback response. Returns true if an x-success response was received from the target app, otherwise false. If false, use the "status" property to determine the type of failure.
*/
open(): boolean
/**
* Add a query parameter for the outgoing URL.
* FIXME: can the value be anything?
*/
addParameter(key: string, value: any): void
/**
* Creates a new CallbackURL object.
*/
static create(): CallbackURL
/**
* Create new instance.
*/
constructor()
}
/**
* A single global "context" object is available to scripts to control flow of the currently running action.
*
* It is important to understand that `cancel()` and `fail()` will not immediately stop script, just stop any further action steps from being performed.
*
* ### Example: Control Flow
*
* ```javascript
* // test for logical condition before continuing
* if (!validationCondition) {
* context.fail();
* }
* // code below will still run.
* ```
*
* ### Example: Retreive values
*
* ```javascript
* // if a "Run Workflow" step preceded this script, lets look for a result
* var response = context.callbackResponses[0];
* if (response) {
* // Workflow returns one "result" parameter, other apps may use other values.
* var result = response["result"];
* if (result) {
* // so something with the result
* }
* }
* ```
*
*/
declare class Context {
private constructor()
/**
* If [Callback URL](https://docs.getdrafts.com/docs/actions/steps/advanced#callback-url) or [Run Shortcut](https://docs.getdrafts.com/docs/actions/steps/advanced#run-shortcut) action steps using the "Wait for response" option have been run in steps before the script step in an action, and the target app returned to Drafts using an x-success callback, this object will contain an array of objects with the parsed query parameters included in those responses, in the order they were received.
*/
callbackResponses: { [x: string]: any }
/**
* If AppleScripts run using the AppleScript object return values, they will be converted to JavaScript object and stored in this array. See [AppleScript docs](https://docs.getdrafts.com/docs/automation/applescript) for details.
*/
appleScriptResponses: { [x: string]: any }
/**
* If [HTML Preview](https://docs.getdrafts.com/docs/actions/html-forms) makes calls to `Drafts.send(key, value)` those values are stored in this object by `key`.
*/
previewValues: { string: any }
/**
* Tell the context to cancel the action at the end of the script execution. If called, at the end of the script the action will be stopped. No subsequent action steps in the action will run, and the action still stop silently - no notification banners, sounds, etc. If a message is included it will be added to the action log to explain the cancellation.
*/
cancel(message: string): void
/**
* Tell the context to fail the current action. In effect this is the same as `cancel()` but an error notification will be shown. If a message is included it will be added to the action log to explain the cancellation.
*/
fail(message: string): void
/**
* Used only when calling a Drafts action from another app via x-callback-url with a `/runAction` URL. Any parameters set via this method will be included as query args when calling the provided `x-success` parameter. As an example, the below:
*
* ```
* context.addSuccessParameter("a", "1");
* context.addSuccessParameter("b", "2");
* ```
*
* Would result in the parameters `?a=1&b=2` being added to the `x-success` callback.
* @param name The name for the parameter
* @param value A string value for the parameter. Do *not* URL encode this value, it will be encoded when added to the callback URL.
*/
addSuccessParameter(name: string, value: string): void
}
declare const context: Context
/**
* Credential objects can be used in actions which require the user to provide a username, password and optionally a host name, to connect to a service. By using credentials objects, actions can be written to connect to arbitrary web services without hard coding credentials into the action.
*
* When an authorize() call is made on a credential object for the first time, the user is prompted to enter their credentials, then Drafts stores those for later use. When the action is used again, there will be no prompt required and the stored credentials will be used.
*
* Credentials objects have unique identifiers, and a single set of user credentials can be used across actions by using the same identifier.
*
* The user can delete those credentials at any time by visiting Settings > Credentials and tapping the "Forget" button on a service.
*
* ### Example
*
* ```javascript
* var credential = Credential.create("My Service", "Description of the service to * appear in user prompt.");
*
* credential.addTextField("username", "Username");
* credential.addPasswordField("password", "Password");
*
* credential.authorize();
*
* var http = HTTP.create();
* var response = http.request({
* "url": "http://myurl.com/api",
* "username": credential.getValue("username"),
* "password": credential.getValue("password"),
* "method": "POST",
* "data": {
* "key":"value"
* },
* "headers": {
* "HeaderName": "HeaderValue"
* }
* });
*
* ```
*/
declare class Credential {
/**
* Create a credential object with the specified identifier and description. Identifiers should be unique, such that any two calls from different actions with the same identifier will return the same credentials
* @param identifier Unique identifier for the credentials
* @param description Optional description
*/
static create(identifier: string, description?: string): Credential
/**
* Create credential already configured with username and password fields.
* @param identifier Unique identifier for the credentials
* @param description Optional description
*/
static createWithUsernamePassword(
identifier: string,
description: string
): Credential
/**
* Create credential already configured with host url, username and password fields.
* @param identifier Unique identifier for the credentials
* @param description Optional description
*/
static createWithHostUsernamePassword(
identifier: string,
description: string
): Credential
/**
* Create new instance.
* @param identifier Unique identifier for the credentials
* @param description Optional description
*/
constructor(identifier: string, description?: string)