appflare 0.2.37 → 0.2.39
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/generators/types/query-definitions/query-helper-functions.ts +82 -2
- package/cli/templates/handlers/index.ts +4 -1
- package/cli/templates/handlers/types.ts +4 -2
- package/dist/cli/index.js +182 -93
- package/dist/cli/index.mjs +182 -93
- 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,12 +1488,12 @@ ${Ce()}
|
|
|
1488
1488
|
|
|
1489
1489
|
${qe()}
|
|
1490
1490
|
|
|
1491
|
-
${Me()}
|
|
1492
|
-
|
|
1493
1491
|
${Fe()}
|
|
1494
1492
|
|
|
1493
|
+
${Me()}
|
|
1494
|
+
|
|
1495
1495
|
${Ie(e)}
|
|
1496
|
-
`}function
|
|
1496
|
+
`}function Ee(){return `
|
|
1497
1497
|
export async function executeOperation<
|
|
1498
1498
|
TShape extends ZodRawShape,
|
|
1499
1499
|
TResult,
|
|
@@ -1532,7 +1532,7 @@ export function handleOperationError(
|
|
|
1532
1532
|
return c.json({ message: (error as Error).message ?? "Unknown error" }, 500);
|
|
1533
1533
|
}
|
|
1534
1534
|
|
|
1535
|
-
`}function
|
|
1535
|
+
`}function Oe(){return `import type { Context } from "hono";
|
|
1536
1536
|
import { ZodError, type ZodRawShape } from "zod";
|
|
1537
1537
|
import {
|
|
1538
1538
|
type AppflareContext,
|
|
@@ -1541,8 +1541,8 @@ import {
|
|
|
1541
1541
|
type WorkerEnv,
|
|
1542
1542
|
} from "./handlers";
|
|
1543
1543
|
|
|
1544
|
-
${
|
|
1545
|
-
`}function
|
|
1544
|
+
${Ee()}
|
|
1545
|
+
`}function je(){return `import { betterAuth } from "better-auth";
|
|
1546
1546
|
import { auth } from "./auth.config";
|
|
1547
1547
|
import {
|
|
1548
1548
|
and,
|
|
@@ -1645,7 +1645,7 @@ export async function isStorageAllowed(
|
|
|
1645
1645
|
|
|
1646
1646
|
return false;
|
|
1647
1647
|
}
|
|
1648
|
-
`}function
|
|
1648
|
+
`}function De(){return `type Primitive = string | number | boolean | Date;
|
|
1649
1649
|
type NonNil<T> = Exclude<T, null | undefined>;
|
|
1650
1650
|
type Friendly<T> = T extends Date ? Date | number : T;
|
|
1651
1651
|
type Comparable<T> = Friendly<Extract<NonNil<T>, Primitive>>;
|
|
@@ -2101,6 +2101,86 @@ function buildJsonFieldFilter(
|
|
|
2101
2101
|
return undefined;
|
|
2102
2102
|
}
|
|
2103
2103
|
|
|
2104
|
+
function buildJsonArrayElementMatchCondition(
|
|
2105
|
+
field: unknown,
|
|
2106
|
+
matchValue: unknown,
|
|
2107
|
+
): SQL {
|
|
2108
|
+
if (!isRecord(matchValue) || matchValue instanceof Date || Array.isArray(matchValue)) {
|
|
2109
|
+
return sql\`EXISTS (SELECT 1 FROM json_each(\${field as never}) j WHERE j.value = \${matchValue})\`;
|
|
2110
|
+
}
|
|
2111
|
+
|
|
2112
|
+
const propConditions: SQL[] = [];
|
|
2113
|
+
for (const [key, propValue] of Object.entries(matchValue)) {
|
|
2114
|
+
const jsonPath = '$.' + key;
|
|
2115
|
+
if (!isRecord(propValue) || propValue instanceof Date || Array.isArray(propValue)) {
|
|
2116
|
+
propConditions.push(
|
|
2117
|
+
sql\`EXISTS (SELECT 1 FROM json_each(\${field as never}) j WHERE json_extract(j.value, \${jsonPath}) = \${propValue})\`,
|
|
2118
|
+
);
|
|
2119
|
+
} else {
|
|
2120
|
+
const nestedConditions: SQL[] = [];
|
|
2121
|
+
const eqVal = readOperatorValue(propValue, "eq");
|
|
2122
|
+
if (eqVal !== undefined) {
|
|
2123
|
+
nestedConditions.push(
|
|
2124
|
+
sql\`EXISTS (SELECT 1 FROM json_each(\${field as never}) j WHERE json_extract(j.value, \${jsonPath}) = \${eqVal})\`,
|
|
2125
|
+
);
|
|
2126
|
+
}
|
|
2127
|
+
const neVal = readOperatorValue(propValue, "ne");
|
|
2128
|
+
if (neVal !== undefined) {
|
|
2129
|
+
nestedConditions.push(
|
|
2130
|
+
sql\`EXISTS (SELECT 1 FROM json_each(\${field as never}) j WHERE json_extract(j.value, \${jsonPath}) != \${neVal})\`,
|
|
2131
|
+
);
|
|
2132
|
+
}
|
|
2133
|
+
const gtVal = readOperatorValue(propValue, "gt");
|
|
2134
|
+
if (gtVal !== undefined) {
|
|
2135
|
+
nestedConditions.push(
|
|
2136
|
+
sql\`EXISTS (SELECT 1 FROM json_each(\${field as never}) j WHERE json_extract(j.value, \${jsonPath}) > \${gtVal})\`,
|
|
2137
|
+
);
|
|
2138
|
+
}
|
|
2139
|
+
const gteVal = readOperatorValue(propValue, "gte");
|
|
2140
|
+
if (gteVal !== undefined) {
|
|
2141
|
+
nestedConditions.push(
|
|
2142
|
+
sql\`EXISTS (SELECT 1 FROM json_each(\${field as never}) j WHERE json_extract(j.value, \${jsonPath}) >= \${gteVal})\`,
|
|
2143
|
+
);
|
|
2144
|
+
}
|
|
2145
|
+
const ltVal = readOperatorValue(propValue, "lt");
|
|
2146
|
+
if (ltVal !== undefined) {
|
|
2147
|
+
nestedConditions.push(
|
|
2148
|
+
sql\`EXISTS (SELECT 1 FROM json_each(\${field as never}) j WHERE json_extract(j.value, \${jsonPath}) < \${ltVal})\`,
|
|
2149
|
+
);
|
|
2150
|
+
}
|
|
2151
|
+
const lteVal = readOperatorValue(propValue, "lte");
|
|
2152
|
+
if (lteVal !== undefined) {
|
|
2153
|
+
nestedConditions.push(
|
|
2154
|
+
sql\`EXISTS (SELECT 1 FROM json_each(\${field as never}) j WHERE json_extract(j.value, \${jsonPath}) <= \${lteVal})\`,
|
|
2155
|
+
);
|
|
2156
|
+
}
|
|
2157
|
+
const inVal = readOperatorValue(propValue, "in");
|
|
2158
|
+
if (Array.isArray(inVal) && inVal.length > 0) {
|
|
2159
|
+
nestedConditions.push(
|
|
2160
|
+
sql\`EXISTS (SELECT 1 FROM json_each(\${field as never}) j WHERE json_extract(j.value, \${jsonPath}) IN (\${sql.join(inVal.map((v) => sql\`\${v}\`), sql\`, \`)})\`,
|
|
2161
|
+
);
|
|
2162
|
+
}
|
|
2163
|
+
if (nestedConditions.length > 0) {
|
|
2164
|
+
propConditions.push(
|
|
2165
|
+
nestedConditions.length === 1
|
|
2166
|
+
? nestedConditions[0]
|
|
2167
|
+
: and(...nestedConditions),
|
|
2168
|
+
);
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
|
|
2173
|
+
if (propConditions.length === 0) {
|
|
2174
|
+
return sql\`EXISTS (SELECT 1 FROM json_each(\${field as never}) j WHERE json_type(j.value) = 'object')\`;
|
|
2175
|
+
}
|
|
2176
|
+
|
|
2177
|
+
if (propConditions.length === 1) {
|
|
2178
|
+
return propConditions[0];
|
|
2179
|
+
}
|
|
2180
|
+
|
|
2181
|
+
return and(...propConditions);
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2104
2184
|
function buildJsonArrayFilter(
|
|
2105
2185
|
fieldName: string,
|
|
2106
2186
|
field: unknown,
|
|
@@ -2115,7 +2195,7 @@ function buildJsonArrayFilter(
|
|
|
2115
2195
|
const includesValue = readOperatorValue(value, "includes");
|
|
2116
2196
|
if (Array.isArray(includesValue) && includesValue.length > 0) {
|
|
2117
2197
|
const conditions = includesValue.map((v) =>
|
|
2118
|
-
|
|
2198
|
+
buildJsonArrayElementMatchCondition(field, v),
|
|
2119
2199
|
);
|
|
2120
2200
|
filters.push(and(...conditions));
|
|
2121
2201
|
}
|
|
@@ -2123,7 +2203,7 @@ function buildJsonArrayFilter(
|
|
|
2123
2203
|
const includesAnyValue = readOperatorValue(value, "includesAny");
|
|
2124
2204
|
if (Array.isArray(includesAnyValue) && includesAnyValue.length > 0) {
|
|
2125
2205
|
const conditions = includesAnyValue.map((v) =>
|
|
2126
|
-
|
|
2206
|
+
buildJsonArrayElementMatchCondition(field, v),
|
|
2127
2207
|
);
|
|
2128
2208
|
filters.push(sql\`(\${sql.join(conditions, sql\` OR \`)})\`);
|
|
2129
2209
|
}
|
|
@@ -3619,7 +3699,7 @@ type TableFindFirstResult<
|
|
|
3619
3699
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3620
3700
|
(typeof mergedSchema)[TName]
|
|
3621
3701
|
>;
|
|
3622
|
-
`}function He(){return [We(),
|
|
3702
|
+
`}function He(){return [We(),De(),Ve(),Be()].join(`
|
|
3623
3703
|
|
|
3624
3704
|
`)}function Le(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3625
3705
|
const withValue = args?.with;
|
|
@@ -4694,10 +4774,17 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4694
4774
|
},
|
|
4695
4775
|
`}function Ke(){return [Qe(),Ue(),_e(),Le(),ze()].join(`
|
|
4696
4776
|
|
|
4697
|
-
`)}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;
|
|
4698
4781
|
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
4699
|
-
${e.length>0?`type UserRole = ${e.map(
|
|
4700
|
-
type User =
|
|
4782
|
+
${e.length>0?`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;'}
|
|
4701
4788
|
type Session = AuthSession['session']
|
|
4702
4789
|
|
|
4703
4790
|
export type StoragePutArgs = {
|
|
@@ -4916,20 +5003,20 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
4916
5003
|
definition,
|
|
4917
5004
|
};
|
|
4918
5005
|
}
|
|
4919
|
-
`}function Ze(e=[]){return [
|
|
5006
|
+
`}function Ze(e=[],t=[]){return [je(),He(),Ke(),Je(e,t),Ge()].join(`
|
|
4920
5007
|
|
|
4921
|
-
`)}function
|
|
5008
|
+
`)}function Xe(e,t=[],n=[]){return `import type { Context } from "hono";
|
|
4922
5009
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
4923
5010
|
import { drizzle } from "drizzle-orm/d1";
|
|
4924
5011
|
import { z, type ZodRawShape } from "zod";
|
|
4925
5012
|
import * as authSchema from "./auth.schema";
|
|
4926
5013
|
import * as schema from "${e}";
|
|
4927
5014
|
|
|
4928
|
-
${Ze(t)}
|
|
4929
|
-
`}function
|
|
4930
|
-
`)}function
|
|
4931
|
-
`)}function
|
|
4932
|
-
`)}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 `
|
|
4933
5020
|
app.get(
|
|
4934
5021
|
"${t.routePath}",
|
|
4935
5022
|
sValidator("query", ${r}),
|
|
@@ -4942,7 +5029,7 @@ ${Ze(t)}
|
|
|
4942
5029
|
}
|
|
4943
5030
|
},
|
|
4944
5031
|
);`}).join(`
|
|
4945
|
-
`)}function
|
|
5032
|
+
`)}function pr(e){return e.filter(({operation:t})=>t.kind==="mutation").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
4946
5033
|
app.post(
|
|
4947
5034
|
"${t.routePath}",
|
|
4948
5035
|
sValidator("json", ${r}),
|
|
@@ -4957,26 +5044,26 @@ ${Ze(t)}
|
|
|
4957
5044
|
}
|
|
4958
5045
|
},
|
|
4959
5046
|
);`}).join(`
|
|
4960
|
-
`)}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 `
|
|
4961
5048
|
${JSON.stringify(a)}: {
|
|
4962
5049
|
definition: ${n}.definition,
|
|
4963
5050
|
schema: ${r},
|
|
4964
5051
|
},`}).join(`
|
|
4965
|
-
`)}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 `
|
|
4966
5053
|
${JSON.stringify(a)}: {
|
|
4967
5054
|
definition: ${n}.definition,
|
|
4968
5055
|
schema: ${r},
|
|
4969
5056
|
},`}).join(`
|
|
4970
|
-
`)}function
|
|
4971
|
-
`)}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 `
|
|
4972
5059
|
{
|
|
4973
5060
|
taskName: ${JSON.stringify(r)},
|
|
4974
5061
|
cronTriggers: ${JSON.stringify(a)},
|
|
4975
5062
|
definition: ${n}.definition,
|
|
4976
5063
|
},`}).join(`
|
|
4977
|
-
`)}function
|
|
5064
|
+
`)}function yr(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
4978
5065
|
${t}.definition.handler,`).join(`
|
|
4979
|
-
`)}function
|
|
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=`
|
|
4980
5067
|
function getRealtimeStub(
|
|
4981
5068
|
env: Record<string, unknown>,
|
|
4982
5069
|
options: RegisterHandlersOptions,
|
|
@@ -6275,7 +6362,7 @@ export async function executeCronTriggers(
|
|
|
6275
6362
|
}
|
|
6276
6363
|
}
|
|
6277
6364
|
}
|
|
6278
|
-
`;function ct(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:c,cronEntries:l,storageHandlersEntries:u}=
|
|
6365
|
+
`;function ct(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:c,cronEntries:l,storageHandlersEntries:u}=Ye(e);return `import { sValidator } from "@hono/standard-validator";
|
|
6279
6366
|
import type { Hono } from "hono";
|
|
6280
6367
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6281
6368
|
import { ZodError, z } from "zod";
|
|
@@ -6350,9 +6437,9 @@ export function registerGeneratedHandlers(
|
|
|
6350
6437
|
${st}
|
|
6351
6438
|
|
|
6352
6439
|
${ut}
|
|
6353
|
-
`}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?`,
|
|
6354
6441
|
KV: c.env["${e}"] as KVNamespace`:""}function dt(e,t){return `{
|
|
6355
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6442
|
+
DATABASE: c.env["${e}"] as D1Database${br(t)}
|
|
6356
6443
|
}`}function pt(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6357
6444
|
const auth = createAuth(
|
|
6358
6445
|
${dt(t,n)},
|
|
@@ -6360,7 +6447,7 @@ ${ut}
|
|
|
6360
6447
|
);
|
|
6361
6448
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6362
6449
|
});
|
|
6363
|
-
`}function
|
|
6450
|
+
`}function wr(){return `export const getHeaders = (headers: Headers) => {
|
|
6364
6451
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6365
6452
|
const headerObject: Record<string, any> = {};
|
|
6366
6453
|
let hasCookie = false;
|
|
@@ -6390,14 +6477,14 @@ ${ut}
|
|
|
6390
6477
|
|
|
6391
6478
|
return headerObject as any as Headers;
|
|
6392
6479
|
};
|
|
6393
|
-
`}function
|
|
6480
|
+
`}function xr(){return `export const getSanitizedRequest = (req: Request) => {
|
|
6394
6481
|
const newRequest = new Request(req, {
|
|
6395
6482
|
headers: getHeaders(req.headers),
|
|
6396
6483
|
});
|
|
6397
6484
|
return newRequest;
|
|
6398
6485
|
};
|
|
6399
|
-
`}function mt(){return
|
|
6400
|
-
`+
|
|
6486
|
+
`}function mt(){return wr()+`
|
|
6487
|
+
`+xr()}function gt(e,t,n){return pt(e,t,n)+`
|
|
6401
6488
|
`+mt()}function ft(){return `const app = new Hono<WorkerEnv>();
|
|
6402
6489
|
|
|
6403
6490
|
app.use('*', cors({
|
|
@@ -6448,7 +6535,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6448
6535
|
`}function wt(){return `type WorkerEnv = {
|
|
6449
6536
|
Bindings: Record<string, unknown>;
|
|
6450
6537
|
};
|
|
6451
|
-
`}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
|
|
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">
|
|
6452
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">
|
|
6453
6540
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6454
6541
|
<span class="truncate">users</span>
|
|
@@ -6513,7 +6600,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6513
6600
|
</a>
|
|
6514
6601
|
`.replace(/\n/g,"\\n")).join("")}function Nt(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
6515
6602
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6516
|
-
`).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 `
|
|
6517
6604
|
<th>
|
|
6518
6605
|
<a href="#"
|
|
6519
6606
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -6525,7 +6612,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6525
6612
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6526
6613
|
</a>
|
|
6527
6614
|
</th>
|
|
6528
|
-
`}).join("")}function Ct(e,t){return e.map(n=>t&&n===t?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${n} ?? '')}" data-copy-value="\${String((row as any).${n} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${n} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${n} ?? '')}">\${String((row as any).${n} ?? '')}</div></td>`).join("")}function
|
|
6615
|
+
`}).join("")}function Ct(e,t){return e.map(n=>t&&n===t?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${n} ?? '')}" data-copy-value="\${String((row as any).${n} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${n} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${n} ?? '')}">\${String((row as any).${n} ?? '')}</div></td>`).join("")}function Y(e,t,n){let r=e.columns.find(i=>i.name===t);if(!r)return "";let a=r.optional?"":" required",o=r.type==="number"?"number":r.type==="date"?"date":"text";if(r.type==="boolean")return n==="edit"?`
|
|
6529
6616
|
<div class="form-control">
|
|
6530
6617
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6531
6618
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6608,7 +6695,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6608
6695
|
payload.${n} = raw_${n};
|
|
6609
6696
|
}
|
|
6610
6697
|
`}).join(`
|
|
6611
|
-
`)}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">
|
|
6612
6699
|
<div class="drawer drawer-end">
|
|
6613
6700
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6614
6701
|
<div class="drawer-content">
|
|
@@ -6946,7 +7033,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6946
7033
|
title: "${e.tableName} - Admin Dashboard",
|
|
6947
7034
|
children: content
|
|
6948
7035
|
}));
|
|
6949
|
-
});`}function
|
|
7036
|
+
});`}function Et(e,t,n,r,a,o,i,s){let c=r==="number"?`
|
|
6950
7037
|
const parsedId = Number(rawId);
|
|
6951
7038
|
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
6952
7039
|
idValue = parsedId;
|
|
@@ -7079,15 +7166,15 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
7079
7166
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7080
7167
|
});
|
|
7081
7168
|
${u}
|
|
7082
|
-
`}function te(e){let t=qt(e),n=!!t,r=e.columns.map(w=>w.name),a=r.filter(w=>
|
|
7083
|
-
`+
|
|
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)+`
|
|
7170
|
+
`+Et(e.exportName,y,t,v,n,i,p,d)}function Ot(){return `
|
|
7084
7171
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7085
7172
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
7086
7173
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
7087
7174
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
7088
7175
|
const search = params.search ? params.search : '';
|
|
7089
7176
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
7090
|
-
};`}function
|
|
7177
|
+
};`}function jt(){return `
|
|
7091
7178
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7092
7179
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7093
7180
|
<div class="modal">
|
|
@@ -7108,7 +7195,7 @@ ${u}
|
|
|
7108
7195
|
</div>
|
|
7109
7196
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
7110
7197
|
</div>
|
|
7111
|
-
\`}`}function
|
|
7198
|
+
\`}`}function Dt(){return `
|
|
7112
7199
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7113
7200
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7114
7201
|
<div class="modal">
|
|
@@ -7129,7 +7216,7 @@ ${u}
|
|
|
7129
7216
|
</div>
|
|
7130
7217
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
7131
7218
|
</div>
|
|
7132
|
-
\`}`}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(`
|
|
7133
7220
|
`),t=B("/admin/users");return `
|
|
7134
7221
|
const tableHtml = html\`
|
|
7135
7222
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
@@ -7198,8 +7285,8 @@ ${u}
|
|
|
7198
7285
|
</div>
|
|
7199
7286
|
</div>
|
|
7200
7287
|
</div>
|
|
7201
|
-
${Dt()}
|
|
7202
7288
|
${jt()}
|
|
7289
|
+
${Dt()}
|
|
7203
7290
|
</td>
|
|
7204
7291
|
</tr>
|
|
7205
7292
|
\`)}
|
|
@@ -7431,7 +7518,7 @@ ${jt()}
|
|
|
7431
7518
|
|
|
7432
7519
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7433
7520
|
});`}function ne(){return `
|
|
7434
|
-
${
|
|
7521
|
+
${Ot()}
|
|
7435
7522
|
|
|
7436
7523
|
const requireAdminSession = async (c: any) => {
|
|
7437
7524
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7462,9 +7549,9 @@ ${ne()}`}function zt(e){return `
|
|
|
7462
7549
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
7463
7550
|
</div>
|
|
7464
7551
|
</div>
|
|
7465
|
-
`}function
|
|
7552
|
+
`}function Ar(e){return e==="boolean"?"checkbox":e==="number"?"number":"text"}function Nr(e){let t=e.args??[];return t.length===0?`
|
|
7466
7553
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
7467
|
-
`: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?`
|
|
7468
7555
|
<div class="flex items-center gap-3 py-1">
|
|
7469
7556
|
<input
|
|
7470
7557
|
type="checkbox"
|
|
@@ -7493,7 +7580,7 @@ ${ne()}`}function zt(e){return `
|
|
|
7493
7580
|
/>
|
|
7494
7581
|
</div>
|
|
7495
7582
|
`}).join(`
|
|
7496
|
-
`)}function
|
|
7583
|
+
`)}function $r(e){return `
|
|
7497
7584
|
<div class="space-y-4">
|
|
7498
7585
|
<div class="flex items-center justify-between">
|
|
7499
7586
|
<div class="flex flex-col">
|
|
@@ -7506,11 +7593,11 @@ ${ne()}`}function zt(e){return `
|
|
|
7506
7593
|
</label>
|
|
7507
7594
|
</div>
|
|
7508
7595
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
7509
|
-
${
|
|
7596
|
+
${Nr(e)}
|
|
7510
7597
|
</div>
|
|
7511
7598
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7512
7599
|
</div>
|
|
7513
|
-
`}function
|
|
7600
|
+
`}function Cr(){return `
|
|
7514
7601
|
<div class="space-y-4">
|
|
7515
7602
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7516
7603
|
<div class="relative group">
|
|
@@ -7527,7 +7614,7 @@ ${ne()}`}function zt(e){return `
|
|
|
7527
7614
|
</div>
|
|
7528
7615
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
7529
7616
|
</div>
|
|
7530
|
-
`}function
|
|
7617
|
+
`}function qr(){return `
|
|
7531
7618
|
<div class="space-y-4">
|
|
7532
7619
|
<div class="flex items-center justify-between">
|
|
7533
7620
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -7562,13 +7649,13 @@ ${ne()}`}function zt(e){return `
|
|
|
7562
7649
|
<!-- Tab Content -->
|
|
7563
7650
|
<div class="flex-1 overflow-y-auto">
|
|
7564
7651
|
<div id="request-tab-args" class="p-5">
|
|
7565
|
-
${
|
|
7652
|
+
${$r(e)}
|
|
7566
7653
|
</div>
|
|
7567
7654
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
7568
|
-
${
|
|
7655
|
+
${Cr()}
|
|
7569
7656
|
</div>
|
|
7570
7657
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
7571
|
-
${
|
|
7658
|
+
${qr()}
|
|
7572
7659
|
</div>
|
|
7573
7660
|
</div>
|
|
7574
7661
|
|
|
@@ -8434,7 +8521,7 @@ ${ne()}`}function zt(e){return `
|
|
|
8434
8521
|
</div>
|
|
8435
8522
|
\`;
|
|
8436
8523
|
};
|
|
8437
|
-
`}function
|
|
8524
|
+
`}function Xt(){return `
|
|
8438
8525
|
const handleStorageListRoute = async (c: any) => {
|
|
8439
8526
|
const bucket = getStorageBucket(c);
|
|
8440
8527
|
if (!bucket) {
|
|
@@ -8456,7 +8543,7 @@ ${ne()}`}function zt(e){return `
|
|
|
8456
8543
|
|
|
8457
8544
|
adminApp.get('/storage', handleStorageListRoute);
|
|
8458
8545
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
8459
|
-
`}function
|
|
8546
|
+
`}function Yt(){return `
|
|
8460
8547
|
adminApp.post('/storage/upload', async (c) => {
|
|
8461
8548
|
const bucket = getStorageBucket(c);
|
|
8462
8549
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8558,13 +8645,13 @@ ${ne()}`}function zt(e){return `
|
|
|
8558
8645
|
|
|
8559
8646
|
${rn()}
|
|
8560
8647
|
|
|
8561
|
-
${
|
|
8648
|
+
${Yt()}
|
|
8562
8649
|
|
|
8563
8650
|
${en()}
|
|
8564
8651
|
|
|
8565
8652
|
${tn()}
|
|
8566
8653
|
|
|
8567
|
-
${
|
|
8654
|
+
${Xt()}
|
|
8568
8655
|
`}function on(){return `
|
|
8569
8656
|
${Gt()}
|
|
8570
8657
|
|
|
@@ -9051,8 +9138,8 @@ ${p}
|
|
|
9051
9138
|
app.route('/admin', adminApp);
|
|
9052
9139
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
9053
9140
|
}
|
|
9054
|
-
`}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
|
|
9055
|
-
`}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)}: {
|
|
9056
9143
|
${a.map(o=>` ${o}`).join(`
|
|
9057
9144
|
`)}
|
|
9058
9145
|
},`);}return t.length===0?`export const __appflareJsonColumns = {} as const;
|
|
@@ -9060,7 +9147,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9060
9147
|
${t.map(n=>` ${n}`).join(`
|
|
9061
9148
|
`)}
|
|
9062
9149
|
} as const;
|
|
9063
|
-
`}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)}: {
|
|
9064
9151
|
targetTable: ${g(i.targetTable)},
|
|
9065
9152
|
junctionTable: ${g(i.junctionTable)},
|
|
9066
9153
|
sourceField: ${g(i.sourceField??"")},
|
|
@@ -9073,7 +9160,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9073
9160
|
${t.map(n=>` ${n}`).join(`
|
|
9074
9161
|
`)}
|
|
9075
9162
|
} as const;
|
|
9076
|
-
`}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)}: {
|
|
9077
9164
|
kind: "one",
|
|
9078
9165
|
targetTable: ${g(i.targetTable)},
|
|
9079
9166
|
sourceField: ${g(i.field??"")},
|
|
@@ -9099,7 +9186,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9099
9186
|
${t.map(n=>` ${n}`).join(`
|
|
9100
9187
|
`)}
|
|
9101
9188
|
} as const;
|
|
9102
|
-
`}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(
|
|
9103
9190
|
${g(p)},
|
|
9104
9191
|
{
|
|
9105
9192
|
${d.join(`
|
|
@@ -9112,7 +9199,7 @@ ${y.join(`,
|
|
|
9112
9199
|
);`):s.push(`export const ${l} = table(${g(p)}, {
|
|
9113
9200
|
${d.join(`
|
|
9114
9201
|
`)}
|
|
9115
|
-
});`);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}, {
|
|
9116
9203
|
fields: [${l}.${T.sourceField}],
|
|
9117
9204
|
references: [${h.targetTable}.${T.targetField}],
|
|
9118
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 }) => ({
|
|
@@ -9121,7 +9208,7 @@ ${I.join(`
|
|
|
9121
9208
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9122
9209
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
9123
9210
|
import { relations } from "drizzle-orm";
|
|
9124
|
-
${
|
|
9211
|
+
${Hr(r)}
|
|
9125
9212
|
${o.join(`
|
|
9126
9213
|
`)}
|
|
9127
9214
|
${i.join(`
|
|
@@ -9135,12 +9222,12 @@ ${c.join(`
|
|
|
9135
9222
|
|
|
9136
9223
|
`)}
|
|
9137
9224
|
|
|
9138
|
-
${zr(e)}
|
|
9139
|
-
|
|
9140
9225
|
${Ur(e)}
|
|
9141
9226
|
|
|
9142
9227
|
${Qr(e)}
|
|
9143
|
-
|
|
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({
|
|
9144
9231
|
${o.join(`
|
|
9145
9232
|
`)}
|
|
9146
9233
|
});
|
|
@@ -9154,7 +9241,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
9154
9241
|
`);}return `import { z } from "zod";
|
|
9155
9242
|
|
|
9156
9243
|
${t.join(`
|
|
9157
|
-
`)}`}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} = {
|
|
9158
9245
|
${i.join(`
|
|
9159
9246
|
`)}
|
|
9160
9247
|
};
|
|
@@ -9167,23 +9254,25 @@ ${s.join(`
|
|
|
9167
9254
|
${n.join(`
|
|
9168
9255
|
|
|
9169
9256
|
`)}
|
|
9170
|
-
`}function
|
|
9171
|
-
`)
|
|
9172
|
-
`);let
|
|
9173
|
-
`)
|
|
9174
|
-
`),Bun.write(
|
|
9175
|
-
`)
|
|
9176
|
-
`);
|
|
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)}
|
|
9177
9266
|
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-l).toFixed(0)}ms)
|
|
9178
|
-
`);async function
|
|
9179
|
-
`);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)
|
|
9180
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)
|
|
9181
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)
|
|
9182
|
-
`);let
|
|
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)
|
|
9183
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)
|
|
9184
|
-
`);}}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}
|
|
9185
9274
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
9186
|
-
`);}async function
|
|
9187
|
-
`);}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}
|
|
9188
9277
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
9189
|
-
`);}async function
|
|
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);});
|