appflare 0.2.31 → 0.2.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/generate.ts +68 -3
- package/dist/cli/index.js +174 -173
- package/dist/cli/index.mjs +174 -173
- package/package.json +1 -1
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'),fs=require('fs'),path=require('path'),promises=require('fs/promises'),url=require('url'),g=require('typescript'),zod=require('zod');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 g__namespace=/*#__PURE__*/_interopNamespace(g);function le(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 ce(){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 Hn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function ue(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function zn(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function de(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 H(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}${zn(i)}: ${H(s,t+1)},`);return e.operation&&(o.push(`${r}run: ${e.operation.alias}Route(runtime).run,`),o.push(`${r}schema: ${e.operation.alias}Route(runtime).schema,`),e.operation.kind==="query"&&o.push(`${r}subscribe: ${e.operation.alias}Route(runtime).subscribe,`)),o.push(`${n}}`),o.join(`
|
|
170
|
+
`)}function Ln(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===0)return null;let r=Hn(`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:`${ue(e.kind)}${ue(n.join("_"))}`}}function Un(e){let t=`${e.typeBase}Input`,n=`${e.typeBase}Output`,r=`${e.typeBase}Schema`,a=e.kind==="query"?"GET":"POST";return e.kind==="query"?`const ${e.alias}Route = (
|
|
171
171
|
runtime: RequestRuntime,
|
|
172
172
|
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}> => {
|
|
173
173
|
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}>["run"] = async (
|
|
@@ -353,15 +353,15 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
353
353
|
schema: ${r},
|
|
354
354
|
run,
|
|
355
355
|
};
|
|
356
|
-
};`}function
|
|
356
|
+
};`}function z(e){let t=e.map((u,c)=>Ln(u,c)).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(`
|
|
357
357
|
`),o=t.map(u=>{let c=`${u.typeBase}Input`,f=`${u.typeBase}Output`,d=`${u.typeBase}Schema`;return `const ${u.schemaConst} = z.object(${u.alias}.definition.args);
|
|
358
358
|
export type ${c} = z.input<typeof ${u.schemaConst}>;
|
|
359
359
|
export type ${f} = Awaited<ReturnType<typeof ${u.alias}.definition.handler>>;
|
|
360
360
|
export const ${d} = ${u.schemaConst};`}).join(`
|
|
361
361
|
|
|
362
|
-
`),i=t.map(u=>
|
|
362
|
+
`),i=t.map(u=>Un(u)).join(`
|
|
363
363
|
|
|
364
|
-
`),s=
|
|
364
|
+
`),s=H(de(n)),l=H(de(r));return `import { z } from "zod";
|
|
365
365
|
import type {
|
|
366
366
|
AppflareErrorMode,
|
|
367
367
|
AppflareRequestError,
|
|
@@ -737,11 +737,11 @@ export function createMutationsClient(
|
|
|
737
737
|
|
|
738
738
|
export type QueriesClient = ReturnType<typeof createQueriesClient>;
|
|
739
739
|
export type MutationsClient = ReturnType<typeof createMutationsClient>;
|
|
740
|
-
`}function
|
|
740
|
+
`}function pe(){return `export * from "./types";
|
|
741
741
|
export * from "./appflare";
|
|
742
742
|
export * from "./storage";
|
|
743
743
|
export * from "./handlers";
|
|
744
|
-
`}function
|
|
744
|
+
`}function me(){return `import type { StorageClient, StorageSignedUrlResponse, StorageListResponse } from "./types";
|
|
745
745
|
|
|
746
746
|
type AuthTokenResolver = (() => string | Promise<string>) | undefined;
|
|
747
747
|
|
|
@@ -933,7 +933,7 @@ export function createStorageClient(
|
|
|
933
933
|
},
|
|
934
934
|
};
|
|
935
935
|
}
|
|
936
|
-
`}function
|
|
936
|
+
`}function ge(e){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
937
937
|
import type appflareConfig from "${e}";
|
|
938
938
|
|
|
939
939
|
export type AppflareConfig = typeof appflareConfig;
|
|
@@ -1116,7 +1116,7 @@ export type RealtimeSubscriptionResponse = {
|
|
|
1116
1116
|
};
|
|
1117
1117
|
};
|
|
1118
1118
|
};
|
|
1119
|
-
`}function
|
|
1119
|
+
`}function fe(e,t){return [{relativePath:"client/index.ts",source:pe()},{relativePath:"client/types.ts",source:ge(e)},{relativePath:"client/storage.ts",source:me()},{relativePath:"client/handlers.ts",source:z(t)},{relativePath:"client/appflare.ts",source:ce()}]}function he(e){return `import { defineConfig } from "drizzle-kit";
|
|
1120
1120
|
|
|
1121
1121
|
export default defineConfig({
|
|
1122
1122
|
dialect: "sqlite",
|
|
@@ -1128,7 +1128,7 @@ export default defineConfig({
|
|
|
1128
1128
|
token: "token",
|
|
1129
1129
|
},
|
|
1130
1130
|
});
|
|
1131
|
-
`}function
|
|
1131
|
+
`}function ye(){return `
|
|
1132
1132
|
|
|
1133
1133
|
import { getHeaders } from "./server";
|
|
1134
1134
|
export async function resolveSession(
|
|
@@ -1162,7 +1162,7 @@ export async function resolveSession(
|
|
|
1162
1162
|
}
|
|
1163
1163
|
}
|
|
1164
1164
|
|
|
1165
|
-
`}function
|
|
1165
|
+
`}function be(){return `
|
|
1166
1166
|
type SchedulerQueueBinding = {
|
|
1167
1167
|
send: (body: unknown, options?: SchedulerEnqueueOptions) => Promise<void>;
|
|
1168
1168
|
};
|
|
@@ -1199,7 +1199,7 @@ type R2BucketBinding = {
|
|
|
1199
1199
|
options?: { expiresIn?: number },
|
|
1200
1200
|
) => Promise<URL>;
|
|
1201
1201
|
};
|
|
1202
|
-
`}function
|
|
1202
|
+
`}function we(){return `
|
|
1203
1203
|
export function createScheduler(
|
|
1204
1204
|
queue?: SchedulerQueueBinding,
|
|
1205
1205
|
): Scheduler {
|
|
@@ -1220,7 +1220,7 @@ export function createScheduler(
|
|
|
1220
1220
|
},
|
|
1221
1221
|
};
|
|
1222
1222
|
}
|
|
1223
|
-
`}function
|
|
1223
|
+
`}function xe(){return `
|
|
1224
1224
|
function createContextErrorHelpers() {
|
|
1225
1225
|
return {
|
|
1226
1226
|
error: (status: number, message: string, details?: unknown) => {
|
|
@@ -1228,7 +1228,7 @@ function createContextErrorHelpers() {
|
|
|
1228
1228
|
},
|
|
1229
1229
|
};
|
|
1230
1230
|
}
|
|
1231
|
-
`}function
|
|
1231
|
+
`}function Te(){return `
|
|
1232
1232
|
function normalizeStoragePath(path: string): string {
|
|
1233
1233
|
const trimmed = path.trim();
|
|
1234
1234
|
if (trimmed.length === 0) {
|
|
@@ -1284,7 +1284,7 @@ function buildSignedRequest(
|
|
|
1284
1284
|
headers,
|
|
1285
1285
|
});
|
|
1286
1286
|
}
|
|
1287
|
-
`}function
|
|
1287
|
+
`}function ve(){return `
|
|
1288
1288
|
function createStorageApi(
|
|
1289
1289
|
ctx: AppflareContext,
|
|
1290
1290
|
bucket: R2BucketBinding | undefined,
|
|
@@ -1363,7 +1363,7 @@ function createStorageApi(
|
|
|
1363
1363
|
},
|
|
1364
1364
|
};
|
|
1365
1365
|
}
|
|
1366
|
-
`}function
|
|
1366
|
+
`}function Re(e){return `
|
|
1367
1367
|
export async function createSchedulerExecutionContext(
|
|
1368
1368
|
env: Record<string, unknown>,
|
|
1369
1369
|
options: RegisterHandlersOptions,
|
|
@@ -1461,7 +1461,7 @@ export async function createExecutionContext(
|
|
|
1461
1461
|
ctx.storage = createStorageApi(ctx, storageBucket);
|
|
1462
1462
|
return ctx;
|
|
1463
1463
|
}
|
|
1464
|
-
`}function
|
|
1464
|
+
`}function ke(e){return `import type { Context } from "hono";
|
|
1465
1465
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
1466
1466
|
import { createAuth } from "./auth.config";
|
|
1467
1467
|
import {
|
|
@@ -1480,20 +1480,20 @@ import {
|
|
|
1480
1480
|
createQueryDb,
|
|
1481
1481
|
} from "./handlers";
|
|
1482
1482
|
|
|
1483
|
-
${
|
|
1483
|
+
${be()}
|
|
1484
1484
|
|
|
1485
|
-
${
|
|
1485
|
+
${ye()}
|
|
1486
1486
|
|
|
1487
|
-
${
|
|
1487
|
+
${we()}
|
|
1488
1488
|
|
|
1489
|
-
${
|
|
1489
|
+
${xe()}
|
|
1490
1490
|
|
|
1491
|
-
${
|
|
1491
|
+
${Te()}
|
|
1492
1492
|
|
|
1493
|
-
${
|
|
1493
|
+
${ve()}
|
|
1494
1494
|
|
|
1495
|
-
${
|
|
1496
|
-
`}function
|
|
1495
|
+
${Re(e)}
|
|
1496
|
+
`}function Se(){return `
|
|
1497
1497
|
export async function executeOperation<
|
|
1498
1498
|
TShape extends ZodRawShape,
|
|
1499
1499
|
TResult,
|
|
@@ -1532,7 +1532,7 @@ export function handleOperationError(
|
|
|
1532
1532
|
return c.json({ message: (error as Error).message ?? "Unknown error" }, 500);
|
|
1533
1533
|
}
|
|
1534
1534
|
|
|
1535
|
-
`}function
|
|
1535
|
+
`}function Ae(){return `import type { Context } from "hono";
|
|
1536
1536
|
import { ZodError, type ZodRawShape } from "zod";
|
|
1537
1537
|
import {
|
|
1538
1538
|
type AppflareContext,
|
|
@@ -1541,8 +1541,8 @@ import {
|
|
|
1541
1541
|
type WorkerEnv,
|
|
1542
1542
|
} from "./handlers";
|
|
1543
1543
|
|
|
1544
|
-
${
|
|
1545
|
-
`}function
|
|
1544
|
+
${Se()}
|
|
1545
|
+
`}function Ne(){return `import { betterAuth } from "better-auth";
|
|
1546
1546
|
import { auth } from "./auth.config";
|
|
1547
1547
|
import {
|
|
1548
1548
|
and,
|
|
@@ -1645,7 +1645,7 @@ export async function isStorageAllowed(
|
|
|
1645
1645
|
|
|
1646
1646
|
return false;
|
|
1647
1647
|
}
|
|
1648
|
-
`}function
|
|
1648
|
+
`}function $e(){return `type Primitive = string | number | boolean | Date;
|
|
1649
1649
|
type NonNil<T> = Exclude<T, null | undefined>;
|
|
1650
1650
|
type Friendly<T> = T extends Date ? Date | number : T;
|
|
1651
1651
|
type Comparable<T> = Friendly<Extract<NonNil<T>, Primitive>>;
|
|
@@ -1923,7 +1923,7 @@ export type QueryDeleteArgs<TName extends TableName> = {
|
|
|
1923
1923
|
where?: WhereInput<TableModel<TName>, TName>;
|
|
1924
1924
|
limit?: number;
|
|
1925
1925
|
};
|
|
1926
|
-
`}function
|
|
1926
|
+
`}function Ce(){return `type AggregateWithInput<TName extends TableName> =
|
|
1927
1927
|
QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1928
1928
|
|
|
1929
1929
|
type NumericFieldKey<TName extends TableName> = NumericModelFieldKey<
|
|
@@ -2055,7 +2055,7 @@ export type DbMutationEvent = {
|
|
|
2055
2055
|
export type QueryDbOptions = {
|
|
2056
2056
|
onMutation?: (event: DbMutationEvent) => void;
|
|
2057
2057
|
};
|
|
2058
|
-
`}function
|
|
2058
|
+
`}function qe(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2059
2059
|
return typeof value === "object" && value !== null;
|
|
2060
2060
|
}
|
|
2061
2061
|
|
|
@@ -3155,7 +3155,7 @@ function inferConflictTarget(table: unknown): string[] {
|
|
|
3155
3155
|
|
|
3156
3156
|
return [];
|
|
3157
3157
|
}
|
|
3158
|
-
`}function
|
|
3158
|
+
`}function Me(){return `const mergedSchema = {
|
|
3159
3159
|
...authSchema,
|
|
3160
3160
|
...schema,
|
|
3161
3161
|
};
|
|
@@ -3430,9 +3430,9 @@ type TableFindFirstResult<
|
|
|
3430
3430
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3431
3431
|
(typeof mergedSchema)[TName]
|
|
3432
3432
|
>;
|
|
3433
|
-
`}function
|
|
3433
|
+
`}function Ie(){return [Me(),$e(),Ce(),qe()].join(`
|
|
3434
3434
|
|
|
3435
|
-
`)}function
|
|
3435
|
+
`)}function Fe(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3436
3436
|
const withValue = args?.with;
|
|
3437
3437
|
const pathSegments = args?.field
|
|
3438
3438
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -3603,7 +3603,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3603
3603
|
},
|
|
3604
3604
|
}) as AppflareQueryDb;
|
|
3605
3605
|
}
|
|
3606
|
-
`}function
|
|
3606
|
+
`}function Pe(){return `export class AppflareHandledError extends Error {
|
|
3607
3607
|
public readonly status: number;
|
|
3608
3608
|
public readonly payload: unknown;
|
|
3609
3609
|
|
|
@@ -3613,7 +3613,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3613
3613
|
this.payload = payload;
|
|
3614
3614
|
}
|
|
3615
3615
|
}
|
|
3616
|
-
`}function
|
|
3616
|
+
`}function Ee(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
3617
3617
|
const where = isRecord(args?.where)
|
|
3618
3618
|
? (args?.where as Record<string, unknown>)
|
|
3619
3619
|
: undefined;
|
|
@@ -3767,7 +3767,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3767
3767
|
);
|
|
3768
3768
|
});
|
|
3769
3769
|
},
|
|
3770
|
-
`}function
|
|
3770
|
+
`}function De(){return `export function createQueryDb(
|
|
3771
3771
|
$db: AppflareDb,
|
|
3772
3772
|
options?: QueryDbOptions,
|
|
3773
3773
|
): AppflareQueryDb {
|
|
@@ -3809,7 +3809,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3809
3809
|
};
|
|
3810
3810
|
|
|
3811
3811
|
const tableApi = {
|
|
3812
|
-
`}function
|
|
3812
|
+
`}function Oe(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
3813
3813
|
const transaction = ($db as any).transaction;
|
|
3814
3814
|
|
|
3815
3815
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -4503,9 +4503,9 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4503
4503
|
);
|
|
4504
4504
|
return rows;
|
|
4505
4505
|
},
|
|
4506
|
-
`}function
|
|
4506
|
+
`}function je(){return [De(),Ee(),Oe(),Fe(),Pe()].join(`
|
|
4507
4507
|
|
|
4508
|
-
`)}function
|
|
4508
|
+
`)}function Be(){return `type AuthSession = typeof auth.$Infer.Session;
|
|
4509
4509
|
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
4510
4510
|
type User = AuthSession['user']
|
|
4511
4511
|
type Session = AuthSession['session']
|
|
@@ -4594,7 +4594,7 @@ export type AppflareContext = {
|
|
|
4594
4594
|
storage: AppflareStorage;
|
|
4595
4595
|
error: (status: number, message: string, details?: unknown) => never;
|
|
4596
4596
|
};
|
|
4597
|
-
`}function
|
|
4597
|
+
`}function Ve(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
4598
4598
|
|
|
4599
4599
|
export type SchedulerEnqueueOptions = {
|
|
4600
4600
|
delaySeconds?: number;
|
|
@@ -4726,20 +4726,20 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
4726
4726
|
definition,
|
|
4727
4727
|
};
|
|
4728
4728
|
}
|
|
4729
|
-
`}function
|
|
4729
|
+
`}function We(){return [Ne(),Ie(),je(),Be(),Ve()].join(`
|
|
4730
4730
|
|
|
4731
|
-
`)}function
|
|
4731
|
+
`)}function He(e){return `import type { Context } from "hono";
|
|
4732
4732
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
4733
4733
|
import { drizzle } from "drizzle-orm/d1";
|
|
4734
4734
|
import { z, type ZodRawShape } from "zod";
|
|
4735
4735
|
import * as authSchema from "./auth.schema";
|
|
4736
4736
|
import * as schema from "${e}";
|
|
4737
4737
|
|
|
4738
|
-
${
|
|
4739
|
-
`}function
|
|
4740
|
-
`)}function
|
|
4741
|
-
`)}function
|
|
4742
|
-
`)}function
|
|
4738
|
+
${We()}
|
|
4739
|
+
`}function Qn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function _n(e,t){let n=e.routePath.replace(/^\//,"").replace(/\//g,"_");return Qn(`op_${t}_${n}`)}function Kn(e){return e.map((t,n)=>({operation:t,index:n,alias:_n(t,n)}))}function Gn(e){return e.map(({operation:t,alias:n})=>`import { ${t.exportName} as ${n} } from "${t.importPath}";`).join(`
|
|
4740
|
+
`)}function Jn(e){return e.filter(({operation:t})=>t.kind==="query"||t.kind==="mutation").map(({alias:t})=>`const ${`${t}Schema`} = z.object(${t}.definition.args);`).join(`
|
|
4741
|
+
`)}function Zn(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(`
|
|
4742
|
+
`)}function Yn(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
4743
4743
|
app.get(
|
|
4744
4744
|
"${t.routePath}",
|
|
4745
4745
|
sValidator("query", ${r}),
|
|
@@ -4752,7 +4752,7 @@ ${Ee()}
|
|
|
4752
4752
|
}
|
|
4753
4753
|
},
|
|
4754
4754
|
);`}).join(`
|
|
4755
|
-
`)}function
|
|
4755
|
+
`)}function Xn(e){return e.filter(({operation:t})=>t.kind==="mutation").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
4756
4756
|
app.post(
|
|
4757
4757
|
"${t.routePath}",
|
|
4758
4758
|
sValidator("json", ${r}),
|
|
@@ -4767,26 +4767,26 @@ ${Ee()}
|
|
|
4767
4767
|
}
|
|
4768
4768
|
},
|
|
4769
4769
|
);`}).join(`
|
|
4770
|
-
`)}function
|
|
4770
|
+
`)}function er(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`,a=t.handlerName??t.routePath;return `
|
|
4771
4771
|
${JSON.stringify(a)}: {
|
|
4772
4772
|
definition: ${n}.definition,
|
|
4773
4773
|
schema: ${r},
|
|
4774
4774
|
},`}).join(`
|
|
4775
|
-
`)}function
|
|
4775
|
+
`)}function tr(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=`${n}SchedulerSchema`,a=t.taskName??`${t.routePath}`;return `
|
|
4776
4776
|
${JSON.stringify(a)}: {
|
|
4777
4777
|
definition: ${n}.definition,
|
|
4778
4778
|
schema: ${r},
|
|
4779
4779
|
},`}).join(`
|
|
4780
|
-
`)}function
|
|
4781
|
-
`)}function
|
|
4780
|
+
`)}function nr(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(`
|
|
4781
|
+
`)}function rr(e){return e.filter(({operation:t})=>t.kind==="cron").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`,a=t.cronTriggers??[];return `
|
|
4782
4782
|
{
|
|
4783
4783
|
taskName: ${JSON.stringify(r)},
|
|
4784
4784
|
cronTriggers: ${JSON.stringify(a)},
|
|
4785
4785
|
definition: ${n}.definition,
|
|
4786
4786
|
},`}).join(`
|
|
4787
|
-
`)}function
|
|
4787
|
+
`)}function ar(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
4788
4788
|
${t}.definition.handler,`).join(`
|
|
4789
|
-
`)}function
|
|
4789
|
+
`)}function ze(e){let t=Kn(e);return {imports:Gn(t),operationSchemas:Jn(t),schedulerSchemas:Zn(t),queryRoutes:Yn(t),mutationRoutes:Xn(t),queryRegistryEntries:er(t),schedulerEntries:tr(t),schedulerPayloadMapEntries:nr(t),cronEntries:rr(t),storageHandlersEntries:ar(t)}}var Le=`
|
|
4790
4790
|
function getRealtimeStub(
|
|
4791
4791
|
env: Record<string, unknown>,
|
|
4792
4792
|
options: RegisterHandlersOptions,
|
|
@@ -4860,7 +4860,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
4860
4860
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
4861
4861
|
return url.toString();
|
|
4862
4862
|
}
|
|
4863
|
-
`;var
|
|
4863
|
+
`;var Ue=`
|
|
4864
4864
|
export class AppflareRealtimeDurableObject {
|
|
4865
4865
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
4866
4866
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -5003,7 +5003,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
5003
5003
|
return new Response("Not found", { status: 404 });
|
|
5004
5004
|
}
|
|
5005
5005
|
}
|
|
5006
|
-
`;var
|
|
5006
|
+
`;var Qe=`
|
|
5007
5007
|
async function publishMutationEvents(
|
|
5008
5008
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
5009
5009
|
options: RegisterHandlersOptions,
|
|
@@ -5104,7 +5104,7 @@ async function publishMutationEvents(
|
|
|
5104
5104
|
}
|
|
5105
5105
|
}
|
|
5106
5106
|
}
|
|
5107
|
-
`;var
|
|
5107
|
+
`;var _e=`
|
|
5108
5108
|
function registerRealtimeRoutes(
|
|
5109
5109
|
app: Hono<WorkerEnv>,
|
|
5110
5110
|
options: RegisterHandlersOptions,
|
|
@@ -5267,7 +5267,7 @@ function registerRealtimeRoutes(
|
|
|
5267
5267
|
return stub.fetch(c.req.raw);
|
|
5268
5268
|
});
|
|
5269
5269
|
}
|
|
5270
|
-
`;var
|
|
5270
|
+
`;var Ke=`
|
|
5271
5271
|
type RealtimeSubscription = {
|
|
5272
5272
|
token: string;
|
|
5273
5273
|
signature: string;
|
|
@@ -5296,7 +5296,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
5296
5296
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
5297
5297
|
? string
|
|
5298
5298
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
5299
|
-
`;var
|
|
5299
|
+
`;var Ge=`
|
|
5300
5300
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5301
5301
|
return typeof value === "object" && value !== null;
|
|
5302
5302
|
}
|
|
@@ -5811,9 +5811,9 @@ function doesSubscriptionMatchMutation(
|
|
|
5811
5811
|
|
|
5812
5812
|
return false;
|
|
5813
5813
|
}
|
|
5814
|
-
`;var
|
|
5814
|
+
`;var Je=[Ke,Ge,Le,Qe,_e,Ue].join(`
|
|
5815
5815
|
|
|
5816
|
-
`);var
|
|
5816
|
+
`);var Ze=`
|
|
5817
5817
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
5818
5818
|
if (!value) {
|
|
5819
5819
|
return undefined;
|
|
@@ -6011,7 +6011,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
6011
6011
|
}
|
|
6012
6012
|
});
|
|
6013
6013
|
}
|
|
6014
|
-
`;var
|
|
6014
|
+
`;var Ye=`
|
|
6015
6015
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
6016
6016
|
? string
|
|
6017
6017
|
: keyof typeof schedulerHandlers;
|
|
@@ -6066,7 +6066,7 @@ export async function executeScheduledBatch(
|
|
|
6066
6066
|
}
|
|
6067
6067
|
}
|
|
6068
6068
|
}
|
|
6069
|
-
`;var
|
|
6069
|
+
`;var Xe=`
|
|
6070
6070
|
export async function executeCronTriggers(
|
|
6071
6071
|
controller: { cron: string },
|
|
6072
6072
|
env: Record<string, unknown>,
|
|
@@ -6091,7 +6091,7 @@ export async function executeCronTriggers(
|
|
|
6091
6091
|
}
|
|
6092
6092
|
}
|
|
6093
6093
|
}
|
|
6094
|
-
`;function
|
|
6094
|
+
`;function et(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:l,cronEntries:u,storageHandlersEntries:c}=ze(e);return `import { sValidator } from "@hono/standard-validator";
|
|
6095
6095
|
import type { Hono } from "hono";
|
|
6096
6096
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6097
6097
|
import { ZodError, z } from "zod";
|
|
@@ -6148,9 +6148,9 @@ const storageHandlers = [${c||`
|
|
|
6148
6148
|
|
|
6149
6149
|
setStorageHandlers([...storageHandlers]);
|
|
6150
6150
|
|
|
6151
|
-
${
|
|
6151
|
+
${Ye}
|
|
6152
6152
|
|
|
6153
|
-
${
|
|
6153
|
+
${Je}
|
|
6154
6154
|
|
|
6155
6155
|
export function registerGeneratedHandlers(
|
|
6156
6156
|
app: Hono<WorkerEnv>,
|
|
@@ -6163,20 +6163,20 @@ export function registerGeneratedHandlers(
|
|
|
6163
6163
|
`}
|
|
6164
6164
|
}
|
|
6165
6165
|
|
|
6166
|
-
${
|
|
6166
|
+
${Ze}
|
|
6167
6167
|
|
|
6168
|
-
${
|
|
6169
|
-
`}function
|
|
6170
|
-
KV: c.env["${e}"] as KVNamespace`:""}function
|
|
6171
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6172
|
-
}`}function
|
|
6168
|
+
${Xe}
|
|
6169
|
+
`}function L(e,t,n){let r=He(e),a=ke(n),o=Ae(),i=et(t);return [{relativePath:"handlers.ts",source:r},{relativePath:"handlers.context.ts",source:a},{relativePath:"handlers.execution.ts",source:o},{relativePath:"handlers.routes.ts",source:i}]}function or(e){return e?`,
|
|
6170
|
+
KV: c.env["${e}"] as KVNamespace`:""}function tt(e,t){return `{
|
|
6171
|
+
DATABASE: c.env["${e}"] as D1Database${or(t)}
|
|
6172
|
+
}`}function nt(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6173
6173
|
const auth = createAuth(
|
|
6174
|
-
${
|
|
6174
|
+
${tt(t,n)},
|
|
6175
6175
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
6176
6176
|
);
|
|
6177
6177
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6178
6178
|
});
|
|
6179
|
-
`}function
|
|
6179
|
+
`}function ir(){return `export const getHeaders = (headers: Headers) => {
|
|
6180
6180
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6181
6181
|
const headerObject: Record<string, any> = {};
|
|
6182
6182
|
let hasCookie = false;
|
|
@@ -6206,15 +6206,15 @@ ${_e}
|
|
|
6206
6206
|
|
|
6207
6207
|
return headerObject as any as Headers;
|
|
6208
6208
|
};
|
|
6209
|
-
`}function
|
|
6209
|
+
`}function sr(){return `export const getSanitizedRequest = (req: Request) => {
|
|
6210
6210
|
const newRequest = new Request(req, {
|
|
6211
6211
|
headers: getHeaders(req.headers),
|
|
6212
6212
|
});
|
|
6213
6213
|
return newRequest;
|
|
6214
6214
|
};
|
|
6215
|
-
`}function
|
|
6216
|
-
`+
|
|
6217
|
-
`+
|
|
6215
|
+
`}function rt(){return ir()+`
|
|
6216
|
+
`+sr()}function at(e,t,n){return nt(e,t,n)+`
|
|
6217
|
+
`+rt()}function ot(){return `const app = new Hono<WorkerEnv>();
|
|
6218
6218
|
|
|
6219
6219
|
app.use('*', cors({
|
|
6220
6220
|
origin: (origin, c) => {
|
|
@@ -6230,7 +6230,7 @@ app.use('*', cors({
|
|
|
6230
6230
|
},
|
|
6231
6231
|
credentials: true
|
|
6232
6232
|
}));
|
|
6233
|
-
`}function
|
|
6233
|
+
`}function it(){return `export { AppflareRealtimeDurableObject };
|
|
6234
6234
|
|
|
6235
6235
|
export default {
|
|
6236
6236
|
fetch: app.fetch,
|
|
@@ -6241,7 +6241,7 @@ export default {
|
|
|
6241
6241
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
6242
6242
|
},
|
|
6243
6243
|
};
|
|
6244
|
-
`}function
|
|
6244
|
+
`}function st(e,t,n="APPFLARE_SCHEDULER_QUEUE",r,a="APPFLARE_REALTIME",o="global",i="/realtime/subscribe",s="/realtime/ws",l="appflare.realtime.v1"){let u=t?`
|
|
6245
6245
|
kvBinding: "${t}",`:"",c=r?`
|
|
6246
6246
|
r2Binding: "${r}",`:"",f=`
|
|
6247
6247
|
realtimeBinding: "${a}",
|
|
@@ -6255,16 +6255,16 @@ export default {
|
|
|
6255
6255
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6256
6256
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
6257
6257
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
6258
|
-
`}function
|
|
6258
|
+
`}function lt(){return `import { createAuth } from "./auth.config";
|
|
6259
6259
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
6260
6260
|
import { registerAdminDashboard } from "./admin.routes";
|
|
6261
6261
|
import { Hono } from "hono";
|
|
6262
6262
|
import { cors } from "hono/cors";
|
|
6263
6263
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6264
|
-
`}function
|
|
6264
|
+
`}function ct(){return `type WorkerEnv = {
|
|
6265
6265
|
Bindings: Record<string, unknown>;
|
|
6266
6266
|
};
|
|
6267
|
-
`}function
|
|
6267
|
+
`}function ut(e,t,n,r,a,o,i,s,l,u){return lt()+ct()+ot()+st(t,n,r,a,o,i,s,l,u)+at(e,t,n)+it()}function dt(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function U(e,t){let n={...e};for(let[r,a]of Object.entries(t)){let o=n[r];if(dt(o)&&dt(a)){n[r]=U(o,a);continue}n[r]=a;}return n}function lr(e){return Array.from(new Set(e.filter(t=>t.length>0)))}function pt(e,t){let n=t.filter(d=>d.kind==="scheduler"||d.kind==="cron"),r=lr(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",l=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:l}],consumers:[{queue:l}]}}:{},...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:c,...f}=e.config.wranglerOverrides;return U(u,f)}function mt(e){return e.tables.map(t=>({exportName:t.exportName,tableName:t.tableName,columns:t.columns.map(n=>n.name)}))}function gt(e){return `<li data-name="users">
|
|
6268
6268
|
<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">
|
|
6269
6269
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6270
6270
|
<span class="truncate">users</span>
|
|
@@ -6276,7 +6276,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6276
6276
|
<span class="truncate">${n.tableName}</span>
|
|
6277
6277
|
</a>
|
|
6278
6278
|
</li>`).join(`
|
|
6279
|
-
`)}`}function
|
|
6279
|
+
`)}`}function ft(e){let t=e.filter(o=>o.kind==="query"),n=e.filter(o=>o.kind==="mutation"),r=t.map(o=>`
|
|
6280
6280
|
<li data-name="${o.exportName}">
|
|
6281
6281
|
<a href="/admin/functions${o.routePath}" hx-get="/admin/functions${o.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">
|
|
6282
6282
|
<iconify-icon icon="solar:reorder-linear" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
@@ -6310,7 +6310,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6310
6310
|
<ul class="flex flex-col gap-0.5">${a}</ul>`:""}
|
|
6311
6311
|
</nav>
|
|
6312
6312
|
</div>
|
|
6313
|
-
`}function
|
|
6313
|
+
`}function ht(e){return e.map(t=>`
|
|
6314
6314
|
<a
|
|
6315
6315
|
href="/admin/table/${t.exportName}"
|
|
6316
6316
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
@@ -6327,9 +6327,9 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6327
6327
|
</div>
|
|
6328
6328
|
</div>
|
|
6329
6329
|
</a>
|
|
6330
|
-
`.replace(/\n/g,"\\n")).join("")}function
|
|
6330
|
+
`.replace(/\n/g,"\\n")).join("")}function yt(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
6331
6331
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6332
|
-
`).join("")}function
|
|
6332
|
+
`).join("")}function cr(e){switch(e){case "number":return "mdi:pound";case "boolean":return "mdi:toggle-switch-outline";case "date":return "mdi:calendar";default:return "mdi:format-text"}}function bt(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n),a=r?cr(r.type):"mdi:format-text";return `
|
|
6333
6333
|
<th>
|
|
6334
6334
|
<a href="#"
|
|
6335
6335
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -6341,7 +6341,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6341
6341
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6342
6342
|
</a>
|
|
6343
6343
|
</th>
|
|
6344
|
-
`}).join("")}function
|
|
6344
|
+
`}).join("")}function wt(e,t){return e.map(n=>t&&n===t?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${n} ?? '')}" data-copy-value="\${String((row as any).${n} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${n} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${n} ?? '')}">\${String((row as any).${n} ?? '')}</div></td>`).join("")}function Q(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"?`
|
|
6345
6345
|
<div class="form-control">
|
|
6346
6346
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6347
6347
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6379,7 +6379,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6379
6379
|
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6380
6380
|
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm"${a} />
|
|
6381
6381
|
</div>
|
|
6382
|
-
`}function
|
|
6382
|
+
`}function _(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n);if(!r)return "";let a=r.optional?"":`
|
|
6383
6383
|
if (raw_${n} === '') {
|
|
6384
6384
|
return c.text('${n} is required', 400);
|
|
6385
6385
|
}
|
|
@@ -6424,7 +6424,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6424
6424
|
payload.${n} = raw_${n};
|
|
6425
6425
|
}
|
|
6426
6426
|
`}).join(`
|
|
6427
|
-
`)}function
|
|
6427
|
+
`)}function xt(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function Tt(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function vt(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function Rt(e,t,n,r){return t?`<td class="text-right">
|
|
6428
6428
|
<div class="drawer drawer-end">
|
|
6429
6429
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6430
6430
|
<div class="drawer-content">
|
|
@@ -6477,7 +6477,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6477
6477
|
</div>
|
|
6478
6478
|
</div>
|
|
6479
6479
|
</div>
|
|
6480
|
-
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function
|
|
6480
|
+
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function F(e){return `
|
|
6481
6481
|
<div class="flex flex-col sm:flex-row justify-between items-center mt-4 gap-3 py-3 px-1">
|
|
6482
6482
|
<div class="text-xs text-base-content/40">
|
|
6483
6483
|
Total found: <span class="font-medium text-base-content/60">\${total}</span>
|
|
@@ -6499,7 +6499,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6499
6499
|
\` : 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>\`}
|
|
6500
6500
|
</div>
|
|
6501
6501
|
\` : ''}
|
|
6502
|
-
</div>`}function
|
|
6502
|
+
</div>`}function P(e,t="Search term or filter..."){return `
|
|
6503
6503
|
<div class="form-control w-full md:w-auto relative">
|
|
6504
6504
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
6505
6505
|
<input type="text"
|
|
@@ -6510,7 +6510,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6510
6510
|
hx-trigger="keyup changed delay:500ms, search"
|
|
6511
6511
|
hx-target="#main-content"
|
|
6512
6512
|
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" />
|
|
6513
|
-
</div>`}function
|
|
6513
|
+
</div>`}function kt(e,t,n,r,a,o,i,s,l,u){let c=F(`/admin/table/${e.exportName}`),f=P(`/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>',b=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>',w=r?`
|
|
6514
6514
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
6515
6515
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
6516
6516
|
<div class="text-xs text-base-content/70">
|
|
@@ -6762,7 +6762,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6762
6762
|
title: "${e.tableName} - Admin Dashboard",
|
|
6763
6763
|
children: content
|
|
6764
6764
|
}));
|
|
6765
|
-
});`}function
|
|
6765
|
+
});`}function St(e,t,n,r,a,o,i,s){let l=r==="number"?`
|
|
6766
6766
|
const parsedId = Number(rawId);
|
|
6767
6767
|
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
6768
6768
|
idValue = parsedId;
|
|
@@ -6895,15 +6895,15 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6895
6895
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
6896
6896
|
});
|
|
6897
6897
|
${c}
|
|
6898
|
-
`}function
|
|
6899
|
-
`+
|
|
6898
|
+
`}function K(e){let t=xt(e),n=!!t,r=e.columns.map(m=>m.name),a=r.filter(m=>Tt(e,m)),o=r.filter(m=>vt(e,m)),i=yt(e),s=bt(e,r),l=wt(r,t),u=a.map(m=>Q(e,m,"create")).join(""),c=o.map(m=>Q(e,m,"edit")).join(""),f=_(e,a),d=_(e,o),b=n?t:r[0]||"id",w=e.columns.find(m=>m.name===t)?.type,y=Rt(e,n,t,c);return kt(e,b,t,n,r,i,s,l,y,u)+`
|
|
6899
|
+
`+St(e.exportName,b,t,w,n,i,f,d)}function At(){return `
|
|
6900
6900
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
6901
6901
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
6902
6902
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
6903
6903
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
6904
6904
|
const search = params.search ? params.search : '';
|
|
6905
6905
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
6906
|
-
};`}function
|
|
6906
|
+
};`}function Nt(){return `
|
|
6907
6907
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6908
6908
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6909
6909
|
<div class="modal">
|
|
@@ -6924,7 +6924,7 @@ ${c}
|
|
|
6924
6924
|
</div>
|
|
6925
6925
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
6926
6926
|
</div>
|
|
6927
|
-
\`}`}function
|
|
6927
|
+
\`}`}function $t(){return `
|
|
6928
6928
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6929
6929
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6930
6930
|
<div class="modal">
|
|
@@ -6945,8 +6945,8 @@ ${c}
|
|
|
6945
6945
|
</div>
|
|
6946
6946
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
6947
6947
|
</div>
|
|
6948
|
-
\`}`}var
|
|
6949
|
-
`),t=
|
|
6948
|
+
\`}`}var ur=["id","name","email","role","createdAt","banned"],dr={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function pr(e){let t=dr[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 Ct(){let e=ur.map(pr).join(`
|
|
6949
|
+
`),t=F("/admin/users");return `
|
|
6950
6950
|
const tableHtml = html\`
|
|
6951
6951
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
6952
6952
|
<div class="overflow-x-auto">
|
|
@@ -7014,8 +7014,8 @@ ${c}
|
|
|
7014
7014
|
</div>
|
|
7015
7015
|
</div>
|
|
7016
7016
|
</div>
|
|
7017
|
-
${
|
|
7018
|
-
${
|
|
7017
|
+
${Nt()}
|
|
7018
|
+
${$t()}
|
|
7019
7019
|
</td>
|
|
7020
7020
|
</tr>
|
|
7021
7021
|
\`)}
|
|
@@ -7031,7 +7031,7 @@ ${vt()}
|
|
|
7031
7031
|
${t}
|
|
7032
7032
|
</div>
|
|
7033
7033
|
\`;
|
|
7034
|
-
`}function
|
|
7034
|
+
`}function qt(){return `
|
|
7035
7035
|
const content = html\`
|
|
7036
7036
|
<div id="main-content">
|
|
7037
7037
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -7043,11 +7043,11 @@ ${vt()}
|
|
|
7043
7043
|
<iconify-icon icon="mdi:refresh" width="14" height="14"></iconify-icon>
|
|
7044
7044
|
</button>
|
|
7045
7045
|
</div>
|
|
7046
|
-
${
|
|
7046
|
+
${P("/admin/users","Search users...")}
|
|
7047
7047
|
</div>
|
|
7048
7048
|
\${tableHtml}
|
|
7049
7049
|
</div>
|
|
7050
|
-
\`;`}function
|
|
7050
|
+
\`;`}function Mt(){let e=Ct(),t=qt();return `
|
|
7051
7051
|
adminApp.get('/users', async (c) => {
|
|
7052
7052
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
7053
7053
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7103,7 +7103,7 @@ ${vt()}
|
|
|
7103
7103
|
title: "users - Admin Dashboard",
|
|
7104
7104
|
children: content,
|
|
7105
7105
|
}));
|
|
7106
|
-
});`}function
|
|
7106
|
+
});`}function It(){return `
|
|
7107
7107
|
adminApp.post('/users/edit', async (c) => {
|
|
7108
7108
|
const session = await requireAdminSession(c);
|
|
7109
7109
|
if (!session) {
|
|
@@ -7246,8 +7246,8 @@ ${vt()}
|
|
|
7246
7246
|
const resolvedPage = String(Math.min(nextPageCandidate, totalPages));
|
|
7247
7247
|
|
|
7248
7248
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7249
|
-
});`}function
|
|
7250
|
-
${
|
|
7249
|
+
});`}function G(){return `
|
|
7250
|
+
${At()}
|
|
7251
7251
|
|
|
7252
7252
|
const requireAdminSession = async (c: any) => {
|
|
7253
7253
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7258,12 +7258,12 @@ ${vt()}
|
|
|
7258
7258
|
return session;
|
|
7259
7259
|
};
|
|
7260
7260
|
|
|
7261
|
-
${
|
|
7261
|
+
${Mt()}
|
|
7262
7262
|
|
|
7263
|
-
${
|
|
7264
|
-
`}function
|
|
7263
|
+
${It()}
|
|
7264
|
+
`}function Ft(e){return `${e.tables.map(t=>K(t)).join(`
|
|
7265
7265
|
`)}
|
|
7266
|
-
${
|
|
7266
|
+
${G()}`}function Pt(e){return `
|
|
7267
7267
|
<div class="flex items-center justify-between">
|
|
7268
7268
|
<div class="flex items-center gap-3">
|
|
7269
7269
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -7278,9 +7278,9 @@ ${Q()}`}function $t(e){return `
|
|
|
7278
7278
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
7279
7279
|
</div>
|
|
7280
7280
|
</div>
|
|
7281
|
-
`}function
|
|
7281
|
+
`}function mr(e){return e==="boolean"?"checkbox":e==="number"?"number":"text"}function gr(e){let t=e.args??[];return t.length===0?`
|
|
7282
7282
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
7283
|
-
`:t.map(n=>{let r=
|
|
7283
|
+
`:t.map(n=>{let r=mr(n.type),a=r==="checkbox",o=`${n.name}${n.optional?"":" *"}`,i=n.type!=="unknown"?`<span class="badge badge-xs badge-ghost font-mono opacity-40 ml-1">${n.type}</span>`:"";return a?`
|
|
7284
7284
|
<div class="flex items-center gap-3 py-1">
|
|
7285
7285
|
<input
|
|
7286
7286
|
type="checkbox"
|
|
@@ -7309,7 +7309,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7309
7309
|
/>
|
|
7310
7310
|
</div>
|
|
7311
7311
|
`}).join(`
|
|
7312
|
-
`)}function
|
|
7312
|
+
`)}function fr(e){return `
|
|
7313
7313
|
<div class="space-y-4">
|
|
7314
7314
|
<div class="flex items-center justify-between">
|
|
7315
7315
|
<div class="flex flex-col">
|
|
@@ -7322,11 +7322,11 @@ ${Q()}`}function $t(e){return `
|
|
|
7322
7322
|
</label>
|
|
7323
7323
|
</div>
|
|
7324
7324
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
7325
|
-
${
|
|
7325
|
+
${gr(e)}
|
|
7326
7326
|
</div>
|
|
7327
7327
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7328
7328
|
</div>
|
|
7329
|
-
`}function
|
|
7329
|
+
`}function hr(){return `
|
|
7330
7330
|
<div class="space-y-4">
|
|
7331
7331
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7332
7332
|
<div class="relative group">
|
|
@@ -7343,7 +7343,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7343
7343
|
</div>
|
|
7344
7344
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
7345
7345
|
</div>
|
|
7346
|
-
`}function
|
|
7346
|
+
`}function yr(){return `
|
|
7347
7347
|
<div class="space-y-4">
|
|
7348
7348
|
<div class="flex items-center justify-between">
|
|
7349
7349
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -7357,7 +7357,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7357
7357
|
</div>
|
|
7358
7358
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
7359
7359
|
</div>
|
|
7360
|
-
`}function
|
|
7360
|
+
`}function Et(e){return `
|
|
7361
7361
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
7362
7362
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
7363
7363
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -7378,13 +7378,13 @@ ${Q()}`}function $t(e){return `
|
|
|
7378
7378
|
<!-- Tab Content -->
|
|
7379
7379
|
<div class="flex-1 overflow-y-auto">
|
|
7380
7380
|
<div id="request-tab-args" class="p-5">
|
|
7381
|
-
${
|
|
7381
|
+
${fr(e)}
|
|
7382
7382
|
</div>
|
|
7383
7383
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
7384
|
-
${
|
|
7384
|
+
${hr()}
|
|
7385
7385
|
</div>
|
|
7386
7386
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
7387
|
-
${
|
|
7387
|
+
${yr()}
|
|
7388
7388
|
</div>
|
|
7389
7389
|
</div>
|
|
7390
7390
|
|
|
@@ -7402,7 +7402,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7402
7402
|
</form>
|
|
7403
7403
|
</div>
|
|
7404
7404
|
</div>
|
|
7405
|
-
`}function
|
|
7405
|
+
`}function Dt(){return `
|
|
7406
7406
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
7407
7407
|
<!-- Panel Header -->
|
|
7408
7408
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -7484,7 +7484,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7484
7484
|
|
|
7485
7485
|
</div>
|
|
7486
7486
|
</div>
|
|
7487
|
-
`}function
|
|
7487
|
+
`}function Ot(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
7488
7488
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
7489
7489
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
7490
7490
|
|
|
@@ -8026,21 +8026,21 @@ ${Q()}`}function $t(e){return `
|
|
|
8026
8026
|
_rtEnabled = false;
|
|
8027
8027
|
});
|
|
8028
8028
|
</script>
|
|
8029
|
-
`}function
|
|
8029
|
+
`}function jt(e){return `
|
|
8030
8030
|
const content = html\`
|
|
8031
8031
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
8032
|
-
${
|
|
8032
|
+
${Pt(e)}
|
|
8033
8033
|
|
|
8034
8034
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
8035
8035
|
<!-- Request Panel -->
|
|
8036
|
-
${
|
|
8036
|
+
${Et(e)}
|
|
8037
8037
|
|
|
8038
8038
|
<!-- Result Panel -->
|
|
8039
|
-
${
|
|
8039
|
+
${Dt()}
|
|
8040
8040
|
</div>
|
|
8041
8041
|
</div>
|
|
8042
8042
|
|
|
8043
|
-
${
|
|
8043
|
+
${Ot(e)}
|
|
8044
8044
|
\`;
|
|
8045
8045
|
|
|
8046
8046
|
if (c.req.header('hx-request')) {
|
|
@@ -8050,11 +8050,11 @@ ${Q()}`}function $t(e){return `
|
|
|
8050
8050
|
return c.html(Layout({
|
|
8051
8051
|
title: "${e.exportName} - Functions",
|
|
8052
8052
|
children: content
|
|
8053
|
-
}));`}function
|
|
8053
|
+
}));`}function Bt(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
8054
8054
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
8055
|
-
${
|
|
8055
|
+
${jt(n)}
|
|
8056
8056
|
});`).join(`
|
|
8057
|
-
`)}function
|
|
8057
|
+
`)}function Vt(){return `
|
|
8058
8058
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
8059
8059
|
const r2Binding = (options as any).r2Binding;
|
|
8060
8060
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -8123,7 +8123,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8123
8123
|
const parts = prefix.split('/').filter(Boolean);
|
|
8124
8124
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
8125
8125
|
};
|
|
8126
|
-
`}function
|
|
8126
|
+
`}function Wt(){return `
|
|
8127
8127
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
8128
8128
|
const parts = prefix.split('/').filter(Boolean);
|
|
8129
8129
|
const breadcrumbs: any[] = [];
|
|
@@ -8250,7 +8250,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8250
8250
|
</div>
|
|
8251
8251
|
\`;
|
|
8252
8252
|
};
|
|
8253
|
-
`}function
|
|
8253
|
+
`}function Ht(){return `
|
|
8254
8254
|
const handleStorageListRoute = async (c: any) => {
|
|
8255
8255
|
const bucket = getStorageBucket(c);
|
|
8256
8256
|
if (!bucket) {
|
|
@@ -8272,7 +8272,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8272
8272
|
|
|
8273
8273
|
adminApp.get('/storage', handleStorageListRoute);
|
|
8274
8274
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
8275
|
-
`}function
|
|
8275
|
+
`}function zt(){return `
|
|
8276
8276
|
adminApp.post('/storage/upload', async (c) => {
|
|
8277
8277
|
const bucket = getStorageBucket(c);
|
|
8278
8278
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8290,7 +8290,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8290
8290
|
|
|
8291
8291
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8292
8292
|
});
|
|
8293
|
-
`}function
|
|
8293
|
+
`}function Lt(){return `
|
|
8294
8294
|
adminApp.delete('/storage/delete', async (c) => {
|
|
8295
8295
|
const bucket = getStorageBucket(c);
|
|
8296
8296
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8305,7 +8305,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8305
8305
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
8306
8306
|
return c.html('');
|
|
8307
8307
|
});
|
|
8308
|
-
`}function
|
|
8308
|
+
`}function Ut(){return `
|
|
8309
8309
|
adminApp.post('/storage/directory', async (c) => {
|
|
8310
8310
|
const bucket = getStorageBucket(c);
|
|
8311
8311
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8331,7 +8331,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8331
8331
|
|
|
8332
8332
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8333
8333
|
});
|
|
8334
|
-
`}function
|
|
8334
|
+
`}function Qt(){return `
|
|
8335
8335
|
adminApp.get('/storage/download', async (c) => {
|
|
8336
8336
|
const bucket = getStorageBucket(c);
|
|
8337
8337
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8351,7 +8351,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8351
8351
|
|
|
8352
8352
|
return new Response(object.body, { headers });
|
|
8353
8353
|
});
|
|
8354
|
-
`}function
|
|
8354
|
+
`}function _t(){return `
|
|
8355
8355
|
adminApp.get('/storage/preview', async (c) => {
|
|
8356
8356
|
const bucket = getStorageBucket(c);
|
|
8357
8357
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8369,25 +8369,25 @@ ${Q()}`}function $t(e){return `
|
|
|
8369
8369
|
|
|
8370
8370
|
return new Response(object.body, { headers });
|
|
8371
8371
|
});
|
|
8372
|
-
`}function
|
|
8373
|
-
${
|
|
8372
|
+
`}function Kt(){return `
|
|
8373
|
+
${Qt()}
|
|
8374
8374
|
|
|
8375
|
-
${
|
|
8375
|
+
${_t()}
|
|
8376
8376
|
|
|
8377
|
-
${
|
|
8377
|
+
${zt()}
|
|
8378
8378
|
|
|
8379
|
-
${
|
|
8379
|
+
${Lt()}
|
|
8380
8380
|
|
|
8381
|
-
${
|
|
8381
|
+
${Ut()}
|
|
8382
8382
|
|
|
8383
|
-
${
|
|
8384
|
-
`}function
|
|
8385
|
-
${
|
|
8383
|
+
${Ht()}
|
|
8384
|
+
`}function Gt(){return `
|
|
8385
|
+
${Vt()}
|
|
8386
8386
|
|
|
8387
|
-
${
|
|
8387
|
+
${Wt()}
|
|
8388
8388
|
|
|
8389
|
-
${
|
|
8390
|
-
`}function
|
|
8389
|
+
${Kt()}
|
|
8390
|
+
`}function Jt(e,t){let n=ft(t);return `
|
|
8391
8391
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
8392
8392
|
return html\`<!DOCTYPE html>
|
|
8393
8393
|
<html lang="en" data-theme="light">
|
|
@@ -8762,7 +8762,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8762
8762
|
</body>
|
|
8763
8763
|
</html>\`;
|
|
8764
8764
|
}
|
|
8765
|
-
`}function
|
|
8765
|
+
`}function Zt(){return `
|
|
8766
8766
|
// Auth Middleware
|
|
8767
8767
|
adminApp.use('*', async (c, next) => {
|
|
8768
8768
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -8821,7 +8821,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8821
8821
|
}
|
|
8822
8822
|
await next();
|
|
8823
8823
|
});
|
|
8824
|
-
`}function
|
|
8824
|
+
`}function Yt(e){return `
|
|
8825
8825
|
adminApp.get('/', (c) => {
|
|
8826
8826
|
return c.html(Layout({
|
|
8827
8827
|
title: "Admin Dashboard",
|
|
@@ -8838,7 +8838,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8838
8838
|
\`
|
|
8839
8839
|
}));
|
|
8840
8840
|
});
|
|
8841
|
-
`}function
|
|
8841
|
+
`}function Xt(e,t,n){let r=mt(t),a=gt(r),o=ht(r),i=Ft(t),s=Bt(n),l=Gt(),u=Jt(a,n),c=Zt(),f=Yt(o);return `import { Hono } from "hono";
|
|
8842
8842
|
import { html, raw } from "hono/html";
|
|
8843
8843
|
import { drizzle } from "drizzle-orm/d1";
|
|
8844
8844
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -8867,8 +8867,8 @@ ${f}
|
|
|
8867
8867
|
app.route('/admin', adminApp);
|
|
8868
8868
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
8869
8869
|
}
|
|
8870
|
-
`}function
|
|
8871
|
-
`}function
|
|
8870
|
+
`}function J(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"}function E(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function O(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(t,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(t,n)=>n.toUpperCase())}function X(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 h(e){return JSON.stringify(e)}function wr(e){if(typeof e=="string")return h(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return "null";if(e instanceof Date)return h(e.toISOString());throw new Error(`Unsupported SQL default value '${String(e)}'. Use string, number, boolean, null, or Date.`)}function xr(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}]))}]))}}function D(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function en(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 tn(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 nn(e,t){return `${e}:${t}`}function Tr(e,t,n,r){let a=nn(e,t),o=nn(n,r);return a<=o?{key:`${a}|${o}`,leftTable:e,leftReferenceField:t,rightTable:n,rightReferenceField:r,sourceIsLeft:true}:{key:`${o}|${a}`,leftTable:n,leftReferenceField:r,rightTable:e,rightReferenceField:t,sourceIsLeft:false}}function vr(e,t){return `${e}${O(t)}Links`}function rn(e,t,n){let r=X(e),a=X(t);return r===a?`${n}${O(r)}Id`:`${r}Id`}function Rr(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 kr(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=Tr(n,o,a.targetTable,i),l=rn(s.leftTable,s.rightTable,"source"),u=rn(s.rightTable,s.leftTable,"target"),c={leftTable:s.leftTable,leftReferenceField:s.leftReferenceField,rightTable:s.rightTable,rightReferenceField:s.rightReferenceField,junctionTable:a.junctionTable??vr(s.leftTable,s.rightTable),leftField:s.sourceIsLeft?a.sourceField??l:a.targetField??l,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(c.leftField===c.rightField)throw new Error(`manyToMany pair '${s.key}' resolves to duplicate junction fields '${c.leftField}'. Set sourceField/targetField explicitly.`);let f=t.get(s.key);f?Rr(f,c,s.key):t.set(s.key,c),a.referenceField=o,a.targetReferenceField=i,a.junctionTable=c.junctionTable,a.sourceField=s.sourceIsLeft?c.leftField:c.rightField,a.targetField=s.sourceIsLeft?c.rightField:c.leftField,a.sourceSqlName=s.sourceIsLeft?c.leftSqlName:c.rightSqlName,a.targetSqlName=s.sourceIsLeft?c.rightSqlName:c.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=D(e,n.leftTable,n.leftReferenceField)??"string",a=D(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 Sr(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 Ar(e){Sr(e);let t=xr(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 l=D(t,o.targetTable,i)??o.fkType??"string";en(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:tn(`${n}.${a}`,o,true),onDelete:o.onDelete,onUpdate:o.onUpdate},l);}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??`${X(n)}Id`;a.field=s;let l=D(t,n,i)??a.fkType??"string";en(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:tn(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},l);}return kr(t),t}function on(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function C(e){return e.notNull!==true}function Nr(e,t,n){let r=t.sqlName??E(e),a=r!==e;return t.type==="int"?a?`t.int(${h(r)})`:"t.int()":t.type==="string"?t.length!==void 0?a?`t.text(${h(r)}, { length: ${t.length} })`:`t.text({ length: ${t.length} })`:a?`t.text(${h(r)})`:"t.text()":t.type==="boolean"?a?`t.int(${h(r)}, { mode: "boolean" })`:'t.int({ mode: "boolean" })':t.type==="date"?a?`t.int(${h(r)}, { mode: "timestamp_ms" })`:'t.int({ mode: "timestamp_ms" })':n==="camelToSnake"&&a?`t.text(${h(r)})`:"t.text()"}function $r(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 Cr(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
8871
|
+
`}function qr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function Mr(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 Ir(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(`${h(o)}: {
|
|
8872
8872
|
targetTable: ${h(i.targetTable)},
|
|
8873
8873
|
junctionTable: ${h(i.junctionTable)},
|
|
8874
8874
|
sourceField: ${h(i.sourceField??"")},
|
|
@@ -8881,7 +8881,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8881
8881
|
${t.map(n=>` ${n}`).join(`
|
|
8882
8882
|
`)}
|
|
8883
8883
|
} as const;
|
|
8884
|
-
`}function
|
|
8884
|
+
`}function Fr(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(`${h(o)}: {
|
|
8885
8885
|
kind: "one",
|
|
8886
8886
|
targetTable: ${h(i.targetTable)},
|
|
8887
8887
|
sourceField: ${h(i.field??"")},
|
|
@@ -8907,7 +8907,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8907
8907
|
${t.map(n=>` ${n}`).join(`
|
|
8908
8908
|
`)}
|
|
8909
8909
|
} as const;
|
|
8910
|
-
`}function
|
|
8910
|
+
`}function Pr(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let i of Object.values(e.tables)){for(let s of qr(i))n.has(s)||r.add(s);for(let s of Object.values(i.columns))s.references&&!n.has(s.references.table)&&r.add(s.references.table);}let a=[],o=[];for(let[i,s]of Object.entries(e.tables)){let l=s.sqlName??E(i),u=[],c=[];for(let[y,m]of Object.entries(s.columns)){let x=Nr(y,m,t);m.uuidPrimaryKey&&(x+=".$defaultFn(() => crypto.randomUUID())"),m.primaryKey&&(x+=m.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),m.notNull&&(x+=".notNull()"),m.sqlDefault!==void 0&&(x+=`.default(${wr(m.sqlDefault)})`);let R=Mr(y,m,s);if(R)if(m.references?.onDelete||m.references?.onUpdate){let k=[];m.references.onDelete&&k.push(`onDelete: ${h(m.references.onDelete)}`),m.references.onUpdate&&k.push(`onUpdate: ${h(m.references.onUpdate)}`),x+=`.references(() => ${R.tableName}.${R.fieldName}, { ${k.join(", ")} })`;}else x+=`.references(() => ${R.tableName}.${R.fieldName})`;if(m.unique){let k=typeof m.unique=="object"&&m.unique.name?m.unique.name:`${l}_${E(y)}_unique_idx`;c.push(` t.uniqueIndex(${h(k)}).on(table.${y})`);}if(m.index){let k=typeof m.index=="object"&&m.index.name?m.index.name:`${l}_${E(y)}_idx`;c.push(` t.index(${h(k)}).on(table.${y})`);}u.push(` ${y}: ${x},`);}c.length>0?a.push(`export const ${i} = table(
|
|
8911
8911
|
${h(l)},
|
|
8912
8912
|
{
|
|
8913
8913
|
${u.join(`
|
|
@@ -8920,7 +8920,7 @@ ${c.join(`,
|
|
|
8920
8920
|
);`):a.push(`export const ${i} = table(${h(l)}, {
|
|
8921
8921
|
${u.join(`
|
|
8922
8922
|
`)}
|
|
8923
|
-
});`);let f=Object.entries(s.relations).filter(([,y])=>y.relation==="one"),d=Object.entries(s.relations).filter(([,y])=>y.relation==="many"),b=Object.entries(s.relations).filter(([,y])=>y.relation==="manyToMany");if(f.length===0&&d.length===0&&b.length===0)continue;let w=[];for(let[y,m]of f){let x
|
|
8923
|
+
});`);let f=Object.entries(s.relations).filter(([,y])=>y.relation==="one"),d=Object.entries(s.relations).filter(([,y])=>y.relation==="many"),b=Object.entries(s.relations).filter(([,y])=>y.relation==="manyToMany");if(f.length===0&&d.length===0&&b.length===0)continue;let w=[];for(let[y,m]of f){let x=$r(i,s,m);w.push(` ${y}: one(${m.targetTable}, {
|
|
8924
8924
|
fields: [${i}.${x.sourceField}],
|
|
8925
8925
|
references: [${m.targetTable}.${x.targetField}],
|
|
8926
8926
|
}),`);}for(let[y,m]of d)w.push(` ${y}: many(${m.targetTable}),`);for(let[y,m]of b){if(!m.junctionTable)throw new Error(`manyToMany relation '${i}.${y}' is missing junctionTable after normalization.`);w.push(` ${y}: many(${m.junctionTable}),`);}o.push(`export const ${i}Relations = relations(${i}, ({ one, many }) => ({
|
|
@@ -8929,7 +8929,7 @@ ${w.join(`
|
|
|
8929
8929
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
8930
8930
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
8931
8931
|
import { relations } from "drizzle-orm";
|
|
8932
|
-
${
|
|
8932
|
+
${Cr(r)}
|
|
8933
8933
|
${a.join(`
|
|
8934
8934
|
|
|
8935
8935
|
`)}
|
|
@@ -8938,10 +8938,10 @@ ${o.join(`
|
|
|
8938
8938
|
|
|
8939
8939
|
`)}
|
|
8940
8940
|
|
|
8941
|
-
${
|
|
8941
|
+
${Ir(e)}
|
|
8942
8942
|
|
|
8943
|
-
${
|
|
8944
|
-
`}function
|
|
8943
|
+
${Fr(e)}
|
|
8944
|
+
`}function an(e,t,n){let r="z.unknown()";return e.type==="int"?r="z.number().int()":e.type==="string"?(r="z.string()",e.length!==void 0&&(r+=`.max(${e.length})`)):e.type==="boolean"?r="z.boolean()":e.type==="date"&&(r="z.date()"),t&&(r+=".optional()"),n&&(r+=".nullable()"),r}function Er(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=O(n),o=[],i=[];for(let[s,l]of Object.entries(r.columns))o.push(` ${s}: ${an(l,on(l),C(l))},`),i.push(` ${s}: ${an(l,C(l),C(l))},`);t.push(`export const ${n}InsertSchema = z.object({
|
|
8945
8945
|
${o.join(`
|
|
8946
8946
|
`)}
|
|
8947
8947
|
});
|
|
@@ -8955,7 +8955,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
8955
8955
|
`);}return `import { z } from "zod";
|
|
8956
8956
|
|
|
8957
8957
|
${t.join(`
|
|
8958
|
-
`)}`}function
|
|
8958
|
+
`)}`}function Dr(e){return e.type==="int"?"number":e.type==="string"?"string":e.type==="boolean"?"boolean":e.type==="date"?"Date":"unknown"}function Or(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=O(n),o=[],i=[];for(let[s,l]of Object.entries(r.columns)){let u=Dr(l),c=C(l)?" | null":"";o.push(` ${s}${C(l)?"?":""}: ${u}${c};`),i.push(` ${s}${on(l)?"?":""}: ${u}${c};`);}t.push(`export type ${a} = {
|
|
8959
8959
|
${o.join(`
|
|
8960
8960
|
`)}
|
|
8961
8961
|
};
|
|
@@ -8966,11 +8966,12 @@ ${i.join(`
|
|
|
8966
8966
|
};`);}return `${t.join(`
|
|
8967
8967
|
|
|
8968
8968
|
`)}
|
|
8969
|
-
`}function qr(e,t){if(t){let n=e[t];if(!_(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(_(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function en(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")),l=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),u=qr(l,t.exportName),c=br(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 f=Ar(c,n),d=Cr(c),b=Nr(c);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(i,b)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function Ir(e){return e.replaceAll("\\","/")}function A(e,t){let n=Ir(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Dr=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()&&Dr.has(path.extname(r.name))&&n.push(a);}return n}function Z(e){return e.replace(/\.[cm]?tsx?$/,"")}function Or(e,t){let n=e,r=false,a,o="unknown";for(;g__namespace.isCallExpression(n);){let i=n.expression;if(!g__namespace.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,n=i.expression;else if(s==="default"){r=true;let l=n.arguments[0];l&&(g__namespace.isStringLiteral(l)||g__namespace.isNumericLiteral(l)?a=l.text:l.kind===g__namespace.SyntaxKind.TrueKeyword?a="true":l.kind===g__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else n=i.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function jr(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g__namespace.isPropertyAssignment(r)&&g__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)||n.push(Or(r.initializer,r.name.text));return n}function Br(e){return g__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g__namespace.SyntaxKind.ExportKeyword)??false:false}function on(e){return g__namespace.isIdentifier(e)?e.text:g__namespace.isParenthesizedExpression(e)?on(e.expression):null}function Vr(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return g__namespace.isStringLiteral(n)||g__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>g__namespace.isStringLiteral(r)||g__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Wr(e,t){let n=g__namespace.createSourceFile(t,e,g__namespace.ScriptTarget.Latest,true,g__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(Br(a))for(let o of a.declarationList.declarations){if(!g__namespace.isIdentifier(o.name)||!o.initializer||!g__namespace.isCallExpression(o.initializer))continue;let i=on(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"?Vr(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?jr(o.initializer.arguments[0]):[]});}return r}function tn(e,t,n){let r=t.replace(/\\/g,"/"),o=Z(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Hr(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 nn(e,t){let n=e.replace(/\\/g,"/"),a=Z(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 sn(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),l=Wr(i,a),u=[{kind:"query",kindDirectory:"queries",exports:l.filter(c=>c.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:l.filter(c=>c.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:l.filter(c=>c.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:l.filter(c=>c.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:l.filter(c=>c.kind==="storage")}];for(let c of u){if(c.exports.length===0)continue;let f=Hr(s,c.kindDirectory);for(let d of c.exports){let b=c.kind==="query"||c.kind==="mutation"?nn(f,d.exportName):void 0,w=c.kind==="scheduler"||c.kind==="cron"?nn(f,d.exportName):void 0,y=c.kind==="query"||c.kind==="mutation"?[...Z(f).split("/").filter(Boolean),d.exportName]:void 0,m=c.kind==="query"?tn("queries",f,d.exportName):c.kind==="mutation"?tn("mutations",f,d.exportName):c.kind==="storage"?`/storage/managers/${d.exportName}`:`/${c.kindDirectory}/${w}`;t.push({kind:c.kind,exportName:d.exportName,filePath:a,importPath:A(e.outDirAbs,a),clientImportPath:A(path.resolve(e.outDirAbs,"client"),a),routePath:m,handlerName:b,clientSegments:y,taskName:w,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 Lr(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,l=false,u=false;for(let f=0;f<e.length;f+=1){let d=e[f];if(u){n+=d,u=false;continue}if(d==="\\"){n+=d,u=true;continue}if(!s&&!l&&d==="'"){i=!i,n+=d;continue}if(!i&&!l&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){l=!l,n+=d;continue}if(i||s||l){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 b=n.trim();b.length>0&&t.push(b),n="";continue}n+=d;}let c=n.trim();return c.length>0&&t.push(c),t}function Ur(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let l=0;l<e.length;l+=1){let u=e[l];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 l}}return -1}function Qr(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function _r(e){let t=Lr(e),n=[];for(let r of t){let a=Ur(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),l=/autoincrement\s*:\s*true/i.test(i),u=/\.default\s*\(/i.test(i),f=!/\.notnull\s*\(/i.test(i)||u||l||s;n.push({name:o,expression:i,type:Qr(i),optional:f,primaryKey:s,autoIncrement:l});}return n}function Kr(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,l=false,u=false,c=false,f=false;for(let d=i;d<o.length;d+=1){let b=o[d];if(f){f=false;continue}if(b==="\\"){f=true;continue}if(!u&&!c&&b==="'"){l=!l;continue}if(!l&&!c&&b==='"'){u=!u;continue}if(!l&&!u&&b==="`"){c=!c;continue}if(!(l||u||c)){if(b==="{"){s+=1;continue}if(b==="}"&&(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 l=r(e,s);if(l===-1){a=t.exec(e);continue}let u=e.slice(s+1,l);n.push({exportName:o,tableName:i,columns:_r(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 un(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(),l=Kr(s);if(l.length>0)return {schemaPath:o,tables:l}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function Jr(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function dn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=A(t,a),s=path.resolve(t,"client"),l=A(s,a);await Promise.all([promises.mkdir(t,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(n,{recursive:true})]);let u=path.resolve(t,"server.ts"),c=path.resolve(t,"client.ts"),f=path.resolve(t,"auth.config.ts"),d=path.resolve(t,"auth.schema.ts"),b=path.resolve(t,"drizzle.config.ts"),w=path.resolve(n,"wrangler.json"),y=await en(e),m=await un(e,y?[y.schemaPath]:[]),x=A(t,m.schemaPath),v=await sn(e),R=at(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),Tn=ce(l,v),vn=W(x,v,r.r2[0]?.binding),Rn=ne(i),kn=y?[Jr(o,y.schemaPath),...r.schema.filter(k=>!/(^|\/)schema\.ts$/.test(k))]:r.schema,Sn=ue(kn),An=it(e,v),Nn=_t(x,m,v),$n=path.resolve(t,"admin.routes.ts"),Cn=vn.map(k=>Bun.write(path.resolve(t,k.relativePath),k.source)),qn=Tn.map(k=>Bun.write(path.resolve(t,k.relativePath),k.source));await Promise.all([Bun.write(u,R),Bun.write(c,`export * from "./client/index";
|
|
8970
|
-
`),...
|
|
8971
|
-
`),Bun.write(
|
|
8969
|
+
`}function jr(e,t){if(t){let n=e[t];if(!J(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(J(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function sn(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")),l=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),u=jr(l,t.exportName),c=Ar(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 f=Pr(c,n),d=Or(c),b=Er(c);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(i,b)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function Vr(e){return e.replaceAll("\\","/")}function A(e,t){let n=Vr(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Lr=new Set([".ts",".tsx",".mts",".cts"]);async function dn(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 dn(a));continue}r.isFile()&&Lr.has(path.extname(r.name))&&n.push(a);}return n}function ee(e){return e.replace(/\.[cm]?tsx?$/,"")}function Ur(e,t){let n=e,r=false,a,o="unknown";for(;g__namespace.isCallExpression(n);){let i=n.expression;if(!g__namespace.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,n=i.expression;else if(s==="default"){r=true;let l=n.arguments[0];l&&(g__namespace.isStringLiteral(l)||g__namespace.isNumericLiteral(l)?a=l.text:l.kind===g__namespace.SyntaxKind.TrueKeyword?a="true":l.kind===g__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else n=i.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function Qr(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g__namespace.isPropertyAssignment(r)&&g__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)||n.push(Ur(r.initializer,r.name.text));return n}function _r(e){return g__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g__namespace.SyntaxKind.ExportKeyword)??false:false}function pn(e){return g__namespace.isIdentifier(e)?e.text:g__namespace.isParenthesizedExpression(e)?pn(e.expression):null}function Kr(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return g__namespace.isStringLiteral(n)||g__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>g__namespace.isStringLiteral(r)||g__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Gr(e,t){let n=g__namespace.createSourceFile(t,e,g__namespace.ScriptTarget.Latest,true,g__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(_r(a))for(let o of a.declarationList.declarations){if(!g__namespace.isIdentifier(o.name)||!o.initializer||!g__namespace.isCallExpression(o.initializer))continue;let i=pn(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"?Kr(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?Qr(o.initializer.arguments[0]):[]});}return r}function ln(e,t,n){let r=t.replace(/\\/g,"/"),o=ee(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Jr(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 cn(e,t){let n=e.replace(/\\/g,"/"),a=ee(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 mn(e){let t=[],n=await dn(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),l=Gr(i,a),u=[{kind:"query",kindDirectory:"queries",exports:l.filter(c=>c.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:l.filter(c=>c.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:l.filter(c=>c.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:l.filter(c=>c.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:l.filter(c=>c.kind==="storage")}];for(let c of u){if(c.exports.length===0)continue;let f=Jr(s,c.kindDirectory);for(let d of c.exports){let b=c.kind==="query"||c.kind==="mutation"?cn(f,d.exportName):void 0,w=c.kind==="scheduler"||c.kind==="cron"?cn(f,d.exportName):void 0,y=c.kind==="query"||c.kind==="mutation"?[...ee(f).split("/").filter(Boolean),d.exportName]:void 0,m=c.kind==="query"?ln("queries",f,d.exportName):c.kind==="mutation"?ln("mutations",f,d.exportName):c.kind==="storage"?`/storage/managers/${d.exportName}`:`/${c.kindDirectory}/${w}`;t.push({kind:c.kind,exportName:d.exportName,filePath:a,importPath:A(e.outDirAbs,a),clientImportPath:A(path.resolve(e.outDirAbs,"client"),a),routePath:m,handlerName:b,clientSegments:y,taskName:w,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 Yr(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,l=false,u=false;for(let f=0;f<e.length;f+=1){let d=e[f];if(u){n+=d,u=false;continue}if(d==="\\"){n+=d,u=true;continue}if(!s&&!l&&d==="'"){i=!i,n+=d;continue}if(!i&&!l&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){l=!l,n+=d;continue}if(i||s||l){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 b=n.trim();b.length>0&&t.push(b),n="";continue}n+=d;}let c=n.trim();return c.length>0&&t.push(c),t}function Xr(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let l=0;l<e.length;l+=1){let u=e[l];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 l}}return -1}function ea(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ta(e){let t=Yr(e),n=[];for(let r of t){let a=Xr(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),l=/autoincrement\s*:\s*true/i.test(i),u=/\.default\s*\(/i.test(i),f=!/\.notnull\s*\(/i.test(i)||u||l||s;n.push({name:o,expression:i,type:ea(i),optional:f,primaryKey:s,autoIncrement:l});}return n}function na(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,l=false,u=false,c=false,f=false;for(let d=i;d<o.length;d+=1){let b=o[d];if(f){f=false;continue}if(b==="\\"){f=true;continue}if(!u&&!c&&b==="'"){l=!l;continue}if(!l&&!c&&b==='"'){u=!u;continue}if(!l&&!u&&b==="`"){c=!c;continue}if(!(l||u||c)){if(b==="{"){s+=1;continue}if(b==="}"&&(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 l=r(e,s);if(l===-1){a=t.exec(e);continue}let u=e.slice(s+1,l);n.push({exportName:o,tableName:i,columns:ta(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 hn(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(),l=na(s);if(l.length>0)return {schemaPath:o,tables:l}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function sa(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function yn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=A(t,a),s=path.resolve(t,"client"),l=A(s,a);await Promise.all([promises.mkdir(t,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(n,{recursive:true})]);let u=path.resolve(t,"server.ts"),c=path.resolve(t,"client.ts"),f=path.resolve(t,"auth.config.ts"),d=path.resolve(t,"auth.schema.ts"),b=path.resolve(t,"drizzle.config.ts"),w=path.resolve(n,"wrangler.json"),y=await sn(e),m=await hn(e,y?[y.schemaPath]:[]),x=A(t,m.schemaPath),R=await mn(e),k=ut(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),Nn=fe(l,R),$n=L(x,R,r.r2[0]?.binding),Cn=le(i),qn=y?[sa(o,y.schemaPath),...r.schema.filter(v=>!/(^|\/)schema\.ts$/.test(v))]:r.schema,Mn=he(qn),In=pt(e,R),Fn=Xt(x,m,R),Pn=path.resolve(t,"admin.routes.ts"),En=$n.map(v=>Bun.write(path.resolve(t,v.relativePath),v.source)),Dn=Nn.map(v=>Bun.write(path.resolve(t,v.relativePath),v.source));await Promise.all([Bun.write(u,k),Bun.write(c,`export * from "./client/index";
|
|
8970
|
+
`),...Dn,...En,Bun.write(f,Cn),Bun.write(d,""),Bun.write(b,Mn),Bun.write(w,`${JSON.stringify(In,null,2)}
|
|
8971
|
+
`),Bun.write(Pn,Fn)]);let V=path.relative(o,f).replace(/\\/g,"/"),On=V.startsWith(".")?V:`./${V}`,W=path.relative(o,d).replace(/\\/g,"/"),jn=W.startsWith(".")?W:`./${W}`,re=await Bun.spawn(["npx","@better-auth/cli","generate","--config",On,"--output",jn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(re!==0)throw new Error(`better-auth generation failed with exit code ${re}`);let Bn={compilerOptions:{lib:["es2024"],types:["@types/node","bun","@cloudflare/workers-types/2023-07-01"],module:"es2022",target:"es2024",moduleResolution:"bundler",strictNullChecks:true,skipLibCheck:true,declaration:true,emitDeclarationOnly:true,jsx:"react-jsx",paths:{"_generated/*":["./*"]}},include:["*.ts","client/*.ts"]},ae=path.resolve(t,"tsconfig.json");await Bun.write(ae,`${JSON.stringify(Bn,null,2)}
|
|
8972
|
+
`);let oe=process.platform==="win32"?"npx.cmd":"npx",ie=await Bun.spawn([oe,"--yes","-p","typescript","tsc","-p",ae],{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(ie!==0)throw new Error(`Generated code build failed with exit code ${ie}`);let Vn=t+"/";async function se(v){let M=await promises.readdir(v,{withFileTypes:true});for(let $ of M){let I=path.join(v,$.name);if($.isDirectory()){if($.name==="node_modules"||$.name.startsWith(".")||I===t)continue;await se(I);}else $.name.endsWith(".d.ts")&&!I.startsWith(Vn)&&await promises.rm(I);}}await se(o);let Wn=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.existsSync(Wn)){let M=await Bun.spawn([oe,"--yes","-p","typescript","tsc","--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(M!==0)throw new Error(`TypeScript build failed with exit code ${M}`)}}var bn=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(),wn=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),xn=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(),Tn=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(),pa=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([bn,zod.z.array(bn).min(1)]),kv:zod.z.union([wn,zod.z.array(wn)]).optional(),r2:zod.z.union([xn,zod.z.array(xn)]).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:Tn.optional(),realtime:da.optional(),wranglerOverrides:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),build:zod.z.boolean().optional()}).strict();function vn(e){return typeof e=="object"&&e!==null}function ma(e){let t=vn(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=Tn.safeParse(t);return n.success?n.data:{}}function ga(e){if(!vn(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function fa(e){let n={...ma(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:ga(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function q(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=pa.parse(o),s=fa(i);return {configPath:t,configDir:n,scanDirAbs:path.resolve(n,s.scanDir),outDirAbs:path.resolve(n,s.outDir),wranglerOutDirAbs:path.resolve(n,s.wranglerOutDir),config:s}}function wa(e){let t=e;for(;;){if(fs.existsSync(path.resolve(t,"package.json")))return t;let n=path.dirname(t);if(n===t)return e;t=n;}}async function B(e,t={}){let n=await q(e);if(t.build!==void 0&&(n.config.build=t.build),await yn(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
8972
8973
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
8973
|
-
`);}async function
|
|
8974
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
8974
|
+
`);}async function kn(e,t={}){if(await B(e,{build:t.build}),!t.watch)return;let n=await q(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await B(e,{build:t.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
8975
|
+
`);}finally{r=false,a&&(a=false,await o());}};ha__default.default.watch(n.scanDirAbs,{ignoreInitial:true}).on("all",async(s,l)=>{process.stdout.write(`\u{1F504} Change detected: ${l}
|
|
8975
8976
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
8976
|
-
`);}async function
|
|
8977
|
+
`);}async function Sn(e,t={}){let n=await q(e),r=wa(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.ts"),i=process.platform==="win32"?"npx.cmd":"npx",l=await Bun.spawn([i,"drizzle-kit","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 u=n.config.database[0].databaseName,c=[i,"wrangler","d1","migrations","apply",u];t.local?c.push("--local"):t.remote?c.push("--remote"):t.preview&&c.push("--preview");let d=await Bun.spawn(c,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(d!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${d}`)}async function An(e,t={name:"",email:"",password:""}){let n=await q(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(),l=Date.now(),u=t.name.replace(/'/g,"''"),c=t.email.replace(/'/g,"''"),f=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${u}', '${c}', 1, ${l}, ${l}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${c}', 'credential', '${i}', '${o}', ${l}, ${l});`].join(" "),d=n.config.database[0].databaseName,w=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${f}`];t.local?w.push("--local"):t.remote&&w.push("--remote");let m=await Bun.spawn(w,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(m!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${m}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var N=new commander.Command;N.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");N.command("build").description("Generate server.ts, client.ts, auth.config.ts, drizzle.config.ts, 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 B(e.config,{build:e.build});});N.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 kn(e.config,{watch:e.watch,build:e.build});});N.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 Sn(e.config,{local:e.local,remote:e.remote,preview:e.preview});});N.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 An(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 N.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|