@learnpack/learnpack 2.0.2 → 2.0.5

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,198 +1,198 @@
1
- import logger from "../utils/console";
2
- import * as fs from "fs";
3
- // import em from "events"
4
- import * as XXH from "xxhashjs";
5
-
6
- // possible events to dispatch
7
- const events = {
8
- START_EXERCISE: "start_exercise",
9
- INIT: "initializing",
10
- RUNNING: "configuration_loaded",
11
- END: "connection_ended",
12
- RESET_EXERCISE: "reset_exercise",
13
- OPEN_FILES: "open_files",
14
- OPEN_WINDOW: "open_window",
15
- INSTRUCTIONS_CLOSED: "instructions_closed",
16
- };
17
-
18
- let options = {
19
- path: null,
20
- create: false,
21
- };
22
- let lastHash: any = null;
23
- let watcher: any = null; // subscribe to file and listen to changes
24
- let actions: any = null; // action queue
25
-
26
- const loadDispatcher = (opts: any) => {
27
- actions = [{ name: "initializing", time: now() }];
28
- logger.debug(`Loading from ${opts.path}`);
29
-
30
- let exists = fs.existsSync(opts.path);
31
- if (opts.create) {
32
- if (exists)
33
- actions.push({ name: "reset", time: now() });
34
- fs.writeFileSync(opts.path, JSON.stringify(actions), { flag: "w" });
35
- exists = true;
36
- }
37
-
38
- if (!exists)
39
- throw new Error(`Invalid queue path, missing file at: ${opts.path}`);
40
-
41
- let incomingActions = [];
42
- try {
43
- const content = fs.readFileSync(opts.path, "utf-8");
44
- incomingActions = JSON.parse(content);
45
- if (!Array.isArray(incomingActions))
46
- incomingActions = [];
47
- } catch {
48
- incomingActions = [];
49
- logger.debug("Error loading VSCode Actions file");
50
- }
51
-
52
- logger.debug("Actions load ", incomingActions);
53
- return incomingActions;
54
- };
55
-
56
- // eslint-disable-next-line
57
- const enqueue = (name: string, data: any | undefined = undefined) => {
58
- if (!Object.values(events).includes(name)) {
59
- logger.debug(`Invalid event ${name}`);
60
- throw new Error(`Invalid action ${name}`);
61
- }
62
-
63
- if (!actions)
64
- actions = [];
65
-
66
- actions.push({ name, time: now(), data: data });
67
- logger.debug(`EMIT -> ${name}:Exporting changes to ${options.path}`);
68
-
69
- return fs.writeFileSync(options.path || "", JSON.stringify(actions));
70
- };
71
-
72
- const now = () => {
73
- const hrTime = process.hrtime();
74
- // eslint-disable-next-line
75
- const htTime0 = hrTime[0] * 1000000;
76
- return (htTime0 + hrTime[1]) / 1000;
77
- };
78
-
79
- const loadFile = (filePath: string) => {
80
- if (!fs.existsSync(filePath))
81
- throw new Error(`No queue.json file to load on ${filePath}`);
82
-
83
- const content = fs.readFileSync(filePath, "utf8");
84
- const newHash = XXH.h32(content, 0xAB_CD).toString(16);
85
- const isUpdated = lastHash !== newHash;
86
- lastHash = newHash;
87
- const incomingActions = JSON.parse(content);
88
- return { isUpdated, incomingActions };
89
- };
90
-
91
- const dequeue = () => {
92
- // first time dequeue loads
93
- if (!actions)
94
- actions = [];
95
-
96
- const { isUpdated, incomingActions } = loadFile(options.path || "");
97
-
98
- if (!isUpdated) {
99
- /**
100
- * make sure no tasks are executed from the queue by matching both
101
- * queues (the incoming with current one)
102
- */
103
- actions = incomingActions;
104
- logger.debug(
105
- `No new actions to process: ${actions.length}/${incomingActions.length}`
106
- );
107
- return null;
108
- }
109
-
110
- // do i need to reset actions to zero?
111
- if (actions.length > 0 && actions[0].time !== incomingActions[0].time) {
112
- actions = [];
113
- }
114
-
115
- const action = incomingActions[incomingActions.length - 1];
116
- logger.debug("Dequeing action ", action);
117
- actions.push(action);
118
- return action;
119
- };
120
-
121
- const pull = (callback: (T: any) => any) => {
122
- logger.debug("Pulling actions");
123
- let incoming = dequeue();
124
- while (incoming) {
125
- callback(incoming);
126
- incoming = dequeue();
127
- }
128
- };
129
-
130
- const reset = (callback: (T?: any) => any) => {
131
- logger.debug("Queue reseted");
132
- actions = [];
133
- if (fs.existsSync(options.path || "")) {
134
- fs.writeFileSync(options.path || "", "[]");
135
- callback();
136
- }
137
- };
138
-
139
- const onPull = (callback: (T?: any) => any) => {
140
- // eslint-disable-next-line
141
- const chokidar = require("chokidar");
142
-
143
- logger.debug("Starting to listen...");
144
- try {
145
- loadFile(options.path || "");
146
- } catch {
147
- logger.debug("No previeues queue file, waiting for it to be created...");
148
- }
149
-
150
- if (!watcher) {
151
- logger.debug(`Watching ${options.path}`);
152
- watcher = chokidar.watch(`${options.path}`, {
153
- persistent: true,
154
- });
155
- } else
156
- logger.debug("Already watching queue path");
157
-
158
- watcher.on("add", () => pull(callback)).on("change", () => pull(callback));
159
-
160
- return true;
161
- };
162
-
163
- const onReset = (callback: (T?: any) => any) => {
164
- // eslint-disable-next-line
165
- const chokidar = require("chokidar");
166
-
167
- if (!watcher) {
168
- logger.debug(`Watching ${options.path}`);
169
- watcher = chokidar.watch(`${options.path}`, {
170
- persistent: true,
171
- });
172
- }
173
-
174
- watcher.on("unlink", () => reset(callback));
175
-
176
- return true;
177
- };
178
-
179
- export default {
180
- events,
181
- dispatcher: (opts: any = {}) => {
182
- if (!actions) {
183
- options = { ...options, ...opts };
184
- logger.debug("Initializing queue dispatcher", options);
185
- actions = loadDispatcher(options);
186
- }
187
-
188
- return { enqueue, events };
189
- },
190
- listener: (opts: any = {}) => {
191
- if (!actions) {
192
- options = { ...options, ...opts };
193
- logger.debug("Initializing queue listener", options);
194
- }
195
-
196
- return { onPull, onReset, events };
197
- },
198
- };
1
+ import logger from "../utils/console";
2
+ import * as fs from "fs";
3
+ // import em from "events"
4
+ import * as XXH from "xxhashjs";
5
+
6
+ // possible events to dispatch
7
+ const events = {
8
+ START_EXERCISE: "start_exercise",
9
+ INIT: "initializing",
10
+ RUNNING: "configuration_loaded",
11
+ END: "connection_ended",
12
+ RESET_EXERCISE: "reset_exercise",
13
+ OPEN_FILES: "open_files",
14
+ OPEN_WINDOW: "open_window",
15
+ INSTRUCTIONS_CLOSED: "instructions_closed",
16
+ };
17
+
18
+ let options = {
19
+ path: null,
20
+ create: false,
21
+ };
22
+ let lastHash: any = null;
23
+ let watcher: any = null; // subscribe to file and listen to changes
24
+ let actions: any = null; // action queue
25
+
26
+ const loadDispatcher = (opts: any) => {
27
+ actions = [{ name: "initializing", time: now() }];
28
+ logger.debug(`Loading from ${opts.path}`);
29
+
30
+ let exists = fs.existsSync(opts.path);
31
+ if (opts.create) {
32
+ if (exists)
33
+ actions.push({ name: "reset", time: now() });
34
+ fs.writeFileSync(opts.path, JSON.stringify(actions), { flag: "w" });
35
+ exists = true;
36
+ }
37
+
38
+ if (!exists)
39
+ throw new Error(`Invalid queue path, missing file at: ${opts.path}`);
40
+
41
+ let incomingActions = [];
42
+ try {
43
+ const content = fs.readFileSync(opts.path, "utf-8");
44
+ incomingActions = JSON.parse(content);
45
+ if (!Array.isArray(incomingActions))
46
+ incomingActions = [];
47
+ } catch {
48
+ incomingActions = [];
49
+ logger.debug("Error loading VSCode Actions file");
50
+ }
51
+
52
+ logger.debug("Actions load ", incomingActions);
53
+ return incomingActions;
54
+ };
55
+
56
+ // eslint-disable-next-line
57
+ const enqueue = (name: string, data: any | undefined = undefined) => {
58
+ if (!Object.values(events).includes(name)) {
59
+ logger.debug(`Invalid event ${name}`);
60
+ throw new Error(`Invalid action ${name}`);
61
+ }
62
+
63
+ if (!actions)
64
+ actions = [];
65
+
66
+ actions.push({ name, time: now(), data: data });
67
+ logger.debug(`EMIT -> ${name}:Exporting changes to ${options.path}`);
68
+
69
+ return fs.writeFileSync(options.path || "", JSON.stringify(actions));
70
+ };
71
+
72
+ const now = () => {
73
+ const hrTime = process.hrtime();
74
+ // eslint-disable-next-line
75
+ const htTime0 = hrTime[0] * 1000000;
76
+ return (htTime0 + hrTime[1]) / 1000;
77
+ };
78
+
79
+ const loadFile = (filePath: string) => {
80
+ if (!fs.existsSync(filePath))
81
+ throw new Error(`No queue.json file to load on ${filePath}`);
82
+
83
+ const content = fs.readFileSync(filePath, "utf8");
84
+ const newHash = XXH.h32(content, 0xAB_CD).toString(16);
85
+ const isUpdated = lastHash !== newHash;
86
+ lastHash = newHash;
87
+ const incomingActions = JSON.parse(content);
88
+ return { isUpdated, incomingActions };
89
+ };
90
+
91
+ const dequeue = () => {
92
+ // first time dequeue loads
93
+ if (!actions)
94
+ actions = [];
95
+
96
+ const { isUpdated, incomingActions } = loadFile(options.path || "");
97
+
98
+ if (!isUpdated) {
99
+ /**
100
+ * make sure no tasks are executed from the queue by matching both
101
+ * queues (the incoming with current one)
102
+ */
103
+ actions = incomingActions;
104
+ logger.debug(
105
+ `No new actions to process: ${actions.length}/${incomingActions.length}`
106
+ );
107
+ return null;
108
+ }
109
+
110
+ // do i need to reset actions to zero?
111
+ if (actions.length > 0 && actions[0].time !== incomingActions[0].time) {
112
+ actions = [];
113
+ }
114
+
115
+ const action = incomingActions[incomingActions.length - 1];
116
+ logger.debug("Dequeing action ", action);
117
+ actions.push(action);
118
+ return action;
119
+ };
120
+
121
+ const pull = (callback: (T: any) => any) => {
122
+ logger.debug("Pulling actions");
123
+ let incoming = dequeue();
124
+ while (incoming) {
125
+ callback(incoming);
126
+ incoming = dequeue();
127
+ }
128
+ };
129
+
130
+ const reset = (callback: (T?: any) => any) => {
131
+ logger.debug("Queue reseted");
132
+ actions = [];
133
+ if (fs.existsSync(options.path || "")) {
134
+ fs.writeFileSync(options.path || "", "[]");
135
+ callback();
136
+ }
137
+ };
138
+
139
+ const onPull = (callback: (T?: any) => any) => {
140
+ // eslint-disable-next-line
141
+ const chokidar = require("chokidar");
142
+
143
+ logger.debug("Starting to listen...");
144
+ try {
145
+ loadFile(options.path || "");
146
+ } catch {
147
+ logger.debug("No previeues queue file, waiting for it to be created...");
148
+ }
149
+
150
+ if (!watcher) {
151
+ logger.debug(`Watching ${options.path}`);
152
+ watcher = chokidar.watch(`${options.path}`, {
153
+ persistent: true,
154
+ });
155
+ } else
156
+ logger.debug("Already watching queue path");
157
+
158
+ watcher.on("add", () => pull(callback)).on("change", () => pull(callback));
159
+
160
+ return true;
161
+ };
162
+
163
+ const onReset = (callback: (T?: any) => any) => {
164
+ // eslint-disable-next-line
165
+ const chokidar = require("chokidar");
166
+
167
+ if (!watcher) {
168
+ logger.debug(`Watching ${options.path}`);
169
+ watcher = chokidar.watch(`${options.path}`, {
170
+ persistent: true,
171
+ });
172
+ }
173
+
174
+ watcher.on("unlink", () => reset(callback));
175
+
176
+ return true;
177
+ };
178
+
179
+ export default {
180
+ events,
181
+ dispatcher: (opts: any = {}) => {
182
+ if (!actions) {
183
+ options = { ...options, ...opts };
184
+ logger.debug("Initializing queue dispatcher", options);
185
+ actions = loadDispatcher(options);
186
+ }
187
+
188
+ return { enqueue, events };
189
+ },
190
+ listener: (opts: any = {}) => {
191
+ if (!actions) {
192
+ options = { ...options, ...opts };
193
+ logger.debug("Initializing queue listener", options);
194
+ }
195
+
196
+ return { onPull, onReset, events };
197
+ },
198
+ };