@effect-uai/discord 0.18.0 → 0.19.0-dev-20261110065930

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.
package/README.md CHANGED
@@ -41,7 +41,7 @@ needs the privileged Message Content intent:
41
41
 
42
42
  ## Docs
43
43
 
44
- <https://effect-uai.betalyra.com/messenger/providers/discord/>
44
+ <https://effect-uai.com/messenger/providers/discord/>
45
45
 
46
46
  ## License
47
47
 
@@ -7,6 +7,7 @@ import * as Cause$1 from "effect/Cause";
7
7
  import * as Duration$1 from "effect/Duration";
8
8
  import * as Effect$1 from "effect/Effect";
9
9
  import * as Exit from "effect/Exit";
10
+ import "effect/Fiber";
10
11
  import { constVoid, flow, pipe } from "effect/Function";
11
12
  import * as Layer$1 from "effect/Layer";
12
13
  import * as Schedule$1 from "effect/Schedule";
@@ -14,30 +15,31 @@ import * as Scope$1 from "effect/Scope";
14
15
  import * as TestClock from "effect/testing/TestClock";
15
16
  import * as TestConsole from "effect/testing/TestConsole";
16
17
  import * as FakeWebSocket from "@effect-uai/core/testing/FakeWebSocket";
17
- //#region ../../../node_modules/.pnpm/@effect+vitest@4.0.1_effect@4.0.1_vitest@5.0.3_@types+node@26.2.0_vite@7.3.2_@types+nod_65816e3353e20bfeb9b2e1494bdddeef/node_modules/@effect/vitest/dist/internal/internal.js
18
+ //#region ../../../node_modules/.pnpm/@effect+vitest@4.1.2_effect@4.1.2_vitest@5.0.3_@types+node@26.2.0_vite@7.3.2_@types+nod_a2fffe0deec250ef9d6207b86a9a1ab8/node_modules/@effect/vitest/dist/internal/internal.js
18
19
  /**
19
20
  * @since 4.0.0
20
21
  */
21
22
  const getCurrentSuite = TestRunner.getCurrentSuite;
22
- const runPromise = /*#__PURE__*/ Effect$1.fnUntraced(function* (effect, _ctx) {
23
- const exit = yield* Effect$1.exit(effect);
23
+ const runPromise = (effect, ctx) => Effect$1.runPromise(Effect$1.uninterruptibleMask((restore) => Effect$1.gen(function* () {
24
+ const exit = yield* Effect$1.exit(restore(effect));
24
25
  if (Exit.isFailure(exit)) {
25
26
  const errors = Cause$1.prettyErrors(exit.cause);
26
27
  for (let i = 0; i < errors.length; i++) yield* Effect$1.logError(errors[i]);
27
28
  }
28
29
  return yield* exit;
29
- }, (effect, _, ctx) => Effect$1.runPromise(effect, { signal: ctx?.signal }));
30
+ })), { signal: ctx?.signal });
31
+ const settleOnAbort = (ctx, promise) => {
32
+ const onAbort = () => ctx.onTestFinished(() => promise.then(constVoid, constVoid));
33
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
34
+ const cleanup = () => ctx.signal.removeEventListener("abort", onAbort);
35
+ promise.then(cleanup, cleanup);
36
+ if (ctx.signal.aborted) onAbort();
37
+ return promise;
38
+ };
30
39
  /** @internal */
31
40
  const runTest = (ctx) => (effect) => {
32
41
  const promise = runPromise(effect, ctx);
33
- if (ctx) {
34
- const onAbort = () => ctx.onTestFinished(() => promise.then(constVoid, constVoid));
35
- ctx.signal.addEventListener("abort", onAbort, { once: true });
36
- const cleanup = () => ctx.signal.removeEventListener("abort", onAbort);
37
- promise.then(cleanup, cleanup);
38
- if (ctx.signal.aborted) onAbort();
39
- }
40
- return promise;
42
+ return ctx ? settleOnAbort(ctx, promise) : promise;
41
43
  };
42
44
  const TestEnv = /*#__PURE__*/ Layer$1.mergeAll(TestConsole.layer, /*#__PURE__*/ TestClock.layer());
43
45
  /** @internal */
@@ -73,6 +75,9 @@ const collectTasks = (tasks, acc = []) => {
73
75
  }
74
76
  return acc;
75
77
  };
78
+ const runsMoreThanOnce = (task) => {
79
+ return ((typeof task.retry === "number" ? task.retry : task.retry?.count) ?? 0) > 0 || (task.repeats ?? 0) > 0;
80
+ };
76
81
  const registerProp = (it, name, arbitraries, property, timeout) => {
77
82
  const arbitrary = makeArbitrary(arbitraries);
78
83
  it(name, testOptions(timeout), withFixturesOf(() => {}, (ctx) => runCheck(ctx, arbitrary, (values) => property(values, ctx), checkOptions(timeout))));
@@ -92,11 +97,35 @@ const makeTester = (mapEffect, it) => {
92
97
  prop
93
98
  });
94
99
  };
95
- const makeProp = (it) => (name, arbitraries, self, timeout) => registerProp(it, name, arbitraries, (values, ctx) => self(values, ctx) !== false, timeout);
100
+ const makeProp = (it) => (name, arbitraries, self, timeout) => registerProp(it, name, arbitraries, (values, ctx) => {
101
+ const result = self(values, ctx);
102
+ if (result !== void 0 && typeof result !== "boolean") throw new TypeError("it.prop callbacks must return boolean or void. Use it.effect.prop for Effect callbacks.");
103
+ return result !== false;
104
+ }, timeout);
96
105
  const makeLayer = (it) => (layer_, options) => (...args) => {
97
106
  const excludeTestServices = options?.excludeTestServices ?? false;
98
107
  const withTestEnv = excludeTestServices ? layer_ : Layer$1.provideMerge(layer_, TestEnv);
99
108
  const memoMap = options?.memoMap ?? Effect$1.runSync(Layer$1.makeMemoMap);
109
+ const buildPerTest = options?.buildPerTest ?? false;
110
+ const suiteOptions = options?.concurrent === void 0 ? {} : { concurrent: options.concurrent };
111
+ const makeBlockMethods = (provide) => makeItProxy(it, {
112
+ effect: makeTester((effect) => provide(Effect$1.scoped(effect)), it),
113
+ prop: makeProp(it),
114
+ flakyTest,
115
+ layer(nestedLayer, nestedOptions) {
116
+ return makeLayer(it)(Layer$1.provideMerge(nestedLayer, withTestEnv), {
117
+ ...nestedOptions,
118
+ memoMap: Layer$1.forkMemoMapUnsafe(memoMap),
119
+ excludeTestServices,
120
+ buildPerTest: buildPerTest || nestedOptions?.buildPerTest === true
121
+ });
122
+ }
123
+ });
124
+ if (buildPerTest) {
125
+ const methods = makeBlockMethods((effect) => Effect$1.scopedWith((scope) => Layer$1.buildWithMemoMap(withTestEnv, Layer$1.forkMemoMapUnsafe(memoMap), scope).pipe(Effect$1.orDie, Effect$1.flatMap((context) => Effect$1.provide(effect, context)))));
126
+ if (args.length === 1) return args[0](methods);
127
+ return describe(args[0], suiteOptions, () => args[1](methods));
128
+ }
100
129
  const scope = Effect$1.runSync(Scope$1.make());
101
130
  const contextEffect = Layer$1.buildWithMemoMap(withTestEnv, memoMap, scope).pipe(Effect$1.orDie, Effect$1.cached, Effect$1.runSync);
102
131
  let closed = false;
@@ -105,18 +134,7 @@ const makeLayer = (it) => (layer_, options) => (...args) => {
105
134
  closed = true;
106
135
  return runPromise(Scope$1.close(scope, Exit.void));
107
136
  };
108
- const methods = makeItProxy(it, {
109
- effect: makeTester((effect) => Effect$1.flatMap(contextEffect, (context) => effect.pipe(Effect$1.scoped, Effect$1.provide(context))), it),
110
- prop: makeProp(it),
111
- flakyTest,
112
- layer(nestedLayer, options) {
113
- return makeLayer(it)(Layer$1.provideMerge(nestedLayer, withTestEnv), {
114
- ...options,
115
- memoMap: Layer$1.forkMemoMapUnsafe(memoMap),
116
- excludeTestServices
117
- });
118
- }
119
- });
137
+ const methods = makeBlockMethods((effect) => Effect$1.flatMap(contextEffect, (context) => Effect$1.provide(effect, context)));
120
138
  if (args.length === 1) {
121
139
  const currentSuite = getCurrentSuite();
122
140
  const previousTasks = new Set(currentSuite.tasks);
@@ -127,10 +145,11 @@ const makeLayer = (it) => (layer_, options) => (...args) => {
127
145
  return;
128
146
  }
129
147
  const blockTaskSet = new Set(blockTasks);
148
+ const releaseAfterLastTest = !blockTasks.some(runsMoreThanOnce);
130
149
  let remaining = blockTasks.length;
131
150
  beforeEach(({ onTestFinished, signal, task }) => {
132
151
  if (!blockTaskSet.has(task)) return;
133
- onTestFinished(() => {
152
+ if (releaseAfterLastTest) onTestFinished(() => {
134
153
  remaining--;
135
154
  if (remaining === 0) return closeScope();
136
155
  });
@@ -139,7 +158,6 @@ const makeLayer = (it) => (layer_, options) => (...args) => {
139
158
  afterAll(() => closeScope(), hookTimeout(options?.timeout));
140
159
  return;
141
160
  }
142
- const suiteOptions = options?.concurrent === void 0 ? {} : { concurrent: options.concurrent };
143
161
  return describe(args[0], suiteOptions, () => {
144
162
  beforeAll(() => runPromise(Effect$1.asVoid(contextEffect)), hookTimeout(options?.timeout));
145
163
  afterAll(() => closeScope(), hookTimeout(options?.timeout));
@@ -161,11 +179,12 @@ const it$1 = /*#__PURE__*/ makeMethods(it$2);
161
179
  /** @internal */
162
180
  const { effect, layer, live, prop } = it$1;
163
181
  //#endregion
164
- //#region ../../../node_modules/.pnpm/@effect+vitest@4.0.1_effect@4.0.1_vitest@5.0.3_@types+node@26.2.0_vite@7.3.2_@types+nod_65816e3353e20bfeb9b2e1494bdddeef/node_modules/@effect/vitest/dist/index.js
165
- /**
166
- * @since 4.0.0
167
- */
182
+ //#region ../../../node_modules/.pnpm/@effect+vitest@4.1.2_effect@4.1.2_vitest@5.0.3_@types+node@26.2.0_vite@7.3.2_@types+nod_a2fffe0deec250ef9d6207b86a9a1ab8/node_modules/@effect/vitest/dist/index.js
168
183
  /**
184
+ * Vitest test API extended with Effect test helpers.
185
+ *
186
+ * @stability unstable
187
+ * @category testing
169
188
  * @since 4.0.0
170
189
  */
171
190
  const it = it$1;
@@ -1 +1 @@
1
- {"version":3,"file":"gateway.test.mjs","names":["Effect","Cause","Duration","Layer","Scope","V.describe","Schedule","it","V.it","internal.it"],"sources":["../../../../../node_modules/.pnpm/@effect+vitest@4.0.1_effect@4.0.1_vitest@5.0.3_@types+node@26.2.0_vite@7.3.2_@types+nod_65816e3353e20bfeb9b2e1494bdddeef/node_modules/@effect/vitest/dist/internal/internal.js","../../../../../node_modules/.pnpm/@effect+vitest@4.0.1_effect@4.0.1_vitest@5.0.3_@types+node@26.2.0_vite@7.3.2_@types+nod_65816e3353e20bfeb9b2e1494bdddeef/node_modules/@effect/vitest/dist/index.js","../../src/internal/gateway.test.ts"],"sourcesContent":["/**\n * @since 4.0.0\n */\nimport * as Arbitrary from \"effect/Arbitrary\";\nimport * as Cause from \"effect/Cause\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport { constVoid, flow, pipe } from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Scope from \"effect/Scope\";\nimport * as TestClock from \"effect/testing/TestClock\";\nimport * as TestConsole from \"effect/testing/TestConsole\";\nimport * as V from \"vitest\";\nconst getCurrentSuite = V.TestRunner.getCurrentSuite;\nconst runPromise = /*#__PURE__*/Effect.fnUntraced(function* (effect, _ctx) {\n const exit = yield* Effect.exit(effect);\n if (Exit.isFailure(exit)) {\n const errors = Cause.prettyErrors(exit.cause);\n for (let i = 0; i < errors.length; i++) {\n yield* Effect.logError(errors[i]);\n }\n }\n return yield* exit;\n}, (effect, _, ctx) => Effect.runPromise(effect, {\n signal: ctx?.signal\n}));\n/** @internal */\nconst runTest = ctx => effect => {\n const promise = runPromise(effect, ctx);\n if (ctx) {\n // Vitest stops awaiting the test promise once the signal aborts (timeout or\n // cancellation), so only then add a hook that waits for the finalizers.\n // Registering it unconditionally would change the teardown of every test.\n const onAbort = () => ctx.onTestFinished(() => promise.then(constVoid, constVoid));\n ctx.signal.addEventListener(\"abort\", onAbort, {\n once: true\n });\n const cleanup = () => ctx.signal.removeEventListener(\"abort\", onAbort);\n promise.then(cleanup, cleanup);\n // A retry after a timed-out attempt reuses the aborted signal, so no event fires.\n if (ctx.signal.aborted) onAbort();\n }\n return promise;\n};\nconst TestEnv = /*#__PURE__*/Layer.mergeAll(TestConsole.layer, /*#__PURE__*/TestClock.layer());\n/** @internal */\nexport const addEqualityTesters = () => {\n V.expect.addEqualityTesters([]);\n};\n/** @internal */\nconst testOptions = timeout => typeof timeout === \"number\" ? {\n timeout\n} : timeout ?? {};\nconst hookTimeout = timeout => timeout === undefined ? undefined : Duration.toMillis(Duration.fromInputUnsafe(timeout));\nconst propertyTestOptions = timeout => typeof timeout === \"number\" ? undefined : timeout;\nconst checkOptions = timeout => propertyTestOptions(timeout)?.arbitrary;\nconst compileArbitraryInput = input => Arbitrary.isArbitrary(input) ? input : Arbitrary.schema(input);\nconst makeArbitrary = arbitraries => Arbitrary.all(Array.isArray(arbitraries) ? arbitraries.map(compileArbitraryInput) : Object.fromEntries(Object.entries(arbitraries).map(([key, input]) => [key, compileArbitraryInput(input)])));\nconst normalizeProperty = (property, value) => Effect.catchCause(Effect.suspend(() => {\n const output = property(value);\n return Effect.isEffect(output) ? output : Effect.succeed(output);\n}), cause => Cause.hasInterrupts(cause) ? Effect.failCause(cause) : Effect.fail(cause));\nconst runCheck = (ctx, arbitrary, property, options) => runTest(ctx)(Effect.flatMapEager(Arbitrary.checkEffect(arbitrary, value => normalizeProperty(property, value), options), result => {\n const failure = Arbitrary.formatCheckFailure(result);\n return failure === undefined ? Effect.void : Effect.die(new Error(failure));\n}));\n// Vitest decides which fixtures to set up by parsing the source of a test\n// function's context parameter, and there is no public API to supply the names\n// for a wrapper, so wrappers expose the source of the function they call.\nconst withFixturesOf = (source, f) => Object.defineProperty(f, \"toString\", {\n value: () => source.toString()\n});\nconst makeItProxy = (it, overrides) => new Proxy(it, {\n apply(target, thisArg, argArray) {\n return Reflect.apply(target, thisArg, argArray);\n },\n get(target, property, receiver) {\n if (Object.hasOwn(overrides, property)) {\n return Reflect.get(overrides, property);\n }\n // do not bind: binding would strip vitest's static helpers (e.g. `describe.each`)\n return Reflect.get(target, property, receiver);\n }\n});\nconst collectTasks = (tasks, acc = []) => {\n for (let i = 0; i < tasks.length; i++) {\n const task = tasks[i];\n if (task.type === \"test\" && task.mode !== \"skip\" && task.mode !== \"todo\") {\n acc.push(task);\n } else if (task.tasks !== undefined) {\n collectTasks(task.tasks, acc);\n }\n }\n return acc;\n};\nconst registerProp = (it, name, arbitraries, property, timeout) => {\n const arbitrary = makeArbitrary(arbitraries);\n // Property callbacks receive only the base context; the empty source requests no fixtures.\n it(name, testOptions(timeout), withFixturesOf(() => {}, ctx => runCheck(ctx, arbitrary, values => property(values, ctx), checkOptions(timeout))));\n};\nconst makeTester = (mapEffect, it) => {\n const run = (ctx, args, self) => pipe(Effect.suspend(() => self(...args)), mapEffect, runTest(ctx));\n const register = test => (name, self, timeout) => test(name, testOptions(timeout), withFixturesOf(self, ctx => run(ctx, [ctx], self)));\n const each = cases => (name, self, timeout) => it.for(cases)(name, testOptions(timeout), withFixturesOf(self, (args, ctx) => run(ctx, [args, ctx], self).then(constVoid)));\n const prop = (name, arbitraries, self, timeout) => registerProp(it, name, arbitraries, (values, ctx) => Effect.mapEager(mapEffect(Effect.suspend(() => self(values, ctx))), value => value !== false), timeout);\n return Object.assign(register(it), {\n skip: register(it.skip),\n skipIf: condition => register(it.skipIf(condition)),\n runIf: condition => register(it.runIf(condition)),\n only: register(it.only),\n each,\n fails: register(it.fails),\n prop\n });\n};\nconst makeProp = it => (name, arbitraries, self, timeout) => registerProp(it, name, arbitraries, (values, ctx) => self(values, ctx) !== false, timeout);\nconst makeLayer = it => (layer_, options) => (...args) => {\n const excludeTestServices = options?.excludeTestServices ?? false;\n const withTestEnv = excludeTestServices ? layer_ : Layer.provideMerge(layer_, TestEnv);\n const memoMap = options?.memoMap ?? Effect.runSync(Layer.makeMemoMap);\n const scope = Effect.runSync(Scope.make());\n const contextEffect = Layer.buildWithMemoMap(withTestEnv, memoMap, scope).pipe(Effect.orDie, Effect.cached, Effect.runSync);\n let closed = false;\n const closeScope = () => {\n if (closed) {\n return Promise.resolve();\n }\n closed = true;\n // Layer cleanup must outlive the last test's already-aborted signal.\n return runPromise(Scope.close(scope, Exit.void));\n };\n const methods = makeItProxy(it, {\n effect: makeTester(effect => Effect.flatMap(contextEffect, context => effect.pipe(Effect.scoped, Effect.provide(context))), it),\n prop: makeProp(it),\n flakyTest,\n layer(nestedLayer, options) {\n return makeLayer(it)(Layer.provideMerge(nestedLayer, withTestEnv), {\n ...options,\n memoMap: Layer.forkMemoMapUnsafe(memoMap),\n excludeTestServices\n });\n }\n });\n if (args.length === 1) {\n const currentSuite = getCurrentSuite();\n const previousTasks = new Set(currentSuite.tasks);\n args[0](methods);\n const blockTasks = collectTasks(currentSuite.tasks.filter(task => !previousTasks.has(task)));\n if (blockTasks.length === 0) {\n V.afterAll(() => closeScope(), hookTimeout(options?.timeout));\n return;\n }\n const blockTaskSet = new Set(blockTasks);\n let remaining = blockTasks.length;\n V.beforeEach(\n // Destructured so Vitest can parse the hook once the suite defines fixtures.\n ({\n onTestFinished,\n signal,\n task\n }) => {\n if (!blockTaskSet.has(task)) {\n return;\n }\n onTestFinished(() => {\n remaining--;\n if (remaining === 0) {\n return closeScope();\n }\n });\n return runPromise(Effect.asVoid(contextEffect), {\n signal\n });\n }, hookTimeout(options?.timeout));\n V.afterAll(() => closeScope(), hookTimeout(options?.timeout));\n return;\n }\n const suiteOptions = options?.concurrent === undefined ? {} : {\n concurrent: options.concurrent\n };\n return V.describe(args[0], suiteOptions, () => {\n V.beforeAll(() => runPromise(Effect.asVoid(contextEffect)), hookTimeout(options?.timeout));\n V.afterAll(() => closeScope(), hookTimeout(options?.timeout));\n return args[1](methods);\n });\n};\n/** @internal */\nexport const flakyTest = (self, timeout = Duration.seconds(30)) => pipe(self, Effect.scoped, Effect.sandbox, Effect.retry(pipe(Schedule.recurs(10), Schedule.while(_ => Effect.succeed(Duration.isLessThanOrEqualTo(Duration.fromInputUnsafe(_.elapsed), Duration.fromInputUnsafe(timeout)))))), Effect.orDie);\n/** @internal */\nexport const makeMethods = it => makeItProxy(it, {\n effect: makeTester(flow(Effect.scoped, Effect.provide(TestEnv)), it),\n live: makeTester(Effect.scoped, it),\n flakyTest,\n layer: makeLayer(it),\n prop: makeProp(it)\n});\n/** @internal */\nexport const it = /*#__PURE__*/makeMethods(V.it);\n/** @internal */\nexport const {\n /** @internal */\n effect,\n /** @internal */\n layer,\n /** @internal */\n live,\n /** @internal */\n prop\n} = it;\n/** @internal */\nexport const describeWrapped = (name, f) => V.describe(name, () => f(it));\n//# sourceMappingURL=internal.js.map","import * as internal from \"./internal/internal.js\";\n/**\n * Re-exports the `vitest` API unchanged.\n *\n * @stability unstable\n * @since 4.0.0\n */\nexport * from \"vitest\";\n/**\n * @since 4.0.0\n */\nexport const addEqualityTesters = internal.addEqualityTesters;\n/**\n * @since 4.0.0\n */\nexport const effect = internal.effect;\n/**\n * @since 4.0.0\n */\nexport const live = internal.live;\n/**\n * Share a `Layer` between multiple tests, optionally wrapping\n * the tests in a `describe` block if a name is provided.\n *\n * Named layers accept `concurrent` to override inherited suite concurrency.\n * Anonymous layers always inherit the enclosing suite's concurrency.\n * Use `ctx.expect` in concurrent tests for test-local snapshots and assertion counts.\n *\n * @since 4.0.0\n *\n * ```ts\n * import { assert, layer } from \"@effect/vitest\"\n * import { Effect, Layer, Context } from \"effect\"\n *\n * class Foo extends Context.Service<Foo, \"foo\">()(\"Foo\") {\n * static layer = Layer.succeed(Foo, \"foo\")\n * }\n *\n * class Bar extends Context.Service<Bar, \"bar\">()(\"Bar\") {\n * static layer = Layer.effect(\n * Bar,\n * Effect.map(Foo, () => \"bar\" as const)\n * )\n * }\n *\n * layer(Foo.layer)(\"layer\", (it) => {\n * it.effect(\"adds context\", () =>\n * Effect.gen(function*() {\n * const foo = yield* Foo\n * assert.strictEqual(foo, \"foo\")\n * }))\n *\n * it.layer(Bar.layer)(\"nested\", (it) => {\n * it.effect(\"adds context\", () =>\n * Effect.gen(function*() {\n * const foo = yield* Foo\n * const bar = yield* Bar\n * assert.strictEqual(foo, \"foo\")\n * assert.strictEqual(bar, \"bar\")\n * }))\n * })\n * })\n * ```\n */\nexport const layer = internal.layer;\n/**\n * @since 4.0.0\n */\nexport const flakyTest = internal.flakyTest;\n/**\n * @since 4.0.0\n */\nexport const prop = internal.prop;\n/**\n * @since 4.0.0\n */\n/**\n * @since 4.0.0\n */\nexport const it = internal.it;\n/**\n * Creates the Effect test helpers for a Vitest test API, such as one extended with fixtures.\n *\n * **Details**\n *\n * Tests receive the fixtures they destructure from their context. Vitest sets them up before the test and tears\n * them down after the test's scope closes, as it does for its own tests. `it.effect.each` passes the context\n * after the test case, and named and anonymous `it.layer` blocks keep the fixtures.\n *\n * **Gotchas**\n *\n * Vitest reads the destructured names to decide which fixtures to set up. Once any fixture is defined, a test that\n * takes the whole context as a plain parameter, such as `(ctx) =>`, fails with a `FixtureParseError`. Property\n * tests receive only the base test context and cannot request fixtures; auto fixtures still run.\n *\n * **Example** (Using a Vitest fixture in an Effect test)\n *\n * ```ts\n * import { assert, makeMethods, test } from \"@effect/vitest\"\n * import { Effect } from \"effect\"\n *\n * const it = makeMethods(\n * test.extend(\"config\", { scope: \"file\" }, () => ({ port: 3000 }))\n * )\n *\n * it.effect(\"reads the config fixture\", ({ config }) =>\n * Effect.sync(() => {\n * assert.strictEqual(config.port, 3000)\n * }))\n * ```\n *\n * @since 4.0.0\n */\nexport const makeMethods = internal.makeMethods;\n/**\n * @since 4.0.0\n */\nexport const describeWrapped = internal.describeWrapped;\n//# sourceMappingURL=index.js.map","import { it as effect } from \"@effect/vitest\"\nimport { Effect, Layer, Queue, Redacted } from \"effect\"\nimport * as Socket from \"effect/socket/Socket\"\nimport * as FakeWebSocket from \"@effect-uai/core/testing/FakeWebSocket\"\nimport { describe, expect, it } from \"vitest\"\nimport { classifyClose, closeReason, connect } from \"./gateway.js\"\n\ndescribe(\"classifyClose\", () => {\n it(\"never retries a close reconnecting cannot fix\", () => {\n expect([4004, 4010, 4011, 4012, 4013, 4014].map(classifyClose)).toEqual(Array(6).fill(\"fatal\"))\n })\n\n it(\"identifies fresh only where the session itself is gone\", () => {\n expect([4007, 4009].map(classifyClose)).toEqual([\"reidentify\", \"reidentify\"])\n })\n\n it(\"resumes on everything else, transport drops included\", () => {\n // 1006 is a dropped connection, 4000 the code the zombie check sends.\n expect([4000, 4003, 4005, 4008, 1006, 1011].map(classifyClose)).toEqual(Array(6).fill(\"resume\"))\n })\n})\n\ndescribe(\"closeReason\", () => {\n it(\"names a fatal code, since Discord's close frames carry no reason\", () => {\n expect(closeReason(4014, \"\")).toContain(\"privileged intent\")\n })\n\n it(\"falls back to whatever the socket reported\", () => {\n expect(closeReason(1006, \"connection reset\")).toBe(\"connection reset\")\n })\n})\n\nconst cfg = { token: Redacted.make(\"token\"), intents: 0, url: \"wss://gateway.test\" }\n\n// Long enough that no heartbeat lands mid-test.\nconst HELLO = { op: 10, d: { heartbeat_interval: 3_600_000 } }\n\nconst READY = {\n op: 0,\n t: \"READY\",\n s: 1,\n d: {\n user: { id: \"1\", username: \"bot\" },\n session_id: \"session\",\n resume_gateway_url: \"wss://resume.test\",\n },\n}\n\n// Identify gets READY, resume gets RESUMED.\nconst answers: Record<number, ReadonlyArray<unknown>> = {\n 2: [READY],\n 6: [{ op: 0, t: \"RESUMED\", s: 2 }],\n}\n\nconst gateway = FakeWebSocket.make({\n greeting: [HELLO],\n reply: (frame) => Effect.succeed(answers[(frame as { op: number }).op] ?? []),\n})\n\n/** One fake per connection, in dial order; the last one takes any extra dials. */\nconst dialing = (servers: ReadonlyArray<FakeWebSocket.FakeWebSocketServer>) => {\n const urls: Array<string> = []\n const layer = Layer.succeed(Socket.WebSocketConstructor)((url, protocols) => {\n const server = servers[Math.min(urls.length, servers.length - 1)]!\n urls.push(url)\n return server.connect(url, protocols)\n })\n return { urls, layer }\n}\n\ndescribe(\"gateway close handling\", () => {\n effect.live.each([1000, 4000])(\"resumes on the resume host after a %i close\", (code) =>\n Effect.gen(function* () {\n const first = yield* gateway\n const second = yield* gateway\n const { urls, layer } = dialing([first, second])\n const session = yield* connect(cfg).pipe(Effect.provide(layer))\n expect(session.bot.username).toBe(\"bot\")\n\n yield* first.close(code)\n yield* second.awaitSent(1)\n\n expect(urls[1]).toMatch(/^wss:\\/\\/resume\\.test\\//)\n expect(yield* second.sent).toEqual([\n { op: 6, d: { token: \"token\", session_id: \"session\", seq: 1 } },\n ])\n }),\n )\n\n effect.live(\"fails the dispatches on a fatal close after READY\", () =>\n Effect.gen(function* () {\n const server = yield* gateway\n const session = yield* connect(cfg).pipe(Effect.provide(dialing([server]).layer))\n\n yield* server.close(4014)\n const error = yield* Queue.take(session.dispatches).pipe(Effect.flip)\n\n expect(error).toMatchObject({ _tag: \"MessengerTransportClosed\", raw: { code: 4014 } })\n }),\n )\n\n effect.live(\"fails the connect on a fatal close before READY\", () =>\n Effect.gen(function* () {\n const server = yield* FakeWebSocket.make({ greeting: [HELLO] })\n yield* server.awaitSent(1).pipe(Effect.andThen(server.close(4004)), Effect.forkScoped)\n\n const error = yield* connect(cfg).pipe(Effect.provide(dialing([server]).layer), Effect.flip)\n\n expect(error._tag).toBe(\"MessengerConnectFailed\")\n expect(error.reason).toContain(\"authentication failed\")\n }),\n )\n})\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;;;;;;;;;;;;;;;;AAeA,MAAM,kBAAA,WAA+B;AACrC,MAAM,aAA0B,uBAAO,WAAW,WAAW,QAAQ,MAAM;CACzE,MAAM,OAAO,OAAOA,SAAO,KAAK,MAAM;CACtC,IAAI,KAAK,UAAU,IAAI,GAAG;EACxB,MAAM,SAASC,QAAM,aAAa,KAAK,KAAK;EAC5C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KACjC,OAAOD,SAAO,SAAS,OAAO,EAAE;CAEpC;CACA,OAAO,OAAO;AAChB,IAAI,QAAQ,GAAG,QAAQA,SAAO,WAAW,QAAQ,EAC/C,QAAQ,KAAK,OACf,CAAC,CAAC;;AAEF,MAAM,WAAU,SAAO,WAAU;CAC/B,MAAM,UAAU,WAAW,QAAQ,GAAG;CACtC,IAAI,KAAK;EAIP,MAAM,gBAAgB,IAAI,qBAAqB,QAAQ,KAAK,WAAW,SAAS,CAAC;EACjF,IAAI,OAAO,iBAAiB,SAAS,SAAS,EAC5C,MAAM,KACR,CAAC;EACD,MAAM,gBAAgB,IAAI,OAAO,oBAAoB,SAAS,OAAO;EACrE,QAAQ,KAAK,SAAS,OAAO;EAE7B,IAAI,IAAI,OAAO,SAAS,QAAQ;CAClC;CACA,OAAO;AACT;AACA,MAAM,UAAuB,sBAAM,SAAS,YAAY,OAAoB,wBAAU,MAAM,CAAC;;AAM7F,MAAM,eAAc,YAAW,OAAO,YAAY,WAAW,EAC3D,QACF,IAAI,WAAW,CAAC;AAChB,MAAM,eAAc,YAAW,YAAY,KAAA,IAAY,KAAA,IA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AK,EAAE,CAAC,CAAC,QAAQ,yBAAyB;EACjD,aAAO,OAAO,OAAO,IAAI,CAAC,CAAC,QAAQ,CACjC;GAAE,IAAI;GAAG,GAAG;IAAE,OAAO;IAAS,YAAY;IAAW,KAAK;GAAE;EAAE,CAChE,CAAC;CACH,CAAC,CACH;CAEA,GAAO,KAAK,2DACV,OAAO,IAAI,aAAa;EACtB,MAAM,SAAS,OAAO;EACtB,MAAM,UAAU,OAAO,QAAQ,GAAG,CAAC,CAAC,KAAK,OAAO,QAAQ,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC;EAEhF,OAAO,OAAO,MAAM,IAAI;EACxB,MAAM,QAAQ,OAAO,MAAM,KAAK,QAAQ,UAAU,CAAC,CAAC,KAAK,OAAO,IAAI;EAEpE,aAAO,KAAK,CAAC,CAAC,cAAc;GAAE,MAAM;GAA4B,KAAK,EAAE,MAAM,KAAK;EAAE,CAAC;CACvF,CAAC,CACH;CAEA,GAAO,KAAK,yDACV,OAAO,IAAI,aAAa;EACtB,MAAM,SAAS,OAAO,cAAc,KAAK,EAAE,UAAU,CAAC,KAAK,EAAE,CAAC;EAC9D,OAAO,OAAO,UAAU,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,MAAM,IAAI,CAAC,GAAG,OAAO,UAAU;EAErF,MAAM,QAAQ,OAAO,QAAQ,GAAG,CAAC,CAAC,KAAK,OAAO,QAAQ,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,OAAO,IAAI;EAE3F,aAAO,MAAM,IAAI,CAAC,CAAC,KAAK,wBAAwB;EAChD,aAAO,MAAM,MAAM,CAAC,CAAC,UAAU,uBAAuB;CACxD,CAAC,CACH;AACF,CAAC"}
1
+ {"version":3,"file":"gateway.test.mjs","names":["Effect","Cause","Duration","Layer","V.describe","Scope","Schedule","it","V.it","internal.it"],"sources":["../../../../../node_modules/.pnpm/@effect+vitest@4.1.2_effect@4.1.2_vitest@5.0.3_@types+node@26.2.0_vite@7.3.2_@types+nod_a2fffe0deec250ef9d6207b86a9a1ab8/node_modules/@effect/vitest/dist/internal/internal.js","../../../../../node_modules/.pnpm/@effect+vitest@4.1.2_effect@4.1.2_vitest@5.0.3_@types+node@26.2.0_vite@7.3.2_@types+nod_a2fffe0deec250ef9d6207b86a9a1ab8/node_modules/@effect/vitest/dist/index.js","../../src/internal/gateway.test.ts"],"sourcesContent":["/**\n * @since 4.0.0\n */\nimport * as Arbitrary from \"effect/Arbitrary\";\nimport * as Cause from \"effect/Cause\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport { constVoid, flow, pipe } from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Scope from \"effect/Scope\";\nimport * as TestClock from \"effect/testing/TestClock\";\nimport * as TestConsole from \"effect/testing/TestConsole\";\nimport * as V from \"vitest\";\nconst getCurrentSuite = V.TestRunner.getCurrentSuite;\nconst runPromise = (effect, ctx) => Effect.runPromise(\n// Only the test is interruptible: once the signal aborts, the fiber stops\n// at its next interruptible step, which would skip reporting the defects\n// raised by finalizers.\nEffect.uninterruptibleMask(restore => Effect.gen(function* () {\n const exit = yield* Effect.exit(restore(effect));\n if (Exit.isFailure(exit)) {\n const errors = Cause.prettyErrors(exit.cause);\n for (let i = 0; i < errors.length; i++) {\n yield* Effect.logError(errors[i]);\n }\n }\n return yield* exit;\n})), {\n signal: ctx?.signal\n});\nconst settleOnAbort = (ctx, promise) => {\n // Vitest stops awaiting the promise once the signal aborts (timeout or\n // cancellation), so only then add a hook that waits for the finalizers.\n // Registering it unconditionally would change the teardown of every test.\n const onAbort = () => ctx.onTestFinished(() => promise.then(constVoid, constVoid));\n ctx.signal.addEventListener(\"abort\", onAbort, {\n once: true\n });\n const cleanup = () => ctx.signal.removeEventListener(\"abort\", onAbort);\n promise.then(cleanup, cleanup);\n // A retry after a timed-out attempt reuses the aborted signal, so no event fires.\n if (ctx.signal.aborted) onAbort();\n return promise;\n};\n/** @internal */\nconst runTest = ctx => effect => {\n const promise = runPromise(effect, ctx);\n return ctx ? settleOnAbort(ctx, promise) : promise;\n};\nconst TestEnv = /*#__PURE__*/Layer.mergeAll(TestConsole.layer, /*#__PURE__*/TestClock.layer());\n/** @internal */\nexport const addEqualityTesters = () => {\n V.expect.addEqualityTesters([]);\n};\n/** @internal */\nconst testOptions = timeout => typeof timeout === \"number\" ? {\n timeout\n} : timeout ?? {};\nconst hookTimeout = timeout => timeout === undefined ? undefined : Duration.toMillis(Duration.fromInputUnsafe(timeout));\nconst propertyTestOptions = timeout => typeof timeout === \"number\" ? undefined : timeout;\nconst checkOptions = timeout => propertyTestOptions(timeout)?.arbitrary;\nconst compileArbitraryInput = input => Arbitrary.isArbitrary(input) ? input : Arbitrary.schema(input);\nconst makeArbitrary = arbitraries => Arbitrary.all(Array.isArray(arbitraries) ? arbitraries.map(compileArbitraryInput) : Object.fromEntries(Object.entries(arbitraries).map(([key, input]) => [key, compileArbitraryInput(input)])));\nconst normalizeProperty = (property, value) => Effect.catchCause(Effect.suspend(() => {\n const output = property(value);\n return Effect.isEffect(output) ? output : Effect.succeed(output);\n}), cause => Cause.hasInterrupts(cause) ? Effect.failCause(cause) : Effect.fail(cause));\nconst runCheck = (ctx, arbitrary, property, options) => runTest(ctx)(Effect.flatMapEager(Arbitrary.checkEffect(arbitrary, value => normalizeProperty(property, value), options), result => {\n const failure = Arbitrary.formatCheckFailure(result);\n return failure === undefined ? Effect.void : Effect.die(new Error(failure));\n}));\n// Vitest decides which fixtures to set up by parsing the source of a test\n// function's context parameter, and there is no public API to supply the names\n// for a wrapper, so wrappers expose the source of the function they call.\nconst withFixturesOf = (source, f) => Object.defineProperty(f, \"toString\", {\n value: () => source.toString()\n});\nconst runHook = (fn, run) => withFixturesOf(fn, (...args) => {\n const result = fn(...args);\n if (!Effect.isEffect(result)) {\n return result;\n }\n const scope = Scope.makeUnsafe();\n // Everything the hook leaves behind lives in the scope: the resources it\n // acquired and, ahead of them, a cleanup function it returned. On failure\n // the scope closes inside the fiber, so interrupting it awaits the release.\n const effect = Scope.provide(result, scope).pipe(Effect.flatMap(cleanup => typeof cleanup === \"function\" ? Scope.addFinalizer(scope, Effect.promise(async () => await cleanup())) : Effect.void), Effect.onError(cause => Scope.close(scope, Exit.failCause(cause))));\n return run(args, effect, scope);\n});\n// Closing must outlive an already-aborted signal, so it runs without one.\nconst closeHookScope = scope => runPromise(Scope.close(scope, Exit.void));\n/** @internal */\nexport const beforeAll = (fn, timeout) => {\n let dispose = () => Promise.resolve();\n // Vitest drops the cleanup of a setup that outlives its timeout, so the\n // scope is disposed by the cleanup of a hook registered just before this\n // one. It runs in the same cleanup phase, in the slot next to this hook's,\n // with this hook's timeout.\n V.beforeAll(() => () => dispose(), timeout);\n V.beforeAll(runHook(fn, (_, effect, scope) => {\n const fiber = Effect.runFork(effect);\n // Interrupting a setup that Vitest stopped waiting for awaits its release.\n dispose = () => runPromise(Effect.andThen(Fiber.interrupt(fiber), Scope.close(scope, Exit.void)));\n return runPromise(Fiber.join(fiber));\n }), timeout);\n};\n/** @internal */\nexport const beforeEach = (fn, timeout) => V.beforeEach(runHook(fn, ([ctx], effect, scope) =>\n// The scope closes when Vitest runs the hook's cleanup after the test,\n// and the next test waits for it even if that cleanup times out.\nrunTest(ctx)(effect).then(() => () => settleOnAbort(ctx, closeHookScope(scope)))), timeout);\nconst makeItProxy = (it, overrides) => new Proxy(it, {\n apply(target, thisArg, argArray) {\n return Reflect.apply(target, thisArg, argArray);\n },\n get(target, property, receiver) {\n if (Object.hasOwn(overrides, property)) {\n return Reflect.get(overrides, property);\n }\n // do not bind: binding would strip vitest's static helpers (e.g. `describe.each`)\n return Reflect.get(target, property, receiver);\n }\n});\nconst collectTasks = (tasks, acc = []) => {\n for (let i = 0; i < tasks.length; i++) {\n const task = tasks[i];\n if (task.type === \"test\" && task.mode !== \"skip\" && task.mode !== \"todo\") {\n acc.push(task);\n } else if (task.tasks !== undefined) {\n collectTasks(task.tasks, acc);\n }\n }\n return acc;\n};\nconst runsMoreThanOnce = task => {\n const retry = typeof task.retry === \"number\" ? task.retry : task.retry?.count;\n return (retry ?? 0) > 0 || (task.repeats ?? 0) > 0;\n};\nconst registerProp = (it, name, arbitraries, property, timeout) => {\n const arbitrary = makeArbitrary(arbitraries);\n // Property callbacks receive only the base context; the empty source requests no fixtures.\n it(name, testOptions(timeout), withFixturesOf(() => {}, ctx => runCheck(ctx, arbitrary, values => property(values, ctx), checkOptions(timeout))));\n};\nconst makeTester = (mapEffect, it) => {\n const run = (ctx, args, self) => pipe(Effect.suspend(() => self(...args)), mapEffect, runTest(ctx));\n const register = test => (name, self, timeout) => test(name, testOptions(timeout), withFixturesOf(self, ctx => run(ctx, [ctx], self)));\n const each = cases => (name, self, timeout) => it.for(cases)(name, testOptions(timeout), withFixturesOf(self, (args, ctx) => run(ctx, [args, ctx], self).then(constVoid)));\n const prop = (name, arbitraries, self, timeout) => registerProp(it, name, arbitraries, (values, ctx) => Effect.mapEager(mapEffect(Effect.suspend(() => self(values, ctx))), value => value !== false), timeout);\n return Object.assign(register(it), {\n skip: register(it.skip),\n skipIf: condition => register(it.skipIf(condition)),\n runIf: condition => register(it.runIf(condition)),\n only: register(it.only),\n each,\n fails: register(it.fails),\n prop\n });\n};\nconst makeProp = it => (name, arbitraries, self, timeout) => registerProp(it, name, arbitraries, (values, ctx) => {\n const result = self(values, ctx);\n if (result !== undefined && typeof result !== \"boolean\") {\n throw new TypeError(\"it.prop callbacks must return boolean or void. Use it.effect.prop for Effect callbacks.\");\n }\n return result !== false;\n}, timeout);\nconst makeLayer = it => (layer_, options) => (...args) => {\n const excludeTestServices = options?.excludeTestServices ?? false;\n const withTestEnv = excludeTestServices ? layer_ : Layer.provideMerge(layer_, TestEnv);\n const memoMap = options?.memoMap ?? Effect.runSync(Layer.makeMemoMap);\n const buildPerTest = options?.buildPerTest ?? false;\n const suiteOptions = options?.concurrent === undefined ? {} : {\n concurrent: options.concurrent\n };\n const makeBlockMethods = provide => makeItProxy(it, {\n effect: makeTester(effect => provide(Effect.scoped(effect)), it),\n prop: makeProp(it),\n flakyTest,\n layer(nestedLayer, nestedOptions) {\n return makeLayer(it)(Layer.provideMerge(nestedLayer, withTestEnv), {\n ...nestedOptions,\n memoMap: Layer.forkMemoMapUnsafe(memoMap),\n excludeTestServices,\n // The services of a per-test block only exist during a test, so\n // blocks nested in it are built per test as well.\n buildPerTest: buildPerTest || nestedOptions?.buildPerTest === true\n });\n }\n });\n if (buildPerTest) {\n // Each test builds into its own fork of the memo map, so it reuses the\n // services of enclosing blocks and releases the rest when it finishes.\n const methods = makeBlockMethods(effect => Effect.scopedWith(scope => Layer.buildWithMemoMap(withTestEnv, Layer.forkMemoMapUnsafe(memoMap), scope).pipe(Effect.orDie, Effect.flatMap(context => Effect.provide(effect, context)))));\n if (args.length === 1) {\n return args[0](methods);\n }\n return V.describe(args[0], suiteOptions, () => args[1](methods));\n }\n const scope = Effect.runSync(Scope.make());\n const contextEffect = Layer.buildWithMemoMap(withTestEnv, memoMap, scope).pipe(Effect.orDie, Effect.cached, Effect.runSync);\n let closed = false;\n const closeScope = () => {\n if (closed) {\n return Promise.resolve();\n }\n closed = true;\n // Layer cleanup must outlive the last test's already-aborted signal.\n return runPromise(Scope.close(scope, Exit.void));\n };\n const methods = makeBlockMethods(effect => Effect.flatMap(contextEffect, context => Effect.provide(effect, context)));\n if (args.length === 1) {\n const currentSuite = getCurrentSuite();\n const previousTasks = new Set(currentSuite.tasks);\n args[0](methods);\n const blockTasks = collectTasks(currentSuite.tasks.filter(task => !previousTasks.has(task)));\n if (blockTasks.length === 0) {\n V.afterAll(() => closeScope(), hookTimeout(options?.timeout));\n return;\n }\n const blockTaskSet = new Set(blockTasks);\n // Vitest runs hooks once per retry and repeat attempt, so a test's last\n // attempt cannot be counted. Blocks with such tests are released by `afterAll`.\n const releaseAfterLastTest = !blockTasks.some(runsMoreThanOnce);\n let remaining = blockTasks.length;\n V.beforeEach(\n // Destructured so Vitest can parse the hook once the suite defines fixtures.\n ({\n onTestFinished,\n signal,\n task\n }) => {\n if (!blockTaskSet.has(task)) {\n return;\n }\n if (releaseAfterLastTest) {\n onTestFinished(() => {\n remaining--;\n if (remaining === 0) {\n return closeScope();\n }\n });\n }\n return runPromise(Effect.asVoid(contextEffect), {\n signal\n });\n }, hookTimeout(options?.timeout));\n V.afterAll(() => closeScope(), hookTimeout(options?.timeout));\n return;\n }\n return V.describe(args[0], suiteOptions, () => {\n V.beforeAll(() => runPromise(Effect.asVoid(contextEffect)), hookTimeout(options?.timeout));\n V.afterAll(() => closeScope(), hookTimeout(options?.timeout));\n return args[1](methods);\n });\n};\n/** @internal */\nexport const flakyTest = (self, timeout = Duration.seconds(30)) => pipe(self, Effect.scoped, Effect.sandbox, Effect.retry(pipe(Schedule.recurs(10), Schedule.while(_ => Effect.succeed(Duration.isLessThanOrEqualTo(Duration.fromInputUnsafe(_.elapsed), Duration.fromInputUnsafe(timeout)))))), Effect.orDie);\n/** @internal */\nexport const makeMethods = it => makeItProxy(it, {\n effect: makeTester(flow(Effect.scoped, Effect.provide(TestEnv)), it),\n live: makeTester(Effect.scoped, it),\n flakyTest,\n layer: makeLayer(it),\n prop: makeProp(it)\n});\n/** @internal */\nexport const it = /*#__PURE__*/makeMethods(V.it);\n/** @internal */\nexport const {\n /** @internal */\n effect,\n /** @internal */\n layer,\n /** @internal */\n live,\n /** @internal */\n prop\n} = it;\n/** @internal */\nexport const describeWrapped = (name, f) => V.describe(name, () => f(it));\n//# sourceMappingURL=internal.js.map","import * as internal from \"./internal/internal.js\";\n/**\n * Re-exports the `vitest` API unchanged.\n *\n * @stability unstable\n * @since 4.0.0\n */\nexport * from \"vitest\";\n/**\n * Invokes the Effect Vitest equality-tester registration hook.\n *\n * @stability unstable\n * @category utils\n * @since 4.0.0\n */\nexport const addEqualityTesters = internal.addEqualityTesters;\n/**\n * Registers a callback to run once before all tests in the current suite. If\n * the callback returns an `Effect`, it is run and awaited with a `Scope` that\n * closes in a cleanup after the suite's `afterAll` hooks, within the hook's\n * timeout. The `Effect` must not require any other services.\n *\n * **Details**\n *\n * If Vitest stops waiting for the setup, the setup is interrupted before the\n * `Scope` closes. As with any `beforeAll` cleanup, Vitest reports a closing\n * that exceeds the hook's timeout and does not wait for it.\n *\n * @stability unstable\n * @category hooks\n * @since 4.0.0\n */\nexport const beforeAll = internal.beforeAll;\n/**\n * Registers a callback to run before each test in the current suite. If the\n * callback returns an `Effect`, it is run and awaited with a `Scope` that\n * closes when the test finishes, and interrupted if the hook times out. The\n * `Effect` must not require any other services.\n *\n * @stability unstable\n * @category hooks\n * @since 4.0.0\n */\nexport const beforeEach = internal.beforeEach;\n/**\n * Runs a scoped Effect test with test clock and console services.\n *\n * @stability unstable\n * @category testing\n * @since 4.0.0\n */\nexport const effect = internal.effect;\n/**\n * Runs a scoped Effect test with live services.\n *\n * @stability unstable\n * @category testing\n * @since 4.0.0\n */\nexport const live = internal.live;\n/**\n * Share a `Layer` between multiple tests, optionally wrapping\n * the tests in a `describe` block if a name is provided.\n *\n * **Details**\n *\n * Named layers accept `concurrent` to override inherited suite concurrency.\n * Anonymous layers always inherit the enclosing suite's concurrency.\n * Use `ctx.expect` in concurrent tests for test-local snapshots and assertion counts.\n *\n * Pass `buildPerTest: true` to build the layer once per test instead of once\n * per block. Each test gets new services, released when the test finishes,\n * while services from an enclosing `layer` block stay shared. A build failure\n * fails only that test. Blocks nested inside a per-test block are built per\n * test as well. `timeout` has no effect on a per-test block, since the test's\n * own timeout covers the build.\n *\n * **Example** (Sharing layers between tests)\n *\n * ```ts\n * import { assert, layer } from \"@effect/vitest\"\n * import { Effect, Layer, Context } from \"effect\"\n *\n * class Foo extends Context.Service<Foo, \"foo\">()(\"Foo\") {\n * static layer = Layer.succeed(Foo, \"foo\")\n * }\n *\n * class Bar extends Context.Service<Bar, \"bar\">()(\"Bar\") {\n * static layer = Layer.effect(\n * Bar,\n * Effect.map(Foo, () => \"bar\" as const)\n * )\n * }\n *\n * layer(Foo.layer)(\"layer\", (it) => {\n * it.effect(\"adds context\", () =>\n * Effect.gen(function*() {\n * const foo = yield* Foo\n * assert.strictEqual(foo, \"foo\")\n * }))\n *\n * it.layer(Bar.layer)(\"nested\", (it) => {\n * it.effect(\"adds context\", () =>\n * Effect.gen(function*() {\n * const foo = yield* Foo\n * const bar = yield* Bar\n * assert.strictEqual(foo, \"foo\")\n * assert.strictEqual(bar, \"bar\")\n * }))\n * })\n * })\n * ```\n *\n * **Example** (Building a layer for each test)\n *\n * ```ts\n * import { assert, layer } from \"@effect/vitest\"\n * import { Effect, Layer, Context, Ref } from \"effect\"\n *\n * class Database extends Context.Service<Database, \"database\">()(\"Database\") {\n * static layer = Layer.succeed(Database, \"database\")\n * }\n *\n * class Cache extends Context.Service<Cache, Ref.Ref<Array<string>>>()(\"Cache\") {\n * static layer = Layer.effect(\n * Cache,\n * Effect.andThen(Database, Ref.make<Array<string>>([]))\n * )\n * }\n *\n * layer(Database.layer)(\"repository\", (it) => {\n * // Database is shared, Cache is built for each test\n * it.layer(Cache.layer, { buildPerTest: true })((it) => {\n * it.effect(\"writes to the cache\", () =>\n * Effect.gen(function*() {\n * const cache = yield* Cache\n * yield* Ref.update(cache, (keys) => [...keys, \"a\"])\n * assert.deepStrictEqual(yield* Ref.get(cache), [\"a\"])\n * }))\n *\n * it.effect(\"starts with an empty cache\", () =>\n * Effect.gen(function*() {\n * const cache = yield* Cache\n * assert.deepStrictEqual(yield* Ref.get(cache), [])\n * }))\n * })\n * })\n * ```\n *\n * @stability unstable\n * @category testing\n * @since 4.0.0\n */\nexport const layer = internal.layer;\n/**\n * Retries a scoped Effect to tolerate intermittent test failures, dying on exhausted retries.\n *\n * @stability unstable\n * @category testing\n * @since 4.0.0\n */\nexport const flakyTest = internal.flakyTest;\n/**\n * Runs a synchronous property test using schemas or arbitraries.\n *\n * @stability unstable\n * @category testing\n * @since 4.0.0\n */\nexport const prop = internal.prop;\n/**\n * Vitest test API extended with Effect test helpers.\n *\n * @stability unstable\n * @category testing\n * @since 4.0.0\n */\nexport const it = internal.it;\n/**\n * Creates the Effect test helpers for a Vitest test API, such as one extended with fixtures.\n *\n * **Details**\n *\n * Tests receive the fixtures they destructure from their context. Vitest sets them up before the test and tears\n * them down after the test's scope closes, as it does for its own tests. `it.effect.each` passes the context\n * after the test case, and named and anonymous `it.layer` blocks keep the fixtures.\n *\n * **Gotchas**\n *\n * Vitest reads the destructured names to decide which fixtures to set up. Once any fixture is defined, a test that\n * takes the whole context as a plain parameter, such as `(ctx) =>`, fails with a `FixtureParseError`. Property\n * tests receive only the base test context and cannot request fixtures; auto fixtures still run.\n *\n * **Example** (Using a Vitest fixture in an Effect test)\n *\n * ```ts\n * import { assert, makeMethods, test } from \"@effect/vitest\"\n * import { Effect } from \"effect\"\n *\n * const it = makeMethods(\n * test.extend(\"config\", { scope: \"file\" }, () => ({ port: 3000 }))\n * )\n *\n * it.effect(\"reads the config fixture\", ({ config }) =>\n * Effect.sync(() => {\n * assert.strictEqual(config.port, 3000)\n * }))\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeMethods = internal.makeMethods;\n/**\n * Creates a named Vitest suite whose callback receives Effect test helpers.\n *\n * @stability unstable\n * @category testing\n * @since 4.0.0\n */\nexport const describeWrapped = internal.describeWrapped;\n//# sourceMappingURL=index.js.map","import { it as effect } from \"@effect/vitest\"\nimport { Effect, Layer, Queue, Redacted } from \"effect\"\nimport * as Socket from \"effect/socket/Socket\"\nimport * as FakeWebSocket from \"@effect-uai/core/testing/FakeWebSocket\"\nimport { describe, expect, it } from \"vitest\"\nimport { classifyClose, closeReason, connect } from \"./gateway.js\"\n\ndescribe(\"classifyClose\", () => {\n it(\"never retries a close reconnecting cannot fix\", () => {\n expect([4004, 4010, 4011, 4012, 4013, 4014].map(classifyClose)).toEqual(Array(6).fill(\"fatal\"))\n })\n\n it(\"identifies fresh only where the session itself is gone\", () => {\n expect([4007, 4009].map(classifyClose)).toEqual([\"reidentify\", \"reidentify\"])\n })\n\n it(\"resumes on everything else, transport drops included\", () => {\n // 1006 is a dropped connection, 4000 the code the zombie check sends.\n expect([4000, 4003, 4005, 4008, 1006, 1011].map(classifyClose)).toEqual(Array(6).fill(\"resume\"))\n })\n})\n\ndescribe(\"closeReason\", () => {\n it(\"names a fatal code, since Discord's close frames carry no reason\", () => {\n expect(closeReason(4014, \"\")).toContain(\"privileged intent\")\n })\n\n it(\"falls back to whatever the socket reported\", () => {\n expect(closeReason(1006, \"connection reset\")).toBe(\"connection reset\")\n })\n})\n\nconst cfg = { token: Redacted.make(\"token\"), intents: 0, url: \"wss://gateway.test\" }\n\n// Long enough that no heartbeat lands mid-test.\nconst HELLO = { op: 10, d: { heartbeat_interval: 3_600_000 } }\n\nconst READY = {\n op: 0,\n t: \"READY\",\n s: 1,\n d: {\n user: { id: \"1\", username: \"bot\" },\n session_id: \"session\",\n resume_gateway_url: \"wss://resume.test\",\n },\n}\n\n// Identify gets READY, resume gets RESUMED.\nconst answers: Record<number, ReadonlyArray<unknown>> = {\n 2: [READY],\n 6: [{ op: 0, t: \"RESUMED\", s: 2 }],\n}\n\nconst gateway = FakeWebSocket.make({\n greeting: [HELLO],\n reply: (frame) => Effect.succeed(answers[(frame as { op: number }).op] ?? []),\n})\n\n/** One fake per connection, in dial order; the last one takes any extra dials. */\nconst dialing = (servers: ReadonlyArray<FakeWebSocket.FakeWebSocketServer>) => {\n const urls: Array<string> = []\n const layer = Layer.succeed(Socket.WebSocketConstructor)((url, protocols) => {\n const server = servers[Math.min(urls.length, servers.length - 1)]!\n urls.push(url)\n return server.connect(url, protocols)\n })\n return { urls, layer }\n}\n\ndescribe(\"gateway close handling\", () => {\n effect.live.each([1000, 4000])(\"resumes on the resume host after a %i close\", (code) =>\n Effect.gen(function* () {\n const first = yield* gateway\n const second = yield* gateway\n const { urls, layer } = dialing([first, second])\n const session = yield* connect(cfg).pipe(Effect.provide(layer))\n expect(session.bot.username).toBe(\"bot\")\n\n yield* first.close(code)\n yield* second.awaitSent(1)\n\n expect(urls[1]).toMatch(/^wss:\\/\\/resume\\.test\\//)\n expect(yield* second.sent).toEqual([\n { op: 6, d: { token: \"token\", session_id: \"session\", seq: 1 } },\n ])\n }),\n )\n\n effect.live(\"fails the dispatches on a fatal close after READY\", () =>\n Effect.gen(function* () {\n const server = yield* gateway\n const session = yield* connect(cfg).pipe(Effect.provide(dialing([server]).layer))\n\n yield* server.close(4014)\n const error = yield* Queue.take(session.dispatches).pipe(Effect.flip)\n\n expect(error).toMatchObject({ _tag: \"MessengerTransportClosed\", raw: { code: 4014 } })\n }),\n )\n\n effect.live(\"fails the connect on a fatal close before READY\", () =>\n Effect.gen(function* () {\n const server = yield* FakeWebSocket.make({ greeting: [HELLO] })\n yield* server.awaitSent(1).pipe(Effect.andThen(server.close(4004)), Effect.forkScoped)\n\n const error = yield* connect(cfg).pipe(Effect.provide(dialing([server]).layer), Effect.flip)\n\n expect(error._tag).toBe(\"MessengerConnectFailed\")\n expect(error.reason).toContain(\"authentication failed\")\n }),\n )\n})\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgBA,MAAM,kBAAA,WAA+B;AACrC,MAAM,cAAc,QAAQ,QAAQA,SAAO,WAI3CA,SAAO,qBAAoB,YAAWA,SAAO,IAAI,aAAa;CAC5D,MAAM,OAAO,OAAOA,SAAO,KAAK,QAAQ,MAAM,CAAC;CAC/C,IAAI,KAAK,UAAU,IAAI,GAAG;EACxB,MAAM,SAASC,QAAM,aAAa,KAAK,KAAK;EAC5C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KACjC,OAAOD,SAAO,SAAS,OAAO,EAAE;CAEpC;CACA,OAAO,OAAO;AAChB,CAAC,CAAC,GAAG,EACH,QAAQ,KAAK,OACf,CAAC;AACD,MAAM,iBAAiB,KAAK,YAAY;CAItC,MAAM,gB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from "@effect-uai/core/Multipart";
5
5
  //#region src/internal/rest.ts
6
6
  const provider = "discord";
7
7
  /** Tracks the package version; Discord requires a `DiscordBot (url, version)` agent. */
8
- const userAgent = "DiscordBot (https://effect-uai.betalyra.com, 0.14.0)";
8
+ const userAgent = "DiscordBot (https://effect-uai.com, 0.14.0)";
9
9
  /**
10
10
  * A REST call that came back non-2xx or never came back at all. `code` is
11
11
  * Discord's own JSON error code, `status` the HTTP one; each verb maps this
@@ -1 +1 @@
1
- {"version":3,"file":"rest.mjs","names":[],"sources":["../../src/internal/rest.ts"],"sourcesContent":["import { Data, Duration, Effect, Redacted, Schema } from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/http\"\nimport * as MessengerError from \"@effect-uai/core/MessengerError\"\nimport * as Multipart from \"@effect-uai/core/Multipart\"\n\nexport const provider = \"discord\"\n\n/** Tracks the package version; Discord requires a `DiscordBot (url, version)` agent. */\nconst userAgent = \"DiscordBot (https://effect-uai.betalyra.com, 0.14.0)\"\n\nexport type Config = {\n readonly token: Redacted.Redacted\n /** Defaults to `https://discord.com/api/v10`. Always version-pinned. */\n readonly baseUrl?: string\n}\n\nexport type Method = \"GET\" | \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\"\n\n/** JSON body fields of a request. */\nexport type Fields = Readonly<Record<string, unknown>>\n\n/**\n * A REST call that came back non-2xx or never came back at all. `code` is\n * Discord's own JSON error code, `status` the HTTP one; each verb maps this\n * onto its own `MessengerError`.\n */\nexport class ApiFailure extends Data.TaggedError(\"DiscordApiFailure\")<{\n readonly route: string\n readonly status?: number\n readonly code?: number\n readonly message: string\n readonly raw: unknown\n}> {}\n\nexport type ApiError = ApiFailure | MessengerError.MessengerRateLimited\n\nconst ErrorBody = Schema.Struct({\n message: Schema.optional(Schema.String),\n code: Schema.optional(Schema.Number),\n retry_after: Schema.optional(Schema.Number),\n})\n\n/** The file part of a multipart message. Discord names it `files[n]`. */\nexport type Upload = {\n readonly bytes: Uint8Array\n readonly filename: string\n readonly mimeType: string\n}\n\nconst endpoint = (cfg: Config, path: string): string =>\n `${cfg.baseUrl ?? \"https://discord.com/api/v10\"}${path}`\n\nconst constructors: Record<Method, (url: string) => HttpClientRequest.HttpClientRequest> = {\n GET: HttpClientRequest.get,\n POST: HttpClientRequest.post,\n PATCH: HttpClientRequest.patch,\n PUT: HttpClientRequest.put,\n DELETE: HttpClientRequest.delete,\n}\n\nconst request = (cfg: Config, method: Method, path: string) =>\n constructors[method](endpoint(cfg, path)).pipe(\n HttpClientRequest.setHeaders({\n Authorization: `Bot ${Redacted.value(cfg.token)}`,\n \"User-Agent\": userAgent,\n }),\n )\n\nconst transportFailure = (route: string) => (raw: unknown) =>\n new ApiFailure({ route, message: \"transport failure\", raw })\n\nconst rejected = (route: string, status: number, raw: unknown): Effect.Effect<never, ApiError> =>\n Effect.gen(function* () {\n const body = yield* Schema.decodeUnknownEffect(ErrorBody)(raw).pipe(\n Effect.orElseSucceed((): typeof ErrorBody.Type => ({})),\n )\n // Discord's `retry_after` is float seconds; only a 429 carries one.\n return yield* status === 429 && body.retry_after !== undefined\n ? new MessengerError.MessengerRateLimited({\n provider,\n retryAfter: Duration.seconds(body.retry_after),\n raw,\n })\n : new ApiFailure({\n route,\n status,\n ...(body.code !== undefined && { code: body.code }),\n message: body.message ?? `HTTP ${status}`,\n raw,\n })\n })\n\nconst send = (\n route: string,\n httpRequest: HttpClientRequest.HttpClientRequest,\n): Effect.Effect<unknown, ApiError, HttpClient.HttpClient> =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError(transportFailure(route)))\n // 204 is the success shape of `typing`, `react` and every delete: no body\n // to read, and reading one would fail.\n if (response.status === 204) return undefined\n const body = yield* response.json.pipe(Effect.mapError(transportFailure(route)))\n return response.status < 400 ? body : yield* rejected(route, response.status, body)\n })\n\n/** One JSON call against the API base. The response body comes back undecoded. */\nexport const call =\n (cfg: Config) =>\n (\n method: Method,\n path: string,\n body?: unknown,\n ): Effect.Effect<unknown, ApiError, HttpClient.HttpClient> =>\n send(\n `${method} ${path}`,\n body === undefined\n ? request(cfg, method, path)\n : request(cfg, method, path).pipe(HttpClientRequest.bodyJsonUnsafe(body)),\n )\n\n// The `attachments` entry is what binds `files[0]` to the message; without it\n// Discord can drop the part and reject the rest as an empty message.\nconst formData = (payload: Fields, file: Upload): FormData => {\n const form = new FormData()\n form.append(\n \"payload_json\",\n JSON.stringify({ ...payload, attachments: [{ id: 0, filename: file.filename }] }),\n )\n form.append(\n \"files[0]\",\n new File([file.bytes as Uint8Array<ArrayBuffer>], file.filename, { type: file.mimeType }),\n )\n return form\n}\n\n/** One multipart message: the JSON fields as `payload_json` plus a single file. */\nexport const upload =\n (cfg: Config) =>\n (\n path: string,\n payload: Fields,\n file: Upload,\n ): Effect.Effect<unknown, ApiError, HttpClient.HttpClient> =>\n Effect.gen(function* () {\n const route = `POST ${path}`\n const body = yield* Multipart.bodyMultipart(formData(payload, file)).pipe(\n Effect.mapError(transportFailure(route)),\n )\n return yield* send(route, request(cfg, \"POST\", path).pipe(body))\n })\n\n/** Decode a response body; a shape mismatch is a malformed response, not a defect. */\nexport const decoded =\n <A>(route: string, schema: Schema.Decoder<A>) =>\n <E, R>(result: Effect.Effect<unknown, E, R>): Effect.Effect<A, E | ApiFailure, R> =>\n Effect.gen(function* () {\n const raw = yield* result\n return yield* Schema.decodeUnknownEffect(schema)(raw).pipe(\n Effect.mapError(() => new ApiFailure({ route, message: \"malformed response\", raw })),\n )\n })\n"],"mappings":";;;;;AAKA,MAAa,WAAW;;AAGxB,MAAM,YAAY;;;;;;AAkBlB,IAAa,aAAb,cAAgC,KAAK,YAAY,mBAAmB,CAAC,CAMlE,CAAC;AAIJ,MAAM,YAAY,OAAO,OAAO;CAC9B,SAAS,OAAO,SAAS,OAAO,MAAM;CACtC,MAAM,OAAO,SAAS,OAAO,MAAM;CACnC,aAAa,OAAO,SAAS,OAAO,MAAM;AAC5C,CAAC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AM,OAAO,OAAO,SAAS,OAAO,SAAS,QAAQ,IAAI;AACpF,CAAC;;AAGH,MAAa,QACV,SAEC,QACA,MACA,SAEA,KACE,GAAG,OAAO,GAAG,QACb,SAAS,KAAA,IACL,QAAQ,KAAK,QAAQ,IAAI,IACzB,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,kBAAkB,eAAe,IAAI,CAAC,CAC5E;AAIJ,MAAM,YAAY,SAAiB,SAA2B;CAC5D,MAAM,OAAO,IAAI,SAAS;CAC1B,KAAK,OACH,gBACA,KAAK,UAAU;EAAE,GAAG;EAAS,aAAa,CAAC;GAAE,IAAI;GAAG,UAAU,KAAK;EAAS,CAAC;CAAE,CAAC,CAClF;CACA,KAAK,OACH,YACA,IAAI,KAAK,CAAC,KAAK,KAAgC,GAAG,KAAK,UAAU,EAAE,MAAM,KAAK,SAAS,CAAC,CAC1F;CACA,OAAO;AACT;;AAGA,MAAa,UACV,SAEC,MACA,SACA,SAEA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,QAAQ;CACtB,MAAM,OAAO,OAAO,UAAU,cAAc,SAAS,SAAS,IAAI,CAAC,CAAC,CAAC,KACnE,OAAO,SAAS,iBAAiB,KAAK,CAAC,CACzC;CACA,OAAO,OAAO,KAAK,OAAO,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,IAAI,CAAC;AACjE,CAAC;;AAGL,MAAa,WACP,OAAe,YACZ,WACL,OAAO,IAAI,aAAa;CACtB,MAAM,MAAM,OAAO;CACnB,OAAO,OAAO,OAAO,oBAAoB,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,KACpD,OAAO,eAAe,IAAI,WAAW;EAAE;EAAO,SAAS;EAAsB;CAAI,CAAC,CAAC,CACrF;AACF,CAAC"}
1
+ {"version":3,"file":"rest.mjs","names":[],"sources":["../../src/internal/rest.ts"],"sourcesContent":["import { Data, Duration, Effect, Redacted, Schema } from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/http\"\nimport * as MessengerError from \"@effect-uai/core/MessengerError\"\nimport * as Multipart from \"@effect-uai/core/Multipart\"\n\nexport const provider = \"discord\"\n\n/** Tracks the package version; Discord requires a `DiscordBot (url, version)` agent. */\nconst userAgent = \"DiscordBot (https://effect-uai.com, 0.14.0)\"\n\nexport type Config = {\n readonly token: Redacted.Redacted\n /** Defaults to `https://discord.com/api/v10`. Always version-pinned. */\n readonly baseUrl?: string\n}\n\nexport type Method = \"GET\" | \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\"\n\n/** JSON body fields of a request. */\nexport type Fields = Readonly<Record<string, unknown>>\n\n/**\n * A REST call that came back non-2xx or never came back at all. `code` is\n * Discord's own JSON error code, `status` the HTTP one; each verb maps this\n * onto its own `MessengerError`.\n */\nexport class ApiFailure extends Data.TaggedError(\"DiscordApiFailure\")<{\n readonly route: string\n readonly status?: number\n readonly code?: number\n readonly message: string\n readonly raw: unknown\n}> {}\n\nexport type ApiError = ApiFailure | MessengerError.MessengerRateLimited\n\nconst ErrorBody = Schema.Struct({\n message: Schema.optional(Schema.String),\n code: Schema.optional(Schema.Number),\n retry_after: Schema.optional(Schema.Number),\n})\n\n/** The file part of a multipart message. Discord names it `files[n]`. */\nexport type Upload = {\n readonly bytes: Uint8Array\n readonly filename: string\n readonly mimeType: string\n}\n\nconst endpoint = (cfg: Config, path: string): string =>\n `${cfg.baseUrl ?? \"https://discord.com/api/v10\"}${path}`\n\nconst constructors: Record<Method, (url: string) => HttpClientRequest.HttpClientRequest> = {\n GET: HttpClientRequest.get,\n POST: HttpClientRequest.post,\n PATCH: HttpClientRequest.patch,\n PUT: HttpClientRequest.put,\n DELETE: HttpClientRequest.delete,\n}\n\nconst request = (cfg: Config, method: Method, path: string) =>\n constructors[method](endpoint(cfg, path)).pipe(\n HttpClientRequest.setHeaders({\n Authorization: `Bot ${Redacted.value(cfg.token)}`,\n \"User-Agent\": userAgent,\n }),\n )\n\nconst transportFailure = (route: string) => (raw: unknown) =>\n new ApiFailure({ route, message: \"transport failure\", raw })\n\nconst rejected = (route: string, status: number, raw: unknown): Effect.Effect<never, ApiError> =>\n Effect.gen(function* () {\n const body = yield* Schema.decodeUnknownEffect(ErrorBody)(raw).pipe(\n Effect.orElseSucceed((): typeof ErrorBody.Type => ({})),\n )\n // Discord's `retry_after` is float seconds; only a 429 carries one.\n return yield* status === 429 && body.retry_after !== undefined\n ? new MessengerError.MessengerRateLimited({\n provider,\n retryAfter: Duration.seconds(body.retry_after),\n raw,\n })\n : new ApiFailure({\n route,\n status,\n ...(body.code !== undefined && { code: body.code }),\n message: body.message ?? `HTTP ${status}`,\n raw,\n })\n })\n\nconst send = (\n route: string,\n httpRequest: HttpClientRequest.HttpClientRequest,\n): Effect.Effect<unknown, ApiError, HttpClient.HttpClient> =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError(transportFailure(route)))\n // 204 is the success shape of `typing`, `react` and every delete: no body\n // to read, and reading one would fail.\n if (response.status === 204) return undefined\n const body = yield* response.json.pipe(Effect.mapError(transportFailure(route)))\n return response.status < 400 ? body : yield* rejected(route, response.status, body)\n })\n\n/** One JSON call against the API base. The response body comes back undecoded. */\nexport const call =\n (cfg: Config) =>\n (\n method: Method,\n path: string,\n body?: unknown,\n ): Effect.Effect<unknown, ApiError, HttpClient.HttpClient> =>\n send(\n `${method} ${path}`,\n body === undefined\n ? request(cfg, method, path)\n : request(cfg, method, path).pipe(HttpClientRequest.bodyJsonUnsafe(body)),\n )\n\n// The `attachments` entry is what binds `files[0]` to the message; without it\n// Discord can drop the part and reject the rest as an empty message.\nconst formData = (payload: Fields, file: Upload): FormData => {\n const form = new FormData()\n form.append(\n \"payload_json\",\n JSON.stringify({ ...payload, attachments: [{ id: 0, filename: file.filename }] }),\n )\n form.append(\n \"files[0]\",\n new File([file.bytes as Uint8Array<ArrayBuffer>], file.filename, { type: file.mimeType }),\n )\n return form\n}\n\n/** One multipart message: the JSON fields as `payload_json` plus a single file. */\nexport const upload =\n (cfg: Config) =>\n (\n path: string,\n payload: Fields,\n file: Upload,\n ): Effect.Effect<unknown, ApiError, HttpClient.HttpClient> =>\n Effect.gen(function* () {\n const route = `POST ${path}`\n const body = yield* Multipart.bodyMultipart(formData(payload, file)).pipe(\n Effect.mapError(transportFailure(route)),\n )\n return yield* send(route, request(cfg, \"POST\", path).pipe(body))\n })\n\n/** Decode a response body; a shape mismatch is a malformed response, not a defect. */\nexport const decoded =\n <A>(route: string, schema: Schema.Decoder<A>) =>\n <E, R>(result: Effect.Effect<unknown, E, R>): Effect.Effect<A, E | ApiFailure, R> =>\n Effect.gen(function* () {\n const raw = yield* result\n return yield* Schema.decodeUnknownEffect(schema)(raw).pipe(\n Effect.mapError(() => new ApiFailure({ route, message: \"malformed response\", raw })),\n )\n })\n"],"mappings":";;;;;AAKA,MAAa,WAAW;;AAGxB,MAAM,YAAY;;;;;;AAkBlB,IAAa,aAAb,cAAgC,KAAK,YAAY,mBAAmB,CAAC,CAMlE,CAAC;AAIJ,MAAM,YAAY,OAAO,OAAO;CAC9B,SAAS,OAAO,SAAS,OAAO,MAAM;CACtC,MAAM,OAAO,SAAS,OAAO,MAAM;CACnC,aAAa,OAAO,SAAS,OAAO,MAAM;AAC5C,CAAC;AASD,MAAM,YAAY,KAAa,SAC7B,GAAG,IAAI,WAAW,gCAAgC;AAEpD,MAAM,eAAqF;CACzF,KAAK,kBAAkB;CACvB,MAAM,kBAAkB;CACxB,OAAO,kBAAkB;CACzB,KAAK,kBAAkB;CACvB,QAAQ,kBAAkB;AAC5B;AAEA,MAAM,WAAW,KAAa,QAAgB,SAC5C,aAAa,OAAO,CAAC,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,KACxC,kBAAkB,WAAW;CAC3B,eAAe,OAAO,SAAS,MAAM,IAAI,KAAK;CAC9C,cAAc;AAChB,CAAC,CACH;AAEF,MAAM,oBAAoB,WAAmB,QAC3C,IAAI,WAAW;CAAE;CAAO,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AAC,CAClF;CACA,KAAK,OACH,YACA,IAAI,KAAK,CAAC,KAAK,KAAgC,GAAG,KAAK,UAAU,EAAE,MAAM,KAAK,SAAS,CAAC,CAC1F;CACA,OAAO;AACT;;AAGA,MAAa,UACV,SAEC,MACA,SACA,SAEA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,QAAQ;CACtB,MAAM,OAAO,OAAO,UAAU,cAAc,SAAS,SAAS,IAAI,CAAC,CAAC,CAAC,KACnE,OAAO,SAAS,iBAAiB,KAAK,CAAC,CACzC;CACA,OAAO,OAAO,KAAK,OAAO,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,KAAK,IAAI,CAAC;AACjE,CAAC;;AAGL,MAAa,WACP,OAAe,YACZ,WACL,OAAO,IAAI,aAAa;CACtB,MAAM,MAAM,OAAO;CACnB,OAAO,OAAO,OAAO,oBAAoB,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,KACpD,OAAO,eAAe,IAAI,WAAW;EAAE;EAAO,SAAS;EAAsB;CAAI,CAAC,CAAC,CACrF;AACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@effect-uai/discord",
3
- "version": "0.18.0",
3
+ "version": "0.19.0-dev-20261110065930",
4
4
  "description": "Discord provider for @effect-uai/core (Messenger capability over the gateway and REST API).",
5
5
  "keywords": [
6
6
  "agents",
@@ -44,12 +44,12 @@
44
44
  "access": "public"
45
45
  },
46
46
  "devDependencies": {
47
- "effect": "4.0.1",
47
+ "effect": "4.1.2",
48
48
  "typescript": "^7.0.2",
49
- "@effect-uai/core": "0.18.0"
49
+ "@effect-uai/core": "0.19.0-dev-20261110065930"
50
50
  },
51
51
  "peerDependencies": {
52
- "@effect-uai/core": ">=0.15.0 <1",
52
+ "@effect-uai/core": "0.19.0-dev-20261110065930",
53
53
  "effect": ">=4.0.1 <5.0.0"
54
54
  },
55
55
  "scripts": {
@@ -6,7 +6,7 @@ import * as Multipart from "@effect-uai/core/Multipart"
6
6
  export const provider = "discord"
7
7
 
8
8
  /** Tracks the package version; Discord requires a `DiscordBot (url, version)` agent. */
9
- const userAgent = "DiscordBot (https://effect-uai.betalyra.com, 0.14.0)"
9
+ const userAgent = "DiscordBot (https://effect-uai.com, 0.14.0)"
10
10
 
11
11
  export type Config = {
12
12
  readonly token: Redacted.Redacted