alchemy 2.0.0-beta.13 → 2.0.0-beta.14

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 (264) hide show
  1. package/bin/alchemy.js +8386 -8205
  2. package/bin/alchemy.js.map +1 -1
  3. package/bin/alchemy.ts +4 -2
  4. package/bin/cli.js +61 -0
  5. package/bin/commands/deploy.ts +6 -3
  6. package/bin/commands/login.ts +1 -1
  7. package/bin/commands/logs.ts +1 -1
  8. package/bin/commands/state.ts +230 -0
  9. package/bin/commands/tail.ts +1 -1
  10. package/lib/AWS/AutoScaling/LaunchTemplate.d.ts +1 -1
  11. package/lib/AWS/EC2/Instance.d.ts +1 -1
  12. package/lib/AWS/EC2/hosted.d.ts +2 -2
  13. package/lib/AWS/ECS/Task.d.ts +4 -4
  14. package/lib/AWS/ECS/Task.d.ts.map +1 -1
  15. package/lib/AWS/ECS/Task.js +2 -2
  16. package/lib/AWS/ECS/Task.js.map +1 -1
  17. package/lib/AWS/Environment.d.ts +2 -2
  18. package/lib/AWS/Lambda/BucketEventSource.d.ts +1 -1
  19. package/lib/AWS/Lambda/BucketEventSource.d.ts.map +1 -1
  20. package/lib/AWS/Lambda/EventBridgeEventSource.d.ts +1 -1
  21. package/lib/AWS/Lambda/EventBridgeEventSource.d.ts.map +1 -1
  22. package/lib/AWS/Lambda/Function.d.ts +2 -2
  23. package/lib/AWS/Lambda/Function.d.ts.map +1 -1
  24. package/lib/AWS/Lambda/Function.js +1 -2
  25. package/lib/AWS/Lambda/Function.js.map +1 -1
  26. package/lib/AWS/Lambda/QueueEventSource.d.ts +1 -1
  27. package/lib/AWS/Lambda/QueueEventSource.d.ts.map +1 -1
  28. package/lib/AWS/Lambda/StreamEventSource.d.ts +1 -1
  29. package/lib/AWS/Lambda/StreamEventSource.d.ts.map +1 -1
  30. package/lib/AWS/Lambda/TableEventSource.d.ts +1 -1
  31. package/lib/AWS/Lambda/TableEventSource.d.ts.map +1 -1
  32. package/lib/AWS/Lambda/TopicEventSource.d.ts +1 -1
  33. package/lib/AWS/Lambda/TopicEventSource.d.ts.map +1 -1
  34. package/lib/AWS/SQS/QueueSink.d.ts.map +1 -1
  35. package/lib/AWS/SQS/QueueSink.js +1 -2
  36. package/lib/AWS/SQS/QueueSink.js.map +1 -1
  37. package/lib/Agent/coding/bash.d.ts +2 -6
  38. package/lib/Agent/coding/bash.d.ts.map +1 -1
  39. package/lib/Agent/coding/bash.js +2 -3
  40. package/lib/Agent/coding/bash.js.map +1 -1
  41. package/lib/Agent/coding/edit.d.ts +1 -1
  42. package/lib/Agent/coding/glob.d.ts +2 -4
  43. package/lib/Agent/coding/glob.d.ts.map +1 -1
  44. package/lib/Agent/coding/glob.js +1 -2
  45. package/lib/Agent/coding/glob.js.map +1 -1
  46. package/lib/Agent/coding/grep.d.ts +2 -4
  47. package/lib/Agent/coding/grep.d.ts.map +1 -1
  48. package/lib/Agent/coding/grep.js +1 -2
  49. package/lib/Agent/coding/grep.js.map +1 -1
  50. package/lib/Agent/coding/read.d.ts +1 -1
  51. package/lib/Agent/coding/write.d.ts +1 -1
  52. package/lib/Agent/util/ripgrep.d.ts +2 -2
  53. package/lib/AlchemyContext.d.ts +13 -0
  54. package/lib/AlchemyContext.d.ts.map +1 -0
  55. package/lib/AlchemyContext.js +18 -0
  56. package/lib/AlchemyContext.js.map +1 -0
  57. package/lib/Auth/AuthProvider.js +1 -1
  58. package/lib/Auth/AuthProvider.js.map +1 -1
  59. package/lib/Auth/Profile.d.ts +1 -1
  60. package/lib/Auth/index.d.ts +3 -1
  61. package/lib/Auth/index.d.ts.map +1 -1
  62. package/lib/Auth/index.js +3 -0
  63. package/lib/Auth/index.js.map +1 -1
  64. package/lib/Build/Command.d.ts +1 -1
  65. package/lib/Build/Memo.d.ts +1 -1
  66. package/lib/Bundle/Docker.d.ts +3 -3
  67. package/lib/Bundle/TempRoot.d.ts +3 -3
  68. package/lib/Cli/InkCLI.d.ts +1 -0
  69. package/lib/Cli/InkCLI.d.ts.map +1 -1
  70. package/lib/Cli/InkCLI.js +5 -0
  71. package/lib/Cli/InkCLI.js.map +1 -1
  72. package/lib/Cli/LoggingCli.d.ts +4 -0
  73. package/lib/Cli/LoggingCli.d.ts.map +1 -0
  74. package/lib/{Test/TestCli.js → Cli/LoggingCli.js} +3 -3
  75. package/lib/Cli/LoggingCli.js.map +1 -0
  76. package/lib/Cloudflare/CloudflareEnvironment.d.ts +1 -1
  77. package/lib/Cloudflare/Container/ContainerApplication.d.ts +2 -2
  78. package/lib/Cloudflare/Container/ContainerApplication.d.ts.map +1 -1
  79. package/lib/Cloudflare/Container/ContainerApplication.js +7 -2
  80. package/lib/Cloudflare/Container/ContainerApplication.js.map +1 -1
  81. package/lib/Cloudflare/EdgeSession.d.ts +53 -0
  82. package/lib/Cloudflare/EdgeSession.d.ts.map +1 -0
  83. package/lib/Cloudflare/EdgeSession.js +78 -0
  84. package/lib/Cloudflare/EdgeSession.js.map +1 -0
  85. package/lib/Cloudflare/Providers.d.ts +1 -1
  86. package/lib/Cloudflare/Providers.d.ts.map +1 -1
  87. package/lib/Cloudflare/StateStore/Api.d.ts +62 -0
  88. package/lib/Cloudflare/StateStore/Api.d.ts.map +1 -0
  89. package/lib/Cloudflare/StateStore/Api.js +101 -0
  90. package/lib/Cloudflare/StateStore/Api.js.map +1 -0
  91. package/lib/Cloudflare/StateStore/State.d.ts +39 -0
  92. package/lib/Cloudflare/StateStore/State.d.ts.map +1 -0
  93. package/lib/Cloudflare/StateStore/State.js +217 -0
  94. package/lib/Cloudflare/StateStore/State.js.map +1 -0
  95. package/lib/Cloudflare/StateStore/Store.d.ts +82 -0
  96. package/lib/Cloudflare/StateStore/Store.d.ts.map +1 -0
  97. package/lib/Cloudflare/StateStore/Store.js +189 -0
  98. package/lib/Cloudflare/StateStore/Store.js.map +1 -0
  99. package/lib/Cloudflare/StateStore/Token.d.ts +41 -0
  100. package/lib/Cloudflare/StateStore/Token.d.ts.map +1 -0
  101. package/lib/Cloudflare/StateStore/Token.js +57 -0
  102. package/lib/Cloudflare/StateStore/Token.js.map +1 -0
  103. package/lib/Cloudflare/StateStore/index.d.ts +2 -0
  104. package/lib/Cloudflare/StateStore/index.d.ts.map +1 -0
  105. package/lib/Cloudflare/StateStore/index.js +2 -0
  106. package/lib/Cloudflare/StateStore/index.js.map +1 -0
  107. package/lib/Cloudflare/Workers/Assets.d.ts +2 -2
  108. package/lib/Cloudflare/Workers/DurableObjectNamespace.d.ts +2 -2
  109. package/lib/Cloudflare/Workers/DurableObjectNamespace.d.ts.map +1 -1
  110. package/lib/Cloudflare/Workers/DurableObjectNamespace.js +0 -1
  111. package/lib/Cloudflare/Workers/DurableObjectNamespace.js.map +1 -1
  112. package/lib/Cloudflare/Workers/HttpServer.d.ts +1 -1
  113. package/lib/Cloudflare/Workers/HttpServer.d.ts.map +1 -1
  114. package/lib/Cloudflare/Workers/HttpServer.js.map +1 -1
  115. package/lib/Cloudflare/Workers/Worker.d.ts +5 -5
  116. package/lib/Cloudflare/Workers/Worker.d.ts.map +1 -1
  117. package/lib/Cloudflare/Workers/Worker.js +0 -1
  118. package/lib/Cloudflare/Workers/Worker.js.map +1 -1
  119. package/lib/Cloudflare/index.d.ts +3 -1
  120. package/lib/Cloudflare/index.d.ts.map +1 -1
  121. package/lib/Cloudflare/index.js +3 -1
  122. package/lib/Cloudflare/index.js.map +1 -1
  123. package/lib/Deploy.d.ts +10 -0
  124. package/lib/Deploy.d.ts.map +1 -0
  125. package/lib/Deploy.js +12 -0
  126. package/lib/Deploy.js.map +1 -0
  127. package/lib/Destroy.d.ts +8 -3
  128. package/lib/Destroy.d.ts.map +1 -1
  129. package/lib/Destroy.js +8 -8
  130. package/lib/Destroy.js.map +1 -1
  131. package/lib/Http.d.ts +1 -1
  132. package/lib/Http.d.ts.map +1 -1
  133. package/lib/Http.js +7 -3
  134. package/lib/Http.js.map +1 -1
  135. package/lib/Kubernetes/client.d.ts +10 -10
  136. package/lib/Output.d.ts.map +1 -1
  137. package/lib/Output.js.map +1 -1
  138. package/lib/Platform.d.ts +2 -2
  139. package/lib/Platform.d.ts.map +1 -1
  140. package/lib/Platform.js.map +1 -1
  141. package/lib/Provider.d.ts.map +1 -1
  142. package/lib/Provider.js +0 -1
  143. package/lib/Provider.js.map +1 -1
  144. package/lib/Stack.d.ts +23 -12
  145. package/lib/Stack.d.ts.map +1 -1
  146. package/lib/Stack.js +32 -14
  147. package/lib/Stack.js.map +1 -1
  148. package/lib/State/HttpStateApi.d.ts +96 -0
  149. package/lib/State/HttpStateApi.d.ts.map +1 -0
  150. package/lib/State/HttpStateApi.js +96 -0
  151. package/lib/State/HttpStateApi.js.map +1 -0
  152. package/lib/State/HttpStateStore.d.ts +10 -0
  153. package/lib/State/HttpStateStore.d.ts.map +1 -0
  154. package/lib/State/HttpStateStore.js +102 -0
  155. package/lib/State/HttpStateStore.js.map +1 -0
  156. package/lib/State/InMemoryState.d.ts +2 -30
  157. package/lib/State/InMemoryState.d.ts.map +1 -1
  158. package/lib/State/InMemoryState.js +23 -18
  159. package/lib/State/InMemoryState.js.map +1 -1
  160. package/lib/State/LocalState.d.ts +4 -2
  161. package/lib/State/LocalState.d.ts.map +1 -1
  162. package/lib/State/LocalState.js +9 -41
  163. package/lib/State/LocalState.js.map +1 -1
  164. package/lib/State/State.d.ts +11 -4
  165. package/lib/State/State.d.ts.map +1 -1
  166. package/lib/State/State.js +1 -1
  167. package/lib/State/State.js.map +1 -1
  168. package/lib/State/StateEncoding.d.ts +31 -0
  169. package/lib/State/StateEncoding.d.ts.map +1 -0
  170. package/lib/State/StateEncoding.js +82 -0
  171. package/lib/State/StateEncoding.js.map +1 -0
  172. package/lib/State/Sync.d.ts +23 -0
  173. package/lib/State/Sync.d.ts.map +1 -0
  174. package/lib/State/Sync.js +49 -0
  175. package/lib/State/Sync.js.map +1 -0
  176. package/lib/State/index.d.ts +4 -0
  177. package/lib/State/index.d.ts.map +1 -1
  178. package/lib/State/index.js +4 -0
  179. package/lib/State/index.js.map +1 -1
  180. package/lib/Test/Bun.d.ts +13 -17
  181. package/lib/Test/Bun.d.ts.map +1 -1
  182. package/lib/Test/Bun.js +16 -33
  183. package/lib/Test/Bun.js.map +1 -1
  184. package/lib/Test/TestState.d.ts +1 -2
  185. package/lib/Test/TestState.d.ts.map +1 -1
  186. package/lib/Test/TestState.js +5 -9
  187. package/lib/Test/TestState.js.map +1 -1
  188. package/lib/Test/Vitest.d.ts +3 -2
  189. package/lib/Test/Vitest.d.ts.map +1 -1
  190. package/lib/Test/Vitest.js +20 -15
  191. package/lib/Test/Vitest.js.map +1 -1
  192. package/lib/Test/index.d.ts +0 -1
  193. package/lib/Test/index.d.ts.map +1 -1
  194. package/lib/Test/index.js +0 -1
  195. package/lib/Test/index.js.map +1 -1
  196. package/lib/Util/FileLogger.d.ts +2 -2
  197. package/lib/Util/FileLogger.d.ts.map +1 -1
  198. package/lib/Util/FileLogger.js +2 -2
  199. package/lib/Util/FileLogger.js.map +1 -1
  200. package/lib/cli/index.d.ts +10 -1
  201. package/lib/cli/index.d.ts.map +1 -1
  202. package/lib/cli/index.js +9 -4
  203. package/lib/cli/index.js.map +1 -1
  204. package/lib/index.d.ts +2 -1
  205. package/lib/index.d.ts.map +1 -1
  206. package/lib/index.js +2 -1
  207. package/lib/index.js.map +1 -1
  208. package/package.json +26 -11
  209. package/src/AWS/ECS/Task.ts +4 -4
  210. package/src/AWS/Lambda/Function.ts +2 -3
  211. package/src/AWS/SQS/QueueSink.ts +1 -2
  212. package/src/Agent/coding/bash.ts +2 -3
  213. package/src/Agent/coding/glob.ts +1 -2
  214. package/src/Agent/coding/grep.ts +1 -2
  215. package/src/AlchemyContext.ts +27 -0
  216. package/src/Auth/AuthProvider.ts +1 -1
  217. package/src/Auth/index.ts +3 -1
  218. package/src/Cli/InkCLI.tsx +10 -0
  219. package/src/{Test/TestCli.ts → Cli/LoggingCli.ts} +2 -2
  220. package/src/Cloudflare/Container/ContainerApplication.ts +8 -2
  221. package/src/Cloudflare/EdgeSession.ts +144 -0
  222. package/src/Cloudflare/StateStore/Api.ts +157 -0
  223. package/src/Cloudflare/StateStore/State.ts +318 -0
  224. package/src/Cloudflare/StateStore/Store.ts +288 -0
  225. package/src/Cloudflare/StateStore/Token.ts +62 -0
  226. package/src/Cloudflare/StateStore/index.ts +1 -0
  227. package/src/Cloudflare/Workers/DurableObjectNamespace.ts +1 -6
  228. package/src/Cloudflare/Workers/HttpServer.ts +1 -1
  229. package/src/Cloudflare/Workers/Worker.ts +7 -7
  230. package/src/Cloudflare/index.ts +3 -1
  231. package/src/Deploy.ts +25 -0
  232. package/src/Destroy.ts +25 -13
  233. package/src/Http.ts +31 -16
  234. package/src/Output.ts +0 -2
  235. package/src/Platform.ts +8 -2
  236. package/src/Provider.ts +0 -2
  237. package/src/Stack.ts +122 -47
  238. package/src/State/HttpStateApi.ts +155 -0
  239. package/src/State/HttpStateStore.ts +155 -0
  240. package/src/State/InMemoryState.ts +15 -17
  241. package/src/State/LocalState.ts +13 -45
  242. package/src/State/State.ts +13 -4
  243. package/src/State/StateEncoding.ts +83 -0
  244. package/src/State/Sync.ts +89 -0
  245. package/src/State/index.ts +4 -0
  246. package/src/Test/Bun.ts +29 -87
  247. package/src/Test/TestState.ts +6 -8
  248. package/src/Test/Vitest.ts +32 -23
  249. package/src/Test/index.ts +0 -1
  250. package/src/Util/FileLogger.ts +2 -2
  251. package/src/index.ts +2 -1
  252. package/lib/Config.d.ts +0 -20
  253. package/lib/Config.d.ts.map +0 -1
  254. package/lib/Config.js +0 -22
  255. package/lib/Config.js.map +0 -1
  256. package/lib/Observability.d.ts +0 -2
  257. package/lib/Observability.d.ts.map +0 -1
  258. package/lib/Observability.js +0 -1
  259. package/lib/Observability.js.map +0 -1
  260. package/lib/Test/TestCli.d.ts +0 -4
  261. package/lib/Test/TestCli.d.ts.map +0 -1
  262. package/lib/Test/TestCli.js.map +0 -1
  263. package/src/Config.ts +0 -31
  264. package/src/Observability.ts +0 -0
@@ -0,0 +1,157 @@
1
+ import * as Cloudflare from "alchemy/Cloudflare";
2
+ import {
3
+ BearerTokenValidator,
4
+ StateApi,
5
+ StateAuthLive,
6
+ } from "alchemy/State/HttpStateApi";
7
+ import * as Effect from "effect/Effect";
8
+ import * as Layer from "effect/Layer";
9
+ import * as Path from "effect/Path";
10
+ import * as Etag from "effect/unstable/http/Etag";
11
+ import * as HttpPlatform from "effect/unstable/http/HttpPlatform";
12
+ import * as HttpRouter from "effect/unstable/http/HttpRouter";
13
+ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
14
+ import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";
15
+ import crypto from "node:crypto";
16
+ import Store from "./Store.ts";
17
+ import { AuthToken } from "./Token.ts";
18
+
19
+ export const STATE_STORE_SCRIPT_NAME = "alchemy-state-store" as const;
20
+
21
+ export default Cloudflare.Worker(
22
+ "Api",
23
+ {
24
+ name: STATE_STORE_SCRIPT_NAME,
25
+ main: import.meta.path,
26
+ url: true,
27
+ compatibility: {
28
+ flags: ["nodejs_compat"],
29
+ date: "2026-03-17",
30
+ },
31
+ },
32
+ Effect.gen(function* () {
33
+ const secret = yield* Cloudflare.Secret.bind(AuthToken);
34
+ const store = yield* Store;
35
+
36
+ const bearerTokenValidator = Layer.effect(
37
+ BearerTokenValidator,
38
+ secret.get().pipe(
39
+ Effect.map((expected) =>
40
+ BearerTokenValidator.of({
41
+ validate: (token) =>
42
+ !!expected && timingSafeEqual(token, expected)
43
+ ? Effect.void
44
+ : Effect.fail(new HttpApiError.Unauthorized()),
45
+ }),
46
+ ),
47
+ Effect.orDie,
48
+ ),
49
+ );
50
+
51
+ const stateApi = HttpApiBuilder.group(StateApi, "state", (handlers) =>
52
+ handlers
53
+ .handle("listStacks", () =>
54
+ store.getByName(Store.ROOT_DO_NAME).listStacks(),
55
+ )
56
+ .handle("listStages", ({ params }) =>
57
+ store.getByName(params.stack).listStages(),
58
+ )
59
+ .handle("listResources", ({ params }) =>
60
+ store.getByName(params.stack).listResources({ stage: params.stage }),
61
+ )
62
+ .handle("getState", ({ params }) =>
63
+ store
64
+ .getByName(params.stack)
65
+ .get({ stage: params.stage, fqn: decodeURIComponent(params.fqn) }),
66
+ )
67
+ .handle("setState", ({ params, payload }) =>
68
+ store
69
+ .getByName(params.stack)
70
+ .set({
71
+ stage: params.stage,
72
+ fqn: decodeURIComponent(params.fqn),
73
+ value: payload as any,
74
+ })
75
+ .pipe(
76
+ Effect.tap(() =>
77
+ store
78
+ .getByName(Store.ROOT_DO_NAME)
79
+ .registerStack({ stack: params.stack }),
80
+ ),
81
+ ),
82
+ )
83
+ .handle("deleteState", ({ params }) =>
84
+ // The DO method is `remove`, not `delete` — `delete` is
85
+ // reserved by Cloudflare's RPC stub proxy.
86
+ store
87
+ .getByName(params.stack)
88
+ .remove({
89
+ stage: params.stage,
90
+ fqn: decodeURIComponent(params.fqn),
91
+ })
92
+ .pipe(Effect.asVoid),
93
+ )
94
+ .handle("getReplacedResources", ({ params }) =>
95
+ store
96
+ .getByName(params.stack)
97
+ .getReplacedResources({ stage: params.stage }),
98
+ )
99
+ .handle("deleteStack", ({ params, query }) =>
100
+ store
101
+ .getByName(params.stack)
102
+ .deleteStack(
103
+ query.stage === undefined ? {} : { stage: query.stage },
104
+ )
105
+ .pipe(
106
+ Effect.flatMap(() =>
107
+ query.stage === undefined
108
+ ? store
109
+ .getByName(Store.ROOT_DO_NAME)
110
+ .unregisterStack({ stack: params.stack })
111
+ : Effect.void,
112
+ ),
113
+ Effect.asVoid,
114
+ ),
115
+ ),
116
+ );
117
+
118
+ return {
119
+ fetch: HttpApiBuilder.layer(StateApi).pipe(
120
+ Layer.provide(stateApi),
121
+ Layer.provide(StateAuthLive),
122
+ Layer.provide(bearerTokenValidator),
123
+ // The state-store worker never serves files, so HttpPlatform's
124
+ // file-response surface is stubbed.
125
+ Layer.provide([Etag.layer, HttpPlatformStub, Path.layer]),
126
+ HttpRouter.toHttpEffect,
127
+ ),
128
+ };
129
+ }).pipe(Effect.provide(Layer.mergeAll(Cloudflare.SecretBindingLive))),
130
+ );
131
+
132
+ /**
133
+ * Stub `HttpPlatform` for the worker. The state-store API never
134
+ * issues file responses, so both surface methods die if invoked. Lets
135
+ * us avoid pulling in a `FileSystem` dependency that workers don't
136
+ * have.
137
+ */
138
+ const HttpPlatformStub = Layer.succeed(HttpPlatform.HttpPlatform, {
139
+ fileResponse: () => Effect.die("HttpPlatform.fileResponse not supported"),
140
+ fileWebResponse: () =>
141
+ Effect.die("HttpPlatform.fileWebResponse not supported"),
142
+ });
143
+
144
+ /**
145
+ * Timing-safe string comparison using the Workers runtime's built-in
146
+ * `crypto.subtle.timingSafeEqual`.
147
+ *
148
+ * @see https://developers.cloudflare.com/workers/examples/protect-against-timing-attacks/
149
+ */
150
+ const timingSafeEqual = (a: string, b: string): boolean => {
151
+ const encoder = new TextEncoder();
152
+ const aBytes = encoder.encode(a);
153
+ const bBytes = encoder.encode(b);
154
+ if (aBytes.byteLength !== bBytes.byteLength) return false;
155
+ // @ts-expect-error - TODO(sam)
156
+ return crypto.subtle.timingSafeEqual(aBytes, bBytes);
157
+ };
@@ -0,0 +1,318 @@
1
+ import * as SecretsStore from "@distilled.cloud/cloudflare/secrets-store";
2
+ import * as workers from "@distilled.cloud/cloudflare/workers";
3
+ import * as Output from "alchemy/Output";
4
+ import * as Effect from "effect/Effect";
5
+ import * as Layer from "effect/Layer";
6
+ import * as Redacted from "effect/Redacted";
7
+ import * as HttpClient from "effect/unstable/http/HttpClient";
8
+
9
+ import * as Config from "effect/Config";
10
+ import { AuthError } from "../../Auth/AuthProvider.ts";
11
+ import { readCredentials, writeCredentials } from "../../Auth/Credentials.ts";
12
+ import { ALCHEMY_PROFILE } from "../../Auth/Profile.ts";
13
+ import * as Cloudflare from "../../Cloudflare/Providers.ts";
14
+ import { deploy } from "../../Deploy.ts";
15
+ import * as Alchemy from "../../Stack.ts";
16
+ import {
17
+ makeHttpStateStore,
18
+ type HttpStateStoreProps,
19
+ } from "../../State/HttpStateStore.ts";
20
+ import * as CloudflareEnvironment from "../CloudflareEnvironment.ts";
21
+ import * as Credentials from "../Credentials.ts";
22
+
23
+ import { AlchemyContext } from "../../AlchemyContext.ts";
24
+ import { makeLocalState } from "../../State/LocalState.ts";
25
+ import { State, type StateService } from "../../State/State.ts";
26
+ import { syncState } from "../../State/Sync.ts";
27
+ import * as Clank from "../../Util/Clank.ts";
28
+ import { CloudflareAuth } from "../Auth/AuthProvider.ts";
29
+ import { EdgeSessionError, createEdgeSession } from "../EdgeSession.ts";
30
+ import Api, { STATE_STORE_SCRIPT_NAME } from "./Api.ts";
31
+ import { AuthTokenSecretName, TokenValue } from "./Token.ts";
32
+
33
+ /** Filename used for stored credentials under the profile directory. */
34
+ const CREDENTIALS_FILE = "cloudflare-state-store";
35
+
36
+ export const state = (props?: {
37
+ /**
38
+ * The name of the script to use for the state store.
39
+ * @default "alchemy-state-store"
40
+ */
41
+ workerName?: string;
42
+ }) =>
43
+ Layer.effect(
44
+ State,
45
+ Effect.gen(function* () {
46
+ const isCI = yield* Config.boolean("CI").pipe(Config.withDefault(false));
47
+ const alchemyContext = yield* AlchemyContext;
48
+ const profileName = yield* ALCHEMY_PROFILE;
49
+ const credentials = yield* readCredentials<HttpStateStoreProps>(
50
+ profileName,
51
+ CREDENTIALS_FILE,
52
+ );
53
+
54
+ const scriptName = props?.workerName ?? STATE_STORE_SCRIPT_NAME;
55
+
56
+ // TODO(sam): support upgrading state store, right now we only deploy once
57
+ if (credentials) {
58
+ // it's in the profile, let's go
59
+ const httpState = yield* makeHttpStateStore(credentials);
60
+
61
+ if (alchemyContext.updateStateStore) {
62
+ yield* deployStateStore(scriptName, httpState);
63
+ }
64
+
65
+ return httpState;
66
+ } else {
67
+ // our profile does not contain a reference to the state store, let's try and resolve it
68
+ const { accountId } =
69
+ yield* CloudflareEnvironment.CloudflareEnvironment;
70
+ const workerExists = yield* workers
71
+ .getScriptSetting({
72
+ accountId,
73
+ scriptName,
74
+ })
75
+ .pipe(
76
+ Effect.map((setting) => setting !== undefined),
77
+ Effect.catchTag("WorkerNotFound", () => Effect.succeed(false)),
78
+ );
79
+
80
+ if (workerExists) {
81
+ // it exists, so fetch the secret token
82
+ const credentials = yield* loginWithCloudflare();
83
+ if (!isCI) {
84
+ yield* writeCredentials<HttpStateStoreProps>(
85
+ profileName,
86
+ CREDENTIALS_FILE,
87
+ credentials,
88
+ );
89
+ }
90
+ const httpState = yield* makeHttpStateStore(credentials);
91
+
92
+ if (alchemyContext.updateStateStore) {
93
+ yield* deployStateStore(scriptName, httpState);
94
+ }
95
+
96
+ return httpState;
97
+ } else if (isCI) {
98
+ // TODO(sam): do we want to support bootstrapping the state store from CI?
99
+ // for now - just die here
100
+ return yield* Effect.die(
101
+ new AuthError({
102
+ message: `State store not found for script ${scriptName}. Deploy the state store first.`,
103
+ }),
104
+ );
105
+ }
106
+
107
+ const shouldDeploy = yield* Clank.confirm({
108
+ message:
109
+ "Cloudflare State Store not found. Do you want to deploy it?",
110
+ });
111
+
112
+ if (!shouldDeploy) {
113
+ return yield* Effect.die(new Clank.PromptCancelled());
114
+ }
115
+
116
+ const { url, authToken, localState } =
117
+ yield* deployStateStore(scriptName);
118
+
119
+ const httpState = yield* makeHttpStateStore({ url, authToken });
120
+
121
+ yield* syncState(localState, httpState);
122
+
123
+ yield* writeCredentials<HttpStateStoreProps>(
124
+ profileName,
125
+ CREDENTIALS_FILE,
126
+ {
127
+ url,
128
+ authToken,
129
+ },
130
+ );
131
+
132
+ yield* localState.deleteStack({
133
+ stack: "CloudflareStateStore",
134
+ stage: scriptName,
135
+ });
136
+
137
+ return httpState;
138
+ }
139
+ }).pipe(Effect.orDie),
140
+ ).pipe(
141
+ Layer.provideMerge(Credentials.fromAuthProvider()),
142
+ Layer.provideMerge(CloudflareEnvironment.fromProfile()),
143
+ Layer.provideMerge(CloudflareAuth),
144
+ Layer.orDie,
145
+ );
146
+
147
+ const deployStateStore = (scriptName: string, state?: StateService) =>
148
+ Effect.gen(function* () {
149
+ const localState = state ?? (yield* makeLocalState());
150
+ // deploy it with local state (which we will then hoist into the Cloudflare state store)
151
+ const stateLayer = Layer.succeed(State, localState);
152
+ const { url, authToken } = yield* deploy({
153
+ // use the script name as the stage name (so the user can have multiple state stores)
154
+ stage: scriptName,
155
+ stack: Alchemy.Stack(
156
+ "CloudflareStateStore",
157
+ {
158
+ providers: Cloudflare.providers(),
159
+ state: stateLayer,
160
+ },
161
+ Effect.gen(function* () {
162
+ const token = yield* TokenValue;
163
+ const api = yield* Api;
164
+
165
+ // Surface the bearer token so tests and clients can authenticate
166
+ // after deploy. The underlying value lives in the Cloudflare
167
+ // Secrets Store; this output carries the same generated string.
168
+ return {
169
+ url: api.url.as<string>(),
170
+ authToken: token.text.pipe(Output.map(Redacted.value)),
171
+ };
172
+ }),
173
+ ),
174
+ }).pipe(
175
+ // TODO(sam): we should not need to do this, but types do complain. fix deploy
176
+ Effect.provide(stateLayer),
177
+ );
178
+ return { url, authToken, localState };
179
+ });
180
+
181
+ /**
182
+ * Log in to a Cloudflare-deployed HTTP state-store.
183
+ *
184
+ * 1. Find the single account-wide Secrets Store.
185
+ * 2. Upload a short-lived edge-preview worker that binds the
186
+ * auth-token secret and returns its value.
187
+ * 3. Derive the state-store worker URL from
188
+ * {@link STATE_STORE_SCRIPT_NAME} and the account's workers.dev
189
+ * subdomain.
190
+ * 4. Persist `{ url, token }` under the `http-state-store`
191
+ * credentials file.
192
+ *
193
+ * Requirements are covered by the Cloudflare provider stack —
194
+ * `CloudflareEnvironment`, `Credentials`, `HttpClient`, and
195
+ * `FileSystem`.
196
+ */
197
+ export const loginWithCloudflare = () =>
198
+ Effect.gen(function* () {
199
+ const isCI = yield* Config.boolean("CI").pipe(Config.withDefault(false));
200
+ const profileName = yield* ALCHEMY_PROFILE;
201
+ const { accountId } = yield* CloudflareEnvironment.CloudflareEnvironment;
202
+
203
+ // 1. Locate the single Secrets Store on the account.
204
+ const stores = yield* SecretsStore.listStores({ accountId });
205
+ const store = stores.result[0];
206
+ if (!store) {
207
+ return yield* Effect.fail(
208
+ new AuthError({
209
+ message:
210
+ "No Secrets Store found on this account. Deploy the state store first.",
211
+ }),
212
+ );
213
+ }
214
+
215
+ // 2. Fetch the auth-token value via an edge-preview worker.
216
+ const authToken = yield* readSecretViaEdge(store.id, AuthTokenSecretName);
217
+
218
+ // 3. Derive the deployed worker URL.
219
+ const { subdomain } = yield* workers.getSubdomain({ accountId });
220
+ const url = `https://${STATE_STORE_SCRIPT_NAME}.${subdomain}.workers.dev`;
221
+
222
+ if (!isCI) {
223
+ // 4. Persist credentials. The profile entry is managed by
224
+ // `loadOrConfigure` when this is invoked through `configure`.
225
+ yield* writeCredentials<HttpStateStoreProps>(
226
+ profileName,
227
+ CREDENTIALS_FILE,
228
+ {
229
+ url,
230
+ authToken: authToken.trim(),
231
+ },
232
+ ).pipe(
233
+ Effect.mapError(
234
+ (e) =>
235
+ new AuthError({ message: "Failed to write credentials", cause: e }),
236
+ ),
237
+ );
238
+
239
+ yield* Clank.success(
240
+ `HTTP state store credentials saved for '${profileName}'.`,
241
+ );
242
+ yield* Clank.info(` url: ${url}`);
243
+ }
244
+
245
+ return {
246
+ url,
247
+ authToken: authToken.trim(),
248
+ };
249
+ }).pipe(
250
+ Effect.catchTag("EdgeSessionError", (e) =>
251
+ Effect.fail(
252
+ new AuthError({
253
+ message: `Edge-preview secret read failed: ${e.message}`,
254
+ cause: e.cause,
255
+ }),
256
+ ),
257
+ ),
258
+ );
259
+
260
+ /** Preview script name used by the edge-probe worker. */
261
+ const PROBE_SCRIPT_NAME = "alchemy-state-store-probe";
262
+
263
+ /**
264
+ * Tiny ES-module worker that reads `env.SECRET.get()` and echoes it
265
+ * back. Uploaded as an ephemeral edge-preview, called once, then
266
+ * discarded — see {@link readSecretViaEdge}.
267
+ */
268
+ const SECRET_PROBE_SOURCE = `export default {
269
+ async fetch(_request, env) {
270
+ try {
271
+ const value = await env.SECRET.get();
272
+ return new Response(value ?? "", { status: 200, headers: { "content-type": "text/plain" } });
273
+ } catch (e) {
274
+ return new Response("Error: " + (e && e.message ? e.message : String(e)), { status: 500 });
275
+ }
276
+ },
277
+ };`;
278
+
279
+ /**
280
+ * Upload a tiny edge-preview worker that binds the given Secrets
281
+ * Store secret, call it once, and return the decoded value. The
282
+ * Cloudflare REST API deliberately hides secret values; only worker
283
+ * bindings can resolve them, so this is the out-of-band path.
284
+ */
285
+ const readSecretViaEdge = (storeId: string, secretName: string) =>
286
+ Effect.gen(function* () {
287
+ const http = yield* HttpClient.HttpClient;
288
+ const file = new File([SECRET_PROBE_SOURCE], "worker.js", {
289
+ type: "application/javascript+module",
290
+ });
291
+ const session = yield* createEdgeSession({
292
+ scriptName: PROBE_SCRIPT_NAME,
293
+ files: [file],
294
+ bindings: [
295
+ { type: "secrets_store_secret", name: "SECRET", secretName, storeId },
296
+ ],
297
+ });
298
+ const response = yield* http.get(session.url, {
299
+ headers: session.headers,
300
+ });
301
+ if (response.status !== 200) {
302
+ const body = yield* response.text.pipe(
303
+ Effect.catch(() => Effect.succeed("")),
304
+ );
305
+ return yield* Effect.fail(
306
+ new EdgeSessionError({
307
+ message: `Secret probe returned ${response.status}: ${body.slice(0, 200)}`,
308
+ }),
309
+ );
310
+ }
311
+ return yield* response.text;
312
+ }).pipe(
313
+ Effect.mapError((cause) =>
314
+ cause instanceof EdgeSessionError
315
+ ? cause
316
+ : new EdgeSessionError({ message: "Failed to read secret", cause }),
317
+ ),
318
+ );