@pelican.ts/sdk 0.2.1 → 0.2.3

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/dist/index.js ADDED
@@ -0,0 +1,1055 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ PelicanApplication: () => PelicanApplication,
34
+ PelicanClient: () => PelicanClient
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+
38
+ // src/api/client/account.ts
39
+ var import_zod = __toESM(require("zod"));
40
+ var Account = class {
41
+ r;
42
+ constructor(requester) {
43
+ this.r = requester;
44
+ }
45
+ info = async () => {
46
+ const { data } = await this.r.get("/account");
47
+ return data.attributes;
48
+ };
49
+ updateEmail = async (newEmail, password) => {
50
+ newEmail = import_zod.default.email().parse(newEmail);
51
+ await this.r.put("/account/email", { email: newEmail, password });
52
+ };
53
+ updatePassword = async (newPassword) => {
54
+ newPassword = import_zod.default.string().min(8).parse(newPassword);
55
+ await this.r.put("/account/password", {
56
+ password: newPassword,
57
+ password_confirmation: newPassword
58
+ });
59
+ };
60
+ apiKeys = {
61
+ list: async () => {
62
+ const { data } = await this.r.get("/account/api-keys");
63
+ return data.data.map((k) => k.attributes);
64
+ },
65
+ create: async (description, allowed_ips) => {
66
+ allowed_ips = import_zod.default.array(import_zod.default.ipv4()).optional().parse(allowed_ips);
67
+ const { data } = await this.r.post("/account/api-keys", { description, allowed_ips });
68
+ return { ...data.attributes, secret_token: data.meta.secret_token };
69
+ },
70
+ delete: async (identifier) => {
71
+ await this.r.delete(`/account/api-keys/${identifier}`);
72
+ }
73
+ };
74
+ sshKeys = {
75
+ list: async () => {
76
+ const { data } = await this.r.get("/account/ssh-keys");
77
+ return data.data.map((k) => k.attributes);
78
+ },
79
+ create: async (name, public_key) => {
80
+ const { data } = await this.r.post("/account/ssh-keys", { name, public_key });
81
+ return data.attributes;
82
+ },
83
+ delete: async (fingerprint) => {
84
+ await this.r.post(`/account/ssh-keys/remove`, { fingerprint });
85
+ }
86
+ };
87
+ twoFactor = {
88
+ info: async () => {
89
+ const { data } = await this.r.get("/account/two-factor");
90
+ return data;
91
+ },
92
+ enable: async (code) => {
93
+ const { data } = await this.r.post("/account/two-factor", { code });
94
+ return data;
95
+ },
96
+ disable: async (password) => {
97
+ await this.r.delete("/account/two-factor", { data: { password } });
98
+ }
99
+ };
100
+ };
101
+
102
+ // src/api/client/client.ts
103
+ var import_zod5 = __toESM(require("zod"));
104
+
105
+ // src/api/client/server_databases.ts
106
+ var import_zod2 = __toESM(require("zod"));
107
+ var ServerDatabases = class {
108
+ r;
109
+ id;
110
+ constructor(requester, id) {
111
+ this.r = requester;
112
+ this.id = id;
113
+ }
114
+ list = async (include, page = 1) => {
115
+ import_zod2.default.number().positive().parse(page);
116
+ const { data } = await this.r.get(`/servers/${this.id}/databases`, {
117
+ params: { include: include?.join(","), page }
118
+ });
119
+ return data.data.map((d) => d.attributes);
120
+ };
121
+ create = async (database, remote) => {
122
+ const { data } = await this.r.post(`/servers/${this.id}/databases`, { database, remote });
123
+ return data.attributes;
124
+ };
125
+ rotatePassword = async (database_id) => {
126
+ const { data } = await this.r.post(`/servers/${this.id}/databases/${database_id}/rotate-password`);
127
+ return data.attributes;
128
+ };
129
+ delete = async (database_id) => {
130
+ await this.r.delete(`/servers/${this.id}/databases/${database_id}`);
131
+ };
132
+ };
133
+
134
+ // src/api/client/server_files.ts
135
+ var import_axios = __toESM(require("axios"));
136
+ var ServerFiles = class {
137
+ r;
138
+ id;
139
+ constructor(requester, id) {
140
+ this.r = requester;
141
+ this.id = id;
142
+ }
143
+ list = async (path) => {
144
+ const { data } = await this.r.get(`/servers/${this.id}/files/list`, {
145
+ params: { directory: path }
146
+ });
147
+ return data.data.map((r) => r.attributes);
148
+ };
149
+ /**
150
+ * Return the contents of a file. To read binary file (non-editable) use {@link download} instead
151
+ */
152
+ contents = async (path) => {
153
+ const { data } = await this.r.get(`/servers/${this.id}/files/contents`, {
154
+ params: { file: path }
155
+ });
156
+ return data;
157
+ };
158
+ downloadGetUrl = async (path) => {
159
+ const { data } = await this.r.get(`/servers/${this.id}/files/download`, {
160
+ params: { file: path }
161
+ });
162
+ return data.attributes.url;
163
+ };
164
+ download = async (path) => {
165
+ const url = await this.downloadGetUrl(path);
166
+ const { data } = await import_axios.default.get(url, { responseType: "arraybuffer" });
167
+ return data;
168
+ };
169
+ rename = async (root = "/", files) => {
170
+ await this.r.put(`/servers/${this.id}/files/rename`, { root, files });
171
+ };
172
+ copy = async (location) => {
173
+ await this.r.post(`/servers/${this.id}/files/copy`, { location });
174
+ };
175
+ write = async (path, content) => {
176
+ await this.r.post(`/servers/${this.id}/files/write`, content, {
177
+ params: { file: path }
178
+ });
179
+ };
180
+ compress = async (root = "/", files, archive_name, extension) => {
181
+ await this.r.post(`/servers/${this.id}/files/compress`, { root, files, archive_name, extension });
182
+ };
183
+ decompress = async (root = "/", file) => {
184
+ await this.r.post(`/servers/${this.id}/files/decompress`, { root, file });
185
+ };
186
+ delete = async (root = "/", files) => {
187
+ await this.r.post(`/servers/${this.id}/files/delete`, { root, files });
188
+ };
189
+ createFolder = async (root = "/", name) => {
190
+ await this.r.post(`/servers/${this.id}/files/create-folder`, { root, name });
191
+ };
192
+ chmod = async (root = "/", files) => {
193
+ await this.r.post(`/servers/${this.id}/files/chmod`, { root, files });
194
+ };
195
+ pullFromRemote = async (url, directory, filename, use_header = false, foreground = false) => {
196
+ await this.r.post(`/servers/${this.id}/files/pull`, { url, directory, filename, use_header, foreground });
197
+ };
198
+ uploadGetUrl = async () => {
199
+ const { data } = await this.r.get(`/servers/${this.id}/files/upload`);
200
+ return data.attributes.url;
201
+ };
202
+ upload = async (file, root = "/") => {
203
+ const url = await this.uploadGetUrl();
204
+ await import_axios.default.post(url, { files: file }, {
205
+ headers: { "Content-Type": "multipart/form-data" },
206
+ params: { directory: root }
207
+ });
208
+ };
209
+ };
210
+
211
+ // src/api/client/server_schedules.ts
212
+ var ServerSchedules = class {
213
+ r;
214
+ id;
215
+ constructor(requester, id) {
216
+ this.r = requester;
217
+ this.id = id;
218
+ }
219
+ list = async () => {
220
+ const { data } = await this.r.get(`/servers/${this.id}/schedules`);
221
+ return data.data.map((d) => d.attributes);
222
+ };
223
+ create = async (params) => {
224
+ const { data } = await this.r.post(`/servers/${this.id}/schedules`, params);
225
+ return data.attributes;
226
+ };
227
+ control = (sched_id) => new ScheduleControl(this.r, this.id, sched_id);
228
+ };
229
+ var ScheduleControl = class {
230
+ r;
231
+ id;
232
+ sched_id;
233
+ constructor(requester, id, sched_id) {
234
+ this.r = requester;
235
+ this.id = id;
236
+ this.sched_id = sched_id;
237
+ }
238
+ info = async () => {
239
+ const { data } = await this.r.get(`/servers/${this.id}/schedules/${this.sched_id}`);
240
+ return data.attributes;
241
+ };
242
+ update = async (params) => {
243
+ const { data } = await this.r.post(`/servers/${this.id}/schedules/${this.sched_id}`, params);
244
+ return data.attributes;
245
+ };
246
+ delete = async () => {
247
+ await this.r.delete(`/servers/${this.id}/schedules/${this.sched_id}`);
248
+ };
249
+ execute = async () => {
250
+ await this.r.post(`/servers/${this.id}/schedules/${this.sched_id}/execute`);
251
+ };
252
+ tasks = {
253
+ create: async (opts) => {
254
+ const { data } = await this.r.post(`/servers/${this.id}/schedules/${this.sched_id}/tasks`, opts);
255
+ return data.attributes;
256
+ },
257
+ update: async (task_id, opts) => {
258
+ const { data } = await this.r.post(`/servers/${this.id}/schedules/${this.sched_id}/tasks/${task_id}`, opts);
259
+ return data.attributes;
260
+ },
261
+ delete: async (task_id) => {
262
+ await this.r.delete(`/servers/${this.id}/schedules/${this.sched_id}/tasks/${task_id}`);
263
+ }
264
+ };
265
+ };
266
+
267
+ // src/api/client/server_allocations.ts
268
+ var ServerAllocations = class {
269
+ r;
270
+ id;
271
+ constructor(requester, id) {
272
+ this.r = requester;
273
+ this.id = id;
274
+ }
275
+ list = async () => {
276
+ const { data } = await this.r.get(`/servers/${this.id}/network/allocations`);
277
+ return data.data.map((r) => r.attributes);
278
+ };
279
+ autoAssign = async () => {
280
+ const { data } = await this.r.post(`/servers/${this.id}/network/allocations`);
281
+ return data.attributes;
282
+ };
283
+ setNotes = async (alloc_id, notes) => {
284
+ const { data } = await this.r.post(`/servers/${this.id}/network/allocations/${alloc_id}`, { notes });
285
+ return data.attributes;
286
+ };
287
+ setPrimary = async (alloc_id) => {
288
+ const { data } = await this.r.post(`/servers/${this.id}/network/allocations/${alloc_id}/primary`);
289
+ return data.attributes;
290
+ };
291
+ unassign = async (alloc_id) => {
292
+ await this.r.delete(`/servers/${this.id}/network/allocations/${alloc_id}`);
293
+ };
294
+ };
295
+
296
+ // src/api/client/server_users.ts
297
+ var ServerUsers = class {
298
+ r;
299
+ id;
300
+ constructor(requester, id) {
301
+ this.r = requester;
302
+ this.id = id;
303
+ }
304
+ list = async () => {
305
+ const { data } = await this.r.get(`/servers/${this.id}/users`);
306
+ return data.data.map((d) => d.attributes);
307
+ };
308
+ create = async (email, permissions) => {
309
+ const { data } = await this.r.post(`/servers/${this.id}/users`, { email, permissions });
310
+ return data.attributes;
311
+ };
312
+ info = async (user_id) => {
313
+ const { data } = await this.r.get(`/servers/${this.id}/users/${user_id}`);
314
+ return data.attributes;
315
+ };
316
+ update = async (user_id, permissions) => {
317
+ const { data } = await this.r.put(`/servers/${this.id}/users/${user_id}`, { permissions });
318
+ return data.attributes;
319
+ };
320
+ delete = async (user_id) => {
321
+ await this.r.delete(`/servers/${this.id}/users/${user_id}`);
322
+ };
323
+ };
324
+
325
+ // src/api/client/server_backups.ts
326
+ var import_axios2 = __toESM(require("axios"));
327
+ var import_zod3 = __toESM(require("zod"));
328
+ var ServerBackups = class {
329
+ r;
330
+ id;
331
+ constructor(requester, id) {
332
+ this.r = requester;
333
+ this.id = id;
334
+ }
335
+ list = async (page = 1) => {
336
+ import_zod3.default.number().positive().parse(page);
337
+ const { data } = await this.r.get(`/servers/${this.id}/backups`, {
338
+ params: { page }
339
+ });
340
+ return data.data.map((d) => d.attributes);
341
+ };
342
+ create = async (args) => {
343
+ args.name = import_zod3.default.string().max(255).optional().parse(args.name);
344
+ const { data } = await this.r.post(`/servers/${this.id}/backups`, {
345
+ name: args.name,
346
+ is_locked: args.is_locked,
347
+ ignored_files: args.ignored_files.join("\n")
348
+ });
349
+ return data.attributes;
350
+ };
351
+ info = async (backup_uuid) => {
352
+ const { data } = await this.r.get(`/servers/${this.id}/backups/${backup_uuid}`);
353
+ return data.attributes;
354
+ };
355
+ downloadGetUrl = async (backup_uuid) => {
356
+ const { data } = await this.r.get(`/servers/${this.id}/backups/${backup_uuid}/download`);
357
+ return data.attributes.url;
358
+ };
359
+ download = async (backup_uuid) => {
360
+ const url = await this.downloadGetUrl(backup_uuid);
361
+ const { data } = await import_axios2.default.get(url, { responseType: "arraybuffer" });
362
+ return data;
363
+ };
364
+ delete = async (backup_uuid) => {
365
+ await this.r.delete(`/servers/${this.id}/backups/${backup_uuid}`);
366
+ };
367
+ };
368
+
369
+ // src/api/client/server_startup.ts
370
+ var ServerStartup = class {
371
+ r;
372
+ id;
373
+ constructor(requester, id) {
374
+ this.r = requester;
375
+ this.id = id;
376
+ }
377
+ list = async () => {
378
+ const { data } = await this.r.get(`/servers/${this.id}/startup`);
379
+ return {
380
+ object: "list",
381
+ meta: data.meta,
382
+ data: data.data.map((d) => d.attributes)
383
+ };
384
+ };
385
+ set = async (key, value) => {
386
+ const { data } = await this.r.put(`/servers/${this.id}/startup/variable`, { key, value });
387
+ return data.attributes;
388
+ };
389
+ };
390
+
391
+ // src/api/client/server_settings.ts
392
+ var import_zod4 = __toESM(require("zod"));
393
+ var ServerSettings = class {
394
+ r;
395
+ id;
396
+ constructor(requester, id) {
397
+ this.r = requester;
398
+ this.id = id;
399
+ }
400
+ rename = async (name) => {
401
+ name = import_zod4.default.string().max(255).parse(name);
402
+ await this.r.post(`/servers/${this.id}/settings/rename`, { name });
403
+ };
404
+ updateDescription = async (description) => {
405
+ await this.r.post(`/servers/${this.id}/settings/description`, { description });
406
+ };
407
+ reinstall = async () => {
408
+ await this.r.post(`/servers/${this.id}/settings/reinstall`);
409
+ };
410
+ changeDockerImage = async (image) => {
411
+ await this.r.post(`/servers/${this.id}/settings/docker-image`, { image });
412
+ };
413
+ };
414
+
415
+ // src/api/client/server_websocket.ts
416
+ var import_events = require("events");
417
+ var import_isomorphic_ws = __toESM(require("isomorphic-ws"));
418
+ var import_strip_color = __toESM(require("strip-color"));
419
+ var isBrowser = typeof window !== "undefined";
420
+ var RECONNECT_ERRORS = /* @__PURE__ */ new Set([
421
+ "jwt: exp claim is invalid",
422
+ "jwt: created too far in past (denylist)"
423
+ ]);
424
+ var FALLBACK_LOG_MESSAGE = "No logs - is the server online?";
425
+ var ServerWebsocket = class {
426
+ r;
427
+ serverId;
428
+ socket;
429
+ currentToken;
430
+ bus = new import_events.EventEmitter();
431
+ debugLogging = false;
432
+ stripColors;
433
+ detachMessageListener;
434
+ constructor(requester, id, stripColors = false) {
435
+ this.r = requester;
436
+ this.serverId = id;
437
+ this.stripColors = stripColors;
438
+ }
439
+ on(event, listener) {
440
+ const handler = listener;
441
+ this.bus.on(event, handler);
442
+ return () => {
443
+ this.bus.removeListener(event, handler);
444
+ };
445
+ }
446
+ deregister(event, listener) {
447
+ const handler = listener;
448
+ this.bus.removeListener(event, handler);
449
+ }
450
+ emit(event, ...args) {
451
+ if (args.length === 0) {
452
+ this.bus.emit(event);
453
+ } else {
454
+ this.bus.emit(event, args[0]);
455
+ }
456
+ }
457
+ async connect(resumable, debugLogging) {
458
+ this.debugLogging = debugLogging ?? false;
459
+ if (this.socket) {
460
+ return;
461
+ }
462
+ const socketUrl = await this.refreshCredentials();
463
+ this.socket = isBrowser ? new import_isomorphic_ws.default(socketUrl) : new import_isomorphic_ws.default(socketUrl, void 0, { origin: new URL(socketUrl).origin });
464
+ await new Promise((resolve, reject) => {
465
+ const socket = this.socket;
466
+ if (!socket) {
467
+ reject(new Error("Failed to create socket connection"));
468
+ return;
469
+ }
470
+ socket.onopen = async () => {
471
+ try {
472
+ await this.authenticate();
473
+ this.attachMessageListener();
474
+ socket.onopen = null;
475
+ socket.onerror = null;
476
+ resolve();
477
+ } catch (error) {
478
+ socket.onopen = null;
479
+ socket.onerror = null;
480
+ reject(error instanceof Error ? error : new Error("Websocket authentication failed"));
481
+ }
482
+ };
483
+ socket.onerror = (event) => {
484
+ socket.onopen = null;
485
+ socket.onerror = null;
486
+ reject(event instanceof Error ? event : new Error("Websocket connection error"));
487
+ };
488
+ });
489
+ if (resumable) {
490
+ this.makeResumable(true);
491
+ }
492
+ }
493
+ onSocketDisconnect(handler) {
494
+ if (!this.socket) {
495
+ console.error(new Error("No socket connection"));
496
+ return;
497
+ }
498
+ this.socket.onclose = handler;
499
+ }
500
+ onSocketError(handler) {
501
+ if (!this.socket) {
502
+ console.error(new Error("No socket connection"));
503
+ return;
504
+ }
505
+ this.socket.onerror = handler;
506
+ }
507
+ makeResumable(disconnectsToo) {
508
+ const scheduleReconnect = () => {
509
+ setTimeout(() => {
510
+ const previous = this.socket;
511
+ this.detachMessageListener?.();
512
+ this.detachMessageListener = void 0;
513
+ this.socket = void 0;
514
+ previous?.close();
515
+ void this.connect(true, this.debugLogging);
516
+ }, 1e3);
517
+ };
518
+ this.onSocketError(() => scheduleReconnect());
519
+ if (disconnectsToo) {
520
+ this.onSocketDisconnect(() => scheduleReconnect());
521
+ }
522
+ }
523
+ attachMessageListener() {
524
+ if (!this.socket) {
525
+ throw new Error("No socket connection");
526
+ }
527
+ this.detachMessageListener?.();
528
+ const handler = (event) => {
529
+ void this.handleIncomingMessage(event);
530
+ };
531
+ if (typeof this.socket.addEventListener === "function") {
532
+ this.socket.addEventListener("message", handler);
533
+ this.detachMessageListener = () => {
534
+ this.socket?.removeEventListener?.("message", handler);
535
+ };
536
+ } else {
537
+ const fallback = (data) => handler({ data });
538
+ const socket = this.socket;
539
+ socket.on?.("message", fallback);
540
+ this.detachMessageListener = () => {
541
+ const target = this.socket;
542
+ if (!target) {
543
+ return;
544
+ }
545
+ if (typeof target.off === "function") {
546
+ target.off("message", fallback);
547
+ } else if (typeof target.removeListener === "function") {
548
+ target.removeListener("message", fallback);
549
+ }
550
+ };
551
+ }
552
+ }
553
+ async handleIncomingMessage(event) {
554
+ const message = this.parseMessage(event);
555
+ if (!message) {
556
+ return;
557
+ }
558
+ try {
559
+ await this.dispatchMessage(message);
560
+ } catch (error) {
561
+ if (this.debugLogging) {
562
+ console.error("Error while handling websocket message", error);
563
+ }
564
+ }
565
+ }
566
+ parseMessage(event) {
567
+ const payload = this.normalisePayload(event);
568
+ if (!payload) {
569
+ return null;
570
+ }
571
+ try {
572
+ return JSON.parse(payload);
573
+ } catch (error) {
574
+ if (this.debugLogging) {
575
+ console.warn("Failed to parse websocket payload", error);
576
+ }
577
+ return null;
578
+ }
579
+ }
580
+ normalisePayload(event) {
581
+ if (typeof event === "string") {
582
+ return event;
583
+ }
584
+ if (typeof event === "object" && event !== null && "data" in event) {
585
+ return this.normalisePayload(event.data);
586
+ }
587
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(event)) {
588
+ return event.toString("utf8");
589
+ }
590
+ if (typeof ArrayBuffer !== "undefined" && event instanceof ArrayBuffer) {
591
+ if (typeof TextDecoder !== "undefined") {
592
+ return new TextDecoder().decode(new Uint8Array(event));
593
+ }
594
+ if (typeof Buffer !== "undefined") {
595
+ return Buffer.from(event).toString("utf8");
596
+ }
597
+ }
598
+ return null;
599
+ }
600
+ async dispatchMessage(message) {
601
+ switch (message.event) {
602
+ case "auth success" /* AUTH_SUCCESS */: {
603
+ if (this.debugLogging) {
604
+ console.debug("Auth success");
605
+ }
606
+ this.emit("auth success" /* AUTH_SUCCESS */);
607
+ break;
608
+ }
609
+ case "status" /* STATUS */: {
610
+ if (this.debugLogging) {
611
+ console.debug("Received status event", message.args[0]);
612
+ }
613
+ this.emit("status" /* STATUS */, message.args[0]);
614
+ break;
615
+ }
616
+ case "console output" /* CONSOLE_OUTPUT */: {
617
+ let output = message.args[0];
618
+ if (this.stripColors) {
619
+ output = (0, import_strip_color.default)(output);
620
+ }
621
+ if (this.debugLogging) {
622
+ console.debug("Received console output", output);
623
+ }
624
+ this.emit("console output" /* CONSOLE_OUTPUT */, output);
625
+ break;
626
+ }
627
+ case "stats" /* STATS */: {
628
+ try {
629
+ const payload = JSON.parse(message.args[0]);
630
+ this.emit("stats" /* STATS */, payload);
631
+ } catch (error) {
632
+ if (this.debugLogging) {
633
+ console.warn("Failed to parse stats payload", error);
634
+ }
635
+ }
636
+ break;
637
+ }
638
+ case "daemon error" /* DAEMON_ERROR */: {
639
+ this.emit("daemon error" /* DAEMON_ERROR */);
640
+ break;
641
+ }
642
+ case "backup completed" /* BACKUP_COMPLETED */: {
643
+ try {
644
+ const payload = JSON.parse(message.args[0]);
645
+ this.emit("backup completed" /* BACKUP_COMPLETED */, payload);
646
+ } catch (error) {
647
+ if (this.debugLogging) {
648
+ console.warn("Failed to parse backup payload", error);
649
+ }
650
+ }
651
+ break;
652
+ }
653
+ case "daemon message" /* DAEMON_MESSAGE */: {
654
+ let output = message.args[0];
655
+ if (this.stripColors) {
656
+ output = (0, import_strip_color.default)(output);
657
+ }
658
+ this.emit("daemon message" /* DAEMON_MESSAGE */, output);
659
+ break;
660
+ }
661
+ case "install output" /* INSTALL_OUTPUT */: {
662
+ let output = message.args[0];
663
+ if (this.stripColors) {
664
+ output = (0, import_strip_color.default)(output);
665
+ }
666
+ this.emit("install output" /* INSTALL_OUTPUT */, output);
667
+ break;
668
+ }
669
+ case "backup restore completed" /* BACKUP_RESTORE_COMPLETED */: {
670
+ this.emit("backup restore completed" /* BACKUP_RESTORE_COMPLETED */);
671
+ break;
672
+ }
673
+ case "install completed" /* INSTALL_COMPLETED */: {
674
+ this.emit("install completed" /* INSTALL_COMPLETED */);
675
+ break;
676
+ }
677
+ case "install started" /* INSTALL_STARTED */: {
678
+ this.emit("install started" /* INSTALL_STARTED */);
679
+ break;
680
+ }
681
+ case "transfer logs" /* TRANSFER_LOGS */: {
682
+ this.emit("transfer logs" /* TRANSFER_LOGS */, message.args[0]);
683
+ break;
684
+ }
685
+ case "transfer status" /* TRANSFER_STATUS */: {
686
+ this.emit("transfer status" /* TRANSFER_STATUS */, message.args[0]);
687
+ break;
688
+ }
689
+ case "token expiring" /* TOKEN_EXPIRING */: {
690
+ this.emit("token expiring" /* TOKEN_EXPIRING */);
691
+ if (this.debugLogging) {
692
+ console.warn("Token expiring, renewing...");
693
+ }
694
+ await this.refreshCredentials();
695
+ await this.authenticate();
696
+ break;
697
+ }
698
+ case "token expired" /* TOKEN_EXPIRED */: {
699
+ this.emit("token expired" /* TOKEN_EXPIRED */);
700
+ throw new Error("Token expired");
701
+ }
702
+ case "jwt error" /* JWT_ERROR */: {
703
+ const reason = message.args[0];
704
+ if (RECONNECT_ERRORS.has(reason)) {
705
+ this.emit("token expiring" /* TOKEN_EXPIRING */);
706
+ if (this.debugLogging) {
707
+ console.warn("Token expiring (JWT error), renewing...");
708
+ }
709
+ await this.refreshCredentials();
710
+ await this.authenticate();
711
+ } else {
712
+ this.emit("jwt error" /* JWT_ERROR */, reason);
713
+ throw new Error("Token expired");
714
+ }
715
+ break;
716
+ }
717
+ default: {
718
+ if (this.debugLogging) {
719
+ console.warn("Unknown websocket event", message);
720
+ }
721
+ break;
722
+ }
723
+ }
724
+ }
725
+ async refreshCredentials() {
726
+ const { data } = await this.r.get(`/servers/${this.serverId}/websocket`);
727
+ this.currentToken = data.data.token;
728
+ return data.data.socket;
729
+ }
730
+ async authenticate() {
731
+ if (!this.socket) {
732
+ throw new Error("No socket connection");
733
+ }
734
+ if (!this.currentToken) {
735
+ throw new Error("Missing websocket token");
736
+ }
737
+ this.socket.send(JSON.stringify({ event: "auth", args: [this.currentToken] }));
738
+ }
739
+ disconnect() {
740
+ this.detachMessageListener?.();
741
+ this.detachMessageListener = void 0;
742
+ if (this.socket) {
743
+ this.socket.close();
744
+ this.socket = void 0;
745
+ }
746
+ }
747
+ requestStats() {
748
+ this.send("send stats", [null]);
749
+ }
750
+ requestLogs() {
751
+ this.send("send logs", [null]);
752
+ }
753
+ send(event, args) {
754
+ if (!this.socket) {
755
+ if (this.debugLogging) {
756
+ console.warn(`Attempted to send "${event}" without an active websocket connection`);
757
+ }
758
+ return;
759
+ }
760
+ this.socket.send(JSON.stringify({ event, args }));
761
+ }
762
+ getStats() {
763
+ return new Promise((resolve, reject) => {
764
+ if (!this.socket) {
765
+ reject(new Error("No socket connection"));
766
+ return;
767
+ }
768
+ let off;
769
+ const timeout = setTimeout(() => {
770
+ off?.();
771
+ reject(new Error("Timed out waiting for stats"));
772
+ }, 5e3);
773
+ off = this.on("stats" /* STATS */, (payload) => {
774
+ clearTimeout(timeout);
775
+ off?.();
776
+ resolve(payload);
777
+ });
778
+ this.requestStats();
779
+ });
780
+ }
781
+ getLogs() {
782
+ return new Promise((resolve, reject) => {
783
+ if (!this.socket) {
784
+ reject(new Error("No socket connection"));
785
+ return;
786
+ }
787
+ const lines = [];
788
+ let off;
789
+ let initialTimeout;
790
+ let idleTimeout;
791
+ const finalize = (payload) => {
792
+ off?.();
793
+ if (initialTimeout) {
794
+ clearTimeout(initialTimeout);
795
+ }
796
+ if (idleTimeout) {
797
+ clearTimeout(idleTimeout);
798
+ }
799
+ resolve(payload);
800
+ };
801
+ initialTimeout = setTimeout(() => {
802
+ finalize(lines.length > 0 ? lines : [FALLBACK_LOG_MESSAGE]);
803
+ }, 5e3);
804
+ off = this.on("console output" /* CONSOLE_OUTPUT */, (line) => {
805
+ lines.push(line);
806
+ if (initialTimeout) {
807
+ clearTimeout(initialTimeout);
808
+ initialTimeout = void 0;
809
+ }
810
+ if (idleTimeout) {
811
+ clearTimeout(idleTimeout);
812
+ }
813
+ idleTimeout = setTimeout(() => {
814
+ finalize(lines);
815
+ }, 1e3);
816
+ });
817
+ this.requestLogs();
818
+ });
819
+ }
820
+ sendPoweraction(action) {
821
+ this.send("set state", [action]);
822
+ }
823
+ sendCommand(cmd) {
824
+ this.send("send command", [cmd]);
825
+ }
826
+ };
827
+
828
+ // src/api/client/server_activity.ts
829
+ var ServerActivity = class {
830
+ r;
831
+ id;
832
+ constructor(r, id) {
833
+ this.r = r;
834
+ this.id = id;
835
+ }
836
+ list = async (page = 1, per_page = 25) => {
837
+ const { data } = await this.r.get(`/server/${this.id}/activity`, {
838
+ params: {
839
+ page,
840
+ per_page
841
+ }
842
+ });
843
+ return data.data.map((log) => log.attributes);
844
+ };
845
+ };
846
+
847
+ // src/api/client/server.ts
848
+ var ServerClient = class {
849
+ r;
850
+ id;
851
+ activity;
852
+ databases;
853
+ files;
854
+ schedules;
855
+ allocations;
856
+ users;
857
+ backups;
858
+ startup;
859
+ variables;
860
+ settings;
861
+ constructor(requester, id) {
862
+ this.r = requester;
863
+ this.id = id;
864
+ this.activity = new ServerActivity(requester, id);
865
+ this.databases = new ServerDatabases(requester, id);
866
+ this.files = new ServerFiles(requester, id);
867
+ this.schedules = new ServerSchedules(requester, id);
868
+ this.allocations = new ServerAllocations(requester, id);
869
+ this.users = new ServerUsers(requester, id);
870
+ this.backups = new ServerBackups(requester, id);
871
+ this.startup = new ServerStartup(requester, id);
872
+ this.variables = this.startup;
873
+ this.settings = new ServerSettings(requester, id);
874
+ }
875
+ info = async (include) => {
876
+ const { data } = await this.r.get(`/servers/${this.id}`, {
877
+ params: { include: include?.join(",") }
878
+ });
879
+ return data.attributes;
880
+ };
881
+ websocket = (stripColors = false) => {
882
+ return new ServerWebsocket(this.r, this.id, stripColors);
883
+ };
884
+ resources = async () => {
885
+ const { data } = await this.r.get(`/servers/${this.id}/resources`);
886
+ return data.attributes;
887
+ };
888
+ command = async (command) => {
889
+ await this.r.post(`/servers/${this.id}/command`, { command });
890
+ };
891
+ power = async (signal) => {
892
+ await this.r.post(`/servers/${this.id}/power`, { signal });
893
+ };
894
+ };
895
+
896
+ // src/api/client/client.ts
897
+ var Client = class {
898
+ account;
899
+ r;
900
+ constructor(requester) {
901
+ this.r = requester;
902
+ this.account = new Account(requester);
903
+ }
904
+ listPermissions = async () => {
905
+ const { data } = await this.r.get("/permissions");
906
+ return data.attributes.permissions;
907
+ };
908
+ listServers = async (type = "accessible", page = 1, per_page = 50, include) => {
909
+ import_zod5.default.number().positive().parse(page);
910
+ const { data } = await this.r.get("/servers", {
911
+ params: { type, page, include: include?.join(",") }
912
+ });
913
+ return data.data.map((s) => s.attributes);
914
+ };
915
+ server = (uuid) => new ServerClient(this.r, uuid);
916
+ };
917
+
918
+ // src/api/application/users.ts
919
+ var import_zod6 = __toESM(require("zod"));
920
+
921
+ // src/utils/transform.ts
922
+ var ArrayQueryParams = (p) => {
923
+ const params = new URLSearchParams();
924
+ const o = {};
925
+ for (const [param, value] of Object.entries(p)) {
926
+ for (const [key, val] of Object.entries(value)) {
927
+ o[`${param}[${key}]`] = val;
928
+ }
929
+ }
930
+ return o;
931
+ };
932
+ var SortParam = (key, p) => {
933
+ return `${p === "desc" ? "-" : ""}${key}`;
934
+ };
935
+
936
+ // src/api/application/users.ts
937
+ var Users = class {
938
+ r;
939
+ constructor(requester) {
940
+ this.r = requester;
941
+ }
942
+ list = async ({ ...opts }, page = 1) => {
943
+ import_zod6.default.number().positive().parse(page);
944
+ const { data } = await this.r.get("/users", {
945
+ params: {
946
+ include: opts.include?.join(","),
947
+ page,
948
+ ...ArrayQueryParams({ filters: opts.filters || {} }),
949
+ sort: opts.sort?.id ? SortParam("id", opts.sort?.id) : SortParam("uuid", opts.sort?.uuid)
950
+ }
951
+ });
952
+ return data.data.map((d) => d.attributes);
953
+ };
954
+ info = async (id, { include }) => {
955
+ import_zod6.default.number().positive().parse(id);
956
+ const { data } = await this.r.get(`/users/${id}`, {
957
+ params: { include: include?.join(",") }
958
+ });
959
+ return data.attributes;
960
+ };
961
+ infoByExternal = async (external_id, { include }) => {
962
+ const { data } = await this.r.get(`/users/external/${external_id}`);
963
+ return data.attributes;
964
+ };
965
+ create = async (user) => {
966
+ const { data } = await this.r.post("/users", user);
967
+ return data.attributes;
968
+ };
969
+ update = async (id, user) => {
970
+ import_zod6.default.number().positive().parse(id);
971
+ const { data } = await this.r.put(`/users/${id}`, user);
972
+ return data.attributes;
973
+ };
974
+ delete = async (id) => {
975
+ import_zod6.default.number().positive().parse(id);
976
+ await this.r.delete(`/users/${id}`);
977
+ };
978
+ };
979
+
980
+ // src/api/application/client.ts
981
+ var Client2 = class {
982
+ r;
983
+ users;
984
+ constructor(requester) {
985
+ this.r = requester;
986
+ this.users = new Users(requester);
987
+ }
988
+ };
989
+
990
+ // src/api/base/request.ts
991
+ var import_zod7 = __toESM(require("zod"));
992
+ var import_axios3 = __toESM(require("axios"));
993
+
994
+ // src/api/base/types.ts
995
+ var PterodactylException = class extends Error {
996
+ data;
997
+ status;
998
+ constructor(message, data, status) {
999
+ super(message);
1000
+ this.data = data;
1001
+ this.status = status;
1002
+ }
1003
+ };
1004
+
1005
+ // src/api/base/request.ts
1006
+ var Agent = class {
1007
+ base_url;
1008
+ token;
1009
+ requester;
1010
+ constructor(url, token, type) {
1011
+ this.base_url = import_zod7.default.url("Invalid URL Schema").parse(url);
1012
+ this.token = import_zod7.default.string().regex(/^(ptl[ac]|pacc|papp)_.+$/, "Invalid token type").parse(token);
1013
+ this.requester = import_axios3.default.create({
1014
+ baseURL: this.base_url.replace(/\/+$/, "") + `/api/${type}`,
1015
+ timeout: 3e3,
1016
+ headers: {
1017
+ Authorization: `Bearer ${this.token}`
1018
+ }
1019
+ });
1020
+ this.requester.interceptors.response.use(void 0, (error) => {
1021
+ if (error.response && error.response.status === 400) {
1022
+ return Promise.reject(new PterodactylException(
1023
+ "Invalid request data",
1024
+ error.response.data,
1025
+ error.response.status
1026
+ ));
1027
+ }
1028
+ return Promise.reject(error);
1029
+ });
1030
+ }
1031
+ };
1032
+
1033
+ // src/index.ts
1034
+ var PelicanClient = class extends Client {
1035
+ constructor(url, token) {
1036
+ const ax = new Agent(url, token, "client");
1037
+ super(ax.requester);
1038
+ }
1039
+ };
1040
+ var PelicanApplication = class extends Client2 {
1041
+ constructor(url, token) {
1042
+ const ax = new Agent(url, token, "application");
1043
+ super(ax.requester);
1044
+ }
1045
+ };
1046
+ // Annotate the CommonJS export names for ESM import in node:
1047
+ 0 && (module.exports = {
1048
+ PelicanApplication,
1049
+ PelicanClient
1050
+ });
1051
+ /*
1052
+ * @author BothimTV
1053
+ * @license MIT
1054
+ */
1055
+ //# sourceMappingURL=index.js.map