appflare 0.2.49 → 0.2.50
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/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'),ja=require('chokidar'),fs=require('fs'),path=require('path'),promises=require('fs/promises'),url=require('url'),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 ja__default=/*#__PURE__*/_interopDefault(ja);var f__namespace=/*#__PURE__*/_interopNamespace(f);function ve(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 Re(){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 ar(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function
|
|
170
|
-
`)}function ir(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=ar(`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:`${
|
|
169
|
+
`}function ar(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function ke(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function or(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function Se(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 G(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}${or(i)}: ${G(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 ir(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=ar(`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:`${ke(e.kind)}${ke(n.join("_"))}`}}function sr(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
|
|
362
|
-
`),o=t.map(
|
|
363
|
-
export type ${
|
|
364
|
-
export type ${p} = Awaited<ReturnType<typeof ${
|
|
365
|
-
export const ${d} = ${
|
|
361
|
+
};`}function Z(e){let t=e.map((u,l)=>ir(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
|
+
`),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
|
+
export type ${l} = z.input<typeof ${u.schemaConst}>;
|
|
364
|
+
export type ${p} = Awaited<ReturnType<typeof ${u.alias}.definition.handler>>;
|
|
365
|
+
export const ${d} = ${u.schemaConst};`}).join(`
|
|
366
366
|
|
|
367
|
-
`),i=t.map(
|
|
367
|
+
`),i=t.map(u=>sr(u)).join(`
|
|
368
368
|
|
|
369
|
-
`),s=
|
|
369
|
+
`),s=G(Se(n)),c=G(Se(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 Ae(){return `export * from "./types";
|
|
746
746
|
export * from "./appflare";
|
|
747
747
|
export * from "./storage";
|
|
748
748
|
export * from "./handlers";
|
|
749
|
-
`}function
|
|
749
|
+
`}function Ne(){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 $e(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 Ce(e,t){return [{relativePath:"client/index.ts",source:Ae()},{relativePath:"client/types.ts",source:$e(e)},{relativePath:"client/storage.ts",source:Ne()},{relativePath:"client/handlers.ts",source:Z(t)},{relativePath:"client/appflare.ts",source:Re()}]}function Fe(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 qe(){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 Me(){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 Ee(){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 je(){return `
|
|
1230
1230
|
function createContextErrorHelpers() {
|
|
1231
1231
|
return {
|
|
1232
1232
|
error: (status: number, message: string, details?: unknown) => {
|
|
@@ -1290,7 +1290,7 @@ function buildSignedRequest(
|
|
|
1290
1290
|
headers,
|
|
1291
1291
|
});
|
|
1292
1292
|
}
|
|
1293
|
-
`}function
|
|
1293
|
+
`}function Pe(){return `
|
|
1294
1294
|
function createStorageApi(
|
|
1295
1295
|
ctx: AppflareContext,
|
|
1296
1296
|
bucket: R2BucketBinding | undefined,
|
|
@@ -1369,7 +1369,7 @@ function createStorageApi(
|
|
|
1369
1369
|
},
|
|
1370
1370
|
};
|
|
1371
1371
|
}
|
|
1372
|
-
`}function
|
|
1372
|
+
`}function Oe(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 De(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
|
+
|
|
1489
1491
|
${qe()}
|
|
1490
1492
|
|
|
1491
|
-
${
|
|
1493
|
+
${Ee()}
|
|
1492
1494
|
|
|
1493
1495
|
${je()}
|
|
1494
1496
|
|
|
1495
|
-
${Me()}
|
|
1496
|
-
|
|
1497
1497
|
${Ie()}
|
|
1498
1498
|
|
|
1499
|
-
${
|
|
1499
|
+
${Pe()}
|
|
1500
1500
|
|
|
1501
|
-
${
|
|
1502
|
-
`}function
|
|
1501
|
+
${Oe(e)}
|
|
1502
|
+
`}function Ve(){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 Be(){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
|
+
${Ve()}
|
|
1553
|
+
`}function We(){return `import { betterAuth } from "better-auth";
|
|
1554
1554
|
import { auth } from "./auth.config";
|
|
1555
1555
|
import {
|
|
1556
1556
|
and,
|
|
@@ -1655,7 +1655,7 @@ export async function isStorageAllowed(
|
|
|
1655
1655
|
|
|
1656
1656
|
return false;
|
|
1657
1657
|
}
|
|
1658
|
-
`}function
|
|
1658
|
+
`}function He(){return `type Primitive = string | number | boolean | Date;
|
|
1659
1659
|
type NonNil<T> = Exclude<T, null | undefined>;
|
|
1660
1660
|
type Friendly<T> = T extends Date ? Date | number : T;
|
|
1661
1661
|
type Comparable<T> = Friendly<Extract<NonNil<T>, Primitive>>;
|
|
@@ -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 Le(){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 ze(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2079
2079
|
return typeof value === "object" && value !== null;
|
|
2080
2080
|
}
|
|
2081
2081
|
|
|
@@ -3454,17 +3454,22 @@ function inferConflictTarget(table: unknown): string[] {
|
|
|
3454
3454
|
|
|
3455
3455
|
return [];
|
|
3456
3456
|
}
|
|
3457
|
-
`}function
|
|
3457
|
+
`}function Ue(){return `const mergedSchema = {
|
|
3458
3458
|
...authSchema,
|
|
3459
3459
|
...schema,
|
|
3460
3460
|
};
|
|
3461
3461
|
|
|
3462
|
+
const mergedDbSchema = {
|
|
3463
|
+
...authSchema,
|
|
3464
|
+
...schema.__appflareDbSchema,
|
|
3465
|
+
};
|
|
3466
|
+
|
|
3462
3467
|
export const createDb = (database: D1Database) =>
|
|
3463
|
-
drizzle(database, { schema:
|
|
3468
|
+
drizzle(database, { schema: mergedDbSchema });
|
|
3464
3469
|
|
|
3465
3470
|
export type AppflareDb = ReturnType<typeof createDb>;
|
|
3466
3471
|
|
|
3467
|
-
type SchemaRelations = ExtractTablesWithRelations<typeof
|
|
3472
|
+
type SchemaRelations = ExtractTablesWithRelations<typeof mergedDbSchema>;
|
|
3468
3473
|
type TableName = Extract<keyof SchemaRelations, string>;
|
|
3469
3474
|
type TableRelationConfig<TName extends TableName> =
|
|
3470
3475
|
TName extends keyof SchemaRelations ? SchemaRelations[TName] : never;
|
|
@@ -3478,29 +3483,11 @@ type NativeFindManyWith<TName extends TableName> =
|
|
|
3478
3483
|
NonNullable<TableFindManyArgs<TName>> extends { with?: infer TWith }
|
|
3479
3484
|
? TWith
|
|
3480
3485
|
: never;
|
|
3481
|
-
type NormalizeWhereInWith<TWith, TNativeWith> = TWith extends Record<string, unknown>
|
|
3482
|
-
? {
|
|
3483
|
-
[K in keyof TWith]: K extends keyof TNativeWith
|
|
3484
|
-
? TWith[K] extends Record<string, unknown>
|
|
3485
|
-
? Omit<TWith[K], 'where'> & { where?: NonNullable<Extract<TNativeWith[K], Record<string, unknown>>['where']> } & (TWith[K] extends { with: infer TNestedWith }
|
|
3486
|
-
? { with: NormalizeWhereInWith<TNestedWith, TNativeWith[K]> }
|
|
3487
|
-
: {})
|
|
3488
|
-
: TWith[K]
|
|
3489
|
-
: TWith[K];
|
|
3490
|
-
}
|
|
3491
|
-
: TWith;
|
|
3492
|
-
|
|
3493
3486
|
type ResolveNativeFindManyWith<
|
|
3494
3487
|
TName extends TableName,
|
|
3495
3488
|
TArgs extends QueryFindManyArgs<TName> | undefined,
|
|
3496
3489
|
> = TArgs extends { with?: infer TWith }
|
|
3497
|
-
?
|
|
3498
|
-
? [TResolved] extends [never]
|
|
3499
|
-
? TWith extends Record<string, unknown>
|
|
3500
|
-
? NormalizeWhereInWith<TWith, NativeFindManyWith<TName>>
|
|
3501
|
-
: never
|
|
3502
|
-
: TResolved
|
|
3503
|
-
: never
|
|
3490
|
+
? NormalizeNativeWithForTable<TName, TWith>
|
|
3504
3491
|
: never;
|
|
3505
3492
|
type ResolveTableFindManySelection<
|
|
3506
3493
|
TName extends TableName,
|
|
@@ -3512,7 +3499,7 @@ type ResolveTableFindManySelection<
|
|
|
3512
3499
|
? {}
|
|
3513
3500
|
: { with: ResolveNativeFindManyWith<TName, TArgs> });
|
|
3514
3501
|
type TableModel<TName extends TableName> = InferSelectModel<
|
|
3515
|
-
(typeof
|
|
3502
|
+
(typeof mergedDbSchema)[TName]
|
|
3516
3503
|
>;
|
|
3517
3504
|
type ManyToManySchemaMap = typeof schema extends {
|
|
3518
3505
|
__appflareManyToMany: infer TMap extends Record<string, unknown>;
|
|
@@ -3570,6 +3557,148 @@ type RuntimeRelationTargetTable<
|
|
|
3570
3557
|
}
|
|
3571
3558
|
? Extract<TTarget, TableName>
|
|
3572
3559
|
: never;
|
|
3560
|
+
type NativeRelationEntry<
|
|
3561
|
+
TSourceTable extends TableName,
|
|
3562
|
+
TRelationName extends string,
|
|
3563
|
+
> = TRelationName extends keyof NativeFindManyWith<TSourceTable>
|
|
3564
|
+
? NativeFindManyWith<TSourceTable>[TRelationName]
|
|
3565
|
+
: never;
|
|
3566
|
+
type NativeRelationWhere<TEntry> = Extract<
|
|
3567
|
+
TEntry,
|
|
3568
|
+
Record<string, unknown>
|
|
3569
|
+
> extends {
|
|
3570
|
+
where?: infer TWhere;
|
|
3571
|
+
}
|
|
3572
|
+
? TWhere
|
|
3573
|
+
: never;
|
|
3574
|
+
type ManyToManyJunctionTableName<
|
|
3575
|
+
TSourceTable extends TableName,
|
|
3576
|
+
TRelationName extends string,
|
|
3577
|
+
> = TRelationName extends keyof ManyToManySourceTableMap<TSourceTable>
|
|
3578
|
+
? ManyToManySourceTableMap<TSourceTable>[TRelationName] extends {
|
|
3579
|
+
junctionTable: infer TJunctionTable extends string;
|
|
3580
|
+
}
|
|
3581
|
+
? Extract<TJunctionTable, TableName>
|
|
3582
|
+
: never
|
|
3583
|
+
: never;
|
|
3584
|
+
type CleanRelationConfig<TEntry> = Omit<
|
|
3585
|
+
Extract<TEntry, Record<string, unknown>>,
|
|
3586
|
+
"where" | "with" | "_count" | "_avg"
|
|
3587
|
+
>;
|
|
3588
|
+
type NormalizeNativeRelationConfig<
|
|
3589
|
+
TSourceTable extends TableName,
|
|
3590
|
+
TRelationName extends string,
|
|
3591
|
+
TEntry,
|
|
3592
|
+
> = CleanRelationConfig<TEntry> &
|
|
3593
|
+
(Extract<TEntry, Record<string, unknown>> extends { where?: unknown }
|
|
3594
|
+
? {
|
|
3595
|
+
where?: NativeRelationWhere<
|
|
3596
|
+
NativeRelationEntry<TSourceTable, TRelationName>
|
|
3597
|
+
>;
|
|
3598
|
+
}
|
|
3599
|
+
: {}) &
|
|
3600
|
+
(Extract<TEntry, Record<string, unknown>> extends { with?: infer TNestedWith }
|
|
3601
|
+
? RuntimeRelationTargetTable<TSourceTable, TRelationName> extends infer TTargetTable
|
|
3602
|
+
? TTargetTable extends TableName
|
|
3603
|
+
? {
|
|
3604
|
+
with?: NormalizeNativeWithForTable<TTargetTable, TNestedWith>;
|
|
3605
|
+
}
|
|
3606
|
+
: {}
|
|
3607
|
+
: {}
|
|
3608
|
+
: {});
|
|
3609
|
+
type NormalizeManyToManyTargetConfig<
|
|
3610
|
+
TSourceTable extends TableName,
|
|
3611
|
+
TRelationName extends string,
|
|
3612
|
+
TEntry,
|
|
3613
|
+
> = ManyToManyTargetTableName<
|
|
3614
|
+
TSourceTable,
|
|
3615
|
+
TRelationName
|
|
3616
|
+
> extends infer TTargetTable
|
|
3617
|
+
? TTargetTable extends TableName
|
|
3618
|
+
? CleanRelationConfig<TEntry> &
|
|
3619
|
+
(Extract<TEntry, Record<string, unknown>> extends { where?: unknown }
|
|
3620
|
+
? ManyToManyJunctionTableName<
|
|
3621
|
+
TSourceTable,
|
|
3622
|
+
TRelationName
|
|
3623
|
+
> extends infer TJunctionTable
|
|
3624
|
+
? TJunctionTable extends TableName
|
|
3625
|
+
? {
|
|
3626
|
+
where?: NativeRelationWhere<
|
|
3627
|
+
NativeRelationEntry<TJunctionTable, TTargetTable>
|
|
3628
|
+
>;
|
|
3629
|
+
}
|
|
3630
|
+
: {}
|
|
3631
|
+
: {}
|
|
3632
|
+
: {}) &
|
|
3633
|
+
(Extract<TEntry, Record<string, unknown>> extends {
|
|
3634
|
+
with?: infer TNestedWith;
|
|
3635
|
+
}
|
|
3636
|
+
? {
|
|
3637
|
+
with?: NormalizeNativeWithForTable<TTargetTable, TNestedWith>;
|
|
3638
|
+
}
|
|
3639
|
+
: {})
|
|
3640
|
+
: never
|
|
3641
|
+
: never;
|
|
3642
|
+
type NormalizeRelationInputForTable<
|
|
3643
|
+
TSourceTable extends TableName,
|
|
3644
|
+
TRelationName extends string,
|
|
3645
|
+
TEntry,
|
|
3646
|
+
> = [ManyToManyTargetTableName<TSourceTable, TRelationName>] extends [never]
|
|
3647
|
+
? (Extract<TEntry, true> extends never ? never : true) |
|
|
3648
|
+
(Extract<TEntry, Record<string, unknown>> extends infer TConfig
|
|
3649
|
+
? TConfig extends Record<string, unknown>
|
|
3650
|
+
? NormalizeNativeRelationConfig<
|
|
3651
|
+
TSourceTable,
|
|
3652
|
+
TRelationName,
|
|
3653
|
+
TConfig
|
|
3654
|
+
>
|
|
3655
|
+
: never
|
|
3656
|
+
: never)
|
|
3657
|
+
: ManyToManyTargetTableName<
|
|
3658
|
+
TSourceTable,
|
|
3659
|
+
TRelationName
|
|
3660
|
+
> extends infer TTargetTable
|
|
3661
|
+
? TTargetTable extends TableName
|
|
3662
|
+
? (Extract<TEntry, true> extends never
|
|
3663
|
+
? never
|
|
3664
|
+
: {
|
|
3665
|
+
with: {
|
|
3666
|
+
[K in TTargetTable]: true;
|
|
3667
|
+
};
|
|
3668
|
+
}) |
|
|
3669
|
+
(Extract<TEntry, Record<string, unknown>> extends infer TConfig
|
|
3670
|
+
? TConfig extends Record<string, unknown>
|
|
3671
|
+
? CleanRelationConfig<TConfig> & {
|
|
3672
|
+
with: {
|
|
3673
|
+
[K in TTargetTable]: keyof NormalizeManyToManyTargetConfig<
|
|
3674
|
+
TSourceTable,
|
|
3675
|
+
TRelationName,
|
|
3676
|
+
TConfig
|
|
3677
|
+
> extends never
|
|
3678
|
+
? true
|
|
3679
|
+
: NormalizeManyToManyTargetConfig<
|
|
3680
|
+
TSourceTable,
|
|
3681
|
+
TRelationName,
|
|
3682
|
+
TConfig
|
|
3683
|
+
>;
|
|
3684
|
+
};
|
|
3685
|
+
}
|
|
3686
|
+
: never
|
|
3687
|
+
: never)
|
|
3688
|
+
: never
|
|
3689
|
+
: never;
|
|
3690
|
+
type NormalizeNativeWithForTable<
|
|
3691
|
+
TSourceTable extends TableName,
|
|
3692
|
+
TWith,
|
|
3693
|
+
> = TWith extends Record<string, unknown>
|
|
3694
|
+
? {
|
|
3695
|
+
[K in keyof TWith]: NormalizeRelationInputForTable<
|
|
3696
|
+
TSourceTable,
|
|
3697
|
+
Extract<K, string>,
|
|
3698
|
+
TWith[K]
|
|
3699
|
+
>;
|
|
3700
|
+
}
|
|
3701
|
+
: TWith;
|
|
3573
3702
|
|
|
3574
3703
|
type TargetTableForRelation<
|
|
3575
3704
|
TSource extends TableName,
|
|
@@ -3691,13 +3820,7 @@ type ResolveNativeFindFirstWith<
|
|
|
3691
3820
|
TName extends TableName,
|
|
3692
3821
|
TArgs extends QueryFindFirstArgs<TName> | undefined,
|
|
3693
3822
|
> = TArgs extends { with?: infer TWith }
|
|
3694
|
-
?
|
|
3695
|
-
? [TResolved] extends [never]
|
|
3696
|
-
? TWith extends Record<string, unknown>
|
|
3697
|
-
? NormalizeWhereInWith<TWith, NativeFindFirstWith<TName>>
|
|
3698
|
-
: never
|
|
3699
|
-
: TResolved
|
|
3700
|
-
: never
|
|
3823
|
+
? NormalizeNativeWithForTable<TName, TWith>
|
|
3701
3824
|
: never;
|
|
3702
3825
|
type ResolveTableFindFirstSelection<
|
|
3703
3826
|
TName extends TableName,
|
|
@@ -3727,11 +3850,11 @@ type TableFindFirstResult<
|
|
|
3727
3850
|
>
|
|
3728
3851
|
>;
|
|
3729
3852
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3730
|
-
(typeof
|
|
3853
|
+
(typeof mergedDbSchema)[TName]
|
|
3731
3854
|
>;
|
|
3732
|
-
`}function
|
|
3855
|
+
`}function _e(){return [Ue(),He(),Le(),ze()].join(`
|
|
3733
3856
|
|
|
3734
|
-
`)}function
|
|
3857
|
+
`)}function Qe(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3735
3858
|
const withValue = args?.with;
|
|
3736
3859
|
const pathSegments = args?.field
|
|
3737
3860
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -3902,7 +4025,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3902
4025
|
},
|
|
3903
4026
|
}) as AppflareQueryDb;
|
|
3904
4027
|
}
|
|
3905
|
-
`}function
|
|
4028
|
+
`}function Je(){return `export class AppflareHandledError extends Error {
|
|
3906
4029
|
public readonly status: number;
|
|
3907
4030
|
public readonly payload: unknown;
|
|
3908
4031
|
|
|
@@ -4066,7 +4189,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4066
4189
|
);
|
|
4067
4190
|
});
|
|
4068
4191
|
},
|
|
4069
|
-
`}function
|
|
4192
|
+
`}function Ge(){return `export function createQueryDb(
|
|
4070
4193
|
$db: AppflareDb,
|
|
4071
4194
|
options?: QueryDbOptions,
|
|
4072
4195
|
): AppflareQueryDb {
|
|
@@ -4108,7 +4231,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4108
4231
|
};
|
|
4109
4232
|
|
|
4110
4233
|
const tableApi = {
|
|
4111
|
-
`}function
|
|
4234
|
+
`}function Ze(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
4112
4235
|
const transaction = ($db as any).transaction;
|
|
4113
4236
|
|
|
4114
4237
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -5063,9 +5186,9 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
5063
5186
|
);
|
|
5064
5187
|
return rows;
|
|
5065
5188
|
},
|
|
5066
|
-
`}function
|
|
5189
|
+
`}function Xe(){return [Ge(),Ke(),Ze(),Qe(),Je()].join(`
|
|
5067
5190
|
|
|
5068
|
-
`)}function
|
|
5191
|
+
`)}function Ye(e=[],t=[]){let n=t.map(i=>` ${i.name}?: ${i.tsType} | null;`).join(`
|
|
5069
5192
|
`),a=[e.length>0?[" role: UserRole;"," banned: boolean | null;"," banReason?: string | null | undefined;"," banExpires?: Date | null | undefined;"].join(`
|
|
5070
5193
|
`):"",n].filter(Boolean).join(`
|
|
5071
5194
|
`);return `type AuthSession = typeof auth.$Infer.Session;
|
|
@@ -5162,7 +5285,7 @@ export type AppflareContext = {
|
|
|
5162
5285
|
storage: AppflareStorage;
|
|
5163
5286
|
error: (status: number, message: string, details?: unknown) => never;
|
|
5164
5287
|
};
|
|
5165
|
-
`}function
|
|
5288
|
+
`}function et(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
5166
5289
|
|
|
5167
5290
|
export type SchedulerEnqueueOptions = {
|
|
5168
5291
|
delaySeconds?: number;
|
|
@@ -5294,16 +5417,16 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
5294
5417
|
definition,
|
|
5295
5418
|
};
|
|
5296
5419
|
}
|
|
5297
|
-
`}function
|
|
5420
|
+
`}function tt(e=[],t=[]){return [We(),_e(),Xe(),Ye(e,t),et()].join(`
|
|
5298
5421
|
|
|
5299
|
-
`)}function
|
|
5422
|
+
`)}function nt(e,t=[],n=[]){return `import type { Context } from "hono";
|
|
5300
5423
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5301
5424
|
import { drizzle } from "drizzle-orm/d1";
|
|
5302
5425
|
import { z, type ZodRawShape } from "zod";
|
|
5303
5426
|
import * as authSchema from "./auth.schema";
|
|
5304
5427
|
import * as schema from "${e}";
|
|
5305
5428
|
|
|
5306
|
-
${
|
|
5429
|
+
${tt(t,n)}
|
|
5307
5430
|
`}function lr(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function ur(e,t){let n=e.routePath.replace(/^\//,"").replace(/\//g,"_");return lr(`op_${t}_${n}`)}function cr(e){return e.map((t,n)=>({operation:t,index:n,alias:ur(t,n)}))}function dr(e){return e.map(({operation:t,alias:n})=>`import { ${t.exportName} as ${n} } from "${t.importPath}";`).join(`
|
|
5308
5431
|
`)}function pr(e){return e.filter(({operation:t})=>t.kind==="query"||t.kind==="mutation").map(({alias:t})=>`const ${`${t}Schema`} = z.object(${t}.definition.args);`).join(`
|
|
5309
5432
|
`)}function mr(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(`
|
|
@@ -5354,7 +5477,7 @@ import * as schema from "${e}";
|
|
|
5354
5477
|
},`}).join(`
|
|
5355
5478
|
`)}function xr(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
5356
5479
|
${t}.definition.handler,`).join(`
|
|
5357
|
-
`)}function
|
|
5480
|
+
`)}function rt(e){let t=cr(e);return {imports:dr(t),operationSchemas:pr(t),schedulerSchemas:mr(t),queryRoutes:fr(t),mutationRoutes:gr(t),queryRegistryEntries:hr(t),schedulerEntries:yr(t),schedulerPayloadMapEntries:br(t),cronEntries:wr(t),storageHandlersEntries:xr(t)}}var at=`
|
|
5358
5481
|
function getRealtimeStub(
|
|
5359
5482
|
env: Record<string, unknown>,
|
|
5360
5483
|
options: RegisterHandlersOptions,
|
|
@@ -5428,7 +5551,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
5428
5551
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
5429
5552
|
return url.toString();
|
|
5430
5553
|
}
|
|
5431
|
-
`;var
|
|
5554
|
+
`;var ot=`
|
|
5432
5555
|
export class AppflareRealtimeDurableObject {
|
|
5433
5556
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
5434
5557
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -5571,7 +5694,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
5571
5694
|
return new Response("Not found", { status: 404 });
|
|
5572
5695
|
}
|
|
5573
5696
|
}
|
|
5574
|
-
`;var
|
|
5697
|
+
`;var it=`
|
|
5575
5698
|
async function publishMutationEvents(
|
|
5576
5699
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
5577
5700
|
options: RegisterHandlersOptions,
|
|
@@ -5672,7 +5795,7 @@ async function publishMutationEvents(
|
|
|
5672
5795
|
}
|
|
5673
5796
|
}
|
|
5674
5797
|
}
|
|
5675
|
-
`;var
|
|
5798
|
+
`;var st=`
|
|
5676
5799
|
function registerRealtimeRoutes(
|
|
5677
5800
|
app: Hono<WorkerEnv>,
|
|
5678
5801
|
options: RegisterHandlersOptions,
|
|
@@ -5835,7 +5958,7 @@ function registerRealtimeRoutes(
|
|
|
5835
5958
|
return stub.fetch(c.req.raw);
|
|
5836
5959
|
});
|
|
5837
5960
|
}
|
|
5838
|
-
`;var
|
|
5961
|
+
`;var lt=`
|
|
5839
5962
|
type RealtimeSubscription = {
|
|
5840
5963
|
token: string;
|
|
5841
5964
|
signature: string;
|
|
@@ -5864,7 +5987,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
5864
5987
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
5865
5988
|
? string
|
|
5866
5989
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
5867
|
-
`;var
|
|
5990
|
+
`;var ut=`
|
|
5868
5991
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5869
5992
|
return typeof value === "object" && value !== null;
|
|
5870
5993
|
}
|
|
@@ -6373,9 +6496,9 @@ function doesSubscriptionMatchMutation(
|
|
|
6373
6496
|
|
|
6374
6497
|
return false;
|
|
6375
6498
|
}
|
|
6376
|
-
`;var
|
|
6499
|
+
`;var ct=[lt,ut,at,it,st,ot].join(`
|
|
6377
6500
|
|
|
6378
|
-
`);var
|
|
6501
|
+
`);var dt=`
|
|
6379
6502
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
6380
6503
|
if (!value) {
|
|
6381
6504
|
return undefined;
|
|
@@ -6573,7 +6696,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
6573
6696
|
}
|
|
6574
6697
|
});
|
|
6575
6698
|
}
|
|
6576
|
-
`;var
|
|
6699
|
+
`;var pt=`
|
|
6577
6700
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
6578
6701
|
? string
|
|
6579
6702
|
: keyof typeof schedulerHandlers;
|
|
@@ -6637,7 +6760,7 @@ export async function executeScheduledBatch(
|
|
|
6637
6760
|
}
|
|
6638
6761
|
}
|
|
6639
6762
|
}
|
|
6640
|
-
`;var
|
|
6763
|
+
`;var mt=`
|
|
6641
6764
|
export async function executeCronTriggers(
|
|
6642
6765
|
controller: { cron: string },
|
|
6643
6766
|
env: Record<string, unknown>,
|
|
@@ -6671,7 +6794,7 @@ export async function executeCronTriggers(
|
|
|
6671
6794
|
}
|
|
6672
6795
|
}
|
|
6673
6796
|
}
|
|
6674
|
-
`;function
|
|
6797
|
+
`;function ft(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:c,cronEntries:u,storageHandlersEntries:l}=rt(e);return `import { sValidator } from "@hono/standard-validator";
|
|
6675
6798
|
import type { Hono } from "hono";
|
|
6676
6799
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6677
6800
|
import { ZodError, z } from "zod";
|
|
@@ -6718,19 +6841,19 @@ type CronHandlerEntry = {
|
|
|
6718
6841
|
};
|
|
6719
6842
|
};
|
|
6720
6843
|
|
|
6721
|
-
const cronHandlers: readonly CronHandlerEntry[] = [${
|
|
6844
|
+
const cronHandlers: readonly CronHandlerEntry[] = [${u||`
|
|
6722
6845
|
`}
|
|
6723
6846
|
];
|
|
6724
6847
|
|
|
6725
|
-
const storageHandlers = [${
|
|
6848
|
+
const storageHandlers = [${l||`
|
|
6726
6849
|
`}
|
|
6727
6850
|
] as const;
|
|
6728
6851
|
|
|
6729
6852
|
setStorageHandlers([...storageHandlers]);
|
|
6730
6853
|
|
|
6731
|
-
${
|
|
6854
|
+
${pt}
|
|
6732
6855
|
|
|
6733
|
-
${
|
|
6856
|
+
${ct}
|
|
6734
6857
|
|
|
6735
6858
|
export function registerGeneratedHandlers(
|
|
6736
6859
|
app: Hono<WorkerEnv>,
|
|
@@ -6743,20 +6866,20 @@ export function registerGeneratedHandlers(
|
|
|
6743
6866
|
`}
|
|
6744
6867
|
}
|
|
6745
6868
|
|
|
6746
|
-
${
|
|
6869
|
+
${dt}
|
|
6747
6870
|
|
|
6748
|
-
${
|
|
6749
|
-
`}function
|
|
6750
|
-
KV: c.env["${e}"] as KVNamespace`:""}function
|
|
6751
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6752
|
-
}`}function
|
|
6871
|
+
${mt}
|
|
6872
|
+
`}function X(e,t,n,r=[],a=[]){let o=nt(e,r,a),i=De(n),s=Be(),c=ft(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 Tr(e){return e?`,
|
|
6873
|
+
KV: c.env["${e}"] as KVNamespace`:""}function gt(e,t){return `{
|
|
6874
|
+
DATABASE: c.env["${e}"] as D1Database${Tr(t)}
|
|
6875
|
+
}`}function ht(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6753
6876
|
const auth = createAuth(
|
|
6754
|
-
${
|
|
6877
|
+
${gt(t,n)},
|
|
6755
6878
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
6756
6879
|
);
|
|
6757
6880
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6758
6881
|
});
|
|
6759
|
-
`}function
|
|
6882
|
+
`}function vr(){return `export const getHeaders = (headers: Headers) => {
|
|
6760
6883
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6761
6884
|
const headerObject: Record<string, any> = {};
|
|
6762
6885
|
let hasCookie = false;
|
|
@@ -6792,9 +6915,9 @@ ${pt}
|
|
|
6792
6915
|
});
|
|
6793
6916
|
return newRequest;
|
|
6794
6917
|
};
|
|
6795
|
-
`}function
|
|
6796
|
-
`+Rr()}function
|
|
6797
|
-
`+
|
|
6918
|
+
`}function yt(){return vr()+`
|
|
6919
|
+
`+Rr()}function bt(e,t,n){return ht(e,t,n)+`
|
|
6920
|
+
`+yt()}function wt(){return `const app = new Hono<WorkerEnv>();
|
|
6798
6921
|
|
|
6799
6922
|
app.use('*', cors({
|
|
6800
6923
|
origin: (origin, c) => {
|
|
@@ -6810,7 +6933,7 @@ app.use('*', cors({
|
|
|
6810
6933
|
},
|
|
6811
6934
|
credentials: true
|
|
6812
6935
|
}));
|
|
6813
|
-
`}function
|
|
6936
|
+
`}function xt(){return `export { AppflareRealtimeDurableObject };
|
|
6814
6937
|
|
|
6815
6938
|
export default {
|
|
6816
6939
|
fetch: app.fetch,
|
|
@@ -6821,16 +6944,16 @@ export default {
|
|
|
6821
6944
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
6822
6945
|
},
|
|
6823
6946
|
};
|
|
6824
|
-
`}function
|
|
6825
|
-
kvBinding: "${t}",`:"",
|
|
6947
|
+
`}function Tt(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?`
|
|
6948
|
+
kvBinding: "${t}",`:"",l=r?`
|
|
6826
6949
|
r2Binding: "${r}",`:"",p=`
|
|
6827
6950
|
realtimeBinding: "${a}",
|
|
6828
6951
|
realtimeObjectName: "${o}",
|
|
6829
6952
|
realtimeSubscribePath: "${i}",
|
|
6830
6953
|
realtimeWebsocketPath: "${s}",
|
|
6831
6954
|
realtimeProtocol: "${c}",`;return `const generatedHandlerOptions = {
|
|
6832
|
-
databaseBinding: "${e}",${
|
|
6833
|
-
schedulerBinding: "${n}",${
|
|
6955
|
+
databaseBinding: "${e}",${u}
|
|
6956
|
+
schedulerBinding: "${n}",${l}${p}
|
|
6834
6957
|
};
|
|
6835
6958
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6836
6959
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
@@ -6841,10 +6964,10 @@ import { registerAdminDashboard } from "./admin.routes";
|
|
|
6841
6964
|
import { Hono } from "hono";
|
|
6842
6965
|
import { cors } from "hono/cors";
|
|
6843
6966
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6844
|
-
`}function
|
|
6967
|
+
`}function Rt(){return `type WorkerEnv = {
|
|
6845
6968
|
Bindings: Record<string, unknown>;
|
|
6846
6969
|
};
|
|
6847
|
-
`}function
|
|
6970
|
+
`}function kt(e,t,n,r,a,o,i,s,c,u){return vt()+Rt()+wt()+Tt(t,n,r,a,o,i,s,c,u)+bt(e,t,n)+xt()}function St(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function Y(e,t){let n={...e};for(let[r,a]of Object.entries(t)){let o=n[r];if(St(o)&&St(a)){n[r]=Y(o,a);continue}n[r]=a;}return n}function kr(e){return Array.from(new Set(e.filter(t=>t.length>0)))}function At(e,t){let n=t.filter(d=>d.kind==="scheduler"||d.kind==="cron"),r=kr(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 Y(u,p)}function ee(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 Nt(e){return e.tables.map(t=>({exportName:t.exportName,tableName:t.tableName,columns:t.columns.map(n=>n.name)}))}function $t(e){return `<li data-name="users">
|
|
6848
6971
|
<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">
|
|
6849
6972
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6850
6973
|
<span class="truncate">users</span>
|
|
@@ -6856,17 +6979,17 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6856
6979
|
<span class="truncate">${n.tableName}</span>
|
|
6857
6980
|
</a>
|
|
6858
6981
|
</li>`).join(`
|
|
6859
|
-
`)}`}function
|
|
6982
|
+
`)}`}function te(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+=`
|
|
6860
6983
|
${n}<li data-name="${e.name}" class="folder-item">`,i+=`
|
|
6861
6984
|
${n} <details class="group/folder" open>`,i+=`
|
|
6862
6985
|
${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+=`
|
|
6863
6986
|
${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+=`
|
|
6864
6987
|
${n} <span class="truncate font-medium">${e.name}</span>`,i+=`
|
|
6865
6988
|
${n} </summary>`,i+=`
|
|
6866
|
-
${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+=
|
|
6989
|
+
${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+=te(c,t+2);for(let c of e.handlers){let u=c.kind==="query"?"solar:reorder-linear":"solar:bolt-linear";i+=`
|
|
6867
6990
|
${n} <li data-name="${c.exportName}">`,i+=`
|
|
6868
6991
|
${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+=`
|
|
6869
|
-
${n} <iconify-icon icon="${
|
|
6992
|
+
${n} <iconify-icon icon="${u}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
6870
6993
|
${n} <span class="truncate">${c.exportName}</span>`,i+=`
|
|
6871
6994
|
${n} </a>`,i+=`
|
|
6872
6995
|
${n} </li>`;}i+=`
|
|
@@ -6878,7 +7001,7 @@ ${n} <a href="/admin/functions${s.routePath}" hx-get="/admin/functions${s.route
|
|
|
6878
7001
|
${n} <iconify-icon icon="${c}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
6879
7002
|
${n} <span class="truncate">${s.exportName}</span>`,i+=`
|
|
6880
7003
|
${n} </a>`,i+=`
|
|
6881
|
-
${n}</li>`;}return i}function
|
|
7004
|
+
${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filter(s=>s.kind==="mutation"),r=ee(t),a=ee(n),o=r.map(s=>te(s,0)).join(""),i=a.map(s=>te(s,0)).join("");return `
|
|
6882
7005
|
<div id="pane-functions" class="flex flex-col h-full hidden">
|
|
6883
7006
|
<div class="px-3 pt-5 pb-3">
|
|
6884
7007
|
<p class="text-[10px] font-semibold uppercase tracking-widest opacity-35 mb-3 px-1">Functions</p>
|
|
@@ -6900,7 +7023,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6900
7023
|
<ul class="flex flex-col gap-0.5">${i}</ul>`:""}
|
|
6901
7024
|
</nav>
|
|
6902
7025
|
</div>
|
|
6903
|
-
`}function
|
|
7026
|
+
`}function Ft(e){return e.map(t=>`
|
|
6904
7027
|
<a
|
|
6905
7028
|
href="/admin/table/${t.exportName}"
|
|
6906
7029
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
@@ -6917,9 +7040,9 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6917
7040
|
</div>
|
|
6918
7041
|
</div>
|
|
6919
7042
|
</a>
|
|
6920
|
-
`.replace(/\n/g,"\\n")).join("")}function
|
|
7043
|
+
`.replace(/\n/g,"\\n")).join("")}function qt(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
6921
7044
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6922
|
-
`).join("")}function Sr(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
|
|
7045
|
+
`).join("")}function Sr(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 Mt(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n),a=r?Sr(r.type):"mdi:format-text";return `
|
|
6923
7046
|
<th>
|
|
6924
7047
|
<a href="#"
|
|
6925
7048
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -6931,7 +7054,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6931
7054
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6932
7055
|
</a>
|
|
6933
7056
|
</th>
|
|
6934
|
-
`}).join("")}function
|
|
7057
|
+
`}).join("")}function Et(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 ne(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"?`
|
|
6935
7058
|
<div class="form-control">
|
|
6936
7059
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6937
7060
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6979,7 +7102,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
6979
7102
|
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6980
7103
|
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm"${a} />
|
|
6981
7104
|
</div>
|
|
6982
|
-
`}function
|
|
7105
|
+
`}function re(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n);if(!r)return "";let a=r.optional?"":`
|
|
6983
7106
|
if (raw_${n} === '') {
|
|
6984
7107
|
return c.text('${n} is required', 400);
|
|
6985
7108
|
}
|
|
@@ -7034,7 +7157,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7034
7157
|
payload.${n} = raw_${n};
|
|
7035
7158
|
}
|
|
7036
7159
|
`}).join(`
|
|
7037
|
-
`)}function
|
|
7160
|
+
`)}function jt(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function It(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function Pt(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function Ot(e,t,n,r){return t?`<td class="text-right">
|
|
7038
7161
|
<div class="drawer drawer-end">
|
|
7039
7162
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
7040
7163
|
<div class="drawer-content">
|
|
@@ -7087,7 +7210,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7087
7210
|
</div>
|
|
7088
7211
|
</div>
|
|
7089
7212
|
</div>
|
|
7090
|
-
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function
|
|
7213
|
+
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function W(e){return `
|
|
7091
7214
|
<div class="flex flex-col sm:flex-row justify-between items-center mt-4 gap-3 py-3 px-1">
|
|
7092
7215
|
<div class="text-xs text-base-content/40">
|
|
7093
7216
|
Total found: <span class="font-medium text-base-content/60">\${total}</span>
|
|
@@ -7109,7 +7232,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7109
7232
|
\` : 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>\`}
|
|
7110
7233
|
</div>
|
|
7111
7234
|
\` : ''}
|
|
7112
|
-
</div>`}function
|
|
7235
|
+
</div>`}function H(e,t="Search term or filter..."){return `
|
|
7113
7236
|
<div class="form-control w-full md:w-auto relative">
|
|
7114
7237
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
7115
7238
|
<input type="text"
|
|
@@ -7120,7 +7243,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7120
7243
|
hx-trigger="keyup changed delay:500ms, search"
|
|
7121
7244
|
hx-target="#main-content"
|
|
7122
7245
|
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" />
|
|
7123
|
-
</div>`}function
|
|
7246
|
+
</div>`}function Dt(e,t,n,r,a,o,i,s,c,u){let l=W(`/admin/table/${e.exportName}`),p=H(`/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?`
|
|
7124
7247
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
7125
7248
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
7126
7249
|
<div class="text-xs text-base-content/70">
|
|
@@ -7310,7 +7433,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7310
7433
|
</tbody>
|
|
7311
7434
|
</table>
|
|
7312
7435
|
</div>
|
|
7313
|
-
${
|
|
7436
|
+
${l}
|
|
7314
7437
|
</div>
|
|
7315
7438
|
\`;
|
|
7316
7439
|
|
|
@@ -7339,7 +7462,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7339
7462
|
${p}
|
|
7340
7463
|
</div>
|
|
7341
7464
|
\${tableHtml}
|
|
7342
|
-
${
|
|
7465
|
+
${x}
|
|
7343
7466
|
</div>
|
|
7344
7467
|
<div class="drawer-side z-50">
|
|
7345
7468
|
<label for="create-drawer-${e.exportName}" aria-label="close sidebar" class="drawer-overlay"></label>
|
|
@@ -7355,7 +7478,7 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7355
7478
|
<input type="hidden" name="order" value="\${order}" />
|
|
7356
7479
|
<input type="hidden" name="search" value="\${search}" />
|
|
7357
7480
|
<input type="hidden" name="page" value="\${page}" />
|
|
7358
|
-
${
|
|
7481
|
+
${u}
|
|
7359
7482
|
<button type="submit" class="btn btn-primary btn-sm mt-2">Create record</button>
|
|
7360
7483
|
</form>
|
|
7361
7484
|
</div>
|
|
@@ -7372,11 +7495,11 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7372
7495
|
title: "${e.tableName} - Admin Dashboard",
|
|
7373
7496
|
children: content
|
|
7374
7497
|
}));
|
|
7375
|
-
});`}function
|
|
7498
|
+
});`}function Vt(e,t,n,r,a,o,i,s){let c=r==="number"?`
|
|
7376
7499
|
const parsedId = Number(rawId);
|
|
7377
7500
|
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
7378
7501
|
idValue = parsedId;
|
|
7379
|
-
`:"",
|
|
7502
|
+
`:"",l=a?`
|
|
7380
7503
|
adminApp.post('/table/${e}/edit', async (c) => {
|
|
7381
7504
|
const db = drizzle(c.env[options.databaseBinding], { schema });
|
|
7382
7505
|
const tableSchema = (schema as any).${e};
|
|
@@ -7504,16 +7627,16 @@ ${n}</li>`;}return i}function $t(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7504
7627
|
});
|
|
7505
7628
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7506
7629
|
});
|
|
7507
|
-
${
|
|
7508
|
-
`}function
|
|
7509
|
-
`+
|
|
7630
|
+
${l}
|
|
7631
|
+
`}function ae(e){let t=jt(e),n=!!t,r=e.columns.map(w=>w.name),a=r.filter(w=>It(e,w)),o=r.filter(w=>Pt(e,w)),i=qt(e),s=Mt(e,r),c=Et(e,r,t),u=a.map(w=>ne(e,w,"create")).join(""),l=o.map(w=>ne(e,w,"edit")).join(""),p=re(e,a),d=re(e,o),y=n?t:r[0]||"id",x=e.columns.find(w=>w.name===t)?.type,N=Ot(e,n,t,l);return Dt(e,y,t,n,r,i,s,c,N,u)+`
|
|
7632
|
+
`+Vt(e.exportName,y,t,x,n,i,p,d)}function Bt(){return `
|
|
7510
7633
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7511
7634
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
7512
7635
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
7513
7636
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
7514
7637
|
const search = params.search ? params.search : '';
|
|
7515
7638
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
7516
|
-
};`}function
|
|
7639
|
+
};`}function Wt(){return `
|
|
7517
7640
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7518
7641
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7519
7642
|
<div class="modal">
|
|
@@ -7534,7 +7657,7 @@ ${u}
|
|
|
7534
7657
|
</div>
|
|
7535
7658
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
7536
7659
|
</div>
|
|
7537
|
-
\`}`}function
|
|
7660
|
+
\`}`}function Ht(){return `
|
|
7538
7661
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7539
7662
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7540
7663
|
<div class="modal">
|
|
@@ -7555,8 +7678,8 @@ ${u}
|
|
|
7555
7678
|
</div>
|
|
7556
7679
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
7557
7680
|
</div>
|
|
7558
|
-
\`}`}var Ar=["id","name","email","role","createdAt","banned"],Nr={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function $r(e){let t=Nr[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
|
|
7559
|
-
`),t=
|
|
7681
|
+
\`}`}var Ar=["id","name","email","role","createdAt","banned"],Nr={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function $r(e){let t=Nr[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 Lt(){let e=Ar.map($r).join(`
|
|
7682
|
+
`),t=W("/admin/users");return `
|
|
7560
7683
|
const tableHtml = html\`
|
|
7561
7684
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
7562
7685
|
<div class="overflow-x-auto">
|
|
@@ -7624,8 +7747,8 @@ ${u}
|
|
|
7624
7747
|
</div>
|
|
7625
7748
|
</div>
|
|
7626
7749
|
</div>
|
|
7627
|
-
${Bt()}
|
|
7628
7750
|
${Wt()}
|
|
7751
|
+
${Ht()}
|
|
7629
7752
|
</td>
|
|
7630
7753
|
</tr>
|
|
7631
7754
|
\`)}
|
|
@@ -7641,7 +7764,7 @@ ${Wt()}
|
|
|
7641
7764
|
${t}
|
|
7642
7765
|
</div>
|
|
7643
7766
|
\`;
|
|
7644
|
-
`}function
|
|
7767
|
+
`}function zt(){return `
|
|
7645
7768
|
const content = html\`
|
|
7646
7769
|
<div id="main-content">
|
|
7647
7770
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -7653,11 +7776,11 @@ ${Wt()}
|
|
|
7653
7776
|
<iconify-icon icon="mdi:refresh" width="14" height="14"></iconify-icon>
|
|
7654
7777
|
</button>
|
|
7655
7778
|
</div>
|
|
7656
|
-
${
|
|
7779
|
+
${H("/admin/users","Search users...")}
|
|
7657
7780
|
</div>
|
|
7658
7781
|
\${tableHtml}
|
|
7659
7782
|
</div>
|
|
7660
|
-
\`;`}function
|
|
7783
|
+
\`;`}function Ut(){let e=Lt(),t=zt();return `
|
|
7661
7784
|
adminApp.get('/users', async (c) => {
|
|
7662
7785
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
7663
7786
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7713,7 +7836,7 @@ ${Wt()}
|
|
|
7713
7836
|
title: "users - Admin Dashboard",
|
|
7714
7837
|
children: content,
|
|
7715
7838
|
}));
|
|
7716
|
-
});`}function
|
|
7839
|
+
});`}function _t(){return `
|
|
7717
7840
|
adminApp.post('/users/edit', async (c) => {
|
|
7718
7841
|
const session = await requireAdminSession(c);
|
|
7719
7842
|
if (!session) {
|
|
@@ -7856,8 +7979,8 @@ ${Wt()}
|
|
|
7856
7979
|
const resolvedPage = String(Math.min(nextPageCandidate, totalPages));
|
|
7857
7980
|
|
|
7858
7981
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7859
|
-
});`}function
|
|
7860
|
-
${
|
|
7982
|
+
});`}function oe(){return `
|
|
7983
|
+
${Bt()}
|
|
7861
7984
|
|
|
7862
7985
|
const requireAdminSession = async (c: any) => {
|
|
7863
7986
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7868,12 +7991,12 @@ ${Wt()}
|
|
|
7868
7991
|
return session;
|
|
7869
7992
|
};
|
|
7870
7993
|
|
|
7871
|
-
${zt()}
|
|
7872
|
-
|
|
7873
7994
|
${Ut()}
|
|
7874
|
-
|
|
7995
|
+
|
|
7996
|
+
${_t()}
|
|
7997
|
+
`}function Qt(e){return `${e.tables.map(t=>ae(t)).join(`
|
|
7875
7998
|
`)}
|
|
7876
|
-
${
|
|
7999
|
+
${oe()}`}function Jt(e){return `
|
|
7877
8000
|
<div class="flex items-center justify-between">
|
|
7878
8001
|
<div class="flex items-center gap-3">
|
|
7879
8002
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -7948,14 +8071,14 @@ ${ae()}`}function Qt(e){return `
|
|
|
7948
8071
|
class="textarea textarea-sm textarea-bordered font-mono w-full bg-base-200/30 focus:bg-base-100 focus:border-primary transition-all rounded-xl border-base-200 resize-y text-xs"
|
|
7949
8072
|
${r.optional?"":"required"}
|
|
7950
8073
|
>${r.defaultValue??""}</textarea>
|
|
7951
|
-
</div>`;if(r.type==="array"){let
|
|
8074
|
+
</div>`;if(r.type==="array"){let u=r.itemType??"string",l=JSON.stringify((r.itemFields??[]).map(p=>({name:p.name,type:p.type})));return `
|
|
7952
8075
|
<div class="form-control">
|
|
7953
8076
|
${s}
|
|
7954
8077
|
<div
|
|
7955
8078
|
data-arg-key="${r.name}"
|
|
7956
8079
|
data-arg-type="array"
|
|
7957
|
-
data-item-type="${
|
|
7958
|
-
data-item-fields='${
|
|
8080
|
+
data-item-type="${u}"
|
|
8081
|
+
data-item-fields='${l}'
|
|
7959
8082
|
class="flex flex-col gap-2"
|
|
7960
8083
|
></div>
|
|
7961
8084
|
<button
|
|
@@ -7979,7 +8102,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
7979
8102
|
${r.optional?"":"required"}
|
|
7980
8103
|
/>
|
|
7981
8104
|
</div>`}).join(`
|
|
7982
|
-
`)}function
|
|
8105
|
+
`)}function Mr(e){return `
|
|
7983
8106
|
<div class="space-y-4">
|
|
7984
8107
|
<div class="flex items-center justify-between">
|
|
7985
8108
|
<div class="flex flex-col">
|
|
@@ -7996,7 +8119,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
7996
8119
|
</div>
|
|
7997
8120
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7998
8121
|
</div>
|
|
7999
|
-
`}function
|
|
8122
|
+
`}function Er(){return `
|
|
8000
8123
|
<div class="space-y-4">
|
|
8001
8124
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
8002
8125
|
<div class="relative group">
|
|
@@ -8013,7 +8136,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8013
8136
|
</div>
|
|
8014
8137
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
8015
8138
|
</div>
|
|
8016
|
-
`}function
|
|
8139
|
+
`}function jr(){return `
|
|
8017
8140
|
<div class="space-y-4">
|
|
8018
8141
|
<div class="flex items-center justify-between">
|
|
8019
8142
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -8048,13 +8171,13 @@ ${ae()}`}function Qt(e){return `
|
|
|
8048
8171
|
<!-- Tab Content -->
|
|
8049
8172
|
<div class="flex-1 overflow-y-auto">
|
|
8050
8173
|
<div id="request-tab-args" class="p-5">
|
|
8051
|
-
${
|
|
8174
|
+
${Mr(e)}
|
|
8052
8175
|
</div>
|
|
8053
8176
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
8054
|
-
${
|
|
8177
|
+
${Er()}
|
|
8055
8178
|
</div>
|
|
8056
8179
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
8057
|
-
${
|
|
8180
|
+
${jr()}
|
|
8058
8181
|
</div>
|
|
8059
8182
|
</div>
|
|
8060
8183
|
|
|
@@ -8072,7 +8195,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8072
8195
|
</form>
|
|
8073
8196
|
</div>
|
|
8074
8197
|
</div>
|
|
8075
|
-
`}function
|
|
8198
|
+
`}function Gt(){return `
|
|
8076
8199
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
8077
8200
|
<!-- Panel Header -->
|
|
8078
8201
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -8154,7 +8277,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8154
8277
|
|
|
8155
8278
|
</div>
|
|
8156
8279
|
</div>
|
|
8157
|
-
`}function
|
|
8280
|
+
`}function Zt(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
8158
8281
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
8159
8282
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
8160
8283
|
|
|
@@ -8845,21 +8968,21 @@ ${ae()}`}function Qt(e){return `
|
|
|
8845
8968
|
_rtEnabled = false;
|
|
8846
8969
|
});
|
|
8847
8970
|
</script>
|
|
8848
|
-
`}function
|
|
8971
|
+
`}function Xt(e){return `
|
|
8849
8972
|
const content = html\`
|
|
8850
8973
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
8851
|
-
${
|
|
8974
|
+
${Jt(e)}
|
|
8852
8975
|
|
|
8853
8976
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
8854
8977
|
<!-- Request Panel -->
|
|
8855
8978
|
${Kt(e)}
|
|
8856
8979
|
|
|
8857
8980
|
<!-- Result Panel -->
|
|
8858
|
-
${
|
|
8981
|
+
${Gt()}
|
|
8859
8982
|
</div>
|
|
8860
8983
|
</div>
|
|
8861
8984
|
|
|
8862
|
-
${
|
|
8985
|
+
${Zt(e)}
|
|
8863
8986
|
\`;
|
|
8864
8987
|
|
|
8865
8988
|
if (c.req.header('hx-request')) {
|
|
@@ -8869,11 +8992,11 @@ ${ae()}`}function Qt(e){return `
|
|
|
8869
8992
|
return c.html(Layout({
|
|
8870
8993
|
title: "${e.exportName} - Functions",
|
|
8871
8994
|
children: content
|
|
8872
|
-
}));`}function
|
|
8995
|
+
}));`}function Yt(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
8873
8996
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
8874
|
-
${
|
|
8997
|
+
${Xt(n)}
|
|
8875
8998
|
});`).join(`
|
|
8876
|
-
`)}function
|
|
8999
|
+
`)}function en(){return `
|
|
8877
9000
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
8878
9001
|
const r2Binding = (options as any).r2Binding;
|
|
8879
9002
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -8942,7 +9065,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
8942
9065
|
const parts = prefix.split('/').filter(Boolean);
|
|
8943
9066
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
8944
9067
|
};
|
|
8945
|
-
`}function
|
|
9068
|
+
`}function tn(){return `
|
|
8946
9069
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
8947
9070
|
const parts = prefix.split('/').filter(Boolean);
|
|
8948
9071
|
const breadcrumbs: any[] = [];
|
|
@@ -9069,7 +9192,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9069
9192
|
</div>
|
|
9070
9193
|
\`;
|
|
9071
9194
|
};
|
|
9072
|
-
`}function
|
|
9195
|
+
`}function nn(){return `
|
|
9073
9196
|
const handleStorageListRoute = async (c: any) => {
|
|
9074
9197
|
const bucket = getStorageBucket(c);
|
|
9075
9198
|
if (!bucket) {
|
|
@@ -9091,7 +9214,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9091
9214
|
|
|
9092
9215
|
adminApp.get('/storage', handleStorageListRoute);
|
|
9093
9216
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
9094
|
-
`}function
|
|
9217
|
+
`}function rn(){return `
|
|
9095
9218
|
adminApp.post('/storage/upload', async (c) => {
|
|
9096
9219
|
const bucket = getStorageBucket(c);
|
|
9097
9220
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9109,7 +9232,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9109
9232
|
|
|
9110
9233
|
return c.redirect(prefixToStoragePath(prefix));
|
|
9111
9234
|
});
|
|
9112
|
-
`}function
|
|
9235
|
+
`}function an(){return `
|
|
9113
9236
|
adminApp.delete('/storage/delete', async (c) => {
|
|
9114
9237
|
const bucket = getStorageBucket(c);
|
|
9115
9238
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9124,7 +9247,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9124
9247
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
9125
9248
|
return c.html('');
|
|
9126
9249
|
});
|
|
9127
|
-
`}function
|
|
9250
|
+
`}function on(){return `
|
|
9128
9251
|
adminApp.post('/storage/directory', async (c) => {
|
|
9129
9252
|
const bucket = getStorageBucket(c);
|
|
9130
9253
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9150,7 +9273,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9150
9273
|
|
|
9151
9274
|
return c.redirect(prefixToStoragePath(prefix));
|
|
9152
9275
|
});
|
|
9153
|
-
`}function
|
|
9276
|
+
`}function sn(){return `
|
|
9154
9277
|
adminApp.get('/storage/download', async (c) => {
|
|
9155
9278
|
const bucket = getStorageBucket(c);
|
|
9156
9279
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9170,7 +9293,7 @@ ${ae()}`}function Qt(e){return `
|
|
|
9170
9293
|
|
|
9171
9294
|
return new Response(object.body, { headers });
|
|
9172
9295
|
});
|
|
9173
|
-
`}function
|
|
9296
|
+
`}function ln(){return `
|
|
9174
9297
|
adminApp.get('/storage/preview', async (c) => {
|
|
9175
9298
|
const bucket = getStorageBucket(c);
|
|
9176
9299
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9188,25 +9311,25 @@ ${ae()}`}function Qt(e){return `
|
|
|
9188
9311
|
|
|
9189
9312
|
return new Response(object.body, { headers });
|
|
9190
9313
|
});
|
|
9191
|
-
`}function
|
|
9192
|
-
${on()}
|
|
9193
|
-
|
|
9314
|
+
`}function un(){return `
|
|
9194
9315
|
${sn()}
|
|
9195
9316
|
|
|
9196
|
-
${
|
|
9317
|
+
${ln()}
|
|
9197
9318
|
|
|
9198
9319
|
${rn()}
|
|
9199
9320
|
|
|
9200
9321
|
${an()}
|
|
9201
9322
|
|
|
9202
|
-
${
|
|
9203
|
-
`}function un(){return `
|
|
9204
|
-
${Yt()}
|
|
9323
|
+
${on()}
|
|
9205
9324
|
|
|
9325
|
+
${nn()}
|
|
9326
|
+
`}function cn(){return `
|
|
9206
9327
|
${en()}
|
|
9207
9328
|
|
|
9208
|
-
${
|
|
9209
|
-
|
|
9329
|
+
${tn()}
|
|
9330
|
+
|
|
9331
|
+
${un()}
|
|
9332
|
+
`}function dn(e,t){let n=Ct(t);return `
|
|
9210
9333
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
9211
9334
|
return html\`<!DOCTYPE html>
|
|
9212
9335
|
<html lang="en" data-theme="light">
|
|
@@ -9613,7 +9736,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9613
9736
|
</body>
|
|
9614
9737
|
</html>\`;
|
|
9615
9738
|
}
|
|
9616
|
-
`}function
|
|
9739
|
+
`}function pn(){return `
|
|
9617
9740
|
// Auth Middleware
|
|
9618
9741
|
adminApp.use('*', async (c, next) => {
|
|
9619
9742
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -9672,7 +9795,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9672
9795
|
}
|
|
9673
9796
|
await next();
|
|
9674
9797
|
});
|
|
9675
|
-
`}function
|
|
9798
|
+
`}function mn(e){return `
|
|
9676
9799
|
adminApp.get('/', (c) => {
|
|
9677
9800
|
return c.html(Layout({
|
|
9678
9801
|
title: "Admin Dashboard",
|
|
@@ -9689,7 +9812,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9689
9812
|
\`
|
|
9690
9813
|
}));
|
|
9691
9814
|
});
|
|
9692
|
-
`}function
|
|
9815
|
+
`}function fn(e,t,n){let r=Nt(t),a=$t(r),o=Ft(r),i=Qt(t),s=Yt(n),c=cn(),u=dn(a,n),l=pn(),p=mn(o);return `import { Hono } from "hono";
|
|
9693
9816
|
import { html, raw } from "hono/html";
|
|
9694
9817
|
import { drizzle } from "drizzle-orm/d1";
|
|
9695
9818
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -9697,12 +9820,12 @@ import { createAuth } from "./auth.config";
|
|
|
9697
9820
|
import * as schema from "${e}";
|
|
9698
9821
|
import { users } from "./auth.schema";
|
|
9699
9822
|
|
|
9700
|
-
${
|
|
9823
|
+
${u}
|
|
9701
9824
|
|
|
9702
9825
|
export function registerAdminDashboard(app: Hono<any>, options: { databaseBinding: string, r2Binding?: string }) {
|
|
9703
9826
|
const adminApp = new Hono<any>();
|
|
9704
9827
|
|
|
9705
|
-
${
|
|
9828
|
+
${l}
|
|
9706
9829
|
|
|
9707
9830
|
${p}
|
|
9708
9831
|
|
|
@@ -9718,8 +9841,8 @@ ${p}
|
|
|
9718
9841
|
app.route('/admin', adminApp);
|
|
9719
9842
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
9720
9843
|
}
|
|
9721
|
-
`}function
|
|
9722
|
-
`}function Qr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function
|
|
9844
|
+
`}function ie(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 I(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function q(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(t,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(t,n)=>n.toUpperCase())}function ue(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 Pr(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 Or(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 L(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function gn(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 hn(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 yn(e,t){return `${e}:${t}`}function Dr(e,t,n,r){let a=yn(e,t),o=yn(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 Vr(e,t){return `${e}${q(t)}Links`}function bn(e,t,n){let r=ue(e),a=ue(t);return r===a?`${n}${q(r)}Id`:`${r}Id`}function Br(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 Wr(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=Dr(n,o,a.targetTable,i),c=bn(s.leftTable,s.rightTable,"source"),u=bn(s.rightTable,s.leftTable,"target"),l={leftTable:s.leftTable,leftReferenceField:s.leftReferenceField,rightTable:s.rightTable,rightReferenceField:s.rightReferenceField,junctionTable:a.junctionTable??Vr(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?Br(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=L(e,n.leftTable,n.leftReferenceField)??"string",a=L(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 Hr(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 Lr(e){Hr(e);let t=Or(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=L(t,o.targetTable,i)??o.fkType??"string";gn(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:hn(`${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??`${ue(n)}Id`;a.field=s;let c=L(t,n,i)??a.fkType??"string";gn(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:hn(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},c);}return Wr(t),t}function xn(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function P(e){return e.notNull!==true}function zr(e,t,n){let r=t.sqlName??I(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=z(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 Ur(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 _r(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
9845
|
+
`}function Qr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function Jr(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 Kr(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=ce(i.jsonShape);a.push(`${g(o)}: { shape: ${s} },`);}a.length!==0&&t.push(`${g(n)}: {
|
|
9723
9846
|
${a.map(o=>` ${o}`).join(`
|
|
9724
9847
|
`)}
|
|
9725
9848
|
},`);}return t.length===0?`export const __appflareJsonColumns = {} as const;
|
|
@@ -9727,7 +9850,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9727
9850
|
${t.map(n=>` ${n}`).join(`
|
|
9728
9851
|
`)}
|
|
9729
9852
|
} as const;
|
|
9730
|
-
`}function
|
|
9853
|
+
`}function ce(e){return e.kind==="array"?`{ kind: "array", element: ${ce(e.element)} }`:e.kind==="object"?`{ kind: "object", shape: { ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${ce(r)}`).join(", ")} } }`:`{ kind: ${g(e.kind)} }`}function Gr(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)}: {
|
|
9731
9854
|
targetTable: ${g(i.targetTable)},
|
|
9732
9855
|
junctionTable: ${g(i.junctionTable)},
|
|
9733
9856
|
sourceField: ${g(i.sourceField??"")},
|
|
@@ -9768,27 +9891,27 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9768
9891
|
${t.map(n=>` ${n}`).join(`
|
|
9769
9892
|
`)}
|
|
9770
9893
|
} as const;
|
|
9771
|
-
`}function Xr(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let l of Object.values(e.tables)){for(let
|
|
9772
|
-
${g(
|
|
9894
|
+
`}function Xr(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 Qr(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=q(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??I(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 k=h.enumRef??`${l}_${b}`,V=q(k),B=h.sqlName??I(b);v=B!==b?`${V}Column(${g(B)})`:`${V}Column()`,h.isArray&&(v+=".array()");}else v=zr(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(${Pr(h.sqlDefault)})`);let A=Jr(b,h,p);if(A)if(h.references?.onDelete||h.references?.onUpdate){let k=[];h.references.onDelete&&k.push(`onDelete: ${g(h.references.onDelete)}`),h.references.onUpdate&&k.push(`onUpdate: ${g(h.references.onUpdate)}`),v+=`.references((): AnySQLiteColumn => ${A.tableName}.${A.fieldName}, { ${k.join(", ")} })`;}else v+=`.references((): AnySQLiteColumn => ${A.tableName}.${A.fieldName})`;if(h.unique){let k=typeof h.unique=="object"&&h.unique.name?h.unique.name:`${d}_${I(b)}_unique_idx`;x.push(` t.uniqueIndex(${g(k)}).on(table.${b})`);}if(h.index){let k=typeof h.index=="object"&&h.index.name?h.index.name:`${d}_${I(b)}_idx`;x.push(` t.index(${g(k)}).on(table.${b})`);}y.push(` ${b}: ${v},`);}x.length>0?s.push(`export const ${l} = table(
|
|
9895
|
+
${g(d)},
|
|
9773
9896
|
{
|
|
9774
|
-
${
|
|
9897
|
+
${y.join(`
|
|
9775
9898
|
`)}
|
|
9776
9899
|
},
|
|
9777
9900
|
(table) => [
|
|
9778
|
-
${
|
|
9901
|
+
${x.join(`,
|
|
9779
9902
|
`)}
|
|
9780
9903
|
],
|
|
9781
|
-
);`):s.push(`export const ${l} = table(${g(
|
|
9782
|
-
${
|
|
9904
|
+
);`):s.push(`export const ${l} = table(${g(d)}, {
|
|
9905
|
+
${y.join(`
|
|
9783
9906
|
`)}
|
|
9784
|
-
});`);let
|
|
9907
|
+
});`);let N=Object.entries(p.relations).filter(([,b])=>b.relation==="one"),w=Object.entries(p.relations).filter(([,b])=>b.relation==="many"),D=Object.entries(p.relations).filter(([,b])=>b.relation==="manyToMany");if(N.length===0&&w.length===0&&D.length===0)continue;let E=[];for(let[b,h]of N){let v=Ur(l,p,h);E.push(` ${b}: one(${h.targetTable}, {
|
|
9785
9908
|
fields: [${l}.${v.sourceField}],
|
|
9786
9909
|
references: [${h.targetTable}.${v.targetField}],
|
|
9787
|
-
}),`);}for(let[b,h]of
|
|
9788
|
-
${
|
|
9910
|
+
}),`);}for(let[b,h]of w)E.push(` ${b}: many(${h.targetTable}),`);for(let[b,h]of D){if(!h.junctionTable)throw new Error(`manyToMany relation '${l}.${b}' is missing junctionTable after normalization.`);E.push(` ${b}: many(${h.junctionTable}),`);}c.push(`export const ${l}Relations = relations(${l}, ({ one, many }) => ({
|
|
9911
|
+
${E.join(`
|
|
9789
9912
|
`)}
|
|
9790
|
-
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9791
|
-
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
9913
|
+
}));`),u.push(` ${l}Relations,`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9914
|
+
import { sqliteTable as table, type AnySQLiteColumn } from "drizzle-orm/sqlite-core";
|
|
9792
9915
|
import { relations } from "drizzle-orm";
|
|
9793
9916
|
${_r(r)}
|
|
9794
9917
|
${o.join(`
|
|
@@ -9804,12 +9927,17 @@ ${c.join(`
|
|
|
9804
9927
|
|
|
9805
9928
|
`)}
|
|
9806
9929
|
|
|
9807
|
-
|
|
9930
|
+
export const __appflareDbSchema = {
|
|
9931
|
+
${u.join(`
|
|
9932
|
+
`)}
|
|
9933
|
+
} as const;
|
|
9934
|
+
|
|
9935
|
+
${Kr(e)}
|
|
9808
9936
|
|
|
9809
9937
|
${Gr(e)}
|
|
9810
9938
|
|
|
9811
9939
|
${Zr(e)}
|
|
9812
|
-
`}function
|
|
9940
|
+
`}function de(e){return e.kind==="array"?`z.array(${de(e.element)})`:e.kind==="object"?`z.object({ ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${de(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 wn(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=de(e.jsonShape));return t&&(r+=".optional()"),n&&(r+=".nullable()"),r}function Yr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=q(n),o=[],i=[];for(let[s,c]of Object.entries(r.columns))o.push(` ${s}: ${wn(c,xn(c),P(c))},`),i.push(` ${s}: ${wn(c,P(c),P(c))},`);t.push(`export const ${n}InsertSchema = z.object({
|
|
9813
9941
|
${o.join(`
|
|
9814
9942
|
`)}
|
|
9815
9943
|
});
|
|
@@ -9823,7 +9951,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
9823
9951
|
`);}return `import { z } from "zod";
|
|
9824
9952
|
|
|
9825
9953
|
${t.join(`
|
|
9826
|
-
`)}`}function
|
|
9954
|
+
`)}`}function z(e){return e.kind==="array"?`Array<${z(e.element)}>`:e.kind==="object"?`{ ${Object.entries(e.shape).map(([n,r])=>`${n}: ${z(r)}`).join("; ")} }`:e.kind==="string"?"string":e.kind==="number"?"number":e.kind==="boolean"?"boolean":e.kind==="date"?"Date":"unknown"}function ea(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?z(e.jsonShape):"unknown"}function ta(e){let t=[];for(let[r,a]of Object.entries(e.enums??{})){let o=q(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=q(r),i=[],s=[];for(let[c,u]of Object.entries(a.columns)){let l=ea(u),p=P(u)?" | null":"";i.push(` ${c}${P(u)?"?":""}: ${l}${p};`),s.push(` ${c}${xn(u)?"?":""}: ${l}${p};`);}n.push(`export type ${o} = {
|
|
9827
9955
|
${i.join(`
|
|
9828
9956
|
`)}
|
|
9829
9957
|
};
|
|
@@ -9836,25 +9964,25 @@ ${s.join(`
|
|
|
9836
9964
|
${n.join(`
|
|
9837
9965
|
|
|
9838
9966
|
`)}
|
|
9839
|
-
`}function na(e,t){if(t){let n=e[t];if(!oe(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(oe(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function xn(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()}`),l=na(c,t.exportName),u=Lr(l);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(u,n),d=ta(u),y=Yr(u);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(u.tables)}}function aa(e){return e.replaceAll("\\","/")}function j(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 kn(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 kn(a));continue}r.isFile()&&la.has(path.extname(r.name))&&n.push(a);}return n}function pe(e){return e.replace(/\.[cm]?tsx?$/,"")}function de(e,t){let n=e,r=false,a,o="unknown",i,s,c;for(;f__namespace.isCallExpression(n);){let l=n.expression;if(!f__namespace.isPropertyAccessExpression(l))break;let u=l.name.text;if(u==="optional"||u==="nullable")r=true,n=l.expression;else if(u==="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=l.expression;}else if(u==="string"||u==="uuid"||u==="email"||u==="url"){o="string";break}else if(u==="number"||u==="int"||u==="float"){o="number";break}else if(u==="boolean"){o="boolean";break}else if(u==="date"){o="date";break}else if(u==="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(de(d.initializer,d.name.text));}break}else if(u==="array"){o="array";let p=n.arguments[0];if(p){let d=de(p,"");s=d.type==="array"?"unknown":d.type,d.type==="object"&&(c=d.fields);}break}else n=l.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(de(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 Sn(e){return f__namespace.isIdentifier(e)?e.text:f__namespace.isParenthesizedExpression(e)?Sn(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=Sn(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=pe(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 Tn(e,t){let n=e.replace(/\\/g,"/"),a=pe(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 An(e){let t=[],n=await kn(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),l=[{kind:"query",kindDirectory:"queries",exports:c.filter(u=>u.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(u=>u.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(u=>u.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(u=>u.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(u=>u.kind==="storage")}];for(let u of l){if(u.exports.length===0)continue;let p=ma(s,u.kindDirectory);for(let d of u.exports){let y=u.kind==="query"||u.kind==="mutation"?Tn(p,d.exportName):void 0,T=u.kind==="scheduler"||u.kind==="cron"?Tn(p,d.exportName):void 0,A=u.kind==="query"||u.kind==="mutation"?[...pe(p).split("/").filter(Boolean),d.exportName]:void 0,w=u.kind==="query"?vn("queries",p,d.exportName):u.kind==="mutation"?vn("mutations",p,d.exportName):u.kind==="storage"?`/storage/managers/${d.exportName}`:`/${u.kindDirectory}/${T}`;t.push({kind:u.kind,exportName:d.exportName,filePath:a,importPath:j(e.outDirAbs,a),clientImportPath:j(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:T,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,l=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(l){n+=d,l=false;continue}if(d==="\\"){n+=d,l=true;continue}if(!s&&!c&&d==="'"){i=!i,n+=d;continue}if(!i&&!c&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){c=!c,n+=d;continue}if(i||s||c){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let u=n.trim();return u.length>0&&t.push(u),t}function 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 l=e[c];if(s){s=false;continue}if(l==="\\"){s=true;continue}if(!o&&!i&&l==="'"){a=!a;continue}if(!a&&!i&&l==='"'){o=!o;continue}if(!a&&!o&&l==="`"){i=!i;continue}if(!(a||o||i)){if(l==="("){t+=1;continue}if(l===")"){t-=1;continue}if(l==="{"){n+=1;continue}if(l==="}"){n-=1;continue}if(l==="["){r+=1;continue}if(l==="]"){r-=1;continue}if(l===":"&&t===0&&n===0&&r===0)return c}}return -1}function 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),l=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||l||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,l=false,u=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!l&&!u&&y==="'"){c=!c;continue}if(!c&&!u&&y==='"'){l=!l;continue}if(!c&&!l&&y==="`"){u=!u;continue}if(!(c||l||u)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let c=r(e,s);if(c===-1){a=t.exec(e);continue}let l=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:ba(l)}),a=t.exec(e);}return n}async function $n(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 $n(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function Cn(e,t=[]){let n=await $n(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 Ta(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
|
|
9840
|
-
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 Sa(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function
|
|
9841
|
-
`);let
|
|
9842
|
-
`);let
|
|
9843
|
-
`),...Zn,...Gn,Bun.write(
|
|
9844
|
-
`),Bun.write(Jn
|
|
9845
|
-
`);let
|
|
9846
|
-
`),
|
|
9847
|
-
`));function er(
|
|
9848
|
-
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-
|
|
9849
|
-
`);async function tr(
|
|
9850
|
-
`);let
|
|
9851
|
-
`);async function
|
|
9852
|
-
`);let nr=t+"/";async function
|
|
9853
|
-
`);let rr=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.existsSync(rr)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-
|
|
9854
|
-
`);let
|
|
9855
|
-
`);}}var
|
|
9967
|
+
`}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
|
|
9968
|
+
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 Sa(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function En(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=M(t,a),s=path.resolve(t,"client"),c=M(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)
|
|
9969
|
+
`);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=path.join(path.dirname(Bun.resolveSync("typescript/package.json",l)),"bin","tsc"),d=path.join(path.dirname(Bun.resolveSync("@better-auth/cli/package.json",l)),"dist","index.mjs"),y=path.resolve(t,"server.ts"),x=path.resolve(t,"client.ts"),N=path.resolve(t,"auth.config.ts"),w=path.resolve(t,"auth.schema.ts"),D=path.resolve(t,"drizzle.config.ts"),E=path.resolve(n,"wrangler.json"),b=await Tn(e),h=await Fn(e,b?[b.schemaPath]:[]),v=M(t,h.schemaPath),A=await Nn(e);process.stdout.write(`\u{1F50D} ${A.length} handler(s) (${(performance.now()-u).toFixed(0)}ms)
|
|
9970
|
+
`);let k=va(r),V=Ra(r),B=kt(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),ye=Ce(c,A),Ln=X(v,A,r.r2[0]?.binding,k,V),zn=ve(i),Un=b?[Sa(o,b.schemaPath),...r.schema.filter(T=>!/(^|\/)schema\.ts$/.test(T))]:r.schema,_n=Fe(Un),Qn=At(e,A),Jn=fn(v,h,A),Kn=path.resolve(t,"admin.routes.ts"),Gn=Ln.map(T=>Bun.write(path.resolve(t,T.relativePath),T.source)),Zn=ye.map(T=>Bun.write(path.resolve(t,T.relativePath),T.source));await Promise.all([Bun.write(y,B),Bun.write(x,`export * from "./client/index";
|
|
9971
|
+
`),...Zn,...Gn,Bun.write(N,zn),Bun.write(w,""),Bun.write(D,_n),Bun.write(E,`${JSON.stringify(Qn,null,2)}
|
|
9972
|
+
`),Bun.write(Kn,Jn)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-u).toFixed(0)}ms)
|
|
9973
|
+
`);let J=path.relative(o,N).replace(/\\/g,"/"),Xn=J.startsWith(".")?J:`./${J}`,K=path.relative(o,w).replace(/\\/g,"/"),Yn=K.startsWith(".")?K:`./${K}`,be=await Bun.spawn([process.execPath,d,"generate","--config",Xn,"--output",Yn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(be!==0)throw new Error(`better-auth generation failed with exit code ${be}`);process.stdout.write(`\u{1F510} Auth schema (${(performance.now()-u).toFixed(0)}ms)
|
|
9974
|
+
`),k.length>0&&(await ka(w,k),process.stdout.write(`\u{1F527} Patched role type (${(performance.now()-u).toFixed(0)}ms)
|
|
9975
|
+
`));function er(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 we=path.resolve(t,"tsconfig.js.json");await Promise.all([Bun.write(we,`${JSON.stringify(er({declaration:true,emitDeclarationOnly:false}),null,2)}
|
|
9976
|
+
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-u).toFixed(0)}ms)
|
|
9977
|
+
`);async function tr(T,C){process.stdout.write(`\u2699\uFE0F ${C}... (${(performance.now()-u).toFixed(0)}ms)
|
|
9978
|
+
`);let $=await Bun.spawn([process.execPath,p,"-p",T],{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if($!==0)throw new Error(`tsc ${C} failed with exit code ${$}`)}await tr(we,"JS files"),process.stdout.write(`\u2705 JS + declarations (${(performance.now()-u).toFixed(0)}ms)
|
|
9979
|
+
`);async function xe(T){let C=await promises.readdir(T,{withFileTypes:true});for(let R of C){let $=path.join(T,R.name);if(R.isDirectory()){if(R.name==="node_modules"||R.name.startsWith("."))continue;await xe($);}else R.name.endsWith(".ts")&&!R.name.endsWith(".d.ts")&&await promises.rm($);}}await xe(t),process.stdout.write(`\u{1F4E6} Cleaned .ts files (${(performance.now()-u).toFixed(0)}ms)
|
|
9980
|
+
`);let nr=t+"/";async function Te(T){let C=await promises.readdir(T,{withFileTypes:true});for(let R of C){let $=path.join(T,R.name);if(R.isDirectory()){if(R.name==="node_modules"||R.name.startsWith(".")||$===t)continue;await Te($);}else !$.startsWith(nr)&&(R.name.endsWith(".d.ts")||R.name.endsWith(".js"))&&await promises.rm($);}}await Te(o),process.stdout.write(`\u{1F9F9} Cleanup (${(performance.now()-u).toFixed(0)}ms)
|
|
9981
|
+
`);let rr=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.existsSync(rr)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-u).toFixed(0)}ms)
|
|
9982
|
+
`);let C=await Bun.spawn([process.execPath,p,"--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)
|
|
9983
|
+
`);}}var jn=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(),In=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),Pn=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(),On=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),queue:zod.z.string().min(1).optional()}).strict(),Ca=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(),Fa=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([jn,zod.z.array(jn).min(1)]),kv:zod.z.union([In,zod.z.array(In)]).optional(),r2:zod.z.union([Pn,zod.z.array(Pn)]).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:On.optional(),realtime:Ca.optional(),wranglerOverrides:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),build:zod.z.boolean().optional()}).strict();function Dn(e){return typeof e=="object"&&e!==null}function qa(e){let t=Dn(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=On.safeParse(t);return n.success?n.data:{}}function Ma(e){if(!Dn(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function Ea(e){let n={...qa(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:Ma(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function O(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=Fa.parse(o),s=Ea(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}}function Oa(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;}}async function Q(e,t={}){let n=await O(e);if(t.build!==void 0&&(n.config.build=t.build),await En(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
9856
9984
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
9857
|
-
`);}async function
|
|
9858
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
9985
|
+
`);}async function Bn(e,t={}){if(await Q(e,{build:t.build}),!t.watch)return;let n=await O(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await Q(e,{build:t.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
9986
|
+
`);}finally{r=false,a&&(a=false,await o());}};ja__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}
|
|
9859
9987
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
9860
|
-
`);}async function
|
|
9988
|
+
`);}async function Wn(e,t={}){let n=await O(e),r=Oa(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=process.platform==="win32"?"npx.cmd":"npx",c=await Bun.spawn([i,"drizzle-kit","generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(c!==0)throw new Error(`drizzle-kit generate failed with exit code ${c}`);let u=n.config.database[0].databaseName,l=[i,"wrangler","d1","migrations","apply",u];t.local?l.push("--local"):t.remote?l.push("--remote"):t.preview&&l.push("--preview");let d=await Bun.spawn(l,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(d!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${d}`)}async function Hn(e,t={name:"",email:"",password:""}){let n=await O(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,x=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${p}`];t.local?x.push("--local"):t.remote&&x.push("--remote");let w=await Bun.spawn(x,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(w!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${w}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var j=new commander.Command;j.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");j.command("build").description("Generate server.ts, client.ts, auth.config.js, drizzle.config.js, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--no-build","Skip TypeScript build step").action(async e=>{await Q(e.config,{build:e.build});});j.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 Bn(e.config,{watch:e.watch,build:e.build});});j.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 Wn(e.config,{local:e.local,remote:e.remote,preview:e.preview});});j.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 Hn(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 j.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|