/
PluginApi.js
722 lines (674 loc) · 18.4 KB
/
PluginApi.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
const path = require('path')
// Connectors
const logs = require('../connectors/logs')
const sharedData = require('../connectors/shared-data')
const views = require('../connectors/views')
const suggestions = require('../connectors/suggestions')
const folders = require('../connectors/folders')
const progress = require('../connectors/progress')
const app = require('../connectors/app')
// Utils
const ipc = require('../util/ipc')
const { notify } = require('../util/notification')
const { matchesPluginId } = require('@vue/cli-shared-utils')
const { log } = require('../util/logger')
// Validators
const { validateConfiguration } = require('./configuration')
const { validateDescribeTask, validateAddTask } = require('./task')
const { validateClientAddon } = require('./client-addon')
const { validateView, validateBadge } = require('./view')
const { validateNotify } = require('./notify')
const { validateSuggestion } = require('./suggestion')
const { validateProgress } = require('./progress')
const { validateWidget } = require('./widget')
/**
* @typedef SetSharedDataOptions
* @prop {boolean} disk Don't keep this data in memory by writing it to disk
*/
/** @typedef {import('../connectors/shared-data').SharedData} SharedData */
class PluginApi {
constructor ({ plugins, file, project, lightMode = false }, context) {
// Context
this.context = context
this.pluginId = null
this.project = project
this.plugins = plugins
this.cwd = file
this.lightMode = lightMode
// Hooks
this.hooks = {
projectOpen: [],
pluginReload: [],
configRead: [],
configWrite: [],
taskRun: [],
taskExit: [],
taskOpen: [],
viewOpen: []
}
// Data
this.configurations = []
this.describedTasks = []
this.addedTasks = []
this.clientAddons = []
this.views = []
this.actions = new Map()
this.ipcHandlers = []
this.widgetDefs = []
}
/**
* Register an handler called when the project is open (only if this plugin is loaded).
*
* @param {function} cb Handler
*/
onProjectOpen (cb) {
if (this.lightMode) return
if (this.project) {
cb(this.project)
return
}
this.hooks.projectOpen.push(cb)
}
/**
* Register an handler called when the plugin is reloaded.
*
* @param {function} cb Handler
*/
onPluginReload (cb) {
if (this.lightMode) return
this.hooks.pluginReload.push(cb)
}
/**
* Register an handler called when a config is red.
*
* @param {function} cb Handler
*/
onConfigRead (cb) {
if (this.lightMode) return
this.hooks.configRead.push(cb)
}
/**
* Register an handler called when a config is written.
*
* @param {function} cb Handler
*/
onConfigWrite (cb) {
if (this.lightMode) return
this.hooks.configWrite.push(cb)
}
/**
* Register an handler called when a task is run.
*
* @param {function} cb Handler
*/
onTaskRun (cb) {
if (this.lightMode) return
this.hooks.taskRun.push(cb)
}
/**
* Register an handler called when a task has exited.
*
* @param {function} cb Handler
*/
onTaskExit (cb) {
if (this.lightMode) return
this.hooks.taskExit.push(cb)
}
/**
* Register an handler called when the user opens one task details.
*
* @param {function} cb Handler
*/
onTaskOpen (cb) {
if (this.lightMode) return
this.hooks.taskOpen.push(cb)
}
/**
* Register an handler called when a view is open.
*
* @param {function} cb Handler
*/
onViewOpen (cb) {
if (this.lightMode) return
this.hooks.viewOpen.push(cb)
}
/**
* Describe a project configuration (usually for config file like `.eslintrc.json`).
*
* @param {object} options Configuration description
*/
describeConfig (options) {
if (this.lightMode) return
try {
validateConfiguration(options)
this.configurations.push({
...options,
pluginId: this.pluginId
})
} catch (e) {
logs.add({
type: 'error',
tag: 'PluginApi',
message: `(${this.pluginId || 'unknown plugin'}) 'describeConfig' options are invalid\n${e.message}`
}, this.context)
console.error(new Error(`Invalid options: ${e.message}`))
}
}
/**
* Describe a project task with additional information.
* The tasks are generated from the scripts in the project `package.json`.
*
* @param {object} options Task description
*/
describeTask (options) {
try {
validateDescribeTask(options)
this.describedTasks.push({
...options,
pluginId: this.pluginId
})
} catch (e) {
logs.add({
type: 'error',
tag: 'PluginApi',
message: `(${this.pluginId || 'unknown plugin'}) 'describeTask' options are invalid\n${e.message}`
}, this.context)
console.error(new Error(`Invalid options: ${e.message}`))
}
}
/**
* Get the task description matching a script command.
*
* @param {string} command Npm script command from `package.json`
* @returns {object} Task description
*/
getDescribedTask (command) {
return this.describedTasks.find(
options => typeof options.match === 'function' ? options.match(command) : options.match.test(command)
)
}
/**
* Add a new task independently from the scripts.
* The task will only appear in the UI.
*
* @param {object} options Task description
*/
addTask (options) {
try {
validateAddTask(options)
this.addedTasks.push({
...options,
pluginId: this.pluginId
})
} catch (e) {
logs.add({
type: 'error',
tag: 'PluginApi',
message: `(${this.pluginId || 'unknown plugin'}) 'addTask' options are invalid\n${e.message}`
}, this.context)
console.error(new Error(`Invalid options: ${e.message}`))
}
}
/**
* Register a client addon (a JS bundle which will be loaded in the browser).
* Used to load components and add vue-router routes.
*
* @param {object} options Client addon options
* {
* id: string,
* url: string
* }
* or
* {
* id: string,
* path: string
* }
*/
addClientAddon (options) {
if (this.lightMode) return
try {
validateClientAddon(options)
if (options.url && options.path) {
throw new Error(`'url' and 'path' can't be defined at the same time.`)
}
this.clientAddons.push({
...options,
pluginId: this.pluginId
})
} catch (e) {
logs.add({
type: 'error',
tag: 'PluginApi',
message: `(${this.pluginId || 'unknown plugin'}) 'addClientAddon' options are invalid\n${e.message}`
}, this.context)
console.error(new Error(`Invalid options: ${e.message}`))
}
}
/* Project view */
/**
* Add a new project view below the builtin 'plugins', 'config' and 'tasks' ones.
*
* @param {object} options ProjectView options
*/
addView (options) {
if (this.lightMode) return
try {
validateView(options)
this.views.push({
...options,
pluginId: this.pluginId
})
} catch (e) {
logs.add({
type: 'error',
tag: 'PluginApi',
message: `(${this.pluginId || 'unknown plugin'}) 'addView' options are invalid\n${e.message}`
}, this.context)
console.error(new Error(`Invalid options: ${e.message}`))
}
}
/**
* Add a badge to the project view button.
* If the badge already exists, add 1 to the counter.
*
* @param {string} viewId Project view id
* @param {object} options Badge options
*/
addViewBadge (viewId, options) {
if (this.lightMode) return
try {
validateBadge(options)
views.addBadge({ viewId, badge: options }, this.context)
} catch (e) {
logs.add({
type: 'error',
tag: 'PluginApi',
message: `(${this.pluginId || 'unknown plugin'}) 'addViewBadge' options are invalid\n${e.message}`
}, this.context)
console.error(new Error(`Invalid options: ${e.message}`))
}
}
/**
* Remove 1 from the counter of a badge if it exists.
* If the badge counter reaches 0, it is removed from the button.
*
* @param {any} viewId
* @param {any} badgeId
* @memberof PluginApi
*/
removeViewBadge (viewId, badgeId) {
views.removeBadge({ viewId, badgeId }, this.context)
}
/* IPC */
/**
* Add a listener to the IPC messages.
*
* @param {function} cb Callback with 'data' param
*/
ipcOn (cb) {
const handler = cb._handler = ({ data, emit }) => {
if (data._projectId) {
if (data._projectId === this.project.id) {
data = data._data
} else {
return
}
}
// eslint-disable-next-line standard/no-callback-literal
cb({ data, emit })
}
this.ipcHandlers.push(handler)
return ipc.on(handler)
}
/**
* Remove a listener for IPC messages.
*
* @param {any} cb Callback to be removed
*/
ipcOff (cb) {
const handler = cb._handler
if (!handler) return
const index = this.ipcHandlers.indexOf(handler)
if (index !== -1) this.ipcHandlers.splice(index, 1)
ipc.off(handler)
}
/**
* Send an IPC message to all connected IPC clients.
*
* @param {any} data Message data
*/
ipcSend (data) {
ipc.send(data)
}
/**
* Get the local DB instance (lowdb)
*
* @readonly
*/
get db () {
return this.context.db
}
/**
* Display a notification in the user OS
* @param {object} options Notification options
*/
notify (options) {
try {
validateNotify(options)
notify(options)
} catch (e) {
logs.add({
type: 'error',
tag: 'PluginApi',
message: `(${this.pluginId || 'unknown plugin'}) 'notify' options are invalid\n${e.message}`
}, this.context)
console.error(new Error(`Invalid options: ${e.message}`))
}
}
/**
* Indicates if a specific plugin is used by the project
* @param {string} id Plugin id or short id
*/
hasPlugin (id) {
if (id === 'router') id = 'vue-router'
if (['vue-router', 'vuex'].includes(id)) {
const pkg = folders.readPackage(this.cwd, this.context, true)
return ((pkg.dependencies && pkg.dependencies[id]) || (pkg.devDependencies && pkg.devDependencies[id]))
}
return this.plugins.some(p => matchesPluginId(id, p.id))
}
/**
* Display the progress screen.
*
* @param {object} options Progress options
*/
setProgress (options) {
if (this.lightMode) return
try {
validateProgress(options)
progress.set({
...options,
id: '__plugins__'
}, this.context)
} catch (e) {
logs.add({
type: 'error',
tag: 'PluginApi',
message: `(${this.pluginId || 'unknown plugin'}) 'setProgress' options are invalid\n${e.message}`
}, this.context)
console.error(new Error(`Invalid options: ${e.message}`))
}
}
/**
* Remove the progress screen.
*/
removeProgress () {
progress.remove('__plugins__', this.context)
}
/**
* Get current working directory.
*/
getCwd () {
return this.cwd
}
/**
* Resolves a file relative to current working directory
* @param {string} file Path to file relative to project
*/
resolve (file) {
return path.resolve(this.cwd, file)
}
/**
* Get currently open project
*/
getProject () {
return this.project
}
/* Namespaced */
/**
* Retrieve a Shared data instance.
*
* @param {string} id Id of the Shared data
* @returns {SharedData} Shared data instance
*/
getSharedData (id) {
return sharedData.get({ id, projectId: this.project.id }, this.context)
}
/**
* Set or update the value of a Shared data
*
* @param {string} id Id of the Shared data
* @param {any} value Value of the Shared data
* @param {SetSharedDataOptions} options
*/
async setSharedData (id, value, { disk = false } = {}) {
return sharedData.set({ id, projectId: this.project.id, value, disk }, this.context)
}
/**
* Delete a shared data.
*
* @param {string} id Id of the Shared data
*/
async removeSharedData (id) {
return sharedData.remove({ id, projectId: this.project.id }, this.context)
}
/**
* Watch for a value change of a shared data
*
* @param {string} id Id of the Shared data
* @param {function} handler Callback
*/
watchSharedData (id, handler) {
sharedData.watch({ id, projectId: this.project.id }, handler)
}
/**
* Delete the watcher of a shared data.
*
* @param {string} id Id of the Shared data
* @param {function} handler Callback
*/
unwatchSharedData (id, handler) {
sharedData.unwatch({ id, projectId: this.project.id }, handler)
}
/**
* Listener triggered when a Plugin action is called from a client addon component.
*
* @param {string} id Id of the action to listen
* @param {any} cb Callback (ex: (params) => {} )
*/
onAction (id, cb) {
let list = this.actions.get(id)
if (!list) {
list = []
this.actions.set(id, list)
}
list.push(cb)
}
/**
* Call a Plugin action. This can also listened by client addon components.
*
* @param {string} id Id of the action
* @param {object} params Params object passed as 1st argument to callbacks
* @returns {Promise}
*/
callAction (id, params) {
const plugins = require('../connectors/plugins')
return plugins.callAction({ id, params }, this.context)
}
/**
* Retrieve a value from the local DB
*
* @param {string} id Path to the item
* @returns Item value
*/
storageGet (id) {
return this.db.get(id).value()
}
/**
* Store a value into the local DB
*
* @param {string} id Path to the item
* @param {any} value Value to be stored (must be serializable in JSON)
*/
storageSet (id, value) {
log('Storage set', id, value)
this.db.set(id, value).write()
}
/**
* Add a suggestion for the user.
*
* @param {object} options Suggestion
*/
addSuggestion (options) {
if (this.lightMode) return
try {
validateSuggestion(options)
suggestions.add(options, this.context)
} catch (e) {
logs.add({
type: 'error',
tag: 'PluginApi',
message: `(${this.pluginId || 'unknown plugin'}) 'addSuggestion' options are invalid\n${e.message}`
}, this.context)
console.error(new Error(`Invalid options: ${e.message}`))
}
}
/**
* Remove a suggestion
*
* @param {string} id Id of the suggestion
*/
removeSuggestion (id) {
suggestions.remove(id, this.context)
}
/**
* Register a widget for project dashboard
*
* @param {object} def Widget definition
*/
registerWidget (def) {
if (this.lightMode) return
try {
validateWidget(def)
this.widgetDefs.push({
...def,
pluginId: this.pluginId
})
} catch (e) {
logs.add({
type: 'error',
tag: 'PluginApi',
message: `(${this.pluginId || 'unknown plugin'}) 'registerWidget' widget definition is invalid\n${e.message}`
}, this.context)
console.error(new Error(`Invalid definition: ${e.message}`))
}
}
/**
* Request a route to be displayed in the client
*/
requestRoute (route) {
app.requestRoute(route, this.context)
}
/**
* Create a namespaced version of:
* - getSharedData
* - setSharedData
* - onAction
* - callAction
*
* @param {string} namespace Prefix to add to the id params
*/
namespace (namespace) {
return {
/**
* Retrieve a Shared data instance.
*
* @param {string} id Id of the Shared data
* @returns {SharedData} Shared data instance
*/
getSharedData: (id) => this.getSharedData(namespace + id),
/**
* Set or update the value of a Shared data
*
* @param {string} id Id of the Shared data
* @param {any} value Value of the Shared data
* @param {SetSharedDataOptions} options
*/
setSharedData: (id, value, options) => this.setSharedData(namespace + id, value, options),
/**
* Delete a shared data.
*
* @param {string} id Id of the Shared data
*/
removeSharedData: (id) => this.removeSharedData(namespace + id),
/**
* Watch for a value change of a shared data
*
* @param {string} id Id of the Shared data
* @param {function} handler Callback
*/
watchSharedData: (id, handler) => this.watchSharedData(namespace + id, handler),
/**
* Delete the watcher of a shared data.
*
* @param {string} id Id of the Shared data
* @param {function} handler Callback
*/
unwatchSharedData: (id, handler) => this.unwatchSharedData(namespace + id, handler),
/**
* Listener triggered when a Plugin action is called from a client addon component.
*
* @param {string} id Id of the action to listen
* @param {any} cb Callback (ex: (params) => {} )
*/
onAction: (id, cb) => this.onAction(namespace + id, cb),
/**
* Call a Plugin action. This can also listened by client addon components.
*
* @param {string} id Id of the action
* @param {object} params Params object passed as 1st argument to callbacks
* @returns {Promise}
*/
callAction: (id, params) => this.callAction(namespace + id, params),
/**
* Retrieve a value from the local DB
*
* @param {string} id Path to the item
* @returns Item value
*/
storageGet: (id) => this.storageGet(namespace + id),
/**
* Store a value into the local DB
*
* @param {string} id Path to the item
* @param {any} value Value to be stored (must be serializable in JSON)
*/
storageSet: (id, value) => this.storageSet(namespace + id, value),
/**
* Add a suggestion for the user.
*
* @param {object} options Suggestion
*/
addSuggestion: (options) => {
options.id = namespace + options.id
return this.addSuggestion(options)
},
/**
* Remove a suggestion
*
* @param {string} id Id of the suggestion
*/
removeSuggestion: (id) => this.removeSuggestion(namespace + id),
/**
* Register a widget for project dashboard
*
* @param {object} def Widget definition
*/
registerWidget: (def) => {
def.id = namespace + def.id
return this.registerWidget(def)
}
}
}
}
module.exports = PluginApi