appflare 0.2.51 → 0.2.53
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/commands/index.ts +33 -25
- package/cli/generate.ts +13 -8
- package/cli/utils/resolve-package.ts +59 -0
- package/dist/cli/index.js +183 -183
- package/dist/cli/index.mjs +183 -183
- package/package.json +68 -23
- package/tsconfig.json +3 -1
- package/tsup.config.ts +0 -2
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
'use strict';var commander=require('commander'),
|
|
2
|
+
'use strict';var commander=require('commander'),Ha=require('chokidar'),path=require('path'),url=require('url'),promises=require('fs/promises'),fs=require('fs'),f=require('typescript'),zod=require('zod');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ha__default=/*#__PURE__*/_interopDefault(Ha);var f__namespace=/*#__PURE__*/_interopNamespace(f);function Re(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";
|
|
@@ -57,7 +57,7 @@ export const createAuth = (
|
|
|
57
57
|
});
|
|
58
58
|
};
|
|
59
59
|
export const auth = createAuth();
|
|
60
|
-
`}function
|
|
60
|
+
`}function ke(){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
61
61
|
import type {
|
|
62
62
|
AppflareAuth,
|
|
63
63
|
AppflareAuthTokenResolver,
|
|
@@ -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 cr(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function Se(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function dr(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function Ae(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 Z(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}${dr(i)}: ${Z(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(`${r}queryKey: ${e.operation.alias}Route(runtime).queryKey,`))),o.push(`${n}}`),o.join(`
|
|
170
|
+
`)}function pr(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=cr(`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:`${Se(e.kind)}${Se(n.join("_"))}`}}function mr(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 (
|
|
@@ -358,15 +358,15 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
358
358
|
schema: ${r},
|
|
359
359
|
run,
|
|
360
360
|
};
|
|
361
|
-
};`}function
|
|
361
|
+
};`}function X(e){let t=e.map((u,l)=>pr(u,l)).filter(u=>u!==null),n=t.filter(u=>u.kind==="query"),r=t.filter(u=>u.kind==="mutation"),a=t.map(u=>`import { ${u.exportName} as ${u.alias} } from "${u.importPath}";`).join(`
|
|
362
362
|
`),o=t.map(u=>{let l=`${u.typeBase}Input`,p=`${u.typeBase}Output`,d=`${u.typeBase}Schema`;return `const ${u.schemaConst} = z.object(${u.alias}.definition.args);
|
|
363
363
|
export type ${l} = z.input<typeof ${u.schemaConst}>;
|
|
364
364
|
export type ${p} = Awaited<ReturnType<typeof ${u.alias}.definition.handler>>;
|
|
365
365
|
export const ${d} = ${u.schemaConst};`}).join(`
|
|
366
366
|
|
|
367
|
-
`),i=t.map(u=>
|
|
367
|
+
`),i=t.map(u=>mr(u)).join(`
|
|
368
368
|
|
|
369
|
-
`),s=
|
|
369
|
+
`),s=Z(Ae(n)),c=Z(Ae(r));return `import { z } from "zod";
|
|
370
370
|
import type {
|
|
371
371
|
AppflareErrorMode,
|
|
372
372
|
AppflareRequestError,
|
|
@@ -742,11 +742,11 @@ export function createMutationsClient(
|
|
|
742
742
|
|
|
743
743
|
export type QueriesClient = ReturnType<typeof createQueriesClient>;
|
|
744
744
|
export type MutationsClient = ReturnType<typeof createMutationsClient>;
|
|
745
|
-
`}function
|
|
745
|
+
`}function Ne(){return `export * from "./types";
|
|
746
746
|
export * from "./appflare";
|
|
747
747
|
export * from "./storage";
|
|
748
748
|
export * from "./handlers";
|
|
749
|
-
`}function
|
|
749
|
+
`}function $e(){return `import type { StorageClient, StorageSignedUrlResponse, StorageListResponse } from "./types";
|
|
750
750
|
|
|
751
751
|
type AuthTokenResolver = (() => string | Promise<string>) | undefined;
|
|
752
752
|
|
|
@@ -938,7 +938,7 @@ export function createStorageClient(
|
|
|
938
938
|
},
|
|
939
939
|
};
|
|
940
940
|
}
|
|
941
|
-
`}function
|
|
941
|
+
`}function Ce(e){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
942
942
|
import type appflareConfig from "${e}";
|
|
943
943
|
|
|
944
944
|
export type AppflareConfig = typeof appflareConfig;
|
|
@@ -1122,7 +1122,7 @@ export type RealtimeSubscriptionResponse = {
|
|
|
1122
1122
|
};
|
|
1123
1123
|
};
|
|
1124
1124
|
};
|
|
1125
|
-
`}function
|
|
1125
|
+
`}function Fe(e,t){return [{relativePath:"client/index.ts",source:Ne()},{relativePath:"client/types.ts",source:Ce(e)},{relativePath:"client/storage.ts",source:$e()},{relativePath:"client/handlers.ts",source:X(t)},{relativePath:"client/appflare.ts",source:ke()}]}function qe(e){return `import { defineConfig } from "drizzle-kit";
|
|
1126
1126
|
|
|
1127
1127
|
export default defineConfig({
|
|
1128
1128
|
dialect: "sqlite",
|
|
@@ -1134,7 +1134,7 @@ export default defineConfig({
|
|
|
1134
1134
|
token: "token",
|
|
1135
1135
|
},
|
|
1136
1136
|
});
|
|
1137
|
-
`}function
|
|
1137
|
+
`}function Me(){return `
|
|
1138
1138
|
|
|
1139
1139
|
import { getHeaders } from "./server";
|
|
1140
1140
|
export async function resolveSession(
|
|
@@ -1168,7 +1168,7 @@ export async function resolveSession(
|
|
|
1168
1168
|
}
|
|
1169
1169
|
}
|
|
1170
1170
|
|
|
1171
|
-
`}function
|
|
1171
|
+
`}function Ee(){return `
|
|
1172
1172
|
type SchedulerQueueBinding = {
|
|
1173
1173
|
send: (body: unknown, options?: SchedulerEnqueueOptions) => Promise<void>;
|
|
1174
1174
|
};
|
|
@@ -1205,7 +1205,7 @@ type R2BucketBinding = {
|
|
|
1205
1205
|
options?: { expiresIn?: number },
|
|
1206
1206
|
) => Promise<URL>;
|
|
1207
1207
|
};
|
|
1208
|
-
`}function
|
|
1208
|
+
`}function je(){return `
|
|
1209
1209
|
export function createScheduler(
|
|
1210
1210
|
queue?: SchedulerQueueBinding,
|
|
1211
1211
|
): Scheduler {
|
|
@@ -1226,7 +1226,7 @@ export function createScheduler(
|
|
|
1226
1226
|
},
|
|
1227
1227
|
};
|
|
1228
1228
|
}
|
|
1229
|
-
`}function
|
|
1229
|
+
`}function Ie(){return `
|
|
1230
1230
|
function createContextErrorHelpers() {
|
|
1231
1231
|
return {
|
|
1232
1232
|
error: (status: number, message: string, details?: unknown) => {
|
|
@@ -1234,7 +1234,7 @@ function createContextErrorHelpers() {
|
|
|
1234
1234
|
},
|
|
1235
1235
|
};
|
|
1236
1236
|
}
|
|
1237
|
-
`}function
|
|
1237
|
+
`}function Pe(){return `
|
|
1238
1238
|
function normalizeStoragePath(path: string): string {
|
|
1239
1239
|
const trimmed = path.trim();
|
|
1240
1240
|
if (trimmed.length === 0) {
|
|
@@ -1369,7 +1369,7 @@ function createStorageApi(
|
|
|
1369
1369
|
},
|
|
1370
1370
|
};
|
|
1371
1371
|
}
|
|
1372
|
-
`}function
|
|
1372
|
+
`}function De(e){return `
|
|
1373
1373
|
export async function createSchedulerExecutionContext(
|
|
1374
1374
|
env: Record<string, unknown>,
|
|
1375
1375
|
options: RegisterHandlersOptions,
|
|
@@ -1467,7 +1467,7 @@ export async function createExecutionContext(
|
|
|
1467
1467
|
ctx.storage = createStorageApi(ctx, storageBucket);
|
|
1468
1468
|
return ctx;
|
|
1469
1469
|
}
|
|
1470
|
-
`}function
|
|
1470
|
+
`}function Ve(e){return `import type { Context } from "hono";
|
|
1471
1471
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
1472
1472
|
import { createAuth } from "./auth.config";
|
|
1473
1473
|
import {
|
|
@@ -1486,20 +1486,20 @@ import {
|
|
|
1486
1486
|
createQueryDb,
|
|
1487
1487
|
} from "./handlers";
|
|
1488
1488
|
|
|
1489
|
-
${Me()}
|
|
1490
|
-
|
|
1491
|
-
${qe()}
|
|
1492
|
-
|
|
1493
1489
|
${Ee()}
|
|
1494
1490
|
|
|
1491
|
+
${Me()}
|
|
1492
|
+
|
|
1495
1493
|
${je()}
|
|
1496
1494
|
|
|
1497
1495
|
${Ie()}
|
|
1498
1496
|
|
|
1497
|
+
${Pe()}
|
|
1498
|
+
|
|
1499
1499
|
${Oe()}
|
|
1500
1500
|
|
|
1501
|
-
${
|
|
1502
|
-
`}function
|
|
1501
|
+
${De(e)}
|
|
1502
|
+
`}function Be(){return `
|
|
1503
1503
|
export async function executeOperation<
|
|
1504
1504
|
TShape extends ZodRawShape,
|
|
1505
1505
|
TResult,
|
|
@@ -1540,7 +1540,7 @@ export function handleOperationError(
|
|
|
1540
1540
|
return c.json({ message: (error as Error).message ?? "Unknown error" }, 500);
|
|
1541
1541
|
}
|
|
1542
1542
|
|
|
1543
|
-
`}function
|
|
1543
|
+
`}function We(){return `import type { Context } from "hono";
|
|
1544
1544
|
import { ZodError, type ZodRawShape } from "zod";
|
|
1545
1545
|
import {
|
|
1546
1546
|
type AppflareContext,
|
|
@@ -1549,8 +1549,8 @@ import {
|
|
|
1549
1549
|
type WorkerEnv,
|
|
1550
1550
|
} from "./handlers";
|
|
1551
1551
|
|
|
1552
|
-
${
|
|
1553
|
-
`}function
|
|
1552
|
+
${Be()}
|
|
1553
|
+
`}function Le(){return `import { betterAuth } from "better-auth";
|
|
1554
1554
|
import { auth } from "./auth.config";
|
|
1555
1555
|
import {
|
|
1556
1556
|
and,
|
|
@@ -1943,7 +1943,7 @@ export type QueryDeleteArgs<TName extends TableName> = {
|
|
|
1943
1943
|
where?: WhereInput<TableModel<TName>, TName>;
|
|
1944
1944
|
limit?: number;
|
|
1945
1945
|
};
|
|
1946
|
-
`}function
|
|
1946
|
+
`}function ze(){return `type AggregateWithInput<TName extends TableName> =
|
|
1947
1947
|
QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1948
1948
|
|
|
1949
1949
|
type NumericFieldKey<TName extends TableName> = NumericModelFieldKey<
|
|
@@ -2075,7 +2075,7 @@ export type DbMutationEvent = {
|
|
|
2075
2075
|
export type QueryDbOptions = {
|
|
2076
2076
|
onMutation?: (event: DbMutationEvent) => void;
|
|
2077
2077
|
};
|
|
2078
|
-
`}function
|
|
2078
|
+
`}function Ue(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2079
2079
|
return typeof value === "object" && value !== null;
|
|
2080
2080
|
}
|
|
2081
2081
|
|
|
@@ -3912,9 +3912,9 @@ type TableFindFirstResult<
|
|
|
3912
3912
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3913
3913
|
(typeof mergedDbSchema)[TName]
|
|
3914
3914
|
>;
|
|
3915
|
-
`}function
|
|
3915
|
+
`}function Qe(){return [_e(),He(),ze(),Ue()].join(`
|
|
3916
3916
|
|
|
3917
|
-
`)}function
|
|
3917
|
+
`)}function Ke(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3918
3918
|
const withValue = args?.with;
|
|
3919
3919
|
const pathSegments = args?.field
|
|
3920
3920
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -4085,7 +4085,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4085
4085
|
},
|
|
4086
4086
|
}) as AppflareQueryDb;
|
|
4087
4087
|
}
|
|
4088
|
-
`}function
|
|
4088
|
+
`}function Je(){return `export class AppflareHandledError extends Error {
|
|
4089
4089
|
public readonly status: number;
|
|
4090
4090
|
public readonly payload: unknown;
|
|
4091
4091
|
|
|
@@ -4095,7 +4095,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4095
4095
|
this.payload = payload;
|
|
4096
4096
|
}
|
|
4097
4097
|
}
|
|
4098
|
-
`}function
|
|
4098
|
+
`}function Ge(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
4099
4099
|
const where = isRecord(args?.where)
|
|
4100
4100
|
? (args?.where as Record<string, unknown>)
|
|
4101
4101
|
: undefined;
|
|
@@ -4249,7 +4249,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4249
4249
|
);
|
|
4250
4250
|
});
|
|
4251
4251
|
},
|
|
4252
|
-
`}function
|
|
4252
|
+
`}function Ze(){return `export function createQueryDb(
|
|
4253
4253
|
$db: AppflareDb,
|
|
4254
4254
|
options?: QueryDbOptions,
|
|
4255
4255
|
): AppflareQueryDb {
|
|
@@ -4291,7 +4291,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4291
4291
|
};
|
|
4292
4292
|
|
|
4293
4293
|
const tableApi = {
|
|
4294
|
-
`}function
|
|
4294
|
+
`}function Xe(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
4295
4295
|
const transaction = ($db as any).transaction;
|
|
4296
4296
|
|
|
4297
4297
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -5246,9 +5246,9 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
5246
5246
|
);
|
|
5247
5247
|
return rows;
|
|
5248
5248
|
},
|
|
5249
|
-
`}function
|
|
5249
|
+
`}function Ye(){return [Ze(),Ge(),Xe(),Ke(),Je()].join(`
|
|
5250
5250
|
|
|
5251
|
-
`)}function
|
|
5251
|
+
`)}function et(e=[],t=[]){let n=t.map(i=>` ${i.name}?: ${i.tsType} | null;`).join(`
|
|
5252
5252
|
`),a=[e.length>0?[" role: UserRole;"," banned: boolean | null;"," banReason?: string | null | undefined;"," banExpires?: Date | null | undefined;"].join(`
|
|
5253
5253
|
`):"",n].filter(Boolean).join(`
|
|
5254
5254
|
`);return `type AuthSession = typeof auth.$Infer.Session;
|
|
@@ -5345,7 +5345,7 @@ export type AppflareContext = {
|
|
|
5345
5345
|
storage: AppflareStorage;
|
|
5346
5346
|
error: (status: number, message: string, details?: unknown) => never;
|
|
5347
5347
|
};
|
|
5348
|
-
`}function
|
|
5348
|
+
`}function tt(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
5349
5349
|
|
|
5350
5350
|
export type SchedulerEnqueueOptions = {
|
|
5351
5351
|
delaySeconds?: number;
|
|
@@ -5477,20 +5477,20 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
5477
5477
|
definition,
|
|
5478
5478
|
};
|
|
5479
5479
|
}
|
|
5480
|
-
`}function
|
|
5480
|
+
`}function nt(e=[],t=[]){return [Le(),Qe(),Ye(),et(e,t),tt()].join(`
|
|
5481
5481
|
|
|
5482
|
-
`)}function
|
|
5482
|
+
`)}function rt(e,t=[],n=[]){return `import type { Context } from "hono";
|
|
5483
5483
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5484
5484
|
import { drizzle } from "drizzle-orm/d1";
|
|
5485
5485
|
import { z, type ZodRawShape } from "zod";
|
|
5486
5486
|
import * as authSchema from "./auth.schema";
|
|
5487
5487
|
import * as schema from "${e}";
|
|
5488
5488
|
|
|
5489
|
-
${
|
|
5490
|
-
`}function
|
|
5491
|
-
`)}function
|
|
5492
|
-
`)}function
|
|
5493
|
-
`)}function
|
|
5489
|
+
${nt(t,n)}
|
|
5490
|
+
`}function fr(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function gr(e,t){let n=e.routePath.replace(/^\//,"").replace(/\//g,"_");return fr(`op_${t}_${n}`)}function hr(e){return e.map((t,n)=>({operation:t,index:n,alias:gr(t,n)}))}function yr(e){return e.map(({operation:t,alias:n})=>`import { ${t.exportName} as ${n} } from "${t.importPath}";`).join(`
|
|
5491
|
+
`)}function br(e){return e.filter(({operation:t})=>t.kind==="query"||t.kind==="mutation").map(({alias:t})=>`const ${`${t}Schema`} = z.object(${t}.definition.args);`).join(`
|
|
5492
|
+
`)}function wr(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(`
|
|
5493
|
+
`)}function xr(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
5494
5494
|
app.get(
|
|
5495
5495
|
"${t.routePath}",
|
|
5496
5496
|
sValidator("query", ${r}),
|
|
@@ -5503,7 +5503,7 @@ import * as schema from "${e}";
|
|
|
5503
5503
|
}
|
|
5504
5504
|
},
|
|
5505
5505
|
);`}).join(`
|
|
5506
|
-
`)}function
|
|
5506
|
+
`)}function Tr(e){return e.filter(({operation:t})=>t.kind==="mutation").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
5507
5507
|
app.post(
|
|
5508
5508
|
"${t.routePath}",
|
|
5509
5509
|
sValidator("json", ${r}),
|
|
@@ -5518,26 +5518,26 @@ import * as schema from "${e}";
|
|
|
5518
5518
|
}
|
|
5519
5519
|
},
|
|
5520
5520
|
);`}).join(`
|
|
5521
|
-
`)}function
|
|
5521
|
+
`)}function vr(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`,a=t.handlerName??t.routePath;return `
|
|
5522
5522
|
${JSON.stringify(a)}: {
|
|
5523
5523
|
definition: ${n}.definition,
|
|
5524
5524
|
schema: ${r},
|
|
5525
5525
|
},`}).join(`
|
|
5526
|
-
`)}function
|
|
5526
|
+
`)}function Rr(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=`${n}SchedulerSchema`,a=t.taskName??`${t.routePath}`;return `
|
|
5527
5527
|
${JSON.stringify(a)}: {
|
|
5528
5528
|
definition: ${n}.definition,
|
|
5529
5529
|
schema: ${r},
|
|
5530
5530
|
},`}).join(`
|
|
5531
|
-
`)}function
|
|
5532
|
-
`)}function
|
|
5531
|
+
`)}function kr(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(`
|
|
5532
|
+
`)}function Sr(e){return e.filter(({operation:t})=>t.kind==="cron").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`,a=t.cronTriggers??[];return `
|
|
5533
5533
|
{
|
|
5534
5534
|
taskName: ${JSON.stringify(r)},
|
|
5535
5535
|
cronTriggers: ${JSON.stringify(a)},
|
|
5536
5536
|
definition: ${n}.definition,
|
|
5537
5537
|
},`}).join(`
|
|
5538
|
-
`)}function
|
|
5538
|
+
`)}function Ar(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
5539
5539
|
${t}.definition.handler,`).join(`
|
|
5540
|
-
`)}function
|
|
5540
|
+
`)}function at(e){let t=hr(e);return {imports:yr(t),operationSchemas:br(t),schedulerSchemas:wr(t),queryRoutes:xr(t),mutationRoutes:Tr(t),queryRegistryEntries:vr(t),schedulerEntries:Rr(t),schedulerPayloadMapEntries:kr(t),cronEntries:Sr(t),storageHandlersEntries:Ar(t)}}var ot=`
|
|
5541
5541
|
function getRealtimeStub(
|
|
5542
5542
|
env: Record<string, unknown>,
|
|
5543
5543
|
options: RegisterHandlersOptions,
|
|
@@ -5611,7 +5611,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
5611
5611
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
5612
5612
|
return url.toString();
|
|
5613
5613
|
}
|
|
5614
|
-
`;var
|
|
5614
|
+
`;var it=`
|
|
5615
5615
|
export class AppflareRealtimeDurableObject {
|
|
5616
5616
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
5617
5617
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -5754,7 +5754,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
5754
5754
|
return new Response("Not found", { status: 404 });
|
|
5755
5755
|
}
|
|
5756
5756
|
}
|
|
5757
|
-
`;var
|
|
5757
|
+
`;var st=`
|
|
5758
5758
|
async function publishMutationEvents(
|
|
5759
5759
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
5760
5760
|
options: RegisterHandlersOptions,
|
|
@@ -5855,7 +5855,7 @@ async function publishMutationEvents(
|
|
|
5855
5855
|
}
|
|
5856
5856
|
}
|
|
5857
5857
|
}
|
|
5858
|
-
`;var
|
|
5858
|
+
`;var lt=`
|
|
5859
5859
|
function registerRealtimeRoutes(
|
|
5860
5860
|
app: Hono<WorkerEnv>,
|
|
5861
5861
|
options: RegisterHandlersOptions,
|
|
@@ -6018,7 +6018,7 @@ function registerRealtimeRoutes(
|
|
|
6018
6018
|
return stub.fetch(c.req.raw);
|
|
6019
6019
|
});
|
|
6020
6020
|
}
|
|
6021
|
-
`;var
|
|
6021
|
+
`;var ut=`
|
|
6022
6022
|
type RealtimeSubscription = {
|
|
6023
6023
|
token: string;
|
|
6024
6024
|
signature: string;
|
|
@@ -6047,7 +6047,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
6047
6047
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
6048
6048
|
? string
|
|
6049
6049
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
6050
|
-
`;var
|
|
6050
|
+
`;var ct=`
|
|
6051
6051
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
6052
6052
|
return typeof value === "object" && value !== null;
|
|
6053
6053
|
}
|
|
@@ -6556,9 +6556,9 @@ function doesSubscriptionMatchMutation(
|
|
|
6556
6556
|
|
|
6557
6557
|
return false;
|
|
6558
6558
|
}
|
|
6559
|
-
`;var
|
|
6559
|
+
`;var dt=[ut,ct,ot,st,lt,it].join(`
|
|
6560
6560
|
|
|
6561
|
-
`);var
|
|
6561
|
+
`);var pt=`
|
|
6562
6562
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
6563
6563
|
if (!value) {
|
|
6564
6564
|
return undefined;
|
|
@@ -6756,7 +6756,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
6756
6756
|
}
|
|
6757
6757
|
});
|
|
6758
6758
|
}
|
|
6759
|
-
`;var
|
|
6759
|
+
`;var mt=`
|
|
6760
6760
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
6761
6761
|
? string
|
|
6762
6762
|
: keyof typeof schedulerHandlers;
|
|
@@ -6820,7 +6820,7 @@ export async function executeScheduledBatch(
|
|
|
6820
6820
|
}
|
|
6821
6821
|
}
|
|
6822
6822
|
}
|
|
6823
|
-
`;var
|
|
6823
|
+
`;var ft=`
|
|
6824
6824
|
export async function executeCronTriggers(
|
|
6825
6825
|
controller: { cron: string },
|
|
6826
6826
|
env: Record<string, unknown>,
|
|
@@ -6854,7 +6854,7 @@ export async function executeCronTriggers(
|
|
|
6854
6854
|
}
|
|
6855
6855
|
}
|
|
6856
6856
|
}
|
|
6857
|
-
`;function
|
|
6857
|
+
`;function gt(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:c,cronEntries:u,storageHandlersEntries:l}=at(e);return `import { sValidator } from "@hono/standard-validator";
|
|
6858
6858
|
import type { Hono } from "hono";
|
|
6859
6859
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6860
6860
|
import { ZodError, z } from "zod";
|
|
@@ -6911,9 +6911,9 @@ const storageHandlers = [${l||`
|
|
|
6911
6911
|
|
|
6912
6912
|
setStorageHandlers([...storageHandlers]);
|
|
6913
6913
|
|
|
6914
|
-
${
|
|
6914
|
+
${mt}
|
|
6915
6915
|
|
|
6916
|
-
${
|
|
6916
|
+
${dt}
|
|
6917
6917
|
|
|
6918
6918
|
export function registerGeneratedHandlers(
|
|
6919
6919
|
app: Hono<WorkerEnv>,
|
|
@@ -6926,20 +6926,20 @@ export function registerGeneratedHandlers(
|
|
|
6926
6926
|
`}
|
|
6927
6927
|
}
|
|
6928
6928
|
|
|
6929
|
-
${
|
|
6929
|
+
${pt}
|
|
6930
6930
|
|
|
6931
|
-
${
|
|
6932
|
-
`}function
|
|
6933
|
-
KV: c.env["${e}"] as KVNamespace`:""}function
|
|
6934
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6935
|
-
}`}function
|
|
6931
|
+
${ft}
|
|
6932
|
+
`}function Y(e,t,n,r=[],a=[]){let o=rt(e,r,a),i=Ve(n),s=We(),c=gt(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 Nr(e){return e?`,
|
|
6933
|
+
KV: c.env["${e}"] as KVNamespace`:""}function ht(e,t){return `{
|
|
6934
|
+
DATABASE: c.env["${e}"] as D1Database${Nr(t)}
|
|
6935
|
+
}`}function yt(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6936
6936
|
const auth = createAuth(
|
|
6937
|
-
${
|
|
6937
|
+
${ht(t,n)},
|
|
6938
6938
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
6939
6939
|
);
|
|
6940
6940
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6941
6941
|
});
|
|
6942
|
-
`}function
|
|
6942
|
+
`}function $r(){return `export const getHeaders = (headers: Headers) => {
|
|
6943
6943
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6944
6944
|
const headerObject: Record<string, any> = {};
|
|
6945
6945
|
let hasCookie = false;
|
|
@@ -6969,15 +6969,15 @@ ${mt}
|
|
|
6969
6969
|
|
|
6970
6970
|
return headerObject as any as Headers;
|
|
6971
6971
|
};
|
|
6972
|
-
`}function
|
|
6972
|
+
`}function Cr(){return `export const getSanitizedRequest = (req: Request) => {
|
|
6973
6973
|
const newRequest = new Request(req, {
|
|
6974
6974
|
headers: getHeaders(req.headers),
|
|
6975
6975
|
});
|
|
6976
6976
|
return newRequest;
|
|
6977
6977
|
};
|
|
6978
|
-
`}function
|
|
6979
|
-
`+
|
|
6980
|
-
`+
|
|
6978
|
+
`}function bt(){return $r()+`
|
|
6979
|
+
`+Cr()}function wt(e,t,n){return yt(e,t,n)+`
|
|
6980
|
+
`+bt()}function xt(){return `const app = new Hono<WorkerEnv>();
|
|
6981
6981
|
|
|
6982
6982
|
app.use('*', cors({
|
|
6983
6983
|
origin: (origin, c) => {
|
|
@@ -6993,7 +6993,7 @@ app.use('*', cors({
|
|
|
6993
6993
|
},
|
|
6994
6994
|
credentials: true
|
|
6995
6995
|
}));
|
|
6996
|
-
`}function
|
|
6996
|
+
`}function Tt(){return `export { AppflareRealtimeDurableObject };
|
|
6997
6997
|
|
|
6998
6998
|
export default {
|
|
6999
6999
|
fetch: app.fetch,
|
|
@@ -7004,7 +7004,7 @@ export default {
|
|
|
7004
7004
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
7005
7005
|
},
|
|
7006
7006
|
};
|
|
7007
|
-
`}function
|
|
7007
|
+
`}function vt(e,t,n="APPFLARE_SCHEDULER_QUEUE",r,a="APPFLARE_REALTIME",o="global",i="/realtime/subscribe",s="/realtime/ws",c="appflare.realtime.v1"){let u=t?`
|
|
7008
7008
|
kvBinding: "${t}",`:"",l=r?`
|
|
7009
7009
|
r2Binding: "${r}",`:"",p=`
|
|
7010
7010
|
realtimeBinding: "${a}",
|
|
@@ -7018,16 +7018,16 @@ export default {
|
|
|
7018
7018
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
7019
7019
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
7020
7020
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
7021
|
-
`}function
|
|
7021
|
+
`}function Rt(){return `import { createAuth } from "./auth.config";
|
|
7022
7022
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
7023
7023
|
import { registerAdminDashboard } from "./admin.routes";
|
|
7024
7024
|
import { Hono } from "hono";
|
|
7025
7025
|
import { cors } from "hono/cors";
|
|
7026
7026
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
7027
|
-
`}function
|
|
7027
|
+
`}function kt(){return `type WorkerEnv = {
|
|
7028
7028
|
Bindings: Record<string, unknown>;
|
|
7029
7029
|
};
|
|
7030
|
-
`}function
|
|
7030
|
+
`}function St(e,t,n,r,a,o,i,s,c,u){return Rt()+kt()+xt()+vt(t,n,r,a,o,i,s,c,u)+wt(e,t,n)+Tt()}function At(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function ee(e,t){let n={...e};for(let[r,a]of Object.entries(t)){let o=n[r];if(At(o)&&At(a)){n[r]=ee(o,a);continue}n[r]=a;}return n}function Fr(e){return Array.from(new Set(e.filter(t=>t.length>0)))}function Nt(e,t){let n=t.filter(d=>d.kind==="scheduler"||d.kind==="cron"),r=Fr(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`,u={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 u;let{scheduler:l,...p}=e.config.wranglerOverrides;return ee(u,p)}function te(e){let t={children:[],handlers:[]};for(let n of e){let r=n.clientSegments??[n.exportName],a=t;for(let o=0;o<r.length-1;o++){let i=r[o],s=a.children.find(c=>c.name===i&&c.type==="folder");s||(s={name:i,type:"folder",children:[],handlers:[]},a.children.push(s)),a=s;}a.handlers.push(n);}return t.children}function $t(e){return e.tables.map(t=>({exportName:t.exportName,tableName:t.tableName,columns:t.columns.map(n=>n.name)}))}function Ct(e){return `<li data-name="users">
|
|
7031
7031
|
<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">
|
|
7032
7032
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
7033
7033
|
<span class="truncate">users</span>
|
|
@@ -7039,14 +7039,14 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
7039
7039
|
<span class="truncate">${n.tableName}</span>
|
|
7040
7040
|
</a>
|
|
7041
7041
|
</li>`).join(`
|
|
7042
|
-
`)}`}function
|
|
7042
|
+
`)}`}function ne(e,t){let n=" ".repeat(t),r=e.children.length>0,a=e.handlers.length>0,o=r||a,i="";if(o){`folder-${e.name.replace(/[^a-zA-Z0-9]/g,"-")}-${t}`;i+=`
|
|
7043
7043
|
${n}<li data-name="${e.name}" class="folder-item">`,i+=`
|
|
7044
7044
|
${n} <details class="group/folder" open>`,i+=`
|
|
7045
7045
|
${n} <summary class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full cursor-pointer list-none">`,i+=`
|
|
7046
7046
|
${n} <iconify-icon icon="solar:folder-bold-duotone" width="16" height="16" class="opacity-50 shrink-0 transition-transform group-open/folder:rotate-0"></iconify-icon>`,i+=`
|
|
7047
7047
|
${n} <span class="truncate font-medium">${e.name}</span>`,i+=`
|
|
7048
7048
|
${n} </summary>`,i+=`
|
|
7049
|
-
${n} <ul class="flex flex-col gap-0.5 ml-4 border-l border-base-200 pl-2">`;for(let c of e.children)i+=
|
|
7049
|
+
${n} <ul class="flex flex-col gap-0.5 ml-4 border-l border-base-200 pl-2">`;for(let c of e.children)i+=ne(c,t+2);for(let c of e.handlers){let u=c.kind==="query"?"solar:reorder-linear":"solar:bolt-linear";i+=`
|
|
7050
7050
|
${n} <li data-name="${c.exportName}">`,i+=`
|
|
7051
7051
|
${n} <a href="/admin/functions${c.routePath}" hx-get="/admin/functions${c.routePath}" 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">`,i+=`
|
|
7052
7052
|
${n} <iconify-icon icon="${u}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
@@ -7061,7 +7061,7 @@ ${n} <a href="/admin/functions${s.routePath}" hx-get="/admin/functions${s.route
|
|
|
7061
7061
|
${n} <iconify-icon icon="${c}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
7062
7062
|
${n} <span class="truncate">${s.exportName}</span>`,i+=`
|
|
7063
7063
|
${n} </a>`,i+=`
|
|
7064
|
-
${n}</li>`;}return i}function
|
|
7064
|
+
${n}</li>`;}return i}function Ft(e){let t=e.filter(s=>s.kind==="query"),n=e.filter(s=>s.kind==="mutation"),r=te(t),a=te(n),o=r.map(s=>ne(s,0)).join(""),i=a.map(s=>ne(s,0)).join("");return `
|
|
7065
7065
|
<div id="pane-functions" class="flex flex-col h-full hidden">
|
|
7066
7066
|
<div class="px-3 pt-5 pb-3">
|
|
7067
7067
|
<p class="text-[10px] font-semibold uppercase tracking-widest opacity-35 mb-3 px-1">Functions</p>
|
|
@@ -7083,7 +7083,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7083
7083
|
<ul class="flex flex-col gap-0.5">${i}</ul>`:""}
|
|
7084
7084
|
</nav>
|
|
7085
7085
|
</div>
|
|
7086
|
-
`}function
|
|
7086
|
+
`}function qt(e){return e.map(t=>`
|
|
7087
7087
|
<a
|
|
7088
7088
|
href="/admin/table/${t.exportName}"
|
|
7089
7089
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
@@ -7100,9 +7100,9 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7100
7100
|
</div>
|
|
7101
7101
|
</div>
|
|
7102
7102
|
</a>
|
|
7103
|
-
`.replace(/\n/g,"\\n")).join("")}function
|
|
7103
|
+
`.replace(/\n/g,"\\n")).join("")}function Mt(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
7104
7104
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
7105
|
-
`).join("")}function
|
|
7105
|
+
`).join("")}function qr(e){switch(e){case "number":return "mdi:pound";case "boolean":return "mdi:toggle-switch-outline";case "date":return "mdi:calendar";case "json":return "mdi:code-braces";default:return "mdi:format-text"}}function Et(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n),a=r?qr(r.type):"mdi:format-text";return `
|
|
7106
7106
|
<th>
|
|
7107
7107
|
<a href="#"
|
|
7108
7108
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -7114,7 +7114,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7114
7114
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
7115
7115
|
</a>
|
|
7116
7116
|
</th>
|
|
7117
|
-
`}).join("")}function
|
|
7117
|
+
`}).join("")}function jt(e,t,n){return t.map(r=>{let a=e.columns.find(o=>o.name===r);return n&&r===n?`<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).${r} ?? '')}" data-copy-value="\${String((row as any).${r} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${r} ?? '')}</button></td>`:a?.type==="json"?`<td>\${raw((() => { const __v = (row as any).${r}; if (__v === null || __v === undefined) return '<span class="opacity-30 text-xs">null</span>'; if (Array.isArray(__v)) { if (__v.length === 0) return '<span class="badge badge-ghost badge-sm font-mono text-xs">[ ]</span>'; return '<div class="flex flex-wrap gap-1 max-w-[200px]">' + __v.slice(0, 3).map((item) => '<span class="badge badge-ghost badge-xs font-mono">' + (typeof item === 'object' && item !== null ? JSON.stringify(item).slice(0, 20) + (JSON.stringify(item).length > 20 ? '\u2026' : '') : String(item ?? '')) + '</span>').join('') + (__v.length > 3 ? '<span class="badge badge-ghost badge-xs opacity-50">+' + (__v.length - 3) + '</span>' : '') + '</div>'; } if (typeof __v === 'object') { const __s = JSON.stringify(__v); return '<span class="badge badge-outline badge-sm font-mono text-[10px]">' + __s.slice(0, 50) + (__s.length > 50 ? '\u2026' : '') + '</span>'; } return String(__v ?? ''); })())}</td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${r} ?? '')}">\${String((row as any).${r} ?? '')}</div></td>`}).join("")}function re(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"?`
|
|
7118
7118
|
<div class="form-control">
|
|
7119
7119
|
<label class="label cursor-pointer justify-start gap-3">
|
|
7120
7120
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -7162,7 +7162,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7162
7162
|
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
7163
7163
|
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm"${a} />
|
|
7164
7164
|
</div>
|
|
7165
|
-
`}function
|
|
7165
|
+
`}function ae(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n);if(!r)return "";let a=r.optional?"":`
|
|
7166
7166
|
if (raw_${n} === '') {
|
|
7167
7167
|
return c.text('${n} is required', 400);
|
|
7168
7168
|
}
|
|
@@ -7217,7 +7217,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7217
7217
|
payload.${n} = raw_${n};
|
|
7218
7218
|
}
|
|
7219
7219
|
`}).join(`
|
|
7220
|
-
`)}function
|
|
7220
|
+
`)}function It(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function Pt(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function Ot(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function Dt(e,t,n,r){return t?`<td class="text-right">
|
|
7221
7221
|
<div class="drawer drawer-end">
|
|
7222
7222
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
7223
7223
|
<div class="drawer-content">
|
|
@@ -7270,7 +7270,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7270
7270
|
</div>
|
|
7271
7271
|
</div>
|
|
7272
7272
|
</div>
|
|
7273
|
-
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function
|
|
7273
|
+
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function H(e){return `
|
|
7274
7274
|
<div class="flex flex-col sm:flex-row justify-between items-center mt-4 gap-3 py-3 px-1">
|
|
7275
7275
|
<div class="text-xs text-base-content/40">
|
|
7276
7276
|
Total found: <span class="font-medium text-base-content/60">\${total}</span>
|
|
@@ -7292,7 +7292,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7292
7292
|
\` : html\`<button class="join-item btn btn-sm btn-ghost btn-disabled"><iconify-icon icon="mdi:chevron-right" width="16" height="16"></iconify-icon></button>\`}
|
|
7293
7293
|
</div>
|
|
7294
7294
|
\` : ''}
|
|
7295
|
-
</div>`}function
|
|
7295
|
+
</div>`}function z(e,t="Search term or filter..."){return `
|
|
7296
7296
|
<div class="form-control w-full md:w-auto relative">
|
|
7297
7297
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
7298
7298
|
<input type="text"
|
|
@@ -7303,7 +7303,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7303
7303
|
hx-trigger="keyup changed delay:500ms, search"
|
|
7304
7304
|
hx-target="#main-content"
|
|
7305
7305
|
class="input input-sm md:input-md input-bordered pl-9 w-full md:w-72 bg-base-200/50 border-base-200 focus:bg-base-100 focus:border-primary transition-all text-sm" />
|
|
7306
|
-
</div>`}function
|
|
7306
|
+
</div>`}function Vt(e,t,n,r,a,o,i,s,c,u){let l=H(`/admin/table/${e.exportName}`),p=z(`/admin/table/${e.exportName}`,"Search term or filter..."),d=r?`<th class="w-10"><input id="select-all-${e.exportName}" type="checkbox" class="checkbox checkbox-xs" /></th>`:'<th class="w-10"><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></th>',y=r?`<td><input type="checkbox" class="checkbox checkbox-xs row-select-checkbox" value="\${String((row as any).${n} ?? '')}" /></td>`:'<td><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></td>',x=r?`
|
|
7307
7307
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
7308
7308
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
7309
7309
|
<div class="text-xs text-base-content/70">
|
|
@@ -7555,7 +7555,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7555
7555
|
title: "${e.tableName} - Admin Dashboard",
|
|
7556
7556
|
children: content
|
|
7557
7557
|
}));
|
|
7558
|
-
});`}function
|
|
7558
|
+
});`}function Bt(e,t,n,r,a,o,i,s){let c=r==="number"?`
|
|
7559
7559
|
const parsedId = Number(rawId);
|
|
7560
7560
|
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
7561
7561
|
idValue = parsedId;
|
|
@@ -7688,15 +7688,15 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7688
7688
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7689
7689
|
});
|
|
7690
7690
|
${l}
|
|
7691
|
-
`}function
|
|
7692
|
-
`+
|
|
7691
|
+
`}function oe(e){let t=It(e),n=!!t,r=e.columns.map(w=>w.name),a=r.filter(w=>Pt(e,w)),o=r.filter(w=>Ot(e,w)),i=Mt(e),s=Et(e,r),c=jt(e,r,t),u=a.map(w=>re(e,w,"create")).join(""),l=o.map(w=>re(e,w,"edit")).join(""),p=ae(e,a),d=ae(e,o),y=n?t:r[0]||"id",x=e.columns.find(w=>w.name===t)?.type,S=Dt(e,n,t,l);return Vt(e,y,t,n,r,i,s,c,S,u)+`
|
|
7692
|
+
`+Bt(e.exportName,y,t,x,n,i,p,d)}function Wt(){return `
|
|
7693
7693
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7694
7694
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
7695
7695
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
7696
7696
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
7697
7697
|
const search = params.search ? params.search : '';
|
|
7698
7698
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
7699
|
-
};`}function
|
|
7699
|
+
};`}function Lt(){return `
|
|
7700
7700
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7701
7701
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7702
7702
|
<div class="modal">
|
|
@@ -7738,8 +7738,8 @@ ${l}
|
|
|
7738
7738
|
</div>
|
|
7739
7739
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
7740
7740
|
</div>
|
|
7741
|
-
\`}`}var
|
|
7742
|
-
`),t=
|
|
7741
|
+
\`}`}var Mr=["id","name","email","role","createdAt","banned"],Er={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function jr(e){let t=Er[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 zt(){let e=Mr.map(jr).join(`
|
|
7742
|
+
`),t=H("/admin/users");return `
|
|
7743
7743
|
const tableHtml = html\`
|
|
7744
7744
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
7745
7745
|
<div class="overflow-x-auto">
|
|
@@ -7807,7 +7807,7 @@ ${l}
|
|
|
7807
7807
|
</div>
|
|
7808
7808
|
</div>
|
|
7809
7809
|
</div>
|
|
7810
|
-
${
|
|
7810
|
+
${Lt()}
|
|
7811
7811
|
${Ht()}
|
|
7812
7812
|
</td>
|
|
7813
7813
|
</tr>
|
|
@@ -7824,7 +7824,7 @@ ${Ht()}
|
|
|
7824
7824
|
${t}
|
|
7825
7825
|
</div>
|
|
7826
7826
|
\`;
|
|
7827
|
-
`}function
|
|
7827
|
+
`}function Ut(){return `
|
|
7828
7828
|
const content = html\`
|
|
7829
7829
|
<div id="main-content">
|
|
7830
7830
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -7836,11 +7836,11 @@ ${Ht()}
|
|
|
7836
7836
|
<iconify-icon icon="mdi:refresh" width="14" height="14"></iconify-icon>
|
|
7837
7837
|
</button>
|
|
7838
7838
|
</div>
|
|
7839
|
-
${
|
|
7839
|
+
${z("/admin/users","Search users...")}
|
|
7840
7840
|
</div>
|
|
7841
7841
|
\${tableHtml}
|
|
7842
7842
|
</div>
|
|
7843
|
-
\`;`}function _t(){let e=
|
|
7843
|
+
\`;`}function _t(){let e=zt(),t=Ut();return `
|
|
7844
7844
|
adminApp.get('/users', async (c) => {
|
|
7845
7845
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
7846
7846
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7896,7 +7896,7 @@ ${Ht()}
|
|
|
7896
7896
|
title: "users - Admin Dashboard",
|
|
7897
7897
|
children: content,
|
|
7898
7898
|
}));
|
|
7899
|
-
});`}function
|
|
7899
|
+
});`}function Qt(){return `
|
|
7900
7900
|
adminApp.post('/users/edit', async (c) => {
|
|
7901
7901
|
const session = await requireAdminSession(c);
|
|
7902
7902
|
if (!session) {
|
|
@@ -8039,8 +8039,8 @@ ${Ht()}
|
|
|
8039
8039
|
const resolvedPage = String(Math.min(nextPageCandidate, totalPages));
|
|
8040
8040
|
|
|
8041
8041
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
8042
|
-
});`}function
|
|
8043
|
-
${
|
|
8042
|
+
});`}function ie(){return `
|
|
8043
|
+
${Wt()}
|
|
8044
8044
|
|
|
8045
8045
|
const requireAdminSession = async (c: any) => {
|
|
8046
8046
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -8053,10 +8053,10 @@ ${Ht()}
|
|
|
8053
8053
|
|
|
8054
8054
|
${_t()}
|
|
8055
8055
|
|
|
8056
|
-
${
|
|
8057
|
-
`}function
|
|
8056
|
+
${Qt()}
|
|
8057
|
+
`}function Kt(e){return `${e.tables.map(t=>oe(t)).join(`
|
|
8058
8058
|
`)}
|
|
8059
|
-
${
|
|
8059
|
+
${ie()}`}function Jt(e){return `
|
|
8060
8060
|
<div class="flex items-center justify-between">
|
|
8061
8061
|
<div class="flex items-center gap-3">
|
|
8062
8062
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -8071,7 +8071,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
8071
8071
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
8072
8072
|
</div>
|
|
8073
8073
|
</div>
|
|
8074
|
-
`}var
|
|
8074
|
+
`}var Ir="input input-xs input-bordered font-mono flex-1 bg-base-200/30 focus:bg-base-100 focus:border-primary transition-all rounded-lg border-base-200";function Pr(e){return e.map(t=>{let n=t.type!=="unknown"?`<span class="badge badge-xs badge-ghost font-mono opacity-25 ml-1">${t.type}</span>`:"";if(t.type==="boolean")return `
|
|
8075
8075
|
<div class="flex items-center gap-2">
|
|
8076
8076
|
<input
|
|
8077
8077
|
type="checkbox"
|
|
@@ -8090,10 +8090,10 @@ ${oe()}`}function Kt(e){return `
|
|
|
8090
8090
|
data-obj-field-type="${t.type}"
|
|
8091
8091
|
placeholder="${t.defaultValue??""}"
|
|
8092
8092
|
value="${t.defaultValue??""}"
|
|
8093
|
-
class="${
|
|
8093
|
+
class="${Ir}"
|
|
8094
8094
|
/>
|
|
8095
8095
|
</div>`}).join(`
|
|
8096
|
-
`)}function
|
|
8096
|
+
`)}function Or(e){let t=e.args??[];if(t.length===0)return `
|
|
8097
8097
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
8098
8098
|
`;let n="input input-sm input-bordered font-mono w-full bg-base-200/30 focus:bg-base-100 focus:border-primary transition-all rounded-xl border-base-200";return t.map(r=>{let a=`${r.name}${r.optional?"":" *"}`,o=r.type!=="unknown"?`<span class="badge badge-xs badge-ghost font-mono opacity-40 ml-1">${r.type}</span>`:"",i=r.optional?'<span class="label-text-alt text-[10px] opacity-30 italic">optional</span>':"",s=`
|
|
8099
8099
|
<label class="label py-0.5">
|
|
@@ -8118,7 +8118,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
8118
8118
|
data-arg-type="object"
|
|
8119
8119
|
class="border border-base-200 rounded-xl p-3 bg-base-200/20 flex flex-col gap-2"
|
|
8120
8120
|
>
|
|
8121
|
-
${
|
|
8121
|
+
${Pr(r.fields)}
|
|
8122
8122
|
</div>
|
|
8123
8123
|
</div>`:`
|
|
8124
8124
|
<div class="form-control">
|
|
@@ -8162,7 +8162,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
8162
8162
|
${r.optional?"":"required"}
|
|
8163
8163
|
/>
|
|
8164
8164
|
</div>`}).join(`
|
|
8165
|
-
`)}function
|
|
8165
|
+
`)}function Dr(e){return `
|
|
8166
8166
|
<div class="space-y-4">
|
|
8167
8167
|
<div class="flex items-center justify-between">
|
|
8168
8168
|
<div class="flex flex-col">
|
|
@@ -8175,11 +8175,11 @@ ${oe()}`}function Kt(e){return `
|
|
|
8175
8175
|
</label>
|
|
8176
8176
|
</div>
|
|
8177
8177
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
8178
|
-
${
|
|
8178
|
+
${Or(e)}
|
|
8179
8179
|
</div>
|
|
8180
8180
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
8181
8181
|
</div>
|
|
8182
|
-
`}function
|
|
8182
|
+
`}function Vr(){return `
|
|
8183
8183
|
<div class="space-y-4">
|
|
8184
8184
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
8185
8185
|
<div class="relative group">
|
|
@@ -8196,7 +8196,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
8196
8196
|
</div>
|
|
8197
8197
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
8198
8198
|
</div>
|
|
8199
|
-
`}function
|
|
8199
|
+
`}function Br(){return `
|
|
8200
8200
|
<div class="space-y-4">
|
|
8201
8201
|
<div class="flex items-center justify-between">
|
|
8202
8202
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -8210,7 +8210,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
8210
8210
|
</div>
|
|
8211
8211
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
8212
8212
|
</div>
|
|
8213
|
-
`}function
|
|
8213
|
+
`}function Gt(e){return `
|
|
8214
8214
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
8215
8215
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
8216
8216
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -8231,13 +8231,13 @@ ${oe()}`}function Kt(e){return `
|
|
|
8231
8231
|
<!-- Tab Content -->
|
|
8232
8232
|
<div class="flex-1 overflow-y-auto">
|
|
8233
8233
|
<div id="request-tab-args" class="p-5">
|
|
8234
|
-
${
|
|
8234
|
+
${Dr(e)}
|
|
8235
8235
|
</div>
|
|
8236
8236
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
8237
|
-
${
|
|
8237
|
+
${Vr()}
|
|
8238
8238
|
</div>
|
|
8239
8239
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
8240
|
-
${
|
|
8240
|
+
${Br()}
|
|
8241
8241
|
</div>
|
|
8242
8242
|
</div>
|
|
8243
8243
|
|
|
@@ -8255,7 +8255,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
8255
8255
|
</form>
|
|
8256
8256
|
</div>
|
|
8257
8257
|
</div>
|
|
8258
|
-
`}function
|
|
8258
|
+
`}function Zt(){return `
|
|
8259
8259
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
8260
8260
|
<!-- Panel Header -->
|
|
8261
8261
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -8337,7 +8337,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
8337
8337
|
|
|
8338
8338
|
</div>
|
|
8339
8339
|
</div>
|
|
8340
|
-
`}function
|
|
8340
|
+
`}function Xt(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
8341
8341
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
8342
8342
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
8343
8343
|
|
|
@@ -9028,21 +9028,21 @@ ${oe()}`}function Kt(e){return `
|
|
|
9028
9028
|
_rtEnabled = false;
|
|
9029
9029
|
});
|
|
9030
9030
|
</script>
|
|
9031
|
-
`}function
|
|
9031
|
+
`}function Yt(e){return `
|
|
9032
9032
|
const content = html\`
|
|
9033
9033
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
9034
|
-
${
|
|
9034
|
+
${Jt(e)}
|
|
9035
9035
|
|
|
9036
9036
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
9037
9037
|
<!-- Request Panel -->
|
|
9038
|
-
${
|
|
9038
|
+
${Gt(e)}
|
|
9039
9039
|
|
|
9040
9040
|
<!-- Result Panel -->
|
|
9041
|
-
${
|
|
9041
|
+
${Zt()}
|
|
9042
9042
|
</div>
|
|
9043
9043
|
</div>
|
|
9044
9044
|
|
|
9045
|
-
${
|
|
9045
|
+
${Xt(e)}
|
|
9046
9046
|
\`;
|
|
9047
9047
|
|
|
9048
9048
|
if (c.req.header('hx-request')) {
|
|
@@ -9052,11 +9052,11 @@ ${oe()}`}function Kt(e){return `
|
|
|
9052
9052
|
return c.html(Layout({
|
|
9053
9053
|
title: "${e.exportName} - Functions",
|
|
9054
9054
|
children: content
|
|
9055
|
-
}));`}function
|
|
9055
|
+
}));`}function en(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
9056
9056
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
9057
|
-
${
|
|
9057
|
+
${Yt(n)}
|
|
9058
9058
|
});`).join(`
|
|
9059
|
-
`)}function
|
|
9059
|
+
`)}function tn(){return `
|
|
9060
9060
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
9061
9061
|
const r2Binding = (options as any).r2Binding;
|
|
9062
9062
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -9125,7 +9125,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
9125
9125
|
const parts = prefix.split('/').filter(Boolean);
|
|
9126
9126
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
9127
9127
|
};
|
|
9128
|
-
`}function
|
|
9128
|
+
`}function nn(){return `
|
|
9129
9129
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
9130
9130
|
const parts = prefix.split('/').filter(Boolean);
|
|
9131
9131
|
const breadcrumbs: any[] = [];
|
|
@@ -9252,7 +9252,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
9252
9252
|
</div>
|
|
9253
9253
|
\`;
|
|
9254
9254
|
};
|
|
9255
|
-
`}function
|
|
9255
|
+
`}function rn(){return `
|
|
9256
9256
|
const handleStorageListRoute = async (c: any) => {
|
|
9257
9257
|
const bucket = getStorageBucket(c);
|
|
9258
9258
|
if (!bucket) {
|
|
@@ -9274,7 +9274,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
9274
9274
|
|
|
9275
9275
|
adminApp.get('/storage', handleStorageListRoute);
|
|
9276
9276
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
9277
|
-
`}function
|
|
9277
|
+
`}function an(){return `
|
|
9278
9278
|
adminApp.post('/storage/upload', async (c) => {
|
|
9279
9279
|
const bucket = getStorageBucket(c);
|
|
9280
9280
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9292,7 +9292,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
9292
9292
|
|
|
9293
9293
|
return c.redirect(prefixToStoragePath(prefix));
|
|
9294
9294
|
});
|
|
9295
|
-
`}function
|
|
9295
|
+
`}function on(){return `
|
|
9296
9296
|
adminApp.delete('/storage/delete', async (c) => {
|
|
9297
9297
|
const bucket = getStorageBucket(c);
|
|
9298
9298
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9307,7 +9307,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
9307
9307
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
9308
9308
|
return c.html('');
|
|
9309
9309
|
});
|
|
9310
|
-
`}function
|
|
9310
|
+
`}function sn(){return `
|
|
9311
9311
|
adminApp.post('/storage/directory', async (c) => {
|
|
9312
9312
|
const bucket = getStorageBucket(c);
|
|
9313
9313
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9333,7 +9333,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
9333
9333
|
|
|
9334
9334
|
return c.redirect(prefixToStoragePath(prefix));
|
|
9335
9335
|
});
|
|
9336
|
-
`}function
|
|
9336
|
+
`}function ln(){return `
|
|
9337
9337
|
adminApp.get('/storage/download', async (c) => {
|
|
9338
9338
|
const bucket = getStorageBucket(c);
|
|
9339
9339
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9353,7 +9353,7 @@ ${oe()}`}function Kt(e){return `
|
|
|
9353
9353
|
|
|
9354
9354
|
return new Response(object.body, { headers });
|
|
9355
9355
|
});
|
|
9356
|
-
`}function
|
|
9356
|
+
`}function un(){return `
|
|
9357
9357
|
adminApp.get('/storage/preview', async (c) => {
|
|
9358
9358
|
const bucket = getStorageBucket(c);
|
|
9359
9359
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9371,25 +9371,25 @@ ${oe()}`}function Kt(e){return `
|
|
|
9371
9371
|
|
|
9372
9372
|
return new Response(object.body, { headers });
|
|
9373
9373
|
});
|
|
9374
|
-
`}function
|
|
9375
|
-
${sn()}
|
|
9376
|
-
|
|
9374
|
+
`}function cn(){return `
|
|
9377
9375
|
${ln()}
|
|
9378
9376
|
|
|
9379
|
-
${
|
|
9377
|
+
${un()}
|
|
9380
9378
|
|
|
9381
9379
|
${an()}
|
|
9382
9380
|
|
|
9383
9381
|
${on()}
|
|
9384
9382
|
|
|
9385
|
-
${
|
|
9386
|
-
`}function cn(){return `
|
|
9387
|
-
${en()}
|
|
9383
|
+
${sn()}
|
|
9388
9384
|
|
|
9385
|
+
${rn()}
|
|
9386
|
+
`}function dn(){return `
|
|
9389
9387
|
${tn()}
|
|
9390
9388
|
|
|
9391
|
-
${
|
|
9392
|
-
|
|
9389
|
+
${nn()}
|
|
9390
|
+
|
|
9391
|
+
${cn()}
|
|
9392
|
+
`}function pn(e,t){let n=Ft(t);return `
|
|
9393
9393
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
9394
9394
|
return html\`<!DOCTYPE html>
|
|
9395
9395
|
<html lang="en" data-theme="light">
|
|
@@ -9796,7 +9796,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9796
9796
|
</body>
|
|
9797
9797
|
</html>\`;
|
|
9798
9798
|
}
|
|
9799
|
-
`}function
|
|
9799
|
+
`}function mn(){return `
|
|
9800
9800
|
// Auth Middleware
|
|
9801
9801
|
adminApp.use('*', async (c, next) => {
|
|
9802
9802
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -9855,7 +9855,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9855
9855
|
}
|
|
9856
9856
|
await next();
|
|
9857
9857
|
});
|
|
9858
|
-
`}function
|
|
9858
|
+
`}function fn(e){return `
|
|
9859
9859
|
adminApp.get('/', (c) => {
|
|
9860
9860
|
return c.html(Layout({
|
|
9861
9861
|
title: "Admin Dashboard",
|
|
@@ -9872,7 +9872,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9872
9872
|
\`
|
|
9873
9873
|
}));
|
|
9874
9874
|
});
|
|
9875
|
-
`}function
|
|
9875
|
+
`}function gn(e,t,n){let r=$t(t),a=Ct(r),o=qt(r),i=Kt(t),s=en(n),c=dn(),u=pn(a,n),l=mn(),p=fn(o);return `import { Hono } from "hono";
|
|
9876
9876
|
import { html, raw } from "hono/html";
|
|
9877
9877
|
import { drizzle } from "drizzle-orm/d1";
|
|
9878
9878
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -9901,8 +9901,8 @@ ${p}
|
|
|
9901
9901
|
app.route('/admin', adminApp);
|
|
9902
9902
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
9903
9903
|
}
|
|
9904
|
-
`}function
|
|
9905
|
-
`}function
|
|
9904
|
+
`}function se(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 D(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function E(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(t,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(t,n)=>n.toUpperCase())}function ce(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 Lr(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());if(typeof e=="object"&&e!==null)return JSON.stringify(e);throw new Error(`Unsupported SQL default value '${String(e)}'. Use string, number, boolean, null, Date, array, or object.`)}function Hr(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 U(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function hn(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 yn(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 bn(e,t){return `${e}:${t}`}function zr(e,t,n,r){let a=bn(e,t),o=bn(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 Ur(e,t){return `${e}${E(t)}Links`}function wn(e,t,n){let r=ce(e),a=ce(t);return r===a?`${n}${E(r)}Id`:`${r}Id`}function _r(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 Qr(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=zr(n,o,a.targetTable,i),c=wn(s.leftTable,s.rightTable,"source"),u=wn(s.rightTable,s.leftTable,"target"),l={leftTable:s.leftTable,leftReferenceField:s.leftReferenceField,rightTable:s.rightTable,rightReferenceField:s.rightReferenceField,junctionTable:a.junctionTable??Ur(s.leftTable,s.rightTable),leftField:s.sourceIsLeft?a.sourceField??c:a.targetField??c,rightField:s.sourceIsLeft?a.targetField??u:a.sourceField??u,leftSqlName:s.sourceIsLeft?a.sourceSqlName:a.targetSqlName,rightSqlName:s.sourceIsLeft?a.targetSqlName:a.sourceSqlName,onDelete:a.onDelete,onUpdate:a.onUpdate};if(l.leftField===l.rightField)throw new Error(`manyToMany pair '${s.key}' resolves to duplicate junction fields '${l.leftField}'. Set sourceField/targetField explicitly.`);let p=t.get(s.key);p?_r(p,l,s.key):t.set(s.key,l),a.referenceField=o,a.targetReferenceField=i,a.junctionTable=l.junctionTable,a.sourceField=s.sourceIsLeft?l.leftField:l.rightField,a.targetField=s.sourceIsLeft?l.rightField:l.leftField,a.sourceSqlName=s.sourceIsLeft?l.leftSqlName:l.rightSqlName,a.targetSqlName=s.sourceIsLeft?l.rightSqlName:l.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=U(e,n.leftTable,n.leftReferenceField)??"string",a=U(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 Kr(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 Jr(e){Kr(e);let t=Hr(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=U(t,o.targetTable,i)??o.fkType??"string";hn(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:yn(`${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??`${ce(n)}Id`;a.field=s;let c=U(t,n,i)??a.fkType??"string";hn(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:yn(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},c);}return Qr(t),t}function Tn(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function V(e){return e.notNull!==true}function Gr(e,t,n){let r=t.sqlName??D(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=_(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 Zr(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 Xr(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
9905
|
+
`}function Yr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function ea(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 ta(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=de(i.jsonShape);a.push(`${g(o)}: { shape: ${s} },`);}a.length!==0&&t.push(`${g(n)}: {
|
|
9906
9906
|
${a.map(o=>` ${o}`).join(`
|
|
9907
9907
|
`)}
|
|
9908
9908
|
},`);}return t.length===0?`export const __appflareJsonColumns = {} as const;
|
|
@@ -9910,7 +9910,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9910
9910
|
${t.map(n=>` ${n}`).join(`
|
|
9911
9911
|
`)}
|
|
9912
9912
|
} as const;
|
|
9913
|
-
`}function
|
|
9913
|
+
`}function de(e){return e.kind==="array"?`{ kind: "array", element: ${de(e.element)} }`:e.kind==="object"?`{ kind: "object", shape: { ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${de(r)}`).join(", ")} } }`:`{ kind: ${g(e.kind)} }`}function na(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)}: {
|
|
9914
9914
|
targetTable: ${g(i.targetTable)},
|
|
9915
9915
|
junctionTable: ${g(i.junctionTable)},
|
|
9916
9916
|
sourceField: ${g(i.sourceField??"")},
|
|
@@ -9925,7 +9925,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9925
9925
|
${t.map(n=>` ${n}`).join(`
|
|
9926
9926
|
`)}
|
|
9927
9927
|
} as const;
|
|
9928
|
-
`}function
|
|
9928
|
+
`}function ra(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)}: {
|
|
9929
9929
|
kind: "one",
|
|
9930
9930
|
targetTable: ${g(i.targetTable)},
|
|
9931
9931
|
sourceField: ${g(i.field??"")},
|
|
@@ -9951,7 +9951,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9951
9951
|
${t.map(n=>` ${n}`).join(`
|
|
9952
9952
|
`)}
|
|
9953
9953
|
} as const;
|
|
9954
|
-
`}function
|
|
9954
|
+
`}function aa(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let l of Object.values(e.tables)){for(let p of Yr(l))n.has(p)||r.add(p);for(let p of Object.values(l.columns))p.references&&!n.has(p.references.table)&&r.add(p.references.table);}let a=new Map;for(let[l,p]of Object.entries(e.tables))for(let[d,y]of Object.entries(p.columns))if(y.type==="enum"&&y.enumValues&&y.enumValues.length>0){let x=y.enumRef??`${l}_${d}`;a.has(x)||a.set(x,{column:y,tableName:l,fieldName:d});}let o=[],i=[];for(let[l,p]of a.entries()){let d=E(l),y=p.column.enumValues.map(x=>`"${x}"`).join(" | ");o.push(`export type ${d} = ${y};`),i.push(`export const ${d}Column = t.customType<{ data: ${d}; dataNotNull: ${d} }>({ dataType: () => "text" });`);}let s=[],c=[],u=[];for(let[l,p]of Object.entries(e.tables)){let d=p.sqlName??D(l),y=[],x=[];u.push(` ${l},`);for(let[b,h]of Object.entries(p.columns)){let v;if(h.type==="enum"&&h.enumValues&&h.enumValues.length>0){let R=h.enumRef??`${l}_${b}`,P=E(R),L=h.sqlName??D(b);v=L!==b?`${P}Column(${g(L)})`:`${P}Column()`,h.isArray&&(v+=".array()");}else v=Gr(b,h,t);h.uuidPrimaryKey&&(v+=".$defaultFn(() => crypto.randomUUID())"),h.primaryKey&&(v+=h.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),h.notNull&&(v+=".notNull()"),h.sqlDefault!==void 0&&(v+=`.default(${Lr(h.sqlDefault)})`);let F=ea(b,h,p);if(F)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)}`),v+=`.references((): AnySQLiteColumn => ${F.tableName}.${F.fieldName}, { ${R.join(", ")} })`;}else v+=`.references((): AnySQLiteColumn => ${F.tableName}.${F.fieldName})`;if(h.unique){let R=typeof h.unique=="object"&&h.unique.name?h.unique.name:`${d}_${D(b)}_unique_idx`;x.push(` t.uniqueIndex(${g(R)}).on(table.${b})`);}if(h.index){let R=typeof h.index=="object"&&h.index.name?h.index.name:`${d}_${D(b)}_idx`;x.push(` t.index(${g(R)}).on(table.${b})`);}y.push(` ${b}: ${v},`);}x.length>0?s.push(`export const ${l} = table(
|
|
9955
9955
|
${g(d)},
|
|
9956
9956
|
{
|
|
9957
9957
|
${y.join(`
|
|
@@ -9964,16 +9964,16 @@ ${x.join(`,
|
|
|
9964
9964
|
);`):s.push(`export const ${l} = table(${g(d)}, {
|
|
9965
9965
|
${y.join(`
|
|
9966
9966
|
`)}
|
|
9967
|
-
});`);let
|
|
9967
|
+
});`);let S=Object.entries(p.relations).filter(([,b])=>b.relation==="one"),w=Object.entries(p.relations).filter(([,b])=>b.relation==="many"),q=Object.entries(p.relations).filter(([,b])=>b.relation==="manyToMany");if(S.length===0&&w.length===0&&q.length===0)continue;let $=[];for(let[b,h]of S){let v=Zr(l,p,h);$.push(` ${b}: one(${h.targetTable}, {
|
|
9968
9968
|
fields: [${l}.${v.sourceField}],
|
|
9969
9969
|
references: [${h.targetTable}.${v.targetField}],
|
|
9970
|
-
}),`);}for(let[b,h]of w)
|
|
9971
|
-
${
|
|
9970
|
+
}),`);}for(let[b,h]of w)$.push(` ${b}: many(${h.targetTable}),`);for(let[b,h]of q){if(!h.junctionTable)throw new Error(`manyToMany relation '${l}.${b}' is missing junctionTable after normalization.`);$.push(` ${b}: many(${h.junctionTable}),`);}c.push(`export const ${l}Relations = relations(${l}, ({ one, many }) => ({
|
|
9971
|
+
${$.join(`
|
|
9972
9972
|
`)}
|
|
9973
9973
|
}));`),u.push(` ${l}Relations,`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9974
9974
|
import { sqliteTable as table, type AnySQLiteColumn } from "drizzle-orm/sqlite-core";
|
|
9975
9975
|
import { relations } from "drizzle-orm";
|
|
9976
|
-
${
|
|
9976
|
+
${Xr(r)}
|
|
9977
9977
|
${o.join(`
|
|
9978
9978
|
`)}
|
|
9979
9979
|
${i.join(`
|
|
@@ -9992,12 +9992,12 @@ ${u.join(`
|
|
|
9992
9992
|
`)}
|
|
9993
9993
|
} as const;
|
|
9994
9994
|
|
|
9995
|
-
${
|
|
9995
|
+
${ta(e)}
|
|
9996
9996
|
|
|
9997
|
-
${
|
|
9997
|
+
${na(e)}
|
|
9998
9998
|
|
|
9999
|
-
${
|
|
10000
|
-
`}function
|
|
9999
|
+
${ra(e)}
|
|
10000
|
+
`}function pe(e){return e.kind==="array"?`z.array(${pe(e.element)})`:e.kind==="object"?`z.object({ ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${pe(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 xn(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=pe(e.jsonShape));return t&&(r+=".optional()"),n&&(r+=".nullable()"),r}function oa(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=E(n),o=[],i=[];for(let[s,c]of Object.entries(r.columns))o.push(` ${s}: ${xn(c,Tn(c),V(c))},`),i.push(` ${s}: ${xn(c,V(c),V(c))},`);t.push(`export const ${n}InsertSchema = z.object({
|
|
10001
10001
|
${o.join(`
|
|
10002
10002
|
`)}
|
|
10003
10003
|
});
|
|
@@ -10011,7 +10011,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
10011
10011
|
`);}return `import { z } from "zod";
|
|
10012
10012
|
|
|
10013
10013
|
${t.join(`
|
|
10014
|
-
`)}`}function
|
|
10014
|
+
`)}`}function _(e){return e.kind==="array"?`Array<${_(e.element)}>`:e.kind==="object"?`{ ${Object.entries(e.shape).map(([n,r])=>`${n}: ${_(r)}`).join("; ")} }`:e.kind==="string"?"string":e.kind==="number"?"number":e.kind==="boolean"?"boolean":e.kind==="date"?"Date":"unknown"}function ia(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?_(e.jsonShape):"unknown"}function sa(e){let t=[];for(let[r,a]of Object.entries(e.enums??{})){let o=E(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=E(r),i=[],s=[];for(let[c,u]of Object.entries(a.columns)){let l=ia(u),p=V(u)?" | null":"";i.push(` ${c}${V(u)?"?":""}: ${l}${p};`),s.push(` ${c}${Tn(u)?"?":""}: ${l}${p};`);}n.push(`export type ${o} = {
|
|
10015
10015
|
${i.join(`
|
|
10016
10016
|
`)}
|
|
10017
10017
|
};
|
|
@@ -10024,25 +10024,25 @@ ${s.join(`
|
|
|
10024
10024
|
${n.join(`
|
|
10025
10025
|
|
|
10026
10026
|
`)}
|
|
10027
|
-
`}function na(e,t){if(t){let n=e[t];if(!ie(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(ie(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function Tn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=path.resolve(e.configDir,t.entry),a=path.resolve(e.configDir,t.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,t.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),u=na(c,t.exportName),l=Lr(u);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.dirname(i),{recursive:true})]);let p=Xr(l,n),d=ta(l),y=Yr(l);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(l.tables)}}function aa(e){return e.replaceAll("\\","/")}function M(e,t){let n=aa(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var la=new Set([".ts",".tsx",".mts",".cts"]);async function Sn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await Sn(a));continue}r.isFile()&&la.has(path.extname(r.name))&&n.push(a);}return n}function me(e){return e.replace(/\.[cm]?tsx?$/,"")}function pe(e,t){let n=e,r=false,a,o="unknown",i,s,c;for(;f__namespace.isCallExpression(n);){let u=n.expression;if(!f__namespace.isPropertyAccessExpression(u))break;let l=u.name.text;if(l==="optional"||l==="nullable")r=true,n=u.expression;else if(l==="default"){r=true;let p=n.arguments[0];p&&(f__namespace.isStringLiteral(p)||f__namespace.isNumericLiteral(p)?a=p.text:p.kind===f__namespace.SyntaxKind.TrueKeyword?a="true":p.kind===f__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=u.expression;}else if(l==="string"||l==="uuid"||l==="email"||l==="url"){o="string";break}else if(l==="number"||l==="int"||l==="float"){o="number";break}else if(l==="boolean"){o="boolean";break}else if(l==="date"){o="date";break}else if(l==="object"){o="object";let p=n.arguments[0];if(p&&f__namespace.isObjectLiteralExpression(p)){i=[];for(let d of p.properties)f__namespace.isPropertyAssignment(d)&&f__namespace.isIdentifier(d.name)&&i.push(pe(d.initializer,d.name.text));}break}else if(l==="array"){o="array";let p=n.arguments[0];if(p){let d=pe(p,"");s=d.type==="array"?"unknown":d.type,d.type==="object"&&(c=d.fields);}break}else n=u.expression;}return {name:t,type:o,optional:r,defaultValue:a,fields:i,itemType:s,itemFields:c}}function ua(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f__namespace.isPropertyAssignment(r)&&f__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)||n.push(pe(r.initializer,r.name.text));return n}function ca(e){return f__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f__namespace.SyntaxKind.ExportKeyword)??false:false}function An(e){return f__namespace.isIdentifier(e)?e.text:f__namespace.isParenthesizedExpression(e)?An(e.expression):null}function da(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return f__namespace.isStringLiteral(n)||f__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>f__namespace.isStringLiteral(r)||f__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function pa(e,t){let n=f__namespace.createSourceFile(t,e,f__namespace.ScriptTarget.Latest,true,f__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(ca(a))for(let o of a.declarationList.declarations){if(!f__namespace.isIdentifier(o.name)||!o.initializer||!f__namespace.isCallExpression(o.initializer))continue;let i=An(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"?da(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ua(o.initializer.arguments[0]):[]});}return r}function vn(e,t,n){let r=t.replace(/\\/g,"/"),o=me(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function ma(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 Rn(e,t){let n=e.replace(/\\/g,"/"),a=me(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 Nn(e){let t=[],n=await Sn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=path.relative(e.scanDirAbs,a),c=pa(i,a),u=[{kind:"query",kindDirectory:"queries",exports:c.filter(l=>l.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(l=>l.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(l=>l.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(l=>l.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(l=>l.kind==="storage")}];for(let l of u){if(l.exports.length===0)continue;let p=ma(s,l.kindDirectory);for(let d of l.exports){let y=l.kind==="query"||l.kind==="mutation"?Rn(p,d.exportName):void 0,x=l.kind==="scheduler"||l.kind==="cron"?Rn(p,d.exportName):void 0,N=l.kind==="query"||l.kind==="mutation"?[...me(p).split("/").filter(Boolean),d.exportName]:void 0,w=l.kind==="query"?vn("queries",p,d.exportName):l.kind==="mutation"?vn("mutations",p,d.exportName):l.kind==="storage"?`/storage/managers/${d.exportName}`:`/${l.kindDirectory}/${x}`;t.push({kind:l.kind,exportName:d.exportName,filePath:a,importPath:M(e.outDirAbs,a),clientImportPath:M(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:N,taskName:x,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 ga(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,u=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(u){n+=d,u=false;continue}if(d==="\\"){n+=d,u=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 l=n.trim();return l.length>0&&t.push(l),t}function ha(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 u=e[c];if(s){s=false;continue}if(u==="\\"){s=true;continue}if(!o&&!i&&u==="'"){a=!a;continue}if(!a&&!i&&u==='"'){o=!o;continue}if(!a&&!o&&u==="`"){i=!i;continue}if(!(a||o||i)){if(u==="("){t+=1;continue}if(u===")"){t-=1;continue}if(u==="{"){n+=1;continue}if(u==="}"){n-=1;continue}if(u==="["){r+=1;continue}if(u==="]"){r-=1;continue}if(u===":"&&t===0&&n===0&&r===0)return c}}return -1}function ya(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":/mode\s*:\s*["'`]json["'`]/.test(t)||/\.json\s*\(/.test(t)?"json":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ba(e){let t=ga(e),n=[];for(let r of t){let a=ha(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),u=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||u||c||s;n.push({name:o,expression:i,type:ya(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function wa(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,u=false,l=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(!u&&!l&&y==="'"){c=!c;continue}if(!c&&!l&&y==='"'){u=!u;continue}if(!c&&!u&&y==="`"){l=!l;continue}if(!(c||u||l)){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 u=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:ba(u)}),a=t.exec(e);}return n}async function Cn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await Cn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function Fn(e,t=[]){let n=await Cn(e.scanDirAbs).catch(()=>[]),r=path.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=wa(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 va(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 Ra(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 ka(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
|
|
10028
|
-
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
|
|
10029
|
-
`);let l=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)))),p=
|
|
10030
|
-
`);let
|
|
10031
|
-
`),...
|
|
10032
|
-
`),Bun.write(
|
|
10033
|
-
`);let
|
|
10034
|
-
`),
|
|
10035
|
-
`));function
|
|
10027
|
+
`}function la(e,t){if(t){let n=e[t];if(!se(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(se(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function vn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=path.resolve(e.configDir,t.entry),a=path.resolve(e.configDir,t.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,t.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),u=la(c,t.exportName),l=Jr(u);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.dirname(i),{recursive:true})]);let p=aa(l,n),d=sa(l),y=oa(l);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(l.tables)}}function ca(e){return e.replaceAll("\\","/")}function j(e,t){let n=ca(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var fa=new Set([".ts",".tsx",".mts",".cts"]);async function An(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await An(a));continue}r.isFile()&&fa.has(path.extname(r.name))&&n.push(a);}return n}function fe(e){return e.replace(/\.[cm]?tsx?$/,"")}function me(e,t){let n=e,r=false,a,o="unknown",i,s,c;for(;f__namespace.isCallExpression(n);){let u=n.expression;if(!f__namespace.isPropertyAccessExpression(u))break;let l=u.name.text;if(l==="optional"||l==="nullable")r=true,n=u.expression;else if(l==="default"){r=true;let p=n.arguments[0];p&&(f__namespace.isStringLiteral(p)||f__namespace.isNumericLiteral(p)?a=p.text:p.kind===f__namespace.SyntaxKind.TrueKeyword?a="true":p.kind===f__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=u.expression;}else if(l==="string"||l==="uuid"||l==="email"||l==="url"){o="string";break}else if(l==="number"||l==="int"||l==="float"){o="number";break}else if(l==="boolean"){o="boolean";break}else if(l==="date"){o="date";break}else if(l==="object"){o="object";let p=n.arguments[0];if(p&&f__namespace.isObjectLiteralExpression(p)){i=[];for(let d of p.properties)f__namespace.isPropertyAssignment(d)&&f__namespace.isIdentifier(d.name)&&i.push(me(d.initializer,d.name.text));}break}else if(l==="array"){o="array";let p=n.arguments[0];if(p){let d=me(p,"");s=d.type==="array"?"unknown":d.type,d.type==="object"&&(c=d.fields);}break}else n=u.expression;}return {name:t,type:o,optional:r,defaultValue:a,fields:i,itemType:s,itemFields:c}}function ga(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f__namespace.isPropertyAssignment(r)&&f__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)||n.push(me(r.initializer,r.name.text));return n}function ha(e){return f__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f__namespace.SyntaxKind.ExportKeyword)??false:false}function Nn(e){return f__namespace.isIdentifier(e)?e.text:f__namespace.isParenthesizedExpression(e)?Nn(e.expression):null}function ya(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return f__namespace.isStringLiteral(n)||f__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>f__namespace.isStringLiteral(r)||f__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function ba(e,t){let n=f__namespace.createSourceFile(t,e,f__namespace.ScriptTarget.Latest,true,f__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(ha(a))for(let o of a.declarationList.declarations){if(!f__namespace.isIdentifier(o.name)||!o.initializer||!f__namespace.isCallExpression(o.initializer))continue;let i=Nn(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"?ya(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ga(o.initializer.arguments[0]):[]});}return r}function Rn(e,t,n){let r=t.replace(/\\/g,"/"),o=fe(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function wa(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 kn(e,t){let n=e.replace(/\\/g,"/"),a=fe(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 $n(e){let t=[],n=await An(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=path.relative(e.scanDirAbs,a),c=ba(i,a),u=[{kind:"query",kindDirectory:"queries",exports:c.filter(l=>l.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(l=>l.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(l=>l.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(l=>l.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(l=>l.kind==="storage")}];for(let l of u){if(l.exports.length===0)continue;let p=wa(s,l.kindDirectory);for(let d of l.exports){let y=l.kind==="query"||l.kind==="mutation"?kn(p,d.exportName):void 0,x=l.kind==="scheduler"||l.kind==="cron"?kn(p,d.exportName):void 0,S=l.kind==="query"||l.kind==="mutation"?[...fe(p).split("/").filter(Boolean),d.exportName]:void 0,w=l.kind==="query"?Rn("queries",p,d.exportName):l.kind==="mutation"?Rn("mutations",p,d.exportName):l.kind==="storage"?`/storage/managers/${d.exportName}`:`/${l.kindDirectory}/${x}`;t.push({kind:l.kind,exportName:d.exportName,filePath:a,importPath:j(e.outDirAbs,a),clientImportPath:j(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:S,taskName:x,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 Ta(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,u=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(u){n+=d,u=false;continue}if(d==="\\"){n+=d,u=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 l=n.trim();return l.length>0&&t.push(l),t}function va(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 u=e[c];if(s){s=false;continue}if(u==="\\"){s=true;continue}if(!o&&!i&&u==="'"){a=!a;continue}if(!a&&!i&&u==='"'){o=!o;continue}if(!a&&!o&&u==="`"){i=!i;continue}if(!(a||o||i)){if(u==="("){t+=1;continue}if(u===")"){t-=1;continue}if(u==="{"){n+=1;continue}if(u==="}"){n-=1;continue}if(u==="["){r+=1;continue}if(u==="]"){r-=1;continue}if(u===":"&&t===0&&n===0&&r===0)return c}}return -1}function Ra(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":/mode\s*:\s*["'`]json["'`]/.test(t)||/\.json\s*\(/.test(t)?"json":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ka(e){let t=Ta(e),n=[];for(let r of t){let a=va(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),u=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||u||c||s;n.push({name:o,expression:i,type:Ra(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function Sa(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,u=false,l=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(!u&&!l&&y==="'"){c=!c;continue}if(!c&&!l&&y==='"'){u=!u;continue}if(!c&&!u&&y==="`"){l=!l;continue}if(!(c||u||l)){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 u=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:ka(u)}),a=t.exec(e);}return n}async function Fn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await Fn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function qn(e,t=[]){let n=await Fn(e.scanDirAbs).catch(()=>[]),r=path.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=Sa(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 ge(e){let t=e;for(;;){if(fs.existsSync(path.resolve(t,"package.json")))return t;let n=path.dirname(t);if(n===t)return e;t=n;}}function Na(e,t){for(let n of t)try{return path.dirname(Bun.resolveSync(`${e}/package.json`,n))}catch{continue}throw new Error(`Could not resolve "${e}". Install it in your project (see appflare peerDependencies).`)}function I(e,t,n){return path.resolve(Na(e,n),t)}function B(e,t=[]){let n=[e,ge(process.cwd()),...t];return [...new Set(n)]}function qa(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 Ma(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 Ea(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
|
|
10028
|
+
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 ja(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function On(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=j(t,a),s=path.resolve(t,"client"),c=j(s,a),u=performance.now();await Promise.all([promises.mkdir(t,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(n,{recursive:true})]),process.stdout.write(`\u{1F4C1} Directories (${(performance.now()-u).toFixed(0)}ms)
|
|
10029
|
+
`);let l=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)))),p=B(l,[o]),d=I("typescript","bin/tsc",p),y=I("@better-auth/cli","dist/index.mjs",p),x=path.resolve(t,"server.ts"),S=path.resolve(t,"client.ts"),w=path.resolve(t,"auth.config.ts"),q=path.resolve(t,"auth.schema.ts"),$=path.resolve(t,"drizzle.config.ts"),b=path.resolve(n,"wrangler.json"),h=await vn(e),v=await qn(e,h?[h.schemaPath]:[]),F=j(t,v.schemaPath),R=await $n(e);process.stdout.write(`\u{1F50D} ${R.length} handler(s) (${(performance.now()-u).toFixed(0)}ms)
|
|
10030
|
+
`);let P=qa(r),L=Ma(r),be=St(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),Kn=Fe(c,R),Jn=Y(F,R,r.r2[0]?.binding,P,L),Gn=Re(i),Zn=h?[ja(o,h.schemaPath),...r.schema.filter(T=>!/(^|\/)schema\.ts$/.test(T))]:r.schema,Xn=qe(Zn),Yn=Nt(e,R),er=gn(F,v,R),tr=path.resolve(t,"admin.routes.ts"),nr=Jn.map(T=>Bun.write(path.resolve(t,T.relativePath),T.source)),rr=Kn.map(T=>Bun.write(path.resolve(t,T.relativePath),T.source));await Promise.all([Bun.write(x,be),Bun.write(S,`export * from "./client/index";
|
|
10031
|
+
`),...rr,...nr,Bun.write(w,Gn),Bun.write(q,""),Bun.write($,Xn),Bun.write(b,`${JSON.stringify(Yn,null,2)}
|
|
10032
|
+
`),Bun.write(tr,er)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-u).toFixed(0)}ms)
|
|
10033
|
+
`);let J=path.relative(o,w).replace(/\\/g,"/"),ar=J.startsWith(".")?J:`./${J}`,G=path.relative(o,q).replace(/\\/g,"/"),or=G.startsWith(".")?G:`./${G}`,we=await Bun.spawn([process.execPath,y,"generate","--config",ar,"--output",or,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(we!==0)throw new Error(`better-auth generation failed with exit code ${we}`);process.stdout.write(`\u{1F510} Auth schema (${(performance.now()-u).toFixed(0)}ms)
|
|
10034
|
+
`),P.length>0&&(await Ea(q,P),process.stdout.write(`\u{1F527} Patched role type (${(performance.now()-u).toFixed(0)}ms)
|
|
10035
|
+
`));function ir(T={}){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/*":["./*"]},...T},include:["./*.ts","./client/*.ts"]}}let xe=path.resolve(t,"tsconfig.js.json");await Promise.all([Bun.write(xe,`${JSON.stringify(ir({declaration:true,emitDeclarationOnly:false}),null,2)}
|
|
10036
10036
|
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-u).toFixed(0)}ms)
|
|
10037
|
-
`);async function
|
|
10038
|
-
`);let
|
|
10039
|
-
`);async function
|
|
10040
|
-
`);let
|
|
10041
|
-
`);let
|
|
10042
|
-
`);let C=await Bun.spawn([process.execPath,
|
|
10043
|
-
`);}}var
|
|
10037
|
+
`);async function sr(T,C){process.stdout.write(`\u2699\uFE0F ${C}... (${(performance.now()-u).toFixed(0)}ms)
|
|
10038
|
+
`);let N=await Bun.spawn([process.execPath,d,"-p",T],{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(N!==0)throw new Error(`tsc ${C} failed with exit code ${N}`)}await sr(xe,"JS files"),process.stdout.write(`\u2705 JS + declarations (${(performance.now()-u).toFixed(0)}ms)
|
|
10039
|
+
`);async function Te(T){let C=await promises.readdir(T,{withFileTypes:true});for(let k of C){let N=path.join(T,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith("."))continue;await Te(N);}else k.name.endsWith(".ts")&&!k.name.endsWith(".d.ts")&&await promises.rm(N);}}await Te(t),process.stdout.write(`\u{1F4E6} Cleaned .ts files (${(performance.now()-u).toFixed(0)}ms)
|
|
10040
|
+
`);let lr=t+"/";async function ve(T){let C=await promises.readdir(T,{withFileTypes:true});for(let k of C){let N=path.join(T,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith(".")||N===t)continue;await ve(N);}else !N.startsWith(lr)&&(k.name.endsWith(".d.ts")||k.name.endsWith(".js"))&&await promises.rm(N);}}await ve(o),process.stdout.write(`\u{1F9F9} Cleanup (${(performance.now()-u).toFixed(0)}ms)
|
|
10041
|
+
`);let ur=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.existsSync(ur)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-u).toFixed(0)}ms)
|
|
10042
|
+
`);let C=await Bun.spawn([process.execPath,d,"--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(C!==0)throw new Error(`TypeScript build failed with exit code ${C}`);process.stdout.write(`\u2705 Build complete (${(performance.now()-u).toFixed(0)}ms)
|
|
10043
|
+
`);}}var Dn=zod.z.object({binding:zod.z.string().min(1),databaseName:zod.z.string().min(1),databaseId:zod.z.string().min(1),previewDatabaseId:zod.z.string().min(1).optional(),migrationsDir:zod.z.string().min(1).optional()}).strict(),Vn=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),Bn=zod.z.object({binding:zod.z.string().min(1),bucketName:zod.z.string().min(1),previewBucketName:zod.z.string().min(1).optional(),jurisdiction:zod.z.string().min(1).optional()}).strict(),Wn=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),queue:zod.z.string().min(1).optional()}).strict(),Da=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),className:zod.z.string().min(1).optional(),objectName:zod.z.string().min(1).optional(),subscribePath:zod.z.string().min(1).optional(),websocketPath:zod.z.string().min(1).optional(),protocol:zod.z.string().min(1).optional()}).strict(),Va=zod.z.object({scanDir:zod.z.string().min(1),outDir:zod.z.string().min(1),wranglerOutDir:zod.z.string().min(1).optional(),wranglerOutPath:zod.z.string().min(1).optional(),schema:zod.z.array(zod.z.string()).min(1),schemaDsl:zod.z.object({entry:zod.z.string().min(1),exportName:zod.z.string().min(1).optional(),outFile:zod.z.string().min(1).optional(),typesOutFile:zod.z.string().min(1).optional(),zodOutFile:zod.z.string().min(1).optional(),namingStrategy:zod.z.literal("camelToSnake").optional()}).strict().optional(),database:zod.z.union([Dn,zod.z.array(Dn).min(1)]),kv:zod.z.union([Vn,zod.z.array(Vn)]).optional(),r2:zod.z.union([Bn,zod.z.array(Bn)]).optional(),auth:zod.z.object({enabled:zod.z.boolean(),basePath:zod.z.string().min(1),options:zod.z.custom(e=>typeof e=="object"&&e!==null),clientOptions:zod.z.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:Wn.optional(),realtime:Da.optional(),wranglerOverrides:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),build:zod.z.boolean().optional()}).strict();function Ln(e){return typeof e=="object"&&e!==null}function Ba(e){let t=Ln(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=Wn.safeParse(t);return n.success?n.data:{}}function Wa(e){if(!Ln(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function La(e){let n={...Ba(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:Wa(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function W(e){let t=path.isAbsolute(e??"")?e:path.resolve(process.cwd(),e??"appflare.config.ts"),n=path.dirname(t),o=(await import(url.pathToFileURL(t).href)).default,i=Va.parse(o),s=La(i);return {configPath:t,configDir:n,scanDirAbs:path.resolve(n,s.scanDir),outDirAbs:path.resolve(n,s.outDir),wranglerOutDirAbs:path.resolve(n,s.wranglerOutDir),config:s}}async function K(e,t={}){let n=await W(e);if(t.build!==void 0&&(n.config.build=t.build),await On(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
10044
10044
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
10045
|
-
`);}async function
|
|
10046
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
10045
|
+
`);}async function Un(e,t={}){if(await K(e,{build:t.build}),!t.watch)return;let n=await W(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await K(e,{build:t.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
10046
|
+
`);}finally{r=false,a&&(a=false,await o());}};Ha__default.default.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}
|
|
10047
10047
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
10048
|
-
`);}async function
|
|
10048
|
+
`);}async function _n(e,t={}){let n=await W(e),r=ge(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=path.resolve(n.outDirAbs,"drizzle.config.js"),i=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)))),s=B(i,[n.configDir,r]),c=I("drizzle-kit","bin.cjs",s),l=await Bun.spawn([process.execPath,c,"generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(l!==0)throw new Error(`drizzle-kit generate failed with exit code ${l}`);let p=n.config.database[0].databaseName,d=I("wrangler","bin/wrangler.js",s),y=[process.execPath,d,"d1","migrations","apply",p];t.local?y.push("--local"):t.remote?y.push("--remote"):t.preview&&y.push("--preview");let S=await Bun.spawn(y,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(S!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${S}`)}async function Qn(e,t={name:"",email:"",password:""}){let n=await W(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(),u=t.name.replace(/'/g,"''"),l=t.email.replace(/'/g,"''"),p=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${u}', '${l}', 1, ${c}, ${c}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${l}', 'credential', '${i}', '${o}', ${c}, ${c});`].join(" "),d=n.config.database[0].databaseName,y=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)))),x=B(y,[n.configDir]),S=I("wrangler","bin/wrangler.js",x),w=[process.execPath,S,"d1","execute",d,`--command=${p}`];t.local?w.push("--local"):t.remote&&w.push("--remote");let $=await Bun.spawn(w,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if($!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${$}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var O=new commander.Command;O.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");O.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 K(e.config,{build:e.build});});O.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 Un(e.config,{watch:e.watch,build:e.build});});O.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 _n(e.config,{local:e.local,remote:e.remote,preview:e.preview});});O.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 Qn(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 O.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|