plugin-workflow-portainer 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +31 -3
  3. package/client-v2.js +1 -0
  4. package/client.js +1 -0
  5. package/dist/client/127.09e6675863ac8138.js +10 -0
  6. package/dist/client/57.67f04a547ead06b8.js +10 -0
  7. package/dist/client/660.546c702d1ddf7eff.js +10 -0
  8. package/dist/client/981.e38099c59bf992f0.js +10 -0
  9. package/dist/client/index.js +10 -0
  10. package/dist/client-v2/127.9f65dc2e3d0df10a.js +10 -0
  11. package/dist/client-v2/57.a60e16e4b4e4fa28.js +10 -0
  12. package/dist/client-v2/660.29ae3c3b4040039d.js +10 -0
  13. package/dist/client-v2/981.8627062881ad83d1.js +10 -0
  14. package/dist/client-v2/index.js +10 -0
  15. package/dist/externalVersion.js +20 -0
  16. package/dist/index.js +48 -0
  17. package/dist/locale/en-US.json +193 -0
  18. package/dist/locale/vi-VN.json +193 -0
  19. package/dist/locale/zh-CN.json +193 -0
  20. package/dist/node_modules/joi/dist/joi-browser.min.js +1 -0
  21. package/dist/node_modules/joi/lib/annotate.js +175 -0
  22. package/dist/node_modules/joi/lib/base.js +1069 -0
  23. package/dist/node_modules/joi/lib/cache.js +143 -0
  24. package/dist/node_modules/joi/lib/common.js +216 -0
  25. package/dist/node_modules/joi/lib/compile.js +283 -0
  26. package/dist/node_modules/joi/lib/errors.js +271 -0
  27. package/dist/node_modules/joi/lib/extend.js +312 -0
  28. package/dist/node_modules/joi/lib/index.d.ts +2365 -0
  29. package/dist/node_modules/joi/lib/index.js +1 -0
  30. package/dist/node_modules/joi/lib/manifest.js +476 -0
  31. package/dist/node_modules/joi/lib/messages.js +207 -0
  32. package/dist/node_modules/joi/lib/modify.js +267 -0
  33. package/dist/node_modules/joi/lib/ref.js +414 -0
  34. package/dist/node_modules/joi/lib/schemas.js +302 -0
  35. package/dist/node_modules/joi/lib/state.js +166 -0
  36. package/dist/node_modules/joi/lib/template.js +463 -0
  37. package/dist/node_modules/joi/lib/trace.js +346 -0
  38. package/dist/node_modules/joi/lib/types/alternatives.js +364 -0
  39. package/dist/node_modules/joi/lib/types/any.js +174 -0
  40. package/dist/node_modules/joi/lib/types/array.js +809 -0
  41. package/dist/node_modules/joi/lib/types/binary.js +100 -0
  42. package/dist/node_modules/joi/lib/types/boolean.js +150 -0
  43. package/dist/node_modules/joi/lib/types/date.js +233 -0
  44. package/dist/node_modules/joi/lib/types/function.js +93 -0
  45. package/dist/node_modules/joi/lib/types/keys.js +1084 -0
  46. package/dist/node_modules/joi/lib/types/link.js +184 -0
  47. package/dist/node_modules/joi/lib/types/number.js +363 -0
  48. package/dist/node_modules/joi/lib/types/object.js +22 -0
  49. package/dist/node_modules/joi/lib/types/string.js +850 -0
  50. package/dist/node_modules/joi/lib/types/symbol.js +102 -0
  51. package/dist/node_modules/joi/lib/validator.js +750 -0
  52. package/dist/node_modules/joi/lib/values.js +263 -0
  53. package/dist/node_modules/joi/node_modules/@hapi/topo/lib/index.d.ts +60 -0
  54. package/dist/node_modules/joi/node_modules/@hapi/topo/lib/index.js +225 -0
  55. package/dist/node_modules/joi/node_modules/@hapi/topo/package.json +30 -0
  56. package/dist/node_modules/joi/package.json +1 -0
  57. package/dist/server/actions/portainer.js +317 -0
  58. package/dist/server/collections/portainer-instances.js +54 -0
  59. package/dist/server/index.js +54 -0
  60. package/dist/server/instructions/PortainerStackControlInstruction.js +156 -0
  61. package/dist/server/instructions/PortainerStackRedeployInstruction.js +254 -0
  62. package/dist/server/instructions/helpers.js +211 -0
  63. package/dist/server/plugin.js +177 -0
  64. package/dist/server/services/PortainerClient.js +669 -0
  65. package/dist/shared/collection.js +57 -0
  66. package/dist/shared/constants.js +66 -0
  67. package/dist/shared/env.js +238 -0
  68. package/dist/shared/types.js +24 -0
  69. package/package.json +50 -4
  70. package/server.js +1 -0
  71. package/src/client/index.tsx +50 -0
  72. package/src/client/instructions.tsx +76 -0
  73. package/src/client-v2/__tests__/workflow-registration.test.tsx +242 -0
  74. package/src/client-v2/components/ControlFieldset.tsx +46 -0
  75. package/src/client-v2/components/PortainerEnvEditor.tsx +223 -0
  76. package/src/client-v2/components/PortainerSettingsPage.tsx +707 -0
  77. package/src/client-v2/components/PortainerTargetFields.tsx +309 -0
  78. package/src/client-v2/components/RedeployFieldset.tsx +124 -0
  79. package/src/client-v2/components/StackDetailDrawer.tsx +790 -0
  80. package/src/client-v2/index.tsx +50 -0
  81. package/src/client-v2/instructions.tsx +162 -0
  82. package/src/client-v2/locale.ts +24 -0
  83. package/src/index.ts +11 -0
  84. package/src/locale/en-US.json +193 -0
  85. package/src/locale/vi-VN.json +193 -0
  86. package/src/locale/zh-CN.json +193 -0
  87. package/src/server/__tests__/portainer-workflow.test.ts +559 -0
  88. package/src/server/actions/portainer.ts +361 -0
  89. package/src/server/collections/portainer-instances.ts +34 -0
  90. package/src/server/index.ts +13 -0
  91. package/src/server/instructions/PortainerStackControlInstruction.ts +139 -0
  92. package/src/server/instructions/PortainerStackRedeployInstruction.ts +255 -0
  93. package/src/server/instructions/helpers.ts +237 -0
  94. package/src/server/plugin.ts +174 -0
  95. package/src/server/services/PortainerClient.ts +846 -0
  96. package/src/shared/collection.ts +32 -0
  97. package/src/shared/constants.ts +25 -0
  98. package/src/shared/env.ts +243 -0
  99. package/src/shared/types.ts +164 -0
@@ -0,0 +1,669 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
+ var PortainerClient_exports = {};
38
+ __export(PortainerClient_exports, {
39
+ PortainerApiError: () => PortainerApiError,
40
+ PortainerClient: () => PortainerClient,
41
+ assertPositiveInt: () => assertPositiveInt,
42
+ assertValidContainerId: () => assertValidContainerId,
43
+ assertValidPortainerUrl: () => assertValidPortainerUrl,
44
+ assertValidWebhookId: () => assertValidWebhookId,
45
+ clampTimeoutMs: () => clampTimeoutMs,
46
+ computeDockerContainerStats: () => computeDockerContainerStats,
47
+ demuxDockerLogBuffer: () => demuxDockerLogBuffer,
48
+ summarizeContainersHealth: () => summarizeContainersHealth,
49
+ toStackDetail: () => toStackDetail,
50
+ toStackSummary: () => toStackSummary
51
+ });
52
+ module.exports = __toCommonJS(PortainerClient_exports);
53
+ var import_node_http = __toESM(require("node:http"));
54
+ var import_node_https = __toESM(require("node:https"));
55
+ var import_node_url = require("node:url");
56
+ var import_constants = require("../../shared/constants");
57
+ class PortainerApiError extends Error {
58
+ status;
59
+ code;
60
+ details;
61
+ constructor(message, options) {
62
+ super(message);
63
+ this.name = "PortainerApiError";
64
+ this.status = options == null ? void 0 : options.status;
65
+ this.code = options == null ? void 0 : options.code;
66
+ this.details = options == null ? void 0 : options.details;
67
+ }
68
+ }
69
+ function assertValidPortainerUrl(rawUrl) {
70
+ const trimmed = String(rawUrl ?? "").trim();
71
+ if (!trimmed) {
72
+ throw new PortainerApiError("Portainer base URL is required", { code: "INVALID_URL" });
73
+ }
74
+ let parsed;
75
+ try {
76
+ parsed = new import_node_url.URL(trimmed);
77
+ } catch {
78
+ throw new PortainerApiError("Portainer base URL is invalid", { code: "INVALID_URL" });
79
+ }
80
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
81
+ throw new PortainerApiError("Portainer base URL must use http or https", { code: "INVALID_URL" });
82
+ }
83
+ if (parsed.username || parsed.password) {
84
+ throw new PortainerApiError("Portainer base URL must not embed credentials", { code: "INVALID_URL" });
85
+ }
86
+ return parsed;
87
+ }
88
+ function assertPositiveInt(value, label) {
89
+ const num = typeof value === "number" ? value : Number(String(value ?? "").trim());
90
+ if (!Number.isSafeInteger(num) || num <= 0) {
91
+ throw new PortainerApiError(`${label} must be a positive integer`, { code: "INVALID_PARAM" });
92
+ }
93
+ return num;
94
+ }
95
+ function assertValidWebhookId(rawWebhookId) {
96
+ const trimmed = String(rawWebhookId ?? "").trim();
97
+ if (!trimmed || !/^[A-Za-z0-9_-]{8,128}$/.test(trimmed)) {
98
+ throw new PortainerApiError("Webhook token must be 8-128 alphanumeric, dash, or underscore characters", {
99
+ code: "INVALID_WEBHOOK"
100
+ });
101
+ }
102
+ return trimmed;
103
+ }
104
+ function assertValidContainerId(rawContainerId) {
105
+ const trimmed = String(rawContainerId ?? "").trim();
106
+ if (!trimmed || !/^[a-fA-F0-9]{12,64}$/.test(trimmed)) {
107
+ throw new PortainerApiError("Container ID must be a 12-64 character hexadecimal identifier", {
108
+ code: "INVALID_PARAM"
109
+ });
110
+ }
111
+ return trimmed;
112
+ }
113
+ function computeDockerContainerStats(raw) {
114
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
115
+ const cpuTotal = Number(((_b = (_a = raw == null ? void 0 : raw.cpu_stats) == null ? void 0 : _a.cpu_usage) == null ? void 0 : _b.total_usage) ?? 0);
116
+ const preCpuTotal = Number(((_d = (_c = raw == null ? void 0 : raw.precpu_stats) == null ? void 0 : _c.cpu_usage) == null ? void 0 : _d.total_usage) ?? 0);
117
+ const sysCpu = Number(((_e = raw == null ? void 0 : raw.cpu_stats) == null ? void 0 : _e.system_cpu_usage) ?? 0);
118
+ const preSysCpu = Number(((_f = raw == null ? void 0 : raw.precpu_stats) == null ? void 0 : _f.system_cpu_usage) ?? 0);
119
+ const cpuDelta = cpuTotal - preCpuTotal;
120
+ const sysDelta = sysCpu - preSysCpu;
121
+ const perCpu = (_h = (_g = raw == null ? void 0 : raw.cpu_stats) == null ? void 0 : _g.cpu_usage) == null ? void 0 : _h.percpu_usage;
122
+ const onlineCpus = Number(((_i = raw == null ? void 0 : raw.cpu_stats) == null ? void 0 : _i.online_cpus) ?? 0) || (Array.isArray(perCpu) ? perCpu.length : 0) || 1;
123
+ const cpuPercent = cpuDelta > 0 && sysDelta > 0 ? Math.round((cpuDelta / sysDelta * onlineCpus * 100 + Number.EPSILON) * 100) / 100 : 0;
124
+ const rawMemUsage = Number(((_j = raw == null ? void 0 : raw.memory_stats) == null ? void 0 : _j.usage) ?? 0);
125
+ const inactiveFile = Number(
126
+ ((_l = (_k = raw == null ? void 0 : raw.memory_stats) == null ? void 0 : _k.stats) == null ? void 0 : _l.inactive_file) ?? ((_n = (_m = raw == null ? void 0 : raw.memory_stats) == null ? void 0 : _m.stats) == null ? void 0 : _n.total_inactive_file) ?? 0
127
+ );
128
+ const memUsageBytes = Math.max(0, rawMemUsage - inactiveFile);
129
+ const memLimitBytes = Math.max(0, Number(((_o = raw == null ? void 0 : raw.memory_stats) == null ? void 0 : _o.limit) ?? 0));
130
+ const memPercent = memLimitBytes > 0 ? Math.round((memUsageBytes / memLimitBytes * 100 + Number.EPSILON) * 100) / 100 : 0;
131
+ let netRxBytes = 0;
132
+ let netTxBytes = 0;
133
+ if ((raw == null ? void 0 : raw.networks) && typeof raw.networks === "object") {
134
+ for (const iface of Object.values(raw.networks)) {
135
+ netRxBytes += Math.max(0, Number((iface == null ? void 0 : iface.rx_bytes) ?? 0));
136
+ netTxBytes += Math.max(0, Number((iface == null ? void 0 : iface.tx_bytes) ?? 0));
137
+ }
138
+ }
139
+ let blockReadBytes = 0;
140
+ let blockWriteBytes = 0;
141
+ const ioEntries = (_p = raw == null ? void 0 : raw.blkio_stats) == null ? void 0 : _p.io_service_bytes_recursive;
142
+ if (Array.isArray(ioEntries)) {
143
+ for (const entry of ioEntries) {
144
+ const op = String((entry == null ? void 0 : entry.op) ?? "").toLowerCase();
145
+ const val = Math.max(0, Number((entry == null ? void 0 : entry.value) ?? 0));
146
+ if (op === "read") {
147
+ blockReadBytes += val;
148
+ } else if (op === "write") {
149
+ blockWriteBytes += val;
150
+ }
151
+ }
152
+ }
153
+ const pids = Math.max(0, Number(((_q = raw == null ? void 0 : raw.pids_stats) == null ? void 0 : _q.current) ?? 0));
154
+ return {
155
+ cpuPercent,
156
+ memUsageBytes,
157
+ memLimitBytes,
158
+ memPercent,
159
+ netRxBytes,
160
+ netTxBytes,
161
+ blockReadBytes,
162
+ blockWriteBytes,
163
+ pids
164
+ };
165
+ }
166
+ function demuxDockerLogBuffer(buf) {
167
+ if (!buf || buf.length === 0) {
168
+ return "";
169
+ }
170
+ const looksMultiplexed = buf.length >= 8 && (buf[0] === 0 || buf[0] === 1 || buf[0] === 2) && buf[1] === 0 && buf[2] === 0 && buf[3] === 0;
171
+ if (!looksMultiplexed) {
172
+ return buf.toString("utf8");
173
+ }
174
+ const parts = [];
175
+ let offset = 0;
176
+ while (offset + 8 <= buf.length) {
177
+ const streamType = buf[offset];
178
+ if (streamType !== 0 && streamType !== 1 && streamType !== 2 || buf[offset + 1] !== 0 || buf[offset + 2] !== 0 || buf[offset + 3] !== 0) {
179
+ parts.push(buf.subarray(offset));
180
+ break;
181
+ }
182
+ const frameLen = buf.readUInt32BE(offset + 4);
183
+ const payloadStart = offset + 8;
184
+ const payloadEnd = Math.min(buf.length, payloadStart + frameLen);
185
+ parts.push(buf.subarray(payloadStart, payloadEnd));
186
+ offset = payloadEnd;
187
+ }
188
+ return Buffer.concat(parts).toString("utf8");
189
+ }
190
+ function clampTimeoutMs(timeoutMs, fallback = import_constants.DEFAULT_TIMEOUT_MS) {
191
+ const num = Number(timeoutMs);
192
+ if (!Number.isFinite(num) || num <= 0) {
193
+ return fallback;
194
+ }
195
+ return Math.min(import_constants.MAX_TIMEOUT_MS, Math.max(import_constants.MIN_TIMEOUT_MS, Math.trunc(num)));
196
+ }
197
+ function normalizeEnvArray(raw) {
198
+ if (!Array.isArray(raw)) {
199
+ return [];
200
+ }
201
+ const pairs = [];
202
+ for (const item of raw) {
203
+ const name = String((item == null ? void 0 : item.name) ?? "").trim();
204
+ if (!name) {
205
+ continue;
206
+ }
207
+ pairs.push({ name, value: String((item == null ? void 0 : item.value) ?? "") });
208
+ }
209
+ return pairs;
210
+ }
211
+ function toStackSummary(stack) {
212
+ const env = normalizeEnvArray(stack.Env);
213
+ const git = stack.GitConfig;
214
+ return {
215
+ id: Number(stack.Id),
216
+ name: String(stack.Name ?? ""),
217
+ endpointId: Number(stack.EndpointId),
218
+ type: Number(stack.Type ?? 2),
219
+ status: Number(stack.Status ?? 1),
220
+ isGitStack: Boolean(git && git.URL),
221
+ gitRepoUrl: (git == null ? void 0 : git.URL) ? String(git.URL) : void 0,
222
+ gitReference: (git == null ? void 0 : git.ReferenceName) ? String(git.ReferenceName) : void 0,
223
+ envCount: env.length
224
+ };
225
+ }
226
+ function toStackDetail(stack) {
227
+ const summary = toStackSummary(stack);
228
+ const git = stack.GitConfig;
229
+ const auth = git == null ? void 0 : git.Authentication;
230
+ const credId = Number((auth == null ? void 0 : auth.GitCredentialID) ?? 0);
231
+ const deployments = Array.isArray(stack.DeploymentStatus) ? stack.DeploymentStatus.map((item) => ({
232
+ status: Number((item == null ? void 0 : item.Status) ?? 0),
233
+ time: typeof (item == null ? void 0 : item.Time) === "number" && item.Time > 0 ? item.Time : void 0,
234
+ message: (item == null ? void 0 : item.Message) ? String(item.Message) : void 0
235
+ })) : void 0;
236
+ return {
237
+ ...summary,
238
+ env: normalizeEnvArray(stack.Env),
239
+ hasSavedGitCredential: credId > 0,
240
+ gitCredentialId: credId > 0 ? credId : 0,
241
+ gitUsername: (auth == null ? void 0 : auth.Username) ? String(auth.Username) : void 0,
242
+ entryPoint: stack.EntryPoint ? String(stack.EntryPoint) : void 0,
243
+ projectPath: stack.ProjectPath ? String(stack.ProjectPath) : void 0,
244
+ createdAt: typeof stack.CreationDate === "number" && stack.CreationDate > 0 ? stack.CreationDate : void 0,
245
+ createdBy: stack.CreatedBy ? String(stack.CreatedBy) : void 0,
246
+ updatedAt: typeof stack.UpdateDate === "number" && stack.UpdateDate > 0 ? stack.UpdateDate : void 0,
247
+ updatedBy: stack.UpdatedBy ? String(stack.UpdatedBy) : void 0,
248
+ gitConfigFilePath: (git == null ? void 0 : git.ConfigFilePath) ? String(git.ConfigFilePath) : void 0,
249
+ gitCommitHash: (git == null ? void 0 : git.ConfigHash) ? String(git.ConfigHash) : void 0,
250
+ deployments
251
+ };
252
+ }
253
+ class PortainerClient {
254
+ baseUrl;
255
+ apiKey;
256
+ allowInsecureTls;
257
+ timeoutMs;
258
+ constructor(options) {
259
+ this.baseUrl = assertValidPortainerUrl(options.baseUrl);
260
+ this.apiKey = String(options.apiKey ?? "").trim();
261
+ this.allowInsecureTls = Boolean(options.allowInsecureTls);
262
+ this.timeoutMs = clampTimeoutMs(options.timeoutMs);
263
+ }
264
+ buildUrl(pathname, query) {
265
+ const basePath = this.baseUrl.pathname.replace(/\/+$/, "");
266
+ const suffix = pathname.startsWith("/") ? pathname : `/${pathname}`;
267
+ const target = new import_node_url.URL(this.baseUrl.toString());
268
+ target.pathname = `${basePath}${suffix}`;
269
+ target.search = "";
270
+ if (query) {
271
+ for (const [key, value] of Object.entries(query)) {
272
+ if (typeof value !== "undefined" && value !== "") {
273
+ target.searchParams.set(key, String(value));
274
+ }
275
+ }
276
+ }
277
+ return target;
278
+ }
279
+ async request(options) {
280
+ if (!options.skipAuth && !this.apiKey) {
281
+ throw new PortainerApiError("Portainer API key is required", { code: "MISSING_API_KEY" });
282
+ }
283
+ const targetUrl = this.buildUrl(options.path, options.query);
284
+ const payload = typeof options.body !== "undefined" ? Buffer.from(JSON.stringify(options.body), "utf8") : null;
285
+ const timeout = clampTimeoutMs(options.timeoutMs, this.timeoutMs);
286
+ const headers = {
287
+ Accept: "application/json"
288
+ };
289
+ if (!options.skipAuth) {
290
+ headers["X-API-Key"] = this.apiKey;
291
+ }
292
+ if (payload) {
293
+ headers["Content-Type"] = "application/json";
294
+ headers["Content-Length"] = String(payload.byteLength);
295
+ }
296
+ const transport = targetUrl.protocol === "https:" ? import_node_https.default : import_node_http.default;
297
+ return new Promise((resolve, reject) => {
298
+ var _a;
299
+ if ((_a = options.signal) == null ? void 0 : _a.aborted) {
300
+ reject(new PortainerApiError("Portainer request aborted", { code: "ECONNABORTED" }));
301
+ return;
302
+ }
303
+ let settled = false;
304
+ const finish = (fn) => {
305
+ if (settled) return;
306
+ settled = true;
307
+ if (options.signal) {
308
+ options.signal.removeEventListener("abort", onAbort);
309
+ }
310
+ fn();
311
+ };
312
+ const req = transport.request(
313
+ targetUrl,
314
+ {
315
+ method: options.method,
316
+ headers,
317
+ timeout,
318
+ ...targetUrl.protocol === "https:" ? { rejectUnauthorized: !this.allowInsecureTls } : {}
319
+ },
320
+ (res) => {
321
+ const chunks = [];
322
+ res.on("data", (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
323
+ res.on("end", () => {
324
+ const fullBuffer = Buffer.concat(chunks);
325
+ const status = res.statusCode ?? 500;
326
+ if (status >= 200 && status < 300 && options.rawBuffer) {
327
+ finish(() => resolve(fullBuffer));
328
+ return;
329
+ }
330
+ const rawText = fullBuffer.toString("utf8");
331
+ let parsedBody = rawText;
332
+ if (rawText.trim()) {
333
+ try {
334
+ parsedBody = JSON.parse(rawText);
335
+ } catch {
336
+ parsedBody = rawText;
337
+ }
338
+ } else {
339
+ parsedBody = null;
340
+ }
341
+ if (status >= 200 && status < 300) {
342
+ finish(() => resolve(parsedBody));
343
+ return;
344
+ }
345
+ const bodyObj = typeof parsedBody === "object" && parsedBody !== null ? parsedBody : null;
346
+ const remoteMessage = typeof (bodyObj == null ? void 0 : bodyObj.message) === "string" && bodyObj.message || typeof (bodyObj == null ? void 0 : bodyObj.details) === "string" && bodyObj.details || typeof parsedBody === "string" && parsedBody.slice(0, 300) || `Portainer responded with HTTP ${status}`;
347
+ finish(
348
+ () => reject(
349
+ new PortainerApiError(remoteMessage, {
350
+ status,
351
+ code: `HTTP_${status}`,
352
+ details: bodyObj ?? void 0
353
+ })
354
+ )
355
+ );
356
+ });
357
+ }
358
+ );
359
+ function onAbort() {
360
+ req.destroy();
361
+ finish(() => reject(new PortainerApiError("Portainer request aborted", { code: "ECONNABORTED" })));
362
+ }
363
+ if (options.signal) {
364
+ options.signal.addEventListener("abort", onAbort, { once: true });
365
+ }
366
+ req.on("timeout", () => {
367
+ req.destroy();
368
+ finish(
369
+ () => reject(new PortainerApiError(`Portainer request timed out after ${timeout}ms`, { code: "ECONNABORTED" }))
370
+ );
371
+ });
372
+ req.on("error", (err) => {
373
+ const safeMsg = (err.message || "Network error calling Portainer").replace(this.apiKey || "__none__", "***");
374
+ finish(() => reject(new PortainerApiError(safeMsg, { code: err.code || "NETWORK_ERROR" })));
375
+ });
376
+ if (payload) {
377
+ req.write(payload);
378
+ }
379
+ req.end();
380
+ });
381
+ }
382
+ async getStatus(signal) {
383
+ return this.request({
384
+ method: "GET",
385
+ path: "/api/status",
386
+ signal
387
+ });
388
+ }
389
+ async listEndpoints(signal) {
390
+ const raw = await this.request({
391
+ method: "GET",
392
+ path: "/api/endpoints",
393
+ signal
394
+ });
395
+ if (!Array.isArray(raw)) {
396
+ return [];
397
+ }
398
+ return raw.map((item) => ({
399
+ id: Number(item.Id),
400
+ name: String(item.Name ?? `Endpoint #${item.Id}`),
401
+ type: Number(item.Type ?? 1),
402
+ status: Number(item.Status ?? 1),
403
+ url: typeof item.URL === "string" ? item.URL : void 0
404
+ }));
405
+ }
406
+ async listStacks(endpointId, signal) {
407
+ const query = endpointId && endpointId > 0 ? { filters: JSON.stringify({ EndpointID: endpointId }) } : void 0;
408
+ const raw = await this.request({
409
+ method: "GET",
410
+ path: "/api/stacks",
411
+ query,
412
+ signal
413
+ });
414
+ if (!Array.isArray(raw)) {
415
+ return [];
416
+ }
417
+ const mapped = raw.map(toStackSummary);
418
+ return endpointId && endpointId > 0 ? mapped.filter((item) => item.endpointId === endpointId) : mapped;
419
+ }
420
+ async getRawStack(stackId, signal) {
421
+ const validId = assertPositiveInt(stackId, "Stack ID");
422
+ return this.request({
423
+ method: "GET",
424
+ path: `/api/stacks/${encodeURIComponent(String(validId))}`,
425
+ signal
426
+ });
427
+ }
428
+ async getStackDetail(stackId, signal) {
429
+ const raw = await this.getRawStack(stackId, signal);
430
+ return toStackDetail(raw);
431
+ }
432
+ async getStackFile(stackId, signal) {
433
+ const validId = assertPositiveInt(stackId, "Stack ID");
434
+ const res = await this.request({
435
+ method: "GET",
436
+ path: `/api/stacks/${encodeURIComponent(String(validId))}/file`,
437
+ signal
438
+ });
439
+ return String((res == null ? void 0 : res.StackFileContent) ?? "");
440
+ }
441
+ async redeployGitStack(stackId, endpointId, payload, options) {
442
+ const validStackId = assertPositiveInt(stackId, "Stack ID");
443
+ const validEndpointId = assertPositiveInt(endpointId, "Environment (Endpoint) ID");
444
+ return this.request({
445
+ method: "PUT",
446
+ path: `/api/stacks/${encodeURIComponent(String(validStackId))}/git/redeploy`,
447
+ query: { endpointId: validEndpointId },
448
+ body: {
449
+ env: payload.env,
450
+ prune: payload.prune,
451
+ pullImage: payload.repullImage,
452
+ repullImageAndRedeploy: payload.repullImage,
453
+ repositoryReferenceName: payload.repositoryReferenceName,
454
+ repositoryAuthentication: payload.repositoryAuthentication,
455
+ ...payload.repositoryGitCredentialID && payload.repositoryGitCredentialID > 0 ? { repositoryGitCredentialID: payload.repositoryGitCredentialID } : {},
456
+ ...payload.repositoryUsername ? { repositoryUsername: payload.repositoryUsername } : {},
457
+ ...payload.repositoryPassword ? { repositoryPassword: payload.repositoryPassword } : {}
458
+ },
459
+ timeoutMs: options == null ? void 0 : options.timeoutMs,
460
+ signal: options == null ? void 0 : options.signal
461
+ });
462
+ }
463
+ async updateComposeStack(stackId, endpointId, payload, options) {
464
+ const validStackId = assertPositiveInt(stackId, "Stack ID");
465
+ const validEndpointId = assertPositiveInt(endpointId, "Environment (Endpoint) ID");
466
+ return this.request({
467
+ method: "PUT",
468
+ path: `/api/stacks/${encodeURIComponent(String(validStackId))}`,
469
+ query: { endpointId: validEndpointId },
470
+ body: {
471
+ stackFileContent: payload.stackFileContent,
472
+ env: payload.env,
473
+ prune: payload.prune,
474
+ pullImage: payload.repullImage
475
+ },
476
+ timeoutMs: options == null ? void 0 : options.timeoutMs,
477
+ signal: options == null ? void 0 : options.signal
478
+ });
479
+ }
480
+ async triggerWebhook(webhookId, tag, options) {
481
+ const validWebhook = assertValidWebhookId(webhookId);
482
+ const trimmedTag = String(tag ?? "").trim();
483
+ return this.request({
484
+ method: "POST",
485
+ path: `/api/stacks/webhooks/${encodeURIComponent(validWebhook)}`,
486
+ query: trimmedTag ? { tag: trimmedTag } : void 0,
487
+ skipAuth: true,
488
+ timeoutMs: options == null ? void 0 : options.timeoutMs,
489
+ signal: options == null ? void 0 : options.signal
490
+ });
491
+ }
492
+ async startStack(stackId, endpointId, signal) {
493
+ const validStackId = assertPositiveInt(stackId, "Stack ID");
494
+ const validEndpointId = assertPositiveInt(endpointId, "Environment (Endpoint) ID");
495
+ return this.request({
496
+ method: "POST",
497
+ path: `/api/stacks/${encodeURIComponent(String(validStackId))}/start`,
498
+ query: { endpointId: validEndpointId },
499
+ signal
500
+ });
501
+ }
502
+ async stopStack(stackId, endpointId, signal) {
503
+ const validStackId = assertPositiveInt(stackId, "Stack ID");
504
+ const validEndpointId = assertPositiveInt(endpointId, "Environment (Endpoint) ID");
505
+ return this.request({
506
+ method: "POST",
507
+ path: `/api/stacks/${encodeURIComponent(String(validStackId))}/stop`,
508
+ query: { endpointId: validEndpointId },
509
+ signal
510
+ });
511
+ }
512
+ /**
513
+ * Wait until an asynchronous Portainer deployment (`Status === 3`, Deploying) settles into Active (`1`),
514
+ * Inactive (`2`), or Error (`4`), throwing `PortainerApiError` when deployment fails.
515
+ */
516
+ async waitForStackSettlement(stackId, initialStack, options) {
517
+ var _a;
518
+ let current = initialStack;
519
+ const timeout = clampTimeoutMs(options == null ? void 0 : options.timeoutMs, this.timeoutMs);
520
+ const pollInterval = Math.max(50, (options == null ? void 0 : options.pollIntervalMs) ?? 1500);
521
+ const deadline = Date.now() + timeout;
522
+ while (Number(current == null ? void 0 : current.Status) === 3) {
523
+ if ((_a = options == null ? void 0 : options.signal) == null ? void 0 : _a.aborted) {
524
+ throw new PortainerApiError("Portainer stack deployment aborted", { code: "ECONNABORTED" });
525
+ }
526
+ if (Date.now() >= deadline) {
527
+ throw new PortainerApiError(`Timed out waiting for Portainer Stack #${stackId} deployment after ${timeout}ms`, {
528
+ code: "ECONNABORTED"
529
+ });
530
+ }
531
+ await new Promise((resolve, reject) => {
532
+ var _a2;
533
+ const timer = setTimeout(() => {
534
+ var _a3;
535
+ (_a3 = options == null ? void 0 : options.signal) == null ? void 0 : _a3.removeEventListener("abort", onAbort);
536
+ resolve();
537
+ }, pollInterval);
538
+ function onAbort() {
539
+ clearTimeout(timer);
540
+ reject(new PortainerApiError("Portainer stack deployment aborted", { code: "ECONNABORTED" }));
541
+ }
542
+ (_a2 = options == null ? void 0 : options.signal) == null ? void 0 : _a2.addEventListener("abort", onAbort, { once: true });
543
+ });
544
+ current = await this.getRawStack(stackId, options == null ? void 0 : options.signal);
545
+ }
546
+ if (Number(current == null ? void 0 : current.Status) === 4) {
547
+ const entries = Array.isArray(current.DeploymentStatus) ? current.DeploymentStatus : [];
548
+ const lastError = [...entries].reverse().find((item) => (item == null ? void 0 : item.Status) === 4 && (item == null ? void 0 : item.Message));
549
+ const message = (lastError == null ? void 0 : lastError.Message) ? `Portainer deployment failed: ${lastError.Message}` : `Portainer Stack #${stackId} entered error status`;
550
+ throw new PortainerApiError(message, { code: "DEPLOYMENT_FAILED", status: 502 });
551
+ }
552
+ return current;
553
+ }
554
+ async listStackContainers(endpointId, stackName, signal) {
555
+ const validEndpointId = assertPositiveInt(endpointId, "Environment (Endpoint) ID");
556
+ const trimmedName = String(stackName ?? "").trim();
557
+ if (!trimmedName) {
558
+ return [];
559
+ }
560
+ const filters = JSON.stringify({
561
+ label: [`com.docker.compose.project=${trimmedName}`]
562
+ });
563
+ const raw = await this.request({
564
+ method: "GET",
565
+ path: `/api/endpoints/${encodeURIComponent(String(validEndpointId))}/docker/containers/json`,
566
+ query: { all: 1, filters },
567
+ signal
568
+ });
569
+ if (!Array.isArray(raw)) {
570
+ return [];
571
+ }
572
+ return raw.map((container) => {
573
+ var _a, _b;
574
+ const state = String(container.State ?? "unknown").toLowerCase();
575
+ const status = String(container.Status ?? "");
576
+ const unhealthy = /\(unhealthy\)/i.test(status) || state === "restarting" || state === "dead";
577
+ const firstName = Array.isArray(container.Names) && container.Names[0] ? container.Names[0] : "";
578
+ const service = (_a = container.Labels) == null ? void 0 : _a["com.docker.compose.service"];
579
+ const portsSet = /* @__PURE__ */ new Set();
580
+ if (Array.isArray(container.Ports)) {
581
+ for (const p of container.Ports) {
582
+ const proto = p.Type || "tcp";
583
+ if (p.PublicPort && p.PrivatePort) {
584
+ const hostPrefix = p.IP ? `${p.IP}:` : "";
585
+ portsSet.add(`${hostPrefix}${p.PublicPort}->${p.PrivatePort}/${proto}`);
586
+ } else if (p.PrivatePort) {
587
+ portsSet.add(`${p.PrivatePort}/${proto}`);
588
+ }
589
+ }
590
+ }
591
+ const ipAddresses = [];
592
+ if (((_b = container.NetworkSettings) == null ? void 0 : _b.Networks) && typeof container.NetworkSettings.Networks === "object") {
593
+ for (const net of Object.values(container.NetworkSettings.Networks)) {
594
+ if ((net == null ? void 0 : net.IPAddress) && !ipAddresses.includes(net.IPAddress)) {
595
+ ipAddresses.push(net.IPAddress);
596
+ }
597
+ }
598
+ }
599
+ return {
600
+ id: String(container.Id ?? "").slice(0, 12),
601
+ name: firstName.replace(/^\/+/, ""),
602
+ service: service ? String(service) : void 0,
603
+ image: String(container.Image ?? ""),
604
+ state,
605
+ status,
606
+ healthy: state === "running" && !unhealthy,
607
+ created: typeof container.Created === "number" && container.Created > 0 ? container.Created : void 0,
608
+ ports: Array.from(portsSet),
609
+ ipAddresses
610
+ };
611
+ });
612
+ }
613
+ async getContainerLiveStats(endpointId, containerId, signal) {
614
+ const validEndpointId = assertPositiveInt(endpointId, "Environment (Endpoint) ID");
615
+ const validContainerId = assertValidContainerId(containerId);
616
+ const raw = await this.request({
617
+ method: "GET",
618
+ path: `/api/endpoints/${encodeURIComponent(String(validEndpointId))}/docker/containers/${encodeURIComponent(
619
+ validContainerId
620
+ )}/stats`,
621
+ query: { stream: "false" },
622
+ timeoutMs: 1e4,
623
+ signal
624
+ });
625
+ return computeDockerContainerStats(raw);
626
+ }
627
+ async getContainerLogs(endpointId, containerId, tail = 100, signal) {
628
+ const validEndpointId = assertPositiveInt(endpointId, "Environment (Endpoint) ID");
629
+ const validContainerId = assertValidContainerId(containerId);
630
+ const clampedTail = Math.min(1e3, Math.max(10, Math.trunc(Number(tail) || 100)));
631
+ const buf = await this.request({
632
+ method: "GET",
633
+ path: `/api/endpoints/${encodeURIComponent(String(validEndpointId))}/docker/containers/${encodeURIComponent(
634
+ validContainerId
635
+ )}/logs`,
636
+ query: {
637
+ stdout: 1,
638
+ stderr: 1,
639
+ tail: clampedTail,
640
+ timestamps: 1
641
+ },
642
+ rawBuffer: true,
643
+ timeoutMs: 15e3,
644
+ signal
645
+ });
646
+ return demuxDockerLogBuffer(buf);
647
+ }
648
+ }
649
+ function summarizeContainersHealth(containers) {
650
+ const totalCount = containers.length;
651
+ const runningCount = containers.filter((c) => c.state === "running").length;
652
+ const healthy = totalCount > 0 && containers.every((c) => c.healthy);
653
+ return { totalCount, runningCount, healthy };
654
+ }
655
+ // Annotate the CommonJS export names for ESM import in node:
656
+ 0 && (module.exports = {
657
+ PortainerApiError,
658
+ PortainerClient,
659
+ assertPositiveInt,
660
+ assertValidContainerId,
661
+ assertValidPortainerUrl,
662
+ assertValidWebhookId,
663
+ clampTimeoutMs,
664
+ computeDockerContainerStats,
665
+ demuxDockerLogBuffer,
666
+ summarizeContainersHealth,
667
+ toStackDetail,
668
+ toStackSummary
669
+ });