appflare 0.2.50 → 0.2.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/commands/index.ts +33 -25
- package/cli/generate.ts +13 -8
- package/cli/templates/handlers/generators/types/query-definitions/schema-and-table-types.ts +69 -9
- package/cli/utils/resolve-package.ts +59 -0
- package/dist/cli/index.js +253 -193
- package/dist/cli/index.mjs +253 -193
- package/package.json +68 -23
- package/tsconfig.json +3 -1
- package/tsup.config.ts +0 -2
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
'use strict';var commander=require('commander'),
|
|
2
|
+
'use strict';var commander=require('commander'),Ha=require('chokidar'),path=require('path'),url=require('url'),promises=require('fs/promises'),fs=require('fs'),f=require('typescript'),zod=require('zod');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ha__default=/*#__PURE__*/_interopDefault(Ha);var f__namespace=/*#__PURE__*/_interopNamespace(f);function Re(e){return `import { betterAuth } from "better-auth";
|
|
3
3
|
import { withCloudflare } from "better-auth-cloudflare";
|
|
4
4
|
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
5
5
|
import { drizzle } from "drizzle-orm/d1";
|
|
@@ -57,7 +57,7 @@ export const createAuth = (
|
|
|
57
57
|
});
|
|
58
58
|
};
|
|
59
59
|
export const auth = createAuth();
|
|
60
|
-
`}function
|
|
60
|
+
`}function ke(){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
61
61
|
import type {
|
|
62
62
|
AppflareAuth,
|
|
63
63
|
AppflareAuthTokenResolver,
|
|
@@ -166,8 +166,8 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
166
166
|
): Appflare<Options> {
|
|
167
167
|
return new Appflare(options);
|
|
168
168
|
}
|
|
169
|
-
`}function
|
|
170
|
-
`)}function
|
|
169
|
+
`}function cr(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function Se(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function dr(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function Ae(e){let t={children:new Map};for(let n of e){let r=t;for(let a of n.segments){let o=r.children.get(a);o||(o={children:new Map},r.children.set(a,o)),r=o;}r.operation=n;}return t}function Z(e,t=1){let n=" ".repeat(t),r=" ".repeat(t+1),a=Array.from(e.children.entries()).sort(([i],[s])=>i.localeCompare(s));if(a.length===0)return e.operation?`${e.operation.alias}Route(runtime)`:"{}";let o=["{"];for(let[i,s]of a)o.push(`${r}${dr(i)}: ${Z(s,t+1)},`);return e.operation&&(o.push(`${r}run: ${e.operation.alias}Route(runtime).run,`),o.push(`${r}schema: ${e.operation.alias}Route(runtime).schema,`),e.operation.kind==="query"&&(o.push(`${r}subscribe: ${e.operation.alias}Route(runtime).subscribe,`),o.push(`${r}queryKey: ${e.operation.alias}Route(runtime).queryKey,`))),o.push(`${n}}`),o.join(`
|
|
170
|
+
`)}function pr(e,t){if(e.kind!=="query"&&e.kind!=="mutation")return null;let n=e.clientSegments&&e.clientSegments.length>0?e.clientSegments:e.routePath.replace(/^\//,"").split("/").filter(Boolean).slice(1);if(n.length>=2&&n[n.length-1]===n[n.length-2]&&n.pop(),n.length===0)return null;let r=cr(`op_${t}_${e.kind}_${n.join("_")}`);return {kind:e.kind,routePath:e.routePath,queryName:e.handlerName??n.join("/"),segments:n,importPath:e.clientImportPath,exportName:e.exportName,alias:r,schemaConst:`${r}Schema`,typeBase:`${Se(e.kind)}${Se(n.join("_"))}`}}function mr(e){let t=`${e.typeBase}Input`,n=`${e.typeBase}Output`,r=`${e.typeBase}Schema`,a=e.kind==="query"?"GET":"POST";return e.kind==="query"?`const ${e.alias}Route = (
|
|
171
171
|
runtime: RequestRuntime,
|
|
172
172
|
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}> => {
|
|
173
173
|
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}>["run"] = async (
|
|
@@ -358,15 +358,15 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
358
358
|
schema: ${r},
|
|
359
359
|
run,
|
|
360
360
|
};
|
|
361
|
-
};`}function
|
|
361
|
+
};`}function X(e){let t=e.map((u,l)=>pr(u,l)).filter(u=>u!==null),n=t.filter(u=>u.kind==="query"),r=t.filter(u=>u.kind==="mutation"),a=t.map(u=>`import { ${u.exportName} as ${u.alias} } from "${u.importPath}";`).join(`
|
|
362
362
|
`),o=t.map(u=>{let l=`${u.typeBase}Input`,p=`${u.typeBase}Output`,d=`${u.typeBase}Schema`;return `const ${u.schemaConst} = z.object(${u.alias}.definition.args);
|
|
363
363
|
export type ${l} = z.input<typeof ${u.schemaConst}>;
|
|
364
364
|
export type ${p} = Awaited<ReturnType<typeof ${u.alias}.definition.handler>>;
|
|
365
365
|
export const ${d} = ${u.schemaConst};`}).join(`
|
|
366
366
|
|
|
367
|
-
`),i=t.map(u=>
|
|
367
|
+
`),i=t.map(u=>mr(u)).join(`
|
|
368
368
|
|
|
369
|
-
`),s=
|
|
369
|
+
`),s=Z(Ae(n)),c=Z(Ae(r));return `import { z } from "zod";
|
|
370
370
|
import type {
|
|
371
371
|
AppflareErrorMode,
|
|
372
372
|
AppflareRequestError,
|
|
@@ -742,11 +742,11 @@ export function createMutationsClient(
|
|
|
742
742
|
|
|
743
743
|
export type QueriesClient = ReturnType<typeof createQueriesClient>;
|
|
744
744
|
export type MutationsClient = ReturnType<typeof createMutationsClient>;
|
|
745
|
-
`}function
|
|
745
|
+
`}function Ne(){return `export * from "./types";
|
|
746
746
|
export * from "./appflare";
|
|
747
747
|
export * from "./storage";
|
|
748
748
|
export * from "./handlers";
|
|
749
|
-
`}function
|
|
749
|
+
`}function $e(){return `import type { StorageClient, StorageSignedUrlResponse, StorageListResponse } from "./types";
|
|
750
750
|
|
|
751
751
|
type AuthTokenResolver = (() => string | Promise<string>) | undefined;
|
|
752
752
|
|
|
@@ -938,7 +938,7 @@ export function createStorageClient(
|
|
|
938
938
|
},
|
|
939
939
|
};
|
|
940
940
|
}
|
|
941
|
-
`}function
|
|
941
|
+
`}function Ce(e){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
942
942
|
import type appflareConfig from "${e}";
|
|
943
943
|
|
|
944
944
|
export type AppflareConfig = typeof appflareConfig;
|
|
@@ -1122,7 +1122,7 @@ export type RealtimeSubscriptionResponse = {
|
|
|
1122
1122
|
};
|
|
1123
1123
|
};
|
|
1124
1124
|
};
|
|
1125
|
-
`}function
|
|
1125
|
+
`}function Fe(e,t){return [{relativePath:"client/index.ts",source:Ne()},{relativePath:"client/types.ts",source:Ce(e)},{relativePath:"client/storage.ts",source:$e()},{relativePath:"client/handlers.ts",source:X(t)},{relativePath:"client/appflare.ts",source:ke()}]}function qe(e){return `import { defineConfig } from "drizzle-kit";
|
|
1126
1126
|
|
|
1127
1127
|
export default defineConfig({
|
|
1128
1128
|
dialect: "sqlite",
|
|
@@ -1134,7 +1134,7 @@ export default defineConfig({
|
|
|
1134
1134
|
token: "token",
|
|
1135
1135
|
},
|
|
1136
1136
|
});
|
|
1137
|
-
`}function
|
|
1137
|
+
`}function Me(){return `
|
|
1138
1138
|
|
|
1139
1139
|
import { getHeaders } from "./server";
|
|
1140
1140
|
export async function resolveSession(
|
|
@@ -1168,7 +1168,7 @@ export async function resolveSession(
|
|
|
1168
1168
|
}
|
|
1169
1169
|
}
|
|
1170
1170
|
|
|
1171
|
-
`}function
|
|
1171
|
+
`}function Ee(){return `
|
|
1172
1172
|
type SchedulerQueueBinding = {
|
|
1173
1173
|
send: (body: unknown, options?: SchedulerEnqueueOptions) => Promise<void>;
|
|
1174
1174
|
};
|
|
@@ -1205,7 +1205,7 @@ type R2BucketBinding = {
|
|
|
1205
1205
|
options?: { expiresIn?: number },
|
|
1206
1206
|
) => Promise<URL>;
|
|
1207
1207
|
};
|
|
1208
|
-
`}function
|
|
1208
|
+
`}function je(){return `
|
|
1209
1209
|
export function createScheduler(
|
|
1210
1210
|
queue?: SchedulerQueueBinding,
|
|
1211
1211
|
): Scheduler {
|
|
@@ -1226,7 +1226,7 @@ export function createScheduler(
|
|
|
1226
1226
|
},
|
|
1227
1227
|
};
|
|
1228
1228
|
}
|
|
1229
|
-
`}function
|
|
1229
|
+
`}function Ie(){return `
|
|
1230
1230
|
function createContextErrorHelpers() {
|
|
1231
1231
|
return {
|
|
1232
1232
|
error: (status: number, message: string, details?: unknown) => {
|
|
@@ -1234,7 +1234,7 @@ function createContextErrorHelpers() {
|
|
|
1234
1234
|
},
|
|
1235
1235
|
};
|
|
1236
1236
|
}
|
|
1237
|
-
`}function
|
|
1237
|
+
`}function Pe(){return `
|
|
1238
1238
|
function normalizeStoragePath(path: string): string {
|
|
1239
1239
|
const trimmed = path.trim();
|
|
1240
1240
|
if (trimmed.length === 0) {
|
|
@@ -1290,7 +1290,7 @@ function buildSignedRequest(
|
|
|
1290
1290
|
headers,
|
|
1291
1291
|
});
|
|
1292
1292
|
}
|
|
1293
|
-
`}function
|
|
1293
|
+
`}function Oe(){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 De(e){return `
|
|
1373
1373
|
export async function createSchedulerExecutionContext(
|
|
1374
1374
|
env: Record<string, unknown>,
|
|
1375
1375
|
options: RegisterHandlersOptions,
|
|
@@ -1467,7 +1467,7 @@ export async function createExecutionContext(
|
|
|
1467
1467
|
ctx.storage = createStorageApi(ctx, storageBucket);
|
|
1468
1468
|
return ctx;
|
|
1469
1469
|
}
|
|
1470
|
-
`}function
|
|
1470
|
+
`}function Ve(e){return `import type { Context } from "hono";
|
|
1471
1471
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
1472
1472
|
import { createAuth } from "./auth.config";
|
|
1473
1473
|
import {
|
|
@@ -1486,20 +1486,20 @@ import {
|
|
|
1486
1486
|
createQueryDb,
|
|
1487
1487
|
} from "./handlers";
|
|
1488
1488
|
|
|
1489
|
-
${Me()}
|
|
1490
|
-
|
|
1491
|
-
${qe()}
|
|
1492
|
-
|
|
1493
1489
|
${Ee()}
|
|
1494
1490
|
|
|
1491
|
+
${Me()}
|
|
1492
|
+
|
|
1495
1493
|
${je()}
|
|
1496
1494
|
|
|
1497
1495
|
${Ie()}
|
|
1498
1496
|
|
|
1499
1497
|
${Pe()}
|
|
1500
1498
|
|
|
1501
|
-
${Oe(
|
|
1502
|
-
|
|
1499
|
+
${Oe()}
|
|
1500
|
+
|
|
1501
|
+
${De(e)}
|
|
1502
|
+
`}function Be(){return `
|
|
1503
1503
|
export async function executeOperation<
|
|
1504
1504
|
TShape extends ZodRawShape,
|
|
1505
1505
|
TResult,
|
|
@@ -1540,7 +1540,7 @@ export function handleOperationError(
|
|
|
1540
1540
|
return c.json({ message: (error as Error).message ?? "Unknown error" }, 500);
|
|
1541
1541
|
}
|
|
1542
1542
|
|
|
1543
|
-
`}function
|
|
1543
|
+
`}function We(){return `import type { Context } from "hono";
|
|
1544
1544
|
import { ZodError, type ZodRawShape } from "zod";
|
|
1545
1545
|
import {
|
|
1546
1546
|
type AppflareContext,
|
|
@@ -1549,8 +1549,8 @@ import {
|
|
|
1549
1549
|
type WorkerEnv,
|
|
1550
1550
|
} from "./handlers";
|
|
1551
1551
|
|
|
1552
|
-
${
|
|
1553
|
-
`}function
|
|
1552
|
+
${Be()}
|
|
1553
|
+
`}function Le(){return `import { betterAuth } from "better-auth";
|
|
1554
1554
|
import { auth } from "./auth.config";
|
|
1555
1555
|
import {
|
|
1556
1556
|
and,
|
|
@@ -1943,7 +1943,7 @@ export type QueryDeleteArgs<TName extends TableName> = {
|
|
|
1943
1943
|
where?: WhereInput<TableModel<TName>, TName>;
|
|
1944
1944
|
limit?: number;
|
|
1945
1945
|
};
|
|
1946
|
-
`}function
|
|
1946
|
+
`}function ze(){return `type AggregateWithInput<TName extends TableName> =
|
|
1947
1947
|
QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1948
1948
|
|
|
1949
1949
|
type NumericFieldKey<TName extends TableName> = NumericModelFieldKey<
|
|
@@ -2075,7 +2075,7 @@ export type DbMutationEvent = {
|
|
|
2075
2075
|
export type QueryDbOptions = {
|
|
2076
2076
|
onMutation?: (event: DbMutationEvent) => void;
|
|
2077
2077
|
};
|
|
2078
|
-
`}function
|
|
2078
|
+
`}function Ue(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2079
2079
|
return typeof value === "object" && value !== null;
|
|
2080
2080
|
}
|
|
2081
2081
|
|
|
@@ -3454,7 +3454,7 @@ function inferConflictTarget(table: unknown): string[] {
|
|
|
3454
3454
|
|
|
3455
3455
|
return [];
|
|
3456
3456
|
}
|
|
3457
|
-
`}function
|
|
3457
|
+
`}function _e(){return `const mergedSchema = {
|
|
3458
3458
|
...authSchema,
|
|
3459
3459
|
...schema,
|
|
3460
3460
|
};
|
|
@@ -3729,6 +3729,48 @@ type ManyToManyRelationRows<
|
|
|
3729
3729
|
>
|
|
3730
3730
|
>
|
|
3731
3731
|
: Array<TableModel<TTargetTable>>;
|
|
3732
|
+
type NativeManyRelationRows<
|
|
3733
|
+
TSourceTable extends TableName,
|
|
3734
|
+
TRelationName extends string,
|
|
3735
|
+
TRelationArgs,
|
|
3736
|
+
> = RuntimeRelationTargetTable<TSourceTable, TRelationName> extends infer TTarget
|
|
3737
|
+
? TTarget extends TableName
|
|
3738
|
+
? TRelationArgs extends true
|
|
3739
|
+
? Array<TableModel<TTarget>>
|
|
3740
|
+
: TRelationArgs extends Record<string, unknown>
|
|
3741
|
+
? Awaited<
|
|
3742
|
+
TableFindManyResult<
|
|
3743
|
+
TTarget,
|
|
3744
|
+
Extract<
|
|
3745
|
+
Omit<TRelationArgs, "_count" | "_avg">,
|
|
3746
|
+
QueryFindManyArgs<TTarget>
|
|
3747
|
+
>
|
|
3748
|
+
>
|
|
3749
|
+
>
|
|
3750
|
+
: Array<TableModel<TTarget>>
|
|
3751
|
+
: never
|
|
3752
|
+
: never;
|
|
3753
|
+
type NativeOneRelationValue<
|
|
3754
|
+
TSourceTable extends TableName,
|
|
3755
|
+
TRelationName extends string,
|
|
3756
|
+
TRelationArgs,
|
|
3757
|
+
> = RuntimeRelationTargetTable<TSourceTable, TRelationName> extends infer TTarget
|
|
3758
|
+
? TTarget extends TableName
|
|
3759
|
+
? TRelationArgs extends true
|
|
3760
|
+
? TableModel<TTarget> | null
|
|
3761
|
+
: TRelationArgs extends Record<string, unknown>
|
|
3762
|
+
? Awaited<
|
|
3763
|
+
TableFindFirstResult<
|
|
3764
|
+
TTarget,
|
|
3765
|
+
Extract<
|
|
3766
|
+
Omit<TRelationArgs, "_count" | "_avg">,
|
|
3767
|
+
QueryFindFirstArgs<TTarget>
|
|
3768
|
+
>
|
|
3769
|
+
>
|
|
3770
|
+
>
|
|
3771
|
+
: TableModel<TTarget> | null
|
|
3772
|
+
: never
|
|
3773
|
+
: never;
|
|
3732
3774
|
type ReplaceManyToManyRelationsInRow<
|
|
3733
3775
|
TSourceTable extends string,
|
|
3734
3776
|
TRow,
|
|
@@ -3739,15 +3781,33 @@ type ReplaceManyToManyRelationsInRow<
|
|
|
3739
3781
|
? TWith extends Record<string, unknown>
|
|
3740
3782
|
? K extends keyof TWith
|
|
3741
3783
|
? [ManyToManyTargetTableName<Extract<TSourceTable, TableName>, K>] extends [never]
|
|
3742
|
-
?
|
|
3743
|
-
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
|
|
3749
|
-
|
|
3750
|
-
|
|
3784
|
+
? RuntimeRelationKind<Extract<TSourceTable, TableName>, K> extends "many"
|
|
3785
|
+
? NativeManyRelationRows<
|
|
3786
|
+
Extract<TSourceTable, TableName>,
|
|
3787
|
+
K,
|
|
3788
|
+
TWith[K]
|
|
3789
|
+
>
|
|
3790
|
+
: RuntimeRelationKind<Extract<TSourceTable, TableName>, K> extends "one"
|
|
3791
|
+
? NativeOneRelationValue<
|
|
3792
|
+
Extract<TSourceTable, TableName>,
|
|
3793
|
+
K,
|
|
3794
|
+
TWith[K]
|
|
3795
|
+
>
|
|
3796
|
+
: ReplaceManyToManyRelationsInRow<
|
|
3797
|
+
[RuntimeRelationTargetTable<
|
|
3798
|
+
Extract<TSourceTable, TableName>,
|
|
3799
|
+
K
|
|
3800
|
+
>] extends [never]
|
|
3801
|
+
? K
|
|
3802
|
+
: RuntimeRelationTargetTable<
|
|
3803
|
+
Extract<TSourceTable, TableName>,
|
|
3804
|
+
K
|
|
3805
|
+
>,
|
|
3806
|
+
TRow[K],
|
|
3807
|
+
TWith[K] extends { with: infer TNestedWith }
|
|
3808
|
+
? TNestedWith
|
|
3809
|
+
: undefined
|
|
3810
|
+
>
|
|
3751
3811
|
: ManyToManyRelationRows<
|
|
3752
3812
|
Extract<ManyToManyTargetTableName<Extract<TSourceTable, TableName>, K>, TableName>,
|
|
3753
3813
|
TWith[K]
|
|
@@ -3852,9 +3912,9 @@ type TableFindFirstResult<
|
|
|
3852
3912
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3853
3913
|
(typeof mergedDbSchema)[TName]
|
|
3854
3914
|
>;
|
|
3855
|
-
`}function
|
|
3915
|
+
`}function Qe(){return [_e(),He(),ze(),Ue()].join(`
|
|
3856
3916
|
|
|
3857
|
-
`)}function
|
|
3917
|
+
`)}function Ke(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3858
3918
|
const withValue = args?.with;
|
|
3859
3919
|
const pathSegments = args?.field
|
|
3860
3920
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -4035,7 +4095,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4035
4095
|
this.payload = payload;
|
|
4036
4096
|
}
|
|
4037
4097
|
}
|
|
4038
|
-
`}function
|
|
4098
|
+
`}function Ge(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
4039
4099
|
const where = isRecord(args?.where)
|
|
4040
4100
|
? (args?.where as Record<string, unknown>)
|
|
4041
4101
|
: undefined;
|
|
@@ -4189,7 +4249,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4189
4249
|
);
|
|
4190
4250
|
});
|
|
4191
4251
|
},
|
|
4192
|
-
`}function
|
|
4252
|
+
`}function Ze(){return `export function createQueryDb(
|
|
4193
4253
|
$db: AppflareDb,
|
|
4194
4254
|
options?: QueryDbOptions,
|
|
4195
4255
|
): AppflareQueryDb {
|
|
@@ -4231,7 +4291,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4231
4291
|
};
|
|
4232
4292
|
|
|
4233
4293
|
const tableApi = {
|
|
4234
|
-
`}function
|
|
4294
|
+
`}function Xe(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
4235
4295
|
const transaction = ($db as any).transaction;
|
|
4236
4296
|
|
|
4237
4297
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -5186,9 +5246,9 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
5186
5246
|
);
|
|
5187
5247
|
return rows;
|
|
5188
5248
|
},
|
|
5189
|
-
`}function
|
|
5249
|
+
`}function Ye(){return [Ze(),Ge(),Xe(),Ke(),Je()].join(`
|
|
5190
5250
|
|
|
5191
|
-
`)}function
|
|
5251
|
+
`)}function et(e=[],t=[]){let n=t.map(i=>` ${i.name}?: ${i.tsType} | null;`).join(`
|
|
5192
5252
|
`),a=[e.length>0?[" role: UserRole;"," banned: boolean | null;"," banReason?: string | null | undefined;"," banExpires?: Date | null | undefined;"].join(`
|
|
5193
5253
|
`):"",n].filter(Boolean).join(`
|
|
5194
5254
|
`);return `type AuthSession = typeof auth.$Infer.Session;
|
|
@@ -5285,7 +5345,7 @@ export type AppflareContext = {
|
|
|
5285
5345
|
storage: AppflareStorage;
|
|
5286
5346
|
error: (status: number, message: string, details?: unknown) => never;
|
|
5287
5347
|
};
|
|
5288
|
-
`}function
|
|
5348
|
+
`}function tt(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
5289
5349
|
|
|
5290
5350
|
export type SchedulerEnqueueOptions = {
|
|
5291
5351
|
delaySeconds?: number;
|
|
@@ -5417,20 +5477,20 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
5417
5477
|
definition,
|
|
5418
5478
|
};
|
|
5419
5479
|
}
|
|
5420
|
-
`}function
|
|
5480
|
+
`}function nt(e=[],t=[]){return [Le(),Qe(),Ye(),et(e,t),tt()].join(`
|
|
5421
5481
|
|
|
5422
|
-
`)}function
|
|
5482
|
+
`)}function rt(e,t=[],n=[]){return `import type { Context } from "hono";
|
|
5423
5483
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5424
5484
|
import { drizzle } from "drizzle-orm/d1";
|
|
5425
5485
|
import { z, type ZodRawShape } from "zod";
|
|
5426
5486
|
import * as authSchema from "./auth.schema";
|
|
5427
5487
|
import * as schema from "${e}";
|
|
5428
5488
|
|
|
5429
|
-
${
|
|
5430
|
-
`}function
|
|
5431
|
-
`)}function
|
|
5432
|
-
`)}function
|
|
5433
|
-
`)}function
|
|
5489
|
+
${nt(t,n)}
|
|
5490
|
+
`}function fr(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function gr(e,t){let n=e.routePath.replace(/^\//,"").replace(/\//g,"_");return fr(`op_${t}_${n}`)}function hr(e){return e.map((t,n)=>({operation:t,index:n,alias:gr(t,n)}))}function yr(e){return e.map(({operation:t,alias:n})=>`import { ${t.exportName} as ${n} } from "${t.importPath}";`).join(`
|
|
5491
|
+
`)}function br(e){return e.filter(({operation:t})=>t.kind==="query"||t.kind==="mutation").map(({alias:t})=>`const ${`${t}Schema`} = z.object(${t}.definition.args);`).join(`
|
|
5492
|
+
`)}function wr(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({alias:t})=>`const ${`${t}SchedulerSchema`} = ${t}.definition.args ? z.object(${t}.definition.args) : z.undefined();`).join(`
|
|
5493
|
+
`)}function xr(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
5434
5494
|
app.get(
|
|
5435
5495
|
"${t.routePath}",
|
|
5436
5496
|
sValidator("query", ${r}),
|
|
@@ -5443,7 +5503,7 @@ import * as schema from "${e}";
|
|
|
5443
5503
|
}
|
|
5444
5504
|
},
|
|
5445
5505
|
);`}).join(`
|
|
5446
|
-
`)}function
|
|
5506
|
+
`)}function Tr(e){return e.filter(({operation:t})=>t.kind==="mutation").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
5447
5507
|
app.post(
|
|
5448
5508
|
"${t.routePath}",
|
|
5449
5509
|
sValidator("json", ${r}),
|
|
@@ -5458,26 +5518,26 @@ import * as schema from "${e}";
|
|
|
5458
5518
|
}
|
|
5459
5519
|
},
|
|
5460
5520
|
);`}).join(`
|
|
5461
|
-
`)}function
|
|
5521
|
+
`)}function vr(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`,a=t.handlerName??t.routePath;return `
|
|
5462
5522
|
${JSON.stringify(a)}: {
|
|
5463
5523
|
definition: ${n}.definition,
|
|
5464
5524
|
schema: ${r},
|
|
5465
5525
|
},`}).join(`
|
|
5466
|
-
`)}function
|
|
5526
|
+
`)}function Rr(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=`${n}SchedulerSchema`,a=t.taskName??`${t.routePath}`;return `
|
|
5467
5527
|
${JSON.stringify(a)}: {
|
|
5468
5528
|
definition: ${n}.definition,
|
|
5469
5529
|
schema: ${r},
|
|
5470
5530
|
},`}).join(`
|
|
5471
|
-
`)}function
|
|
5472
|
-
`)}function
|
|
5531
|
+
`)}function kr(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`;return ` ${JSON.stringify(r)}: Parameters<typeof ${n}.definition.handler>[1];`}).join(`
|
|
5532
|
+
`)}function Sr(e){return e.filter(({operation:t})=>t.kind==="cron").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`,a=t.cronTriggers??[];return `
|
|
5473
5533
|
{
|
|
5474
5534
|
taskName: ${JSON.stringify(r)},
|
|
5475
5535
|
cronTriggers: ${JSON.stringify(a)},
|
|
5476
5536
|
definition: ${n}.definition,
|
|
5477
5537
|
},`}).join(`
|
|
5478
|
-
`)}function
|
|
5538
|
+
`)}function Ar(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
5479
5539
|
${t}.definition.handler,`).join(`
|
|
5480
|
-
`)}function
|
|
5540
|
+
`)}function at(e){let t=hr(e);return {imports:yr(t),operationSchemas:br(t),schedulerSchemas:wr(t),queryRoutes:xr(t),mutationRoutes:Tr(t),queryRegistryEntries:vr(t),schedulerEntries:Rr(t),schedulerPayloadMapEntries:kr(t),cronEntries:Sr(t),storageHandlersEntries:Ar(t)}}var ot=`
|
|
5481
5541
|
function getRealtimeStub(
|
|
5482
5542
|
env: Record<string, unknown>,
|
|
5483
5543
|
options: RegisterHandlersOptions,
|
|
@@ -5551,7 +5611,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
5551
5611
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
5552
5612
|
return url.toString();
|
|
5553
5613
|
}
|
|
5554
|
-
`;var
|
|
5614
|
+
`;var it=`
|
|
5555
5615
|
export class AppflareRealtimeDurableObject {
|
|
5556
5616
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
5557
5617
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -5694,7 +5754,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
5694
5754
|
return new Response("Not found", { status: 404 });
|
|
5695
5755
|
}
|
|
5696
5756
|
}
|
|
5697
|
-
`;var
|
|
5757
|
+
`;var st=`
|
|
5698
5758
|
async function publishMutationEvents(
|
|
5699
5759
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
5700
5760
|
options: RegisterHandlersOptions,
|
|
@@ -5795,7 +5855,7 @@ async function publishMutationEvents(
|
|
|
5795
5855
|
}
|
|
5796
5856
|
}
|
|
5797
5857
|
}
|
|
5798
|
-
`;var
|
|
5858
|
+
`;var lt=`
|
|
5799
5859
|
function registerRealtimeRoutes(
|
|
5800
5860
|
app: Hono<WorkerEnv>,
|
|
5801
5861
|
options: RegisterHandlersOptions,
|
|
@@ -5958,7 +6018,7 @@ function registerRealtimeRoutes(
|
|
|
5958
6018
|
return stub.fetch(c.req.raw);
|
|
5959
6019
|
});
|
|
5960
6020
|
}
|
|
5961
|
-
`;var
|
|
6021
|
+
`;var ut=`
|
|
5962
6022
|
type RealtimeSubscription = {
|
|
5963
6023
|
token: string;
|
|
5964
6024
|
signature: string;
|
|
@@ -5987,7 +6047,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
5987
6047
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
5988
6048
|
? string
|
|
5989
6049
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
5990
|
-
`;var
|
|
6050
|
+
`;var ct=`
|
|
5991
6051
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5992
6052
|
return typeof value === "object" && value !== null;
|
|
5993
6053
|
}
|
|
@@ -6496,9 +6556,9 @@ function doesSubscriptionMatchMutation(
|
|
|
6496
6556
|
|
|
6497
6557
|
return false;
|
|
6498
6558
|
}
|
|
6499
|
-
`;var
|
|
6559
|
+
`;var dt=[ut,ct,ot,st,lt,it].join(`
|
|
6500
6560
|
|
|
6501
|
-
`);var
|
|
6561
|
+
`);var pt=`
|
|
6502
6562
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
6503
6563
|
if (!value) {
|
|
6504
6564
|
return undefined;
|
|
@@ -6696,7 +6756,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
6696
6756
|
}
|
|
6697
6757
|
});
|
|
6698
6758
|
}
|
|
6699
|
-
`;var
|
|
6759
|
+
`;var mt=`
|
|
6700
6760
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
6701
6761
|
? string
|
|
6702
6762
|
: keyof typeof schedulerHandlers;
|
|
@@ -6760,7 +6820,7 @@ export async function executeScheduledBatch(
|
|
|
6760
6820
|
}
|
|
6761
6821
|
}
|
|
6762
6822
|
}
|
|
6763
|
-
`;var
|
|
6823
|
+
`;var ft=`
|
|
6764
6824
|
export async function executeCronTriggers(
|
|
6765
6825
|
controller: { cron: string },
|
|
6766
6826
|
env: Record<string, unknown>,
|
|
@@ -6794,7 +6854,7 @@ export async function executeCronTriggers(
|
|
|
6794
6854
|
}
|
|
6795
6855
|
}
|
|
6796
6856
|
}
|
|
6797
|
-
`;function
|
|
6857
|
+
`;function gt(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:c,cronEntries:u,storageHandlersEntries:l}=at(e);return `import { sValidator } from "@hono/standard-validator";
|
|
6798
6858
|
import type { Hono } from "hono";
|
|
6799
6859
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6800
6860
|
import { ZodError, z } from "zod";
|
|
@@ -6851,9 +6911,9 @@ const storageHandlers = [${l||`
|
|
|
6851
6911
|
|
|
6852
6912
|
setStorageHandlers([...storageHandlers]);
|
|
6853
6913
|
|
|
6854
|
-
${
|
|
6914
|
+
${mt}
|
|
6855
6915
|
|
|
6856
|
-
${
|
|
6916
|
+
${dt}
|
|
6857
6917
|
|
|
6858
6918
|
export function registerGeneratedHandlers(
|
|
6859
6919
|
app: Hono<WorkerEnv>,
|
|
@@ -6866,20 +6926,20 @@ export function registerGeneratedHandlers(
|
|
|
6866
6926
|
`}
|
|
6867
6927
|
}
|
|
6868
6928
|
|
|
6869
|
-
${
|
|
6929
|
+
${pt}
|
|
6870
6930
|
|
|
6871
|
-
${
|
|
6872
|
-
`}function
|
|
6873
|
-
KV: c.env["${e}"] as KVNamespace`:""}function
|
|
6874
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6875
|
-
}`}function
|
|
6931
|
+
${ft}
|
|
6932
|
+
`}function Y(e,t,n,r=[],a=[]){let o=rt(e,r,a),i=Ve(n),s=We(),c=gt(t);return [{relativePath:"handlers.ts",source:o},{relativePath:"handlers.context.ts",source:i},{relativePath:"handlers.execution.ts",source:s},{relativePath:"handlers.routes.ts",source:c}]}function Nr(e){return e?`,
|
|
6933
|
+
KV: c.env["${e}"] as KVNamespace`:""}function ht(e,t){return `{
|
|
6934
|
+
DATABASE: c.env["${e}"] as D1Database${Nr(t)}
|
|
6935
|
+
}`}function yt(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6876
6936
|
const auth = createAuth(
|
|
6877
|
-
${
|
|
6937
|
+
${ht(t,n)},
|
|
6878
6938
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
6879
6939
|
);
|
|
6880
6940
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6881
6941
|
});
|
|
6882
|
-
`}function
|
|
6942
|
+
`}function $r(){return `export const getHeaders = (headers: Headers) => {
|
|
6883
6943
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6884
6944
|
const headerObject: Record<string, any> = {};
|
|
6885
6945
|
let hasCookie = false;
|
|
@@ -6909,15 +6969,15 @@ ${mt}
|
|
|
6909
6969
|
|
|
6910
6970
|
return headerObject as any as Headers;
|
|
6911
6971
|
};
|
|
6912
|
-
`}function
|
|
6972
|
+
`}function Cr(){return `export const getSanitizedRequest = (req: Request) => {
|
|
6913
6973
|
const newRequest = new Request(req, {
|
|
6914
6974
|
headers: getHeaders(req.headers),
|
|
6915
6975
|
});
|
|
6916
6976
|
return newRequest;
|
|
6917
6977
|
};
|
|
6918
|
-
`}function
|
|
6919
|
-
`+
|
|
6920
|
-
`+
|
|
6978
|
+
`}function bt(){return $r()+`
|
|
6979
|
+
`+Cr()}function wt(e,t,n){return yt(e,t,n)+`
|
|
6980
|
+
`+bt()}function xt(){return `const app = new Hono<WorkerEnv>();
|
|
6921
6981
|
|
|
6922
6982
|
app.use('*', cors({
|
|
6923
6983
|
origin: (origin, c) => {
|
|
@@ -6933,7 +6993,7 @@ app.use('*', cors({
|
|
|
6933
6993
|
},
|
|
6934
6994
|
credentials: true
|
|
6935
6995
|
}));
|
|
6936
|
-
`}function
|
|
6996
|
+
`}function Tt(){return `export { AppflareRealtimeDurableObject };
|
|
6937
6997
|
|
|
6938
6998
|
export default {
|
|
6939
6999
|
fetch: app.fetch,
|
|
@@ -6944,7 +7004,7 @@ export default {
|
|
|
6944
7004
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
6945
7005
|
},
|
|
6946
7006
|
};
|
|
6947
|
-
`}function
|
|
7007
|
+
`}function vt(e,t,n="APPFLARE_SCHEDULER_QUEUE",r,a="APPFLARE_REALTIME",o="global",i="/realtime/subscribe",s="/realtime/ws",c="appflare.realtime.v1"){let u=t?`
|
|
6948
7008
|
kvBinding: "${t}",`:"",l=r?`
|
|
6949
7009
|
r2Binding: "${r}",`:"",p=`
|
|
6950
7010
|
realtimeBinding: "${a}",
|
|
@@ -6958,16 +7018,16 @@ export default {
|
|
|
6958
7018
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6959
7019
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
6960
7020
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
6961
|
-
`}function
|
|
7021
|
+
`}function Rt(){return `import { createAuth } from "./auth.config";
|
|
6962
7022
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
6963
7023
|
import { registerAdminDashboard } from "./admin.routes";
|
|
6964
7024
|
import { Hono } from "hono";
|
|
6965
7025
|
import { cors } from "hono/cors";
|
|
6966
7026
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6967
|
-
`}function
|
|
7027
|
+
`}function kt(){return `type WorkerEnv = {
|
|
6968
7028
|
Bindings: Record<string, unknown>;
|
|
6969
7029
|
};
|
|
6970
|
-
`}function
|
|
7030
|
+
`}function St(e,t,n,r,a,o,i,s,c,u){return Rt()+kt()+xt()+vt(t,n,r,a,o,i,s,c,u)+wt(e,t,n)+Tt()}function At(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function ee(e,t){let n={...e};for(let[r,a]of Object.entries(t)){let o=n[r];if(At(o)&&At(a)){n[r]=ee(o,a);continue}n[r]=a;}return n}function Fr(e){return Array.from(new Set(e.filter(t=>t.length>0)))}function Nt(e,t){let n=t.filter(d=>d.kind==="scheduler"||d.kind==="cron"),r=Fr(t.filter(d=>d.kind==="cron").flatMap(d=>d.cronTriggers??[])),a=e.config.scheduler.enabled&&n.length>0,o=e.config.realtime.enabled,s=(typeof e.config.wranglerOverrides?.name=="string"?e.config.wranglerOverrides.name:void 0)??"appflare-worker",c=e.config.scheduler.queue??`${s}-scheduler`,u={name:s,main:"./src/index.ts",d1_databases:e.config.database.map(d=>({binding:d.binding,database_name:d.databaseName,database_id:d.databaseId,preview_database_id:d.previewDatabaseId??d.databaseId,...d.migrationsDir?{migrations_dir:d.migrationsDir}:{}})),kv_namespaces:e.config.kv.map(d=>({binding:d.binding,id:d.id,...d.previewId?{preview_id:d.previewId}:{}})),r2_buckets:e.config.r2.map(d=>({binding:d.binding,bucket_name:d.bucketName,...d.previewBucketName?{preview_bucket_name:d.previewBucketName}:{},...d.jurisdiction?{jurisdiction:d.jurisdiction}:{}})),...a?{queues:{producers:[{binding:e.config.scheduler.binding,queue:c}],consumers:[{queue:c}]}}:{},...r.length>0?{triggers:{crons:r}}:{},...o?{durable_objects:{bindings:[{name:e.config.realtime.binding,class_name:e.config.realtime.className}]},migrations:[{tag:"appflare-realtime-v1",new_sqlite_classes:[e.config.realtime.className]}]}:{}};if(!e.config.wranglerOverrides)return u;let{scheduler:l,...p}=e.config.wranglerOverrides;return ee(u,p)}function te(e){let t={children:[],handlers:[]};for(let n of e){let r=n.clientSegments??[n.exportName],a=t;for(let o=0;o<r.length-1;o++){let i=r[o],s=a.children.find(c=>c.name===i&&c.type==="folder");s||(s={name:i,type:"folder",children:[],handlers:[]},a.children.push(s)),a=s;}a.handlers.push(n);}return t.children}function $t(e){return e.tables.map(t=>({exportName:t.exportName,tableName:t.tableName,columns:t.columns.map(n=>n.name)}))}function Ct(e){return `<li data-name="users">
|
|
6971
7031
|
<a href="/admin/users" hx-get="/admin/users" hx-target="#main-content" hx-push-url="true" hx-swap="outerHTML" class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full">
|
|
6972
7032
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6973
7033
|
<span class="truncate">users</span>
|
|
@@ -6979,14 +7039,14 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6979
7039
|
<span class="truncate">${n.tableName}</span>
|
|
6980
7040
|
</a>
|
|
6981
7041
|
</li>`).join(`
|
|
6982
|
-
`)}`}function
|
|
7042
|
+
`)}`}function ne(e,t){let n=" ".repeat(t),r=e.children.length>0,a=e.handlers.length>0,o=r||a,i="";if(o){`folder-${e.name.replace(/[^a-zA-Z0-9]/g,"-")}-${t}`;i+=`
|
|
6983
7043
|
${n}<li data-name="${e.name}" class="folder-item">`,i+=`
|
|
6984
7044
|
${n} <details class="group/folder" open>`,i+=`
|
|
6985
7045
|
${n} <summary class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full cursor-pointer list-none">`,i+=`
|
|
6986
7046
|
${n} <iconify-icon icon="solar:folder-bold-duotone" width="16" height="16" class="opacity-50 shrink-0 transition-transform group-open/folder:rotate-0"></iconify-icon>`,i+=`
|
|
6987
7047
|
${n} <span class="truncate font-medium">${e.name}</span>`,i+=`
|
|
6988
7048
|
${n} </summary>`,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+=
|
|
7049
|
+
${n} <ul class="flex flex-col gap-0.5 ml-4 border-l border-base-200 pl-2">`;for(let c of e.children)i+=ne(c,t+2);for(let c of e.handlers){let u=c.kind==="query"?"solar:reorder-linear":"solar:bolt-linear";i+=`
|
|
6990
7050
|
${n} <li data-name="${c.exportName}">`,i+=`
|
|
6991
7051
|
${n} <a href="/admin/functions${c.routePath}" hx-get="/admin/functions${c.routePath}" hx-target="#main-content" hx-push-url="true" hx-swap="outerHTML" class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full">`,i+=`
|
|
6992
7052
|
${n} <iconify-icon icon="${u}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
@@ -7001,7 +7061,7 @@ ${n} <a href="/admin/functions${s.routePath}" hx-get="/admin/functions${s.route
|
|
|
7001
7061
|
${n} <iconify-icon icon="${c}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
7002
7062
|
${n} <span class="truncate">${s.exportName}</span>`,i+=`
|
|
7003
7063
|
${n} </a>`,i+=`
|
|
7004
|
-
${n}</li>`;}return i}function
|
|
7064
|
+
${n}</li>`;}return i}function Ft(e){let t=e.filter(s=>s.kind==="query"),n=e.filter(s=>s.kind==="mutation"),r=te(t),a=te(n),o=r.map(s=>ne(s,0)).join(""),i=a.map(s=>ne(s,0)).join("");return `
|
|
7005
7065
|
<div id="pane-functions" class="flex flex-col h-full hidden">
|
|
7006
7066
|
<div class="px-3 pt-5 pb-3">
|
|
7007
7067
|
<p class="text-[10px] font-semibold uppercase tracking-widest opacity-35 mb-3 px-1">Functions</p>
|
|
@@ -7023,7 +7083,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7023
7083
|
<ul class="flex flex-col gap-0.5">${i}</ul>`:""}
|
|
7024
7084
|
</nav>
|
|
7025
7085
|
</div>
|
|
7026
|
-
`}function
|
|
7086
|
+
`}function qt(e){return e.map(t=>`
|
|
7027
7087
|
<a
|
|
7028
7088
|
href="/admin/table/${t.exportName}"
|
|
7029
7089
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
@@ -7040,9 +7100,9 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7040
7100
|
</div>
|
|
7041
7101
|
</div>
|
|
7042
7102
|
</a>
|
|
7043
|
-
`.replace(/\n/g,"\\n")).join("")}function
|
|
7103
|
+
`.replace(/\n/g,"\\n")).join("")}function Mt(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
7044
7104
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
7045
|
-
`).join("")}function
|
|
7105
|
+
`).join("")}function qr(e){switch(e){case "number":return "mdi:pound";case "boolean":return "mdi:toggle-switch-outline";case "date":return "mdi:calendar";case "json":return "mdi:code-braces";default:return "mdi:format-text"}}function Et(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n),a=r?qr(r.type):"mdi:format-text";return `
|
|
7046
7106
|
<th>
|
|
7047
7107
|
<a href="#"
|
|
7048
7108
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -7054,7 +7114,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7054
7114
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
7055
7115
|
</a>
|
|
7056
7116
|
</th>
|
|
7057
|
-
`}).join("")}function
|
|
7117
|
+
`}).join("")}function jt(e,t,n){return t.map(r=>{let a=e.columns.find(o=>o.name===r);return n&&r===n?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${r} ?? '')}" data-copy-value="\${String((row as any).${r} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${r} ?? '')}</button></td>`:a?.type==="json"?`<td>\${raw((() => { const __v = (row as any).${r}; if (__v === null || __v === undefined) return '<span class="opacity-30 text-xs">null</span>'; if (Array.isArray(__v)) { if (__v.length === 0) return '<span class="badge badge-ghost badge-sm font-mono text-xs">[ ]</span>'; return '<div class="flex flex-wrap gap-1 max-w-[200px]">' + __v.slice(0, 3).map((item) => '<span class="badge badge-ghost badge-xs font-mono">' + (typeof item === 'object' && item !== null ? JSON.stringify(item).slice(0, 20) + (JSON.stringify(item).length > 20 ? '\u2026' : '') : String(item ?? '')) + '</span>').join('') + (__v.length > 3 ? '<span class="badge badge-ghost badge-xs opacity-50">+' + (__v.length - 3) + '</span>' : '') + '</div>'; } if (typeof __v === 'object') { const __s = JSON.stringify(__v); return '<span class="badge badge-outline badge-sm font-mono text-[10px]">' + __s.slice(0, 50) + (__s.length > 50 ? '\u2026' : '') + '</span>'; } return String(__v ?? ''); })())}</td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${r} ?? '')}">\${String((row as any).${r} ?? '')}</div></td>`}).join("")}function re(e,t,n){let r=e.columns.find(i=>i.name===t);if(!r)return "";let a=r.optional?"":" required",o=r.type==="number"?"number":r.type==="date"?"date":"text";if(r.type==="boolean")return n==="edit"?`
|
|
7058
7118
|
<div class="form-control">
|
|
7059
7119
|
<label class="label cursor-pointer justify-start gap-3">
|
|
7060
7120
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -7102,7 +7162,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7102
7162
|
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
7103
7163
|
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm"${a} />
|
|
7104
7164
|
</div>
|
|
7105
|
-
`}function
|
|
7165
|
+
`}function ae(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n);if(!r)return "";let a=r.optional?"":`
|
|
7106
7166
|
if (raw_${n} === '') {
|
|
7107
7167
|
return c.text('${n} is required', 400);
|
|
7108
7168
|
}
|
|
@@ -7157,7 +7217,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7157
7217
|
payload.${n} = raw_${n};
|
|
7158
7218
|
}
|
|
7159
7219
|
`}).join(`
|
|
7160
|
-
`)}function
|
|
7220
|
+
`)}function It(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function Pt(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function Ot(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function Dt(e,t,n,r){return t?`<td class="text-right">
|
|
7161
7221
|
<div class="drawer drawer-end">
|
|
7162
7222
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
7163
7223
|
<div class="drawer-content">
|
|
@@ -7210,7 +7270,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7210
7270
|
</div>
|
|
7211
7271
|
</div>
|
|
7212
7272
|
</div>
|
|
7213
|
-
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function
|
|
7273
|
+
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function H(e){return `
|
|
7214
7274
|
<div class="flex flex-col sm:flex-row justify-between items-center mt-4 gap-3 py-3 px-1">
|
|
7215
7275
|
<div class="text-xs text-base-content/40">
|
|
7216
7276
|
Total found: <span class="font-medium text-base-content/60">\${total}</span>
|
|
@@ -7232,7 +7292,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7232
7292
|
\` : html\`<button class="join-item btn btn-sm btn-ghost btn-disabled"><iconify-icon icon="mdi:chevron-right" width="16" height="16"></iconify-icon></button>\`}
|
|
7233
7293
|
</div>
|
|
7234
7294
|
\` : ''}
|
|
7235
|
-
</div>`}function
|
|
7295
|
+
</div>`}function z(e,t="Search term or filter..."){return `
|
|
7236
7296
|
<div class="form-control w-full md:w-auto relative">
|
|
7237
7297
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
7238
7298
|
<input type="text"
|
|
@@ -7243,7 +7303,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7243
7303
|
hx-trigger="keyup changed delay:500ms, search"
|
|
7244
7304
|
hx-target="#main-content"
|
|
7245
7305
|
class="input input-sm md:input-md input-bordered pl-9 w-full md:w-72 bg-base-200/50 border-base-200 focus:bg-base-100 focus:border-primary transition-all text-sm" />
|
|
7246
|
-
</div>`}function
|
|
7306
|
+
</div>`}function Vt(e,t,n,r,a,o,i,s,c,u){let l=H(`/admin/table/${e.exportName}`),p=z(`/admin/table/${e.exportName}`,"Search term or filter..."),d=r?`<th class="w-10"><input id="select-all-${e.exportName}" type="checkbox" class="checkbox checkbox-xs" /></th>`:'<th class="w-10"><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></th>',y=r?`<td><input type="checkbox" class="checkbox checkbox-xs row-select-checkbox" value="\${String((row as any).${n} ?? '')}" /></td>`:'<td><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></td>',x=r?`
|
|
7247
7307
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
7248
7308
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
7249
7309
|
<div class="text-xs text-base-content/70">
|
|
@@ -7495,7 +7555,7 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7495
7555
|
title: "${e.tableName} - Admin Dashboard",
|
|
7496
7556
|
children: content
|
|
7497
7557
|
}));
|
|
7498
|
-
});`}function
|
|
7558
|
+
});`}function Bt(e,t,n,r,a,o,i,s){let c=r==="number"?`
|
|
7499
7559
|
const parsedId = Number(rawId);
|
|
7500
7560
|
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
7501
7561
|
idValue = parsedId;
|
|
@@ -7628,15 +7688,15 @@ ${n}</li>`;}return i}function Ct(e){let t=e.filter(s=>s.kind==="query"),n=e.filt
|
|
|
7628
7688
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7629
7689
|
});
|
|
7630
7690
|
${l}
|
|
7631
|
-
`}function
|
|
7632
|
-
`+
|
|
7691
|
+
`}function oe(e){let t=It(e),n=!!t,r=e.columns.map(w=>w.name),a=r.filter(w=>Pt(e,w)),o=r.filter(w=>Ot(e,w)),i=Mt(e),s=Et(e,r),c=jt(e,r,t),u=a.map(w=>re(e,w,"create")).join(""),l=o.map(w=>re(e,w,"edit")).join(""),p=ae(e,a),d=ae(e,o),y=n?t:r[0]||"id",x=e.columns.find(w=>w.name===t)?.type,S=Dt(e,n,t,l);return Vt(e,y,t,n,r,i,s,c,S,u)+`
|
|
7692
|
+
`+Bt(e.exportName,y,t,x,n,i,p,d)}function Wt(){return `
|
|
7633
7693
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7634
7694
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
7635
7695
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
7636
7696
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
7637
7697
|
const search = params.search ? params.search : '';
|
|
7638
7698
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
7639
|
-
};`}function
|
|
7699
|
+
};`}function Lt(){return `
|
|
7640
7700
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7641
7701
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7642
7702
|
<div class="modal">
|
|
@@ -7678,8 +7738,8 @@ ${l}
|
|
|
7678
7738
|
</div>
|
|
7679
7739
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
7680
7740
|
</div>
|
|
7681
|
-
\`}`}var
|
|
7682
|
-
`),t=
|
|
7741
|
+
\`}`}var Mr=["id","name","email","role","createdAt","banned"],Er={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function jr(e){let t=Er[e]||"mdi:format-text";return `<th><a href="#" hx-get="/admin/users?page=\${page}&search=\${search}&sort=${e}&order=\${sort === '${e}' && order === 'asc' ? 'desc' : 'asc'}" hx-target="#main-content" hx-push-url="true" class="hover:text-primary flex items-center gap-1.5 transition-colors whitespace-nowrap"><iconify-icon icon="${t}" width="14" height="14" class="opacity-40"></iconify-icon>${e} <span class="text-[10px] opacity-30">\${sort === '${e}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span></a></th>`}function zt(){let e=Mr.map(jr).join(`
|
|
7742
|
+
`),t=H("/admin/users");return `
|
|
7683
7743
|
const tableHtml = html\`
|
|
7684
7744
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
7685
7745
|
<div class="overflow-x-auto">
|
|
@@ -7747,7 +7807,7 @@ ${l}
|
|
|
7747
7807
|
</div>
|
|
7748
7808
|
</div>
|
|
7749
7809
|
</div>
|
|
7750
|
-
${
|
|
7810
|
+
${Lt()}
|
|
7751
7811
|
${Ht()}
|
|
7752
7812
|
</td>
|
|
7753
7813
|
</tr>
|
|
@@ -7764,7 +7824,7 @@ ${Ht()}
|
|
|
7764
7824
|
${t}
|
|
7765
7825
|
</div>
|
|
7766
7826
|
\`;
|
|
7767
|
-
`}function
|
|
7827
|
+
`}function Ut(){return `
|
|
7768
7828
|
const content = html\`
|
|
7769
7829
|
<div id="main-content">
|
|
7770
7830
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -7776,11 +7836,11 @@ ${Ht()}
|
|
|
7776
7836
|
<iconify-icon icon="mdi:refresh" width="14" height="14"></iconify-icon>
|
|
7777
7837
|
</button>
|
|
7778
7838
|
</div>
|
|
7779
|
-
${
|
|
7839
|
+
${z("/admin/users","Search users...")}
|
|
7780
7840
|
</div>
|
|
7781
7841
|
\${tableHtml}
|
|
7782
7842
|
</div>
|
|
7783
|
-
\`;`}function
|
|
7843
|
+
\`;`}function _t(){let e=zt(),t=Ut();return `
|
|
7784
7844
|
adminApp.get('/users', async (c) => {
|
|
7785
7845
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
7786
7846
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7836,7 +7896,7 @@ ${Ht()}
|
|
|
7836
7896
|
title: "users - Admin Dashboard",
|
|
7837
7897
|
children: content,
|
|
7838
7898
|
}));
|
|
7839
|
-
});`}function
|
|
7899
|
+
});`}function Qt(){return `
|
|
7840
7900
|
adminApp.post('/users/edit', async (c) => {
|
|
7841
7901
|
const session = await requireAdminSession(c);
|
|
7842
7902
|
if (!session) {
|
|
@@ -7979,8 +8039,8 @@ ${Ht()}
|
|
|
7979
8039
|
const resolvedPage = String(Math.min(nextPageCandidate, totalPages));
|
|
7980
8040
|
|
|
7981
8041
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7982
|
-
});`}function
|
|
7983
|
-
${
|
|
8042
|
+
});`}function ie(){return `
|
|
8043
|
+
${Wt()}
|
|
7984
8044
|
|
|
7985
8045
|
const requireAdminSession = async (c: any) => {
|
|
7986
8046
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7991,12 +8051,12 @@ ${Ht()}
|
|
|
7991
8051
|
return session;
|
|
7992
8052
|
};
|
|
7993
8053
|
|
|
7994
|
-
${Ut()}
|
|
7995
|
-
|
|
7996
8054
|
${_t()}
|
|
7997
|
-
|
|
8055
|
+
|
|
8056
|
+
${Qt()}
|
|
8057
|
+
`}function Kt(e){return `${e.tables.map(t=>oe(t)).join(`
|
|
7998
8058
|
`)}
|
|
7999
|
-
${
|
|
8059
|
+
${ie()}`}function Jt(e){return `
|
|
8000
8060
|
<div class="flex items-center justify-between">
|
|
8001
8061
|
<div class="flex items-center gap-3">
|
|
8002
8062
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -8011,7 +8071,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
8011
8071
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
8012
8072
|
</div>
|
|
8013
8073
|
</div>
|
|
8014
|
-
`}var
|
|
8074
|
+
`}var Ir="input input-xs input-bordered font-mono flex-1 bg-base-200/30 focus:bg-base-100 focus:border-primary transition-all rounded-lg border-base-200";function Pr(e){return e.map(t=>{let n=t.type!=="unknown"?`<span class="badge badge-xs badge-ghost font-mono opacity-25 ml-1">${t.type}</span>`:"";if(t.type==="boolean")return `
|
|
8015
8075
|
<div class="flex items-center gap-2">
|
|
8016
8076
|
<input
|
|
8017
8077
|
type="checkbox"
|
|
@@ -8030,10 +8090,10 @@ ${oe()}`}function Jt(e){return `
|
|
|
8030
8090
|
data-obj-field-type="${t.type}"
|
|
8031
8091
|
placeholder="${t.defaultValue??""}"
|
|
8032
8092
|
value="${t.defaultValue??""}"
|
|
8033
|
-
class="${
|
|
8093
|
+
class="${Ir}"
|
|
8034
8094
|
/>
|
|
8035
8095
|
</div>`}).join(`
|
|
8036
|
-
`)}function
|
|
8096
|
+
`)}function Or(e){let t=e.args??[];if(t.length===0)return `
|
|
8037
8097
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
8038
8098
|
`;let n="input input-sm input-bordered font-mono w-full bg-base-200/30 focus:bg-base-100 focus:border-primary transition-all rounded-xl border-base-200";return t.map(r=>{let a=`${r.name}${r.optional?"":" *"}`,o=r.type!=="unknown"?`<span class="badge badge-xs badge-ghost font-mono opacity-40 ml-1">${r.type}</span>`:"",i=r.optional?'<span class="label-text-alt text-[10px] opacity-30 italic">optional</span>':"",s=`
|
|
8039
8099
|
<label class="label py-0.5">
|
|
@@ -8058,7 +8118,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
8058
8118
|
data-arg-type="object"
|
|
8059
8119
|
class="border border-base-200 rounded-xl p-3 bg-base-200/20 flex flex-col gap-2"
|
|
8060
8120
|
>
|
|
8061
|
-
${
|
|
8121
|
+
${Pr(r.fields)}
|
|
8062
8122
|
</div>
|
|
8063
8123
|
</div>`:`
|
|
8064
8124
|
<div class="form-control">
|
|
@@ -8102,7 +8162,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
8102
8162
|
${r.optional?"":"required"}
|
|
8103
8163
|
/>
|
|
8104
8164
|
</div>`}).join(`
|
|
8105
|
-
`)}function
|
|
8165
|
+
`)}function Dr(e){return `
|
|
8106
8166
|
<div class="space-y-4">
|
|
8107
8167
|
<div class="flex items-center justify-between">
|
|
8108
8168
|
<div class="flex flex-col">
|
|
@@ -8115,11 +8175,11 @@ ${oe()}`}function Jt(e){return `
|
|
|
8115
8175
|
</label>
|
|
8116
8176
|
</div>
|
|
8117
8177
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
8118
|
-
${
|
|
8178
|
+
${Or(e)}
|
|
8119
8179
|
</div>
|
|
8120
8180
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
8121
8181
|
</div>
|
|
8122
|
-
`}function
|
|
8182
|
+
`}function Vr(){return `
|
|
8123
8183
|
<div class="space-y-4">
|
|
8124
8184
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
8125
8185
|
<div class="relative group">
|
|
@@ -8136,7 +8196,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
8136
8196
|
</div>
|
|
8137
8197
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
8138
8198
|
</div>
|
|
8139
|
-
`}function
|
|
8199
|
+
`}function Br(){return `
|
|
8140
8200
|
<div class="space-y-4">
|
|
8141
8201
|
<div class="flex items-center justify-between">
|
|
8142
8202
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -8150,7 +8210,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
8150
8210
|
</div>
|
|
8151
8211
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
8152
8212
|
</div>
|
|
8153
|
-
`}function
|
|
8213
|
+
`}function Gt(e){return `
|
|
8154
8214
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
8155
8215
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
8156
8216
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -8171,13 +8231,13 @@ ${oe()}`}function Jt(e){return `
|
|
|
8171
8231
|
<!-- Tab Content -->
|
|
8172
8232
|
<div class="flex-1 overflow-y-auto">
|
|
8173
8233
|
<div id="request-tab-args" class="p-5">
|
|
8174
|
-
${
|
|
8234
|
+
${Dr(e)}
|
|
8175
8235
|
</div>
|
|
8176
8236
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
8177
|
-
${
|
|
8237
|
+
${Vr()}
|
|
8178
8238
|
</div>
|
|
8179
8239
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
8180
|
-
${
|
|
8240
|
+
${Br()}
|
|
8181
8241
|
</div>
|
|
8182
8242
|
</div>
|
|
8183
8243
|
|
|
@@ -8195,7 +8255,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
8195
8255
|
</form>
|
|
8196
8256
|
</div>
|
|
8197
8257
|
</div>
|
|
8198
|
-
`}function
|
|
8258
|
+
`}function Zt(){return `
|
|
8199
8259
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
8200
8260
|
<!-- Panel Header -->
|
|
8201
8261
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -8277,7 +8337,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
8277
8337
|
|
|
8278
8338
|
</div>
|
|
8279
8339
|
</div>
|
|
8280
|
-
`}function
|
|
8340
|
+
`}function Xt(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
8281
8341
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
8282
8342
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
8283
8343
|
|
|
@@ -8968,21 +9028,21 @@ ${oe()}`}function Jt(e){return `
|
|
|
8968
9028
|
_rtEnabled = false;
|
|
8969
9029
|
});
|
|
8970
9030
|
</script>
|
|
8971
|
-
`}function
|
|
9031
|
+
`}function Yt(e){return `
|
|
8972
9032
|
const content = html\`
|
|
8973
9033
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
8974
9034
|
${Jt(e)}
|
|
8975
9035
|
|
|
8976
9036
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
8977
9037
|
<!-- Request Panel -->
|
|
8978
|
-
${
|
|
9038
|
+
${Gt(e)}
|
|
8979
9039
|
|
|
8980
9040
|
<!-- Result Panel -->
|
|
8981
|
-
${
|
|
9041
|
+
${Zt()}
|
|
8982
9042
|
</div>
|
|
8983
9043
|
</div>
|
|
8984
9044
|
|
|
8985
|
-
${
|
|
9045
|
+
${Xt(e)}
|
|
8986
9046
|
\`;
|
|
8987
9047
|
|
|
8988
9048
|
if (c.req.header('hx-request')) {
|
|
@@ -8992,11 +9052,11 @@ ${oe()}`}function Jt(e){return `
|
|
|
8992
9052
|
return c.html(Layout({
|
|
8993
9053
|
title: "${e.exportName} - Functions",
|
|
8994
9054
|
children: content
|
|
8995
|
-
}));`}function
|
|
9055
|
+
}));`}function en(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
8996
9056
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
8997
|
-
${
|
|
9057
|
+
${Yt(n)}
|
|
8998
9058
|
});`).join(`
|
|
8999
|
-
`)}function
|
|
9059
|
+
`)}function tn(){return `
|
|
9000
9060
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
9001
9061
|
const r2Binding = (options as any).r2Binding;
|
|
9002
9062
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -9065,7 +9125,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
9065
9125
|
const parts = prefix.split('/').filter(Boolean);
|
|
9066
9126
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
9067
9127
|
};
|
|
9068
|
-
`}function
|
|
9128
|
+
`}function nn(){return `
|
|
9069
9129
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
9070
9130
|
const parts = prefix.split('/').filter(Boolean);
|
|
9071
9131
|
const breadcrumbs: any[] = [];
|
|
@@ -9192,7 +9252,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
9192
9252
|
</div>
|
|
9193
9253
|
\`;
|
|
9194
9254
|
};
|
|
9195
|
-
`}function
|
|
9255
|
+
`}function rn(){return `
|
|
9196
9256
|
const handleStorageListRoute = async (c: any) => {
|
|
9197
9257
|
const bucket = getStorageBucket(c);
|
|
9198
9258
|
if (!bucket) {
|
|
@@ -9214,7 +9274,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
9214
9274
|
|
|
9215
9275
|
adminApp.get('/storage', handleStorageListRoute);
|
|
9216
9276
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
9217
|
-
`}function
|
|
9277
|
+
`}function an(){return `
|
|
9218
9278
|
adminApp.post('/storage/upload', async (c) => {
|
|
9219
9279
|
const bucket = getStorageBucket(c);
|
|
9220
9280
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9232,7 +9292,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
9232
9292
|
|
|
9233
9293
|
return c.redirect(prefixToStoragePath(prefix));
|
|
9234
9294
|
});
|
|
9235
|
-
`}function
|
|
9295
|
+
`}function on(){return `
|
|
9236
9296
|
adminApp.delete('/storage/delete', async (c) => {
|
|
9237
9297
|
const bucket = getStorageBucket(c);
|
|
9238
9298
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9247,7 +9307,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
9247
9307
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
9248
9308
|
return c.html('');
|
|
9249
9309
|
});
|
|
9250
|
-
`}function
|
|
9310
|
+
`}function sn(){return `
|
|
9251
9311
|
adminApp.post('/storage/directory', async (c) => {
|
|
9252
9312
|
const bucket = getStorageBucket(c);
|
|
9253
9313
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9273,7 +9333,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
9273
9333
|
|
|
9274
9334
|
return c.redirect(prefixToStoragePath(prefix));
|
|
9275
9335
|
});
|
|
9276
|
-
`}function
|
|
9336
|
+
`}function ln(){return `
|
|
9277
9337
|
adminApp.get('/storage/download', async (c) => {
|
|
9278
9338
|
const bucket = getStorageBucket(c);
|
|
9279
9339
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9293,7 +9353,7 @@ ${oe()}`}function Jt(e){return `
|
|
|
9293
9353
|
|
|
9294
9354
|
return new Response(object.body, { headers });
|
|
9295
9355
|
});
|
|
9296
|
-
`}function
|
|
9356
|
+
`}function un(){return `
|
|
9297
9357
|
adminApp.get('/storage/preview', async (c) => {
|
|
9298
9358
|
const bucket = getStorageBucket(c);
|
|
9299
9359
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -9311,25 +9371,25 @@ ${oe()}`}function Jt(e){return `
|
|
|
9311
9371
|
|
|
9312
9372
|
return new Response(object.body, { headers });
|
|
9313
9373
|
});
|
|
9314
|
-
`}function
|
|
9315
|
-
${sn()}
|
|
9316
|
-
|
|
9374
|
+
`}function cn(){return `
|
|
9317
9375
|
${ln()}
|
|
9318
9376
|
|
|
9319
|
-
${
|
|
9377
|
+
${un()}
|
|
9320
9378
|
|
|
9321
9379
|
${an()}
|
|
9322
9380
|
|
|
9323
9381
|
${on()}
|
|
9324
9382
|
|
|
9325
|
-
${
|
|
9326
|
-
`}function cn(){return `
|
|
9327
|
-
${en()}
|
|
9383
|
+
${sn()}
|
|
9328
9384
|
|
|
9385
|
+
${rn()}
|
|
9386
|
+
`}function dn(){return `
|
|
9329
9387
|
${tn()}
|
|
9330
9388
|
|
|
9331
|
-
${
|
|
9332
|
-
|
|
9389
|
+
${nn()}
|
|
9390
|
+
|
|
9391
|
+
${cn()}
|
|
9392
|
+
`}function pn(e,t){let n=Ft(t);return `
|
|
9333
9393
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
9334
9394
|
return html\`<!DOCTYPE html>
|
|
9335
9395
|
<html lang="en" data-theme="light">
|
|
@@ -9736,7 +9796,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9736
9796
|
</body>
|
|
9737
9797
|
</html>\`;
|
|
9738
9798
|
}
|
|
9739
|
-
`}function
|
|
9799
|
+
`}function mn(){return `
|
|
9740
9800
|
// Auth Middleware
|
|
9741
9801
|
adminApp.use('*', async (c, next) => {
|
|
9742
9802
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -9795,7 +9855,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9795
9855
|
}
|
|
9796
9856
|
await next();
|
|
9797
9857
|
});
|
|
9798
|
-
`}function
|
|
9858
|
+
`}function fn(e){return `
|
|
9799
9859
|
adminApp.get('/', (c) => {
|
|
9800
9860
|
return c.html(Layout({
|
|
9801
9861
|
title: "Admin Dashboard",
|
|
@@ -9812,7 +9872,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9812
9872
|
\`
|
|
9813
9873
|
}));
|
|
9814
9874
|
});
|
|
9815
|
-
`}function
|
|
9875
|
+
`}function gn(e,t,n){let r=$t(t),a=Ct(r),o=qt(r),i=Kt(t),s=en(n),c=dn(),u=pn(a,n),l=mn(),p=fn(o);return `import { Hono } from "hono";
|
|
9816
9876
|
import { html, raw } from "hono/html";
|
|
9817
9877
|
import { drizzle } from "drizzle-orm/d1";
|
|
9818
9878
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -9841,8 +9901,8 @@ ${p}
|
|
|
9841
9901
|
app.route('/admin', adminApp);
|
|
9842
9902
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
9843
9903
|
}
|
|
9844
|
-
`}function
|
|
9845
|
-
`}function
|
|
9904
|
+
`}function se(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"&&(typeof t.enums=="object"||t.enums===void 0)}function D(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function E(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(t,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(t,n)=>n.toUpperCase())}function ce(e){return e.endsWith("ies")?`${e.slice(0,-3)}y`:e.endsWith("ses")?e.slice(0,-2):e.endsWith("s")&&e.length>1?e.slice(0,-1):e}function g(e){return JSON.stringify(e)}function Lr(e){if(typeof e=="string")return g(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return "null";if(e instanceof Date)return g(e.toISOString());if(typeof e=="object"&&e!==null)return JSON.stringify(e);throw new Error(`Unsupported SQL default value '${String(e)}'. Use string, number, boolean, null, Date, array, or object.`)}function Hr(e){return {kind:"schema",tables:Object.fromEntries(Object.entries(e.tables).map(([t,n])=>[t,{kind:"table",sqlName:n.sqlName,columns:Object.fromEntries(Object.entries(n.columns).map(([r,a])=>[r,{...a}])),relations:Object.fromEntries(Object.entries(n.relations).map(([r,a])=>[r,{...a}]))}])),enums:Object.fromEntries(Object.entries(e.enums??{}).map(([t,n])=>[t,{...n}]))}}function U(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function hn(e,t,n,r,a,o,i){let s=t.columns[n];if(s){if(s.references&&(s.references.table!==r||s.references.column!==a))throw new Error(`Inferred relation '${e}.${n}' conflicts with explicit references(${s.references.table}.${s.references.column}).`);t.columns[n]={...s,notNull:s.notNull??(s.nullable===true?false:o.notNull),nullable:s.nullable??(o.notNull===false?true:void 0),references:{table:r,column:a,onDelete:s.references?.onDelete??o.onDelete,onUpdate:s.references?.onUpdate??o.onUpdate}};return}t.columns[n]={kind:"column",type:o.fkType??i,sqlName:o.sqlName,notNull:o.notNull??true,nullable:o.notNull===false?true:void 0,references:{table:r,column:a,onDelete:o.onDelete,onUpdate:o.onUpdate}};}function yn(e,t,n){if(t.notNull===true&&t.nullable===true)throw new Error(`Invalid nullable configuration on '${e}': cannot set both notNull and nullable to true.`);return t.notNull===true?true:t.nullable===true||t.notNull===false?false:n}function bn(e,t){return `${e}:${t}`}function zr(e,t,n,r){let a=bn(e,t),o=bn(n,r);return a<=o?{key:`${a}|${o}`,leftTable:e,leftReferenceField:t,rightTable:n,rightReferenceField:r,sourceIsLeft:true}:{key:`${o}|${a}`,leftTable:n,leftReferenceField:r,rightTable:e,rightReferenceField:t,sourceIsLeft:false}}function Ur(e,t){return `${e}${E(t)}Links`}function wn(e,t,n){let r=ce(e),a=ce(t);return r===a?`${n}${E(r)}Id`:`${r}Id`}function _r(e,t,n){if(e.junctionTable!==t.junctionTable)throw new Error(`manyToMany pair '${n}' has conflicting junctionTable values ('${e.junctionTable}' vs '${t.junctionTable}').`);if(e.leftField!==t.leftField)throw new Error(`manyToMany pair '${n}' has conflicting left field values ('${e.leftField}' vs '${t.leftField}').`);if(e.rightField!==t.rightField)throw new Error(`manyToMany pair '${n}' has conflicting right field values ('${e.rightField}' vs '${t.rightField}').`);if(e.leftSqlName!==t.leftSqlName)throw new Error(`manyToMany pair '${n}' has conflicting left sql name values ('${e.leftSqlName}' vs '${t.leftSqlName}').`);if(e.rightSqlName!==t.rightSqlName)throw new Error(`manyToMany pair '${n}' has conflicting right sql name values ('${e.rightSqlName}' vs '${t.rightSqlName}').`);if(e.onDelete!==t.onDelete)throw new Error(`manyToMany pair '${n}' has conflicting onDelete values ('${e.onDelete}' vs '${t.onDelete}').`);if(e.onUpdate!==t.onUpdate)throw new Error(`manyToMany pair '${n}' has conflicting onUpdate values ('${e.onUpdate}' vs '${t.onUpdate}').`);return e}function Qr(e){let t=new Map;for(let[n,r]of Object.entries(e.tables))for(let a of Object.values(r.relations)){if(a.relation!=="manyToMany")continue;let o=a.referenceField??"id",i=a.targetReferenceField??"id",s=zr(n,o,a.targetTable,i),c=wn(s.leftTable,s.rightTable,"source"),u=wn(s.rightTable,s.leftTable,"target"),l={leftTable:s.leftTable,leftReferenceField:s.leftReferenceField,rightTable:s.rightTable,rightReferenceField:s.rightReferenceField,junctionTable:a.junctionTable??Ur(s.leftTable,s.rightTable),leftField:s.sourceIsLeft?a.sourceField??c:a.targetField??c,rightField:s.sourceIsLeft?a.targetField??u:a.sourceField??u,leftSqlName:s.sourceIsLeft?a.sourceSqlName:a.targetSqlName,rightSqlName:s.sourceIsLeft?a.targetSqlName:a.sourceSqlName,onDelete:a.onDelete,onUpdate:a.onUpdate};if(l.leftField===l.rightField)throw new Error(`manyToMany pair '${s.key}' resolves to duplicate junction fields '${l.leftField}'. Set sourceField/targetField explicitly.`);let p=t.get(s.key);p?_r(p,l,s.key):t.set(s.key,l),a.referenceField=o,a.targetReferenceField=i,a.junctionTable=l.junctionTable,a.sourceField=s.sourceIsLeft?l.leftField:l.rightField,a.targetField=s.sourceIsLeft?l.rightField:l.leftField,a.sourceSqlName=s.sourceIsLeft?l.leftSqlName:l.rightSqlName,a.targetSqlName=s.sourceIsLeft?l.rightSqlName:l.leftSqlName;}for(let n of t.values()){if(n.junctionTable in e.tables)throw new Error(`manyToMany auto junction table '${n.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`);let r=U(e,n.leftTable,n.leftReferenceField)??"string",a=U(e,n.rightTable,n.rightReferenceField)??"string";e.tables[n.junctionTable]={kind:"table",columns:{[n.leftField]:{kind:"column",type:r,sqlName:n.leftSqlName,notNull:true,nullable:false,references:{table:n.leftTable,column:n.leftReferenceField,onDelete:n.onDelete,onUpdate:n.onUpdate},index:true},[n.rightField]:{kind:"column",type:a,sqlName:n.rightSqlName,notNull:true,nullable:false,references:{table:n.rightTable,column:n.rightReferenceField,onDelete:n.onDelete,onUpdate:n.onUpdate},index:true}},relations:{[n.leftTable]:{kind:"relation",relation:"one",targetTable:n.leftTable,field:n.leftField,referenceField:n.leftReferenceField},[n.rightTable]:{kind:"relation",relation:"one",targetTable:n.rightTable,field:n.rightField,referenceField:n.rightReferenceField}}};}}function Kr(e){for(let[t,n]of Object.entries(e.tables)){for(let[r,a]of Object.entries(n.columns))if(a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${t}.${r}': cannot set both notNull and nullable to true.`);for(let[r,a]of Object.entries(n.relations))if(a.relation!=="manyToMany"&&a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${t}.${r}': cannot set both notNull and nullable to true.`)}}function Jr(e){Kr(e);let t=Hr(e);for(let[n,r]of Object.entries(t.tables))for(let[a,o]of Object.entries(r.relations)){if(o.relation!=="one")continue;let i=o.referenceField??"id",s=o.field??`${a}Id`;o.field=s;let c=U(t,o.targetTable,i)??o.fkType??"string";hn(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:yn(`${n}.${a}`,o,true),onDelete:o.onDelete,onUpdate:o.onUpdate},c);}for(let[n,r]of Object.entries(t.tables))for(let a of Object.values(r.relations)){if(a.relation!=="many")continue;let o=t.tables[a.targetTable];if(!o)continue;let i=a.referenceField??"id",s=a.field??`${ce(n)}Id`;a.field=s;let c=U(t,n,i)??a.fkType??"string";hn(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:yn(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},c);}return Qr(t),t}function Tn(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function V(e){return e.notNull!==true}function Gr(e,t,n){let r=t.sqlName??D(e),a=r!==e;if(t.type==="int")return a?`t.int(${g(r)})`:"t.int()";if(t.type==="string")return t.length!==void 0?a?`t.text(${g(r)}, { length: ${t.length} })`:`t.text({ length: ${t.length} })`:a?`t.text(${g(r)})`:"t.text()";if(t.type==="boolean")return a?`t.int(${g(r)}, { mode: "boolean" })`:'t.int({ mode: "boolean" })';if(t.type==="date")return a?`t.int(${g(r)}, { mode: "timestamp_ms" })`:'t.int({ mode: "timestamp_ms" })';if(t.type==="enum"&&t.enumValues&&t.enumValues.length>0)return t.isArray?a?`t.text(${g(r)}).array()`:"t.text().array()":a?`t.text(${g(r)})`:"t.text()";if(t.type==="json"&&t.jsonShape){let o=_(t.jsonShape);return `${a?`t.text(${g(r)}, { mode: "json" })`:'t.text({ mode: "json" })'}.$type<${o}>()`}return n==="camelToSnake"&&a?`t.text(${g(r)})`:"t.text()"}function Zr(e,t,n){let r=n.field,a=n.referenceField??"id";if(!r)throw new Error(`Relation on '${e}' targeting '${n.targetTable}' is missing a local field.`);if(!(r in t.columns))throw new Error(`Relation '${e}.${r}' references missing local field '${r}'.`);return {sourceField:r,targetField:a}}function Xr(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
9905
|
+
`}function Yr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function ea(e,t,n){if(t.references)return {tableName:t.references.table,fieldName:t.references.column};let r=Object.values(n.relations).find(a=>a.relation==="one"&&a.field===e);if(r)return {tableName:r.targetTable,fieldName:r.referenceField??"id"}}function ta(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.columns)){if(i.type!=="json"||!i.jsonShape)continue;let s=de(i.jsonShape);a.push(`${g(o)}: { shape: ${s} },`);}a.length!==0&&t.push(`${g(n)}: {
|
|
9846
9906
|
${a.map(o=>` ${o}`).join(`
|
|
9847
9907
|
`)}
|
|
9848
9908
|
},`);}return t.length===0?`export const __appflareJsonColumns = {} as const;
|
|
@@ -9850,7 +9910,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9850
9910
|
${t.map(n=>` ${n}`).join(`
|
|
9851
9911
|
`)}
|
|
9852
9912
|
} as const;
|
|
9853
|
-
`}function
|
|
9913
|
+
`}function de(e){return e.kind==="array"?`{ kind: "array", element: ${de(e.element)} }`:e.kind==="object"?`{ kind: "object", shape: { ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${de(r)}`).join(", ")} } }`:`{ kind: ${g(e.kind)} }`}function na(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations))i.relation==="manyToMany"&&i.junctionTable&&a.push(`${g(o)}: {
|
|
9854
9914
|
targetTable: ${g(i.targetTable)},
|
|
9855
9915
|
junctionTable: ${g(i.junctionTable)},
|
|
9856
9916
|
sourceField: ${g(i.sourceField??"")},
|
|
@@ -9865,7 +9925,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9865
9925
|
${t.map(n=>` ${n}`).join(`
|
|
9866
9926
|
`)}
|
|
9867
9927
|
} as const;
|
|
9868
|
-
`}function
|
|
9928
|
+
`}function ra(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations)){if(i.relation==="one"){a.push(`${g(o)}: {
|
|
9869
9929
|
kind: "one",
|
|
9870
9930
|
targetTable: ${g(i.targetTable)},
|
|
9871
9931
|
sourceField: ${g(i.field??"")},
|
|
@@ -9891,7 +9951,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
9891
9951
|
${t.map(n=>` ${n}`).join(`
|
|
9892
9952
|
`)}
|
|
9893
9953
|
} as const;
|
|
9894
|
-
`}function
|
|
9954
|
+
`}function aa(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let l of Object.values(e.tables)){for(let p of Yr(l))n.has(p)||r.add(p);for(let p of Object.values(l.columns))p.references&&!n.has(p.references.table)&&r.add(p.references.table);}let a=new Map;for(let[l,p]of Object.entries(e.tables))for(let[d,y]of Object.entries(p.columns))if(y.type==="enum"&&y.enumValues&&y.enumValues.length>0){let x=y.enumRef??`${l}_${d}`;a.has(x)||a.set(x,{column:y,tableName:l,fieldName:d});}let o=[],i=[];for(let[l,p]of a.entries()){let d=E(l),y=p.column.enumValues.map(x=>`"${x}"`).join(" | ");o.push(`export type ${d} = ${y};`),i.push(`export const ${d}Column = t.customType<{ data: ${d}; dataNotNull: ${d} }>({ dataType: () => "text" });`);}let s=[],c=[],u=[];for(let[l,p]of Object.entries(e.tables)){let d=p.sqlName??D(l),y=[],x=[];u.push(` ${l},`);for(let[b,h]of Object.entries(p.columns)){let v;if(h.type==="enum"&&h.enumValues&&h.enumValues.length>0){let R=h.enumRef??`${l}_${b}`,P=E(R),L=h.sqlName??D(b);v=L!==b?`${P}Column(${g(L)})`:`${P}Column()`,h.isArray&&(v+=".array()");}else v=Gr(b,h,t);h.uuidPrimaryKey&&(v+=".$defaultFn(() => crypto.randomUUID())"),h.primaryKey&&(v+=h.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),h.notNull&&(v+=".notNull()"),h.sqlDefault!==void 0&&(v+=`.default(${Lr(h.sqlDefault)})`);let F=ea(b,h,p);if(F)if(h.references?.onDelete||h.references?.onUpdate){let R=[];h.references.onDelete&&R.push(`onDelete: ${g(h.references.onDelete)}`),h.references.onUpdate&&R.push(`onUpdate: ${g(h.references.onUpdate)}`),v+=`.references((): AnySQLiteColumn => ${F.tableName}.${F.fieldName}, { ${R.join(", ")} })`;}else v+=`.references((): AnySQLiteColumn => ${F.tableName}.${F.fieldName})`;if(h.unique){let R=typeof h.unique=="object"&&h.unique.name?h.unique.name:`${d}_${D(b)}_unique_idx`;x.push(` t.uniqueIndex(${g(R)}).on(table.${b})`);}if(h.index){let R=typeof h.index=="object"&&h.index.name?h.index.name:`${d}_${D(b)}_idx`;x.push(` t.index(${g(R)}).on(table.${b})`);}y.push(` ${b}: ${v},`);}x.length>0?s.push(`export const ${l} = table(
|
|
9895
9955
|
${g(d)},
|
|
9896
9956
|
{
|
|
9897
9957
|
${y.join(`
|
|
@@ -9904,16 +9964,16 @@ ${x.join(`,
|
|
|
9904
9964
|
);`):s.push(`export const ${l} = table(${g(d)}, {
|
|
9905
9965
|
${y.join(`
|
|
9906
9966
|
`)}
|
|
9907
|
-
});`);let
|
|
9967
|
+
});`);let S=Object.entries(p.relations).filter(([,b])=>b.relation==="one"),w=Object.entries(p.relations).filter(([,b])=>b.relation==="many"),q=Object.entries(p.relations).filter(([,b])=>b.relation==="manyToMany");if(S.length===0&&w.length===0&&q.length===0)continue;let $=[];for(let[b,h]of S){let v=Zr(l,p,h);$.push(` ${b}: one(${h.targetTable}, {
|
|
9908
9968
|
fields: [${l}.${v.sourceField}],
|
|
9909
9969
|
references: [${h.targetTable}.${v.targetField}],
|
|
9910
|
-
}),`);}for(let[b,h]of w)
|
|
9911
|
-
${
|
|
9970
|
+
}),`);}for(let[b,h]of w)$.push(` ${b}: many(${h.targetTable}),`);for(let[b,h]of q){if(!h.junctionTable)throw new Error(`manyToMany relation '${l}.${b}' is missing junctionTable after normalization.`);$.push(` ${b}: many(${h.junctionTable}),`);}c.push(`export const ${l}Relations = relations(${l}, ({ one, many }) => ({
|
|
9971
|
+
${$.join(`
|
|
9912
9972
|
`)}
|
|
9913
9973
|
}));`),u.push(` ${l}Relations,`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9914
9974
|
import { sqliteTable as table, type AnySQLiteColumn } from "drizzle-orm/sqlite-core";
|
|
9915
9975
|
import { relations } from "drizzle-orm";
|
|
9916
|
-
${
|
|
9976
|
+
${Xr(r)}
|
|
9917
9977
|
${o.join(`
|
|
9918
9978
|
`)}
|
|
9919
9979
|
${i.join(`
|
|
@@ -9932,12 +9992,12 @@ ${u.join(`
|
|
|
9932
9992
|
`)}
|
|
9933
9993
|
} as const;
|
|
9934
9994
|
|
|
9935
|
-
${
|
|
9995
|
+
${ta(e)}
|
|
9936
9996
|
|
|
9937
|
-
${
|
|
9997
|
+
${na(e)}
|
|
9938
9998
|
|
|
9939
|
-
${
|
|
9940
|
-
`}function
|
|
9999
|
+
${ra(e)}
|
|
10000
|
+
`}function pe(e){return e.kind==="array"?`z.array(${pe(e.element)})`:e.kind==="object"?`z.object({ ${Object.entries(e.shape).map(([n,r])=>`${g(n)}: ${pe(r)}`).join(", ")} })`:e.kind==="string"?"z.string()":e.kind==="number"?"z.number()":e.kind==="boolean"?"z.boolean()":e.kind==="date"?"z.date()":"z.unknown()"}function xn(e,t,n){let r="z.unknown()";if(e.type==="int")r="z.number().int()";else if(e.type==="string")r="z.string()",e.length!==void 0&&(r+=`.max(${e.length})`);else if(e.type==="boolean")r="z.boolean()";else if(e.type==="date")r="z.date()";else if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0){let o=`z.enum([${e.enumValues.map(i=>`"${i}"`).join(", ")}])`;r=e.isArray?`z.array(${o})`:o;}else e.type==="json"&&e.jsonShape&&(r=pe(e.jsonShape));return t&&(r+=".optional()"),n&&(r+=".nullable()"),r}function oa(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=E(n),o=[],i=[];for(let[s,c]of Object.entries(r.columns))o.push(` ${s}: ${xn(c,Tn(c),V(c))},`),i.push(` ${s}: ${xn(c,V(c),V(c))},`);t.push(`export const ${n}InsertSchema = z.object({
|
|
9941
10001
|
${o.join(`
|
|
9942
10002
|
`)}
|
|
9943
10003
|
});
|
|
@@ -9951,7 +10011,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
9951
10011
|
`);}return `import { z } from "zod";
|
|
9952
10012
|
|
|
9953
10013
|
${t.join(`
|
|
9954
|
-
`)}`}function
|
|
10014
|
+
`)}`}function _(e){return e.kind==="array"?`Array<${_(e.element)}>`:e.kind==="object"?`{ ${Object.entries(e.shape).map(([n,r])=>`${n}: ${_(r)}`).join("; ")} }`:e.kind==="string"?"string":e.kind==="number"?"number":e.kind==="boolean"?"boolean":e.kind==="date"?"Date":"unknown"}function ia(e){if(e.type==="int")return "number";if(e.type==="string")return "string";if(e.type==="boolean")return "boolean";if(e.type==="date")return "Date";if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0){let t=e.enumValues.map(n=>`"${n}"`).join(" | ");return e.isArray?`Array<${t}>`:t}return e.type==="json"&&e.jsonShape?_(e.jsonShape):"unknown"}function sa(e){let t=[];for(let[r,a]of Object.entries(e.enums??{})){let o=E(r),i=a.values.map(s=>`"${s}"`).join(" | ");t.push(`export type ${o} = ${i};`);}let n=[];for(let[r,a]of Object.entries(e.tables)){let o=E(r),i=[],s=[];for(let[c,u]of Object.entries(a.columns)){let l=ia(u),p=V(u)?" | null":"";i.push(` ${c}${V(u)?"?":""}: ${l}${p};`),s.push(` ${c}${Tn(u)?"?":""}: ${l}${p};`);}n.push(`export type ${o} = {
|
|
9955
10015
|
${i.join(`
|
|
9956
10016
|
`)}
|
|
9957
10017
|
};
|
|
@@ -9964,25 +10024,25 @@ ${s.join(`
|
|
|
9964
10024
|
${n.join(`
|
|
9965
10025
|
|
|
9966
10026
|
`)}
|
|
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
|
|
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=
|
|
9970
|
-
`);let
|
|
9971
|
-
`),...
|
|
9972
|
-
`),Bun.write(
|
|
9973
|
-
`);let J=path.relative(o,
|
|
9974
|
-
`),
|
|
9975
|
-
`));function
|
|
10027
|
+
`}function la(e,t){if(t){let n=e[t];if(!se(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(se(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function vn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=path.resolve(e.configDir,t.entry),a=path.resolve(e.configDir,t.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,t.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),u=la(c,t.exportName),l=Jr(u);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.dirname(i),{recursive:true})]);let p=aa(l,n),d=sa(l),y=oa(l);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(l.tables)}}function ca(e){return e.replaceAll("\\","/")}function j(e,t){let n=ca(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var fa=new Set([".ts",".tsx",".mts",".cts"]);async function An(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await An(a));continue}r.isFile()&&fa.has(path.extname(r.name))&&n.push(a);}return n}function fe(e){return e.replace(/\.[cm]?tsx?$/,"")}function me(e,t){let n=e,r=false,a,o="unknown",i,s,c;for(;f__namespace.isCallExpression(n);){let u=n.expression;if(!f__namespace.isPropertyAccessExpression(u))break;let l=u.name.text;if(l==="optional"||l==="nullable")r=true,n=u.expression;else if(l==="default"){r=true;let p=n.arguments[0];p&&(f__namespace.isStringLiteral(p)||f__namespace.isNumericLiteral(p)?a=p.text:p.kind===f__namespace.SyntaxKind.TrueKeyword?a="true":p.kind===f__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=u.expression;}else if(l==="string"||l==="uuid"||l==="email"||l==="url"){o="string";break}else if(l==="number"||l==="int"||l==="float"){o="number";break}else if(l==="boolean"){o="boolean";break}else if(l==="date"){o="date";break}else if(l==="object"){o="object";let p=n.arguments[0];if(p&&f__namespace.isObjectLiteralExpression(p)){i=[];for(let d of p.properties)f__namespace.isPropertyAssignment(d)&&f__namespace.isIdentifier(d.name)&&i.push(me(d.initializer,d.name.text));}break}else if(l==="array"){o="array";let p=n.arguments[0];if(p){let d=me(p,"");s=d.type==="array"?"unknown":d.type,d.type==="object"&&(c=d.fields);}break}else n=u.expression;}return {name:t,type:o,optional:r,defaultValue:a,fields:i,itemType:s,itemFields:c}}function ga(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f__namespace.isPropertyAssignment(r)&&f__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)||n.push(me(r.initializer,r.name.text));return n}function ha(e){return f__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f__namespace.SyntaxKind.ExportKeyword)??false:false}function Nn(e){return f__namespace.isIdentifier(e)?e.text:f__namespace.isParenthesizedExpression(e)?Nn(e.expression):null}function ya(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return f__namespace.isStringLiteral(n)||f__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>f__namespace.isStringLiteral(r)||f__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function ba(e,t){let n=f__namespace.createSourceFile(t,e,f__namespace.ScriptTarget.Latest,true,f__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(ha(a))for(let o of a.declarationList.declarations){if(!f__namespace.isIdentifier(o.name)||!o.initializer||!f__namespace.isCallExpression(o.initializer))continue;let i=Nn(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?ya(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ga(o.initializer.arguments[0]):[]});}return r}function Rn(e,t,n){let r=t.replace(/\\/g,"/"),o=fe(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function wa(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function kn(e,t){let n=e.replace(/\\/g,"/"),a=fe(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function $n(e){let t=[],n=await An(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=path.relative(e.scanDirAbs,a),c=ba(i,a),u=[{kind:"query",kindDirectory:"queries",exports:c.filter(l=>l.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(l=>l.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(l=>l.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(l=>l.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(l=>l.kind==="storage")}];for(let l of u){if(l.exports.length===0)continue;let p=wa(s,l.kindDirectory);for(let d of l.exports){let y=l.kind==="query"||l.kind==="mutation"?kn(p,d.exportName):void 0,x=l.kind==="scheduler"||l.kind==="cron"?kn(p,d.exportName):void 0,S=l.kind==="query"||l.kind==="mutation"?[...fe(p).split("/").filter(Boolean),d.exportName]:void 0,w=l.kind==="query"?Rn("queries",p,d.exportName):l.kind==="mutation"?Rn("mutations",p,d.exportName):l.kind==="storage"?`/storage/managers/${d.exportName}`:`/${l.kindDirectory}/${x}`;t.push({kind:l.kind,exportName:d.exportName,filePath:a,importPath:j(e.outDirAbs,a),clientImportPath:j(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:S,taskName:x,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function Ta(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,u=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(u){n+=d,u=false;continue}if(d==="\\"){n+=d,u=true;continue}if(!s&&!c&&d==="'"){i=!i,n+=d;continue}if(!i&&!c&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){c=!c,n+=d;continue}if(i||s||c){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let l=n.trim();return l.length>0&&t.push(l),t}function va(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let c=0;c<e.length;c+=1){let u=e[c];if(s){s=false;continue}if(u==="\\"){s=true;continue}if(!o&&!i&&u==="'"){a=!a;continue}if(!a&&!i&&u==='"'){o=!o;continue}if(!a&&!o&&u==="`"){i=!i;continue}if(!(a||o||i)){if(u==="("){t+=1;continue}if(u===")"){t-=1;continue}if(u==="{"){n+=1;continue}if(u==="}"){n-=1;continue}if(u==="["){r+=1;continue}if(u==="]"){r-=1;continue}if(u===":"&&t===0&&n===0&&r===0)return c}}return -1}function Ra(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/mode\s*:\s*["'`]json["'`]/.test(t)||/\.json\s*\(/.test(t)?"json":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ka(e){let t=Ta(e),n=[];for(let r of t){let a=va(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),c=/autoincrement\s*:\s*true/i.test(i),u=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||u||c||s;n.push({name:o,expression:i,type:Ra(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function Sa(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,u=false,l=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!u&&!l&&y==="'"){c=!c;continue}if(!c&&!l&&y==='"'){u=!u;continue}if(!c&&!u&&y==="`"){l=!l;continue}if(!(c||u||l)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let c=r(e,s);if(c===-1){a=t.exec(e);continue}let u=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:ka(u)}),a=t.exec(e);}return n}async function Fn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await Fn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function qn(e,t=[]){let n=await Fn(e.scanDirAbs).catch(()=>[]),r=path.resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),c=Sa(s);if(c.length>0)return {schemaPath:o,tables:c}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function ge(e){let t=e;for(;;){if(fs.existsSync(path.resolve(t,"package.json")))return t;let n=path.dirname(t);if(n===t)return e;t=n;}}function Na(e,t){for(let n of t)try{return path.dirname(Bun.resolveSync(`${e}/package.json`,n))}catch{continue}throw new Error(`Could not resolve "${e}". Install it in your project (see appflare peerDependencies).`)}function I(e,t,n){return path.resolve(Na(e,n),t)}function B(e,t=[]){let n=[e,ge(process.cwd()),...t];return [...new Set(n)]}function qa(e){let t=e.auth.options.plugins;if(!Array.isArray(t))return [];for(let n of t)if(n&&typeof n=="object"){let r=n;if(r.id==="admin"&&"options"in r){let a=r.options;if(a&&typeof a=="object"&&"roles"in a){let o=a.roles;if(o&&typeof o=="object")return Object.keys(o)}}}return []}function Ma(e){let r=e.auth.options?.user?.additionalFields;if(!r||typeof r!="object")return [];let a={string:"string",number:"number",boolean:"boolean",date:"Date"};return Object.entries(r).filter(([,o])=>o&&typeof o=="object"&&"type"in o).map(([o,i])=>({name:o,tsType:a[i.type]||"unknown"}))}async function Ea(e,t){let n=await Bun.file(e).text(),r=t.map(o=>`"${o}"`).join(" | "),a=n.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
10028
|
+
import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["']role["']\)/,`role: customType<{ data: ${r}; dataNotNull: ${r} }>({ dataType: () => "text" })("role")`);await Bun.write(e,a);}function ja(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function On(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=j(t,a),s=path.resolve(t,"client"),c=j(s,a),u=performance.now();await Promise.all([promises.mkdir(t,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(n,{recursive:true})]),process.stdout.write(`\u{1F4C1} Directories (${(performance.now()-u).toFixed(0)}ms)
|
|
10029
|
+
`);let l=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)))),p=B(l,[o]),d=I("typescript","bin/tsc",p),y=I("@better-auth/cli","dist/index.mjs",p),x=path.resolve(t,"server.ts"),S=path.resolve(t,"client.ts"),w=path.resolve(t,"auth.config.ts"),q=path.resolve(t,"auth.schema.ts"),$=path.resolve(t,"drizzle.config.ts"),b=path.resolve(n,"wrangler.json"),h=await vn(e),v=await qn(e,h?[h.schemaPath]:[]),F=j(t,v.schemaPath),R=await $n(e);process.stdout.write(`\u{1F50D} ${R.length} handler(s) (${(performance.now()-u).toFixed(0)}ms)
|
|
10030
|
+
`);let P=qa(r),L=Ma(r),be=St(r.auth.basePath,r.database[0].binding,r.kv[0]?.binding,r.scheduler.binding,r.r2[0]?.binding,r.realtime.binding,r.realtime.objectName,r.realtime.subscribePath,r.realtime.websocketPath,r.realtime.protocol),Kn=Fe(c,R),Jn=Y(F,R,r.r2[0]?.binding,P,L),Gn=Re(i),Zn=h?[ja(o,h.schemaPath),...r.schema.filter(T=>!/(^|\/)schema\.ts$/.test(T))]:r.schema,Xn=qe(Zn),Yn=Nt(e,R),er=gn(F,v,R),tr=path.resolve(t,"admin.routes.ts"),nr=Jn.map(T=>Bun.write(path.resolve(t,T.relativePath),T.source)),rr=Kn.map(T=>Bun.write(path.resolve(t,T.relativePath),T.source));await Promise.all([Bun.write(x,be),Bun.write(S,`export * from "./client/index";
|
|
10031
|
+
`),...rr,...nr,Bun.write(w,Gn),Bun.write(q,""),Bun.write($,Xn),Bun.write(b,`${JSON.stringify(Yn,null,2)}
|
|
10032
|
+
`),Bun.write(tr,er)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-u).toFixed(0)}ms)
|
|
10033
|
+
`);let J=path.relative(o,w).replace(/\\/g,"/"),ar=J.startsWith(".")?J:`./${J}`,G=path.relative(o,q).replace(/\\/g,"/"),or=G.startsWith(".")?G:`./${G}`,we=await Bun.spawn([process.execPath,y,"generate","--config",ar,"--output",or,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(we!==0)throw new Error(`better-auth generation failed with exit code ${we}`);process.stdout.write(`\u{1F510} Auth schema (${(performance.now()-u).toFixed(0)}ms)
|
|
10034
|
+
`),P.length>0&&(await Ea(q,P),process.stdout.write(`\u{1F527} Patched role type (${(performance.now()-u).toFixed(0)}ms)
|
|
10035
|
+
`));function ir(T={}){return {compilerOptions:{lib:["es2024"],types:["@types/node","@cloudflare/workers-types/2023-07-01"],module:"es2022",target:"es2024",moduleResolution:"bundler",strictNullChecks:true,skipLibCheck:true,declaration:true,emitDeclarationOnly:true,noCheck:true,jsx:"react-jsx",paths:{"_generated/*":["./*"]},...T},include:["./*.ts","./client/*.ts"]}}let xe=path.resolve(t,"tsconfig.js.json");await Promise.all([Bun.write(xe,`${JSON.stringify(ir({declaration:true,emitDeclarationOnly:false}),null,2)}
|
|
9976
10036
|
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-u).toFixed(0)}ms)
|
|
9977
|
-
`);async function
|
|
9978
|
-
`);let
|
|
9979
|
-
`);async function
|
|
9980
|
-
`);let
|
|
9981
|
-
`);let
|
|
9982
|
-
`);let C=await Bun.spawn([process.execPath,
|
|
9983
|
-
`);}}var
|
|
10037
|
+
`);async function sr(T,C){process.stdout.write(`\u2699\uFE0F ${C}... (${(performance.now()-u).toFixed(0)}ms)
|
|
10038
|
+
`);let N=await Bun.spawn([process.execPath,d,"-p",T],{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(N!==0)throw new Error(`tsc ${C} failed with exit code ${N}`)}await sr(xe,"JS files"),process.stdout.write(`\u2705 JS + declarations (${(performance.now()-u).toFixed(0)}ms)
|
|
10039
|
+
`);async function Te(T){let C=await promises.readdir(T,{withFileTypes:true});for(let k of C){let N=path.join(T,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith("."))continue;await Te(N);}else k.name.endsWith(".ts")&&!k.name.endsWith(".d.ts")&&await promises.rm(N);}}await Te(t),process.stdout.write(`\u{1F4E6} Cleaned .ts files (${(performance.now()-u).toFixed(0)}ms)
|
|
10040
|
+
`);let lr=t+"/";async function ve(T){let C=await promises.readdir(T,{withFileTypes:true});for(let k of C){let N=path.join(T,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith(".")||N===t)continue;await ve(N);}else !N.startsWith(lr)&&(k.name.endsWith(".d.ts")||k.name.endsWith(".js"))&&await promises.rm(N);}}await ve(o),process.stdout.write(`\u{1F9F9} Cleanup (${(performance.now()-u).toFixed(0)}ms)
|
|
10041
|
+
`);let ur=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.existsSync(ur)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-u).toFixed(0)}ms)
|
|
10042
|
+
`);let C=await Bun.spawn([process.execPath,d,"--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(C!==0)throw new Error(`TypeScript build failed with exit code ${C}`);process.stdout.write(`\u2705 Build complete (${(performance.now()-u).toFixed(0)}ms)
|
|
10043
|
+
`);}}var Dn=zod.z.object({binding:zod.z.string().min(1),databaseName:zod.z.string().min(1),databaseId:zod.z.string().min(1),previewDatabaseId:zod.z.string().min(1).optional(),migrationsDir:zod.z.string().min(1).optional()}).strict(),Vn=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),Bn=zod.z.object({binding:zod.z.string().min(1),bucketName:zod.z.string().min(1),previewBucketName:zod.z.string().min(1).optional(),jurisdiction:zod.z.string().min(1).optional()}).strict(),Wn=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),queue:zod.z.string().min(1).optional()}).strict(),Da=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),className:zod.z.string().min(1).optional(),objectName:zod.z.string().min(1).optional(),subscribePath:zod.z.string().min(1).optional(),websocketPath:zod.z.string().min(1).optional(),protocol:zod.z.string().min(1).optional()}).strict(),Va=zod.z.object({scanDir:zod.z.string().min(1),outDir:zod.z.string().min(1),wranglerOutDir:zod.z.string().min(1).optional(),wranglerOutPath:zod.z.string().min(1).optional(),schema:zod.z.array(zod.z.string()).min(1),schemaDsl:zod.z.object({entry:zod.z.string().min(1),exportName:zod.z.string().min(1).optional(),outFile:zod.z.string().min(1).optional(),typesOutFile:zod.z.string().min(1).optional(),zodOutFile:zod.z.string().min(1).optional(),namingStrategy:zod.z.literal("camelToSnake").optional()}).strict().optional(),database:zod.z.union([Dn,zod.z.array(Dn).min(1)]),kv:zod.z.union([Vn,zod.z.array(Vn)]).optional(),r2:zod.z.union([Bn,zod.z.array(Bn)]).optional(),auth:zod.z.object({enabled:zod.z.boolean(),basePath:zod.z.string().min(1),options:zod.z.custom(e=>typeof e=="object"&&e!==null),clientOptions:zod.z.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:Wn.optional(),realtime:Da.optional(),wranglerOverrides:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),build:zod.z.boolean().optional()}).strict();function Ln(e){return typeof e=="object"&&e!==null}function Ba(e){let t=Ln(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=Wn.safeParse(t);return n.success?n.data:{}}function Wa(e){if(!Ln(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function La(e){let n={...Ba(e)??{},...e.scheduler??{}},r=e.realtime??{};return {...e,database:Array.isArray(e.database)?e.database:[e.database],kv:e.kv?Array.isArray(e.kv)?e.kv:[e.kv]:[],r2:e.r2?Array.isArray(e.r2)?e.r2:[e.r2]:[],scheduler:{enabled:n.enabled??true,binding:n.binding??"APPFLARE_SCHEDULER_QUEUE",queue:n.queue},realtime:{enabled:r.enabled??true,binding:r.binding??"APPFLARE_REALTIME",className:r.className??"AppflareRealtimeDurableObject",objectName:r.objectName??"global",subscribePath:r.subscribePath??"/realtime/subscribe",websocketPath:r.websocketPath??"/realtime/ws",protocol:r.protocol??"appflare.realtime.v1"},wranglerOverrides:Wa(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function W(e){let t=path.isAbsolute(e??"")?e:path.resolve(process.cwd(),e??"appflare.config.ts"),n=path.dirname(t),o=(await import(url.pathToFileURL(t).href)).default,i=Va.parse(o),s=La(i);return {configPath:t,configDir:n,scanDirAbs:path.resolve(n,s.scanDir),outDirAbs:path.resolve(n,s.outDir),wranglerOutDirAbs:path.resolve(n,s.wranglerOutDir),config:s}}async function K(e,t={}){let n=await W(e);if(t.build!==void 0&&(n.config.build=t.build),await On(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
9984
10044
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
9985
|
-
`);}async function
|
|
9986
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
10045
|
+
`);}async function Un(e,t={}){if(await K(e,{build:t.build}),!t.watch)return;let n=await W(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await K(e,{build:t.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
10046
|
+
`);}finally{r=false,a&&(a=false,await o());}};Ha__default.default.watch(n.scanDirAbs,{ignoreInitial:true,ignored:s=>s.includes("/_generated/")||s.includes("/dist/")||s.includes("/out/")||s.includes("/node_modules/")||s.endsWith(".d.ts")}).on("all",async(s,c)=>{process.stdout.write(`\u{1F504} Change detected: ${c}
|
|
9987
10047
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
9988
|
-
`);}async function
|
|
10048
|
+
`);}async function _n(e,t={}){let n=await W(e),r=ge(process.cwd());if([!!t.local,!!t.remote,!!t.preview].filter(Boolean).length>1)throw new Error("Only one of --local, --remote, or --preview can be set.");let o=path.resolve(n.outDirAbs,"drizzle.config.js"),i=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)))),s=B(i,[n.configDir,r]),c=I("drizzle-kit","bin.cjs",s),l=await Bun.spawn([process.execPath,c,"generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(l!==0)throw new Error(`drizzle-kit generate failed with exit code ${l}`);let p=n.config.database[0].databaseName,d=I("wrangler","bin/wrangler.js",s),y=[process.execPath,d,"d1","migrations","apply",p];t.local?y.push("--local"):t.remote?y.push("--remote"):t.preview&&y.push("--preview");let S=await Bun.spawn(y,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(S!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${S}`)}async function Qn(e,t={name:"",email:"",password:""}){let n=await W(e);if([!!t.local,!!t.remote].filter(Boolean).length>1)throw new Error("Only one of --local or --remote can be set.");let{hashPassword:a}=await import('better-auth/crypto'),o=await a(t.password),i=crypto.randomUUID(),s=crypto.randomUUID(),c=Date.now(),u=t.name.replace(/'/g,"''"),l=t.email.replace(/'/g,"''"),p=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${u}', '${l}', 1, ${c}, ${c}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${l}', 'credential', '${i}', '${o}', ${c}, ${c});`].join(" "),d=n.config.database[0].databaseName,y=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)))),x=B(y,[n.configDir]),S=I("wrangler","bin/wrangler.js",x),w=[process.execPath,S,"d1","execute",d,`--command=${p}`];t.local?w.push("--local"):t.remote&&w.push("--remote");let $=await Bun.spawn(w,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if($!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${$}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var O=new commander.Command;O.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");O.command("build").description("Generate server.ts, client.ts, auth.config.js, drizzle.config.js, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--no-build","Skip TypeScript build step").action(async e=>{await K(e.config,{build:e.build});});O.command("dev").description("Run generator in development mode").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("-w, --watch","Watch scanDir and regenerate on changes",false).option("--no-build","Skip TypeScript build step").action(async e=>{await Un(e.config,{watch:e.watch,build:e.build});});O.command("migrate").description("Generate drizzle migration files from outDir/auth.schema.ts and apply them to the configured D1 database").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute commands/files against a local DB for use with wrangler dev",false).option("--remote","Execute commands/files against a remote DB for use with wrangler dev --remote",false).option("--preview","Execute commands/files against a preview D1 DB",false).action(async e=>{await _n(e.config,{local:e.local,remote:e.remote,preview:e.preview});});O.command("add-admin").description("Add an admin user to the database").requiredOption("-n, --name <name>","Admin's display name").requiredOption("-e, --email <email>","Admin's email address").requiredOption("-p, --password <password>","Admin's password").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute command against a local DB for use with wrangler dev",false).option("--remote","Execute command against a remote DB for use with wrangler dev --remote",false).action(async e=>{await Qn(e.config,{name:e.name,email:e.email,password:e.password,local:e.local,remote:e.remote});});(async()=>{process.versions.bun||(console.error("Appflare CLI must be run with Bun."),process.exit(1)),await O.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|