@effect/chat-slack 0.0.0 → 4.1.6

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 (182) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +47 -0
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/52_graphql/10_basics.ts +117 -0
  69. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  70. package/ai-docs/src/52_graphql/30_batching.ts +118 -0
  71. package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
  72. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  73. package/ai-docs/src/52_graphql/index.md +6 -0
  74. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  75. package/ai-docs/src/60_child-process/index.md +3 -0
  76. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  77. package/ai-docs/src/70_cli/index.md +5 -0
  78. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  79. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  80. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  81. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  82. package/ai-docs/src/71_ai/index.md +5 -0
  83. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  84. package/ai-docs/src/80_cluster/index.md +4 -0
  85. package/ai-docs/src/index.md +10 -0
  86. package/ai-docs/tsconfig.json +28 -0
  87. package/dist/SlackChat.d.ts +500 -0
  88. package/dist/SlackChat.d.ts.map +1 -0
  89. package/dist/SlackChat.js +512 -0
  90. package/dist/SlackChat.js.map +1 -0
  91. package/dist/SlackWebApi.d.ts +74 -0
  92. package/dist/SlackWebApi.d.ts.map +1 -0
  93. package/dist/SlackWebApi.js +96 -0
  94. package/dist/SlackWebApi.js.map +1 -0
  95. package/dist/index.d.ts +15 -0
  96. package/dist/index.d.ts.map +1 -0
  97. package/dist/index.js +16 -0
  98. package/dist/index.js.map +1 -0
  99. package/dist/internal/actions.d.ts +2 -0
  100. package/dist/internal/actions.d.ts.map +1 -0
  101. package/dist/internal/actions.js +169 -0
  102. package/dist/internal/actions.js.map +1 -0
  103. package/dist/internal/adapter.d.ts +2 -0
  104. package/dist/internal/adapter.d.ts.map +1 -0
  105. package/dist/internal/adapter.js +836 -0
  106. package/dist/internal/adapter.js.map +1 -0
  107. package/dist/internal/address.d.ts +2 -0
  108. package/dist/internal/address.d.ts.map +1 -0
  109. package/dist/internal/address.js +36 -0
  110. package/dist/internal/address.js.map +1 -0
  111. package/dist/internal/emoji.d.ts +2 -0
  112. package/dist/internal/emoji.d.ts.map +1 -0
  113. package/dist/internal/emoji.js +207 -0
  114. package/dist/internal/emoji.js.map +1 -0
  115. package/dist/internal/emojiData.d.ts +54 -0
  116. package/dist/internal/emojiData.d.ts.map +1 -0
  117. package/dist/internal/emojiData.js +1965 -0
  118. package/dist/internal/emojiData.js.map +1 -0
  119. package/dist/internal/errors.d.ts +2 -0
  120. package/dist/internal/errors.d.ts.map +1 -0
  121. package/dist/internal/errors.js +190 -0
  122. package/dist/internal/errors.js.map +1 -0
  123. package/dist/internal/escape.d.ts +14 -0
  124. package/dist/internal/escape.d.ts.map +1 -0
  125. package/dist/internal/escape.js +413 -0
  126. package/dist/internal/escape.js.map +1 -0
  127. package/dist/internal/interactions.d.ts +2 -0
  128. package/dist/internal/interactions.d.ts.map +1 -0
  129. package/dist/internal/interactions.js +389 -0
  130. package/dist/internal/interactions.js.map +1 -0
  131. package/dist/internal/json.d.ts +2 -0
  132. package/dist/internal/json.d.ts.map +1 -0
  133. package/dist/internal/json.js +30 -0
  134. package/dist/internal/json.js.map +1 -0
  135. package/dist/internal/length.d.ts +2 -0
  136. package/dist/internal/length.d.ts.map +1 -0
  137. package/dist/internal/length.js +33 -0
  138. package/dist/internal/length.js.map +1 -0
  139. package/dist/internal/mentions.d.ts +2 -0
  140. package/dist/internal/mentions.d.ts.map +1 -0
  141. package/dist/internal/mentions.js +229 -0
  142. package/dist/internal/mentions.js.map +1 -0
  143. package/dist/internal/normalize.d.ts +2 -0
  144. package/dist/internal/normalize.d.ts.map +1 -0
  145. package/dist/internal/normalize.js +211 -0
  146. package/dist/internal/normalize.js.map +1 -0
  147. package/dist/internal/options.d.ts +2 -0
  148. package/dist/internal/options.d.ts.map +1 -0
  149. package/dist/internal/options.js +6 -0
  150. package/dist/internal/options.js.map +1 -0
  151. package/dist/internal/richText.d.ts +2 -0
  152. package/dist/internal/richText.d.ts.map +1 -0
  153. package/dist/internal/richText.js +346 -0
  154. package/dist/internal/richText.js.map +1 -0
  155. package/dist/internal/text.d.ts +2 -0
  156. package/dist/internal/text.d.ts.map +1 -0
  157. package/dist/internal/text.js +239 -0
  158. package/dist/internal/text.js.map +1 -0
  159. package/dist/internal/webhook.d.ts +2 -0
  160. package/dist/internal/webhook.d.ts.map +1 -0
  161. package/dist/internal/webhook.js +142 -0
  162. package/dist/internal/webhook.js.map +1 -0
  163. package/package.json +62 -1
  164. package/src/SlackChat.ts +640 -0
  165. package/src/SlackWebApi.ts +135 -0
  166. package/src/index.ts +18 -0
  167. package/src/internal/actions.ts +203 -0
  168. package/src/internal/adapter.ts +961 -0
  169. package/src/internal/address.ts +50 -0
  170. package/src/internal/emoji.ts +223 -0
  171. package/src/internal/emojiData.ts +1965 -0
  172. package/src/internal/errors.ts +192 -0
  173. package/src/internal/escape.ts +428 -0
  174. package/src/internal/interactions.ts +391 -0
  175. package/src/internal/json.ts +35 -0
  176. package/src/internal/length.ts +41 -0
  177. package/src/internal/mentions.ts +224 -0
  178. package/src/internal/normalize.ts +221 -0
  179. package/src/internal/options.ts +22 -0
  180. package/src/internal/richText.ts +367 -0
  181. package/src/internal/text.ts +252 -0
  182. package/src/internal/webhook.ts +199 -0
@@ -0,0 +1,192 @@
1
+ import {
2
+ ChatError,
3
+ type ChatErrorReason,
4
+ fileRefused as fileRefusedDetail,
5
+ Forbidden,
6
+ InvalidRequest,
7
+ InvalidResponse,
8
+ NoAdapter,
9
+ NotFound,
10
+ PlatformUnavailable,
11
+ RateLimited,
12
+ TooLarge,
13
+ Transport,
14
+ Unauthenticated,
15
+ Unknown,
16
+ Unsupported
17
+ } from "effect/chat/ChatError"
18
+ import * as Duration from "effect/Duration"
19
+ import { platform } from "./address.ts"
20
+
21
+ const unauthenticated = new Set([
22
+ "invalid_auth",
23
+ "not_authed",
24
+ "account_inactive",
25
+ "token_revoked",
26
+ "token_expired",
27
+ "org_login_required"
28
+ ])
29
+
30
+ const forbidden = new Set([
31
+ "access_denied",
32
+ "accesslimited",
33
+ "missing_scope",
34
+ "not_in_channel",
35
+ "is_archived",
36
+ "channel_is_archived",
37
+ "no_permission",
38
+ "not_allowed_token_type",
39
+ "not_authorized",
40
+ "restricted_action",
41
+ "restricted_action_read_only_channel",
42
+ "restricted_action_thread_only_channel",
43
+ "restricted_action_non_threadable_channel",
44
+ "cant_update_message",
45
+ "cant_delete_message",
46
+ "cant_delete_file",
47
+ "edit_window_closed",
48
+ "ekm_access_denied",
49
+ "enterprise_is_restricted",
50
+ "team_access_not_granted",
51
+ "posting_to_general_channel_denied",
52
+ "message_not_owned_by_app",
53
+ "messages_tab_disabled",
54
+ "message_limit_exceeded",
55
+ "thread_locked",
56
+ "user_is_restricted",
57
+ "feature_disabled",
58
+ "channel_type_not_supported"
59
+ ])
60
+
61
+ const notFoundCodes = new Set([
62
+ "channel_not_found",
63
+ "message_not_found",
64
+ "thread_not_found",
65
+ "user_not_found",
66
+ "users_not_found",
67
+ "file_not_found",
68
+ "file_deleted",
69
+ "bot_not_found",
70
+ "team_not_found"
71
+ ])
72
+
73
+ const tooLarge = new Set(["msg_too_long", "msg_blocks_too_long"])
74
+
75
+ const serverErrors = new Set(["internal_error", "fatal_error", "service_unavailable", "request_timeout"])
76
+
77
+ /**
78
+ * Maps the `error` of an `ok: false` answer to a reason. `detail` is always
79
+ * Slack's error code, which holds no message text or ids.
80
+ *
81
+ * @internal
82
+ */
83
+ export const reasonForCode = (
84
+ code: string,
85
+ options: { readonly write: boolean; readonly retryAfter?: Duration.Duration | undefined }
86
+ ): ChatErrorReason => {
87
+ if (code === "ratelimited" || code === "rate_limited") {
88
+ return new RateLimited({
89
+ detail: code,
90
+ ...(options.retryAfter === undefined ? {} : { retryAfter: options.retryAfter })
91
+ })
92
+ }
93
+ if (unauthenticated.has(code)) return new Unauthenticated({ detail: code })
94
+ if (forbidden.has(code)) return new Forbidden({ detail: code })
95
+ if (notFoundCodes.has(code)) return new NotFound({ detail: code })
96
+ if (tooLarge.has(code)) return new TooLarge({ subject: "text", detail: code })
97
+ if (code === "file_too_large" || code === "too_many_files") return new TooLarge({ subject: "files", detail: code })
98
+ if (serverErrors.has(code)) {
99
+ return new PlatformUnavailable({ retry: options.write ? "uncertain" : "retry", detail: code })
100
+ }
101
+ return new InvalidRequest({ detail: code })
102
+ }
103
+
104
+ /** @internal */
105
+ export const reasonForStatus = (
106
+ status: number,
107
+ options: { readonly write: boolean; readonly retryAfter?: Duration.Duration | undefined; readonly cause?: unknown }
108
+ ): ChatErrorReason => {
109
+ const detail = `http_${status}`
110
+ const cause = options.cause === undefined ? {} : { cause: options.cause }
111
+ if (status === 429) {
112
+ return new RateLimited({
113
+ detail,
114
+ ...cause,
115
+ ...(options.retryAfter === undefined ? {} : { retryAfter: options.retryAfter })
116
+ })
117
+ }
118
+ if (status >= 500) return new PlatformUnavailable({ retry: options.write ? "uncertain" : "retry", detail, ...cause })
119
+ if (status === 401) return new Unauthenticated({ detail, ...cause })
120
+ if (status === 403) return new Forbidden({ detail, ...cause })
121
+ if (status === 404) return new NotFound({ detail, ...cause })
122
+ if (status === 413) return new TooLarge({ detail, ...cause })
123
+ return new InvalidRequest({ detail, ...cause })
124
+ }
125
+
126
+ /** A request that failed before an answer came. @internal */
127
+ export const transport = (write: boolean, detail: string, cause?: unknown): ChatErrorReason =>
128
+ new Transport({ retry: write ? "uncertain" : "retry", detail, ...(cause === undefined ? {} : { cause }) })
129
+
130
+ /** An answer the adapter cannot read. A write may have landed. @internal */
131
+ export const invalidResponse = (write: boolean, detail: string, cause?: unknown): ChatErrorReason => {
132
+ const fields = { detail, ...(cause === undefined ? {} : { cause }) }
133
+ return write ? new Unknown(fields) : new InvalidResponse(fields)
134
+ }
135
+
136
+ /** @internal */
137
+ export const parseRetryAfter = (value: string | undefined): Duration.Duration | undefined => {
138
+ if (value === undefined) return undefined
139
+ const seconds = Number(value)
140
+ return Number.isFinite(seconds) && seconds >= 0 ? Duration.seconds(seconds) : undefined
141
+ }
142
+
143
+ /** @internal */
144
+ export const chatError = (op: string, reason: ChatErrorReason): ChatError => new ChatError({ platform, op, reason })
145
+
146
+ /** @internal */
147
+ export const withOp = (op: string) => (error: ChatError): ChatError =>
148
+ error.op === op ? error : new ChatError({ platform: error.platform, op, reason: error.reason })
149
+
150
+ /** @internal */
151
+ export const invalidRequest = (detail: string): ChatErrorReason => new InvalidRequest({ detail })
152
+
153
+ /** @internal */
154
+ export const notFound = (detail: string): ChatErrorReason => new NotFound({ detail })
155
+
156
+ /**
157
+ * A `denied` reason from an upload call, or from the attach of a post whose
158
+ * rollback left nothing behind, as a refused file: the same reason with
159
+ * detail `file_refused`, and the reason it replaces, with Slack's code, as
160
+ * its `cause`. Any other reason is returned as it is.
161
+ *
162
+ * @internal
163
+ */
164
+ export const fileRefused = (reason: ChatErrorReason): ChatErrorReason => {
165
+ if (reason.retry !== "denied" || reason.detail === fileRefusedDetail) return reason
166
+ const fields = { detail: fileRefusedDetail, cause: reason }
167
+ switch (reason._tag) {
168
+ case "Unsupported":
169
+ return new Unsupported({ capability: reason.capability, ...fields })
170
+ case "Transport":
171
+ return new Transport({ retry: reason.retry, ...fields })
172
+ case "PlatformUnavailable":
173
+ return new PlatformUnavailable({ retry: reason.retry, ...fields })
174
+ case "NoAdapter":
175
+ return new NoAdapter(fields)
176
+ case "Unauthenticated":
177
+ return new Unauthenticated(fields)
178
+ case "Forbidden":
179
+ return new Forbidden(fields)
180
+ case "NotFound":
181
+ return new NotFound(fields)
182
+ case "TooLarge":
183
+ return new TooLarge({ ...(reason.subject === undefined ? {} : { subject: reason.subject }), ...fields })
184
+ case "InvalidRequest":
185
+ return new InvalidRequest(fields)
186
+ case "InvalidResponse":
187
+ return new InvalidResponse(fields)
188
+ case "RateLimited":
189
+ case "Unknown":
190
+ return reason
191
+ }
192
+ }
@@ -0,0 +1,428 @@
1
+ /**
2
+ * Escaping for what the adapter sends Slack.
3
+ *
4
+ * - The Markdown, in a `markdown` block or in `markdown_text`: a `<`
5
+ * outside inline and fenced code becomes `&lt;`, unless the scoped notify
6
+ * options allow that token.
7
+ * - The `text` beside a `markdown` block, from which Slack decides who is
8
+ * mentioned: every `<`, `>` and `&` becomes an entity, in code too, and
9
+ * only the tokens the block keeps intact stay intact.
10
+ * - A stream append, which has no `text`: `escapeStream` puts U+200B after
11
+ * whatever spells the `<` of a token shape, in prose and in code alike.
12
+ */
13
+
14
+ /** @internal */
15
+ export interface Notify {
16
+ readonly users?: ReadonlyArray<string> | undefined
17
+ readonly groups?: ReadonlyArray<string> | undefined
18
+ readonly broadcast?: boolean | undefined
19
+ }
20
+
21
+ interface Fence {
22
+ readonly char: string
23
+ readonly length: number
24
+ }
25
+
26
+ /**
27
+ * Where an escaper left off: the fence open at the start of the current line,
28
+ * and the raw text of that line consumed so far.
29
+ *
30
+ * @internal
31
+ */
32
+ export interface State {
33
+ readonly fence: Fence | undefined
34
+ readonly line: string
35
+ }
36
+
37
+ /** @internal */
38
+ export const initialState: State = { fence: undefined, line: "" }
39
+
40
+ /** @internal */
41
+ export interface Escaped {
42
+ /** What to send for the consumed part of the input. */
43
+ readonly sent: string
44
+ /** How many characters of the input were consumed. The rest is held. */
45
+ readonly consumed: number
46
+ readonly state: State
47
+ }
48
+
49
+ /** Past this many held characters, an undecided `<` is escaped anyway. */
50
+ const holdBound = 300
51
+
52
+ const tokenPattern = /^<(@([UW][A-Z0-9]+)|!subteam\^([A-Z0-9]+)|!(here|channel|everyone))(\|[^<>]*)?>/
53
+
54
+ const allowsAny = (notify: Notify): boolean =>
55
+ (notify.users?.length ?? 0) > 0 || (notify.groups?.length ?? 0) > 0 || notify.broadcast === true
56
+
57
+ const allowedToken = (rest: string, notify: Notify): number => {
58
+ const match = tokenPattern.exec(rest)
59
+ if (match === null) return 0
60
+ const [token, , user, group, broadcast] = match
61
+ if (user !== undefined) return notify.users?.includes(user) ? token.length : 0
62
+ if (group !== undefined) return notify.groups?.includes(group) ? token.length : 0
63
+ return broadcast !== undefined && notify.broadcast === true ? token.length : 0
64
+ }
65
+
66
+ const openingFence = /^ {0,3}(`{3,}|~{3,})(.*)$/
67
+ const closingFence = /^ {0,3}(`{3,}|~{3,})[ \t]*\r?$/
68
+
69
+ const opensFence = (line: string): Fence | undefined => {
70
+ const match = openingFence.exec(line)
71
+ if (match === null) return undefined
72
+ const marker = match[1]
73
+ if (marker[0] === "`" && match[2].includes("`")) return undefined
74
+ return { char: marker[0], length: marker.length }
75
+ }
76
+
77
+ const closesFence = (line: string, fence: Fence): boolean => {
78
+ const match = closingFence.exec(line)
79
+ return match !== null && match[1][0] === fence.char && match[1].length >= fence.length
80
+ }
81
+
82
+ const backtickRun = (line: string, start: number): number => {
83
+ let end = start
84
+ while (line[end] === "`") end++
85
+ return end - start
86
+ }
87
+
88
+ /**
89
+ * The code spans of one line, as `[start, end)` pairs, and the position of a
90
+ * backtick run that opens a span the line has not closed yet.
91
+ */
92
+ const codeSpans = (line: string): { readonly spans: Array<readonly [number, number]>; readonly open: number } => {
93
+ const spans: Array<readonly [number, number]> = []
94
+ let i = 0
95
+ let open = -1
96
+ while (i < line.length) {
97
+ if (line[i] !== "`") {
98
+ i++
99
+ continue
100
+ }
101
+ const length = backtickRun(line, i)
102
+ let j = i + length
103
+ let closed = -1
104
+ while (j < line.length) {
105
+ if (line[j] === "`") {
106
+ const run = backtickRun(line, j)
107
+ if (run === length) {
108
+ closed = j
109
+ break
110
+ }
111
+ j += run
112
+ } else {
113
+ j++
114
+ }
115
+ }
116
+ if (closed === -1) {
117
+ if (open === -1) open = i
118
+ i += length
119
+ } else {
120
+ spans.push([i, closed + length])
121
+ i = closed + length
122
+ }
123
+ }
124
+ return { spans, open }
125
+ }
126
+
127
+ /**
128
+ * Escapes `text`, continuing from `state`. Without `flush`, a `<` whose
129
+ * meaning the rest of the stream could still change is held: an unclosed
130
+ * token that the notify options might allow, or one after a backtick the line
131
+ * has not closed yet. With `flush`, or once the held text passes a bound,
132
+ * it is escaped.
133
+ *
134
+ * @internal
135
+ */
136
+ export const escape = (
137
+ text: string,
138
+ notify: Notify,
139
+ options?: {
140
+ readonly state?: State | undefined
141
+ readonly flush?: boolean | undefined
142
+ /** Write every `<`, `>` and `&` as an entity, apart from allowed tokens. */
143
+ readonly entities?: boolean | undefined
144
+ /** Called with the span in the output of each allowed token kept intact. */
145
+ readonly onToken?: ((start: number, end: number) => void) | undefined
146
+ }
147
+ ): Escaped => {
148
+ const state = options?.state ?? initialState
149
+ const flush = options?.flush === true
150
+ const entities = options?.entities === true
151
+ const full = state.line + text
152
+ const offset = state.line.length
153
+ const anyAllowed = allowsAny(notify)
154
+ let fence = state.fence
155
+ let out = ""
156
+ let lineStart = 0
157
+ const emit = (from: number, to: number, piece?: string) => {
158
+ if (to <= offset) return
159
+ if (piece !== undefined) out += piece
160
+ else {
161
+ const slice = full.slice(Math.max(from, offset), to)
162
+ out += entities ? textEntities(slice) : slice
163
+ }
164
+ }
165
+ while (lineStart <= full.length) {
166
+ const newline = full.indexOf("\n", lineStart)
167
+ const complete = newline !== -1
168
+ const lineEnd = complete ? newline : full.length
169
+ const line = full.slice(lineStart, lineEnd)
170
+ if (fence !== undefined) {
171
+ emit(lineStart, lineEnd)
172
+ if (complete && closesFence(line, fence)) fence = undefined
173
+ } else {
174
+ const opener = complete ? opensFence(line) : undefined
175
+ const { open, spans } = opener === undefined ? codeSpans(line) : { open: -1, spans: [] }
176
+ let i = 0
177
+ let span = 0
178
+ while (i < line.length) {
179
+ while (span < spans.length && spans[span][1] <= i) span++
180
+ if (span < spans.length && spans[span][0] <= i) {
181
+ emit(lineStart + i, lineStart + spans[span][1])
182
+ i = spans[span][1]
183
+ continue
184
+ }
185
+ const next = line.indexOf("<", i)
186
+ const stop = next === -1 ? line.length : Math.min(next, span < spans.length ? spans[span][0] : line.length)
187
+ if (stop > i) {
188
+ emit(lineStart + i, lineStart + stop)
189
+ i = stop
190
+ continue
191
+ }
192
+ const at = lineStart + i
193
+ const rest = line.slice(i)
194
+ const undecided = !flush && !complete && full.length - at <= holdBound && (
195
+ (open !== -1 && open < i) ||
196
+ (anyAllowed && !rest.includes(">") && /^<(@|!)?[\w^|]*$/.test(rest))
197
+ )
198
+ if (undecided) {
199
+ return {
200
+ sent: out,
201
+ consumed: at - offset,
202
+ state: { fence, line: full.slice(lineStart, at) }
203
+ }
204
+ }
205
+ const token = allowedToken(rest, notify)
206
+ if (token > 0) {
207
+ const start = out.length
208
+ emit(at, at + token, at >= offset ? rest.slice(0, token) : undefined)
209
+ if (at >= offset) options?.onToken?.(start, out.length)
210
+ i += token
211
+ } else {
212
+ emit(at, at + 1, at >= offset ? "&lt;" : undefined)
213
+ i += 1
214
+ }
215
+ }
216
+ if (opener !== undefined) fence = opener
217
+ }
218
+ if (!complete) {
219
+ return { sent: out, consumed: full.length - offset, state: { fence, line } }
220
+ }
221
+ emit(lineEnd, lineEnd + 1)
222
+ lineStart = lineEnd + 1
223
+ }
224
+ return { sent: out, consumed: full.length - offset, state: { fence, line: "" } }
225
+ }
226
+
227
+ const entityOf: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;" }
228
+
229
+ const textEntities = (text: string): string => text.replace(/[&<>]/g, (char) => entityOf[char])
230
+
231
+ const zeroWidthSpace = "\u200B"
232
+
233
+ /** The character references a stream decodes for `<`, `@` and `!`, each only with its semicolon. */
234
+ const references: ReadonlyArray<readonly [RegExp, string]> = [
235
+ [/&(?:lt|LT|#0*60|#[xX]0*3[cC]);/y, "<"],
236
+ [/&(?:commat|#0*64|#[xX]0*40);/y, "@"],
237
+ [/&(?:excl|#0*33|#[xX]0*21);/y, "!"]
238
+ ]
239
+
240
+ const referenceNames = ["lt", "LT", "commat", "excl"]
241
+
242
+ /** Whether `text`, from its `&` on, could still grow into one of `references`. */
243
+ const unfinishedReference = (text: string): boolean => {
244
+ const body = text.slice(1)
245
+ return /^#(?:[0-9]*|[xX][0-9a-fA-F]*)$/.test(body) || referenceNames.some((name) => name.startsWith(body))
246
+ }
247
+
248
+ /** The start of a token an allowed one could still complete, label included. */
249
+ const unclosedToken = /^<[@!][\w^]*(?:\|[^<>]*)?$/
250
+
251
+ interface Decoded {
252
+ readonly char: string
253
+ /** How many characters of the input spell it. */
254
+ readonly length: number
255
+ }
256
+
257
+ /**
258
+ * The character at `i` in the decoded view of `line`, which must be within
259
+ * it. A reference may have any number of leading zeros.
260
+ */
261
+ const decodeAt = (line: string, i: number): Decoded => {
262
+ if (line[i] === "&") {
263
+ for (const [pattern, char] of references) {
264
+ pattern.lastIndex = i
265
+ const match = pattern.exec(line)
266
+ if (match !== null) return { char, length: match[0].length }
267
+ }
268
+ }
269
+ return { char: line[i], length: 1 }
270
+ }
271
+
272
+ /**
273
+ * The character at `i` in the decoded view of `line`. `undefined` past
274
+ * the end of the text, and `unfinished` where the next chunk could still
275
+ * change it.
276
+ */
277
+ const decodedAt = (line: string, i: number, ended: boolean): Decoded | "unfinished" | undefined => {
278
+ if (i >= line.length) return ended ? undefined : "unfinished"
279
+ const decoded = decodeAt(line, i)
280
+ return decoded.char === "&" && !ended && unfinishedReference(line.slice(i)) ? "unfinished" : decoded
281
+ }
282
+
283
+ /** `line` from `i` to its first `>`, or to its end, decoded, with the end in `line` of each decoded character. */
284
+ const decodeToken = (line: string, i: number): { readonly text: string; readonly ends: ReadonlyArray<number> } => {
285
+ const close = line.indexOf(">", i)
286
+ const end = close === -1 ? line.length : close + 1
287
+ let text = ""
288
+ const ends: Array<number> = []
289
+ for (let j = i; j < end;) {
290
+ const decoded = decodeAt(line, j)
291
+ text += decoded.char
292
+ j += decoded.length
293
+ ends.push(j)
294
+ }
295
+ return { text, ends }
296
+ }
297
+
298
+ /**
299
+ * Escapes a stream's Markdown, continuing from `state`. Slack decodes the
300
+ * character references for `<`, `@` and `!` in a stream, joins one split
301
+ * across two appends, and has no `text` to send beside it, so:
302
+ *
303
+ * - Token shapes are found on the decoded view, which decodes those
304
+ * references only with their semicolon, in prose and in code alike. A
305
+ * shape is `<@`, or `<!` followed by an ASCII letter.
306
+ * - On a shape, U+200B goes straight after whatever spells the `<`, and the
307
+ * rest is left as written. A token the notify options allow is sent as it
308
+ * is.
309
+ * - Every other `<` keeps the rule of `escape`: `&lt;` outside code, as
310
+ * written inside it.
311
+ *
312
+ * Without `flush`, it holds what the next chunk could still change: a
313
+ * `<` with too little after it to tell, a trailing reference that is not
314
+ * finished, an unclosed token the notify options might allow, and a `<`
315
+ * after a backtick the line has not closed yet. Past a bound, or with
316
+ * `flush`, it decides with what it has. A shape that only the next chunk
317
+ * completes, after such a write, gets U+200B at the start of the next write,
318
+ * since Slack reads the writes joined.
319
+ *
320
+ * @internal
321
+ */
322
+ export const escapeStream = (
323
+ text: string,
324
+ notify: Notify,
325
+ options?: {
326
+ readonly state?: State | undefined
327
+ readonly flush?: boolean | undefined
328
+ }
329
+ ): Escaped => {
330
+ const state = options?.state ?? initialState
331
+ const flush = options?.flush === true
332
+ const full = state.line + text
333
+ const offset = state.line.length
334
+ const anyAllowed = allowsAny(notify)
335
+ let fence = state.fence
336
+ let out = ""
337
+ let lineStart = 0
338
+ const emit = (from: number, to: number) => {
339
+ if (to > offset) out += full.slice(Math.max(from, offset), to)
340
+ }
341
+ while (lineStart <= full.length) {
342
+ const newline = full.indexOf("\n", lineStart)
343
+ const complete = newline !== -1
344
+ const lineEnd = complete ? newline : full.length
345
+ const line = full.slice(lineStart, lineEnd)
346
+ const inFence = fence !== undefined
347
+ const opener = !inFence && complete ? opensFence(line) : undefined
348
+ const { open, spans } = inFence || opener !== undefined ? { open: -1, spans: [] } : codeSpans(line)
349
+ const hold = (i: number): Escaped => {
350
+ const at = lineStart + i
351
+ return { sent: out, consumed: at - offset, state: { fence, line: full.slice(lineStart, at) } }
352
+ }
353
+ let i = 0
354
+ let span = 0
355
+ while (i < line.length) {
356
+ const next = line.slice(i).search(/[<&]/)
357
+ if (next === -1) {
358
+ emit(lineStart + i, lineEnd)
359
+ break
360
+ }
361
+ emit(lineStart + i, lineStart + i + next)
362
+ i += next
363
+ const at = lineStart + i
364
+ // What an earlier write sent can't be held.
365
+ const ended = complete || flush || at < offset || full.length - at > holdBound
366
+ const first = decodedAt(line, i, ended)
367
+ if (first === "unfinished") return hold(i)
368
+ if (first === undefined || first.char !== "<") {
369
+ // An `&` that spells no `<`. What it spells is decided where it is used.
370
+ emit(at, at + 1)
371
+ i += 1
372
+ continue
373
+ }
374
+ const second = decodedAt(line, i + first.length, ended)
375
+ if (second === "unfinished") return hold(i)
376
+ let shape = second?.char === "@"
377
+ // Where the text that makes it a shape ends.
378
+ let decided = i + first.length + (second?.length ?? 0)
379
+ if (second?.char === "!") {
380
+ const third = decodedAt(line, decided, ended)
381
+ if (third === "unfinished") return hold(i)
382
+ shape = third !== undefined && third.length === 1 && /[A-Za-z]/.test(third.char)
383
+ decided += third?.length ?? 0
384
+ }
385
+ if (shape) {
386
+ const token = decodeToken(line, i)
387
+ const length = allowedToken(token.text, notify)
388
+ if (length > 0) {
389
+ emit(at, lineStart + token.ends[length - 1])
390
+ i = token.ends[length - 1]
391
+ continue
392
+ }
393
+ if (!ended && anyAllowed && unclosedToken.test(token.text)) return hold(i)
394
+ // A shape an earlier write ended inside, which that write could not see, gets the space at the
395
+ // start of this one: Slack reads the writes joined.
396
+ if (lineStart + decided > offset) {
397
+ emit(at, at + first.length)
398
+ out += zeroWidthSpace
399
+ }
400
+ i += first.length
401
+ continue
402
+ }
403
+ if (first.length > 1) {
404
+ // A reference for `<` that starts no token shape is left as written.
405
+ emit(at, at + first.length)
406
+ i += first.length
407
+ continue
408
+ }
409
+ while (span < spans.length && spans[span][1] <= i) span++
410
+ const inCode = inFence || opener !== undefined || (span < spans.length && spans[span][0] <= i)
411
+ if (!inCode && !ended && open !== -1 && open < i) return hold(i)
412
+ if (inCode) emit(at, at + 1)
413
+ else if (at >= offset) out += "&lt;"
414
+ i += 1
415
+ }
416
+ if (inFence) {
417
+ if (complete && closesFence(line, fence!)) fence = undefined
418
+ } else if (opener !== undefined) {
419
+ fence = opener
420
+ }
421
+ if (!complete) {
422
+ return { sent: out, consumed: full.length - offset, state: { fence, line } }
423
+ }
424
+ emit(lineEnd, lineEnd + 1)
425
+ lineStart = lineEnd + 1
426
+ }
427
+ return { sent: out, consumed: full.length - offset, state: { fence, line: "" } }
428
+ }