Skip to main content

deforge_adapter_cf/
lib.rs

1use deforge_core::ProjectConfig;
2use std::fs;
3use std::path::Path;
4use walkdir::WalkDir;
5
6pub fn generate(output_dir: &Path, config: &ProjectConfig) -> anyhow::Result<()> {
7    // Collect all handlers for router
8    let mut routes = Vec::new();
9    let src_dir = output_dir.join("src");
10
11    if src_dir.exists() {
12        for entry in WalkDir::new(&src_dir) {
13            let entry = entry?;
14            if entry.file_type().is_file() {
15                let path = entry.path();
16                if let Some(ext) = path.extension() {
17                    if ext == "ts" || ext == "js" {
18                        let relative = path.strip_prefix(&src_dir).unwrap();
19                        let route = filename_to_route(relative.to_string_lossy().as_ref());
20                        let import_path = relative
21                            .to_string_lossy()
22                            .to_string()
23                            .trim_end_matches(".ts")
24                            .trim_end_matches(".js")
25                            .to_string();
26                        routes.push((route, import_path));
27                    }
28                }
29            }
30        }
31    }
32
33    // Generate main router
34    generate_router(output_dir, &routes)?;
35
36    // Generate wrangler.toml
37    let has_kv = config
38        .services
39        .as_ref()
40        .and_then(|s| s.kv.as_ref())
41        .map(|kv| kv.enabled)
42        .unwrap_or(false);
43
44    let has_database = config
45        .services
46        .as_ref()
47        .and_then(|s| s.database.as_ref())
48        .map(|db| db.enabled)
49        .unwrap_or(false);
50
51    let wrangler_toml = format!(
52        r#"name = "{}"
53main = "index.ts"
54compatibility_date = "2024-01-01"
55
56[env.staging]
57route = "staging.{}.workers.dev"
58
59[env.production]
60route = "{}.workers.dev"
61{}{}
62"#,
63        config.name,
64        config.name,
65        config.name,
66        if has_kv {
67            r#"
68[[kv_namespaces]]
69binding = "KV"
70id = ""  # Add your KV namespace ID
71"#
72        } else {
73            ""
74        },
75        if has_database {
76            r#"
77[[d1_databases]]
78binding = "DB"
79database_name = ""  # Add your D1 database name
80database_id = ""    # Add your D1 database ID
81"#
82        } else {
83            ""
84        }
85    );
86
87    fs::write(output_dir.join("wrangler.toml"), wrangler_toml)?;
88
89    // Generate KV adapter
90    let kv_adapter = r#"/**
91 * Cloudflare KV Adapter
92 */
93
94export function createKVAdapter(namespace: any) {
95  return {
96    async get(key: string): Promise<string | null> {
97      return namespace.get(key);
98    },
99
100    async getJSON<T = any>(key: string): Promise<T | null> {
101      return namespace.get(key, 'json');
102    },
103
104    async put(key: string, value: string, options?: any): Promise<void> {
105      await namespace.put(key, value, {
106        expirationTtl: options?.expirationTtl,
107        metadata: options?.metadata
108      });
109    },
110
111    async putJSON<T = any>(key: string, value: T, options?: any): Promise<void> {
112      await namespace.put(key, JSON.stringify(value), {
113        expirationTtl: options?.expirationTtl,
114        metadata: options?.metadata
115      });
116    },
117
118    async delete(key: string): Promise<void> {
119      await namespace.delete(key);
120    },
121
122    async list(options?: any) {
123      const result = await namespace.list(options);
124      return {
125        keys: result.keys,
126        list_complete: result.list_complete,
127        cursor: result.cursor
128      };
129    },
130
131    async exists(key: string): Promise<boolean> {
132      return (await namespace.get(key)) !== null;
133    }
134  };
135}
136"#;
137
138    let adapters_dir = output_dir.join("adapters");
139    fs::create_dir_all(&adapters_dir)?;
140    fs::write(adapters_dir.join("kv-adapter.ts"), kv_adapter)?;
141
142    // Generate Context builder
143    let context_builder = r#"/**
144 * Cloudflare Context Builder
145 */
146
147import { createKVAdapter } from './kv-adapter';
148
149export function createContextBuilder(env: any, ctx: any) {
150  return function buildContext(request: Request, route: string = '/') {
151    const url = new URL(request.url);
152
153    return {
154      request,
155      env: {},
156      params: extractParams(url.pathname, route),
157      path: url.pathname,
158      method: request.method,
159      query: Object.fromEntries(url.searchParams),
160      headers: request.headers,
161      cookies: parseCookies(request),
162      services: {
163        kv: env.KV ? createKVAdapter(env.KV) : undefined,
164      },
165      log: {
166        debug: (...args: any[]) => console.debug(...args),
167        info: (...args: any[]) => console.info(...args),
168        warn: (...args: any[]) => console.warn(...args),
169        error: (...args: any[]) => console.error(...args),
170      },
171      cache: {
172        match: async (req: Request | string) => caches.default.match(req),
173        put: async (req: Request | string, res: Response) => caches.default.put(req, res),
174        delete: async (req: Request | string) => caches.default.delete(req),
175      },
176      waitUntil: (promise: Promise<any>) => ctx.waitUntil(promise),
177    };
178  };
179}
180
181function extractParams(pathname: string, route: string): Record<string, string> {
182  const params: Record<string, string> = {};
183  const routeParts = route.split('/');
184  const pathParts = pathname.split('/');
185
186  routeParts.forEach((part, i) => {
187    if (part.startsWith(':')) {
188      const paramName = part.slice(1);
189      params[paramName] = pathParts[i] || '';
190    }
191  });
192
193  return params;
194}
195
196function parseCookies(request: Request): any {
197  const cookies: Record<string, string> = {};
198  const cookieHeader = request.headers.get('Cookie');
199
200  if (cookieHeader) {
201    cookieHeader.split(';').forEach(cookie => {
202      const [name, ...rest] = cookie.split('=');
203      cookies[name.trim()] = rest.join('=').trim();
204    });
205  }
206
207  return {
208    get(name: string) { return cookies[name]; },
209    set(name: string, value: string) { cookies[name] = value; },
210    delete(name: string) { delete cookies[name]; },
211    getAll() { return { ...cookies }; }
212  };
213}
214"#;
215
216    fs::write(adapters_dir.join("context-builder.ts"), context_builder)?;
217
218    Ok(())
219}
220
221fn generate_router(output_dir: &Path, routes: &[(String, String)]) -> anyhow::Result<()> {
222    let mut imports = String::new();
223    let mut route_handlers = String::new();
224
225    for (i, (route, import_path)) in routes.iter().enumerate() {
226        imports.push_str(&format!("import handler{i} from './src/{import_path}';\n"));
227
228        route_handlers.push_str(&format!(
229            r#"  if (matchRoute(url.pathname, '{route}')) {{
230    return handler{i}.fetch(request, env, ctx);
231  }}
232"#
233        ));
234    }
235
236    let router = format!(
237        r#"/**
238 * Cloudflare Workers Router
239 * Auto-generated entry point
240 */
241
242{imports}
243
244export default {{
245  async fetch(request, env, ctx) {{
246    const url = new URL(request.url);
247
248{route_handlers}
249    // 404 Not Found
250    return new Response('Not Found', {{ status: 404 }});
251  }}
252}};
253
254function matchRoute(pathname: string, route: string): boolean {{
255  // Exact match
256  if (pathname === route) return true;
257
258  // Dynamic parameter match
259  const routeParts = route.split('/');
260  const pathParts = pathname.split('/');
261
262  if (routeParts.length !== pathParts.length) return false;
263
264  return routeParts.every((part, i) => {{
265    if (part.startsWith(':')) return true;
266    return part === pathParts[i];
267  }});
268}}
269"#
270    );
271
272    fs::write(output_dir.join("index.ts"), router)?;
273
274    Ok(())
275}
276
277fn filename_to_route(filename: &str) -> String {
278    let without_ext = filename.trim_end_matches(".ts").trim_end_matches(".js");
279
280    let route = if without_ext == "index" {
281        "/"
282    } else if without_ext.ends_with("/index") {
283        without_ext.trim_end_matches("/index")
284    } else {
285        without_ext
286    };
287
288    let route = route.replace("[", ":").replace("]", "");
289
290    if route.starts_with('/') {
291        route.to_string()
292    } else {
293        format!("/{route}")
294    }
295}