@vercel/slack-bolt 1.4.0 → 1.4.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.
@@ -1,1003 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkQHMZVK6J_js = require('./chunk-QHMZVK6J.js');
4
- var path2 = require('path');
5
- var yaml = require('yaml');
6
- var crypto = require('crypto');
7
- var fs = require('fs');
8
-
9
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
-
11
- var path2__default = /*#__PURE__*/_interopDefault(path2);
12
- var crypto__default = /*#__PURE__*/_interopDefault(crypto);
13
- var fs__default = /*#__PURE__*/_interopDefault(fs);
14
-
15
- // src/internal/manifest/index.ts
16
- function rewriteUrl(originalUrl, branchUrl, bypassSecret) {
17
- const pathStart = originalUrl.indexOf("/", originalUrl.indexOf("//") + 2);
18
- const pathAndQuery = pathStart !== -1 ? originalUrl.slice(pathStart) : "/";
19
- const url = new URL(pathAndQuery, `https://${branchUrl}`);
20
- if (bypassSecret) {
21
- url.searchParams.set("x-vercel-protection-bypass", bypassSecret);
22
- }
23
- return url.toString();
24
- }
25
- function createManifestDescription(params) {
26
- const shortSha = params.commitSha?.slice(0, 7) ?? "unknown";
27
- const safeCommitMsg = params.commitMessage ?? "";
28
- const safeCommitAuthor = params.commitAuthor ?? "unknown";
29
- const deploymentInfo = `
30
- :globe_with_meridians: *Deployment URL:* ${params.branchUrl}
31
- :seedling: *Branch:* ${params.branch}
32
- :technologist: *Commit:* ${shortSha} ${safeCommitMsg}
33
- :bust_in_silhouette: *Last updated by:* ${safeCommitAuthor}
34
-
35
- _Automatically created by \u25B2 Vercel_
36
- `;
37
- const maxLongDesc = 4e3;
38
- const combined = params.existingDescription + deploymentInfo;
39
- let longDescription;
40
- if (combined.length > maxLongDesc) {
41
- const available = Math.max(0, maxLongDesc - deploymentInfo.length);
42
- longDescription = (params.existingDescription.slice(0, available) + deploymentInfo).slice(0, maxLongDesc);
43
- } else {
44
- longDescription = combined;
45
- }
46
- const maxDisplayName = 35;
47
- const cleanBranch = params.branch.replace(/^refs\/heads\//, "").replace(/\//g, "-");
48
- let displayName = `${params.existingName} (${cleanBranch})`;
49
- if (displayName.length > maxDisplayName) {
50
- const prefix = `${params.existingName} (`;
51
- const suffix = ")";
52
- const availableForBranch = maxDisplayName - prefix.length - suffix.length;
53
- displayName = availableForBranch > 0 ? `${prefix}${cleanBranch.slice(0, availableForBranch)}${suffix}` : displayName.slice(0, maxDisplayName);
54
- }
55
- return { longDescription, displayName };
56
- }
57
- function createNewManifest(params) {
58
- const manifest = structuredClone(params.originalManifest);
59
- if (manifest.settings?.event_subscriptions?.request_url) {
60
- manifest.settings.event_subscriptions.request_url = rewriteUrl(
61
- manifest.settings.event_subscriptions.request_url,
62
- params.branchUrl,
63
- params.bypassSecret
64
- );
65
- }
66
- if (manifest.settings?.interactivity?.request_url) {
67
- manifest.settings.interactivity.request_url = rewriteUrl(
68
- manifest.settings.interactivity.request_url,
69
- params.branchUrl,
70
- params.bypassSecret
71
- );
72
- }
73
- if (manifest.features?.slash_commands) {
74
- for (const cmd of manifest.features.slash_commands) {
75
- if (cmd.url) {
76
- cmd.url = rewriteUrl(cmd.url, params.branchUrl, params.bypassSecret);
77
- }
78
- }
79
- }
80
- if (manifest.oauth_config?.redirect_urls) {
81
- manifest.oauth_config.redirect_urls = manifest.oauth_config.redirect_urls.map(
82
- (originalUrl) => rewriteUrl(originalUrl, params.branchUrl)
83
- );
84
- }
85
- const { longDescription, displayName } = createManifestDescription({
86
- existingDescription: manifest.display_information.long_description ?? "",
87
- existingName: manifest.features?.bot_user?.display_name ?? manifest.display_information.name,
88
- branchUrl: params.branchUrl,
89
- branch: params.branch,
90
- commitSha: params.commitSha,
91
- commitMessage: params.commitMessage,
92
- commitAuthor: params.commitAuthor
93
- });
94
- manifest.display_information.long_description = longDescription;
95
- manifest.display_information.name = displayName;
96
- if (manifest.features?.bot_user) {
97
- manifest.features.bot_user.display_name = displayName;
98
- }
99
- return manifest;
100
- }
101
- var init_manifest = chunkQHMZVK6J_js.__esm({
102
- "src/internal/manifest/index.ts"() {
103
- }
104
- });
105
- function isYaml(filePath) {
106
- const ext = path2__default.default.extname(filePath).toLowerCase();
107
- return ext === ".yaml" || ext === ".yml";
108
- }
109
- function parseManifest(raw, filePath) {
110
- if (isYaml(filePath)) {
111
- return yaml.parse(raw);
112
- }
113
- return JSON.parse(raw);
114
- }
115
- function stringifyManifest(manifest, filePath) {
116
- if (isYaml(filePath)) {
117
- return yaml.stringify(manifest);
118
- }
119
- return JSON.stringify(manifest, null, 2);
120
- }
121
- var init_parse = chunkQHMZVK6J_js.__esm({
122
- "src/internal/manifest/parse.ts"() {
123
- }
124
- });
125
-
126
- // src/internal/vercel/errors.ts
127
- var HTTPError;
128
- var init_errors = chunkQHMZVK6J_js.__esm({
129
- "src/internal/vercel/errors.ts"() {
130
- HTTPError = class _HTTPError extends Error {
131
- constructor(message, status, statusText, body) {
132
- const parts = [`${message}: ${status} ${statusText}`];
133
- if (body) parts.push(body);
134
- super(parts.join(" - "));
135
- this.status = status;
136
- this.statusText = statusText;
137
- this.body = body;
138
- }
139
- static async fromResponse(message, response) {
140
- let body;
141
- try {
142
- const text = await response.text();
143
- if (text) body = text;
144
- } catch {
145
- }
146
- return new _HTTPError(message, response.status, response.statusText, body);
147
- }
148
- };
149
- }
150
- });
151
-
152
- // src/internal/slack/errors.ts
153
- var SlackManifestCreateError, SlackManifestUpdateError, SlackManifestExportError;
154
- var init_errors2 = chunkQHMZVK6J_js.__esm({
155
- "src/internal/slack/errors.ts"() {
156
- SlackManifestCreateError = class extends Error {
157
- constructor(message, errors) {
158
- super(message);
159
- this.errors = errors;
160
- }
161
- };
162
- SlackManifestUpdateError = class extends Error {
163
- constructor(message, errors) {
164
- super(message);
165
- this.errors = errors;
166
- }
167
- };
168
- SlackManifestExportError = class extends Error {
169
- };
170
- }
171
- });
172
-
173
- // src/internal/slack/index.ts
174
- async function createSlackApp({
175
- token,
176
- manifest
177
- }) {
178
- const response = await fetch("https://slack.com/api/apps.manifest.create", {
179
- method: "POST",
180
- headers: {
181
- Authorization: `Bearer ${token}`,
182
- "Content-Type": "application/json; charset=utf-8"
183
- },
184
- body: JSON.stringify({ manifest: JSON.stringify(manifest) })
185
- });
186
- if (!response.ok) {
187
- throw new HTTPError(
188
- "Failed to create Slack app",
189
- response.status,
190
- response.statusText
191
- );
192
- }
193
- const data = await response.json();
194
- if (!data.ok) {
195
- throw new SlackManifestCreateError(
196
- data?.error ?? "Unknown error",
197
- data?.errors
198
- );
199
- }
200
- return data;
201
- }
202
- async function updateSlackApp({
203
- token,
204
- appId,
205
- manifest
206
- }) {
207
- const response = await fetch("https://slack.com/api/apps.manifest.update", {
208
- method: "POST",
209
- headers: {
210
- Authorization: `Bearer ${token}`,
211
- "Content-Type": "application/json; charset=utf-8"
212
- },
213
- body: JSON.stringify({
214
- app_id: appId,
215
- manifest: JSON.stringify(manifest)
216
- })
217
- });
218
- if (!response.ok) {
219
- throw new HTTPError(
220
- "Failed to update Slack app",
221
- response.status,
222
- response.statusText
223
- );
224
- }
225
- const data = await response.json();
226
- if (!data.ok) {
227
- throw new SlackManifestUpdateError(
228
- data?.error ?? "Unknown error",
229
- data?.errors
230
- );
231
- }
232
- return data;
233
- }
234
- async function exportSlackApp({
235
- token,
236
- appId
237
- }) {
238
- const response = await fetch("https://slack.com/api/apps.manifest.export", {
239
- method: "POST",
240
- headers: {
241
- Authorization: `Bearer ${token}`,
242
- "Content-Type": "application/json; charset=utf-8"
243
- },
244
- body: JSON.stringify({ app_id: appId })
245
- });
246
- if (!response.ok) {
247
- throw new HTTPError(
248
- "Failed to export Slack app",
249
- response.status,
250
- response.statusText
251
- );
252
- }
253
- const data = await response.json();
254
- if (!data.ok) {
255
- throw new SlackManifestExportError(data?.error ?? "Unknown error");
256
- }
257
- return data;
258
- }
259
- async function upsertSlackApp({
260
- token,
261
- appId,
262
- manifest
263
- }) {
264
- if (appId) {
265
- try {
266
- await exportSlackApp({ token, appId });
267
- const app2 = await updateSlackApp({ token, appId, manifest });
268
- return { isNew: false, app: app2 };
269
- } catch {
270
- }
271
- }
272
- const app = await createSlackApp({ token, manifest });
273
- return { isNew: true, app };
274
- }
275
- async function deleteSlackApp({
276
- token,
277
- appId
278
- }) {
279
- const response = await fetch("https://slack.com/api/apps.manifest.delete", {
280
- method: "POST",
281
- headers: {
282
- Authorization: `Bearer ${token}`,
283
- "Content-Type": "application/json; charset=utf-8"
284
- },
285
- body: JSON.stringify({ app_id: appId })
286
- });
287
- if (!response.ok) {
288
- throw new HTTPError(
289
- "Failed to delete Slack app",
290
- response.status,
291
- response.statusText
292
- );
293
- }
294
- const data = await response.json();
295
- if (!data.ok) {
296
- throw new Error(data.error ?? "Unknown error");
297
- }
298
- }
299
- async function rotateConfigToken({
300
- refreshToken
301
- }) {
302
- const response = await fetch("https://slack.com/api/tooling.tokens.rotate", {
303
- method: "POST",
304
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
305
- body: new URLSearchParams({ refresh_token: refreshToken })
306
- });
307
- if (!response.ok) {
308
- throw new HTTPError(
309
- "Failed to rotate configuration token",
310
- response.status,
311
- response.statusText
312
- );
313
- }
314
- const data = await response.json();
315
- if (!data.ok || !data.token || !data.refresh_token) {
316
- throw new Error(data.error ?? "Unknown error rotating token");
317
- }
318
- return {
319
- token: data.token,
320
- refreshToken: data.refresh_token,
321
- exp: data.exp ?? 0
322
- };
323
- }
324
- async function authTest({
325
- token
326
- }) {
327
- const response = await fetch("https://slack.com/api/auth.test", {
328
- method: "POST",
329
- headers: {
330
- Authorization: `Bearer ${token}`,
331
- "Content-Type": "application/json; charset=utf-8"
332
- }
333
- });
334
- if (!response.ok) {
335
- throw new HTTPError(
336
- "Auth test failed",
337
- response.status,
338
- response.statusText
339
- );
340
- }
341
- const data = await response.json();
342
- if (!data.ok) {
343
- throw new Error(data.error ?? "Unknown error");
344
- }
345
- return {
346
- userId: data.user_id ?? "",
347
- teamId: data.team_id ?? ""
348
- };
349
- }
350
- async function verifyServiceTokenAccess(params) {
351
- try {
352
- await exportSlackApp({ token: params.serviceToken, appId: params.appId });
353
- return { hasAccess: true };
354
- } catch {
355
- return { hasAccess: false };
356
- }
357
- }
358
- async function installApp(params) {
359
- const { serviceToken, appId, botScopes, outgoingDomains } = params;
360
- if (!serviceToken) {
361
- return {
362
- status: "missing_service_token"
363
- };
364
- }
365
- const response = await fetch("https://slack.com/api/apps.developerInstall", {
366
- method: "POST",
367
- headers: {
368
- Authorization: `Bearer ${serviceToken}`,
369
- "Content-Type": "application/json; charset=utf-8"
370
- },
371
- body: JSON.stringify({
372
- app_id: appId,
373
- bot_scopes: botScopes,
374
- outgoing_domains: outgoingDomains ?? []
375
- })
376
- });
377
- if (!response.ok) {
378
- return {
379
- status: "slack_api_error",
380
- error: response.statusText
381
- };
382
- }
383
- const data = await response.json();
384
- if (data.error) {
385
- switch (data.error) {
386
- case "app_approval_request_eligible":
387
- return {
388
- status: "app_approval_request_eligible"
389
- };
390
- case "app_approval_request_pending":
391
- return {
392
- status: "app_approval_request_pending"
393
- };
394
- case "app_approval_request_denied":
395
- return {
396
- status: "app_approval_request_denied"
397
- };
398
- case "invalid_app_id": {
399
- if (serviceToken) {
400
- const { hasAccess } = await verifyServiceTokenAccess({
401
- serviceToken,
402
- appId
403
- });
404
- if (!hasAccess) {
405
- return { status: "no_access" };
406
- }
407
- }
408
- return { status: "invalid_app_id" };
409
- }
410
- default:
411
- return {
412
- status: "unknown_error"
413
- };
414
- }
415
- }
416
- return {
417
- status: "installed",
418
- botToken: data.api_access_tokens?.bot,
419
- appLevelToken: data.api_access_tokens?.app_level,
420
- userToken: data.api_access_tokens?.user
421
- };
422
- }
423
- var init_slack = chunkQHMZVK6J_js.__esm({
424
- "src/internal/slack/index.ts"() {
425
- init_errors();
426
- init_errors2();
427
- init_errors2();
428
- }
429
- });
430
- async function getProject({
431
- projectId,
432
- token,
433
- teamId
434
- }) {
435
- const url = new URL(
436
- `https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}`
437
- );
438
- if (teamId) url.searchParams.set("teamId", teamId);
439
- const response = await fetch(url, {
440
- method: "GET",
441
- headers: {
442
- Authorization: `Bearer ${token}`
443
- }
444
- });
445
- if (!response.ok) {
446
- throw await HTTPError.fromResponse(
447
- "Failed to access Vercel project",
448
- response
449
- );
450
- }
451
- }
452
- async function updateProtectionBypass({
453
- projectId,
454
- token,
455
- teamId
456
- }) {
457
- const newSecret = crypto__default.default.randomBytes(16).toString("hex");
458
- const note = "Created by @vercel/slack-bolt";
459
- const url = new URL(
460
- `https://api.vercel.com/v1/projects/${encodeURIComponent(projectId)}/protection-bypass`
461
- );
462
- if (teamId) url.searchParams.set("teamId", teamId);
463
- const response = await fetch(url, {
464
- method: "PATCH",
465
- headers: {
466
- Authorization: `Bearer ${token}`,
467
- "Content-Type": "application/json"
468
- },
469
- body: JSON.stringify({
470
- generate: {
471
- secret: newSecret,
472
- note
473
- }
474
- })
475
- });
476
- if (!response.ok) {
477
- throw await HTTPError.fromResponse(
478
- "Failed to update protection bypass",
479
- response
480
- );
481
- }
482
- return newSecret;
483
- }
484
- async function addEnvironmentVariables({
485
- projectId,
486
- token,
487
- teamId,
488
- envs,
489
- upsert = true
490
- }) {
491
- const url = new URL(
492
- `https://api.vercel.com/v10/projects/${encodeURIComponent(projectId)}/env`
493
- );
494
- if (teamId) url.searchParams.set("teamId", teamId);
495
- if (upsert) url.searchParams.set("upsert", "true");
496
- const response = await fetch(url, {
497
- method: "POST",
498
- headers: {
499
- Authorization: `Bearer ${token}`,
500
- "Content-Type": "application/json"
501
- },
502
- body: JSON.stringify(envs)
503
- });
504
- if (!response.ok) {
505
- throw await HTTPError.fromResponse(
506
- "Failed to create environment variables",
507
- response
508
- );
509
- }
510
- return response.json();
511
- }
512
- async function cancelDeployment({
513
- deploymentId,
514
- token,
515
- teamId
516
- }) {
517
- const url = new URL(
518
- `https://api.vercel.com/v12/deployments/${encodeURIComponent(deploymentId)}/cancel`
519
- );
520
- if (teamId) url.searchParams.set("teamId", teamId);
521
- const response = await fetch(url, {
522
- method: "PATCH",
523
- headers: { Authorization: `Bearer ${token}` }
524
- });
525
- if (!response.ok) {
526
- throw await HTTPError.fromResponse("Failed to cancel deployment", response);
527
- }
528
- }
529
- async function createDeployment({
530
- deploymentId,
531
- projectId,
532
- token,
533
- teamId
534
- }) {
535
- const url = new URL("https://api.vercel.com/v13/deployments");
536
- if (teamId) url.searchParams.set("teamId", teamId);
537
- url.searchParams.set("forceNew", "1");
538
- const response = await fetch(url, {
539
- method: "POST",
540
- headers: {
541
- Authorization: `Bearer ${token}`,
542
- "Content-Type": "application/json"
543
- },
544
- body: JSON.stringify({
545
- deploymentId,
546
- name: projectId,
547
- project: projectId
548
- })
549
- });
550
- if (!response.ok) {
551
- throw await HTTPError.fromResponse("Failed to create deployment", response);
552
- }
553
- const data = await response.json();
554
- return { id: data.id, url: data.url };
555
- }
556
- async function getActiveBranches({
557
- projectId,
558
- token,
559
- teamId
560
- }) {
561
- const params = new URLSearchParams({ active: "1", limit: "100" });
562
- if (teamId) params.set("teamId", teamId);
563
- const response = await fetch(
564
- `https://api.vercel.com/v5/projects/${encodeURIComponent(projectId)}/branches?${params}`,
565
- { headers: { Authorization: `Bearer ${token}` } }
566
- );
567
- if (!response.ok) {
568
- throw await HTTPError.fromResponse(
569
- "Failed to fetch active branches",
570
- response
571
- );
572
- }
573
- const data = await response.json();
574
- return new Set(data.branches?.map((b) => b.branch) ?? []);
575
- }
576
- async function getEnvironmentVariables({
577
- projectId,
578
- token,
579
- teamId
580
- }) {
581
- const url = new URL(
582
- `https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}/env`
583
- );
584
- if (teamId) url.searchParams.set("teamId", teamId);
585
- const response = await fetch(url, {
586
- headers: { Authorization: `Bearer ${token}` }
587
- });
588
- if (!response.ok) {
589
- throw await HTTPError.fromResponse(
590
- "Failed to fetch environment variables",
591
- response
592
- );
593
- }
594
- const data = await response.json();
595
- return data.envs ?? [];
596
- }
597
- async function getEnvironmentVariable({
598
- projectId,
599
- envId,
600
- token,
601
- teamId
602
- }) {
603
- const url = new URL(
604
- `https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}/env/${encodeURIComponent(envId)}`
605
- );
606
- if (teamId) url.searchParams.set("teamId", teamId);
607
- const response = await fetch(url, {
608
- headers: { Authorization: `Bearer ${token}` }
609
- });
610
- if (!response.ok) {
611
- throw await HTTPError.fromResponse(
612
- "Failed to fetch environment variable",
613
- response
614
- );
615
- }
616
- const data = await response.json();
617
- return data.value ?? null;
618
- }
619
- async function deleteEnvironmentVariable({
620
- projectId,
621
- envId,
622
- token,
623
- teamId
624
- }) {
625
- const url = new URL(
626
- `https://api.vercel.com/v9/projects/${encodeURIComponent(projectId)}/env/${encodeURIComponent(envId)}`
627
- );
628
- if (teamId) url.searchParams.set("teamId", teamId);
629
- const response = await fetch(url, {
630
- method: "DELETE",
631
- headers: { Authorization: `Bearer ${token}` }
632
- });
633
- if (!response.ok) {
634
- throw await HTTPError.fromResponse(
635
- "Failed to delete environment variable",
636
- response
637
- );
638
- }
639
- }
640
- var init_vercel = chunkQHMZVK6J_js.__esm({
641
- "src/internal/vercel/index.ts"() {
642
- init_errors();
643
- }
644
- });
645
-
646
- // src/logger.ts
647
- function isDebug() {
648
- return process.env.VERCEL_SLACK_DEBUG === "1" || process.env.VERCEL_SLACK_DEBUG === "true";
649
- }
650
- function isSensitiveKey(key) {
651
- const lower = key.toLowerCase();
652
- if (SENSITIVE_BODY_KEYS.has(lower)) return true;
653
- return SENSITIVE_KEY_PATTERNS.some((pattern) => lower.includes(pattern));
654
- }
655
- function redactValue(value) {
656
- if (value.length <= 4) return "****";
657
- return `****${value.slice(-4)}`;
658
- }
659
- function redactSensitiveFields(obj) {
660
- if (Array.isArray(obj)) {
661
- return obj.map((item) => redactSensitiveFields(item));
662
- }
663
- if (obj !== null && typeof obj === "object") {
664
- const result = {};
665
- for (const [key, val] of Object.entries(obj)) {
666
- if (isSensitiveKey(key) && typeof val === "string") {
667
- result[key] = redactValue(val);
668
- } else {
669
- result[key] = redactSensitiveFields(val);
670
- }
671
- }
672
- return result;
673
- }
674
- return obj;
675
- }
676
- function redactBody(body) {
677
- try {
678
- const parsed = JSON.parse(body);
679
- const redacted = redactSensitiveFields(parsed);
680
- return JSON.stringify(redacted);
681
- } catch {
682
- return `<non-JSON body, ${body.length} bytes>`;
683
- }
684
- }
685
- function formatHeaders(headers) {
686
- const entries = headers instanceof Headers ? [...headers.entries()] : Object.entries(headers ?? {});
687
- const redacted = entries.map(
688
- ([k, v]) => REDACTED_HEADERS.has(k.toLowerCase()) ? [k, `****${v.slice(-4)}`] : [k, v]
689
- );
690
- return JSON.stringify(Object.fromEntries(redacted));
691
- }
692
- function enableFetchDebugLogging() {
693
- if (globalThis.fetch.__debugPatched) return;
694
- const originalFetch = globalThis.fetch;
695
- const patched = async (input, init) => {
696
- const method = init?.method ?? "GET";
697
- const url = input instanceof Request ? input.url : input.toString();
698
- const start = performance.now();
699
- exports.log.debug(`-> ${method} ${url}`);
700
- exports.log.debug(` headers: ${formatHeaders(init?.headers)}`);
701
- if (typeof init?.body === "string")
702
- exports.log.debug(` body: ${redactBody(init.body)}`);
703
- const response = await originalFetch(input, init);
704
- const ms = (performance.now() - start).toFixed(0);
705
- exports.log.debug(`<- ${response.status} ${response.statusText} (${ms}ms)`);
706
- exports.log.debug(` headers: ${formatHeaders(response.headers)}`);
707
- const clone = response.clone();
708
- try {
709
- const body = await clone.text();
710
- if (body) exports.log.debug(` body: ${redactBody(body)}`);
711
- } catch {
712
- }
713
- return response;
714
- };
715
- patched.__debugPatched = true;
716
- globalThis.fetch = patched;
717
- }
718
- var BOLD, RESET, DIM, GREEN, YELLOW; exports.log = void 0; var REDACTED_HEADERS, SENSITIVE_BODY_KEYS, SENSITIVE_KEY_PATTERNS; exports.startMessage = void 0;
719
- var init_logger = chunkQHMZVK6J_js.__esm({
720
- "src/logger.ts"() {
721
- BOLD = "\x1B[1m";
722
- RESET = "\x1B[0m";
723
- DIM = "\x1B[2m";
724
- GREEN = "\x1B[32m";
725
- YELLOW = "\x1B[33m";
726
- exports.log = {
727
- step: (msg) => console.log(` ${msg} ...`),
728
- success: (msg) => console.log(`${GREEN}\u2713${RESET} ${msg}`),
729
- info: (msg) => console.log(` ${msg}`),
730
- warning: (msg) => console.log(`${YELLOW}\u26A0${RESET} ${msg}`),
731
- error: (...args) => console.error(...args),
732
- debug: (...args) => {
733
- if (isDebug()) {
734
- const msg = args.map((a) => typeof a === "string" ? a : String(a)).join(" ");
735
- console.debug(`${DIM}${msg}${RESET}`);
736
- }
737
- }
738
- };
739
- REDACTED_HEADERS = /* @__PURE__ */ new Set(["authorization"]);
740
- SENSITIVE_BODY_KEYS = /* @__PURE__ */ new Set([
741
- "token",
742
- "bot",
743
- "app_level",
744
- "user",
745
- "secret",
746
- "client_secret",
747
- "signing_secret",
748
- "verification_token",
749
- "bot_token",
750
- "user_token",
751
- "app_level_token",
752
- "value",
753
- "access_token",
754
- "refresh_token",
755
- "password"
756
- ]);
757
- SENSITIVE_KEY_PATTERNS = ["token", "secret", "password", "credential"];
758
- exports.startMessage = (version, branch, commit, appId) => {
759
- const lines = [`\u25B2 @vercel/slack-bolt ${version ?? ""}`];
760
- if (branch) lines.push(` - Branch: ${branch}`);
761
- if (commit) lines.push(` - Commit: ${commit.slice(0, 7)}`);
762
- if (appId) lines.push(` - App ID: ${appId}`);
763
- return `${BOLD}${lines.join("\n")}${RESET}
764
- `;
765
- };
766
- }
767
- });
768
- exports.preview = void 0;
769
- var init_preview = chunkQHMZVK6J_js.__esm({
770
- "src/preview.ts"() {
771
- init_manifest();
772
- init_parse();
773
- init_slack();
774
- init_vercel();
775
- init_logger();
776
- exports.preview = async (params, context) => {
777
- const {
778
- branch,
779
- projectId,
780
- deploymentUrl,
781
- teamId,
782
- commitAuthor,
783
- commitMessage: commitMsg,
784
- commitSha,
785
- slackAppId,
786
- slackConfigurationToken,
787
- slackServiceToken,
788
- manifestPath,
789
- vercelApiToken
790
- } = params;
791
- const cli = context === "cli";
792
- const branchUrl = params.branchUrl ?? deploymentUrl;
793
- let bypassSecret = params.automationBypassSecret;
794
- if (!bypassSecret) {
795
- if (cli) exports.log.step("Generating automation bypass secret");
796
- bypassSecret = await updateProtectionBypass({
797
- projectId,
798
- token: vercelApiToken,
799
- teamId
800
- });
801
- if (cli) exports.log.success("Automation bypass secret generated");
802
- }
803
- if (cli) exports.log.step(`Reading manifest from ${manifestPath}`);
804
- const rawFileManifest = fs__default.default.readFileSync(
805
- path2__default.default.join(process.cwd(), manifestPath),
806
- "utf8"
807
- );
808
- const manifest = parseManifest(rawFileManifest, manifestPath);
809
- const newManifest = createNewManifest({
810
- originalManifest: manifest,
811
- branchUrl,
812
- bypassSecret,
813
- branch,
814
- commitSha,
815
- commitMessage: commitMsg,
816
- commitAuthor
817
- });
818
- fs__default.default.writeFileSync(
819
- path2__default.default.join(process.cwd(), manifestPath),
820
- stringifyManifest(newManifest, manifestPath),
821
- "utf8"
822
- );
823
- if (cli) exports.log.success(`Manifest updated for ${branchUrl}`);
824
- if (cli) exports.log.step("Creating or updating Slack app");
825
- const { isNew, app } = await upsertSlackApp({
826
- token: slackConfigurationToken,
827
- appId: slackAppId,
828
- manifest: newManifest
829
- });
830
- if (isNew) {
831
- const credentialEnvs = [];
832
- if (app.app_id) {
833
- credentialEnvs.push({
834
- key: "SLACK_APP_ID",
835
- value: app.app_id,
836
- type: "encrypted",
837
- target: ["preview"],
838
- gitBranch: branch,
839
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
840
- });
841
- }
842
- if (app.credentials?.client_id) {
843
- credentialEnvs.push({
844
- key: "SLACK_CLIENT_ID",
845
- value: app.credentials.client_id,
846
- type: "encrypted",
847
- target: ["preview"],
848
- gitBranch: branch,
849
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
850
- });
851
- }
852
- if (app.credentials?.client_secret) {
853
- credentialEnvs.push({
854
- key: "SLACK_CLIENT_SECRET",
855
- value: app.credentials.client_secret,
856
- type: "encrypted",
857
- target: ["preview"],
858
- gitBranch: branch,
859
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
860
- });
861
- }
862
- if (app.credentials?.signing_secret) {
863
- credentialEnvs.push({
864
- key: "SLACK_SIGNING_SECRET",
865
- value: app.credentials.signing_secret,
866
- type: "encrypted",
867
- target: ["preview"],
868
- gitBranch: branch,
869
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
870
- });
871
- }
872
- if (credentialEnvs.length > 0) {
873
- await addEnvironmentVariables({
874
- projectId,
875
- token: vercelApiToken,
876
- teamId,
877
- envs: credentialEnvs
878
- });
879
- }
880
- }
881
- if (cli)
882
- exports.log.success(`${isNew ? "Created" : "Updated"} Slack app ${app.app_id}`);
883
- if (cli) exports.log.step("Installing Slack app");
884
- const { status, botToken, appLevelToken, userToken } = await installApp({
885
- serviceToken: slackServiceToken,
886
- appId: app.app_id,
887
- botScopes: manifest.oauth_config?.scopes?.bot ?? []
888
- });
889
- if (isNew) {
890
- const tokenEnvs = [];
891
- if (botToken) {
892
- tokenEnvs.push({
893
- key: "SLACK_BOT_TOKEN",
894
- value: botToken,
895
- type: "encrypted",
896
- target: ["preview"],
897
- gitBranch: branch,
898
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
899
- });
900
- }
901
- if (appLevelToken) {
902
- tokenEnvs.push({
903
- key: "SLACK_APP_LEVEL_TOKEN",
904
- value: appLevelToken,
905
- type: "encrypted",
906
- target: ["preview"],
907
- gitBranch: branch,
908
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
909
- });
910
- }
911
- if (userToken) {
912
- tokenEnvs.push({
913
- key: "SLACK_USER_TOKEN",
914
- value: userToken,
915
- type: "encrypted",
916
- target: ["preview"],
917
- gitBranch: branch,
918
- comment: `Created by @vercel/slack-bolt for app ${app.app_id} on branch ${branch}`
919
- });
920
- }
921
- if (tokenEnvs.length > 0) {
922
- await addEnvironmentVariables({
923
- projectId,
924
- token: vercelApiToken,
925
- teamId,
926
- envs: tokenEnvs
927
- });
928
- }
929
- }
930
- if (cli) {
931
- switch (status) {
932
- case "missing_service_token":
933
- exports.log.warning(
934
- "SLACK_SERVICE_TOKEN is not set \u2014 app must be installed manually"
935
- );
936
- exports.log.info("https://docs.slack.dev/authentication/tokens/#service");
937
- break;
938
- case "installed":
939
- exports.log.success(`Installed Slack app ${app.app_id}`);
940
- break;
941
- case "app_approval_request_eligible":
942
- exports.log.warning("App requires approval before it can be installed");
943
- break;
944
- case "app_approval_request_pending":
945
- exports.log.warning("App is pending approval before it can be installed");
946
- break;
947
- case "app_approval_request_denied":
948
- exports.log.warning("App approval request was denied");
949
- break;
950
- case "no_access":
951
- exports.log.warning(
952
- `SLACK_SERVICE_TOKEN does not have access to app ${app.app_id}. This usually means the service token and configuration token were created by different users. Ensure both tokens are generated by the same Slack user.
953
- https://docs.slack.dev/authentication/tokens/#service`
954
- );
955
- break;
956
- case "invalid_app_id":
957
- exports.log.warning(
958
- "Invalid app ID. This is a bug in the @vercel/slack-bolt package. Please open an issue at https://github.com/vercel/slack-bolt/issues"
959
- );
960
- break;
961
- case "slack_api_error":
962
- exports.log.warning("Slack API error while installing the app");
963
- break;
964
- case "unknown_error":
965
- exports.log.warning("Unknown error while installing the app");
966
- break;
967
- }
968
- console.log();
969
- if (app.app_id) {
970
- exports.log.info(`View app: https://api.slack.com/apps/${app.app_id}`);
971
- }
972
- if (isNew && app.oauth_authorize_url) {
973
- exports.log.info(`Install URL: ${app.oauth_authorize_url}`);
974
- }
975
- console.log();
976
- }
977
- return {
978
- isNew,
979
- installStatus: status,
980
- app
981
- };
982
- };
983
- }
984
- });
985
-
986
- exports.addEnvironmentVariables = addEnvironmentVariables;
987
- exports.authTest = authTest;
988
- exports.cancelDeployment = cancelDeployment;
989
- exports.createDeployment = createDeployment;
990
- exports.deleteEnvironmentVariable = deleteEnvironmentVariable;
991
- exports.deleteSlackApp = deleteSlackApp;
992
- exports.enableFetchDebugLogging = enableFetchDebugLogging;
993
- exports.getActiveBranches = getActiveBranches;
994
- exports.getEnvironmentVariable = getEnvironmentVariable;
995
- exports.getEnvironmentVariables = getEnvironmentVariables;
996
- exports.getProject = getProject;
997
- exports.init_logger = init_logger;
998
- exports.init_preview = init_preview;
999
- exports.init_slack = init_slack;
1000
- exports.init_vercel = init_vercel;
1001
- exports.rotateConfigToken = rotateConfigToken;
1002
- //# sourceMappingURL=chunk-DYB6RJG4.js.map
1003
- //# sourceMappingURL=chunk-DYB6RJG4.js.map