alchemy 0.4.1 → 0.5.1

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 (52) 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/apply.js +0 -8
  7. package/lib/cloudflare/assets.js +3 -1
  8. package/lib/cloudflare/bound.d.ts +2 -1
  9. package/lib/cloudflare/bucket.d.ts +16 -2
  10. package/lib/cloudflare/bucket.js +15 -6
  11. package/lib/cloudflare/custom-domain.d.ts +1 -15
  12. package/lib/cloudflare/custom-domain.js +1 -15
  13. package/lib/cloudflare/index.d.ts +0 -1
  14. package/lib/cloudflare/index.js +0 -1
  15. package/lib/cloudflare/worker.d.ts +4 -0
  16. package/lib/cloudflare/worker.js +3 -1
  17. package/lib/internal/docs/providers.js +2 -1
  18. package/lib/os/exec.d.ts +103 -0
  19. package/lib/os/exec.js +103 -0
  20. package/lib/os/index.d.ts +1 -0
  21. package/lib/os/index.js +1 -0
  22. package/lib/secret.d.ts +2 -2
  23. package/lib/secret.js +2 -2
  24. package/lib/web/vitepress/vitepress.js +1 -1
  25. package/package.json +2 -1
  26. package/src/ai/data.ts +10 -0
  27. package/src/alchemy.ts +97 -100
  28. package/src/apply.ts +0 -9
  29. package/src/cloudflare/assets.ts +3 -0
  30. package/src/cloudflare/bound.ts +4 -1
  31. package/src/cloudflare/bucket.ts +24 -9
  32. package/src/cloudflare/custom-domain.ts +1 -15
  33. package/src/cloudflare/index.ts +0 -1
  34. package/src/cloudflare/worker.ts +8 -1
  35. package/src/internal/docs/providers.ts +2 -1
  36. package/src/os/exec.ts +190 -0
  37. package/src/os/index.ts +1 -0
  38. package/src/secret.ts +2 -2
  39. package/src/web/vitepress/vitepress.ts +1 -1
  40. package/lib/cloudflare/generate-asset-manifest.d.ts +0 -2
  41. package/lib/cloudflare/generate-asset-manifest.js +0 -68
  42. package/lib/cloudflare/static-site-router.d.ts +0 -18
  43. package/lib/cloudflare/static-site-router.js +0 -115
  44. package/lib/cloudflare/static-site.d.ts +0 -211
  45. package/lib/cloudflare/static-site.js +0 -213
  46. package/lib/cloudflare/upload-asset-manifest.d.ts +0 -11
  47. package/lib/cloudflare/upload-asset-manifest.js +0 -56
  48. package/src/cloudflare/generate-asset-manifest.ts +0 -93
  49. package/src/cloudflare/static-site-router.ts +0 -157
  50. package/src/cloudflare/static-site.ts +0 -416
  51. package/src/cloudflare/upload-asset-manifest.ts +0 -85
  52. package/src/web/vitepress/index.md +0 -75
package/lib/secret.js CHANGED
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * 1. Globally when initializing the alchemy application:
7
7
  * ```ts
8
- * const app = alchemy("my-app", {
8
+ * const app = await alchemy("my-app", {
9
9
  * password: process.env.SECRET_PASSPHRASE
10
10
  * });
11
11
  * ```
@@ -54,7 +54,7 @@ export function isSecret(binding) {
54
54
  *
55
55
  * @example
56
56
  * // Global password for all secrets
57
- * const app = alchemy("my-app", {
57
+ * const app = await alchemy("my-app", {
58
58
  * password: process.env.SECRET_PASSPHRASE
59
59
  * });
60
60
  *
@@ -76,7 +76,7 @@ export const VitepressProject = Resource("project::VitepressProject", {
76
76
  // import { Folder } from "alchemy/fs";
77
77
  // import { Document } from "alchemy/docs";
78
78
  // import path from "path";
79
- // await using _ = alchemy("alchemy.run", {
79
+ // const app = await alchemy("alchemy.run", {
80
80
  // stage: "prod",
81
81
  // phase: process.argv.includes("--destroy") ? "destroy" : "up",
82
82
  // password: process.env.SECRET_PASSPHRASE,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alchemy",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "type": "module",
5
5
  "module": "./lib/index.js",
6
6
  "scripts": {
@@ -18,6 +18,7 @@
18
18
  "./esbuild": "./lib/esbuild/index.js",
19
19
  "./fs": "./lib/fs/index.js",
20
20
  "./github": "./lib/github/index.js",
21
+ "./os": "./lib/os/index.js",
21
22
  "./shadcn": "./lib/shadcn/index.js",
22
23
  "./stripe": "./lib/stripe/index.js",
23
24
  "./test/bun": "./lib/test/bun.js",
package/src/ai/data.ts CHANGED
@@ -63,6 +63,12 @@ export interface DataProps<T extends Type<any, any>> {
63
63
  * Model configuration
64
64
  */
65
65
  model?: ModelConfig;
66
+
67
+ /**
68
+ * Whether to freeze the generated object
69
+ * @default false
70
+ */
71
+ freeze?: boolean;
66
72
  }
67
73
 
68
74
  /**
@@ -171,6 +177,10 @@ export const Data = Resource("ai::Object", async function <
171
177
  throw new Error("Either prompt or messages must be provided");
172
178
  }
173
179
 
180
+ if (this.phase === "update" && props.freeze) {
181
+ return this(this.output);
182
+ }
183
+
174
184
  // Create messages array if only prompt is provided
175
185
  const messages = props.messages || [{ role: "user", content: props.prompt! }];
176
186
 
package/src/alchemy.ts CHANGED
@@ -22,7 +22,7 @@ export const alchemy: Alchemy = _alchemy as any;
22
22
  *
23
23
  * @example
24
24
  * // Create an application scope with stage and secret handling
25
- * const app = alchemy("github:alchemy", {
25
+ * const app = await alchemy("github:alchemy", {
26
26
  * stage: "prod",
27
27
  * phase: "up",
28
28
  * // Required for encrypting/decrypting secrets
@@ -57,13 +57,13 @@ export interface Alchemy {
57
57
  * Used to create and manage resources with proper secret handling.
58
58
  *
59
59
  * @example
60
- * const app = alchemy("my-app", {
60
+ * const app = await alchemy("my-app", {
61
61
  * stage: "prod",
62
62
  * // Required for encrypting/decrypting secrets
63
63
  * password: process.env.SECRET_PASSPHRASE
64
64
  * });
65
65
  */
66
- (...parameters: Parameters<typeof scope>): ReturnType<typeof scope>;
66
+ (...parameters: Parameters<typeof scope>): Promise<Scope>;
67
67
  /**
68
68
  * Template literal tag that supports file interpolation for documentation.
69
69
  * Automatically formats the content and appends file contents as code blocks.
@@ -88,11 +88,11 @@ export interface Alchemy {
88
88
  * Implementation of the alchemy function that handles both application scoping
89
89
  * and template string interpolation.
90
90
  */
91
- function _alchemy(
91
+ async function _alchemy(
92
92
  ...args:
93
93
  | [template: TemplateStringsArray, ...values: any[]]
94
94
  | [appName: string, options?: Omit<AlchemyOptions, "appName">]
95
- ): any {
95
+ ): Promise<Scope | string | never> {
96
96
  if (typeof args[0] === "string") {
97
97
  const [appName, options] = args as [string, AlchemyOptions?];
98
98
  const root = scope(undefined, {
@@ -101,9 +101,8 @@ function _alchemy(
101
101
  stage: options?.stage,
102
102
  });
103
103
  if (options?.phase === "destroy") {
104
- return destroy(root).finally(() => {
105
- process.exit(0);
106
- });
104
+ await destroy(root);
105
+ return process.exit(0);
107
106
  }
108
107
  return root;
109
108
  } else {
@@ -114,106 +113,104 @@ function _alchemy(
114
113
  : 0;
115
114
  const indent = " ".repeat(leadingSpaces);
116
115
 
117
- return (async () => {
118
- const { isFileCollection, isFileRef } = await import("./fs");
116
+ const { isFileCollection, isFileRef } = await import("./fs");
119
117
 
120
- const appendices: Record<string, string> = {};
118
+ const appendices: Record<string, string> = {};
121
119
 
122
- const stringValues = await Promise.all(
123
- values.map(async function resolve(value): Promise<string> {
124
- if (typeof value === "string") {
125
- return indent + value;
126
- } else if (value === null) {
127
- return "null";
128
- } else if (value === undefined) {
129
- return "undefined";
130
- } else if (
131
- typeof value === "number" ||
132
- typeof value === "boolean" ||
133
- typeof value === "bigint"
134
- ) {
135
- return value.toString();
136
- } else if (value instanceof Promise) {
137
- return resolve(await value);
138
- } else if (isFileRef(value)) {
139
- if (!(value.path in appendices)) {
140
- appendices[value.path] = await fs.readFile(value.path, "utf-8");
141
- }
120
+ const stringValues = await Promise.all(
121
+ values.map(async function resolve(value): Promise<string> {
122
+ if (typeof value === "string") {
123
+ return indent + value;
124
+ } else if (value === null) {
125
+ return "null";
126
+ } else if (value === undefined) {
127
+ return "undefined";
128
+ } else if (
129
+ typeof value === "number" ||
130
+ typeof value === "boolean" ||
131
+ typeof value === "bigint"
132
+ ) {
133
+ return value.toString();
134
+ } else if (value instanceof Promise) {
135
+ return resolve(await value);
136
+ } else if (isFileRef(value)) {
137
+ if (!(value.path in appendices)) {
138
+ appendices[value.path] = await fs.readFile(value.path, "utf-8");
139
+ }
140
+ return `[${path.basename(value.path)}](${value.path})`;
141
+ } else if (isFileCollection(value)) {
142
+ return Object.entries(value.files)
143
+ .map(([filePath, content]) => {
144
+ appendices[filePath] = content;
145
+ return `[${path.basename(filePath)}](${filePath})`;
146
+ })
147
+ .join("\n\n");
148
+ } else if (Array.isArray(value)) {
149
+ return (
150
+ await Promise.all(
151
+ value.map(async (value, i) => `${i}. ${await resolve(value)}`)
152
+ )
153
+ ).join("\n");
154
+ } else if (
155
+ typeof value === "object" &&
156
+ typeof value.path === "string"
157
+ ) {
158
+ if (typeof value.content === "string") {
159
+ appendices[value.path] = value.content;
142
160
  return `[${path.basename(value.path)}](${value.path})`;
143
- } else if (isFileCollection(value)) {
144
- return Object.entries(value.files)
145
- .map(([filePath, content]) => {
146
- appendices[filePath] = content;
147
- return `[${path.basename(filePath)}](${filePath})`;
148
- })
149
- .join("\n\n");
150
- } else if (Array.isArray(value)) {
151
- return (
152
- await Promise.all(
153
- value.map(async (value, i) => `${i}. ${await resolve(value)}`)
154
- )
155
- ).join("\n");
156
- } else if (
157
- typeof value === "object" &&
158
- typeof value.path === "string"
159
- ) {
160
- if (typeof value.content === "string") {
161
- appendices[value.path] = value.content;
162
- return `[${path.basename(value.path)}](${value.path})`;
163
- } else {
164
- appendices[value.path] = await fs.readFile(value.path, "utf-8");
165
- return `[${path.basename(value.path)}](${value.path})`;
166
- }
167
- } else if (typeof value === "object") {
168
- return (
169
- await Promise.all(
170
- Object.entries(value).map(async ([key, value]) => {
171
- return `* ${key}: ${await resolve(value)}`;
172
- })
173
- )
174
- ).join("\n");
175
161
  } else {
176
- // TODO: support other types
177
- console.log(value);
178
- throw new Error(`Unsupported value type: ${value}`);
162
+ appendices[value.path] = await fs.readFile(value.path, "utf-8");
163
+ return `[${path.basename(value.path)}](${value.path})`;
179
164
  }
180
- })
181
- );
182
-
183
- // Construct the string template by joining template parts with interpolated values
184
- const lines = template
185
- .map((part) =>
186
- part
187
- .split("\n")
188
- .map((line) =>
189
- line.startsWith(indent) ? line.slice(indent.length) : line
165
+ } else if (typeof value === "object") {
166
+ return (
167
+ await Promise.all(
168
+ Object.entries(value).map(async ([key, value]) => {
169
+ return `* ${key}: ${await resolve(value)}`;
170
+ })
190
171
  )
191
- .join("\n")
192
- )
193
- .flatMap((part, i) =>
194
- i < stringValues.length ? [part, stringValues[i] ?? ""] : [part]
195
- )
196
- .join("")
197
- .split("\n");
172
+ ).join("\n");
173
+ } else {
174
+ // TODO: support other types
175
+ console.log(value);
176
+ throw new Error(`Unsupported value type: ${value}`);
177
+ }
178
+ })
179
+ );
198
180
 
199
- // Collect and sort appendices by file path
200
- return [
201
- // format the user prompt and trim the first line if it's empty
202
- lines.length > 1 && lines[0].replaceAll(" ", "").length === 0
203
- ? lines.slice(1).join("\n")
204
- : lines.join("\n"),
181
+ // Construct the string template by joining template parts with interpolated values
182
+ const lines = template
183
+ .map((part) =>
184
+ part
185
+ .split("\n")
186
+ .map((line) =>
187
+ line.startsWith(indent) ? line.slice(indent.length) : line
188
+ )
189
+ .join("\n")
190
+ )
191
+ .flatMap((part, i) =>
192
+ i < stringValues.length ? [part, stringValues[i] ?? ""] : [part]
193
+ )
194
+ .join("")
195
+ .split("\n");
205
196
 
206
- // sort appendices by path and include at the end of the prompt
207
- Object.entries(appendices)
208
- .sort(([a], [b]) => a.localeCompare(b))
209
- .map(([filePath, content]) => {
210
- const extension = path.extname(filePath).slice(1);
211
- const codeTag = extension ? extension : "";
212
- return `// ${filePath}\n\`\`\`${codeTag}\n${content}\n\`\`\``;
213
- })
214
- .join("\n\n"),
215
- ].join("\n");
216
- })();
197
+ // Collect and sort appendices by file path
198
+ return [
199
+ // format the user prompt and trim the first line if it's empty
200
+ lines.length > 1 && lines[0].replaceAll(" ", "").length === 0
201
+ ? lines.slice(1).join("\n")
202
+ : lines.join("\n"),
203
+
204
+ // sort appendices by path and include at the end of the prompt
205
+ Object.entries(appendices)
206
+ .sort(([a], [b]) => a.localeCompare(b))
207
+ .map(([filePath, content]) => {
208
+ const extension = path.extname(filePath).slice(1);
209
+ const codeTag = extension ? extension : "";
210
+ return `// ${filePath}\n\`\`\`${codeTag}\n${content}\n\`\`\``;
211
+ })
212
+ .join("\n\n"),
213
+ ].join("\n");
217
214
  }
218
215
  }
219
216
  _alchemy.destroy = destroy;
package/src/apply.ts CHANGED
@@ -70,15 +70,6 @@ export async function apply<Out extends Resource>(
70
70
  }
71
71
  return state.output as Awaited<Out>;
72
72
  }
73
-
74
- const diff = await import("diff");
75
- const yaml = await import("yaml");
76
- const old = yaml.stringify(oldProps);
77
- const news = yaml.stringify(newProps);
78
- const patch = diff.createPatch(resource.ID, old, news);
79
- // console.log(patch);
80
- // if (resource.ID === "what-is-alchemy") {
81
- // }
82
73
  }
83
74
 
84
75
  const phase = state.status === "creating" ? "create" : "update";
@@ -86,6 +86,9 @@ export interface AssetFile {
86
86
  */
87
87
  export const Assets = Resource(
88
88
  "cloudflare::Asset",
89
+ {
90
+ alwaysUpdate: true,
91
+ },
89
92
  async function (
90
93
  this: Context<Assets>,
91
94
  id: string,
@@ -1,4 +1,5 @@
1
1
  import type { Secret } from "../secret";
2
+ import type { Assets } from "./assets";
2
3
  import type { Binding } from "./bindings";
3
4
  import type { R2Bucket as _R2Bucket } from "./bucket";
4
5
  import type { DurableObjectNamespace as _DurableObjectNamespace } from "./durable-object-namespace";
@@ -15,4 +16,6 @@ export type Bound<T extends Binding> = T extends _DurableObjectNamespace
15
16
  ? R2Bucket
16
17
  : T extends Secret
17
18
  ? string
18
- : never;
19
+ : T extends Assets
20
+ ? Service
21
+ : Service;
@@ -40,11 +40,18 @@ export interface BucketProps extends CloudflareApiOptions {
40
40
  allowPublicAccess?: boolean;
41
41
 
42
42
  /**
43
- * Whether to delete the bucket and its contents during resource deletion
43
+ * Whether to delete the bucket.
44
44
  * If set to false, the bucket will remain but the resource will be removed from state
45
- * Default: true
45
+ *
46
+ * @default true
46
47
  */
47
48
  delete?: boolean;
49
+
50
+ /**
51
+ * Whether to empty the bucket and delete all objects during resource deletion
52
+ * @default false
53
+ */
54
+ empty?: boolean;
48
55
  }
49
56
 
50
57
  /**
@@ -103,6 +110,14 @@ export interface R2Bucket
103
110
  * jurisdiction: "fedramp"
104
111
  * });
105
112
  *
113
+ * @example
114
+ * // Create a bucket that will be automatically emptied when deleted
115
+ * // This will delete all objects in the bucket before deleting the bucket itself
116
+ * const temporaryBucket = await R2Bucket("temp-storage", {
117
+ * name: "temp-storage",
118
+ * empty: true // All objects will be deleted when this resource is destroyed
119
+ * });
120
+ *
106
121
  * @see https://developers.cloudflare.com/r2/buckets/
107
122
  */
108
123
  export const R2Bucket = Resource(
@@ -112,18 +127,18 @@ export const R2Bucket = Resource(
112
127
  id: string,
113
128
  props: BucketProps
114
129
  ): Promise<R2Bucket> {
115
- const [api, r2Client] = await Promise.all([
116
- createCloudflareApi(props),
117
- createR2Client(props),
118
- ]);
119
-
130
+ const api = await createCloudflareApi(props);
120
131
  const bucketName = props.name || this.id;
121
132
 
122
133
  if (this.phase === "delete") {
123
134
  console.log("Deleting R2 bucket:", bucketName);
124
135
  if (props.delete !== false) {
125
- // Empty the bucket first by deleting all objects
126
- await emptyBucket(r2Client, bucketName, props.jurisdiction);
136
+ if (props.empty) {
137
+ console.log("Emptying R2 bucket:", bucketName);
138
+ const r2Client = await createR2Client(props);
139
+ // Empty the bucket first by deleting all objects
140
+ await emptyBucket(r2Client, bucketName, props.jurisdiction);
141
+ }
127
142
 
128
143
  // Delete R2 bucket
129
144
  console.log("Deleting R2 bucket:", bucketName);
@@ -64,8 +64,7 @@ export interface CustomDomain
64
64
 
65
65
  /**
66
66
  * Configure custom domain for a Cloudflare Worker using the Cloudflare Custom Domains API
67
- * This attaches a worker (either a standard Worker or the one backing a StaticSite)
68
- * to a specific hostname within a zone.
67
+ * This attaches a worker to a specific hostname within a zone.
69
68
  *
70
69
  * @example
71
70
  * // Bind a domain to a standard Cloudflare Worker
@@ -80,19 +79,6 @@ export interface CustomDomain
80
79
  * workerName: apiWorker.name // Use the name from the Worker resource
81
80
  * });
82
81
  *
83
- * @example
84
- * // Bind a domain to a Cloudflare Static Site
85
- * const mySite = await StaticSite("landing-page", {
86
- * name: "my-landing-page-site", // This becomes the underlying worker name
87
- * dir: "./dist/landing-page"
88
- * });
89
- *
90
- * const siteDomain = await CustomDomain("site-domain-binding", {
91
- * name: "www.example.com",
92
- * zoneId: "YOUR_ZONE_ID", // Replace with actual Zone ID
93
- * workerName: mySite.name // Use the name from the StaticSite resource
94
- * });
95
- *
96
82
  * @see https://developers.cloudflare.com/api/resources/workers/subresources/domains/
97
83
  */
98
84
  export const CustomDomain = Resource(
@@ -9,7 +9,6 @@ export * from "./durable-object-namespace";
9
9
  export * from "./kv-namespace";
10
10
  export * from "./permission-groups";
11
11
  export * from "./r2-rest-state-store";
12
- export * from "./static-site";
13
12
  export * from "./worker";
14
13
  export * from "./wrangler.json";
15
14
  export * from "./zone";
@@ -101,6 +101,11 @@ export interface WorkerProps<B extends Bindings = Bindings> {
101
101
  * Migrations to apply to the worker
102
102
  */
103
103
  migrations?: SingleStepMigration;
104
+
105
+ /**
106
+ * Whether to adopt the Worker if it already exists when creating
107
+ */
108
+ adopt?: boolean;
104
109
  }
105
110
 
106
111
  /**
@@ -245,7 +250,9 @@ export const Worker = Resource(
245
250
  await deleteWorker(this, api, workerName);
246
251
  return this.destroy();
247
252
  } else if (this.phase === "create") {
248
- await assertWorkerDoesNotExist(this, api, workerName);
253
+ if (!props.adopt) {
254
+ await assertWorkerDoesNotExist(this, api, workerName);
255
+ }
249
256
  }
250
257
 
251
258
  const oldBindings = await this.get<Bindings>("bindings");
@@ -124,6 +124,7 @@ async function generateProviderDocs({
124
124
  reasoningEffort: "high",
125
125
  },
126
126
  },
127
+ freeze: true,
127
128
  temperature: 0.1,
128
129
  schema: type({
129
130
  groups: type({
@@ -156,7 +157,7 @@ async function generateProviderDocs({
156
157
  A file is considered a "Utility" if it contains utility functions that are not resources or clients.
157
158
  A file is considered a "Types" if it contains just type definitions and maybe helpers around working with those types.
158
159
 
159
- The title should be simply the name of the resource's const in code (with spaces added in between each word), e.g. "Bucket" or "Function", except with spaces, e.g. "Static Site" for "const StaticSite". Maintain all other casing.
160
+ The title should be simply the name of the resource's const in code (with spaces added in between each word), e.g. "Bucket" or "Function", except with spaces, e.g. "StaticSite" for "const StaticSite". Maintain all other casing.
160
161
 
161
162
  // "Resource Name"
162
163
  const ResourceName = Resource(...)