alchemy 0.4.1 → 0.5.0

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 (47) hide show
  1. package/README.md +3 -463
  2. package/lib/ai/data.d.ts +5 -0
  3. package/lib/ai/data.js +3 -0
  4. package/lib/alchemy.d.ts +3 -3
  5. package/lib/alchemy.js +82 -85
  6. package/lib/cloudflare/assets.js +3 -1
  7. package/lib/cloudflare/bound.d.ts +2 -1
  8. package/lib/cloudflare/custom-domain.d.ts +1 -15
  9. package/lib/cloudflare/custom-domain.js +1 -15
  10. package/lib/cloudflare/index.d.ts +0 -1
  11. package/lib/cloudflare/index.js +0 -1
  12. package/lib/cloudflare/worker.d.ts +4 -0
  13. package/lib/cloudflare/worker.js +3 -1
  14. package/lib/internal/docs/providers.js +2 -1
  15. package/lib/os/exec.d.ts +103 -0
  16. package/lib/os/exec.js +103 -0
  17. package/lib/os/index.d.ts +1 -0
  18. package/lib/os/index.js +1 -0
  19. package/lib/secret.d.ts +2 -2
  20. package/lib/secret.js +2 -2
  21. package/lib/web/vitepress/vitepress.js +1 -1
  22. package/package.json +2 -1
  23. package/src/ai/data.ts +10 -0
  24. package/src/alchemy.ts +97 -100
  25. package/src/cloudflare/assets.ts +3 -0
  26. package/src/cloudflare/bound.ts +4 -1
  27. package/src/cloudflare/custom-domain.ts +1 -15
  28. package/src/cloudflare/index.ts +0 -1
  29. package/src/cloudflare/worker.ts +8 -1
  30. package/src/internal/docs/providers.ts +2 -1
  31. package/src/os/exec.ts +190 -0
  32. package/src/os/index.ts +1 -0
  33. package/src/secret.ts +2 -2
  34. package/src/web/vitepress/vitepress.ts +1 -1
  35. package/lib/cloudflare/generate-asset-manifest.d.ts +0 -2
  36. package/lib/cloudflare/generate-asset-manifest.js +0 -68
  37. package/lib/cloudflare/static-site-router.d.ts +0 -18
  38. package/lib/cloudflare/static-site-router.js +0 -115
  39. package/lib/cloudflare/static-site.d.ts +0 -211
  40. package/lib/cloudflare/static-site.js +0 -213
  41. package/lib/cloudflare/upload-asset-manifest.d.ts +0 -11
  42. package/lib/cloudflare/upload-asset-manifest.js +0 -56
  43. package/src/cloudflare/generate-asset-manifest.ts +0 -93
  44. package/src/cloudflare/static-site-router.ts +0 -157
  45. package/src/cloudflare/static-site.ts +0 -416
  46. package/src/cloudflare/upload-asset-manifest.ts +0 -85
  47. package/src/web/vitepress/index.md +0 -75
package/README.md CHANGED
@@ -10,7 +10,7 @@ Resources are simple memoized async functions that can run in any JavaScript run
10
10
  import alchemy from "alchemy";
11
11
 
12
12
  // initialize the app (with default state $USER)
13
- const app = alchemy("cloudflare-worker");
13
+ const app = await alchemy("cloudflare-worker");
14
14
 
15
15
  // create a Cloudflare Worker
16
16
  export const worker = await Worker("worker", {
@@ -18,7 +18,7 @@ export const worker = await Worker("worker", {
18
18
  entrypoint: "./src/index.ts",
19
19
  bindings: {
20
20
  COUNTER: counter,
21
- STORAGE: storage, // Bind the R2 bucket to the worker
21
+ STORAGE: storage,
22
22
  AUTH_STORE: authStore,
23
23
  GITHUB_CLIENT_ID: alchemy.secret(process.env.GITHUB_CLIENT_ID),
24
24
  GITHUB_CLIENT_SECRET: alchemy.secret(process.env.GITHUB_CLIENT_SECRET),
@@ -48,464 +48,4 @@ await app.finalize();
48
48
 
49
49
  # Getting Started
50
50
 
51
- An alchemy "app" (if you want to call it that) is just an ordinary TypeScript or JavaScript script. Once you've installed the `alchemy` package, you can start using it however you want.
52
-
53
- ```bash
54
- # I recommend bun, but you can use any JavaScript runtime.
55
- bun add alchemy
56
- ```
57
-
58
- Usually, you'll want to create an `alchemy.config.ts` script and then define your Resources.
59
-
60
- > [!TIP]
61
- > The `alchemy.config.ts` file is just a convention, not a requirement.
62
-
63
- Your script should start by creating the Alchemy `app` (aka. "Root Scope", more on [Scopes](#resource-scope-tree) later):
64
-
65
- ```ts
66
- import alchemy from "alchemy";
67
-
68
- // async disposables trigger finalization of the stack at the end of the script (after resources are declared)
69
- await using app = alchemy("my-app", {
70
- // namespace for stages
71
- stage: process.env.STAGE ?? "dev",
72
- // update or destroy the app
73
- phase: process.argv.includes("--destroy") ? "destroy" : "up"
74
- // password for encrypting/decrypting secrets stored in state
75
- password: process.env.SECRET_PASSPHRASE,
76
- // whether to log Create/Update/Delete events
77
- quiet: process.argv.includes("--verbose") ? false : true,
78
- });
79
-
80
- // (otherwise, declare resources here AFTER the bootstrap)
81
- ```
82
-
83
- Now that our app is initialized, we can start creating Resources, e.g. an AWS IAM Role:
84
-
85
- ```ts
86
- import { Role } from "alchemy/aws";
87
-
88
- export const role = await Role("my-role", {
89
- roleName: "my-role",
90
- assumeRolePolicy: {
91
- Version: "2012-10-17",
92
- Statement: [
93
- {
94
- Effect: "Allow",
95
- // Or whatever principal you want
96
- Principal: { Service: "lambda.amazonaws.com" },
97
- Action: "sts:AssumeRole",
98
- },
99
- ],
100
- },
101
- });
102
- ```
103
-
104
- Notice how the `Role` is created by an `await Role(..)` function call.
105
- In contrast to other IaC frameworks, Alchemy models Resources as memoized async functions that can be executed in any async environment - including the browser, serverless functions and durable workflows.
106
-
107
- A nice benefit of async-await is how easy it becomes to access physical properties (otherwise known as "Stack Outputs").
108
- You can just log the role name (crazy concept, right?):
109
-
110
- ```ts
111
- console.log({
112
- roleName: role.roleName, // string
113
- });
114
- ```
115
-
116
- ## Alchemy State
117
-
118
- Now, when you run your script:
119
-
120
- ```sh
121
- bun ./my-app.ts
122
- ```
123
-
124
- You'll notice some files show up in `.alchemy/`:
125
-
126
- ```sh
127
- .alchemy/
128
- my-app/
129
- prod/
130
- my-role.json
131
- ```
132
-
133
- These are called the "state files".
134
-
135
- Go ahead, click on one and take a look - here's how my `my-role.json` looks:
136
-
137
- ```jsonc
138
- {
139
- "provider": "iam::Role",
140
- "data": {},
141
- "deps": [],
142
- "status": "updated",
143
- "output": {
144
- "roleName": "alchemy-api-lambda-role"
145
- // ..
146
- },
147
- "props": {
148
- "roleName": "alchemy-api-lambda-role",
149
- "assumeRolePolicy": {
150
- "Version": "2012-10-17"
151
- // ..
152
- }
153
- }
154
- }
155
- ```
156
-
157
- Alchemy uses state to determine when to Create, Update, Delete or Skip Resources at runtime:
158
-
159
- 1. If the resource doesn't have a prior state, it will be `created`
160
- 1. If the inputs haven't changed since the last deployment, then it will be `skipped`,
161
- 1. If the inputs have changed, it will be `updated`
162
- 1. If the Resource no longer exists in the program (aka. is an orphan), then it will be `deleted`.
163
-
164
- > [!TIP]
165
- > Alchemy goes to great effort to be fully transparent. Each Resource's state is just a JSON file, nothing more. You can inspect it, modify it, commit it to your repo, store it in a database, etc.
166
-
167
- ## "Custom" Resources
168
-
169
- Adding new Resources is the whole point of Alchemy, and is therefore very simple.
170
-
171
- A Resource provider is just a function with a globally unique name, e.g. `dynamo::Table`, and an implementation of the Create, Update, Delete lifecycle operations.
172
-
173
- Below is an illustrative example of the `dynamo::Table` provider.
174
-
175
- > [!NOTE]
176
- > See [table.ts](./alchemy/src/aws/table.ts) for the full implementation.
177
-
178
- All Resources follow the same templated structure/convention:
179
-
180
- 1. an interface (or type) for the Resource's (Input) Properties
181
-
182
- ```ts
183
- // a type to represent the Resource's input properties
184
- export interface TableProps {
185
- name: string;
186
- //..
187
- }
188
- ```
189
-
190
- 2. an interface (or type) for the Resource's (Output) Attributes
191
-
192
- ```ts
193
- // declare a type to represent the Resource's properties (aka. attributes)
194
- export interface Table extends Resource<"dynamo::Table"> {
195
- tableArn: string;
196
- }
197
- ```
198
-
199
- 3. a special "Resource" function defining the Resource's globally unique name and resource lifecycle handler:
200
-
201
- ```ts
202
- export const Table = Resource(
203
- "dynamo::Table",
204
- async function (
205
- // the resource context (phase, previous state, etc.) is made available as the bound `this` param
206
- this: Context<TableOutput>,
207
- // the resource's ID (unique within the current Scope)
208
- id: string,
209
- // the resource input properties
210
- props: TableInputs
211
- ): Promise<Table> {
212
- // this function implement the CRUD resource lifecycle for an instance of this Resource
213
-
214
- if (this.phase === "create") {
215
- // (create logic)
216
- } else if (this.phase === "update") {
217
- // (update logic)
218
- } else if (this.phase === "delete") {
219
- // (delete logic)
220
-
221
- // terminate the delete process early
222
- return this.destroy();
223
- }
224
- // return the created/updated resource properties
225
- return this(props);
226
- }
227
- );
228
- ```
229
-
230
- <details>
231
- <summary>Nitty gritty details on this pattern's design and oddities</summary>
232
- I call this pattern the "pseudo class", designed to model a Resource with a CRUD lifecycle implemented with memoized async functions.
233
-
234
- The `this` parameter in this "pseudo class" serves many purposes:
235
-
236
- 1. contains the resource' `phase` (`create`, `update`, `delete`)
237
- 2. contains the resource's current state and previous props (`this.props`, `this.fqn`, `this.stage`, `this.scope`)
238
- 3. provides a handle to destroy the resource (`this.destroy`)
239
- 4. provides a factory for constructing the resource object (`this({..}`) - you can think of this as emulating `super({..})`
240
- </details>
241
-
242
- > [!TIP]
243
- > Use Cursor or an LLM like Claude/OpenAI to generate the implementation of your resource. I think you'll be pleasantly surprised at how well it works, especially if you provide the API reference docs in your context.
244
-
245
- That's it! Now you can instantiate DynamoDB Tables:
246
-
247
- ```ts
248
- const table = await Table("items", {
249
- name: "items",
250
- //..
251
- });
252
-
253
- table.tableArn; // string
254
- ```
255
-
256
- ## Secrets
257
-
258
- Recall that the `alchemy` function accepts a `password` property:
259
-
260
- ```ts
261
- await using app = alchemy("my-app", {
262
- // password for encrypting/decrypting secrets stored in state
263
- password: process.env.SECRET_PASSPHRASE,
264
- });
265
- ```
266
-
267
- This password is used to encrypt and decrypt secret data within an Alchemy state:
268
-
269
- ```ts
270
- const OPENAI_API_KEY = alchemy.secret(process.env.OPENAI_API_KEY);
271
- ```
272
-
273
- Now, I can pass this secret to a Resource safely:
274
-
275
- ```ts
276
- await Worker("my-func", {
277
- bindings: {
278
- OPENAI_API_KEY,
279
- },
280
- });
281
- ```
282
-
283
- In our `.alchemy/` state, the property will be encrypted instead of plain text:
284
-
285
- ```json
286
- {
287
- "props": {
288
- "bindings": {
289
- "OPENAI_API_KEY": {
290
- "@secret": "Tgz3e/WAscu4U1oanm5S4YXH..."
291
- }
292
- }
293
- }
294
- }
295
- ```
296
-
297
- ## Resource Scope Tree
298
-
299
- Alchemy manages resources with a named tree of `Scope`s, similar to a file system. Each Scope has a name and contains named Resources and other (named) Scopes.
300
-
301
- ### Application Scope
302
-
303
- The `alchemy` bootstrap (in your `alchemy.config.ts`) creates and binds to the Alchemy Application Scope (aka. "Root Scope"):
304
-
305
- ```ts
306
- await using app = alchemy("my-app", {
307
- stage: "prod",
308
- // ..
309
- });
310
- ```
311
-
312
- To get a better understanding, notice how it has 1:1 correspondence with the `.alchemy/` state files:
313
-
314
- ```sh
315
- .alchemy/
316
- my-app/ # app scope
317
- prod/ # stage scope
318
- my-role.json # resource instance
319
- ```
320
-
321
- ### Stage Scope
322
-
323
- When you create an app, you can also specify a `stage`.
324
-
325
- Stage is just an opinionated Scope placed under the root useful as a convention for isolating "stages" such as `prod`, `dev`, `$USER`.
326
-
327
- ```ts
328
- await using app = alchemy("my-app", {
329
- // scope: my-app/prod
330
- stage: "prod",
331
- });
332
- ```
333
-
334
- ### Instance Scope
335
-
336
- Each Resource instance has its own scope to isolate Resources created in its Lifecycle Handler:
337
-
338
- ```ts
339
- export const MyResource = Resource(
340
- "my::Resource",
341
- async function (this, id, props) {
342
- if (this.phase === "delete") {
343
- return this.destroy();
344
- }
345
- await Role("my-role");
346
- await Worker("my-worker");
347
- }
348
- );
349
- ```
350
-
351
- When you create an instance of `MyResource`, its nested Resources will be scoped to the Resource Instance:
352
-
353
- ```ts
354
- await MyResource("instance");
355
- ```
356
-
357
- ```sh
358
- .alchemy/
359
- my-app/ # app
360
- prod/ # stage
361
- instance.json # instance
362
- instance/ # instance scope
363
- my-role.json # instance
364
- my-worker.json # instance
365
- ```
366
-
367
- ### Nested Scopes
368
-
369
- Nested Scopes are stored within their parent Scope's state folder:
370
-
371
- ```sh
372
- .alchemy/
373
- my-app/ # app
374
- prod/ # stage
375
- nested/ # scope
376
- my-worker.json # instance
377
- ```
378
-
379
- > [!TIP]
380
- > Scopes can be nested arbitrarily.
381
-
382
- ### `alchemy.scope`
383
-
384
- You can create and "enter" a Nested Scope synchronously in a function. This will create and set the current async context's Scope (using AsyncLocalStorage):
385
-
386
- ```ts
387
- await using scope = alchemy.scope("nested");
388
-
389
- // resources created AFTER are placed in the "nested' Scope
390
- await Worker("my-worker");
391
- ```
392
-
393
- ### `alchemy.run`
394
-
395
- You can also create nested scopes using the `alchemy.run` function and a closure:
396
-
397
- ```ts
398
- await alchemy.run("nested", async () => {
399
- // resources created in here are isolated to the "nested' Scope
400
- await Worker("my-worker");
401
- });
402
-
403
- // resources out here are placed in the "parent" SCope
404
- await Worker("my-worker");
405
- ```
406
-
407
- ### Get the current Scope
408
-
409
- The current Scope is stored in `AsyncLocalStorage` and accessible when needed:
410
-
411
- ```ts
412
- Scope.current; // will throw if not in a scope
413
- Scope.get(); // Scope | undefined
414
- await alchemy.run("nested", async (scope) => {
415
- // scope is passed in as an argument
416
- });
417
- // create a Scope and bind to the current async context
418
- using scope = alchemy.scope("nested");
419
- ```
420
-
421
- ## `destroy`
422
-
423
- `Scope`, `Resource` and `ResourcePromise` can be "destroyed" individually and programmatically.
424
-
425
- ### Destroy a Resource
426
-
427
- Say, you've got some two resources, a `Role` and a `Function`.
428
-
429
- ```ts
430
- const role = await Role("my-role", {
431
- name: "my-role",
432
- //..
433
- });
434
-
435
- const func = await Function("my-function", {
436
- name: "my-function",
437
- role: role.roleArn,
438
- //..
439
- });
440
- ```
441
-
442
- Each of these Resources is known as a "sub-graph".
443
-
444
- In this case we have `Role` (a 1-node graph, `Role`), and `Function` (a 2-node graph, `Role → Function`).
445
-
446
- Each sub-graph can be "applied" or "destroyed" individually using the `apply` and `destroy` functions:
447
-
448
- ```ts
449
- import { destroy } from "alchemy";
450
-
451
- await destroy(func); // will delete just the Function
452
-
453
- // destroy deletes the resource and any downstream dependencies
454
- // so, if you want to delete Role AND Function, you should call destroy(role)
455
- await destroy(role); // will delete Role and then Function
456
- ```
457
-
458
- ### Destroy a Scope
459
-
460
- You can destroy all Resources in a Scope with a single `destroy` call:
461
-
462
- ```ts
463
- const scope = alchemy.scope("scope");
464
- try {
465
- await Role("role");
466
- await Worker("worker");
467
- } finally {
468
- // destroy them all!
469
- await destroy(scope);
470
- }
471
- ```
472
-
473
- ### Destroy the App
474
-
475
- To destroy the whole app (aka. the whole graph), you can call `alchemy` with the `phase: "destroy"` option. This will delete all resources in the specified or default stage.
476
-
477
- ```ts
478
- await using _ = alchemy({
479
- phase: "destroy",
480
- // ..
481
- });
482
- ```
483
-
484
- > [!TIP]
485
- > Alchemy is designed to have the minimum number of opinions as possible. This "embeddable" design is so that you can implement your own tools around Alchemy, e.g. a CLI or UI, instead of being stuck with a specific tool.
486
- >
487
- > ```ts
488
- > await using _ = alchemy({
489
- > // decide the mode/stage however you want, e.g. a CLI parser
490
- > phase: process.argv[2] === "destroy" ? "destroy" : "up",
491
- > stage: process.argv[3],
492
- > });
493
- > ```
494
-
495
- ## Test Resources
496
-
497
- > [!NOTE]
498
- > TODO
499
-
500
- ## Physical Names
501
-
502
- > [!CAUTION]
503
- > It is up to you to ensure that the physical names of resources don't conflict - alchemy does not (yet) offer any help or opinions here. You must decide on physical names, but you're free to add name generation logic to your resources if you so desire.
504
- >
505
- > ```ts
506
- > const Table = Resource("dynamo::Table", async function (this, inputs) {
507
- > const tableName = `${this.stage}-${inputs.tableName}`;
508
- >
509
- > // ..
510
- > });
511
- > ```
51
+ See the [Getting Started Guide](https://alchemy.run/docs/getting-started.html).
package/lib/ai/data.d.ts CHANGED
@@ -54,6 +54,11 @@ export interface DataProps<T extends Type<any, any>> {
54
54
  * Model configuration
55
55
  */
56
56
  model?: ModelConfig;
57
+ /**
58
+ * Whether to freeze the generated object
59
+ * @default false
60
+ */
61
+ freeze?: boolean;
57
62
  }
58
63
  /**
59
64
  * A resource that uses AI to generate structured content based on a schema
package/lib/ai/data.js CHANGED
@@ -80,6 +80,9 @@ export const Data = Resource("ai::Object", async function (id, props) {
80
80
  if (!props.prompt && !props.messages) {
81
81
  throw new Error("Either prompt or messages must be provided");
82
82
  }
83
+ if (this.phase === "update" && props.freeze) {
84
+ return this(this.output);
85
+ }
83
86
  // Create messages array if only prompt is provided
84
87
  const messages = props.messages || [{ role: "user", content: props.prompt }];
85
88
  // Generate structured output using generateObject
package/lib/alchemy.d.ts CHANGED
@@ -13,7 +13,7 @@ export declare const alchemy: Alchemy;
13
13
  *
14
14
  * @example
15
15
  * // Create an application scope with stage and secret handling
16
- * const app = alchemy("github:alchemy", {
16
+ * const app = await alchemy("github:alchemy", {
17
17
  * stage: "prod",
18
18
  * phase: "up",
19
19
  * // Required for encrypting/decrypting secrets
@@ -46,13 +46,13 @@ export interface Alchemy {
46
46
  * Used to create and manage resources with proper secret handling.
47
47
  *
48
48
  * @example
49
- * const app = alchemy("my-app", {
49
+ * const app = await alchemy("my-app", {
50
50
  * stage: "prod",
51
51
  * // Required for encrypting/decrypting secrets
52
52
  * password: process.env.SECRET_PASSPHRASE
53
53
  * });
54
54
  */
55
- (...parameters: Parameters<typeof scope>): ReturnType<typeof scope>;
55
+ (...parameters: Parameters<typeof scope>): Promise<Scope>;
56
56
  /**
57
57
  * Template literal tag that supports file interpolation for documentation.
58
58
  * Automatically formats the content and appends file contents as code blocks.