appflare 0.2.38 → 0.2.40
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/cli/generate.ts +47 -0
- package/cli/templates/auth/config.ts +2 -2
- package/cli/templates/handlers/generators/handlers.ts +3 -2
- package/cli/templates/handlers/generators/types/context.ts +30 -7
- package/cli/templates/handlers/index.ts +4 -1
- package/cli/templates/handlers/types.ts +4 -2
- package/dist/cli/index.js +83 -74
- package/dist/cli/index.mjs +83 -74
- package/package.json +1 -1
package/dist/cli/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import {Command}from'commander';import
|
|
2
|
+
import {Command}from'commander';import Fa from'chokidar';import {existsSync}from'fs';import {resolve,isAbsolute,dirname,join,relative,extname}from'path';import {mkdir,readdir,rm}from'fs/promises';import {pathToFileURL,fileURLToPath}from'url';import*as f from'typescript';import {z}from'zod';function be(e){return `import { betterAuth } from "better-auth";
|
|
3
3
|
import { withCloudflare } from "better-auth-cloudflare";
|
|
4
4
|
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
5
5
|
import { drizzle } from "drizzle-orm/d1";
|
|
@@ -41,11 +41,11 @@ export const createAuth = (
|
|
|
41
41
|
: undefined,
|
|
42
42
|
kv: env?.KV,
|
|
43
43
|
},
|
|
44
|
-
config.auth.options
|
|
44
|
+
config.auth.options,
|
|
45
45
|
);
|
|
46
46
|
|
|
47
47
|
return betterAuth({
|
|
48
|
-
...
|
|
48
|
+
...cloudflareOptions,
|
|
49
49
|
...(env
|
|
50
50
|
? {}
|
|
51
51
|
: {
|
|
@@ -166,8 +166,8 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
166
166
|
): Appflare<Options> {
|
|
167
167
|
return new Appflare(options);
|
|
168
168
|
}
|
|
169
|
-
`}function
|
|
170
|
-
`)}function
|
|
169
|
+
`}function tr(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function xe(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function nr(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function Te(e){let t={children:new Map};for(let n of e){let r=t;for(let a of n.segments){let o=r.children.get(a);o||(o={children:new Map},r.children.set(a,o)),r=o;}r.operation=n;}return t}function J(e,t=1){let n=" ".repeat(t),r=" ".repeat(t+1),a=Array.from(e.children.entries()).sort(([i],[s])=>i.localeCompare(s));if(a.length===0)return e.operation?`${e.operation.alias}Route(runtime)`:"{}";let o=["{"];for(let[i,s]of a)o.push(`${r}${nr(i)}: ${J(s,t+1)},`);return e.operation&&(o.push(`${r}run: ${e.operation.alias}Route(runtime).run,`),o.push(`${r}schema: ${e.operation.alias}Route(runtime).schema,`),e.operation.kind==="query"&&o.push(`${r}subscribe: ${e.operation.alias}Route(runtime).subscribe,`)),o.push(`${n}}`),o.join(`
|
|
170
|
+
`)}function rr(e,t){if(e.kind!=="query"&&e.kind!=="mutation")return null;let n=e.clientSegments&&e.clientSegments.length>0?e.clientSegments:e.routePath.replace(/^\//,"").split("/").filter(Boolean).slice(1);if(n.length>=2&&n[n.length-1]===n[n.length-2]&&n.pop(),n.length===0)return null;let r=tr(`op_${t}_${e.kind}_${n.join("_")}`);return {kind:e.kind,routePath:e.routePath,queryName:e.handlerName??n.join("/"),segments:n,importPath:e.clientImportPath,exportName:e.exportName,alias:r,schemaConst:`${r}Schema`,typeBase:`${xe(e.kind)}${xe(n.join("_"))}`}}function ar(e){let t=`${e.typeBase}Input`,n=`${e.typeBase}Output`,r=`${e.typeBase}Schema`,a=e.kind==="query"?"GET":"POST";return e.kind==="query"?`const ${e.alias}Route = (
|
|
171
171
|
runtime: RequestRuntime,
|
|
172
172
|
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}> => {
|
|
173
173
|
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}>["run"] = async (
|
|
@@ -353,13 +353,13 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
353
353
|
schema: ${r},
|
|
354
354
|
run,
|
|
355
355
|
};
|
|
356
|
-
};`}function G(e){let t=e.map((l,u)=>
|
|
356
|
+
};`}function G(e){let t=e.map((l,u)=>rr(l,u)).filter(l=>l!==null),n=t.filter(l=>l.kind==="query"),r=t.filter(l=>l.kind==="mutation"),a=t.map(l=>`import { ${l.exportName} as ${l.alias} } from "${l.importPath}";`).join(`
|
|
357
357
|
`),o=t.map(l=>{let u=`${l.typeBase}Input`,p=`${l.typeBase}Output`,d=`${l.typeBase}Schema`;return `const ${l.schemaConst} = z.object(${l.alias}.definition.args);
|
|
358
358
|
export type ${u} = z.input<typeof ${l.schemaConst}>;
|
|
359
359
|
export type ${p} = Awaited<ReturnType<typeof ${l.alias}.definition.handler>>;
|
|
360
360
|
export const ${d} = ${l.schemaConst};`}).join(`
|
|
361
361
|
|
|
362
|
-
`),i=t.map(l=>
|
|
362
|
+
`),i=t.map(l=>ar(l)).join(`
|
|
363
363
|
|
|
364
364
|
`),s=J(Te(n)),c=J(Te(r));return `import { z } from "zod";
|
|
365
365
|
import type {
|
|
@@ -1228,7 +1228,7 @@ function createContextErrorHelpers() {
|
|
|
1228
1228
|
},
|
|
1229
1229
|
};
|
|
1230
1230
|
}
|
|
1231
|
-
`}function
|
|
1231
|
+
`}function Fe(){return `
|
|
1232
1232
|
function normalizeStoragePath(path: string): string {
|
|
1233
1233
|
const trimmed = path.trim();
|
|
1234
1234
|
if (trimmed.length === 0) {
|
|
@@ -1284,7 +1284,7 @@ function buildSignedRequest(
|
|
|
1284
1284
|
headers,
|
|
1285
1285
|
});
|
|
1286
1286
|
}
|
|
1287
|
-
`}function
|
|
1287
|
+
`}function Me(){return `
|
|
1288
1288
|
function createStorageApi(
|
|
1289
1289
|
ctx: AppflareContext,
|
|
1290
1290
|
bucket: R2BucketBinding | undefined,
|
|
@@ -1488,10 +1488,10 @@ ${Ce()}
|
|
|
1488
1488
|
|
|
1489
1489
|
${qe()}
|
|
1490
1490
|
|
|
1491
|
-
${Me()}
|
|
1492
|
-
|
|
1493
1491
|
${Fe()}
|
|
1494
1492
|
|
|
1493
|
+
${Me()}
|
|
1494
|
+
|
|
1495
1495
|
${Ie(e)}
|
|
1496
1496
|
`}function Ee(){return `
|
|
1497
1497
|
export async function executeOperation<
|
|
@@ -4774,10 +4774,17 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4774
4774
|
},
|
|
4775
4775
|
`}function Ke(){return [Qe(),Ue(),_e(),Le(),ze()].join(`
|
|
4776
4776
|
|
|
4777
|
-
`)}function Je(e=[]){
|
|
4777
|
+
`)}function Je(e=[],t=[]){let n=t.map(i=>` ${i.name}?: ${i.tsType} | null;`).join(`
|
|
4778
|
+
`),a=[e.length>0?[" role: UserRole;"," banned: boolean | null;"," banReason?: string | null | undefined;"," banExpires?: Date | null | undefined;"].join(`
|
|
4779
|
+
`):"",n].filter(Boolean).join(`
|
|
4780
|
+
`);return `type AuthSession = typeof auth.$Infer.Session;
|
|
4778
4781
|
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
4779
|
-
${e.length>0?`type UserRole = ${e.map(
|
|
4780
|
-
type User =
|
|
4782
|
+
${e.length>0?`export type UserRole = ${e.map(i=>`"${i}"`).join(" | ")};
|
|
4783
|
+
type User = import("better-auth").User & {
|
|
4784
|
+
${a}
|
|
4785
|
+
};`:t.length>0?`type User = import("better-auth").User & {
|
|
4786
|
+
${a}
|
|
4787
|
+
};`:'type User = import("better-auth").User;'}
|
|
4781
4788
|
type Session = AuthSession['session']
|
|
4782
4789
|
|
|
4783
4790
|
export type StoragePutArgs = {
|
|
@@ -4996,20 +5003,20 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
4996
5003
|
definition,
|
|
4997
5004
|
};
|
|
4998
5005
|
}
|
|
4999
|
-
`}function Ze(e=[]){return [je(),He(),Ke(),Je(e),Ge()].join(`
|
|
5006
|
+
`}function Ze(e=[],t=[]){return [je(),He(),Ke(),Je(e,t),Ge()].join(`
|
|
5000
5007
|
|
|
5001
|
-
`)}function Xe(e,t=[]){return `import type { Context } from "hono";
|
|
5008
|
+
`)}function Xe(e,t=[],n=[]){return `import type { Context } from "hono";
|
|
5002
5009
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5003
5010
|
import { drizzle } from "drizzle-orm/d1";
|
|
5004
5011
|
import { z, type ZodRawShape } from "zod";
|
|
5005
5012
|
import * as authSchema from "./auth.schema";
|
|
5006
5013
|
import * as schema from "${e}";
|
|
5007
5014
|
|
|
5008
|
-
${Ze(t)}
|
|
5009
|
-
`}function
|
|
5010
|
-
`)}function
|
|
5011
|
-
`)}function
|
|
5012
|
-
`)}function
|
|
5015
|
+
${Ze(t,n)}
|
|
5016
|
+
`}function or(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function ir(e,t){let n=e.routePath.replace(/^\//,"").replace(/\//g,"_");return or(`op_${t}_${n}`)}function sr(e){return e.map((t,n)=>({operation:t,index:n,alias:ir(t,n)}))}function lr(e){return e.map(({operation:t,alias:n})=>`import { ${t.exportName} as ${n} } from "${t.importPath}";`).join(`
|
|
5017
|
+
`)}function ur(e){return e.filter(({operation:t})=>t.kind==="query"||t.kind==="mutation").map(({alias:t})=>`const ${`${t}Schema`} = z.object(${t}.definition.args);`).join(`
|
|
5018
|
+
`)}function cr(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({alias:t})=>`const ${`${t}SchedulerSchema`} = ${t}.definition.args ? z.object(${t}.definition.args) : z.undefined();`).join(`
|
|
5019
|
+
`)}function dr(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
5013
5020
|
app.get(
|
|
5014
5021
|
"${t.routePath}",
|
|
5015
5022
|
sValidator("query", ${r}),
|
|
@@ -5022,7 +5029,7 @@ ${Ze(t)}
|
|
|
5022
5029
|
}
|
|
5023
5030
|
},
|
|
5024
5031
|
);`}).join(`
|
|
5025
|
-
`)}function
|
|
5032
|
+
`)}function pr(e){return e.filter(({operation:t})=>t.kind==="mutation").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
5026
5033
|
app.post(
|
|
5027
5034
|
"${t.routePath}",
|
|
5028
5035
|
sValidator("json", ${r}),
|
|
@@ -5037,26 +5044,26 @@ ${Ze(t)}
|
|
|
5037
5044
|
}
|
|
5038
5045
|
},
|
|
5039
5046
|
);`}).join(`
|
|
5040
|
-
`)}function
|
|
5047
|
+
`)}function mr(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`,a=t.handlerName??t.routePath;return `
|
|
5041
5048
|
${JSON.stringify(a)}: {
|
|
5042
5049
|
definition: ${n}.definition,
|
|
5043
5050
|
schema: ${r},
|
|
5044
5051
|
},`}).join(`
|
|
5045
|
-
`)}function
|
|
5052
|
+
`)}function gr(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=`${n}SchedulerSchema`,a=t.taskName??`${t.routePath}`;return `
|
|
5046
5053
|
${JSON.stringify(a)}: {
|
|
5047
5054
|
definition: ${n}.definition,
|
|
5048
5055
|
schema: ${r},
|
|
5049
5056
|
},`}).join(`
|
|
5050
|
-
`)}function
|
|
5051
|
-
`)}function
|
|
5057
|
+
`)}function fr(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`;return ` ${JSON.stringify(r)}: Parameters<typeof ${n}.definition.handler>[1];`}).join(`
|
|
5058
|
+
`)}function hr(e){return e.filter(({operation:t})=>t.kind==="cron").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`,a=t.cronTriggers??[];return `
|
|
5052
5059
|
{
|
|
5053
5060
|
taskName: ${JSON.stringify(r)},
|
|
5054
5061
|
cronTriggers: ${JSON.stringify(a)},
|
|
5055
5062
|
definition: ${n}.definition,
|
|
5056
5063
|
},`}).join(`
|
|
5057
|
-
`)}function
|
|
5064
|
+
`)}function yr(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
5058
5065
|
${t}.definition.handler,`).join(`
|
|
5059
|
-
`)}function Ye(e){let t=
|
|
5066
|
+
`)}function Ye(e){let t=sr(e);return {imports:lr(t),operationSchemas:ur(t),schedulerSchemas:cr(t),queryRoutes:dr(t),mutationRoutes:pr(t),queryRegistryEntries:mr(t),schedulerEntries:gr(t),schedulerPayloadMapEntries:fr(t),cronEntries:hr(t),storageHandlersEntries:yr(t)}}var et=`
|
|
5060
5067
|
function getRealtimeStub(
|
|
5061
5068
|
env: Record<string, unknown>,
|
|
5062
5069
|
options: RegisterHandlersOptions,
|
|
@@ -6430,9 +6437,9 @@ export function registerGeneratedHandlers(
|
|
|
6430
6437
|
${st}
|
|
6431
6438
|
|
|
6432
6439
|
${ut}
|
|
6433
|
-
`}function Z(e,t,n,r=[]){let
|
|
6440
|
+
`}function Z(e,t,n,r=[],a=[]){let o=Xe(e,r,a),i=Pe(n),s=Oe(),c=ct(t);return [{relativePath:"handlers.ts",source:o},{relativePath:"handlers.context.ts",source:i},{relativePath:"handlers.execution.ts",source:s},{relativePath:"handlers.routes.ts",source:c}]}function br(e){return e?`,
|
|
6434
6441
|
KV: c.env["${e}"] as KVNamespace`:""}function dt(e,t){return `{
|
|
6435
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6442
|
+
DATABASE: c.env["${e}"] as D1Database${br(t)}
|
|
6436
6443
|
}`}function pt(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6437
6444
|
const auth = createAuth(
|
|
6438
6445
|
${dt(t,n)},
|
|
@@ -6440,7 +6447,7 @@ ${ut}
|
|
|
6440
6447
|
);
|
|
6441
6448
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6442
6449
|
});
|
|
6443
|
-
`}function
|
|
6450
|
+
`}function wr(){return `export const getHeaders = (headers: Headers) => {
|
|
6444
6451
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6445
6452
|
const headerObject: Record<string, any> = {};
|
|
6446
6453
|
let hasCookie = false;
|
|
@@ -6470,14 +6477,14 @@ ${ut}
|
|
|
6470
6477
|
|
|
6471
6478
|
return headerObject as any as Headers;
|
|
6472
6479
|
};
|
|
6473
|
-
`}function
|
|
6480
|
+
`}function xr(){return `export const getSanitizedRequest = (req: Request) => {
|
|
6474
6481
|
const newRequest = new Request(req, {
|
|
6475
6482
|
headers: getHeaders(req.headers),
|
|
6476
6483
|
});
|
|
6477
6484
|
return newRequest;
|
|
6478
6485
|
};
|
|
6479
|
-
`}function mt(){return
|
|
6480
|
-
`+
|
|
6486
|
+
`}function mt(){return wr()+`
|
|
6487
|
+
`+xr()}function gt(e,t,n){return pt(e,t,n)+`
|
|
6481
6488
|
`+mt()}function ft(){return `const app = new Hono<WorkerEnv>();
|
|
6482
6489
|
|
|
6483
6490
|
app.use('*', cors({
|
|
@@ -6528,7 +6535,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6528
6535
|
`}function wt(){return `type WorkerEnv = {
|
|
6529
6536
|
Bindings: Record<string, unknown>;
|
|
6530
6537
|
};
|
|
6531
|
-
`}function xt(e,t,n,r,a,o,i,s,c,l){return bt()+wt()+ft()+yt(t,n,r,a,o,i,s,c,l)+gt(e,t,n)+ht()}function Tt(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function X(e,t){let n={...e};for(let[r,a]of Object.entries(t)){let o=n[r];if(Tt(o)&&Tt(a)){n[r]=X(o,a);continue}n[r]=a;}return n}function
|
|
6538
|
+
`}function xt(e,t,n,r,a,o,i,s,c,l){return bt()+wt()+ft()+yt(t,n,r,a,o,i,s,c,l)+gt(e,t,n)+ht()}function Tt(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function X(e,t){let n={...e};for(let[r,a]of Object.entries(t)){let o=n[r];if(Tt(o)&&Tt(a)){n[r]=X(o,a);continue}n[r]=a;}return n}function Tr(e){return Array.from(new Set(e.filter(t=>t.length>0)))}function vt(e,t){let n=t.filter(d=>d.kind==="scheduler"||d.kind==="cron"),r=Tr(t.filter(d=>d.kind==="cron").flatMap(d=>d.cronTriggers??[])),a=e.config.scheduler.enabled&&n.length>0,o=e.config.realtime.enabled,s=(typeof e.config.wranglerOverrides?.name=="string"?e.config.wranglerOverrides.name:void 0)??"appflare-worker",c=e.config.scheduler.queue??`${s}-scheduler`,l={name:s,main:"./src/index.ts",d1_databases:e.config.database.map(d=>({binding:d.binding,database_name:d.databaseName,database_id:d.databaseId,preview_database_id:d.previewDatabaseId??d.databaseId,...d.migrationsDir?{migrations_dir:d.migrationsDir}:{}})),kv_namespaces:e.config.kv.map(d=>({binding:d.binding,id:d.id,...d.previewId?{preview_id:d.previewId}:{}})),r2_buckets:e.config.r2.map(d=>({binding:d.binding,bucket_name:d.bucketName,...d.previewBucketName?{preview_bucket_name:d.previewBucketName}:{},...d.jurisdiction?{jurisdiction:d.jurisdiction}:{}})),...a?{queues:{producers:[{binding:e.config.scheduler.binding,queue:c}],consumers:[{queue:c}]}}:{},...r.length>0?{triggers:{crons:r}}:{},...o?{durable_objects:{bindings:[{name:e.config.realtime.binding,class_name:e.config.realtime.className}]},migrations:[{tag:"appflare-realtime-v1",new_sqlite_classes:[e.config.realtime.className]}]}:{}};if(!e.config.wranglerOverrides)return l;let{scheduler:u,...p}=e.config.wranglerOverrides;return X(l,p)}function Rt(e){return e.tables.map(t=>({exportName:t.exportName,tableName:t.tableName,columns:t.columns.map(n=>n.name)}))}function kt(e){return `<li data-name="users">
|
|
6532
6539
|
<a href="/admin/users" hx-get="/admin/users" hx-target="#main-content" hx-push-url="true" hx-swap="outerHTML" class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full">
|
|
6533
6540
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6534
6541
|
<span class="truncate">users</span>
|
|
@@ -6593,7 +6600,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6593
6600
|
</a>
|
|
6594
6601
|
`.replace(/\n/g,"\\n")).join("")}function Nt(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
6595
6602
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6596
|
-
`).join("")}function
|
|
6603
|
+
`).join("")}function vr(e){switch(e){case "number":return "mdi:pound";case "boolean":return "mdi:toggle-switch-outline";case "date":return "mdi:calendar";default:return "mdi:format-text"}}function $t(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n),a=r?vr(r.type):"mdi:format-text";return `
|
|
6597
6604
|
<th>
|
|
6598
6605
|
<a href="#"
|
|
6599
6606
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -6688,7 +6695,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6688
6695
|
payload.${n} = raw_${n};
|
|
6689
6696
|
}
|
|
6690
6697
|
`}).join(`
|
|
6691
|
-
`)}function qt(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function
|
|
6698
|
+
`)}function qt(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function Ft(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function Mt(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function It(e,t,n,r){return t?`<td class="text-right">
|
|
6692
6699
|
<div class="drawer drawer-end">
|
|
6693
6700
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6694
6701
|
<div class="drawer-content">
|
|
@@ -7159,7 +7166,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
7159
7166
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7160
7167
|
});
|
|
7161
7168
|
${u}
|
|
7162
|
-
`}function te(e){let t=qt(e),n=!!t,r=e.columns.map(w=>w.name),a=r.filter(w=>
|
|
7169
|
+
`}function te(e){let t=qt(e),n=!!t,r=e.columns.map(w=>w.name),a=r.filter(w=>Ft(e,w)),o=r.filter(w=>Mt(e,w)),i=Nt(e),s=$t(e,r),c=Ct(r,t),l=a.map(w=>Y(e,w,"create")).join(""),u=o.map(w=>Y(e,w,"edit")).join(""),p=ee(e,a),d=ee(e,o),y=n?t:r[0]||"id",v=e.columns.find(w=>w.name===t)?.type,A=It(e,n,t,u);return Pt(e,y,t,n,r,i,s,c,A,l)+`
|
|
7163
7170
|
`+Et(e.exportName,y,t,v,n,i,p,d)}function Ot(){return `
|
|
7164
7171
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7165
7172
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
@@ -7209,7 +7216,7 @@ ${u}
|
|
|
7209
7216
|
</div>
|
|
7210
7217
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
7211
7218
|
</div>
|
|
7212
|
-
\`}`}var
|
|
7219
|
+
\`}`}var Rr=["id","name","email","role","createdAt","banned"],kr={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function Sr(e){let t=kr[e]||"mdi:format-text";return `<th><a href="#" hx-get="/admin/users?page=\${page}&search=\${search}&sort=${e}&order=\${sort === '${e}' && order === 'asc' ? 'desc' : 'asc'}" hx-target="#main-content" hx-push-url="true" class="hover:text-primary flex items-center gap-1.5 transition-colors whitespace-nowrap"><iconify-icon icon="${t}" width="14" height="14" class="opacity-40"></iconify-icon>${e} <span class="text-[10px] opacity-30">\${sort === '${e}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span></a></th>`}function Vt(){let e=Rr.map(Sr).join(`
|
|
7213
7220
|
`),t=B("/admin/users");return `
|
|
7214
7221
|
const tableHtml = html\`
|
|
7215
7222
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
@@ -7542,9 +7549,9 @@ ${ne()}`}function zt(e){return `
|
|
|
7542
7549
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
7543
7550
|
</div>
|
|
7544
7551
|
</div>
|
|
7545
|
-
`}function
|
|
7552
|
+
`}function Ar(e){return e==="boolean"?"checkbox":e==="number"?"number":"text"}function Nr(e){let t=e.args??[];return t.length===0?`
|
|
7546
7553
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
7547
|
-
`:t.map(n=>{let r=
|
|
7554
|
+
`:t.map(n=>{let r=Ar(n.type),a=r==="checkbox",o=`${n.name}${n.optional?"":" *"}`,i=n.type!=="unknown"?`<span class="badge badge-xs badge-ghost font-mono opacity-40 ml-1">${n.type}</span>`:"";return a?`
|
|
7548
7555
|
<div class="flex items-center gap-3 py-1">
|
|
7549
7556
|
<input
|
|
7550
7557
|
type="checkbox"
|
|
@@ -7573,7 +7580,7 @@ ${ne()}`}function zt(e){return `
|
|
|
7573
7580
|
/>
|
|
7574
7581
|
</div>
|
|
7575
7582
|
`}).join(`
|
|
7576
|
-
`)}function
|
|
7583
|
+
`)}function $r(e){return `
|
|
7577
7584
|
<div class="space-y-4">
|
|
7578
7585
|
<div class="flex items-center justify-between">
|
|
7579
7586
|
<div class="flex flex-col">
|
|
@@ -7586,11 +7593,11 @@ ${ne()}`}function zt(e){return `
|
|
|
7586
7593
|
</label>
|
|
7587
7594
|
</div>
|
|
7588
7595
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
7589
|
-
${
|
|
7596
|
+
${Nr(e)}
|
|
7590
7597
|
</div>
|
|
7591
7598
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7592
7599
|
</div>
|
|
7593
|
-
`}function
|
|
7600
|
+
`}function Cr(){return `
|
|
7594
7601
|
<div class="space-y-4">
|
|
7595
7602
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7596
7603
|
<div class="relative group">
|
|
@@ -7607,7 +7614,7 @@ ${ne()}`}function zt(e){return `
|
|
|
7607
7614
|
</div>
|
|
7608
7615
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
7609
7616
|
</div>
|
|
7610
|
-
`}function
|
|
7617
|
+
`}function qr(){return `
|
|
7611
7618
|
<div class="space-y-4">
|
|
7612
7619
|
<div class="flex items-center justify-between">
|
|
7613
7620
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -7642,13 +7649,13 @@ ${ne()}`}function zt(e){return `
|
|
|
7642
7649
|
<!-- Tab Content -->
|
|
7643
7650
|
<div class="flex-1 overflow-y-auto">
|
|
7644
7651
|
<div id="request-tab-args" class="p-5">
|
|
7645
|
-
${
|
|
7652
|
+
${$r(e)}
|
|
7646
7653
|
</div>
|
|
7647
7654
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
7648
|
-
${
|
|
7655
|
+
${Cr()}
|
|
7649
7656
|
</div>
|
|
7650
7657
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
7651
|
-
${
|
|
7658
|
+
${qr()}
|
|
7652
7659
|
</div>
|
|
7653
7660
|
</div>
|
|
7654
7661
|
|
|
@@ -9131,8 +9138,8 @@ ${p}
|
|
|
9131
9138
|
app.route('/admin', adminApp);
|
|
9132
9139
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
9133
9140
|
}
|
|
9134
|
-
`}function re(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"&&(typeof t.enums=="object"||t.enums===void 0)}function
|
|
9135
|
-
`}function
|
|
9141
|
+
`}function re(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"&&(typeof t.enums=="object"||t.enums===void 0)}function O(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function F(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(t,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(t,n)=>n.toUpperCase())}function ie(e){return e.endsWith("ies")?`${e.slice(0,-3)}y`:e.endsWith("ses")?e.slice(0,-2):e.endsWith("s")&&e.length>1?e.slice(0,-1):e}function g(e){return JSON.stringify(e)}function Mr(e){if(typeof e=="string")return g(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return "null";if(e instanceof Date)return g(e.toISOString());throw new Error(`Unsupported SQL default value '${String(e)}'. Use string, number, boolean, null, or Date.`)}function Ir(e){return {kind:"schema",tables:Object.fromEntries(Object.entries(e.tables).map(([t,n])=>[t,{kind:"table",sqlName:n.sqlName,columns:Object.fromEntries(Object.entries(n.columns).map(([r,a])=>[r,{...a}])),relations:Object.fromEntries(Object.entries(n.relations).map(([r,a])=>[r,{...a}]))}])),enums:Object.fromEntries(Object.entries(e.enums??{}).map(([t,n])=>[t,{...n}]))}}function H(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function dn(e,t,n,r,a,o,i){let s=t.columns[n];if(s){if(s.references&&(s.references.table!==r||s.references.column!==a))throw new Error(`Inferred relation '${e}.${n}' conflicts with explicit references(${s.references.table}.${s.references.column}).`);t.columns[n]={...s,notNull:s.notNull??(s.nullable===true?false:o.notNull),nullable:s.nullable??(o.notNull===false?true:void 0),references:{table:r,column:a,onDelete:s.references?.onDelete??o.onDelete,onUpdate:s.references?.onUpdate??o.onUpdate}};return}t.columns[n]={kind:"column",type:o.fkType??i,sqlName:o.sqlName,notNull:o.notNull??true,nullable:o.notNull===false?true:void 0,references:{table:r,column:a,onDelete:o.onDelete,onUpdate:o.onUpdate}};}function pn(e,t,n){if(t.notNull===true&&t.nullable===true)throw new Error(`Invalid nullable configuration on '${e}': cannot set both notNull and nullable to true.`);return t.notNull===true?true:t.nullable===true||t.notNull===false?false:n}function mn(e,t){return `${e}:${t}`}function Pr(e,t,n,r){let a=mn(e,t),o=mn(n,r);return a<=o?{key:`${a}|${o}`,leftTable:e,leftReferenceField:t,rightTable:n,rightReferenceField:r,sourceIsLeft:true}:{key:`${o}|${a}`,leftTable:n,leftReferenceField:r,rightTable:e,rightReferenceField:t,sourceIsLeft:false}}function Er(e,t){return `${e}${F(t)}Links`}function gn(e,t,n){let r=ie(e),a=ie(t);return r===a?`${n}${F(r)}Id`:`${r}Id`}function Or(e,t,n){if(e.junctionTable!==t.junctionTable)throw new Error(`manyToMany pair '${n}' has conflicting junctionTable values ('${e.junctionTable}' vs '${t.junctionTable}').`);if(e.leftField!==t.leftField)throw new Error(`manyToMany pair '${n}' has conflicting left field values ('${e.leftField}' vs '${t.leftField}').`);if(e.rightField!==t.rightField)throw new Error(`manyToMany pair '${n}' has conflicting right field values ('${e.rightField}' vs '${t.rightField}').`);if(e.leftSqlName!==t.leftSqlName)throw new Error(`manyToMany pair '${n}' has conflicting left sql name values ('${e.leftSqlName}' vs '${t.leftSqlName}').`);if(e.rightSqlName!==t.rightSqlName)throw new Error(`manyToMany pair '${n}' has conflicting right sql name values ('${e.rightSqlName}' vs '${t.rightSqlName}').`);if(e.onDelete!==t.onDelete)throw new Error(`manyToMany pair '${n}' has conflicting onDelete values ('${e.onDelete}' vs '${t.onDelete}').`);if(e.onUpdate!==t.onUpdate)throw new Error(`manyToMany pair '${n}' has conflicting onUpdate values ('${e.onUpdate}' vs '${t.onUpdate}').`);return e}function jr(e){let t=new Map;for(let[n,r]of Object.entries(e.tables))for(let a of Object.values(r.relations)){if(a.relation!=="manyToMany")continue;let o=a.referenceField??"id",i=a.targetReferenceField??"id",s=Pr(n,o,a.targetTable,i),c=gn(s.leftTable,s.rightTable,"source"),l=gn(s.rightTable,s.leftTable,"target"),u={leftTable:s.leftTable,leftReferenceField:s.leftReferenceField,rightTable:s.rightTable,rightReferenceField:s.rightReferenceField,junctionTable:a.junctionTable??Er(s.leftTable,s.rightTable),leftField:s.sourceIsLeft?a.sourceField??c:a.targetField??c,rightField:s.sourceIsLeft?a.targetField??l:a.sourceField??l,leftSqlName:s.sourceIsLeft?a.sourceSqlName:a.targetSqlName,rightSqlName:s.sourceIsLeft?a.targetSqlName:a.sourceSqlName,onDelete:a.onDelete,onUpdate:a.onUpdate};if(u.leftField===u.rightField)throw new Error(`manyToMany pair '${s.key}' resolves to duplicate junction fields '${u.leftField}'. Set sourceField/targetField explicitly.`);let p=t.get(s.key);p?Or(p,u,s.key):t.set(s.key,u),a.referenceField=o,a.targetReferenceField=i,a.junctionTable=u.junctionTable,a.sourceField=s.sourceIsLeft?u.leftField:u.rightField,a.targetField=s.sourceIsLeft?u.rightField:u.leftField,a.sourceSqlName=s.sourceIsLeft?u.leftSqlName:u.rightSqlName,a.targetSqlName=s.sourceIsLeft?u.rightSqlName:u.leftSqlName;}for(let n of t.values()){if(n.junctionTable in e.tables)throw new Error(`manyToMany auto junction table '${n.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`);let r=H(e,n.leftTable,n.leftReferenceField)??"string",a=H(e,n.rightTable,n.rightReferenceField)??"string";e.tables[n.junctionTable]={kind:"table",columns:{[n.leftField]:{kind:"column",type:r,sqlName:n.leftSqlName,notNull:true,nullable:false,references:{table:n.leftTable,column:n.leftReferenceField,onDelete:n.onDelete,onUpdate:n.onUpdate},index:true},[n.rightField]:{kind:"column",type:a,sqlName:n.rightSqlName,notNull:true,nullable:false,references:{table:n.rightTable,column:n.rightReferenceField,onDelete:n.onDelete,onUpdate:n.onUpdate},index:true}},relations:{[n.leftTable]:{kind:"relation",relation:"one",targetTable:n.leftTable,field:n.leftField,referenceField:n.leftReferenceField},[n.rightTable]:{kind:"relation",relation:"one",targetTable:n.rightTable,field:n.rightField,referenceField:n.rightReferenceField}}};}}function Dr(e){for(let[t,n]of Object.entries(e.tables)){for(let[r,a]of Object.entries(n.columns))if(a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${t}.${r}': cannot set both notNull and nullable to true.`);for(let[r,a]of Object.entries(n.relations))if(a.relation!=="manyToMany"&&a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${t}.${r}': cannot set both notNull and nullable to true.`)}}function Vr(e){Dr(e);let t=Ir(e);for(let[n,r]of Object.entries(t.tables))for(let[a,o]of Object.entries(r.relations)){if(o.relation!=="one")continue;let i=o.referenceField??"id",s=o.field??`${a}Id`;o.field=s;let c=H(t,o.targetTable,i)??o.fkType??"string";dn(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:pn(`${n}.${a}`,o,true),onDelete:o.onDelete,onUpdate:o.onUpdate},c);}for(let[n,r]of Object.entries(t.tables))for(let a of Object.values(r.relations)){if(a.relation!=="many")continue;let o=t.tables[a.targetTable];if(!o)continue;let i=a.referenceField??"id",s=a.field??`${ie(n)}Id`;a.field=s;let c=H(t,n,i)??a.fkType??"string";dn(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:pn(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},c);}return jr(t),t}function hn(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function j(e){return e.notNull!==true}function Br(e,t,n){let r=t.sqlName??O(e),a=r!==e;if(t.type==="int")return a?`t.int(${g(r)})`:"t.int()";if(t.type==="string")return t.length!==void 0?a?`t.text(${g(r)}, { length: ${t.length} })`:`t.text({ length: ${t.length} })`:a?`t.text(${g(r)})`:"t.text()";if(t.type==="boolean")return a?`t.int(${g(r)}, { mode: "boolean" })`:'t.int({ mode: "boolean" })';if(t.type==="date")return a?`t.int(${g(r)}, { mode: "timestamp_ms" })`:'t.int({ mode: "timestamp_ms" })';if(t.type==="enum"&&t.enumValues&&t.enumValues.length>0)return t.isArray?a?`t.text(${g(r)}).array()`:"t.text().array()":a?`t.text(${g(r)})`:"t.text()";if(t.type==="json"&&t.jsonShape){let o=L(t.jsonShape);return `${a?`t.text(${g(r)}, { mode: "json" })`:'t.text({ mode: "json" })'}.$type<${o}>()`}return n==="camelToSnake"&&a?`t.text(${g(r)})`:"t.text()"}function Wr(e,t,n){let r=n.field,a=n.referenceField??"id";if(!r)throw new Error(`Relation on '${e}' targeting '${n.targetTable}' is missing a local field.`);if(!(r in t.columns))throw new Error(`Relation '${e}.${r}' references missing local field '${r}'.`);return {sourceField:r,targetField:a}}function Hr(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
9142
|
+
`}function Lr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function zr(e,t,n){if(t.references)return {tableName:t.references.table,fieldName:t.references.column};let r=Object.values(n.relations).find(a=>a.relation==="one"&&a.field===e);if(r)return {tableName:r.targetTable,fieldName:r.referenceField??"id"}}function Ur(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.columns)){if(i.type!=="json"||!i.jsonShape)continue;let s=se(i.jsonShape);a.push(`${g(o)}: { shape: ${s} },`);}a.length!==0&&t.push(`${g(n)}: {
|
|
9136
9143
|
${a.map(o=>` ${o}`).join(`
|
|
9137
9144
|
`)}
|
|
9138
9145
|
},`);}return t.length===0?`export const __appflareJsonColumns = {} as const;
|
|
@@ -9140,7 +9147,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9140
9147
|
${t.map(n=>` ${n}`).join(`
|
|
9141
9148
|
`)}
|
|
9142
9149
|
} as const;
|
|
9143
|
-
`}function se(e){return e.kind==="array"?`{ kind: "array", element: ${se(e.element)} }`:e.kind==="object"?`{ kind: "object", shape: { ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${se(r)}`).join(", ")} } }`:`{ kind: ${g(e.kind)} }`}function
|
|
9150
|
+
`}function se(e){return e.kind==="array"?`{ kind: "array", element: ${se(e.element)} }`:e.kind==="object"?`{ kind: "object", shape: { ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${se(r)}`).join(", ")} } }`:`{ kind: ${g(e.kind)} }`}function Qr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations))i.relation==="manyToMany"&&i.junctionTable&&a.push(`${g(o)}: {
|
|
9144
9151
|
targetTable: ${g(i.targetTable)},
|
|
9145
9152
|
junctionTable: ${g(i.junctionTable)},
|
|
9146
9153
|
sourceField: ${g(i.sourceField??"")},
|
|
@@ -9153,7 +9160,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9153
9160
|
${t.map(n=>` ${n}`).join(`
|
|
9154
9161
|
`)}
|
|
9155
9162
|
} as const;
|
|
9156
|
-
`}function
|
|
9163
|
+
`}function _r(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations)){if(i.relation==="one"){a.push(`${g(o)}: {
|
|
9157
9164
|
kind: "one",
|
|
9158
9165
|
targetTable: ${g(i.targetTable)},
|
|
9159
9166
|
sourceField: ${g(i.field??"")},
|
|
@@ -9179,7 +9186,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9179
9186
|
${t.map(n=>` ${n}`).join(`
|
|
9180
9187
|
`)}
|
|
9181
9188
|
} as const;
|
|
9182
|
-
`}function
|
|
9189
|
+
`}function Kr(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let l of Object.values(e.tables)){for(let u of Lr(l))n.has(u)||r.add(u);for(let u of Object.values(l.columns))u.references&&!n.has(u.references.table)&&r.add(u.references.table);}let a=new Map;for(let l of Object.values(e.tables))for(let[u,p]of Object.entries(l.columns))if(p.type==="enum"&&p.enumValues&&p.enumValues.length>0){let d=p.enumRef??`${u}`;a.has(d)||a.set(d,p);}let o=[],i=[];for(let[l,u]of a.entries()){let p=F(l),d=u.enumValues.map(y=>`"${y}"`).join(" | ");o.push(`export type ${p} = ${d};`),i.push(`export const ${p}Column = t.customType<{ data: ${p}; dataNotNull: ${p} }>({ dataType: () => "text" });`);}let s=[],c=[];for(let[l,u]of Object.entries(e.tables)){let p=u.sqlName??O(l),d=[],y=[];for(let[b,h]of Object.entries(u.columns)){let T;if(h.type==="enum"&&h.enumValues&&h.enumValues.length>0){let R=h.enumRef??b,P=F(R),V=h.sqlName??O(b);T=V!==b?`${P}Column(${g(V)})`:`${P}Column()`,h.isArray&&(T+=".array()");}else T=Br(b,h,t);h.uuidPrimaryKey&&(T+=".$defaultFn(() => crypto.randomUUID())"),h.primaryKey&&(T+=h.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),h.notNull&&(T+=".notNull()"),h.sqlDefault!==void 0&&(T+=`.default(${Mr(h.sqlDefault)})`);let C=zr(b,h,u);if(C)if(h.references?.onDelete||h.references?.onUpdate){let R=[];h.references.onDelete&&R.push(`onDelete: ${g(h.references.onDelete)}`),h.references.onUpdate&&R.push(`onUpdate: ${g(h.references.onUpdate)}`),T+=`.references(() => ${C.tableName}.${C.fieldName}, { ${R.join(", ")} })`;}else T+=`.references(() => ${C.tableName}.${C.fieldName})`;if(h.unique){let R=typeof h.unique=="object"&&h.unique.name?h.unique.name:`${p}_${O(b)}_unique_idx`;y.push(` t.uniqueIndex(${g(R)}).on(table.${b})`);}if(h.index){let R=typeof h.index=="object"&&h.index.name?h.index.name:`${p}_${O(b)}_idx`;y.push(` t.index(${g(R)}).on(table.${b})`);}d.push(` ${b}: ${T},`);}y.length>0?s.push(`export const ${l} = table(
|
|
9183
9190
|
${g(p)},
|
|
9184
9191
|
{
|
|
9185
9192
|
${d.join(`
|
|
@@ -9192,7 +9199,7 @@ ${y.join(`,
|
|
|
9192
9199
|
);`):s.push(`export const ${l} = table(${g(p)}, {
|
|
9193
9200
|
${d.join(`
|
|
9194
9201
|
`)}
|
|
9195
|
-
});`);let v=Object.entries(u.relations).filter(([,b])=>b.relation==="one"),A=Object.entries(u.relations).filter(([,b])=>b.relation==="many"),w=Object.entries(u.relations).filter(([,b])=>b.relation==="manyToMany");if(v.length===0&&A.length===0&&w.length===0)continue;let I=[];for(let[b,h]of v){let T=
|
|
9202
|
+
});`);let v=Object.entries(u.relations).filter(([,b])=>b.relation==="one"),A=Object.entries(u.relations).filter(([,b])=>b.relation==="many"),w=Object.entries(u.relations).filter(([,b])=>b.relation==="manyToMany");if(v.length===0&&A.length===0&&w.length===0)continue;let I=[];for(let[b,h]of v){let T=Wr(l,u,h);I.push(` ${b}: one(${h.targetTable}, {
|
|
9196
9203
|
fields: [${l}.${T.sourceField}],
|
|
9197
9204
|
references: [${h.targetTable}.${T.targetField}],
|
|
9198
9205
|
}),`);}for(let[b,h]of A)I.push(` ${b}: many(${h.targetTable}),`);for(let[b,h]of w){if(!h.junctionTable)throw new Error(`manyToMany relation '${l}.${b}' is missing junctionTable after normalization.`);I.push(` ${b}: many(${h.junctionTable}),`);}c.push(`export const ${l}Relations = relations(${l}, ({ one, many }) => ({
|
|
@@ -9201,7 +9208,7 @@ ${I.join(`
|
|
|
9201
9208
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9202
9209
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
9203
9210
|
import { relations } from "drizzle-orm";
|
|
9204
|
-
${
|
|
9211
|
+
${Hr(r)}
|
|
9205
9212
|
${o.join(`
|
|
9206
9213
|
`)}
|
|
9207
9214
|
${i.join(`
|
|
@@ -9215,12 +9222,12 @@ ${c.join(`
|
|
|
9215
9222
|
|
|
9216
9223
|
`)}
|
|
9217
9224
|
|
|
9218
|
-
${zr(e)}
|
|
9219
|
-
|
|
9220
9225
|
${Ur(e)}
|
|
9221
9226
|
|
|
9222
9227
|
${Qr(e)}
|
|
9223
|
-
|
|
9228
|
+
|
|
9229
|
+
${_r(e)}
|
|
9230
|
+
`}function le(e){return e.kind==="array"?`z.array(${le(e.element)})`:e.kind==="object"?`z.object({ ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${le(r)}`).join(", ")} })`:e.kind==="string"?"z.string()":e.kind==="number"?"z.number()":e.kind==="boolean"?"z.boolean()":e.kind==="date"?"z.date()":"z.unknown()"}function fn(e,t,n){let r="z.unknown()";if(e.type==="int")r="z.number().int()";else if(e.type==="string")r="z.string()",e.length!==void 0&&(r+=`.max(${e.length})`);else if(e.type==="boolean")r="z.boolean()";else if(e.type==="date")r="z.date()";else if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0){let o=`z.enum([${e.enumValues.map(i=>`"${i}"`).join(", ")}])`;r=e.isArray?`z.array(${o})`:o;}else e.type==="json"&&e.jsonShape&&(r=le(e.jsonShape));return t&&(r+=".optional()"),n&&(r+=".nullable()"),r}function Jr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=F(n),o=[],i=[];for(let[s,c]of Object.entries(r.columns))o.push(` ${s}: ${fn(c,hn(c),j(c))},`),i.push(` ${s}: ${fn(c,j(c),j(c))},`);t.push(`export const ${n}InsertSchema = z.object({
|
|
9224
9231
|
${o.join(`
|
|
9225
9232
|
`)}
|
|
9226
9233
|
});
|
|
@@ -9234,7 +9241,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
9234
9241
|
`);}return `import { z } from "zod";
|
|
9235
9242
|
|
|
9236
9243
|
${t.join(`
|
|
9237
|
-
`)}`}function L(e){return e.kind==="array"?`Array<${L(e.element)}>`:e.kind==="object"?`{ ${Object.entries(e.shape).map(([n,r])=>`${n}: ${L(r)}`).join("; ")} }`:e.kind==="string"?"string":e.kind==="number"?"number":e.kind==="boolean"?"boolean":e.kind==="date"?"Date":"unknown"}function
|
|
9244
|
+
`)}`}function L(e){return e.kind==="array"?`Array<${L(e.element)}>`:e.kind==="object"?`{ ${Object.entries(e.shape).map(([n,r])=>`${n}: ${L(r)}`).join("; ")} }`:e.kind==="string"?"string":e.kind==="number"?"number":e.kind==="boolean"?"boolean":e.kind==="date"?"Date":"unknown"}function Gr(e){if(e.type==="int")return "number";if(e.type==="string")return "string";if(e.type==="boolean")return "boolean";if(e.type==="date")return "Date";if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0){let t=e.enumValues.map(n=>`"${n}"`).join(" | ");return e.isArray?`Array<${t}>`:t}return e.type==="json"&&e.jsonShape?L(e.jsonShape):"unknown"}function Zr(e){let t=[];for(let[r,a]of Object.entries(e.enums??{})){let o=F(r),i=a.values.map(s=>`"${s}"`).join(" | ");t.push(`export type ${o} = ${i};`);}let n=[];for(let[r,a]of Object.entries(e.tables)){let o=F(r),i=[],s=[];for(let[c,l]of Object.entries(a.columns)){let u=Gr(l),p=j(l)?" | null":"";i.push(` ${c}${j(l)?"?":""}: ${u}${p};`),s.push(` ${c}${hn(l)?"?":""}: ${u}${p};`);}n.push(`export type ${o} = {
|
|
9238
9245
|
${i.join(`
|
|
9239
9246
|
`)}
|
|
9240
9247
|
};
|
|
@@ -9247,23 +9254,25 @@ ${s.join(`
|
|
|
9247
9254
|
${n.join(`
|
|
9248
9255
|
|
|
9249
9256
|
`)}
|
|
9250
|
-
`}function
|
|
9251
|
-
`)
|
|
9252
|
-
`);let
|
|
9253
|
-
`)
|
|
9254
|
-
`),Bun.write(
|
|
9255
|
-
`)
|
|
9256
|
-
`);
|
|
9257
|
+
`}function Xr(e,t){if(t){let n=e[t];if(!re(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(re(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function yn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=resolve(e.configDir,t.entry),a=resolve(e.configDir,t.outFile??resolve(e.outDirAbs,"schema.compiled.ts")),o=resolve(e.configDir,t.typesOutFile??resolve(e.outDirAbs,"schema.types.ts")),i=resolve(e.configDir,t.zodOutFile??resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),l=Xr(c,t.exportName),u=Vr(l);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(dirname(i),{recursive:true})]);let p=Kr(u,n),d=Zr(u),y=Jr(u);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(u.tables)}}function ea(e){return e.replaceAll("\\","/")}function M(e,t){let n=ea(relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var aa=new Set([".ts",".tsx",".mts",".cts"]);async function Tn(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await Tn(a));continue}r.isFile()&&aa.has(extname(r.name))&&n.push(a);}return n}function ue(e){return e.replace(/\.[cm]?tsx?$/,"")}function oa(e,t){let n=e,r=false,a,o="unknown";for(;f.isCallExpression(n);){let i=n.expression;if(!f.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,n=i.expression;else if(s==="default"){r=true;let c=n.arguments[0];c&&(f.isStringLiteral(c)||f.isNumericLiteral(c)?a=c.text:c.kind===f.SyntaxKind.TrueKeyword?a="true":c.kind===f.SyntaxKind.FalseKeyword&&(a="false")),n=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else n=i.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function ia(e){if(!e||!f.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f.isPropertyAssignment(r)&&f.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f.isPropertyAssignment(r)||!f.isIdentifier(r.name)||n.push(oa(r.initializer,r.name.text));return n}function sa(e){return f.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f.SyntaxKind.ExportKeyword)??false:false}function vn(e){return f.isIdentifier(e)?e.text:f.isParenthesizedExpression(e)?vn(e.expression):null}function la(e){if(!e||!f.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f.isPropertyAssignment(r)||!f.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f.isPropertyAssignment(t))return [];let n=t.initializer;return f.isStringLiteral(n)||f.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f.isArrayLiteralExpression(n)?n.elements.map(r=>f.isStringLiteral(r)||f.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function ua(e,t){let n=f.createSourceFile(t,e,f.ScriptTarget.Latest,true,f.ScriptKind.TS),r=[];for(let a of n.statements)if(sa(a))for(let o of a.declarationList.declarations){if(!f.isIdentifier(o.name)||!o.initializer||!f.isCallExpression(o.initializer))continue;let i=vn(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?la(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ia(o.initializer.arguments[0]):[]});}return r}function bn(e,t,n){let r=t.replace(/\\/g,"/"),o=ue(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function ca(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function wn(e,t){let n=e.replace(/\\/g,"/"),a=ue(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function Rn(e){let t=[],n=await Tn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=relative(e.scanDirAbs,a),c=ua(i,a),l=[{kind:"query",kindDirectory:"queries",exports:c.filter(u=>u.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(u=>u.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(u=>u.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(u=>u.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(u=>u.kind==="storage")}];for(let u of l){if(u.exports.length===0)continue;let p=ca(s,u.kindDirectory);for(let d of u.exports){let y=u.kind==="query"||u.kind==="mutation"?wn(p,d.exportName):void 0,v=u.kind==="scheduler"||u.kind==="cron"?wn(p,d.exportName):void 0,A=u.kind==="query"||u.kind==="mutation"?[...ue(p).split("/").filter(Boolean),d.exportName]:void 0,w=u.kind==="query"?bn("queries",p,d.exportName):u.kind==="mutation"?bn("mutations",p,d.exportName):u.kind==="storage"?`/storage/managers/${d.exportName}`:`/${u.kindDirectory}/${v}`;t.push({kind:u.kind,exportName:d.exportName,filePath:a,importPath:M(e.outDirAbs,a),clientImportPath:M(resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:v,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function pa(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,l=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(l){n+=d,l=false;continue}if(d==="\\"){n+=d,l=true;continue}if(!s&&!c&&d==="'"){i=!i,n+=d;continue}if(!i&&!c&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){c=!c,n+=d;continue}if(i||s||c){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let u=n.trim();return u.length>0&&t.push(u),t}function ma(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let c=0;c<e.length;c+=1){let l=e[c];if(s){s=false;continue}if(l==="\\"){s=true;continue}if(!o&&!i&&l==="'"){a=!a;continue}if(!a&&!i&&l==='"'){o=!o;continue}if(!a&&!o&&l==="`"){i=!i;continue}if(!(a||o||i)){if(l==="("){t+=1;continue}if(l===")"){t-=1;continue}if(l==="{"){n+=1;continue}if(l==="}"){n-=1;continue}if(l==="["){r+=1;continue}if(l==="]"){r-=1;continue}if(l===":"&&t===0&&n===0&&r===0)return c}}return -1}function ga(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function fa(e){let t=pa(e),n=[];for(let r of t){let a=ma(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),c=/autoincrement\s*:\s*true/i.test(i),l=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||l||c||s;n.push({name:o,expression:i,type:ga(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function ha(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,l=false,u=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!l&&!u&&y==="'"){c=!c;continue}if(!c&&!u&&y==='"'){l=!l;continue}if(!c&&!l&&y==="`"){u=!u;continue}if(!(c||l||u)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let c=r(e,s);if(c===-1){a=t.exec(e);continue}let l=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:fa(l)}),a=t.exec(e);}return n}async function Sn(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await Sn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function An(e,t=[]){let n=await Sn(e.scanDirAbs).catch(()=>[]),r=resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),c=ha(s);if(c.length>0)return {schemaPath:o,tables:c}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function wa(e){let t=e.auth.options.plugins;if(!Array.isArray(t))return [];for(let n of t)if(n&&typeof n=="object"){let r=n;if(r.id==="admin"&&"options"in r){let a=r.options;if(a&&typeof a=="object"&&"roles"in a){let o=a.roles;if(o&&typeof o=="object")return Object.keys(o)}}}return []}function xa(e){let r=e.auth.options?.user?.additionalFields;if(!r||typeof r!="object")return [];let a={string:"string",number:"number",boolean:"boolean",date:"Date"};return Object.entries(r).filter(([,o])=>o&&typeof o=="object"&&"type"in o).map(([o,i])=>({name:o,tsType:a[i.type]||"unknown"}))}async function Ta(e,t){let n=await Bun.file(e).text(),r=t.map(o=>`"${o}"`).join(" | "),a=n.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
9258
|
+
import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["']role["']\)/,`role: customType<{ data: ${r}; dataNotNull: ${r} }>({ dataType: () => "text" })("role")`);await Bun.write(e,a);}function va(e,t){let n=relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function Cn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=M(t,a),s=resolve(t,"client"),c=M(s,a),l=performance.now();await Promise.all([mkdir(t,{recursive:true}),mkdir(s,{recursive:true}),mkdir(n,{recursive:true})]),process.stdout.write(`\u{1F4C1} Directories (${(performance.now()-l).toFixed(0)}ms)
|
|
9259
|
+
`);let u=dirname(fileURLToPath(import.meta.url)),p=join(dirname(Bun.resolveSync("typescript/package.json",u)),"bin","tsc"),d=join(dirname(Bun.resolveSync("@better-auth/cli/package.json",u)),"dist","index.mjs"),y=resolve(t,"server.ts"),v=resolve(t,"client.ts"),A=resolve(t,"auth.config.ts"),w=resolve(t,"auth.schema.ts"),I=resolve(t,"drizzle.config.ts"),b=resolve(n,"wrangler.json"),h=await yn(e),T=await An(e,h?[h.schemaPath]:[]),C=M(t,T.schemaPath),R=await Rn(e);process.stdout.write(`\u{1F50D} ${R.length} handler(s) (${(performance.now()-l).toFixed(0)}ms)
|
|
9260
|
+
`);let P=wa(r),V=xa(r),me=xt(r.auth.basePath,r.database[0].binding,r.kv[0]?.binding,r.scheduler.binding,r.r2[0]?.binding,r.realtime.binding,r.realtime.objectName,r.realtime.subscribePath,r.realtime.websocketPath,r.realtime.protocol),Vn=Se(c,R),Bn=Z(C,R,r.r2[0]?.binding,P,V),Wn=be(i),Hn=h?[va(o,h.schemaPath),...r.schema.filter(x=>!/(^|\/)schema\.ts$/.test(x))]:r.schema,Ln=Ae(Hn),zn=vt(e,R),Un=cn(C,T,R),Qn=resolve(t,"admin.routes.ts"),_n=Bn.map(x=>Bun.write(resolve(t,x.relativePath),x.source)),Kn=Vn.map(x=>Bun.write(resolve(t,x.relativePath),x.source));await Promise.all([Bun.write(y,me),Bun.write(v,`export * from "./client/index";
|
|
9261
|
+
`),...Kn,..._n,Bun.write(A,Wn),Bun.write(w,""),Bun.write(I,Ln),Bun.write(b,`${JSON.stringify(zn,null,2)}
|
|
9262
|
+
`),Bun.write(Qn,Un)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-l).toFixed(0)}ms)
|
|
9263
|
+
`);let _=relative(o,A).replace(/\\/g,"/"),Jn=_.startsWith(".")?_:`./${_}`,K=relative(o,w).replace(/\\/g,"/"),Gn=K.startsWith(".")?K:`./${K}`,ge=await Bun.spawn([process.execPath,d,"generate","--config",Jn,"--output",Gn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(ge!==0)throw new Error(`better-auth generation failed with exit code ${ge}`);process.stdout.write(`\u{1F510} Auth schema (${(performance.now()-l).toFixed(0)}ms)
|
|
9264
|
+
`),P.length>0&&(await Ta(w,P),process.stdout.write(`\u{1F527} Patched role type (${(performance.now()-l).toFixed(0)}ms)
|
|
9265
|
+
`));function Zn(x={}){return {compilerOptions:{lib:["es2024"],types:["@types/node","@cloudflare/workers-types/2023-07-01"],module:"es2022",target:"es2024",moduleResolution:"bundler",strictNullChecks:true,skipLibCheck:true,declaration:true,emitDeclarationOnly:true,noCheck:true,jsx:"react-jsx",paths:{"_generated/*":["./*"]},...x},include:["./*.ts","./client/*.ts"]}}let fe=resolve(t,"tsconfig.js.json");await Promise.all([Bun.write(fe,`${JSON.stringify(Zn({declaration:true,emitDeclarationOnly:false}),null,2)}
|
|
9257
9266
|
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-l).toFixed(0)}ms)
|
|
9258
|
-
`);async function
|
|
9259
|
-
`);let N=await Bun.spawn([process.execPath,p,"-p",x],{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(N!==0)throw new Error(`tsc ${$} failed with exit code ${N}`)}await
|
|
9267
|
+
`);async function Xn(x,$){process.stdout.write(`\u2699\uFE0F ${$}... (${(performance.now()-l).toFixed(0)}ms)
|
|
9268
|
+
`);let N=await Bun.spawn([process.execPath,p,"-p",x],{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(N!==0)throw new Error(`tsc ${$} failed with exit code ${N}`)}await Xn(fe,"JS files"),process.stdout.write(`\u2705 JS + declarations (${(performance.now()-l).toFixed(0)}ms)
|
|
9260
9269
|
`);async function he(x){let $=await readdir(x,{withFileTypes:true});for(let k of $){let N=join(x,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith("."))continue;await he(N);}else k.name.endsWith(".ts")&&!k.name.endsWith(".d.ts")&&await rm(N);}}await he(t),process.stdout.write(`\u{1F4E6} Cleaned .ts files (${(performance.now()-l).toFixed(0)}ms)
|
|
9261
|
-
`);let
|
|
9262
|
-
`);let
|
|
9270
|
+
`);let Yn=t+"/";async function ye(x){let $=await readdir(x,{withFileTypes:true});for(let k of $){let N=join(x,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith(".")||N===t)continue;await ye(N);}else !N.startsWith(Yn)&&(k.name.endsWith(".d.ts")||k.name.endsWith(".js"))&&await rm(N);}}await ye(o),process.stdout.write(`\u{1F9F9} Cleanup (${(performance.now()-l).toFixed(0)}ms)
|
|
9271
|
+
`);let er=resolve(o,"tsconfig.json");if(e.config.build&&existsSync(er)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-l).toFixed(0)}ms)
|
|
9263
9272
|
`);let $=await Bun.spawn([process.execPath,p,"--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if($!==0)throw new Error(`TypeScript build failed with exit code ${$}`);process.stdout.write(`\u2705 Build complete (${(performance.now()-l).toFixed(0)}ms)
|
|
9264
|
-
`);}}var qn=z.object({binding:z.string().min(1),databaseName:z.string().min(1),databaseId:z.string().min(1),previewDatabaseId:z.string().min(1).optional(),migrationsDir:z.string().min(1).optional()}).strict(),
|
|
9273
|
+
`);}}var qn=z.object({binding:z.string().min(1),databaseName:z.string().min(1),databaseId:z.string().min(1),previewDatabaseId:z.string().min(1).optional(),migrationsDir:z.string().min(1).optional()}).strict(),Fn=z.object({binding:z.string().min(1),id:z.string().min(1),previewId:z.string().min(1).optional()}).strict(),Mn=z.object({binding:z.string().min(1),bucketName:z.string().min(1),previewBucketName:z.string().min(1).optional(),jurisdiction:z.string().min(1).optional()}).strict(),In=z.object({enabled:z.boolean().optional(),binding:z.string().min(1).optional(),queue:z.string().min(1).optional()}).strict(),Aa=z.object({enabled:z.boolean().optional(),binding:z.string().min(1).optional(),className:z.string().min(1).optional(),objectName:z.string().min(1).optional(),subscribePath:z.string().min(1).optional(),websocketPath:z.string().min(1).optional(),protocol:z.string().min(1).optional()}).strict(),Na=z.object({scanDir:z.string().min(1),outDir:z.string().min(1),wranglerOutDir:z.string().min(1).optional(),wranglerOutPath:z.string().min(1).optional(),schema:z.array(z.string()).min(1),schemaDsl:z.object({entry:z.string().min(1),exportName:z.string().min(1).optional(),outFile:z.string().min(1).optional(),typesOutFile:z.string().min(1).optional(),zodOutFile:z.string().min(1).optional(),namingStrategy:z.literal("camelToSnake").optional()}).strict().optional(),database:z.union([qn,z.array(qn).min(1)]),kv:z.union([Fn,z.array(Fn)]).optional(),r2:z.union([Mn,z.array(Mn)]).optional(),auth:z.object({enabled:z.boolean(),basePath:z.string().min(1),options:z.custom(e=>typeof e=="object"&&e!==null),clientOptions:z.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:In.optional(),realtime:Aa.optional(),wranglerOverrides:z.record(z.string(),z.unknown()).optional(),build:z.boolean().optional()}).strict();function Pn(e){return typeof e=="object"&&e!==null}function $a(e){let t=Pn(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=In.safeParse(t);return n.success?n.data:{}}function Ca(e){if(!Pn(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function qa(e){let n={...$a(e)??{},...e.scheduler??{}},r=e.realtime??{};return {...e,database:Array.isArray(e.database)?e.database:[e.database],kv:e.kv?Array.isArray(e.kv)?e.kv:[e.kv]:[],r2:e.r2?Array.isArray(e.r2)?e.r2:[e.r2]:[],scheduler:{enabled:n.enabled??true,binding:n.binding??"APPFLARE_SCHEDULER_QUEUE",queue:n.queue},realtime:{enabled:r.enabled??true,binding:r.binding??"APPFLARE_REALTIME",className:r.className??"AppflareRealtimeDurableObject",objectName:r.objectName??"global",subscribePath:r.subscribePath??"/realtime/subscribe",websocketPath:r.websocketPath??"/realtime/ws",protocol:r.protocol??"appflare.realtime.v1"},wranglerOverrides:Ca(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function D(e){let t=isAbsolute(e??"")?e:resolve(process.cwd(),e??"appflare.config.ts"),n=dirname(t),o=(await import(pathToFileURL(t).href)).default,i=Na.parse(o),s=qa(i);return {configPath:t,configDir:n,scanDirAbs:resolve(n,s.scanDir),outDirAbs:resolve(n,s.outDir),wranglerOutDirAbs:resolve(n,s.wranglerOutDir),config:s}}function Pa(e){let t=e;for(;;){if(existsSync(resolve(t,"package.json")))return t;let n=dirname(t);if(n===t)return e;t=n;}}async function Q(e,t={}){let n=await D(e);if(t.build!==void 0&&(n.config.build=t.build),await Cn(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
9265
9274
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
9266
|
-
`);}async function On(e,t={}){if(await Q(e,{build:t.build}),!t.watch)return;let n=await
|
|
9267
|
-
`);}finally{r=false,a&&(a=false,await o());}}
|
|
9275
|
+
`);}async function On(e,t={}){if(await Q(e,{build:t.build}),!t.watch)return;let n=await D(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await Q(e,{build:t.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
9276
|
+
`);}finally{r=false,a&&(a=false,await o());}};Fa.watch(n.scanDirAbs,{ignoreInitial:true,ignored:s=>s.includes("/_generated/")||s.includes("/dist/")||s.includes("/out/")||s.includes("/node_modules/")||s.endsWith(".d.ts")}).on("all",async(s,c)=>{process.stdout.write(`\u{1F504} Change detected: ${c}
|
|
9268
9277
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
9269
|
-
`);}async function jn(e,t={}){let n=await
|
|
9278
|
+
`);}async function jn(e,t={}){let n=await D(e),r=Pa(process.cwd());if([!!t.local,!!t.remote,!!t.preview].filter(Boolean).length>1)throw new Error("Only one of --local, --remote, or --preview can be set.");let o=resolve(n.outDirAbs,"drizzle.config.js"),i=process.platform==="win32"?"npx.cmd":"npx",c=await Bun.spawn([i,"drizzle-kit","generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(c!==0)throw new Error(`drizzle-kit generate failed with exit code ${c}`);let l=n.config.database[0].databaseName,u=[i,"wrangler","d1","migrations","apply",l];t.local?u.push("--local"):t.remote?u.push("--remote"):t.preview&&u.push("--preview");let d=await Bun.spawn(u,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(d!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${d}`)}async function Dn(e,t={name:"",email:"",password:""}){let n=await D(e);if([!!t.local,!!t.remote].filter(Boolean).length>1)throw new Error("Only one of --local or --remote can be set.");let{hashPassword:a}=await import('better-auth/crypto'),o=await a(t.password),i=crypto.randomUUID(),s=crypto.randomUUID(),c=Date.now(),l=t.name.replace(/'/g,"''"),u=t.email.replace(/'/g,"''"),p=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${l}', '${u}', 1, ${c}, ${c}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${u}', 'credential', '${i}', '${o}', ${c}, ${c});`].join(" "),d=n.config.database[0].databaseName,v=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${p}`];t.local?v.push("--local"):t.remote&&v.push("--remote");let w=await Bun.spawn(v,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(w!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${w}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var E=new Command;E.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");E.command("build").description("Generate server.ts, client.ts, auth.config.js, drizzle.config.js, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--no-build","Skip TypeScript build step").action(async e=>{await Q(e.config,{build:e.build});});E.command("dev").description("Run generator in development mode").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("-w, --watch","Watch scanDir and regenerate on changes",false).option("--no-build","Skip TypeScript build step").action(async e=>{await On(e.config,{watch:e.watch,build:e.build});});E.command("migrate").description("Generate drizzle migration files from outDir/auth.schema.ts and apply them to the configured D1 database").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute commands/files against a local DB for use with wrangler dev",false).option("--remote","Execute commands/files against a remote DB for use with wrangler dev --remote",false).option("--preview","Execute commands/files against a preview D1 DB",false).action(async e=>{await jn(e.config,{local:e.local,remote:e.remote,preview:e.preview});});E.command("add-admin").description("Add an admin user to the database").requiredOption("-n, --name <name>","Admin's display name").requiredOption("-e, --email <email>","Admin's email address").requiredOption("-p, --password <password>","Admin's password").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute command against a local DB for use with wrangler dev",false).option("--remote","Execute command against a remote DB for use with wrangler dev --remote",false).action(async e=>{await Dn(e.config,{name:e.name,email:e.email,password:e.password,local:e.local,remote:e.remote});});(async()=>{process.versions.bun||(console.error("Appflare CLI must be run with Bun."),process.exit(1)),await E.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|