@learnpack/learnpack 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +695 -0
  2. package/bin/run +5 -0
  3. package/bin/run.cmd +3 -0
  4. package/oclif.manifest.json +1 -0
  5. package/package.json +111 -0
  6. package/plugin/command/compile.js +17 -0
  7. package/plugin/command/test.js +29 -0
  8. package/plugin/index.js +6 -0
  9. package/plugin/plugin.js +71 -0
  10. package/plugin/utils.js +78 -0
  11. package/src/commands/audit.js +243 -0
  12. package/src/commands/clean.js +27 -0
  13. package/src/commands/download.js +52 -0
  14. package/src/commands/hello.js +20 -0
  15. package/src/commands/init.js +133 -0
  16. package/src/commands/login.js +45 -0
  17. package/src/commands/logout.js +39 -0
  18. package/src/commands/publish.js +78 -0
  19. package/src/commands/start.js +169 -0
  20. package/src/commands/test.js +85 -0
  21. package/src/index.js +1 -0
  22. package/src/managers/config/allowed_files.js +12 -0
  23. package/src/managers/config/defaults.js +32 -0
  24. package/src/managers/config/exercise.js +212 -0
  25. package/src/managers/config/index.js +342 -0
  26. package/src/managers/file.js +137 -0
  27. package/src/managers/server/index.js +62 -0
  28. package/src/managers/server/routes.js +151 -0
  29. package/src/managers/session.js +83 -0
  30. package/src/managers/socket.js +185 -0
  31. package/src/managers/test.js +77 -0
  32. package/src/ui/download.js +48 -0
  33. package/src/utils/BaseCommand.js +34 -0
  34. package/src/utils/SessionCommand.js +46 -0
  35. package/src/utils/api.js +164 -0
  36. package/src/utils/audit.js +114 -0
  37. package/src/utils/console.js +16 -0
  38. package/src/utils/errors.js +90 -0
  39. package/src/utils/exercisesQueue.js +45 -0
  40. package/src/utils/fileQueue.js +194 -0
  41. package/src/utils/misc.js +26 -0
  42. package/src/utils/templates/gitignore.txt +20 -0
  43. package/src/utils/templates/incremental/.learn/exercises/01-hello-world/README.es.md +26 -0
  44. package/src/utils/templates/incremental/.learn/exercises/01-hello-world/README.md +25 -0
  45. package/src/utils/templates/incremental/README.ejs +5 -0
  46. package/src/utils/templates/incremental/README.es.ejs +5 -0
  47. package/src/utils/templates/isolated/01-hello-world/README.es.md +27 -0
  48. package/src/utils/templates/isolated/01-hello-world/README.md +27 -0
  49. package/src/utils/templates/isolated/README.ejs +5 -0
  50. package/src/utils/templates/isolated/README.es.ejs +5 -0
  51. package/src/utils/templates/no-grading/README.ejs +5 -0
  52. package/src/utils/templates/no-grading/README.es.ejs +5 -0
  53. package/src/utils/validators.js +15 -0
  54. package/src/utils/watcher.js +24 -0
@@ -0,0 +1,62 @@
1
+ const express = require("express");
2
+ const Console = require("../../utils/console");
3
+ const cors = require("cors");
4
+ const shell = require("shelljs");
5
+ const addRoutes = require("./routes.js");
6
+ const cli = require("cli-ux").default;
7
+
8
+ module.exports = async function (
9
+ configObj,
10
+ configManager,
11
+ isTestingEnvironment = false
12
+ ) {
13
+ const { config } = configObj;
14
+ var app = express();
15
+ var server = require("http").Server(app);
16
+ app.use(cors());
17
+ // app.use(function(req, res, next) {
18
+ // res.header("Access-Control-Allow-Origin", "*")
19
+ // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
20
+ // res.header("Access-Control-Allow-Methods", "GET,PUT")
21
+ // next()
22
+ // })
23
+
24
+ // add all needed endpoints
25
+ await addRoutes(app, configObj, configManager);
26
+
27
+ server.listen(isTestingEnvironment ? 5000 : config.port, function () {
28
+ if (!isTestingEnvironment) {
29
+ Console.success(
30
+ `Exercises are running 😃 Open your browser to start practicing!`
31
+ );
32
+ Console.success(`\n Open the exercise on this link:`);
33
+ Console.log(` ${config.publicUrl}`);
34
+ if (config.editor.mode === "standalone") cli.open(`${config.publicUrl}`);
35
+ }
36
+ });
37
+
38
+ const sockets = new Set();
39
+
40
+ server.on("connection", (socket) => {
41
+ sockets.add(socket);
42
+
43
+ server.once("close", () => {
44
+ sockets.delete(socket);
45
+ });
46
+ });
47
+
48
+ /**
49
+ * Forcefully terminates HTTP server.
50
+ */
51
+ server.terminate = (callback) => {
52
+ for (const socket of sockets) {
53
+ socket.destroy();
54
+
55
+ sockets.delete(socket);
56
+ }
57
+
58
+ server.close(callback);
59
+ };
60
+
61
+ return server;
62
+ };
@@ -0,0 +1,151 @@
1
+ const Console = require('../../utils/console')
2
+ const express = require('express')
3
+ const fs = require('fs')
4
+ const bodyParser = require('body-parser')
5
+ const socket = require('../socket.js');
6
+ const queue = require("../../utils/fileQueue")
7
+ const { detect, filterFiles } = require("../config/exercise");
8
+
9
+ const withHandler = (func) => (req, res) => {
10
+ try{
11
+ func(req, res)
12
+ }
13
+ catch(err){
14
+ Console.debug(err)
15
+ const _err = {
16
+ message: err.message || 'There has been an error' ,
17
+ status: err.status || 500,
18
+ type: err.type || null
19
+ }
20
+ Console.error(_err.message)
21
+
22
+ //send rep to the server
23
+ res.status(_err.status)
24
+ res.json(_err)
25
+ }
26
+ }
27
+
28
+ module.exports = async function(app, configObject, configManager){
29
+
30
+ const { config } = configObject;
31
+
32
+ // Dispatcher will communicate events to 3rd party apps that
33
+ // subscribe to the queue, you can read documentation about this queue here:
34
+ // https://github.com/alesanchezr/text-queue/blob/main/README.md
35
+ const dispatcher = queue.dispatcher({ create: true, path: `${config.dirPath}/vscode_queue.json` })
36
+
37
+ app.get('/config', withHandler((req, res)=>{
38
+ res.json(configObject)
39
+ }))
40
+
41
+ /**
42
+ * TODO: replicate a socket action, the request payload must be passed to the socket as well
43
+ */
44
+ const jsonBodyParser = bodyParser.json()
45
+ app.post('/socket/:actionName', jsonBodyParser, withHandler((req, res)=>{
46
+ if(socket[req.params.actionName] instanceof Function){
47
+ socket[req.params.actionName](req.body ? req.body.data : null)
48
+ res.json({ "details": "Socket call executed sucessfully"})
49
+ }else res.status(400).json({ "details": `Socket action ${req.params.actionName} not found`})
50
+ }))
51
+
52
+ //symbolic link to maintain path compatiblity
53
+ const fetchStaticAsset = withHandler((req, res) => {
54
+ let filePath = `${config.dirPath}/assets/${req.params.filePath}`
55
+ if (!fs.existsSync(filePath)) throw Error('File not found: '+filePath)
56
+ const content = fs.readFileSync(filePath)
57
+ res.write(content);
58
+ res.end();
59
+ })
60
+ app.get(`${config.dirPath.indexOf("./") === 0 ? config.dirPath.substring(1) : config.dirPath}/assets/:filePath`, fetchStaticAsset);
61
+ app.get('/assets/:filePath', fetchStaticAsset);
62
+
63
+ app.get('/exercise', withHandler((req, res) => {
64
+ res.json(configObject.exercises)
65
+ }))
66
+
67
+ app.get('/exercise/:slug/readme', withHandler((req, res) => {
68
+ const readme = configManager.getExercise(req.params.slug).getReadme(req.query.lang || null)
69
+ res.json(readme)
70
+ }))
71
+
72
+ app.get('/exercise/:slug/report', withHandler((req, res) => {
73
+ const report = configManager.getExercise(req.params.slug).getTestReport()
74
+ res.json(JSON.stringify(report))
75
+ }))
76
+
77
+ app.get('/exercise/:slug', withHandler((req, res) => {
78
+
79
+ // no need to re-start exercise if it's already started
80
+ if(configObject.currentExercise && req.params.slug === configObject.currentExercise){
81
+ let exercise = configManager.getExercise(req.params.slug)
82
+ res.json(exercise)
83
+ return;
84
+ }
85
+
86
+ let exercise = configManager.startExercise(req.params.slug)
87
+ dispatcher.enqueue(dispatcher.events.START_EXERCISE, req.params.slug)
88
+
89
+ const entries = Object.keys(config.entries).map(lang => config.entries[lang]);
90
+
91
+ // if we are in incremental grading, the entry file can by dinamically detected
92
+ // based on the changes the student is making during the exercise
93
+ if(config.grading === "incremental"){
94
+ const scanedFiles = fs.readdirSync(`./`);
95
+
96
+ // update the file hierarchy with updates
97
+ exercise.files = exercise.files.filter(f => f.name.includes("test.")).concat(filterFiles(scanedFiles))
98
+ Console.debug(`Exercise updated files: `, exercise.files)
99
+
100
+ }
101
+ // detect lang
102
+ const detected = detect(configObject, exercise.files.filter(fileName => entries.includes(fileName.name || fileName)).map(f => f.name || f));
103
+
104
+ //if a new language for the testing engine is detected, we replace it
105
+ // if not we leave it as it was before
106
+ if(configObject.language && !["", "auto"].includes(configObject.language)){
107
+ Console.debug(`Exercise language ignored, instead imported from configuration ${configObject.language}`)
108
+ exercise.language = detected.language;
109
+ }
110
+ else if(detected.language && (!configObject.language || configObject.language === "auto")){
111
+ Console.debug(`Switching to ${detected.language} engine in this exercise`)
112
+ exercise.language = detected.language;
113
+ }
114
+
115
+ // WARNING: has to be the FULL PATH to the entry path
116
+ // We need to detect entry in both gradings: Incremental and Isolate
117
+ exercise.entry = detected.entry;
118
+ Console.debug(`Exercise detected entry: ${detected.entry} and language ${exercise.language}`)
119
+
120
+ if(!exercise.graded || config.disableGrading || config.disabledActions.includes("test")) socket.removeAllowed("test")
121
+ else socket.addAllowed('test')
122
+
123
+ if(!exercise.entry || config.disabledActions.includes("build")){
124
+ socket.removeAllowed("build")
125
+ Console.debug(`No entry was found for this exercise ${req.params.slug}, looking for the following entries from the config: `, config.entries)
126
+ }
127
+ else socket.addAllowed('build')
128
+
129
+ if(exercise.files.filter(f => !f.name.toLowerCase().includes("readme.") && !f.name.toLowerCase().includes("test.")).length === 0) socket.removeAllowed("reset")
130
+ else if(!config.disabledActions.includes("reset")) socket.addAllowed('reset')
131
+
132
+ socket.log('ready')
133
+
134
+ res.json(exercise)
135
+ }))
136
+
137
+ app.get('/exercise/:slug/file/:fileName', withHandler((req, res) => {
138
+ res.write(configManager.getExercise(req.params.slug).getFile(req.params.fileName))
139
+ res.end()
140
+ }))
141
+
142
+ const textBodyParser = bodyParser.text()
143
+ app.put('/exercise/:slug/file/:fileName', textBodyParser, withHandler((req, res) => {
144
+ const result = configManager.getExercise(req.params.slug).saveFile(req.params.fileName, req.body)
145
+ res.end()
146
+ }))
147
+
148
+ if(config.outputPath) app.use('/preview', express.static(config.outputPath))
149
+
150
+ app.use('/',express.static(config.dirPath+'/_app'))
151
+ }
@@ -0,0 +1,83 @@
1
+ const Console = require('../utils/console');
2
+ const api = require('../utils/api');
3
+
4
+ const v = require('validator');
5
+ const { ValidationError, InternalError } = require('../utils/errors');
6
+ const moment = require('moment');
7
+ const fs = require('fs');
8
+ const cli = require("cli-ux").default
9
+ const storage = require('node-persist');
10
+
11
+ module.exports = {
12
+ sessionStarted: false,
13
+ token: null,
14
+ config: null,
15
+ currentCohort: null,
16
+ initialize: async function(){
17
+ if(!this.sessionStarted){
18
+
19
+ if(!this.config) throw InternalError('Configuration not found')
20
+ if(!fs.existsSync(this.config.dirPath)) fs.mkdirSync(this.config.dirPath)
21
+ await storage.init({ dir: `${this.config.dirPath}/.session` });
22
+ this.sessionStarted = true;
23
+ }
24
+ return true
25
+ },
26
+ setPayload: async function(value){
27
+ await this.initialize();
28
+ await storage.setItem('bc-payload', { token: this.token, ...value });
29
+ Console.debug("Payload successfuly found and set for "+value.email);
30
+ return true;
31
+ },
32
+ getPayload: async function(){
33
+ await this.initialize();
34
+ let payload = null;
35
+ try{
36
+ payload = await storage.getItem('bc-payload');
37
+ }
38
+ catch(err){
39
+ Console.debug("Error retriving session payload");
40
+ }
41
+ return payload;
42
+ },
43
+ isActive: function(){
44
+ if(this.token) return true;
45
+ else return false;
46
+ },
47
+ get: async function(configObj=null){
48
+ if(configObj) this.config = configObj.config;
49
+
50
+ await this.sync();
51
+ if(!this.isActive()) return null;
52
+
53
+ const payload = await this.getPayload();
54
+ return {
55
+ payload, token: this.token,
56
+ };
57
+ },
58
+ login: async function(){
59
+
60
+ var email = await cli.prompt('What is your email?')
61
+ if(!v.isEmail(email)) throw ValidationError('Invalid email');
62
+
63
+ var password = await cli.prompt('What is your password?', {type: 'hide'})
64
+
65
+ const data = await api.login(email, password);
66
+ if(data) this.start({ token: data.token, payload: data });
67
+
68
+ },
69
+ sync: async function(){
70
+ const payload = await this.getPayload();
71
+ if(payload) this.token = payload.token;
72
+ },
73
+ start: async function({ token, payload=null }){
74
+ if(!token) throw new Error("A token and email is needed to start a session");
75
+ this.token = token;
76
+ if(payload) if(await this.setPayload(payload)) Console.success(`Successfully logged in as ${payload.email}`);
77
+ },
78
+ destroy: async function(){
79
+ await storage.clear();
80
+ this.token = null;
81
+ Console.success('You have logged out');
82
+ }
83
+ };
@@ -0,0 +1,185 @@
1
+ let connect = require("socket.io");
2
+ let Console = require("../utils/console");
3
+ const queue = require("../utils/fileQueue");
4
+
5
+ module.exports = {
6
+ socket: null,
7
+ config: null,
8
+ allowedActions: null,
9
+ isTestingEnvironment: false,
10
+ actionCallBacks: {
11
+ clean: (data, s) => {
12
+ s.logs = [];
13
+ },
14
+ },
15
+ addAllowed: function (actions) {
16
+ if (!Array.isArray(actions)) actions = [actions];
17
+
18
+ //avoid adding the "test" action if grading is disabled
19
+ if (actions.includes("test") && this.config.disable_grading)
20
+ actions = actions.filter((a) => a != "test");
21
+
22
+ //remove duplicates
23
+ this.allowedActions = this.allowedActions
24
+ .filter((a) => !actions.includes(a))
25
+ .concat(actions);
26
+ },
27
+ removeAllowed: function (actions) {
28
+ if (!Array.isArray(actions)) actions = [actions];
29
+ this.allowedActions = this.allowedActions.filter(
30
+ (a) => !actions.includes(a)
31
+ );
32
+ },
33
+ start: function (config, server, isTestingEnvironment = false) {
34
+ this.config = config;
35
+ this.isTestingEnvironment = isTestingEnvironment;
36
+
37
+ // remove test action if grading is disabled
38
+ this.allowedActions = config.actions.filter((act) =>
39
+ config.disable_grading ? act !== "test" : true
40
+ );
41
+
42
+ this.socket = connect(server);
43
+ this.socket.on("connection", (socket) => {
44
+ Console.debug(
45
+ "Connection with client successfully established",
46
+ this.allowedActions
47
+ );
48
+
49
+ if (!this.isTestingEnvironment) {
50
+ this.log("ready", ["Ready to compile or test..."]);
51
+ }
52
+
53
+ socket.on("compiler", ({ action, data }) => {
54
+ this.emit("clean", "pending", ["Working..."]);
55
+
56
+ if (typeof data.exerciseSlug == "undefined") {
57
+ this.log("internal-error", ["No exercise slug specified"]);
58
+ Console.error("No exercise slug especified");
59
+ return;
60
+ }
61
+
62
+ if (typeof this.actionCallBacks[action] == "function")
63
+ this.actionCallBacks[action](data);
64
+ else this.log("internal-error", ["Uknown action " + action]);
65
+ });
66
+ });
67
+ },
68
+ on: function (action, callBack) {
69
+ this.actionCallBacks[action] = callBack;
70
+ },
71
+ clean: function (status = "pending", logs = []) {
72
+ this.emit("clean", "pending", logs);
73
+ },
74
+ ask: function (questions = []) {
75
+ return new Promise((resolve, reject) => {
76
+ this.emit("ask", "pending", ["Waiting for input..."], questions);
77
+ this.on("input", ({ inputs }) => {
78
+ // Workaround to fix issue because null inputs
79
+ let isNull = false;
80
+ inputs.forEach((input) => {
81
+ if (input === null) {
82
+ isNull = true;
83
+ }
84
+ });
85
+
86
+ if (!isNull) {
87
+ resolve(inputs);
88
+ }
89
+ });
90
+ });
91
+ },
92
+ reload: function (files = null, exercises = null) {
93
+ this.emit("reload", files, exercises);
94
+ },
95
+ openWindow: function (url = "") {
96
+ queue.dispatcher().enqueue(queue.events.OPEN_WINDOW, url);
97
+ this.emit(
98
+ queue.events.OPEN_WINDOW,
99
+ (status = "ready"),
100
+ (logs = [`Opening ${url}`]),
101
+ (inputs = []),
102
+ (report = []),
103
+ (data = url)
104
+ );
105
+ },
106
+ log: function (status, messages = [], report = [], data = null) {
107
+ this.emit("log", status, messages, [], report, data);
108
+ Console.log(messages);
109
+ },
110
+ emit: function (
111
+ action,
112
+ status = "ready",
113
+ logs = [],
114
+ inputs = [],
115
+ report = [],
116
+ data = null
117
+ ) {
118
+ if (
119
+ ["webpack", "vanillajs", "vue", "react", "css", "html"].includes(
120
+ this.config.compiler
121
+ )
122
+ ) {
123
+ if (["compiler-success", "compiler-warning"].includes(status))
124
+ this.addAllowed("preview");
125
+ if (["compiler-error"].includes(status) || action == "ready")
126
+ this.removeAllowed("preview");
127
+ }
128
+
129
+ if (this.config.grading === "incremental") {
130
+ this.removeAllowed("reset");
131
+ }
132
+
133
+ Console.debug("dactions", this.config)
134
+ this.config.disabledActions.forEach(a => this.removeAllowed(a))
135
+
136
+ this.socket.emit("compiler", {
137
+ action,
138
+ status,
139
+ logs,
140
+ allowed: this.allowedActions,
141
+ inputs,
142
+ report,
143
+ data,
144
+ });
145
+ },
146
+
147
+ ready: function (message) {
148
+ this.log("ready", [message]);
149
+ },
150
+ success: function (type, stdout = "") {
151
+ const types = ["compiler", "testing"];
152
+ if (!types.includes(type))
153
+ this.fatal(`Invalid socket success type "${type}" on socket`);
154
+ else {
155
+ if (stdout === "")
156
+ this.log(type + "-success", ["No stdout to display on the console"]);
157
+ else this.log(type + "-success", [stdout]);
158
+ }
159
+
160
+ if (this.isTestingEnvironment) {
161
+ this.onTestingFinised({
162
+ result: "success",
163
+ });
164
+ }
165
+ },
166
+ error: function (type, stdout) {
167
+ console.error("Socket error: " + type, stdout);
168
+ this.log(type, [stdout]);
169
+
170
+ if (this.isTestingEnvironment) {
171
+ this.onTestingFinised({
172
+ result: "failed",
173
+ });
174
+ }
175
+ },
176
+ fatal: function (msg) {
177
+ this.log("internal-error", [msg]);
178
+ throw msg;
179
+ },
180
+ onTestingFinised: function (result) {
181
+ if (this.config.testingFinishedCallback) {
182
+ this.config.testingFinishedCallback(result);
183
+ }
184
+ },
185
+ };
@@ -0,0 +1,77 @@
1
+ const path = require('path');
2
+ let shell = require('shelljs');
3
+ const fs = require('fs');
4
+ let { TestingError } = require('./errors');
5
+ let Console = require('../utils/console');
6
+ const color = require('colors');
7
+ const bcActivity = require('./bcActivity.js');
8
+
9
+ module.exports = async function({ socket, files, config, slug }){
10
+
11
+ const configPath = path.resolve(__dirname,`./config/tester/${config.tester}/${config.language}.config.js`);
12
+ if (!fs.existsSync(configPath)) throw CompilerError(`Uknown testing engine for compiler: '${config.language}'`);
13
+
14
+ const testingConfig = require(configPath)(files, config, slug);
15
+ testingConfig.validate();
16
+
17
+ if(config.ignoreTests) throw TestingError('Grading is disabled on learn.json file.');
18
+
19
+ if (!fs.existsSync(`${config.dirPath}/reports`)){
20
+ fs.mkdirSync(`${config.dirPath}/reports`);
21
+ Console.debug(`Creating the ${config.dirPath}/reports directory`);
22
+ }
23
+
24
+ Console.info('Running tests...');
25
+
26
+ const command = await testingConfig.getCommand(socket)
27
+ const { stdout, stderr, code } = shell.exec(command);
28
+
29
+ if(code != 0){
30
+ const errors = typeof(testingConfig.getErrors === 'function') ? testingConfig.getErrors(stdout || stderr) : [];
31
+ socket.log('testing-error', errors);
32
+ console.log(errors.join('\n'))
33
+
34
+ Console.error("There was an error while testing");
35
+ bcActivity.error('exercise_error', {
36
+ message: errors,
37
+ name: `${config.tester}-error`,
38
+ framework: config.tester,
39
+ language: config.language,
40
+ data: slug,
41
+ compiler: config.compiler
42
+ });
43
+ }
44
+ else{
45
+ socket.log('testing-success',[ stdout || stderr ].concat(["😁Everything is amazing!"]));
46
+ Console.success("Everything is amazing!");
47
+
48
+
49
+ bcActivity.activity('exercise_success', {
50
+ language: config.language,
51
+ slug: slug,
52
+ editor: config.editor,
53
+ compiler: config.compiler
54
+ });
55
+ config.exercises = config.exercises.map(e => {
56
+ if(e.slug === slug) e.done = true;
57
+ return e;
58
+ });
59
+ }
60
+
61
+
62
+ if(typeof testingConfig.cleanup !== "undefined"){
63
+ if(typeof testingConfig.cleanup === 'function' || typeof testingConfig.cleanup === 'object'){
64
+ const clean = await testingConfig.cleanup(socket);
65
+ if(clean){
66
+ const { stdout, stderr, code } = shell.exec(clean);
67
+ if(code == 0){
68
+ Console.debug("The cleanup command runned successfully");
69
+ }
70
+ else Console.warning("There is an error on the cleanup command for the test");
71
+ }
72
+
73
+ }
74
+ }
75
+
76
+ return true;
77
+ };
@@ -0,0 +1,48 @@
1
+ const { prompt } = require("enquirer")
2
+ const Console = require('../utils/console')
3
+ const api = require('../utils/api')
4
+ const fetch = require('node-fetch')
5
+
6
+ const askPackage = () => new Promise(async (resolve, reject) => {
7
+ Console.info(`No package was specified`)
8
+ const languages = await api.getLangs()
9
+ if(languages.length === 0){
10
+ reject(new Error("No categories available"))
11
+ return null;
12
+ }
13
+ let packages = []
14
+ prompt([{
15
+ type: 'select',
16
+ name: 'lang',
17
+ message: 'What language do you want to practice?',
18
+ choices: languages.map(l => ({ message: l.title, name: l.slug })),
19
+ }])
20
+ .then(({ lang }) => {
21
+ return (async() => {
22
+ const response = await api.getAllPackages({ lang })
23
+ const packages = response.results
24
+ if(packages.length === 0){
25
+ const error = new Error(`No packages found for language ${lang}`)
26
+ Console.error(error)
27
+ return error
28
+ }
29
+ return await prompt([{
30
+ type: 'select',
31
+ name: 'pack',
32
+ message: 'Choose one of the packages available',
33
+ choices: packages.map(l => ({
34
+ message: `${l.title}, difficulty: ${l.difficulty}, downloads: ${l.downloads} ${l.skills.length > 0 ? `(Skills: ${l.skills.join(",")})` : ""}`,
35
+ value: l
36
+ })),
37
+ }])
38
+ })()
39
+ })
40
+ .then(resp => {
41
+ if(!resp) reject(resp.message || resp)
42
+ else resolve(resp)
43
+ })
44
+ .catch(error => {
45
+ Console.error(error.message || error)
46
+ })
47
+ })
48
+ module.exports = { askPackage }
@@ -0,0 +1,34 @@
1
+ const {Command, flags} = require('@oclif/command')
2
+ const Console = require('./console')
3
+ const SessionManager = require('../managers/session.js')
4
+
5
+
6
+ class BaseCommand extends Command {
7
+ constructor(...params){
8
+ super(...params)
9
+ }
10
+ async catch(err) {
11
+ Console.debug("COMMAND CATCH", err)
12
+
13
+ throw err
14
+ }
15
+ async init() {
16
+ const {flags, args} = this.parse(BaseCommand)
17
+ Console.debug("COMMAND INIT")
18
+ Console.debug("These are your flags: ",flags);
19
+ Console.debug("These are your args: ",args);
20
+
21
+ // quick fix for listening to the process termination on windows
22
+ process.on('SIGINT', function() {
23
+ Console.debug("Terminated (SIGINT)")
24
+ process.exit();
25
+ });
26
+
27
+ }
28
+ async finally() {
29
+ Console.debug("COMMAND FINALLY")
30
+ // called after run and catch regardless of whether or not the command errored
31
+ }
32
+ }
33
+
34
+ module.exports = BaseCommand
@@ -0,0 +1,46 @@
1
+ const {flags} = require('@oclif/command')
2
+ const BaseCommand = require("./BaseCommand")
3
+ const Console = require('./console')
4
+ const SessionManager = require('../managers/session.js')
5
+ const ConfigManager = require('../managers/config/index.js')
6
+ const { AuthError } = require('./errors.js')
7
+
8
+ class SessionCommand extends BaseCommand {
9
+ constructor(...args){
10
+ super(...args)
11
+ this.configManager = null
12
+ this.session = null
13
+ }
14
+
15
+ async initSession(flags, _private){
16
+ try{
17
+ if(!this.configManager) await this.buildConfig(flags)
18
+
19
+ this.session = await SessionManager.get(this.configManager.get())
20
+ if(this.session) Console.debug(`Session open for ${this.session.payload.email}.`)
21
+ else{
22
+ if(_private) throw AuthError("You need to log in, run the following command to continue: $ learnpack login");
23
+ Console.debug("No active session available", _private)
24
+ }
25
+ }
26
+ catch(error){
27
+ Console.error(error.message)
28
+ }
29
+ }
30
+ async buildConfig(flags){
31
+ Console.debug("Building configuration for the first time")
32
+ Console.debug("Flags", flags)
33
+ this.configManager = await ConfigManager(flags)
34
+ }
35
+ async catch(err) {
36
+ Console.debug("COMMAND CATCH", err)
37
+ throw err
38
+ }
39
+ }
40
+
41
+ // SessionCommand.description = `Describe the command here
42
+ // ...
43
+ // Extra documentation goes here
44
+ // `
45
+
46
+ module.exports = SessionCommand