plugin-workflow-portainer 0.0.0-stage → 0.1.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.
Files changed (98) 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.5012da93825a6e5c.js +10 -0
  6. package/dist/client/57.ace9538136438718.js +10 -0
  7. package/dist/client/65.ec4a55173511c06d.js +10 -0
  8. package/dist/client/660.546c702d1ddf7eff.js +10 -0
  9. package/dist/client/index.js +10 -0
  10. package/dist/client-v2/127.0ec4dce7b13750e9.js +10 -0
  11. package/dist/client-v2/57.e7cfc50fb651ac14.js +10 -0
  12. package/dist/client-v2/65.9c745ea32ac96e98.js +10 -0
  13. package/dist/client-v2/660.29ae3c3b4040039d.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 +151 -0
  18. package/dist/locale/vi-VN.json +151 -0
  19. package/dist/locale/zh-CN.json +151 -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 +192 -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 +170 -0
  64. package/dist/server/services/PortainerClient.js +497 -0
  65. package/dist/shared/collection.js +57 -0
  66. package/dist/shared/constants.js +66 -0
  67. package/dist/shared/env.js +221 -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 +132 -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 +671 -0
  77. package/src/client-v2/components/PortainerTargetFields.tsx +317 -0
  78. package/src/client-v2/components/RedeployFieldset.tsx +123 -0
  79. package/src/client-v2/index.tsx +50 -0
  80. package/src/client-v2/instructions.tsx +162 -0
  81. package/src/client-v2/locale.ts +24 -0
  82. package/src/index.ts +11 -0
  83. package/src/locale/en-US.json +151 -0
  84. package/src/locale/vi-VN.json +151 -0
  85. package/src/locale/zh-CN.json +151 -0
  86. package/src/server/__tests__/portainer-workflow.test.ts +455 -0
  87. package/src/server/actions/portainer.ts +196 -0
  88. package/src/server/collections/portainer-instances.ts +34 -0
  89. package/src/server/index.ts +13 -0
  90. package/src/server/instructions/PortainerStackControlInstruction.ts +139 -0
  91. package/src/server/instructions/PortainerStackRedeployInstruction.ts +255 -0
  92. package/src/server/instructions/helpers.ts +237 -0
  93. package/src/server/plugin.ts +167 -0
  94. package/src/server/services/PortainerClient.ts +589 -0
  95. package/src/shared/collection.ts +32 -0
  96. package/src/shared/constants.ts +25 -0
  97. package/src/shared/env.ts +228 -0
  98. package/src/shared/types.ts +105 -0
@@ -0,0 +1,589 @@
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
+ import http from 'node:http';
11
+ import https from 'node:https';
12
+ import { URL } from 'node:url';
13
+ import { DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, MIN_TIMEOUT_MS } from '../../shared/constants';
14
+ import type {
15
+ ID,
16
+ PortainerContainerSummary,
17
+ PortainerEndpointSummary,
18
+ PortainerEnvPair,
19
+ PortainerStackDetail,
20
+ PortainerStackSummary,
21
+ } from '../../shared/types';
22
+
23
+ export interface PortainerClientOptions {
24
+ baseUrl: string;
25
+ apiKey?: string;
26
+ allowInsecureTls?: boolean;
27
+ timeoutMs?: number;
28
+ }
29
+
30
+ export class PortainerApiError extends Error {
31
+ status?: number;
32
+ code?: string;
33
+ details?: unknown;
34
+
35
+ constructor(message: string, options?: { status?: number; code?: string; details?: unknown }) {
36
+ super(message);
37
+ this.name = 'PortainerApiError';
38
+ this.status = options?.status;
39
+ this.code = options?.code;
40
+ this.details = options?.details;
41
+ }
42
+ }
43
+
44
+ export interface RawPortainerGitAuth {
45
+ Username?: string;
46
+ Password?: string;
47
+ GitCredentialID?: number;
48
+ }
49
+
50
+ export interface RawPortainerGitConfig {
51
+ URL?: string;
52
+ ReferenceName?: string;
53
+ ConfigFilePath?: string;
54
+ Authentication?: RawPortainerGitAuth | null;
55
+ }
56
+
57
+ export interface RawPortainerDeploymentStatus {
58
+ Status?: number;
59
+ Time?: number;
60
+ Message?: string;
61
+ }
62
+
63
+ export interface RawPortainerStack {
64
+ Id: number;
65
+ Name: string;
66
+ EndpointId: number;
67
+ Type?: number;
68
+ Status?: number;
69
+ Env?: Array<{ name?: string; value?: string }> | null;
70
+ GitConfig?: RawPortainerGitConfig | null;
71
+ DeploymentStatus?: RawPortainerDeploymentStatus[] | null;
72
+ }
73
+
74
+ interface RawDockerContainer {
75
+ Id?: string;
76
+ Names?: string[];
77
+ Image?: string;
78
+ State?: string;
79
+ Status?: string;
80
+ }
81
+
82
+ export function assertValidPortainerUrl(rawUrl: string): URL {
83
+ const trimmed = String(rawUrl ?? '').trim();
84
+ if (!trimmed) {
85
+ throw new PortainerApiError('Portainer base URL is required', { code: 'INVALID_URL' });
86
+ }
87
+ let parsed: URL;
88
+ try {
89
+ parsed = new URL(trimmed);
90
+ } catch {
91
+ throw new PortainerApiError('Portainer base URL is invalid', { code: 'INVALID_URL' });
92
+ }
93
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
94
+ throw new PortainerApiError('Portainer base URL must use http or https', { code: 'INVALID_URL' });
95
+ }
96
+ if (parsed.username || parsed.password) {
97
+ throw new PortainerApiError('Portainer base URL must not embed credentials', { code: 'INVALID_URL' });
98
+ }
99
+ return parsed;
100
+ }
101
+
102
+ export function assertPositiveInt(value: ID | null | undefined, label: string): number {
103
+ const num = typeof value === 'number' ? value : Number(String(value ?? '').trim());
104
+ if (!Number.isSafeInteger(num) || num <= 0) {
105
+ throw new PortainerApiError(`${label} must be a positive integer`, { code: 'INVALID_PARAM' });
106
+ }
107
+ return num;
108
+ }
109
+
110
+ export function assertValidWebhookId(rawWebhookId: string | null | undefined): string {
111
+ const trimmed = String(rawWebhookId ?? '').trim();
112
+ if (!trimmed || !/^[A-Za-z0-9_-]{8,128}$/.test(trimmed)) {
113
+ throw new PortainerApiError('Webhook token must be 8-128 alphanumeric, dash, or underscore characters', {
114
+ code: 'INVALID_WEBHOOK',
115
+ });
116
+ }
117
+ return trimmed;
118
+ }
119
+
120
+ export function clampTimeoutMs(timeoutMs?: number | null, fallback = DEFAULT_TIMEOUT_MS): number {
121
+ const num = Number(timeoutMs);
122
+ if (!Number.isFinite(num) || num <= 0) {
123
+ return fallback;
124
+ }
125
+ return Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, Math.trunc(num)));
126
+ }
127
+
128
+ function normalizeEnvArray(raw?: Array<{ name?: string; value?: string }> | null): PortainerEnvPair[] {
129
+ if (!Array.isArray(raw)) {
130
+ return [];
131
+ }
132
+ const pairs: PortainerEnvPair[] = [];
133
+ for (const item of raw) {
134
+ const name = String(item?.name ?? '').trim();
135
+ if (!name) {
136
+ continue;
137
+ }
138
+ pairs.push({ name, value: String(item?.value ?? '') });
139
+ }
140
+ return pairs;
141
+ }
142
+
143
+ export function toStackSummary(stack: RawPortainerStack): PortainerStackSummary {
144
+ const env = normalizeEnvArray(stack.Env);
145
+ const git = stack.GitConfig;
146
+ return {
147
+ id: Number(stack.Id),
148
+ name: String(stack.Name ?? ''),
149
+ endpointId: Number(stack.EndpointId),
150
+ type: Number(stack.Type ?? 2),
151
+ status: Number(stack.Status ?? 1),
152
+ isGitStack: Boolean(git && git.URL),
153
+ gitRepoUrl: git?.URL ? String(git.URL) : undefined,
154
+ gitReference: git?.ReferenceName ? String(git.ReferenceName) : undefined,
155
+ envCount: env.length,
156
+ };
157
+ }
158
+
159
+ export function toStackDetail(stack: RawPortainerStack): PortainerStackDetail {
160
+ const summary = toStackSummary(stack);
161
+ const auth = stack.GitConfig?.Authentication;
162
+ const credId = Number(auth?.GitCredentialID ?? 0);
163
+ return {
164
+ ...summary,
165
+ env: normalizeEnvArray(stack.Env),
166
+ hasSavedGitCredential: credId > 0,
167
+ gitCredentialId: credId > 0 ? credId : 0,
168
+ gitUsername: auth?.Username ? String(auth.Username) : undefined,
169
+ };
170
+ }
171
+
172
+ export class PortainerClient {
173
+ private readonly baseUrl: URL;
174
+ private readonly apiKey: string;
175
+ private readonly allowInsecureTls: boolean;
176
+ private readonly timeoutMs: number;
177
+
178
+ constructor(options: PortainerClientOptions) {
179
+ this.baseUrl = assertValidPortainerUrl(options.baseUrl);
180
+ this.apiKey = String(options.apiKey ?? '').trim();
181
+ this.allowInsecureTls = Boolean(options.allowInsecureTls);
182
+ this.timeoutMs = clampTimeoutMs(options.timeoutMs);
183
+ }
184
+
185
+ private buildUrl(pathname: string, query?: Record<string, string | number | undefined>): URL {
186
+ const basePath = this.baseUrl.pathname.replace(/\/+$/, '');
187
+ const suffix = pathname.startsWith('/') ? pathname : `/${pathname}`;
188
+ const target = new URL(this.baseUrl.toString());
189
+ target.pathname = `${basePath}${suffix}`;
190
+ target.search = '';
191
+ if (query) {
192
+ for (const [key, value] of Object.entries(query)) {
193
+ if (typeof value !== 'undefined' && value !== '') {
194
+ target.searchParams.set(key, String(value));
195
+ }
196
+ }
197
+ }
198
+ return target;
199
+ }
200
+
201
+ async request<TResponse>(options: {
202
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
203
+ path: string;
204
+ query?: Record<string, string | number | undefined>;
205
+ body?: unknown;
206
+ timeoutMs?: number;
207
+ skipAuth?: boolean;
208
+ signal?: AbortSignal;
209
+ }): Promise<TResponse> {
210
+ if (!options.skipAuth && !this.apiKey) {
211
+ throw new PortainerApiError('Portainer API key is required', { code: 'MISSING_API_KEY' });
212
+ }
213
+ const targetUrl = this.buildUrl(options.path, options.query);
214
+ const payload = typeof options.body !== 'undefined' ? Buffer.from(JSON.stringify(options.body), 'utf8') : null;
215
+ const timeout = clampTimeoutMs(options.timeoutMs, this.timeoutMs);
216
+
217
+ const headers: Record<string, string> = {
218
+ Accept: 'application/json',
219
+ };
220
+ if (!options.skipAuth) {
221
+ headers['X-API-Key'] = this.apiKey;
222
+ }
223
+ if (payload) {
224
+ headers['Content-Type'] = 'application/json';
225
+ headers['Content-Length'] = String(payload.byteLength);
226
+ }
227
+
228
+ const transport = targetUrl.protocol === 'https:' ? https : http;
229
+
230
+ return new Promise<TResponse>((resolve, reject) => {
231
+ if (options.signal?.aborted) {
232
+ reject(new PortainerApiError('Portainer request aborted', { code: 'ECONNABORTED' }));
233
+ return;
234
+ }
235
+
236
+ let settled = false;
237
+ const finish = (fn: () => void) => {
238
+ if (settled) return;
239
+ settled = true;
240
+ if (options.signal) {
241
+ options.signal.removeEventListener('abort', onAbort);
242
+ }
243
+ fn();
244
+ };
245
+
246
+ const req = transport.request(
247
+ targetUrl,
248
+ {
249
+ method: options.method,
250
+ headers,
251
+ timeout,
252
+ ...(targetUrl.protocol === 'https:' ? { rejectUnauthorized: !this.allowInsecureTls } : {}),
253
+ },
254
+ (res) => {
255
+ const chunks: Buffer[] = [];
256
+ res.on('data', (chunk: Buffer) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
257
+ res.on('end', () => {
258
+ const rawText = Buffer.concat(chunks).toString('utf8');
259
+ const status = res.statusCode ?? 500;
260
+ let parsedBody: unknown = rawText;
261
+ if (rawText.trim()) {
262
+ try {
263
+ parsedBody = JSON.parse(rawText);
264
+ } catch {
265
+ parsedBody = rawText;
266
+ }
267
+ } else {
268
+ parsedBody = null;
269
+ }
270
+
271
+ if (status >= 200 && status < 300) {
272
+ finish(() => resolve(parsedBody as TResponse));
273
+ return;
274
+ }
275
+
276
+ const bodyObj =
277
+ typeof parsedBody === 'object' && parsedBody !== null ? (parsedBody as Record<string, unknown>) : null;
278
+ const remoteMessage =
279
+ (typeof bodyObj?.message === 'string' && bodyObj.message) ||
280
+ (typeof bodyObj?.details === 'string' && bodyObj.details) ||
281
+ (typeof parsedBody === 'string' && parsedBody.slice(0, 300)) ||
282
+ `Portainer responded with HTTP ${status}`;
283
+
284
+ finish(() =>
285
+ reject(
286
+ new PortainerApiError(remoteMessage, {
287
+ status,
288
+ code: `HTTP_${status}`,
289
+ details: bodyObj ?? undefined,
290
+ }),
291
+ ),
292
+ );
293
+ });
294
+ },
295
+ );
296
+
297
+ function onAbort() {
298
+ req.destroy();
299
+ finish(() => reject(new PortainerApiError('Portainer request aborted', { code: 'ECONNABORTED' })));
300
+ }
301
+
302
+ if (options.signal) {
303
+ options.signal.addEventListener('abort', onAbort, { once: true });
304
+ }
305
+
306
+ req.on('timeout', () => {
307
+ req.destroy();
308
+ finish(() =>
309
+ reject(new PortainerApiError(`Portainer request timed out after ${timeout}ms`, { code: 'ECONNABORTED' })),
310
+ );
311
+ });
312
+
313
+ req.on('error', (err: NodeJS.ErrnoException) => {
314
+ const safeMsg = (err.message || 'Network error calling Portainer').replace(this.apiKey || '__none__', '***');
315
+ finish(() => reject(new PortainerApiError(safeMsg, { code: err.code || 'NETWORK_ERROR' })));
316
+ });
317
+
318
+ if (payload) {
319
+ req.write(payload);
320
+ }
321
+ req.end();
322
+ });
323
+ }
324
+
325
+ async getStatus(signal?: AbortSignal): Promise<{ Version?: string; InstanceID?: string }> {
326
+ return this.request<{ Version?: string; InstanceID?: string }>({
327
+ method: 'GET',
328
+ path: '/api/status',
329
+ signal,
330
+ });
331
+ }
332
+
333
+ async listEndpoints(signal?: AbortSignal): Promise<PortainerEndpointSummary[]> {
334
+ const raw = await this.request<Array<Record<string, unknown>>>({
335
+ method: 'GET',
336
+ path: '/api/endpoints',
337
+ signal,
338
+ });
339
+ if (!Array.isArray(raw)) {
340
+ return [];
341
+ }
342
+ return raw.map((item) => ({
343
+ id: Number(item.Id),
344
+ name: String(item.Name ?? `Endpoint #${item.Id}`),
345
+ type: Number(item.Type ?? 1),
346
+ status: Number(item.Status ?? 1),
347
+ url: typeof item.URL === 'string' ? item.URL : undefined,
348
+ }));
349
+ }
350
+
351
+ async listStacks(endpointId?: number | null, signal?: AbortSignal): Promise<PortainerStackSummary[]> {
352
+ const query = endpointId && endpointId > 0 ? { filters: JSON.stringify({ EndpointID: endpointId }) } : undefined;
353
+ const raw = await this.request<RawPortainerStack[]>({
354
+ method: 'GET',
355
+ path: '/api/stacks',
356
+ query,
357
+ signal,
358
+ });
359
+ if (!Array.isArray(raw)) {
360
+ return [];
361
+ }
362
+ const mapped = raw.map(toStackSummary);
363
+ return endpointId && endpointId > 0 ? mapped.filter((item) => item.endpointId === endpointId) : mapped;
364
+ }
365
+
366
+ async getRawStack(stackId: number, signal?: AbortSignal): Promise<RawPortainerStack> {
367
+ const validId = assertPositiveInt(stackId, 'Stack ID');
368
+ return this.request<RawPortainerStack>({
369
+ method: 'GET',
370
+ path: `/api/stacks/${encodeURIComponent(String(validId))}`,
371
+ signal,
372
+ });
373
+ }
374
+
375
+ async getStackDetail(stackId: number, signal?: AbortSignal): Promise<PortainerStackDetail> {
376
+ const raw = await this.getRawStack(stackId, signal);
377
+ return toStackDetail(raw);
378
+ }
379
+
380
+ async getStackFile(stackId: number, signal?: AbortSignal): Promise<string> {
381
+ const validId = assertPositiveInt(stackId, 'Stack ID');
382
+ const res = await this.request<{ StackFileContent?: string }>({
383
+ method: 'GET',
384
+ path: `/api/stacks/${encodeURIComponent(String(validId))}/file`,
385
+ signal,
386
+ });
387
+ return String(res?.StackFileContent ?? '');
388
+ }
389
+
390
+ async redeployGitStack(
391
+ stackId: number,
392
+ endpointId: number,
393
+ payload: {
394
+ env: PortainerEnvPair[];
395
+ prune: boolean;
396
+ repullImage: boolean;
397
+ repositoryReferenceName: string;
398
+ repositoryAuthentication: boolean;
399
+ repositoryGitCredentialID?: number;
400
+ repositoryUsername?: string;
401
+ repositoryPassword?: string;
402
+ },
403
+ options?: { timeoutMs?: number; signal?: AbortSignal },
404
+ ): Promise<RawPortainerStack> {
405
+ const validStackId = assertPositiveInt(stackId, 'Stack ID');
406
+ const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
407
+ return this.request<RawPortainerStack>({
408
+ method: 'PUT',
409
+ path: `/api/stacks/${encodeURIComponent(String(validStackId))}/git/redeploy`,
410
+ query: { endpointId: validEndpointId },
411
+ body: {
412
+ env: payload.env,
413
+ prune: payload.prune,
414
+ pullImage: payload.repullImage,
415
+ repullImageAndRedeploy: payload.repullImage,
416
+ repositoryReferenceName: payload.repositoryReferenceName,
417
+ repositoryAuthentication: payload.repositoryAuthentication,
418
+ ...(payload.repositoryGitCredentialID && payload.repositoryGitCredentialID > 0
419
+ ? { repositoryGitCredentialID: payload.repositoryGitCredentialID }
420
+ : {}),
421
+ ...(payload.repositoryUsername ? { repositoryUsername: payload.repositoryUsername } : {}),
422
+ ...(payload.repositoryPassword ? { repositoryPassword: payload.repositoryPassword } : {}),
423
+ },
424
+ timeoutMs: options?.timeoutMs,
425
+ signal: options?.signal,
426
+ });
427
+ }
428
+
429
+ async updateComposeStack(
430
+ stackId: number,
431
+ endpointId: number,
432
+ payload: {
433
+ stackFileContent: string;
434
+ env: PortainerEnvPair[];
435
+ prune: boolean;
436
+ repullImage: boolean;
437
+ },
438
+ options?: { timeoutMs?: number; signal?: AbortSignal },
439
+ ): Promise<RawPortainerStack> {
440
+ const validStackId = assertPositiveInt(stackId, 'Stack ID');
441
+ const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
442
+ return this.request<RawPortainerStack>({
443
+ method: 'PUT',
444
+ path: `/api/stacks/${encodeURIComponent(String(validStackId))}`,
445
+ query: { endpointId: validEndpointId },
446
+ body: {
447
+ stackFileContent: payload.stackFileContent,
448
+ env: payload.env,
449
+ prune: payload.prune,
450
+ pullImage: payload.repullImage,
451
+ },
452
+ timeoutMs: options?.timeoutMs,
453
+ signal: options?.signal,
454
+ });
455
+ }
456
+
457
+ async triggerWebhook(
458
+ webhookId: string,
459
+ tag?: string | null,
460
+ options?: { timeoutMs?: number; signal?: AbortSignal },
461
+ ): Promise<unknown> {
462
+ const validWebhook = assertValidWebhookId(webhookId);
463
+ const trimmedTag = String(tag ?? '').trim();
464
+ return this.request<unknown>({
465
+ method: 'POST',
466
+ path: `/api/stacks/webhooks/${encodeURIComponent(validWebhook)}`,
467
+ query: trimmedTag ? { tag: trimmedTag } : undefined,
468
+ skipAuth: true,
469
+ timeoutMs: options?.timeoutMs,
470
+ signal: options?.signal,
471
+ });
472
+ }
473
+
474
+ async startStack(stackId: number, endpointId: number, signal?: AbortSignal): Promise<RawPortainerStack> {
475
+ const validStackId = assertPositiveInt(stackId, 'Stack ID');
476
+ const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
477
+ return this.request<RawPortainerStack>({
478
+ method: 'POST',
479
+ path: `/api/stacks/${encodeURIComponent(String(validStackId))}/start`,
480
+ query: { endpointId: validEndpointId },
481
+ signal,
482
+ });
483
+ }
484
+
485
+ async stopStack(stackId: number, endpointId: number, signal?: AbortSignal): Promise<RawPortainerStack> {
486
+ const validStackId = assertPositiveInt(stackId, 'Stack ID');
487
+ const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
488
+ return this.request<RawPortainerStack>({
489
+ method: 'POST',
490
+ path: `/api/stacks/${encodeURIComponent(String(validStackId))}/stop`,
491
+ query: { endpointId: validEndpointId },
492
+ signal,
493
+ });
494
+ }
495
+
496
+ /**
497
+ * Wait until an asynchronous Portainer deployment (`Status === 3`, Deploying) settles into Active (`1`),
498
+ * Inactive (`2`), or Error (`4`), throwing `PortainerApiError` when deployment fails.
499
+ */
500
+ async waitForStackSettlement(
501
+ stackId: number,
502
+ initialStack: RawPortainerStack,
503
+ options?: { timeoutMs?: number; pollIntervalMs?: number; signal?: AbortSignal },
504
+ ): Promise<RawPortainerStack> {
505
+ let current = initialStack;
506
+ const timeout = clampTimeoutMs(options?.timeoutMs, this.timeoutMs);
507
+ const pollInterval = Math.max(50, options?.pollIntervalMs ?? 1500);
508
+ const deadline = Date.now() + timeout;
509
+
510
+ while (Number(current?.Status) === 3) {
511
+ if (options?.signal?.aborted) {
512
+ throw new PortainerApiError('Portainer stack deployment aborted', { code: 'ECONNABORTED' });
513
+ }
514
+ if (Date.now() >= deadline) {
515
+ throw new PortainerApiError(`Timed out waiting for Portainer Stack #${stackId} deployment after ${timeout}ms`, {
516
+ code: 'ECONNABORTED',
517
+ });
518
+ }
519
+ await new Promise<void>((resolve, reject) => {
520
+ const timer = setTimeout(() => {
521
+ options?.signal?.removeEventListener('abort', onAbort);
522
+ resolve();
523
+ }, pollInterval);
524
+ function onAbort() {
525
+ clearTimeout(timer);
526
+ reject(new PortainerApiError('Portainer stack deployment aborted', { code: 'ECONNABORTED' }));
527
+ }
528
+ options?.signal?.addEventListener('abort', onAbort, { once: true });
529
+ });
530
+ current = await this.getRawStack(stackId, options?.signal);
531
+ }
532
+
533
+ if (Number(current?.Status) === 4) {
534
+ const entries = Array.isArray(current.DeploymentStatus) ? current.DeploymentStatus : [];
535
+ const lastError = [...entries].reverse().find((item) => item?.Status === 4 && item?.Message);
536
+ const message = lastError?.Message
537
+ ? `Portainer deployment failed: ${lastError.Message}`
538
+ : `Portainer Stack #${stackId} entered error status`;
539
+ throw new PortainerApiError(message, { code: 'DEPLOYMENT_FAILED', status: 502 });
540
+ }
541
+
542
+ return current;
543
+ }
544
+
545
+ async listStackContainers(
546
+ endpointId: number,
547
+ stackName: string,
548
+ signal?: AbortSignal,
549
+ ): Promise<PortainerContainerSummary[]> {
550
+ const validEndpointId = assertPositiveInt(endpointId, 'Environment (Endpoint) ID');
551
+ const trimmedName = String(stackName ?? '').trim();
552
+ if (!trimmedName) {
553
+ return [];
554
+ }
555
+ const filters = JSON.stringify({
556
+ label: [`com.docker.compose.project=${trimmedName}`],
557
+ });
558
+ const raw = await this.request<RawDockerContainer[]>({
559
+ method: 'GET',
560
+ path: `/api/endpoints/${encodeURIComponent(String(validEndpointId))}/docker/containers/json`,
561
+ query: { all: 1, filters },
562
+ signal,
563
+ });
564
+ if (!Array.isArray(raw)) {
565
+ return [];
566
+ }
567
+ return raw.map((container) => {
568
+ const state = String(container.State ?? 'unknown').toLowerCase();
569
+ const status = String(container.Status ?? '');
570
+ const unhealthy = /\(unhealthy\)/i.test(status) || state === 'restarting' || state === 'dead';
571
+ const firstName = Array.isArray(container.Names) && container.Names[0] ? container.Names[0] : '';
572
+ return {
573
+ id: String(container.Id ?? '').slice(0, 12),
574
+ name: firstName.replace(/^\/+/, ''),
575
+ image: String(container.Image ?? ''),
576
+ state,
577
+ status,
578
+ healthy: state === 'running' && !unhealthy,
579
+ };
580
+ });
581
+ }
582
+ }
583
+
584
+ export function summarizeContainersHealth(containers: PortainerContainerSummary[]) {
585
+ const totalCount = containers.length;
586
+ const runningCount = containers.filter((c) => c.state === 'running').length;
587
+ const healthy = totalCount > 0 && containers.every((c) => c.healthy);
588
+ return { totalCount, runningCount, healthy };
589
+ }
@@ -0,0 +1,32 @@
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
+ import { DEFAULT_TIMEOUT_MS, PORTAINER_INSTANCES_COLLECTION } from './constants';
11
+
12
+ export const portainerInstancesCollection = {
13
+ name: PORTAINER_INSTANCES_COLLECTION,
14
+ title: 'Portainer Instances',
15
+ hidden: true,
16
+ fields: [
17
+ { name: 'id', type: 'bigInt', autoIncrement: true, primaryKey: true },
18
+ { name: 'name', type: 'string' },
19
+ { name: 'baseUrl', type: 'string' },
20
+ { name: 'apiKey', type: 'text' },
21
+ { name: 'gitUsername', type: 'string' },
22
+ { name: 'gitAccessToken', type: 'text' },
23
+ { name: 'gitCredentialId', type: 'integer' },
24
+ { name: 'allowInsecureTls', type: 'boolean', defaultValue: false },
25
+ { name: 'defaultTimeoutMs', type: 'integer', defaultValue: DEFAULT_TIMEOUT_MS },
26
+ { name: 'isDefault', type: 'boolean', defaultValue: false },
27
+ { name: 'enabled', type: 'boolean', defaultValue: true },
28
+ { name: 'lastHealthStatus', type: 'string' },
29
+ { name: 'lastVersion', type: 'string' },
30
+ { name: 'lastCheckedAt', type: 'date' },
31
+ ],
32
+ };
@@ -0,0 +1,25 @@
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
+ export const PLUGIN_NAMESPACE = 'plugin-workflow-portainer';
11
+ export const PORTAINER_INSTANCES_COLLECTION = 'portainerInstances';
12
+ export const PORTAINER_RESOURCE = 'portainerWorkflow';
13
+ export const PORTAINER_ACL_SNIPPET = 'pm.plugin-workflow-portainer';
14
+
15
+ export const INSTRUCTION_GROUP_KEY = 'portainer';
16
+
17
+ export const INSTRUCTION_TYPES = {
18
+ redeploy: 'portainer-stack-redeploy',
19
+ control: 'portainer-stack-control',
20
+ } as const;
21
+
22
+ export const SECRET_MASK = '••••••••';
23
+ export const DEFAULT_TIMEOUT_MS = 600_000;
24
+ export const MIN_TIMEOUT_MS = 1_000;
25
+ export const MAX_TIMEOUT_MS = 3_600_000;