tering-serieuze-sdk 3.12.0 → 3.13.1
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.
- package/biome.json +2 -2
- package/dist/index.mjs +135 -131
- package/dist/index.mjs.map +3 -3
- package/package.json +3 -3
- package/src/api/auth.ts +1 -7
- package/src/api/jingle.ts +5 -5
- package/src/api/k8s.ts +1 -1
- package/src/api/user.ts +3 -3
- package/src/cache/filesystemCache.ts +39 -23
- package/src/cache/nullCache.ts +1 -1
- package/src/cache/onePasswordCache.ts +2 -2
- package/src/index.ts +7 -7
- package/test/api/jingle.test.ts +1 -1
- package/test/cache/nullCache.test.ts +1 -1
package/biome.json
CHANGED
|
@@ -31,10 +31,10 @@
|
|
|
31
31
|
"useReadonlyClassProperties": "error"
|
|
32
32
|
},
|
|
33
33
|
"performance": {
|
|
34
|
-
"noBarrelFile": "
|
|
34
|
+
"noBarrelFile": "off",
|
|
35
35
|
"noDelete": "error",
|
|
36
36
|
"noNamespaceImport": "error",
|
|
37
|
-
"noReExportAll": "
|
|
37
|
+
"noReExportAll": "off"
|
|
38
38
|
},
|
|
39
39
|
"style": {
|
|
40
40
|
"noCommonJs": "error",
|
package/dist/index.mjs
CHANGED
|
@@ -5,6 +5,79 @@ var __publicField = (obj, key, value) => {
|
|
|
5
5
|
return value;
|
|
6
6
|
};
|
|
7
7
|
|
|
8
|
+
// src/api/base.ts
|
|
9
|
+
var BaseModule = class {
|
|
10
|
+
constructor(api, cache) {
|
|
11
|
+
this.api = api;
|
|
12
|
+
this.cache = cache;
|
|
13
|
+
}
|
|
14
|
+
getCache() {
|
|
15
|
+
return this.cache;
|
|
16
|
+
}
|
|
17
|
+
setCache(cache) {
|
|
18
|
+
this.cache = cache;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// src/api/auth.ts
|
|
23
|
+
function parseJwt(token) {
|
|
24
|
+
let jsonPayload = "";
|
|
25
|
+
if (typeof Buffer !== "undefined") {
|
|
26
|
+
jsonPayload = Buffer.from(token.split(".")[1], "base64").toString();
|
|
27
|
+
} else {
|
|
28
|
+
const base64Url = token.split(".")[1];
|
|
29
|
+
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
|
|
30
|
+
jsonPayload = decodeURIComponent(
|
|
31
|
+
window.atob(base64).split("").map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2)).join("")
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
return JSON.parse(jsonPayload);
|
|
35
|
+
}
|
|
36
|
+
var _AuthModule = class extends BaseModule {
|
|
37
|
+
getToken() {
|
|
38
|
+
return process.env.TSS_TOKEN ? Promise.resolve(process.env.TSS_TOKEN) : this.cache.get(_AuthModule.cacheKey);
|
|
39
|
+
}
|
|
40
|
+
setToken(token, lifetime) {
|
|
41
|
+
return this.cache.set(_AuthModule.cacheKey, token, lifetime);
|
|
42
|
+
}
|
|
43
|
+
removeToken() {
|
|
44
|
+
return this.cache.remove(_AuthModule.cacheKey);
|
|
45
|
+
}
|
|
46
|
+
async getSessionId() {
|
|
47
|
+
const token = await this.getToken();
|
|
48
|
+
const { sessionId } = parseJwt(token ?? "");
|
|
49
|
+
return sessionId;
|
|
50
|
+
}
|
|
51
|
+
async removeSession(sessionId) {
|
|
52
|
+
const session = sessionId ?? await this.getSessionId();
|
|
53
|
+
await this.api.delete(`session/${session}`, { credentials: "include" });
|
|
54
|
+
}
|
|
55
|
+
async logout() {
|
|
56
|
+
await this.removeSession();
|
|
57
|
+
this.removeToken();
|
|
58
|
+
}
|
|
59
|
+
getRegistrationOptions(registrationToken) {
|
|
60
|
+
return this.api.get(`auth/registration-options/${registrationToken}`);
|
|
61
|
+
}
|
|
62
|
+
getAuthenticationOptions() {
|
|
63
|
+
return this.api.get("auth/authentication-options");
|
|
64
|
+
}
|
|
65
|
+
verifyRegistration(registrationToken, registrationResponse) {
|
|
66
|
+
return this.api.post(
|
|
67
|
+
`auth/verify-registration/${registrationToken}`,
|
|
68
|
+
registrationResponse,
|
|
69
|
+
{ credentials: "include" }
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
verifyAuthentication(token, response) {
|
|
73
|
+
return this.api.post(`auth/verify-authentication/${token}`, response, {
|
|
74
|
+
credentials: "include"
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
var AuthModule = _AuthModule;
|
|
79
|
+
__publicField(AuthModule, "cacheKey", "TSS-TOKEN");
|
|
80
|
+
|
|
8
81
|
// node_modules/stack-trace/index.js
|
|
9
82
|
function get(belowFn) {
|
|
10
83
|
const oldLimit = Error.stackTraceLimit;
|
|
@@ -81,14 +154,14 @@ var AbstractCache = class {
|
|
|
81
154
|
|
|
82
155
|
// src/cache/cookieCache.ts
|
|
83
156
|
var CookieCache = class extends AbstractCache {
|
|
84
|
-
cacheOrGet(
|
|
157
|
+
cacheOrGet() {
|
|
85
158
|
throw new Error("Not implemented, use get() and set()");
|
|
86
159
|
}
|
|
87
|
-
|
|
160
|
+
get(key) {
|
|
88
161
|
if (document.cookie.includes(`${key}=`)) {
|
|
89
|
-
return document.cookie.split(`${key}=`)[1]?.split(";")[0];
|
|
162
|
+
return Promise.resolve(document.cookie.split(`${key}=`)[1]?.split(";")[0]);
|
|
90
163
|
}
|
|
91
|
-
return void 0;
|
|
164
|
+
return Promise.resolve(void 0);
|
|
92
165
|
}
|
|
93
166
|
set(key, value, lifetime) {
|
|
94
167
|
const expires = lifetime ? new Date(Date.now() + lifetime).toUTCString() : "";
|
|
@@ -103,31 +176,34 @@ var CookieCache = class extends AbstractCache {
|
|
|
103
176
|
};
|
|
104
177
|
|
|
105
178
|
// src/cache/filesystemCache.ts
|
|
106
|
-
import fs from "fs";
|
|
107
|
-
import
|
|
108
|
-
import
|
|
179
|
+
import fs from "node:fs";
|
|
180
|
+
import os from "node:os";
|
|
181
|
+
import path from "node:path";
|
|
109
182
|
var FilesystemCache = class extends AbstractCache {
|
|
110
183
|
initialized = false;
|
|
111
|
-
state =
|
|
184
|
+
state = /* @__PURE__ */ new Map();
|
|
112
185
|
async cacheOrGet(callbackWhenEmpty, key, lifetime) {
|
|
113
|
-
|
|
114
|
-
const cachedValue = await this.get(
|
|
186
|
+
const usedKey = key ?? this.getCacheKey();
|
|
187
|
+
const cachedValue = await this.get(usedKey);
|
|
115
188
|
if (cachedValue) {
|
|
116
189
|
return cachedValue;
|
|
117
190
|
}
|
|
118
191
|
const result = await callbackWhenEmpty();
|
|
119
|
-
this.set(
|
|
192
|
+
this.set(usedKey, result, lifetime);
|
|
120
193
|
return result;
|
|
121
194
|
}
|
|
122
|
-
|
|
195
|
+
get(key) {
|
|
123
196
|
if (!this.initialized) {
|
|
124
|
-
|
|
197
|
+
this._initialize();
|
|
125
198
|
}
|
|
126
|
-
const
|
|
127
|
-
if (
|
|
128
|
-
|
|
199
|
+
const item = this.state.get(key);
|
|
200
|
+
if (item) {
|
|
201
|
+
const expires = item.expiresAt;
|
|
202
|
+
if (expires === void 0 || expires > Date.now()) {
|
|
203
|
+
return Promise.resolve(item.value);
|
|
204
|
+
}
|
|
129
205
|
}
|
|
130
|
-
return void 0;
|
|
206
|
+
return Promise.resolve(void 0);
|
|
131
207
|
}
|
|
132
208
|
set(key, value, lifetime) {
|
|
133
209
|
const expiresAt = lifetime ? Date.now() + lifetime : void 0;
|
|
@@ -135,15 +211,15 @@ var FilesystemCache = class extends AbstractCache {
|
|
|
135
211
|
if (expiresAt) {
|
|
136
212
|
content.expiresAt = expiresAt;
|
|
137
213
|
}
|
|
138
|
-
this.state
|
|
214
|
+
this.state.set(key, content);
|
|
139
215
|
this.writeState();
|
|
140
216
|
}
|
|
141
217
|
remove(key) {
|
|
142
|
-
|
|
218
|
+
this.state.delete(key);
|
|
143
219
|
this.writeState();
|
|
144
220
|
}
|
|
145
221
|
clear() {
|
|
146
|
-
this.state
|
|
222
|
+
this.state.clear();
|
|
147
223
|
if (fs.existsSync(this.getFilePath())) {
|
|
148
224
|
fs.unlinkSync(this.getFilePath());
|
|
149
225
|
}
|
|
@@ -154,39 +230,46 @@ var FilesystemCache = class extends AbstractCache {
|
|
|
154
230
|
_initialize() {
|
|
155
231
|
this.initialized = true;
|
|
156
232
|
if (fs.existsSync(this.getFilePath())) {
|
|
157
|
-
|
|
233
|
+
try {
|
|
234
|
+
const fileContent = fs.readFileSync(this.getFilePath(), "utf8");
|
|
235
|
+
const parsed = JSON.parse(fileContent);
|
|
236
|
+
this.state = new Map(Object.entries(parsed));
|
|
237
|
+
} catch (_e) {
|
|
238
|
+
this.state = /* @__PURE__ */ new Map();
|
|
239
|
+
}
|
|
158
240
|
}
|
|
159
241
|
}
|
|
160
242
|
writeState() {
|
|
161
243
|
if (!fs.existsSync(path.dirname(this.getFilePath()))) {
|
|
162
|
-
fs.mkdirSync(path.dirname(this.getFilePath()));
|
|
244
|
+
fs.mkdirSync(path.dirname(this.getFilePath()), { recursive: true });
|
|
163
245
|
}
|
|
164
|
-
|
|
246
|
+
const plainObject = Object.fromEntries(this.state);
|
|
247
|
+
fs.writeFileSync(this.getFilePath(), JSON.stringify(plainObject));
|
|
165
248
|
}
|
|
166
249
|
};
|
|
167
250
|
|
|
168
251
|
// src/cache/nullCache.ts
|
|
169
252
|
var NullCache = class extends AbstractCache {
|
|
170
|
-
cacheOrGet(callbackWhenEmpty
|
|
253
|
+
cacheOrGet(callbackWhenEmpty) {
|
|
171
254
|
return callbackWhenEmpty();
|
|
172
255
|
}
|
|
173
|
-
|
|
174
|
-
return void 0;
|
|
256
|
+
get() {
|
|
257
|
+
return Promise.resolve(void 0);
|
|
175
258
|
}
|
|
176
|
-
set(
|
|
259
|
+
set() {
|
|
177
260
|
}
|
|
178
|
-
remove(
|
|
261
|
+
remove() {
|
|
179
262
|
}
|
|
180
263
|
clear() {
|
|
181
264
|
}
|
|
182
265
|
};
|
|
183
266
|
|
|
184
267
|
// src/cache/onePasswordCache.ts
|
|
185
|
-
import
|
|
186
|
-
import
|
|
268
|
+
import child_process from "node:child_process";
|
|
269
|
+
import util from "node:util";
|
|
187
270
|
var OnePasswordCache = class extends AbstractCache {
|
|
188
271
|
asyncExec = util.promisify(child_process.exec);
|
|
189
|
-
cacheOrGet(
|
|
272
|
+
cacheOrGet() {
|
|
190
273
|
throw new Error("Not implemented, use get() and set()");
|
|
191
274
|
}
|
|
192
275
|
async get(key) {
|
|
@@ -197,14 +280,14 @@ var OnePasswordCache = class extends AbstractCache {
|
|
|
197
280
|
}
|
|
198
281
|
return JSON.parse(stdout).value;
|
|
199
282
|
}
|
|
200
|
-
async set(key, value
|
|
283
|
+
async set(key, value) {
|
|
201
284
|
let action = `op item edit '${key}' 'credential=${value}'`;
|
|
202
285
|
try {
|
|
203
|
-
|
|
204
|
-
} catch (
|
|
286
|
+
await this.get(key);
|
|
287
|
+
} catch (_e) {
|
|
205
288
|
action = `op item create --category="API Credential" --title ${key} 'credential=${value}'`;
|
|
206
289
|
}
|
|
207
|
-
const {
|
|
290
|
+
const { stderr } = await this.asyncExec(action);
|
|
208
291
|
if (stderr) {
|
|
209
292
|
console.log(stderr);
|
|
210
293
|
throw new Error("ERROR");
|
|
@@ -217,88 +300,9 @@ var OnePasswordCache = class extends AbstractCache {
|
|
|
217
300
|
}
|
|
218
301
|
};
|
|
219
302
|
|
|
220
|
-
// src/api/base.ts
|
|
221
|
-
var BaseModule = class {
|
|
222
|
-
constructor(api, cache) {
|
|
223
|
-
this.api = api;
|
|
224
|
-
this.cache = cache;
|
|
225
|
-
}
|
|
226
|
-
getCache() {
|
|
227
|
-
return this.cache;
|
|
228
|
-
}
|
|
229
|
-
setCache(cache) {
|
|
230
|
-
this.cache = cache;
|
|
231
|
-
}
|
|
232
|
-
};
|
|
233
|
-
|
|
234
|
-
// src/api/auth.ts
|
|
235
|
-
function parseJwt(token) {
|
|
236
|
-
let jsonPayload;
|
|
237
|
-
if (typeof Buffer !== "undefined") {
|
|
238
|
-
jsonPayload = Buffer.from(token.split(".")[1], "base64").toString();
|
|
239
|
-
} else {
|
|
240
|
-
const base64Url = token.split(".")[1];
|
|
241
|
-
const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
|
|
242
|
-
jsonPayload = decodeURIComponent(
|
|
243
|
-
window.atob(base64).split("").map(function(c) {
|
|
244
|
-
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
|
|
245
|
-
}).join("")
|
|
246
|
-
);
|
|
247
|
-
}
|
|
248
|
-
return JSON.parse(jsonPayload);
|
|
249
|
-
}
|
|
250
|
-
var _AuthModule = class extends BaseModule {
|
|
251
|
-
async getToken() {
|
|
252
|
-
return process.env.TSS_TOKEN ?? this.cache.get(_AuthModule.cacheKey);
|
|
253
|
-
}
|
|
254
|
-
async setToken(token, lifetime) {
|
|
255
|
-
return this.cache.set(_AuthModule.cacheKey, token, lifetime);
|
|
256
|
-
}
|
|
257
|
-
async setCode(code) {
|
|
258
|
-
const { accessToken } = await this.api.post(`auth/setCode?code=${code}`, {}, { credentials: "include" });
|
|
259
|
-
return accessToken;
|
|
260
|
-
}
|
|
261
|
-
async removeToken() {
|
|
262
|
-
return this.cache.remove(_AuthModule.cacheKey);
|
|
263
|
-
}
|
|
264
|
-
async getSessionId() {
|
|
265
|
-
const token = await this.getToken();
|
|
266
|
-
const { sessionId } = parseJwt(token ?? "");
|
|
267
|
-
return sessionId;
|
|
268
|
-
}
|
|
269
|
-
async removeSession(sessionId) {
|
|
270
|
-
const session = sessionId ?? await this.getSessionId();
|
|
271
|
-
await this.api.delete(`session/${session}`, { credentials: "include" });
|
|
272
|
-
}
|
|
273
|
-
async logout() {
|
|
274
|
-
await this.removeSession();
|
|
275
|
-
await this.removeToken();
|
|
276
|
-
}
|
|
277
|
-
async getRegistrationOptions(registrationToken) {
|
|
278
|
-
return this.api.get(`auth/registration-options/${registrationToken}`);
|
|
279
|
-
}
|
|
280
|
-
async getAuthenticationOptions() {
|
|
281
|
-
return this.api.get("auth/authentication-options");
|
|
282
|
-
}
|
|
283
|
-
async verifyRegistration(registrationToken, registrationResponse) {
|
|
284
|
-
return this.api.post(
|
|
285
|
-
`auth/verify-registration/${registrationToken}`,
|
|
286
|
-
registrationResponse,
|
|
287
|
-
{ credentials: "include" }
|
|
288
|
-
);
|
|
289
|
-
}
|
|
290
|
-
async verifyAuthentication(token, response) {
|
|
291
|
-
return this.api.post(`auth/verify-authentication/${token}`, response, {
|
|
292
|
-
credentials: "include"
|
|
293
|
-
});
|
|
294
|
-
}
|
|
295
|
-
};
|
|
296
|
-
var AuthModule = _AuthModule;
|
|
297
|
-
__publicField(AuthModule, "cacheKey", "TSS-TOKEN");
|
|
298
|
-
|
|
299
303
|
// src/api/jingle.ts
|
|
300
304
|
var JingleModule = class extends BaseModule {
|
|
301
|
-
|
|
305
|
+
getGrouped() {
|
|
302
306
|
return this.cache.cacheOrGet(
|
|
303
307
|
() => {
|
|
304
308
|
return this.api.get("jingle/grouped");
|
|
@@ -307,7 +311,7 @@ var JingleModule = class extends BaseModule {
|
|
|
307
311
|
864e5 /* Day */
|
|
308
312
|
);
|
|
309
313
|
}
|
|
310
|
-
|
|
314
|
+
getAll() {
|
|
311
315
|
return this.cache.cacheOrGet(
|
|
312
316
|
() => {
|
|
313
317
|
return this.api.get("jingle");
|
|
@@ -320,18 +324,18 @@ var JingleModule = class extends BaseModule {
|
|
|
320
324
|
const jingles = await this.getAll();
|
|
321
325
|
return jingles.sort((a, b) => b.mtime - a.mtime).slice(0, 30);
|
|
322
326
|
}
|
|
323
|
-
|
|
327
|
+
play(playJingleDto) {
|
|
324
328
|
console.log(`Playing jingle ${playJingleDto.folder}/${playJingleDto.file}`);
|
|
325
329
|
return this.api.post("jingle/play", playJingleDto);
|
|
326
330
|
}
|
|
327
|
-
|
|
331
|
+
getBigBrotherData() {
|
|
328
332
|
return this.api.get("jingle/bigbrother");
|
|
329
333
|
}
|
|
330
334
|
async find(query, jingles = []) {
|
|
331
|
-
|
|
335
|
+
const items = jingles.length > 0 ? jingles : await this.getAll();
|
|
332
336
|
const queryParts = query.split(" ");
|
|
333
|
-
const matches =
|
|
334
|
-
(jingle) => queryParts.every((queryPart) =>
|
|
337
|
+
const matches = items.filter(
|
|
338
|
+
(jingle) => queryParts.every((queryPart) => `${jingle.folder}/${jingle.file}`.includes(queryPart))
|
|
335
339
|
);
|
|
336
340
|
return matches.sort((a, b) => {
|
|
337
341
|
const aScore = a.keywords.filter((keyword) => query.includes(keyword)).length;
|
|
@@ -347,25 +351,25 @@ var K8sModule = class extends BaseModule {
|
|
|
347
351
|
return this.api.get("k8s");
|
|
348
352
|
}
|
|
349
353
|
async deletePod(podName) {
|
|
350
|
-
return this.api.delete(`k8s/${podName}`);
|
|
354
|
+
return await this.api.delete(`k8s/${podName}`);
|
|
351
355
|
}
|
|
352
356
|
};
|
|
353
357
|
|
|
354
358
|
// src/api/user.ts
|
|
355
359
|
var UserModule = class extends BaseModule {
|
|
356
360
|
async get(userId) {
|
|
357
|
-
return this.cache.cacheOrGet(() => {
|
|
361
|
+
return await this.cache.cacheOrGet(() => {
|
|
358
362
|
const userIdParam = userId ? `/${userId}` : "";
|
|
359
363
|
return this.api.get(`user${userIdParam}`);
|
|
360
364
|
});
|
|
361
365
|
}
|
|
362
366
|
async getAll() {
|
|
363
|
-
return this.cache.cacheOrGet(() => {
|
|
367
|
+
return await this.cache.cacheOrGet(() => {
|
|
364
368
|
return this.api.get("user/all");
|
|
365
369
|
});
|
|
366
370
|
}
|
|
367
371
|
async setWindowState(setWindowStateDto) {
|
|
368
|
-
return this.api.putPossibleEmptyResponse("user/windowState", setWindowStateDto);
|
|
372
|
+
return await this.api.putPossibleEmptyResponse("user/windowState", setWindowStateDto);
|
|
369
373
|
}
|
|
370
374
|
};
|
|
371
375
|
|
|
@@ -414,7 +418,7 @@ var TssApi = class {
|
|
|
414
418
|
let response;
|
|
415
419
|
try {
|
|
416
420
|
response = await fetch(fullUrl, config);
|
|
417
|
-
} catch (
|
|
421
|
+
} catch (_e) {
|
|
418
422
|
throw new ErrorResponse(503, "API erg dood");
|
|
419
423
|
}
|
|
420
424
|
if (response.status >= 400) {
|
|
@@ -423,7 +427,7 @@ var TssApi = class {
|
|
|
423
427
|
}
|
|
424
428
|
return response;
|
|
425
429
|
}
|
|
426
|
-
|
|
430
|
+
fetchPossibleEmptyResponse(method, url, dto, config = {}) {
|
|
427
431
|
return this.fetch(url, {
|
|
428
432
|
method,
|
|
429
433
|
...config,
|
|
@@ -432,7 +436,7 @@ var TssApi = class {
|
|
|
432
436
|
}
|
|
433
437
|
async get(url) {
|
|
434
438
|
const response = await this.fetch(url);
|
|
435
|
-
return response.json();
|
|
439
|
+
return await response.json();
|
|
436
440
|
}
|
|
437
441
|
async post(url, dto, config = {}) {
|
|
438
442
|
const response = await this.fetchPossibleEmptyResponse("POST", url, dto, config);
|
|
@@ -441,7 +445,7 @@ var TssApi = class {
|
|
|
441
445
|
}
|
|
442
446
|
return await response.json();
|
|
443
447
|
}
|
|
444
|
-
|
|
448
|
+
postPossibleEmptyResponse(url, dto) {
|
|
445
449
|
return this.fetchPossibleEmptyResponse("POST", url, dto);
|
|
446
450
|
}
|
|
447
451
|
async put(url, dto) {
|
|
@@ -451,10 +455,10 @@ var TssApi = class {
|
|
|
451
455
|
}
|
|
452
456
|
return await response.json();
|
|
453
457
|
}
|
|
454
|
-
|
|
458
|
+
putPossibleEmptyResponse(url, dto) {
|
|
455
459
|
return this.fetchPossibleEmptyResponse("PUT", url, dto);
|
|
456
460
|
}
|
|
457
|
-
|
|
461
|
+
delete(url, config = {}) {
|
|
458
462
|
return this.fetch(url, {
|
|
459
463
|
method: "DELETE",
|
|
460
464
|
...config
|
package/dist/index.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../
|
|
4
|
-
"sourcesContent": ["export function get(belowFn) {\r\n const oldLimit = Error.stackTraceLimit;\r\n Error.stackTraceLimit = Infinity;\r\n\r\n const dummyObject = {};\r\n\r\n const v8Handler = Error.prepareStackTrace;\r\n Error.prepareStackTrace = function(dummyObject, v8StackTrace) {\r\n return v8StackTrace;\r\n };\r\n Error.captureStackTrace(dummyObject, belowFn || get);\r\n\r\n const v8StackTrace = dummyObject.stack;\r\n Error.prepareStackTrace = v8Handler;\r\n Error.stackTraceLimit = oldLimit;\r\n\r\n return v8StackTrace;\r\n}\r\n\r\nexport function parse(err) {\r\n if (!err.stack) {\r\n return [];\r\n }\r\n\r\n const lines = err.stack.split('\\n').slice(1);\r\n return lines\r\n .map(function(line) {\r\n if (line.match(/^\\s*[-]{4,}$/)) {\r\n return createParsedCallSite({\r\n fileName: line,\r\n lineNumber: null,\r\n functionName: null,\r\n typeName: null,\r\n methodName: null,\r\n columnNumber: null,\r\n 'native': null,\r\n });\r\n }\r\n\r\n const lineMatch = line.match(/at (?:(.+?)\\s+\\()?(?:(.+?):(\\d+)(?::(\\d+))?|([^)]+))\\)?/);\r\n if (!lineMatch) {\r\n return;\r\n }\r\n\r\n let object = null;\r\n let method = null;\r\n let functionName = null;\r\n let typeName = null;\r\n let methodName = null;\r\n let isNative = (lineMatch[5] === 'native');\r\n\r\n if (lineMatch[1]) {\r\n functionName = lineMatch[1];\r\n let methodStart = functionName.lastIndexOf('.');\r\n if (functionName[methodStart-1] == '.')\r\n methodStart--;\r\n if (methodStart > 0) {\r\n object = functionName.substr(0, methodStart);\r\n method = functionName.substr(methodStart + 1);\r\n const objectEnd = object.indexOf('.Module');\r\n if (objectEnd > 0) {\r\n functionName = functionName.substr(objectEnd + 1);\r\n object = object.substr(0, objectEnd);\r\n }\r\n }\r\n }\r\n\r\n if (method) {\r\n typeName = object;\r\n methodName = method;\r\n }\r\n\r\n if (method === '<anonymous>') {\r\n methodName = null;\r\n functionName = null;\r\n }\r\n\r\n const properties = {\r\n fileName: lineMatch[2] || null,\r\n lineNumber: parseInt(lineMatch[3], 10) || null,\r\n functionName: functionName,\r\n typeName: typeName,\r\n methodName: methodName,\r\n columnNumber: parseInt(lineMatch[4], 10) || null,\r\n 'native': isNative,\r\n };\r\n\r\n return createParsedCallSite(properties);\r\n })\r\n .filter(function(callSite) {\r\n return !!callSite;\r\n });\r\n}\r\n\r\nfunction CallSite(properties) {\r\n for (const property in properties) {\r\n this[property] = properties[property];\r\n }\r\n}\r\n\r\nconst strProperties = [\r\n 'this',\r\n 'typeName',\r\n 'functionName',\r\n 'methodName',\r\n 'fileName',\r\n 'lineNumber',\r\n 'columnNumber',\r\n 'function',\r\n 'evalOrigin'\r\n];\r\n\r\nconst boolProperties = [\r\n 'topLevel',\r\n 'eval',\r\n 'native',\r\n 'constructor'\r\n];\r\n\r\nstrProperties.forEach(function (property) {\r\n CallSite.prototype[property] = null;\r\n CallSite.prototype['get' + property[0].toUpperCase() + property.substr(1)] = function () {\r\n return this[property];\r\n }\r\n});\r\n\r\nboolProperties.forEach(function (property) {\r\n CallSite.prototype[property] = false;\r\n CallSite.prototype['is' + property[0].toUpperCase() + property.substr(1)] = function () {\r\n return this[property];\r\n }\r\n});\r\n\r\nfunction createParsedCallSite(properties) {\r\n return new CallSite(properties);\r\n}\r\n", "import { get } from 'stack-trace';\n\nexport enum CacheLifetime {\n Day = 60 * 60 * 24 * 1000,\n Week = 60 * 60 * 24 * 7 * 1000,\n}\n\nexport abstract class AbstractCache {\n constructor(protected cacheName: string) {}\n\n public abstract cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T>;\n\n public abstract get<T>(key: string): Promise<T | undefined>;\n\n public abstract set<T>(key: string, value: T, lifetime?: number): void;\n\n public abstract remove(key: string): void;\n\n public abstract clear(): void;\n\n public getCacheKey(): string {\n const errorMessage = 'Could not determine cache key. Please provide a key manually.';\n const trace = get();\n if (trace.length < 3) {\n throw new Error(errorMessage);\n }\n\n const functionName = get()[2].getFunctionName();\n if (!functionName) {\n throw new Error(errorMessage);\n }\n\n return functionName;\n }\n}\n", "import { AbstractCache } from './abstractCache';\n\nexport class CookieCache extends AbstractCache {\n public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n throw new Error('Not implemented, use get() and set()');\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n if (document.cookie.includes(`${key}=`)) {\n return document.cookie.split(`${key}=`)[1]?.split(';')[0] as T;\n }\n\n return undefined;\n }\n\n public set<T>(key: string, value: T, lifetime?: number): void {\n const expires = lifetime ? new Date(Date.now() + lifetime).toUTCString() : '';\n document.cookie = `${key}=${value}; expires=${expires}; path=/; samesite=strict; secure`;\n }\n\n public remove(key: string): void {\n document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;\n }\n\n public clear(): void {\n throw new Error('Not implemented, use remove()');\n }\n}\n", "import { AbstractCache } from './abstractCache';\nimport fs from 'fs';\nimport path from 'path';\nimport os from 'os';\n\ntype CacheItem = {\n value: any;\n expiresAt?: number;\n};\n\nexport class FilesystemCache extends AbstractCache {\n protected initialized = false;\n\n protected state: { [key: string]: CacheItem } = {};\n\n public async cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n key = key ?? this.getCacheKey();\n\n const cachedValue = await this.get<T>(key);\n if (cachedValue) {\n return cachedValue;\n }\n\n const result = await callbackWhenEmpty();\n this.set(key, result, lifetime);\n return result;\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n if (!this.initialized) {\n await this._initialize();\n }\n\n const expires = this.state[key]?.expiresAt;\n if (Object.keys(this.state).includes(key) && (expires === undefined || expires > Date.now())) {\n return this.state[key].value;\n }\n\n return undefined;\n }\n\n public set<T>(key: string, value: T, lifetime?: number): void {\n const expiresAt = lifetime ? Date.now() + lifetime : undefined;\n const content: CacheItem = { value };\n if (expiresAt) {\n content.expiresAt = expiresAt;\n }\n this.state[key] = content;\n this.writeState();\n }\n\n public remove(key: string): void {\n delete this.state[key];\n this.writeState();\n }\n\n public clear(): void {\n this.state = {};\n if (fs.existsSync(this.getFilePath())) {\n fs.unlinkSync(this.getFilePath());\n }\n }\n\n public getFilePath() {\n return path.join(os.homedir(), '.tss', `${this.cacheName}.json`);\n }\n\n protected _initialize() {\n this.initialized = true;\n if (fs.existsSync(this.getFilePath())) {\n this.state = JSON.parse(fs.readFileSync(this.getFilePath(), 'utf8'));\n }\n }\n\n protected writeState() {\n if (!fs.existsSync(path.dirname(this.getFilePath()))) {\n fs.mkdirSync(path.dirname(this.getFilePath()));\n }\n\n fs.writeFileSync(this.getFilePath(), JSON.stringify(this.state));\n }\n}\n", "import { AbstractCache } from './abstractCache';\n\nexport class NullCache extends AbstractCache {\n public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n return callbackWhenEmpty();\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n return undefined;\n }\n\n public set<T>(key: string, value: T, lifetime?: number): void {}\n\n public remove(key: string): void {}\n\n public clear(): void {}\n}\n", "import { AbstractCache } from './abstractCache';\nimport util from 'util';\nimport child_process from 'child_process';\n\n// TODO error handling en lifetime\nexport class OnePasswordCache extends AbstractCache {\n protected asyncExec = util.promisify(child_process.exec);\n\n public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n throw new Error('Not implemented, use get() and set()');\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n const { stdout, stderr } = await this.asyncExec(`op item get \"${key}\" --fields label=credential --format json`);\n\n if (stderr) {\n console.log(stderr);\n throw new Error('ERROR');\n }\n\n return JSON.parse(stdout).value;\n }\n\n public async set<T>(key: string, value: T, lifetime?: number): Promise<void> {\n let action = `op item edit '${key}' 'credential=${value}'`;\n\n try {\n const t = await this.get(key);\n } catch (e) {\n action = `op item create --category=\"API Credential\" --title ${key} 'credential=${value}'`;\n }\n\n const { stdout, stderr } = await this.asyncExec(action);\n\n if (stderr) {\n console.log(stderr);\n throw new Error('ERROR');\n }\n }\n\n public async remove(key: string): Promise<void> {\n await this.asyncExec(`op item delete '${key}'`);\n }\n\n public clear(): void {\n // Loopje maken en heel 1password leeg maken?\n }\n}\n", "import { AbstractCache } from '../cache';\nimport { TssApi } from '../index';\n\nexport class BaseModule {\n constructor(protected api: TssApi, protected cache: AbstractCache) {}\n\n public getCache() {\n return this.cache;\n }\n\n public setCache(cache: AbstractCache) {\n this.cache = cache;\n }\n}\n", "import { BaseModule } from './base';\nimport { AuthenticationOptionsDto, VerificationResponseDto, type TokenContent } from 'tering-serieuze-types';\nimport type {\n AuthenticationResponseJSON,\n PublicKeyCredentialCreationOptionsJSON,\n RegistrationResponseJSON,\n} from '@simplewebauthn/types';\n\nexport function parseJwt<T>(token: string): T {\n let jsonPayload;\n\n if (typeof Buffer !== 'undefined') {\n jsonPayload = Buffer.from(token.split('.')[1], 'base64').toString();\n } else {\n const base64Url = token.split('.')[1];\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n jsonPayload = decodeURIComponent(\n window\n .atob(base64)\n .split('')\n .map(function (c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(''),\n );\n }\n\n return JSON.parse(jsonPayload) as T;\n}\n\nexport class AuthModule extends BaseModule {\n public static cacheKey = 'TSS-TOKEN';\n\n async getToken(): Promise<string | undefined> {\n return process.env.TSS_TOKEN ?? this.cache.get(AuthModule.cacheKey);\n }\n\n async setToken(token: string, lifetime?: number) {\n return this.cache.set(AuthModule.cacheKey, token, lifetime);\n }\n\n async setCode(code: string) {\n // TODO any ?!\n const { accessToken } = await this.api.post<any>(`auth/setCode?code=${code}`, {}, { credentials: 'include' });\n return accessToken;\n }\n\n async removeToken() {\n return this.cache.remove(AuthModule.cacheKey);\n }\n\n async getSessionId() {\n const token = await this.getToken();\n const { sessionId } = parseJwt<TokenContent>(token ?? '');\n return sessionId;\n }\n\n async removeSession(sessionId?: string) {\n const session = sessionId ?? (await this.getSessionId());\n await this.api.delete(`session/${session}`, { credentials: 'include' });\n }\n\n async logout() {\n await this.removeSession();\n await this.removeToken();\n }\n\n async getRegistrationOptions(registrationToken: string) {\n return this.api.get<PublicKeyCredentialCreationOptionsJSON>(`auth/registration-options/${registrationToken}`);\n }\n\n async getAuthenticationOptions() {\n return this.api.get<AuthenticationOptionsDto>('auth/authentication-options');\n }\n\n async verifyRegistration(registrationToken: string, registrationResponse: RegistrationResponseJSON) {\n return this.api.post<VerificationResponseDto>(\n `auth/verify-registration/${registrationToken}`,\n registrationResponse,\n { credentials: 'include' },\n );\n }\n\n async verifyAuthentication(token: string, response: AuthenticationResponseJSON) {\n return this.api.post<VerificationResponseDto>(`auth/verify-authentication/${token}`, response, {\n credentials: 'include',\n });\n }\n}\n", "import type { JingleFolder, Jingle, PlayJingleDto, BigBrotherItem } from 'tering-serieuze-types';\nimport { BaseModule } from './base';\nimport { CacheLifetime } from '../cache';\n\nexport class JingleModule extends BaseModule {\n async getGrouped(): Promise<JingleFolder[]> {\n return this.cache.cacheOrGet(\n () => {\n return this.api.get<JingleFolder[]>('jingle/grouped');\n },\n 'getGrouped',\n CacheLifetime.Day,\n );\n }\n\n async getAll(): Promise<Jingle[]> {\n return this.cache.cacheOrGet(\n () => {\n return this.api.get<Jingle[]>('jingle');\n },\n 'getAll',\n CacheLifetime.Day,\n );\n }\n\n async getRecentlyAdded(): Promise<Jingle[]> {\n const jingles = await this.getAll();\n return jingles.sort((a, b) => b.mtime - a.mtime).slice(0, 30);\n }\n\n async play(playJingleDto: PlayJingleDto) {\n console.log(`Playing jingle ${playJingleDto.folder}/${playJingleDto.file}`);\n return this.api.post('jingle/play', playJingleDto);\n }\n\n async getBigBrotherData(): Promise<BigBrotherItem[]> {\n return this.api.get<BigBrotherItem[]>('jingle/bigbrother');\n }\n\n async find(query: string, jingles: Jingle[] = []): Promise<Jingle[]> {\n jingles = jingles.length ? jingles : await this.getAll();\n\n const queryParts = query.split(' ');\n const matches = jingles.filter((jingle) =>\n queryParts.every((queryPart) => (jingle.folder + '/' + jingle.file).includes(queryPart)),\n );\n\n return matches.sort((a, b) => {\n const aScore = a.keywords.filter((keyword) => query.includes(keyword)).length;\n const bScore = b.keywords.filter((keyword) => query.includes(keyword)).length;\n\n return bScore - aScore;\n });\n }\n}\n", "import { BaseModule } from './base';\nimport type { Pod } from 'tering-serieuze-types';\n\nexport class K8sModule extends BaseModule {\n getPods() {\n return this.api.get<Pod[]>('k8s');\n }\n\n async deletePod(podName: string) {\n return this.api.delete(`k8s/${podName}`);\n }\n}\n", "import { BaseModule } from './base';\nimport type { SetWindowStateDto, User } from 'tering-serieuze-types';\n\nexport class UserModule extends BaseModule {\n async get(userId?: string) {\n return this.cache.cacheOrGet(() => {\n const userIdParam = userId ? `/${userId}` : '';\n return this.api.get<User>(`user${userIdParam}`);\n });\n }\n\n async getAll() {\n return this.cache.cacheOrGet(() => {\n return this.api.get<User[]>('user/all');\n });\n }\n\n async setWindowState(setWindowStateDto: SetWindowStateDto) {\n return this.api.putPossibleEmptyResponse('user/windowState', setWindowStateDto);\n }\n}\n", "import { AbstractCache, NullCache } from './cache';\nimport { AuthModule, JingleModule, K8sModule, UserModule } from './api';\nimport type { Dto } from 'tering-serieuze-types';\n\nexport * from './api';\nexport * from './cache';\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n\nexport interface SDKRequestInit extends RequestInit {\n method?: HttpMethod;\n}\n\nexport enum CacheType {\n jingle = 'jingle',\n auth = 'auth',\n k8s = 'k8s',\n user = 'user',\n}\n\nexport type ApiConfiguration = {\n API_URL: string;\n};\n\nexport type CacheConfiguration = {\n [key in keyof typeof CacheType]?: AbstractCache;\n};\n\nexport class ErrorResponse extends Error {\n constructor(public readonly status: number, public readonly message: string) {\n super();\n }\n}\n\nexport class TssApi {\n auth: AuthModule;\n jingle: JingleModule;\n k8s: K8sModule;\n user: UserModule;\n\n constructor(protected readonly apiConfiguration: ApiConfiguration, cacheConfiguration?: CacheConfiguration) {\n this.jingle = new JingleModule(this, cacheConfiguration?.jingle ?? new NullCache('jingle'));\n this.auth = new AuthModule(this, cacheConfiguration?.auth ?? new NullCache('auth'));\n this.k8s = new K8sModule(this, cacheConfiguration?.k8s ?? new NullCache('k8s'));\n this.user = new UserModule(this, cacheConfiguration?.user ?? new NullCache('user'));\n }\n\n async fetch(url: string, config: SDKRequestInit = {}) {\n config.method = config.method ?? 'GET';\n config.headers = {\n ...config.headers,\n Authorization: `Bearer ${await this.auth.getToken()}`,\n };\n\n // @ts-ignore\n if (!config.headers['Content-Type']) {\n // @ts-ignore\n config.headers['Content-Type'] = config.body ? 'application/json' : 'text/plain';\n }\n\n const apiPrefix = this.apiConfiguration.API_URL;\n\n if (apiPrefix.match(/^https?:\\/\\/localhost/) !== null && typeof process !== 'undefined' && process.env) {\n process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';\n }\n\n const fullUrl = `${apiPrefix}/api/${url}`;\n console.log('Fetching url', fullUrl);\n\n let response;\n try {\n response = await fetch(fullUrl, config);\n } catch (e) {\n throw new ErrorResponse(503, 'API erg dood');\n }\n\n if (response.status >= 400) {\n const error = await response.json();\n throw new ErrorResponse(error.statusCode, error.message ?? error.error);\n }\n\n return response;\n }\n\n protected async fetchPossibleEmptyResponse<T>(\n method: HttpMethod,\n url: string,\n dto: Dto,\n config: SDKRequestInit = {},\n ) {\n return this.fetch(url, {\n method,\n ...config,\n body: JSON.stringify(dto),\n });\n }\n\n async get<T>(url: string) {\n const response = await this.fetch(url);\n return response.json() as Promise<T>;\n }\n\n async post<T>(url: string, dto: Dto, config: SDKRequestInit = {}) {\n const response = await this.fetchPossibleEmptyResponse<T>('POST', url, dto, config);\n if (response === undefined) {\n throw new Error('Response was undefined');\n }\n return (await response.json()) as Promise<T>;\n }\n\n async postPossibleEmptyResponse(url: string, dto: Dto) {\n return this.fetchPossibleEmptyResponse('POST', url, dto);\n }\n\n async put<T>(url: string, dto: Dto) {\n const response = await this.fetchPossibleEmptyResponse<T>('PUT', url, dto);\n if (response === undefined) {\n throw new Error('Response was undefined');\n }\n return (await response.json()) as Promise<T>;\n }\n\n async putPossibleEmptyResponse(url: string, dto: Dto) {\n return this.fetchPossibleEmptyResponse('PUT', url, dto);\n }\n\n async delete<T>(url: string, config: SDKRequestInit = {}) {\n return this.fetch(url, {\n method: 'DELETE',\n ...config,\n });\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;
|
|
3
|
+
"sources": ["../src/api/base.ts", "../src/api/auth.ts", "../node_modules/stack-trace/index.js", "../src/cache/abstractCache.ts", "../src/cache/cookieCache.ts", "../src/cache/filesystemCache.ts", "../src/cache/nullCache.ts", "../src/cache/onePasswordCache.ts", "../src/api/jingle.ts", "../src/api/k8s.ts", "../src/api/user.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["import { AbstractCache } from '../cache';\nimport { TssApi } from '../index';\n\nexport class BaseModule {\n constructor(\n protected api: TssApi,\n protected cache: AbstractCache,\n ) {}\n\n public getCache() {\n return this.cache;\n }\n\n public setCache(cache: AbstractCache) {\n this.cache = cache;\n }\n}\n", "import type {\n AuthenticationResponseJSON,\n PublicKeyCredentialCreationOptionsJSON,\n RegistrationResponseJSON,\n} from '@simplewebauthn/types';\nimport { AuthenticationOptionsDto, type TokenContent, VerificationResponseDto } from 'tering-serieuze-types';\nimport { BaseModule } from './base';\n\nexport function parseJwt<T>(token: string): T {\n let jsonPayload = '';\n\n if (typeof Buffer !== 'undefined') {\n jsonPayload = Buffer.from(token.split('.')[1], 'base64').toString();\n } else {\n const base64Url = token.split('.')[1];\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n jsonPayload = decodeURIComponent(\n window\n .atob(base64)\n .split('')\n // biome-ignore lint/style/useTemplate: Hier wel handig\n .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))\n .join(''),\n );\n }\n\n return JSON.parse(jsonPayload) as T;\n}\n\nexport class AuthModule extends BaseModule {\n public static cacheKey = 'TSS-TOKEN';\n\n getToken(): Promise<string | undefined> {\n return process.env.TSS_TOKEN ? Promise.resolve(process.env.TSS_TOKEN) : this.cache.get(AuthModule.cacheKey);\n }\n\n setToken(token: string, lifetime?: number) {\n return this.cache.set(AuthModule.cacheKey, token, lifetime);\n }\n\n removeToken() {\n return this.cache.remove(AuthModule.cacheKey);\n }\n\n async getSessionId() {\n const token = await this.getToken();\n const { sessionId } = parseJwt<TokenContent>(token ?? '');\n return sessionId;\n }\n\n async removeSession(sessionId?: string) {\n const session = sessionId ?? (await this.getSessionId());\n await this.api.delete(`session/${session}`, { credentials: 'include' });\n }\n\n async logout() {\n await this.removeSession();\n this.removeToken();\n }\n\n getRegistrationOptions(registrationToken: string) {\n return this.api.get<PublicKeyCredentialCreationOptionsJSON>(`auth/registration-options/${registrationToken}`);\n }\n\n getAuthenticationOptions() {\n return this.api.get<AuthenticationOptionsDto>('auth/authentication-options');\n }\n\n verifyRegistration(registrationToken: string, registrationResponse: RegistrationResponseJSON) {\n return this.api.post<VerificationResponseDto>(\n `auth/verify-registration/${registrationToken}`,\n registrationResponse,\n { credentials: 'include' },\n );\n }\n\n verifyAuthentication(token: string, response: AuthenticationResponseJSON) {\n return this.api.post<VerificationResponseDto>(`auth/verify-authentication/${token}`, response, {\n credentials: 'include',\n });\n }\n}\n", "export function get(belowFn) {\r\n const oldLimit = Error.stackTraceLimit;\r\n Error.stackTraceLimit = Infinity;\r\n\r\n const dummyObject = {};\r\n\r\n const v8Handler = Error.prepareStackTrace;\r\n Error.prepareStackTrace = function(dummyObject, v8StackTrace) {\r\n return v8StackTrace;\r\n };\r\n Error.captureStackTrace(dummyObject, belowFn || get);\r\n\r\n const v8StackTrace = dummyObject.stack;\r\n Error.prepareStackTrace = v8Handler;\r\n Error.stackTraceLimit = oldLimit;\r\n\r\n return v8StackTrace;\r\n}\r\n\r\nexport function parse(err) {\r\n if (!err.stack) {\r\n return [];\r\n }\r\n\r\n const lines = err.stack.split('\\n').slice(1);\r\n return lines\r\n .map(function(line) {\r\n if (line.match(/^\\s*[-]{4,}$/)) {\r\n return createParsedCallSite({\r\n fileName: line,\r\n lineNumber: null,\r\n functionName: null,\r\n typeName: null,\r\n methodName: null,\r\n columnNumber: null,\r\n 'native': null,\r\n });\r\n }\r\n\r\n const lineMatch = line.match(/at (?:(.+?)\\s+\\()?(?:(.+?):(\\d+)(?::(\\d+))?|([^)]+))\\)?/);\r\n if (!lineMatch) {\r\n return;\r\n }\r\n\r\n let object = null;\r\n let method = null;\r\n let functionName = null;\r\n let typeName = null;\r\n let methodName = null;\r\n let isNative = (lineMatch[5] === 'native');\r\n\r\n if (lineMatch[1]) {\r\n functionName = lineMatch[1];\r\n let methodStart = functionName.lastIndexOf('.');\r\n if (functionName[methodStart-1] == '.')\r\n methodStart--;\r\n if (methodStart > 0) {\r\n object = functionName.substr(0, methodStart);\r\n method = functionName.substr(methodStart + 1);\r\n const objectEnd = object.indexOf('.Module');\r\n if (objectEnd > 0) {\r\n functionName = functionName.substr(objectEnd + 1);\r\n object = object.substr(0, objectEnd);\r\n }\r\n }\r\n }\r\n\r\n if (method) {\r\n typeName = object;\r\n methodName = method;\r\n }\r\n\r\n if (method === '<anonymous>') {\r\n methodName = null;\r\n functionName = null;\r\n }\r\n\r\n const properties = {\r\n fileName: lineMatch[2] || null,\r\n lineNumber: parseInt(lineMatch[3], 10) || null,\r\n functionName: functionName,\r\n typeName: typeName,\r\n methodName: methodName,\r\n columnNumber: parseInt(lineMatch[4], 10) || null,\r\n 'native': isNative,\r\n };\r\n\r\n return createParsedCallSite(properties);\r\n })\r\n .filter(function(callSite) {\r\n return !!callSite;\r\n });\r\n}\r\n\r\nfunction CallSite(properties) {\r\n for (const property in properties) {\r\n this[property] = properties[property];\r\n }\r\n}\r\n\r\nconst strProperties = [\r\n 'this',\r\n 'typeName',\r\n 'functionName',\r\n 'methodName',\r\n 'fileName',\r\n 'lineNumber',\r\n 'columnNumber',\r\n 'function',\r\n 'evalOrigin'\r\n];\r\n\r\nconst boolProperties = [\r\n 'topLevel',\r\n 'eval',\r\n 'native',\r\n 'constructor'\r\n];\r\n\r\nstrProperties.forEach(function (property) {\r\n CallSite.prototype[property] = null;\r\n CallSite.prototype['get' + property[0].toUpperCase() + property.substr(1)] = function () {\r\n return this[property];\r\n }\r\n});\r\n\r\nboolProperties.forEach(function (property) {\r\n CallSite.prototype[property] = false;\r\n CallSite.prototype['is' + property[0].toUpperCase() + property.substr(1)] = function () {\r\n return this[property];\r\n }\r\n});\r\n\r\nfunction createParsedCallSite(properties) {\r\n return new CallSite(properties);\r\n}\r\n", "import { get } from 'stack-trace';\n\nexport enum CacheLifetime {\n Day = 60 * 60 * 24 * 1000,\n Week = 60 * 60 * 24 * 7 * 1000,\n}\n\nexport abstract class AbstractCache {\n constructor(protected cacheName: string) {}\n\n public abstract cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T>;\n\n public abstract get<T>(key: string): Promise<T | undefined>;\n\n public abstract set<T>(key: string, value: T, lifetime?: number): void;\n\n public abstract remove(key: string): void;\n\n public abstract clear(): void;\n\n public getCacheKey(): string {\n const errorMessage = 'Could not determine cache key. Please provide a key manually.';\n const trace = get();\n if (trace.length < 3) {\n throw new Error(errorMessage);\n }\n\n const functionName = get()[2].getFunctionName();\n if (!functionName) {\n throw new Error(errorMessage);\n }\n\n return functionName;\n }\n}\n", "/** biome-ignore-all lint/suspicious/noDocumentCookie: Hier mag het hoor */\nimport { AbstractCache } from './abstractCache';\n\nexport class CookieCache extends AbstractCache {\n public cacheOrGet<T>(): Promise<T> {\n throw new Error('Not implemented, use get() and set()');\n }\n\n public get<T>(key: string): Promise<T | undefined> {\n if (document.cookie.includes(`${key}=`)) {\n return Promise.resolve(document.cookie.split(`${key}=`)[1]?.split(';')[0] as T);\n }\n\n return Promise.resolve(undefined);\n }\n\n public set<T>(key: string, value: T, lifetime?: number): void {\n const expires = lifetime ? new Date(Date.now() + lifetime).toUTCString() : '';\n document.cookie = `${key}=${value}; expires=${expires}; path=/; samesite=strict; secure`;\n }\n\n public remove(key: string): void {\n document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;\n }\n\n public clear(): void {\n throw new Error('Not implemented, use remove()');\n }\n}\n", "import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { AbstractCache } from './abstractCache';\n\ntype CacheItem<T> = {\n value: T;\n expiresAt?: number;\n};\n\nexport class FilesystemCache<T = unknown> extends AbstractCache {\n protected initialized = false;\n\n protected state = new Map<string, CacheItem<T>>();\n\n public async cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {\n const usedKey = key ?? this.getCacheKey();\n\n const cachedValue = await this.get<T>(usedKey);\n if (cachedValue) {\n return cachedValue;\n }\n\n const result = await callbackWhenEmpty();\n this.set(usedKey, result, lifetime);\n return result;\n }\n\n public get<T>(key: string): Promise<T | undefined> {\n if (!this.initialized) {\n this._initialize();\n }\n\n const item = this.state.get(key);\n\n if (item) {\n const expires = item.expiresAt;\n if (expires === undefined || expires > Date.now()) {\n return Promise.resolve(item.value as unknown as T);\n }\n }\n\n return Promise.resolve(undefined);\n }\n\n public set<T>(key: string, value: T, lifetime?: number): void {\n const expiresAt = lifetime ? Date.now() + lifetime : undefined;\n\n // 'content' is typed as the Method's T\n const content: CacheItem<T> = { value };\n if (expiresAt) {\n content.expiresAt = expiresAt;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: hier mag alles\n this.state.set(key, content as any);\n\n this.writeState();\n }\n\n public remove(key: string): void {\n this.state.delete(key);\n this.writeState();\n }\n\n public clear(): void {\n this.state.clear();\n if (fs.existsSync(this.getFilePath())) {\n fs.unlinkSync(this.getFilePath());\n }\n }\n\n public getFilePath() {\n return path.join(os.homedir(), '.tss', `${this.cacheName}.json`);\n }\n\n protected _initialize() {\n this.initialized = true;\n if (fs.existsSync(this.getFilePath())) {\n try {\n const fileContent = fs.readFileSync(this.getFilePath(), 'utf8');\n const parsed = JSON.parse(fileContent);\n this.state = new Map(Object.entries(parsed)) as Map<string, CacheItem<T>>;\n } catch (_e) {\n this.state = new Map();\n }\n }\n }\n\n protected writeState() {\n if (!fs.existsSync(path.dirname(this.getFilePath()))) {\n fs.mkdirSync(path.dirname(this.getFilePath()), { recursive: true });\n }\n\n const plainObject = Object.fromEntries(this.state);\n fs.writeFileSync(this.getFilePath(), JSON.stringify(plainObject));\n }\n}\n", "import { AbstractCache } from './abstractCache';\n\nexport class NullCache extends AbstractCache {\n public cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>): Promise<T> {\n return callbackWhenEmpty();\n }\n\n public get<T>(): Promise<T | undefined> {\n return Promise.resolve(undefined);\n }\n\n public set(): void {\n // void\n }\n\n public remove(): void {\n // void\n }\n\n public clear(): void {\n // void\n }\n}\n", "import child_process from 'node:child_process';\nimport util from 'node:util';\nimport { AbstractCache } from './abstractCache';\n\n// TODO error handling en lifetime\nexport class OnePasswordCache extends AbstractCache {\n protected asyncExec = util.promisify(child_process.exec);\n\n public cacheOrGet<T>(): Promise<T> {\n throw new Error('Not implemented, use get() and set()');\n }\n\n public async get<T>(key: string): Promise<T | undefined> {\n const { stdout, stderr } = await this.asyncExec(`op item get \"${key}\" --fields label=credential --format json`);\n\n if (stderr) {\n console.log(stderr);\n throw new Error('ERROR');\n }\n\n return JSON.parse(stdout).value;\n }\n\n public async set<T>(key: string, value: T): Promise<void> {\n let action = `op item edit '${key}' 'credential=${value}'`;\n\n try {\n await this.get(key);\n } catch (_e) {\n action = `op item create --category=\"API Credential\" --title ${key} 'credential=${value}'`;\n }\n\n const { stderr } = await this.asyncExec(action);\n\n if (stderr) {\n console.log(stderr);\n throw new Error('ERROR');\n }\n }\n\n public async remove(key: string): Promise<void> {\n await this.asyncExec(`op item delete '${key}'`);\n }\n\n public clear(): void {\n // Loopje maken en heel 1password leeg maken?\n }\n}\n", "import type { BigBrotherItem, Jingle, JingleFolder, PlayJingleDto } from 'tering-serieuze-types';\nimport { CacheLifetime } from '../cache';\nimport { BaseModule } from './base';\n\nexport class JingleModule extends BaseModule {\n getGrouped(): Promise<JingleFolder[]> {\n return this.cache.cacheOrGet(\n () => {\n return this.api.get<JingleFolder[]>('jingle/grouped');\n },\n 'getGrouped',\n CacheLifetime.Day,\n );\n }\n\n getAll(): Promise<Jingle[]> {\n return this.cache.cacheOrGet(\n () => {\n return this.api.get<Jingle[]>('jingle');\n },\n 'getAll',\n CacheLifetime.Day,\n );\n }\n\n async getRecentlyAdded(): Promise<Jingle[]> {\n const jingles = await this.getAll();\n return jingles.sort((a, b) => b.mtime - a.mtime).slice(0, 30);\n }\n\n play(playJingleDto: PlayJingleDto): Promise<{ success: boolean }> {\n console.log(`Playing jingle ${playJingleDto.folder}/${playJingleDto.file}`);\n return this.api.post<{ success: boolean }>('jingle/play', playJingleDto);\n }\n\n getBigBrotherData(): Promise<BigBrotherItem[]> {\n return this.api.get<BigBrotherItem[]>('jingle/bigbrother');\n }\n\n async find(query: string, jingles: Jingle[] = []): Promise<Jingle[]> {\n const items = jingles.length > 0 ? jingles : await this.getAll();\n\n const queryParts = query.split(' ');\n const matches = items.filter((jingle) =>\n queryParts.every((queryPart) => `${jingle.folder}/${jingle.file}`.includes(queryPart)),\n );\n\n return matches.sort((a, b) => {\n const aScore = a.keywords.filter((keyword) => query.includes(keyword)).length;\n const bScore = b.keywords.filter((keyword) => query.includes(keyword)).length;\n\n return bScore - aScore;\n });\n }\n}\n", "import type { Pod } from 'tering-serieuze-types';\nimport { BaseModule } from './base';\n\nexport class K8sModule extends BaseModule {\n getPods() {\n return this.api.get<Pod[]>('k8s');\n }\n\n async deletePod(podName: string) {\n return await this.api.delete(`k8s/${podName}`);\n }\n}\n", "import type { SetWindowStateDto, User } from 'tering-serieuze-types';\nimport { BaseModule } from './base';\n\nexport class UserModule extends BaseModule {\n async get(userId?: string) {\n return await this.cache.cacheOrGet(() => {\n const userIdParam = userId ? `/${userId}` : '';\n return this.api.get<User>(`user${userIdParam}`);\n });\n }\n\n async getAll() {\n return await this.cache.cacheOrGet(() => {\n return this.api.get<User[]>('user/all');\n });\n }\n\n async setWindowState(setWindowStateDto: SetWindowStateDto) {\n return await this.api.putPossibleEmptyResponse('user/windowState', setWindowStateDto);\n }\n}\n", "import type { Dto } from 'tering-serieuze-types';\nimport { AuthModule, JingleModule, K8sModule, UserModule } from './api';\nimport { AbstractCache, NullCache } from './cache';\n\nexport * from './api';\nexport * from './cache';\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n\nexport interface SDKRequestInit extends RequestInit {\n method?: HttpMethod;\n}\n\nexport enum CacheType {\n jingle = 'jingle',\n auth = 'auth',\n k8s = 'k8s',\n user = 'user',\n}\n\nexport type ApiConfiguration = {\n API_URL: string;\n};\n\nexport type CacheConfiguration = {\n [key in keyof typeof CacheType]?: AbstractCache;\n};\n\nexport class ErrorResponse extends Error {\n constructor(\n public readonly status: number,\n public readonly message: string,\n ) {\n super();\n }\n}\n\nexport class TssApi {\n auth: AuthModule;\n jingle: JingleModule;\n k8s: K8sModule;\n user: UserModule;\n\n constructor(\n protected readonly apiConfiguration: ApiConfiguration,\n cacheConfiguration?: CacheConfiguration,\n ) {\n this.jingle = new JingleModule(this, cacheConfiguration?.jingle ?? new NullCache('jingle'));\n this.auth = new AuthModule(this, cacheConfiguration?.auth ?? new NullCache('auth'));\n this.k8s = new K8sModule(this, cacheConfiguration?.k8s ?? new NullCache('k8s'));\n this.user = new UserModule(this, cacheConfiguration?.user ?? new NullCache('user'));\n }\n\n async fetch(url: string, config: SDKRequestInit = {}) {\n config.method = config.method ?? 'GET';\n config.headers = {\n ...config.headers,\n Authorization: `Bearer ${await this.auth.getToken()}`,\n };\n\n // @ts-ignore\n if (!config.headers['Content-Type']) {\n // @ts-ignore\n config.headers['Content-Type'] = config.body ? 'application/json' : 'text/plain';\n }\n\n const apiPrefix = this.apiConfiguration.API_URL;\n\n if (apiPrefix.match(/^https?:\\/\\/localhost/) !== null && typeof process !== 'undefined' && process.env) {\n process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';\n }\n\n const fullUrl = `${apiPrefix}/api/${url}`;\n console.log('Fetching url', fullUrl);\n\n let response: Response;\n try {\n response = await fetch(fullUrl, config);\n } catch (_e) {\n throw new ErrorResponse(503, 'API erg dood');\n }\n\n if (response.status >= 400) {\n const error = await response.json();\n throw new ErrorResponse(error.statusCode, error.message ?? error.error);\n }\n\n return response;\n }\n\n protected fetchPossibleEmptyResponse(method: HttpMethod, url: string, dto: Dto, config: SDKRequestInit = {}) {\n return this.fetch(url, {\n method,\n ...config,\n body: JSON.stringify(dto),\n });\n }\n\n async get<T>(url: string): Promise<T> {\n const response = await this.fetch(url);\n return (await response.json()) as Promise<T>;\n }\n\n async post<T>(url: string, dto: Dto, config: SDKRequestInit = {}) {\n const response = await this.fetchPossibleEmptyResponse('POST', url, dto, config);\n if (response === undefined) {\n throw new Error('Response was undefined');\n }\n return (await response.json()) as Promise<T>;\n }\n\n postPossibleEmptyResponse(url: string, dto: Dto) {\n return this.fetchPossibleEmptyResponse('POST', url, dto);\n }\n\n async put<T>(url: string, dto: Dto) {\n const response = await this.fetchPossibleEmptyResponse('PUT', url, dto);\n if (response === undefined) {\n throw new Error('Response was undefined');\n }\n return (await response.json()) as Promise<T>;\n }\n\n putPossibleEmptyResponse(url: string, dto: Dto) {\n return this.fetchPossibleEmptyResponse('PUT', url, dto);\n }\n\n delete(url: string, config: SDKRequestInit = {}) {\n return this.fetch(url, {\n method: 'DELETE',\n ...config,\n });\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;AAGO,IAAM,aAAN,MAAiB;AAAA,EACpB,YACc,KACA,OACZ;AAFY;AACA;AAAA,EACX;AAAA,EAEI,WAAW;AACd,WAAO,KAAK;AAAA,EAChB;AAAA,EAEO,SAAS,OAAsB;AAClC,SAAK,QAAQ;AAAA,EACjB;AACJ;;;ACRO,SAAS,SAAY,OAAkB;AAC1C,MAAI,cAAc;AAElB,MAAI,OAAO,WAAW,aAAa;AAC/B,kBAAc,OAAO,KAAK,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,QAAQ,EAAE,S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;AAAA,EAEA,OAAO,KAAa,SAAyB,CAAC,GAAG;AAC7C,WAAO,KAAK,MAAM,KAAK;AAAA,MACnB,QAAQ;AAAA,MACR,GAAG;AAAA,IACP,CAAC;AAAA,EACL;AACJ;",
|
|
6
6
|
"names": ["dummyObject", "v8StackTrace", "CacheLifetime", "CacheType"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tering-serieuze-sdk",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.13.1",
|
|
4
4
|
"description": "Teringserieuze sdk",
|
|
5
5
|
"author": "Frank",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"types": "index.d.ts",
|
|
9
9
|
"type": "module",
|
|
10
10
|
"scripts": {
|
|
11
|
-
"test": "API_URL=
|
|
11
|
+
"test": "API_URL=http://localhost:8081 vitest run",
|
|
12
12
|
"lint": "biome ci . --error-on-warnings",
|
|
13
13
|
"coverage": "vitest run --coverage",
|
|
14
14
|
"dev": "esbuild src/index.ts --bundle --platform=node --outfile=dist/index.mjs --packages=external --sourcemap=external --format=esm --watch",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"@types/node": "^18.19.4",
|
|
37
37
|
"@vitest/coverage-c8": "^0.28.5",
|
|
38
38
|
"esbuild": "^0.17.12",
|
|
39
|
-
"tering-serieuze-types": "^1.
|
|
39
|
+
"tering-serieuze-types": "^1.27.1",
|
|
40
40
|
"vitest": "^0.28.5"
|
|
41
41
|
}
|
|
42
42
|
}
|
package/src/api/auth.ts
CHANGED
|
@@ -31,19 +31,13 @@ export class AuthModule extends BaseModule {
|
|
|
31
31
|
public static cacheKey = 'TSS-TOKEN';
|
|
32
32
|
|
|
33
33
|
getToken(): Promise<string | undefined> {
|
|
34
|
-
return Promise.resolve(process.env.TSS_TOKEN)
|
|
34
|
+
return process.env.TSS_TOKEN ? Promise.resolve(process.env.TSS_TOKEN) : this.cache.get(AuthModule.cacheKey);
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
setToken(token: string, lifetime?: number) {
|
|
38
38
|
return this.cache.set(AuthModule.cacheKey, token, lifetime);
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
async setCode(code: string) {
|
|
42
|
-
// TODO any ?!
|
|
43
|
-
const { accessToken } = await this.api.post<any>(`auth/setCode?code=${code}`, {}, { credentials: 'include' });
|
|
44
|
-
return accessToken;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
41
|
removeToken() {
|
|
48
42
|
return this.cache.remove(AuthModule.cacheKey);
|
|
49
43
|
}
|
package/src/api/jingle.ts
CHANGED
|
@@ -28,9 +28,9 @@ export class JingleModule extends BaseModule {
|
|
|
28
28
|
return jingles.sort((a, b) => b.mtime - a.mtime).slice(0, 30);
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
play(playJingleDto: PlayJingleDto) {
|
|
31
|
+
play(playJingleDto: PlayJingleDto): Promise<{ success: boolean }> {
|
|
32
32
|
console.log(`Playing jingle ${playJingleDto.folder}/${playJingleDto.file}`);
|
|
33
|
-
return this.api.post('jingle/play', playJingleDto);
|
|
33
|
+
return this.api.post<{ success: boolean }>('jingle/play', playJingleDto);
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
getBigBrotherData(): Promise<BigBrotherItem[]> {
|
|
@@ -38,11 +38,11 @@ export class JingleModule extends BaseModule {
|
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
async find(query: string, jingles: Jingle[] = []): Promise<Jingle[]> {
|
|
41
|
-
|
|
41
|
+
const items = jingles.length > 0 ? jingles : await this.getAll();
|
|
42
42
|
|
|
43
43
|
const queryParts = query.split(' ');
|
|
44
|
-
const matches =
|
|
45
|
-
queryParts.every((queryPart) =>
|
|
44
|
+
const matches = items.filter((jingle) =>
|
|
45
|
+
queryParts.every((queryPart) => `${jingle.folder}/${jingle.file}`.includes(queryPart)),
|
|
46
46
|
);
|
|
47
47
|
|
|
48
48
|
return matches.sort((a, b) => {
|
package/src/api/k8s.ts
CHANGED
package/src/api/user.ts
CHANGED
|
@@ -3,19 +3,19 @@ import { BaseModule } from './base';
|
|
|
3
3
|
|
|
4
4
|
export class UserModule extends BaseModule {
|
|
5
5
|
async get(userId?: string) {
|
|
6
|
-
return this.cache.cacheOrGet(() => {
|
|
6
|
+
return await this.cache.cacheOrGet(() => {
|
|
7
7
|
const userIdParam = userId ? `/${userId}` : '';
|
|
8
8
|
return this.api.get<User>(`user${userIdParam}`);
|
|
9
9
|
});
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
async getAll() {
|
|
13
|
-
return this.cache.cacheOrGet(() => {
|
|
13
|
+
return await this.cache.cacheOrGet(() => {
|
|
14
14
|
return this.api.get<User[]>('user/all');
|
|
15
15
|
});
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
async setWindowState(setWindowStateDto: SetWindowStateDto) {
|
|
19
|
-
return this.api.putPossibleEmptyResponse('user/windowState', setWindowStateDto);
|
|
19
|
+
return await this.api.putPossibleEmptyResponse('user/windowState', setWindowStateDto);
|
|
20
20
|
}
|
|
21
21
|
}
|
|
@@ -1,61 +1,70 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import os from 'os';
|
|
3
|
-
import path from 'path';
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
4
|
import { AbstractCache } from './abstractCache';
|
|
5
5
|
|
|
6
|
-
type CacheItem = {
|
|
7
|
-
value:
|
|
6
|
+
type CacheItem<T> = {
|
|
7
|
+
value: T;
|
|
8
8
|
expiresAt?: number;
|
|
9
9
|
};
|
|
10
10
|
|
|
11
|
-
export class FilesystemCache extends AbstractCache {
|
|
11
|
+
export class FilesystemCache<T = unknown> extends AbstractCache {
|
|
12
12
|
protected initialized = false;
|
|
13
13
|
|
|
14
|
-
protected state
|
|
14
|
+
protected state = new Map<string, CacheItem<T>>();
|
|
15
15
|
|
|
16
16
|
public async cacheOrGet<T>(callbackWhenEmpty: () => Promise<T>, key?: string, lifetime?: number): Promise<T> {
|
|
17
|
-
|
|
17
|
+
const usedKey = key ?? this.getCacheKey();
|
|
18
18
|
|
|
19
|
-
const cachedValue = await this.get<T>(
|
|
19
|
+
const cachedValue = await this.get<T>(usedKey);
|
|
20
20
|
if (cachedValue) {
|
|
21
21
|
return cachedValue;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
const result = await callbackWhenEmpty();
|
|
25
|
-
this.set(
|
|
25
|
+
this.set(usedKey, result, lifetime);
|
|
26
26
|
return result;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
public
|
|
29
|
+
public get<T>(key: string): Promise<T | undefined> {
|
|
30
30
|
if (!this.initialized) {
|
|
31
|
-
|
|
31
|
+
this._initialize();
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
const item = this.state.get(key);
|
|
35
|
+
|
|
36
|
+
if (item) {
|
|
37
|
+
const expires = item.expiresAt;
|
|
38
|
+
if (expires === undefined || expires > Date.now()) {
|
|
39
|
+
return Promise.resolve(item.value as unknown as T);
|
|
40
|
+
}
|
|
37
41
|
}
|
|
38
42
|
|
|
39
|
-
return undefined;
|
|
43
|
+
return Promise.resolve(undefined);
|
|
40
44
|
}
|
|
41
45
|
|
|
42
46
|
public set<T>(key: string, value: T, lifetime?: number): void {
|
|
43
47
|
const expiresAt = lifetime ? Date.now() + lifetime : undefined;
|
|
44
|
-
|
|
48
|
+
|
|
49
|
+
// 'content' is typed as the Method's T
|
|
50
|
+
const content: CacheItem<T> = { value };
|
|
45
51
|
if (expiresAt) {
|
|
46
52
|
content.expiresAt = expiresAt;
|
|
47
53
|
}
|
|
48
|
-
|
|
54
|
+
|
|
55
|
+
// biome-ignore lint/suspicious/noExplicitAny: hier mag alles
|
|
56
|
+
this.state.set(key, content as any);
|
|
57
|
+
|
|
49
58
|
this.writeState();
|
|
50
59
|
}
|
|
51
60
|
|
|
52
61
|
public remove(key: string): void {
|
|
53
|
-
|
|
62
|
+
this.state.delete(key);
|
|
54
63
|
this.writeState();
|
|
55
64
|
}
|
|
56
65
|
|
|
57
66
|
public clear(): void {
|
|
58
|
-
this.state
|
|
67
|
+
this.state.clear();
|
|
59
68
|
if (fs.existsSync(this.getFilePath())) {
|
|
60
69
|
fs.unlinkSync(this.getFilePath());
|
|
61
70
|
}
|
|
@@ -68,15 +77,22 @@ export class FilesystemCache extends AbstractCache {
|
|
|
68
77
|
protected _initialize() {
|
|
69
78
|
this.initialized = true;
|
|
70
79
|
if (fs.existsSync(this.getFilePath())) {
|
|
71
|
-
|
|
80
|
+
try {
|
|
81
|
+
const fileContent = fs.readFileSync(this.getFilePath(), 'utf8');
|
|
82
|
+
const parsed = JSON.parse(fileContent);
|
|
83
|
+
this.state = new Map(Object.entries(parsed)) as Map<string, CacheItem<T>>;
|
|
84
|
+
} catch (_e) {
|
|
85
|
+
this.state = new Map();
|
|
86
|
+
}
|
|
72
87
|
}
|
|
73
88
|
}
|
|
74
89
|
|
|
75
90
|
protected writeState() {
|
|
76
91
|
if (!fs.existsSync(path.dirname(this.getFilePath()))) {
|
|
77
|
-
fs.mkdirSync(path.dirname(this.getFilePath()));
|
|
92
|
+
fs.mkdirSync(path.dirname(this.getFilePath()), { recursive: true });
|
|
78
93
|
}
|
|
79
94
|
|
|
80
|
-
|
|
95
|
+
const plainObject = Object.fromEntries(this.state);
|
|
96
|
+
fs.writeFileSync(this.getFilePath(), JSON.stringify(plainObject));
|
|
81
97
|
}
|
|
82
98
|
}
|
package/src/cache/nullCache.ts
CHANGED
|
@@ -25,8 +25,8 @@ export class OnePasswordCache extends AbstractCache {
|
|
|
25
25
|
let action = `op item edit '${key}' 'credential=${value}'`;
|
|
26
26
|
|
|
27
27
|
try {
|
|
28
|
-
|
|
29
|
-
} catch (
|
|
28
|
+
await this.get(key);
|
|
29
|
+
} catch (_e) {
|
|
30
30
|
action = `op item create --category="API Credential" --title ${key} 'credential=${value}'`;
|
|
31
31
|
}
|
|
32
32
|
|
package/src/index.ts
CHANGED
|
@@ -76,7 +76,7 @@ export class TssApi {
|
|
|
76
76
|
let response: Response;
|
|
77
77
|
try {
|
|
78
78
|
response = await fetch(fullUrl, config);
|
|
79
|
-
} catch (
|
|
79
|
+
} catch (_e) {
|
|
80
80
|
throw new ErrorResponse(503, 'API erg dood');
|
|
81
81
|
}
|
|
82
82
|
|
|
@@ -88,7 +88,7 @@ export class TssApi {
|
|
|
88
88
|
return response;
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
protected fetchPossibleEmptyResponse
|
|
91
|
+
protected fetchPossibleEmptyResponse(method: HttpMethod, url: string, dto: Dto, config: SDKRequestInit = {}) {
|
|
92
92
|
return this.fetch(url, {
|
|
93
93
|
method,
|
|
94
94
|
...config,
|
|
@@ -96,13 +96,13 @@ export class TssApi {
|
|
|
96
96
|
});
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
-
async get<T>(url: string) {
|
|
99
|
+
async get<T>(url: string): Promise<T> {
|
|
100
100
|
const response = await this.fetch(url);
|
|
101
|
-
return response.json() as Promise<T>;
|
|
101
|
+
return (await response.json()) as Promise<T>;
|
|
102
102
|
}
|
|
103
103
|
|
|
104
104
|
async post<T>(url: string, dto: Dto, config: SDKRequestInit = {}) {
|
|
105
|
-
const response = await this.fetchPossibleEmptyResponse
|
|
105
|
+
const response = await this.fetchPossibleEmptyResponse('POST', url, dto, config);
|
|
106
106
|
if (response === undefined) {
|
|
107
107
|
throw new Error('Response was undefined');
|
|
108
108
|
}
|
|
@@ -114,7 +114,7 @@ export class TssApi {
|
|
|
114
114
|
}
|
|
115
115
|
|
|
116
116
|
async put<T>(url: string, dto: Dto) {
|
|
117
|
-
const response = await this.fetchPossibleEmptyResponse
|
|
117
|
+
const response = await this.fetchPossibleEmptyResponse('PUT', url, dto);
|
|
118
118
|
if (response === undefined) {
|
|
119
119
|
throw new Error('Response was undefined');
|
|
120
120
|
}
|
|
@@ -125,7 +125,7 @@ export class TssApi {
|
|
|
125
125
|
return this.fetchPossibleEmptyResponse('PUT', url, dto);
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
-
delete
|
|
128
|
+
delete(url: string, config: SDKRequestInit = {}) {
|
|
129
129
|
return this.fetch(url, {
|
|
130
130
|
method: 'DELETE',
|
|
131
131
|
...config,
|
package/test/api/jingle.test.ts
CHANGED
|
@@ -28,7 +28,7 @@ describe('Jingle API', () => {
|
|
|
28
28
|
});
|
|
29
29
|
|
|
30
30
|
it('Plays a jingle', async () => {
|
|
31
|
-
const result
|
|
31
|
+
const result = await api.jingle.play({ folder: 'keeskankerkachel', file: 'aan.mp3' });
|
|
32
32
|
expect(result.success).toBe(true);
|
|
33
33
|
});
|
|
34
34
|
});
|