@distilled.cloud/slack 0.0.0 → 1.0.0-rc.10

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 (212) hide show
  1. package/LICENSE +201 -0
  2. package/lib/credentials.d.ts +27 -0
  3. package/lib/credentials.d.ts.map +1 -0
  4. package/lib/credentials.js +53 -0
  5. package/lib/credentials.js.map +1 -0
  6. package/lib/errors.d.ts +83 -0
  7. package/lib/errors.d.ts.map +1 -0
  8. package/lib/errors.js +59 -0
  9. package/lib/errors.js.map +1 -0
  10. package/lib/index.d.ts +17 -0
  11. package/lib/index.d.ts.map +1 -0
  12. package/lib/index.js +17 -0
  13. package/lib/index.js.map +1 -0
  14. package/lib/pagination.d.ts +31 -0
  15. package/lib/pagination.d.ts.map +1 -0
  16. package/lib/pagination.js +31 -0
  17. package/lib/pagination.js.map +1 -0
  18. package/lib/protocol.d.ts +18 -0
  19. package/lib/protocol.d.ts.map +1 -0
  20. package/lib/protocol.js +230 -0
  21. package/lib/protocol.js.map +1 -0
  22. package/lib/retry.d.ts +52 -0
  23. package/lib/retry.d.ts.map +1 -0
  24. package/lib/retry.js +45 -0
  25. package/lib/retry.js.map +1 -0
  26. package/lib/services/admin.d.ts +2796 -0
  27. package/lib/services/admin.d.ts.map +1 -0
  28. package/lib/services/admin.js +3217 -0
  29. package/lib/services/admin.js.map +1 -0
  30. package/lib/services/api.d.ts +23 -0
  31. package/lib/services/api.d.ts.map +1 -0
  32. package/lib/services/api.js +26 -0
  33. package/lib/services/api.js.map +1 -0
  34. package/lib/services/apps.d.ts +568 -0
  35. package/lib/services/apps.d.ts.map +1 -0
  36. package/lib/services/apps.js +584 -0
  37. package/lib/services/apps.js.map +1 -0
  38. package/lib/services/assistant.d.ts +290 -0
  39. package/lib/services/assistant.d.ts.map +1 -0
  40. package/lib/services/assistant.js +232 -0
  41. package/lib/services/assistant.js.map +1 -0
  42. package/lib/services/auth.d.ts +90 -0
  43. package/lib/services/auth.d.ts.map +1 -0
  44. package/lib/services/auth.js +114 -0
  45. package/lib/services/auth.js.map +1 -0
  46. package/lib/services/blocks.d.ts +31 -0
  47. package/lib/services/blocks.d.ts.map +1 -0
  48. package/lib/services/blocks.js +31 -0
  49. package/lib/services/blocks.js.map +1 -0
  50. package/lib/services/bookmarks.d.ts +91 -0
  51. package/lib/services/bookmarks.d.ts.map +1 -0
  52. package/lib/services/bookmarks.js +98 -0
  53. package/lib/services/bookmarks.js.map +1 -0
  54. package/lib/services/bots.d.ts +60 -0
  55. package/lib/services/bots.d.ts.map +1 -0
  56. package/lib/services/bots.js +68 -0
  57. package/lib/services/bots.js.map +1 -0
  58. package/lib/services/calls.d.ts +124 -0
  59. package/lib/services/calls.d.ts.map +1 -0
  60. package/lib/services/calls.js +136 -0
  61. package/lib/services/calls.js.map +1 -0
  62. package/lib/services/canvases.d.ts +152 -0
  63. package/lib/services/canvases.d.ts.map +1 -0
  64. package/lib/services/canvases.js +152 -0
  65. package/lib/services/canvases.js.map +1 -0
  66. package/lib/services/chat.d.ts +525 -0
  67. package/lib/services/chat.d.ts.map +1 -0
  68. package/lib/services/chat.js +436 -0
  69. package/lib/services/chat.js.map +1 -0
  70. package/lib/services/conversations.d.ts +642 -0
  71. package/lib/services/conversations.d.ts.map +1 -0
  72. package/lib/services/conversations.js +769 -0
  73. package/lib/services/conversations.js.map +1 -0
  74. package/lib/services/dialog.d.ts +20 -0
  75. package/lib/services/dialog.d.ts.map +1 -0
  76. package/lib/services/dialog.js +27 -0
  77. package/lib/services/dialog.js.map +1 -0
  78. package/lib/services/dnd.d.ts +94 -0
  79. package/lib/services/dnd.d.ts.map +1 -0
  80. package/lib/services/dnd.js +111 -0
  81. package/lib/services/dnd.js.map +1 -0
  82. package/lib/services/emoji.d.ts +35 -0
  83. package/lib/services/emoji.d.ts.map +1 -0
  84. package/lib/services/emoji.js +40 -0
  85. package/lib/services/emoji.js.map +1 -0
  86. package/lib/services/entity.d.ts +93 -0
  87. package/lib/services/entity.d.ts.map +1 -0
  88. package/lib/services/entity.js +89 -0
  89. package/lib/services/entity.js.map +1 -0
  90. package/lib/services/files.d.ts +473 -0
  91. package/lib/services/files.d.ts.map +1 -0
  92. package/lib/services/files.js +510 -0
  93. package/lib/services/files.js.map +1 -0
  94. package/lib/services/functions.d.ts +235 -0
  95. package/lib/services/functions.d.ts.map +1 -0
  96. package/lib/services/functions.js +256 -0
  97. package/lib/services/functions.js.map +1 -0
  98. package/lib/services/index.d.ts +35 -0
  99. package/lib/services/index.d.ts.map +1 -0
  100. package/lib/services/index.js +36 -0
  101. package/lib/services/index.js.map +1 -0
  102. package/lib/services/lists.d.ts +300 -0
  103. package/lib/services/lists.d.ts.map +1 -0
  104. package/lib/services/lists.js +366 -0
  105. package/lib/services/lists.js.map +1 -0
  106. package/lib/services/migration.d.ts +34 -0
  107. package/lib/services/migration.d.ts.map +1 -0
  108. package/lib/services/migration.js +36 -0
  109. package/lib/services/migration.js.map +1 -0
  110. package/lib/services/oauth.d.ts +307 -0
  111. package/lib/services/oauth.d.ts.map +1 -0
  112. package/lib/services/oauth.js +278 -0
  113. package/lib/services/oauth.js.map +1 -0
  114. package/lib/services/openid.d.ts +86 -0
  115. package/lib/services/openid.d.ts.map +1 -0
  116. package/lib/services/openid.js +93 -0
  117. package/lib/services/openid.js.map +1 -0
  118. package/lib/services/pins.d.ts +64 -0
  119. package/lib/services/pins.d.ts.map +1 -0
  120. package/lib/services/pins.js +75 -0
  121. package/lib/services/pins.js.map +1 -0
  122. package/lib/services/reactions.d.ts +108 -0
  123. package/lib/services/reactions.d.ts.map +1 -0
  124. package/lib/services/reactions.js +119 -0
  125. package/lib/services/reactions.js.map +1 -0
  126. package/lib/services/reminders.d.ts +89 -0
  127. package/lib/services/reminders.d.ts.map +1 -0
  128. package/lib/services/reminders.js +109 -0
  129. package/lib/services/reminders.js.map +1 -0
  130. package/lib/services/rtm.d.ts +68 -0
  131. package/lib/services/rtm.d.ts.map +1 -0
  132. package/lib/services/rtm.js +74 -0
  133. package/lib/services/rtm.js.map +1 -0
  134. package/lib/services/search.d.ts +239 -0
  135. package/lib/services/search.d.ts.map +1 -0
  136. package/lib/services/search.js +190 -0
  137. package/lib/services/search.js.map +1 -0
  138. package/lib/services/stars.d.ts +126 -0
  139. package/lib/services/stars.d.ts.map +1 -0
  140. package/lib/services/stars.js +145 -0
  141. package/lib/services/stars.js.map +1 -0
  142. package/lib/services/team.d.ts +309 -0
  143. package/lib/services/team.d.ts.map +1 -0
  144. package/lib/services/team.js +333 -0
  145. package/lib/services/team.js.map +1 -0
  146. package/lib/services/tooling.d.ts +31 -0
  147. package/lib/services/tooling.d.ts.map +1 -0
  148. package/lib/services/tooling.js +38 -0
  149. package/lib/services/tooling.js.map +1 -0
  150. package/lib/services/usergroups.d.ts +183 -0
  151. package/lib/services/usergroups.d.ts.map +1 -0
  152. package/lib/services/usergroups.js +180 -0
  153. package/lib/services/usergroups.js.map +1 -0
  154. package/lib/services/users.d.ts +246 -0
  155. package/lib/services/users.d.ts.map +1 -0
  156. package/lib/services/users.js +309 -0
  157. package/lib/services/users.js.map +1 -0
  158. package/lib/services/views.d.ts +84 -0
  159. package/lib/services/views.d.ts.map +1 -0
  160. package/lib/services/views.js +95 -0
  161. package/lib/services/views.js.map +1 -0
  162. package/lib/services/workflows.d.ts +231 -0
  163. package/lib/services/workflows.d.ts.map +1 -0
  164. package/lib/services/workflows.js +238 -0
  165. package/lib/services/workflows.js.map +1 -0
  166. package/lib/traits.d.ts +11 -0
  167. package/lib/traits.d.ts.map +1 -0
  168. package/lib/traits.js +12 -0
  169. package/lib/traits.js.map +1 -0
  170. package/package.json +82 -4
  171. package/src/credentials.ts +86 -0
  172. package/src/errors.ts +101 -0
  173. package/src/index.ts +20 -0
  174. package/src/pagination.ts +35 -0
  175. package/src/protocol.ts +326 -0
  176. package/src/retry.ts +76 -0
  177. package/src/services/admin.ts +7722 -0
  178. package/src/services/api.ts +58 -0
  179. package/src/services/apps.ts +1441 -0
  180. package/src/services/assistant.ts +639 -0
  181. package/src/services/auth.ts +241 -0
  182. package/src/services/blocks.ts +80 -0
  183. package/src/services/bookmarks.ts +223 -0
  184. package/src/services/bots.ts +144 -0
  185. package/src/services/calls.ts +318 -0
  186. package/src/services/canvases.ts +392 -0
  187. package/src/services/chat.ts +1191 -0
  188. package/src/services/conversations.ts +1754 -0
  189. package/src/services/dialog.ts +55 -0
  190. package/src/services/dnd.ts +246 -0
  191. package/src/services/emoji.ts +91 -0
  192. package/src/services/entity.ts +225 -0
  193. package/src/services/files.ts +1192 -0
  194. package/src/services/functions.ts +642 -0
  195. package/src/services/index.ts +35 -0
  196. package/src/services/lists.ts +832 -0
  197. package/src/services/migration.ts +85 -0
  198. package/src/services/oauth.ts +658 -0
  199. package/src/services/openid.ts +243 -0
  200. package/src/services/pins.ts +167 -0
  201. package/src/services/reactions.ts +272 -0
  202. package/src/services/reminders.ts +240 -0
  203. package/src/services/rtm.ts +162 -0
  204. package/src/services/search.ts +507 -0
  205. package/src/services/stars.ts +323 -0
  206. package/src/services/team.ts +834 -0
  207. package/src/services/tooling.ts +78 -0
  208. package/src/services/usergroups.ts +441 -0
  209. package/src/services/users.ts +685 -0
  210. package/src/services/views.ts +212 -0
  211. package/src/services/workflows.ts +605 -0
  212. package/src/traits.ts +45 -0
package/package.json CHANGED
@@ -1,6 +1,84 @@
1
1
  {
2
2
  "name": "@distilled.cloud/slack",
3
- "version": "0.0.0",
4
- "description": "placeholder",
5
- "license": "Apache-2.0"
6
- }
3
+ "version": "1.0.0-rc.10",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "https://github.com/alchemy-run/distilled",
7
+ "directory": "packages/slack"
8
+ },
9
+ "license": "Apache-2.0",
10
+ "type": "module",
11
+ "sideEffects": false,
12
+ "files": [
13
+ "lib",
14
+ "src"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./lib/index.d.ts",
19
+ "bun": "./src/index.ts",
20
+ "worker": "./src/index.ts",
21
+ "default": "./lib/index.js"
22
+ },
23
+ "./Credentials": {
24
+ "types": "./lib/credentials.d.ts",
25
+ "bun": "./src/credentials.ts",
26
+ "worker": "./src/credentials.ts",
27
+ "default": "./lib/credentials.js"
28
+ },
29
+ "./Errors": {
30
+ "types": "./lib/errors.d.ts",
31
+ "bun": "./src/errors.ts",
32
+ "worker": "./src/errors.ts",
33
+ "default": "./lib/errors.js"
34
+ },
35
+ "./Traits": {
36
+ "types": "./lib/traits.d.ts",
37
+ "bun": "./src/traits.ts",
38
+ "worker": "./src/traits.ts",
39
+ "default": "./lib/traits.js"
40
+ },
41
+ "./Protocol": {
42
+ "types": "./lib/protocol.d.ts",
43
+ "bun": "./src/protocol.ts",
44
+ "worker": "./src/protocol.ts",
45
+ "default": "./lib/protocol.js"
46
+ },
47
+ "./Retry": {
48
+ "types": "./lib/retry.d.ts",
49
+ "bun": "./src/retry.ts",
50
+ "worker": "./src/retry.ts",
51
+ "default": "./lib/retry.js"
52
+ },
53
+ "./Pagination": {
54
+ "types": "./lib/pagination.d.ts",
55
+ "bun": "./src/pagination.ts",
56
+ "worker": "./src/pagination.ts",
57
+ "default": "./lib/pagination.js"
58
+ },
59
+ "./*": {
60
+ "types": "./lib/services/*.d.ts",
61
+ "bun": "./src/services/*.ts",
62
+ "worker": "./src/services/*.ts",
63
+ "default": "./lib/services/*.js"
64
+ }
65
+ },
66
+ "dependencies": {
67
+ "@distilled.cloud/core": "1.0.0-rc.10"
68
+ },
69
+ "devDependencies": {
70
+ "@types/bun": "1.3.14",
71
+ "@types/node": "26.2.0",
72
+ "@effect/platform-bun": ">=4.0.0-rc.115 || >=4.0.0"
73
+ },
74
+ "peerDependencies": {
75
+ "effect": ">=4.0.0-rc.115 || >=4.0.0"
76
+ },
77
+ "scripts": {
78
+ "build": "tsc -b",
79
+ "download-docs": "bun scripts/download-docs.ts",
80
+ "convert": "bun scripts/convert.ts",
81
+ "generate": "bun scripts/convert.ts && bun scripts/generate.ts",
82
+ "typecheck": "tsc -p tsconfig.json"
83
+ }
84
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Slack credentials — hand-written.
3
+ *
4
+ * The `Credentials` service resolves `{ token, apiBaseUrl }` per request; the
5
+ * protocol layer formats the `Authorization: Bearer <token>` header from it.
6
+ *
7
+ * Slack authorizes Web API calls with one bearer token, and the token's
8
+ * PREFIX carries its kind (https://docs.slack.dev/authentication/tokens):
9
+ * • `xoxb-…` — a bot token (what almost every integration uses)
10
+ * • `xoxp-…` — a user token, for calls made on behalf of a user
11
+ * • `xoxe.xoxb-…` / `xoxe.xoxp-…` — rotating (expiring) variants
12
+ * • `xapp-…` — an app-level token (Socket Mode / `apps.connections.open`)
13
+ * The header is the same for all of them, so there is no token-type knob.
14
+ *
15
+ * The OAuth exchange methods (`oauth.v2.access`, `openid.connect.token`, …)
16
+ * authenticate with `client_id`/`client_secret` args instead of a token — for
17
+ * those, an empty-string token is allowed and the protocol simply omits the
18
+ * Authorization header.
19
+ */
20
+ import * as EffectConfig from "effect/Config";
21
+ import * as Context from "effect/Context";
22
+ import * as Effect from "effect/Effect";
23
+ import * as Layer from "effect/Layer";
24
+ import * as Redacted from "effect/Redacted";
25
+ import { ConfigError } from "@distilled.cloud/core/errors";
26
+
27
+ /**
28
+ * Slack Web API base URL. Every method is `POST/GET <base>/<method>`.
29
+ * Override via `SLACK_API_URL` only to point at a proxy or a mock.
30
+ */
31
+ export const DEFAULT_API_BASE_URL = "https://slack.com/api";
32
+
33
+ export interface Config {
34
+ readonly token: Redacted.Redacted<string>;
35
+ readonly apiBaseUrl: string;
36
+ }
37
+
38
+ export class Credentials extends Context.Service<
39
+ Credentials,
40
+ Effect.Effect<Config>
41
+ >()("SlackCredentials") {}
42
+
43
+ const envConfig = EffectConfig.all({
44
+ // SLACK_BOT_TOKEN is the spelling Bolt and most hosting platforms use;
45
+ // SLACK_TOKEN is the fallback (the node SDK's CLI convention).
46
+ token: EffectConfig.String("SLACK_BOT_TOKEN").pipe(
47
+ EffectConfig.orElse(() => EffectConfig.String("SLACK_TOKEN")),
48
+ ),
49
+ apiBaseUrl: EffectConfig.String("SLACK_API_URL").pipe(
50
+ EffectConfig.withDefault(DEFAULT_API_BASE_URL),
51
+ ),
52
+ });
53
+
54
+ export const CredentialsFromEnv = Layer.succeed(
55
+ Credentials,
56
+ envConfig.pipe(
57
+ Effect.mapError(
58
+ () =>
59
+ new ConfigError({
60
+ message:
61
+ "SLACK_BOT_TOKEN (or SLACK_TOKEN) environment variable is required",
62
+ }),
63
+ ),
64
+ Effect.map(({ token, apiBaseUrl }) => ({
65
+ token: Redacted.make(token),
66
+ apiBaseUrl,
67
+ })),
68
+ Effect.orDie,
69
+ ),
70
+ );
71
+
72
+ /**
73
+ * Convenience layer from a plain token + optional base URL. Pass an empty
74
+ * token (`""`) for the credential-less OAuth exchange methods.
75
+ */
76
+ export const credentials = (config: {
77
+ readonly token: string;
78
+ readonly apiBaseUrl?: string;
79
+ }): Layer.Layer<Credentials> =>
80
+ Layer.succeed(
81
+ Credentials,
82
+ Effect.succeed({
83
+ token: Redacted.make(config.token),
84
+ apiBaseUrl: config.apiBaseUrl ?? DEFAULT_API_BASE_URL,
85
+ }),
86
+ );
package/src/errors.ts ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Slack-specific error types.
3
+ *
4
+ * Slack reports failures as `{ "ok": false, "error": "<slug>" }` — usually
5
+ * with HTTP 200 — so the interesting field is the machine-readable `error`
6
+ * slug, not the status. The protocol maps the well-known infrastructure
7
+ * slugs (auth, throttling, server hiccups) onto core's shared HTTP error
8
+ * classes and surfaces everything else as {@link SlackError} with the slug
9
+ * preserved for branching. Each generated operation's doc comment lists the
10
+ * slugs that method can produce.
11
+ */
12
+ export {
13
+ BadGateway,
14
+ BadRequest,
15
+ Conflict,
16
+ ConfigError,
17
+ Forbidden,
18
+ GatewayTimeout,
19
+ InternalServerError,
20
+ NotFound,
21
+ ServiceUnavailable,
22
+ TooManyRequests,
23
+ Unauthorized,
24
+ UnprocessableEntity,
25
+ HTTP_STATUS_MAP,
26
+ DEFAULT_ERRORS,
27
+ API_ERRORS,
28
+ } from "@distilled.cloud/core/errors";
29
+ import type { DefaultErrors as CoreDefaultErrors } from "@distilled.cloud/core/errors";
30
+
31
+ import * as Schema from "effect/Schema";
32
+ import * as Category from "@distilled.cloud/core/category";
33
+ import { withCategory } from "@distilled.cloud/core/error-category";
34
+ import { DurationSchema, RETRYABLE } from "@distilled.cloud/core/errors";
35
+
36
+ /**
37
+ * A Slack API error envelope: `ok: false` with a machine-readable slug.
38
+ * `code` is the slug (`channel_not_found`, `invalid_blocks`, …) — the field
39
+ * to branch on; the per-method slugs are listed in each operation's doc
40
+ * comment. `needed`/`provided` carry scope detail on `missing_scope`;
41
+ * `messages` carries the envelope's `response_metadata.messages` (per-field
42
+ * validation detail on `invalid_arguments`).
43
+ */
44
+ export class SlackError extends Schema.TaggedError<SlackError>()("SlackError", {
45
+ code: Schema.String,
46
+ message: Schema.optional(Schema.String),
47
+ needed: Schema.optional(Schema.String),
48
+ provided: Schema.optional(Schema.String),
49
+ messages: Schema.optional(Schema.Array(Schema.String)),
50
+ }) {}
51
+
52
+ /**
53
+ * Slack rate limit — a 429 or the `rate_limited`/`ratelimited` slug. Slack
54
+ * answers with a `Retry-After` header the default retry policy honors.
55
+ */
56
+ export class SlackRateLimited extends Schema.TaggedError<SlackRateLimited>()(
57
+ "SlackRateLimited",
58
+ {
59
+ code: Schema.String,
60
+ message: Schema.optional(Schema.String),
61
+ retryAfter: Schema.optional(DurationSchema),
62
+ },
63
+ ).pipe(withCategory(RETRYABLE), Category.withThrottlingError) {}
64
+
65
+ /**
66
+ * HTTP error — a non-2xx response without a parseable Slack error envelope
67
+ * (proxy pages, HTML 5xx bodies).
68
+ */
69
+ export class SlackHttpError extends Schema.TaggedError<SlackHttpError>()(
70
+ "SlackHttpError",
71
+ {
72
+ status: Schema.Number,
73
+ message: Schema.String,
74
+ body: Schema.optional(Schema.String),
75
+ },
76
+ ) {}
77
+
78
+ /** Schema parse error wrapper. */
79
+ export class SlackParseError extends Schema.TaggedError<SlackParseError>()(
80
+ "SlackParseError",
81
+ {
82
+ body: Schema.Unknown,
83
+ cause: Schema.Unknown,
84
+ },
85
+ ).pipe(Category.withParseError) {}
86
+
87
+ /**
88
+ * Errors any Slack operation may surface in addition to the shared HTTP
89
+ * status errors.
90
+ */
91
+ export type ClientErrors =
92
+ | SlackError
93
+ | SlackRateLimited
94
+ | SlackHttpError
95
+ | SlackParseError;
96
+
97
+ /**
98
+ * Default Slack operation errors: the shared HTTP status errors from core
99
+ * plus the client-level envelope/decode errors.
100
+ */
101
+ export type DefaultErrors = CoreDefaultErrors | ClientErrors;
package/src/index.ts ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @distilled.cloud/slack — Slack Web API SDK for Effect.
3
+ *
4
+ * `./services` is generated by `scripts/generate.ts` from the Smithy models
5
+ * in `.generated-specs` (written by `scripts/convert.ts` from the JSON twins
6
+ * of the docs.slack.dev method reference, downloaded by
7
+ * `scripts/download-docs.ts`). Everything else in this folder is
8
+ * hand-written.
9
+ */
10
+ export * from "./credentials.ts";
11
+ export * from "./errors.ts";
12
+ export * as T from "./traits.ts";
13
+ export {
14
+ SlackProtocol,
15
+ type SlackOpError,
16
+ type SlackOpContext,
17
+ } from "./protocol.ts";
18
+ export * as Retry from "./retry.ts";
19
+ export * as Pagination from "./pagination.ts";
20
+ export * as Services from "./services/index.ts";
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Slack pagination — hand-written.
3
+ *
4
+ * Slack's cursor convention: pass `cursor` (from the previous response's
5
+ * `response_metadata.next_cursor`), and an EMPTY `next_cursor` means the
6
+ * last page — which is exactly core's cursor traversal (`isTerminalToken`
7
+ * treats `""` as terminal). Paginated operations are compiled with this
8
+ * strategy by scripts/generate.ts from the `smithy.api#paginated` traits the
9
+ * converter stamps.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import * as Effect from "effect/Effect";
14
+ * import * as Stream from "effect/Stream";
15
+ * import * as Users from "@distilled.cloud/slack/users";
16
+ *
17
+ * // Every member, cursors followed automatically:
18
+ * const members = Users.list.items({ limit: 200 }).pipe(
19
+ * Stream.runCollect,
20
+ * );
21
+ * // Or page by page:
22
+ * const pages = Users.list.pages({ limit: 200 });
23
+ * ```
24
+ */
25
+ import * as Pagination from "@distilled.cloud/core/pagination";
26
+
27
+ /**
28
+ * Cursor traversal for Slack: follow `response_metadata.next_cursor` until
29
+ * it comes back empty/absent.
30
+ */
31
+ export const slackPaginate: Pagination.PaginationStrategy = (
32
+ operation,
33
+ input,
34
+ pagination,
35
+ ) => Pagination.paginateCursor(operation, input, pagination);
@@ -0,0 +1,326 @@
1
+ /**
2
+ * SlackProtocol — hand-written.
3
+ *
4
+ * Speaks the Slack Web API convention. The generic request/response machinery
5
+ * (trait-driven request building, recursive wire-name mapping, typed-error
6
+ * matcher evaluation) lives in `@distilled.cloud/core/protocol-http`; this
7
+ * module supplies what is Slack's own:
8
+ *
9
+ * request: credentials → `Authorization: Bearer <token>` (omitted for an
10
+ * empty token — the OAuth exchange methods authenticate with
11
+ * `client_id`/`client_secret` args instead), and array-valued
12
+ * query args joined with commas (`channel_ids=C1,C2` — Slack
13
+ * reads comma-separated lists, not repeated params)
14
+ *
15
+ * response: `{ "ok": true, …payload }` — the payload shares the envelope's
16
+ * level, so a successful body maps onto the output schema
17
+ * directly (`ok` is a modeled member).
18
+ * `{ "ok": false, "error": "<slug>" }` — usually WITH HTTP 200 —
19
+ * becomes a typed error: per-op matcher classes first, then the
20
+ * infrastructure slugs (auth → Unauthorized, throttling →
21
+ * SlackRateLimited, server hiccups → retryable 5xx classes),
22
+ * then {@link SlackError} carrying the slug.
23
+ * A successful NON-JSON body is returned as raw bytes — the one
24
+ * method that answers this way (`admin.analytics.getFile`) sends
25
+ * a gzipped NDJSON file.
26
+ */
27
+ import * as Effect from "effect/Effect";
28
+ import * as Layer from "effect/Layer";
29
+ import type * as AST from "effect/SchemaAST";
30
+ import type * as HttpClient from "effect/unstable/http/HttpClient";
31
+ import type * as HttpClientError from "effect/unstable/http/HttpClientError";
32
+ import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
33
+ import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
34
+ import * as Redacted from "effect/Redacted";
35
+ import * as API from "@distilled.cloud/core/api";
36
+ import {
37
+ httpSymbol,
38
+ querySymbol,
39
+ type HttpTrait,
40
+ } from "@distilled.cloud/core/trait";
41
+ import {
42
+ buildRequest,
43
+ getAnn,
44
+ getProps,
45
+ hasPropAnn,
46
+ mapKeys,
47
+ matchTypedError,
48
+ } from "@distilled.cloud/core/protocol-http";
49
+ import {
50
+ unwrapRedactedDeep,
51
+ wrapSensitive,
52
+ } from "@distilled.cloud/core/protocol-rest";
53
+ import {
54
+ ConfigError,
55
+ GatewayTimeout,
56
+ HTTP_STATUS_MAP,
57
+ InternalServerError,
58
+ ServiceUnavailable,
59
+ Unauthorized,
60
+ } from "@distilled.cloud/core/errors";
61
+ import {
62
+ parseRetryAfterForStatus,
63
+ parseServerRetryHint,
64
+ } from "@distilled.cloud/core/retry-after";
65
+ import { Credentials, type Config } from "./credentials.ts";
66
+ import {
67
+ type DefaultErrors,
68
+ SlackError,
69
+ SlackHttpError,
70
+ SlackRateLimited,
71
+ } from "./errors.ts";
72
+
73
+ /**
74
+ * Error channel shared by every generated Slack operation. Generated service
75
+ * files annotate operations with `API.OperationMethod<I, O, SlackOpError,
76
+ * SlackOpContext>` explicitly so the compiler never infers these back out of
77
+ * the schema generics.
78
+ */
79
+ export type SlackOpError =
80
+ | DefaultErrors
81
+ | ConfigError
82
+ | HttpClientError.HttpClientError;
83
+
84
+ /** Context (requirements) shared by every generated Slack operation. */
85
+ export type SlackOpContext = Credentials | HttpClient.HttpClient;
86
+
87
+ // Bridge: Protocol.decode is typed as Effect<unknown> (no error channel), but
88
+ // Slack failures are real typed errors that an operation re-surfaces via its
89
+ // `errors: [...]` list. Fail with the instance and erase the error type here;
90
+ // `API.make`'s signature reintroduces it for callers.
91
+ const fail = (e: unknown): Effect.Effect<never> =>
92
+ Effect.fail(e) as Effect.Effect<never>;
93
+
94
+ /**
95
+ * Envelope slugs that mean "the token is no good" on ANY method — mapped to
96
+ * the shared Unauthorized class so one catch handles credential problems
97
+ * across the SDK. Permission-shaped slugs (`missing_scope`, `no_permission`,
98
+ * `access_denied`, …) stay {@link SlackError}: they carry method-specific
99
+ * detail (`needed`/`provided`) the shared class would drop.
100
+ */
101
+ const AUTH_SLUGS = new Set([
102
+ "not_authed",
103
+ "invalid_auth",
104
+ "account_inactive",
105
+ "token_revoked",
106
+ "token_expired",
107
+ ]);
108
+
109
+ /** Envelope slugs that are Slack-side hiccups — retryable server errors. */
110
+ const SERVER_SLUGS: Record<string, (message: string) => unknown> = {
111
+ internal_error: (message) => new InternalServerError({ message }),
112
+ fatal_error: (message) => new InternalServerError({ message }),
113
+ service_unavailable: (message) => new ServiceUnavailable({ message }),
114
+ request_timeout: (message) => new GatewayTimeout({ message }),
115
+ };
116
+
117
+ /**
118
+ * Serialize input members the way Slack's wire wants them, before the
119
+ * generic request builder runs:
120
+ *
121
+ * • Array-valued QUERY args join with commas (`channel_ids=C1,C2`) —
122
+ * core's default would repeat the param instead.
123
+ * • On form-urlencoded operations, every non-scalar body member is
124
+ * flattened to the string Slack's form convention reads: ID lists
125
+ * comma-joined, rich values (blocks, barrier subjects, datastore items)
126
+ * JSON-encoded — core's default is Stripe-style bracket notation, which
127
+ * Slack does not speak.
128
+ */
129
+ const serializeForWire = (input: unknown, inputAst: AST.AST): unknown => {
130
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
131
+ return input;
132
+ }
133
+ const isForm =
134
+ (getAnn(inputAst, httpSymbol) as HttpTrait | undefined)?.contentType ===
135
+ "form-urlencoded";
136
+ const props = getProps(inputAst);
137
+ if (props.length === 0) return input;
138
+ let out: Record<string, unknown> | undefined;
139
+ for (const prop of props) {
140
+ const key = String(prop.name);
141
+ const value = (input as Record<string, unknown>)[key];
142
+ if (value === null || typeof value !== "object") continue;
143
+ const isQuery = hasPropAnn(prop, querySymbol);
144
+ if (Array.isArray(value) && (isQuery || isForm)) {
145
+ out ??= { ...(input as Record<string, unknown>) };
146
+ out[key] = value.every((v) => typeof v !== "object" || v === null)
147
+ ? value.join(",")
148
+ : JSON.stringify(value);
149
+ } else if (isForm && !isQuery) {
150
+ out ??= { ...(input as Record<string, unknown>) };
151
+ out[key] = JSON.stringify(value);
152
+ }
153
+ }
154
+ return out ?? input;
155
+ };
156
+
157
+ // The protocol layer is memoized per process by `API.make` (see
158
+ // `OperationConfig.protocol`), so the build must not capture credentials —
159
+ // `encode` resolves Credentials from the calling fiber's context on every
160
+ // request instead. Like the error channel above, the requirement is erased at
161
+ // this boundary (Protocol effects are typed with no requirements) and
162
+ // reintroduced for callers by the generated `SlackOpContext` annotations.
163
+ const encode = ({
164
+ input,
165
+ inputAst,
166
+ }: {
167
+ readonly input: unknown;
168
+ readonly inputAst: AST.AST;
169
+ }) =>
170
+ Effect.gen(function* () {
171
+ const resolveCredentials = yield* Credentials;
172
+ const creds = yield* resolveCredentials as Effect.Effect<Config>;
173
+ const token = Redacted.value(creds.token);
174
+ return buildRequest({
175
+ input: serializeForWire(unwrapRedactedDeep(input), inputAst),
176
+ inputAst,
177
+ baseUrl: creds.apiBaseUrl,
178
+ // An empty token means a credential-less call (the OAuth exchange
179
+ // methods) — no Authorization header at all.
180
+ headers: token === "" ? {} : { authorization: `Bearer ${token}` },
181
+ });
182
+ });
183
+
184
+ const decode = ({
185
+ response,
186
+ outputAst,
187
+ errors: errorClasses,
188
+ }: {
189
+ readonly response: HttpClientResponse.HttpClientResponse;
190
+ readonly outputAst: AST.AST;
191
+ readonly errors: ReadonlyArray<unknown>;
192
+ }) =>
193
+ Effect.gen(function* () {
194
+ // Read as BYTES first: the analytics export answers a successful call
195
+ // with a gzipped file, which a text read would corrupt. Everything else
196
+ // decodes from the same buffer.
197
+ const bytes = new Uint8Array(
198
+ yield* response.arrayBuffer.pipe(Effect.orDie),
199
+ );
200
+ const text = new TextDecoder().decode(bytes);
201
+ if (process.env.DISTILLED_DEBUG_HTTP) {
202
+ console.error(`[distilled] <- ${response.status} ${text.slice(0, 400)}`);
203
+ }
204
+
205
+ let json: Record<string, unknown> | undefined;
206
+ if (text.trim().length > 0) {
207
+ try {
208
+ const parsed = JSON.parse(text);
209
+ if (parsed !== null && typeof parsed === "object") {
210
+ json = parsed as Record<string, unknown>;
211
+ }
212
+ } catch {
213
+ // non-JSON — a binary success payload or an HTML error page
214
+ }
215
+ }
216
+ const status = response.status;
217
+ const headers = response.headers as Record<string, string | undefined>;
218
+
219
+ // Slack reports failures as `ok: false`, usually WITH HTTP 200 — a
220
+ // non-2xx status without an envelope (proxy pages) is also a failure.
221
+ const failed = status >= 400 || json?.ok === false;
222
+ if (failed) {
223
+ const slug = typeof json?.error === "string" ? json.error : undefined;
224
+ // `response_metadata.messages` carries per-field validation detail
225
+ // (e.g. `invalid_arguments`); some envelopes use a bare `errors` list.
226
+ const detailMessages = (
227
+ [
228
+ ...((json?.response_metadata as { messages?: unknown[] } | undefined)
229
+ ?.messages ?? []),
230
+ ...((Array.isArray(json?.errors) ? json.errors : []) as unknown[]),
231
+ ] as unknown[]
232
+ ).filter((m): m is string => typeof m === "string");
233
+ const message =
234
+ detailMessages[0] ??
235
+ slug ??
236
+ (json === undefined && text.trim() ? text.trim() : `HTTP ${status}`);
237
+
238
+ // 1. Per-operation typed error (matcher metadata on the class — none
239
+ // are generated today, but model patches can add them). Slack's
240
+ // error codes are string slugs, and matcher `code`s are numeric —
241
+ // a patch-declared class matches on `status`/`message` instead
242
+ // (`message` is the slug when the envelope carries no detail).
243
+ const typed = matchTypedError(errorClasses, status, [{ message }]);
244
+ if (typed !== undefined) return yield* fail(typed);
245
+
246
+ // 2. Throttling — the 429 or its envelope spellings.
247
+ if (status === 429 || slug === "rate_limited" || slug === "ratelimited") {
248
+ return yield* fail(
249
+ new SlackRateLimited({
250
+ code: slug ?? "rate_limited",
251
+ message,
252
+ retryAfter: parseServerRetryHint(headers),
253
+ }),
254
+ );
255
+ }
256
+
257
+ // 3. Infrastructure slugs: credential problems and Slack-side hiccups.
258
+ if (slug !== undefined && AUTH_SLUGS.has(slug)) {
259
+ return yield* fail(new Unauthorized({ message: slug }));
260
+ }
261
+ if (slug !== undefined && slug in SERVER_SLUGS) {
262
+ return yield* fail(SERVER_SLUGS[slug]!(message));
263
+ }
264
+
265
+ // 4. Any other envelope slug → SlackError, the slug preserved.
266
+ if (slug !== undefined) {
267
+ return yield* fail(
268
+ new SlackError({
269
+ code: slug,
270
+ ...(message !== slug ? { message } : {}),
271
+ ...(typeof json?.needed === "string"
272
+ ? { needed: json.needed }
273
+ : {}),
274
+ ...(typeof json?.provided === "string"
275
+ ? { provided: json.provided }
276
+ : {}),
277
+ ...(detailMessages.length > 0 ? { messages: detailMessages } : {}),
278
+ }),
279
+ );
280
+ }
281
+
282
+ // 5. No envelope at all: HTTP-status classes / retryable 5xx / raw.
283
+ const StatusErrorClass =
284
+ HTTP_STATUS_MAP[status as keyof typeof HTTP_STATUS_MAP];
285
+ if (StatusErrorClass) {
286
+ return yield* fail(
287
+ new StatusErrorClass({
288
+ message,
289
+ retryAfter: parseRetryAfterForStatus(status, headers),
290
+ } as any),
291
+ );
292
+ }
293
+ if (status >= 500) {
294
+ return yield* fail(
295
+ new InternalServerError({
296
+ message,
297
+ retryAfter: parseRetryAfterForStatus(status, headers),
298
+ }),
299
+ );
300
+ }
301
+ return yield* fail(
302
+ new SlackHttpError({ status, message, body: text.slice(0, 2000) }),
303
+ );
304
+ }
305
+
306
+ // Successful non-JSON body: raw bytes (the analytics file download —
307
+ // modeled as a Document output, so the bytes pass through verbatim).
308
+ if (json === undefined) {
309
+ return bytes;
310
+ }
311
+
312
+ // 2xx envelope: the body IS the payload (`ok` rides along as a modeled
313
+ // member). Wire→TS key mapping is schema-driven; sensitive members
314
+ // (OAuth access/refresh tokens) wrap in Redacted.
315
+ return wrapSensitive(outputAst, mapKeys(outputAst, json, "decode"));
316
+ });
317
+
318
+ export const SlackProtocol: Layer.Layer<API.Protocol> = Layer.succeed(
319
+ API.Protocol,
320
+ API.Protocol.of({
321
+ // Erase encode's Credentials requirement (see comment above).
322
+ encode: (args) =>
323
+ encode(args) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
324
+ decode,
325
+ }),
326
+ );