appflare 0.2.30 → 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/Documentation.md +758 -758
- package/cli/commands/index.ts +238 -238
- package/cli/generate.ts +243 -178
- package/cli/index.ts +120 -120
- package/cli/load-config.ts +184 -184
- package/cli/schema-compiler.ts +1183 -1183
- package/cli/templates/auth/README.md +156 -156
- package/cli/templates/auth/config.ts +61 -61
- package/cli/templates/auth/route-config.ts +1 -1
- package/cli/templates/auth/route-handler.ts +1 -1
- package/cli/templates/auth/route-request-utils.ts +5 -5
- package/cli/templates/auth/route.config.ts +18 -18
- package/cli/templates/auth/route.handler.ts +18 -18
- package/cli/templates/auth/route.request-utils.ts +55 -55
- package/cli/templates/auth/route.ts +14 -14
- package/cli/templates/core/README.md +266 -266
- package/cli/templates/core/app-creation.ts +19 -19
- package/cli/templates/core/client/appflare.ts +112 -112
- package/cli/templates/core/client/handlers/index.ts +748 -748
- package/cli/templates/core/client/handlers.ts +1 -1
- package/cli/templates/core/client/index.ts +7 -7
- package/cli/templates/core/client/storage.ts +195 -195
- package/cli/templates/core/client/types.ts +186 -186
- package/cli/templates/core/client-modules/appflare.ts +1 -1
- package/cli/templates/core/client-modules/handlers.ts +1 -1
- package/cli/templates/core/client-modules/index.ts +1 -1
- package/cli/templates/core/client-modules/storage.ts +1 -1
- package/cli/templates/core/client-modules/types.ts +1 -1
- package/cli/templates/core/client.artifacts.ts +39 -39
- package/cli/templates/core/client.ts +4 -4
- package/cli/templates/core/drizzle.ts +15 -15
- package/cli/templates/core/export.ts +14 -14
- package/cli/templates/core/handlers.route.ts +24 -24
- package/cli/templates/core/handlers.ts +1 -1
- package/cli/templates/core/imports.ts +9 -9
- package/cli/templates/core/server.ts +38 -38
- package/cli/templates/core/types.ts +6 -6
- package/cli/templates/core/wrangler.ts +109 -109
- package/cli/templates/dashboard/builders/functions/index.ts +17 -17
- package/cli/templates/dashboard/builders/functions/render-page/header.ts +20 -20
- package/cli/templates/dashboard/builders/functions/render-page/index.ts +33 -33
- package/cli/templates/dashboard/builders/functions/render-page/request-panel.ts +171 -171
- package/cli/templates/dashboard/builders/functions/render-page/result-panel.ts +85 -85
- package/cli/templates/dashboard/builders/functions/render-page/scripts.ts +554 -554
- package/cli/templates/dashboard/builders/navigation.ts +122 -122
- package/cli/templates/dashboard/builders/storage/index.ts +13 -13
- package/cli/templates/dashboard/builders/storage/routes/create-directory-route.ts +29 -29
- package/cli/templates/dashboard/builders/storage/routes/delete-route.ts +18 -18
- package/cli/templates/dashboard/builders/storage/routes/download-route.ts +23 -23
- package/cli/templates/dashboard/builders/storage/routes/index.ts +22 -22
- package/cli/templates/dashboard/builders/storage/routes/list-route.ts +25 -25
- package/cli/templates/dashboard/builders/storage/routes/preview-route.ts +21 -21
- package/cli/templates/dashboard/builders/storage/routes/upload-route.ts +21 -21
- package/cli/templates/dashboard/builders/storage/runtime/helpers.ts +72 -72
- package/cli/templates/dashboard/builders/storage/runtime/storage-page.ts +130 -130
- package/cli/templates/dashboard/builders/table-routes/common/drawer-panel.ts +27 -27
- package/cli/templates/dashboard/builders/table-routes/common/pagination.ts +30 -30
- package/cli/templates/dashboard/builders/table-routes/common/search-bar.ts +23 -23
- package/cli/templates/dashboard/builders/table-routes/fragments.ts +217 -217
- package/cli/templates/dashboard/builders/table-routes/helpers.ts +45 -45
- package/cli/templates/dashboard/builders/table-routes/index.ts +8 -8
- package/cli/templates/dashboard/builders/table-routes/table/actions-cell.ts +71 -71
- package/cli/templates/dashboard/builders/table-routes/table/get-route.ts +291 -291
- package/cli/templates/dashboard/builders/table-routes/table/index.ts +80 -80
- package/cli/templates/dashboard/builders/table-routes/table/post-routes.ts +163 -163
- package/cli/templates/dashboard/builders/table-routes/table-route.ts +7 -7
- package/cli/templates/dashboard/builders/table-routes/users/get-route.ts +69 -69
- package/cli/templates/dashboard/builders/table-routes/users/html/modals.ts +57 -57
- package/cli/templates/dashboard/builders/table-routes/users/html/page.ts +27 -27
- package/cli/templates/dashboard/builders/table-routes/users/html/table.ts +128 -128
- package/cli/templates/dashboard/builders/table-routes/users/index.ts +32 -32
- package/cli/templates/dashboard/builders/table-routes/users/post-routes.ts +150 -150
- package/cli/templates/dashboard/builders/table-routes/users/redirect.ts +14 -14
- package/cli/templates/dashboard/builders/table-routes/users-route.ts +10 -10
- package/cli/templates/dashboard/components/dashboard-home.ts +23 -23
- package/cli/templates/dashboard/components/layout.ts +388 -388
- package/cli/templates/dashboard/components/login-page.ts +65 -65
- package/cli/templates/dashboard/index.ts +61 -61
- package/cli/templates/dashboard/types.ts +9 -9
- package/cli/templates/handlers/README.md +353 -353
- package/cli/templates/handlers/auth.ts +37 -37
- package/cli/templates/handlers/execution.ts +42 -42
- package/cli/templates/handlers/generators/context/context-creation.ts +101 -101
- package/cli/templates/handlers/generators/context/error-helpers.ts +11 -11
- package/cli/templates/handlers/generators/context/scheduler.ts +24 -24
- package/cli/templates/handlers/generators/context/storage-api.ts +82 -82
- package/cli/templates/handlers/generators/context/storage-helpers.ts +59 -59
- package/cli/templates/handlers/generators/context/types.ts +40 -40
- package/cli/templates/handlers/generators/context.ts +43 -43
- package/cli/templates/handlers/generators/execution.ts +15 -15
- package/cli/templates/handlers/generators/handlers.ts +13 -13
- package/cli/templates/handlers/generators/registration/modules/cron.ts +26 -26
- package/cli/templates/handlers/generators/registration/modules/realtime/auth.ts +75 -75
- package/cli/templates/handlers/generators/registration/modules/realtime/durable-object.ts +144 -144
- package/cli/templates/handlers/generators/registration/modules/realtime/index.ts +14 -14
- package/cli/templates/handlers/generators/registration/modules/realtime/publisher.ts +102 -102
- package/cli/templates/handlers/generators/registration/modules/realtime/routes.ts +164 -164
- package/cli/templates/handlers/generators/registration/modules/realtime/types.ts +30 -30
- package/cli/templates/handlers/generators/registration/modules/realtime/utils.ts +516 -516
- package/cli/templates/handlers/generators/registration/modules/scheduler.ts +56 -56
- package/cli/templates/handlers/generators/registration/modules/storage.ts +199 -199
- package/cli/templates/handlers/generators/registration/sections.ts +210 -210
- package/cli/templates/handlers/generators/types/context.ts +92 -92
- package/cli/templates/handlers/generators/types/core.ts +106 -106
- package/cli/templates/handlers/generators/types/operations.ts +135 -135
- package/cli/templates/handlers/generators/types/query-definitions/filter-and-where-types.ts +281 -259
- package/cli/templates/handlers/generators/types/query-definitions/query-api-types.ts +135 -135
- package/cli/templates/handlers/generators/types/query-definitions/query-helper-functions.ts +1103 -1031
- package/cli/templates/handlers/generators/types/query-definitions/schema-and-table-types.ts +278 -246
- package/cli/templates/handlers/generators/types/query-definitions.ts +13 -13
- package/cli/templates/handlers/generators/types/query-runtime/handled-error.ts +13 -13
- package/cli/templates/handlers/generators/types/query-runtime/runtime-aggregate-and-footer.ts +174 -174
- package/cli/templates/handlers/generators/types/query-runtime/runtime-read.ts +157 -121
- package/cli/templates/handlers/generators/types/query-runtime/runtime-setup.ts +45 -45
- package/cli/templates/handlers/generators/types/query-runtime/runtime-write.ts +697 -697
- package/cli/templates/handlers/generators/types/query-runtime.ts +15 -15
- package/cli/templates/handlers/index.ts +43 -43
- package/cli/templates/handlers/operations.ts +116 -116
- package/cli/templates/handlers/registration.ts +91 -91
- package/cli/templates/handlers/types.ts +15 -15
- package/cli/templates/handlers/utils.ts +48 -48
- package/cli/types.ts +110 -110
- package/cli/utils/handler-discovery.ts +466 -466
- package/cli/utils/json-utils.ts +24 -24
- package/cli/utils/path-utils.ts +19 -19
- package/cli/utils/schema-discovery.ts +399 -399
- package/dist/cli/index.d.mts +2 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +366 -203
- package/dist/cli/index.mjs +366 -203
- package/index.ts +18 -18
- package/package.json +58 -58
- package/react/index.ts +5 -5
- package/react/use-infinite-query.ts +252 -252
- package/react/use-mutation.ts +89 -89
- package/react/use-query.ts +207 -207
- package/schema.ts +415 -415
- package/test-better-auth-hash.ts +2 -2
- package/tsconfig.json +6 -6
- package/tsup.config.ts +82 -82
package/dist/cli/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import {Command}from'commander';import
|
|
2
|
+
import {Command}from'commander';import ha from'chokidar';import {existsSync}from'fs';import {resolve,isAbsolute,dirname,relative,join,extname}from'path';import {mkdir,readdir,rm}from'fs/promises';import {pathToFileURL}from'url';import*as g from'typescript';import {z as z$1}from'zod';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>>;
|
|
@@ -1712,15 +1712,25 @@ type WhereFieldValue<T, TFieldKey extends string> =
|
|
|
1712
1712
|
| Friendly<NonNil<T>>
|
|
1713
1713
|
| FieldOperators<T, TFieldKey>;
|
|
1714
1714
|
|
|
1715
|
-
|
|
1716
|
-
[K in keyof TModel]?:
|
|
1717
|
-
TModel[K],
|
|
1718
|
-
|
|
1719
|
-
>;
|
|
1715
|
+
type RelationWhereInput<TModel extends Record<string, unknown>, TName extends TableName | any = any> = {
|
|
1716
|
+
[K in keyof TModel]?:
|
|
1717
|
+
| WhereFieldValue<TModel[K], Extract<keyof TModel, string>>
|
|
1718
|
+
| (TModel[K] extends Record<string, unknown> ? RelationWhereInput<TModel[K]> : never);
|
|
1720
1719
|
} & {
|
|
1721
1720
|
geoWithin?: GeoWithinOperandForField<Extract<keyof TModel, string>>;
|
|
1722
1721
|
$geoWithin?: GeoWithinOperandForField<Extract<keyof TModel, string>>;
|
|
1723
|
-
}
|
|
1722
|
+
} & (TName extends TableName ? {
|
|
1723
|
+
[TRelation in keyof NativeFindManyWith<TName>]?: NativeFindManyWith<TName>[TRelation] extends infer TRelationConfig
|
|
1724
|
+
? TRelationConfig extends Record<string, unknown>
|
|
1725
|
+
? RelationWhereInput<
|
|
1726
|
+
RelationModelFromConfig<TRelationConfig>,
|
|
1727
|
+
any
|
|
1728
|
+
>
|
|
1729
|
+
: never
|
|
1730
|
+
: never;
|
|
1731
|
+
} : {});
|
|
1732
|
+
|
|
1733
|
+
export type WhereInput<TModel extends Record<string, unknown>, TName extends TableName | any = any> = RelationWhereInput<TModel, TName>;
|
|
1724
1734
|
|
|
1725
1735
|
type ColumnData<TColumn> = TColumn extends { _: { data: infer TData } }
|
|
1726
1736
|
? TData
|
|
@@ -1736,6 +1746,10 @@ type InferRelationWhereFields<TConfig> = TConfig extends { where?: infer TWhere
|
|
|
1736
1746
|
: never
|
|
1737
1747
|
: never;
|
|
1738
1748
|
|
|
1749
|
+
type InferRelationNativeWith<TConfig> = TConfig extends { with?: infer TWith }
|
|
1750
|
+
? TWith
|
|
1751
|
+
: never;
|
|
1752
|
+
|
|
1739
1753
|
type RelationModelFromConfig<TConfig extends Record<string, unknown>> =
|
|
1740
1754
|
InferRelationWhereFields<TConfig> extends infer TFields
|
|
1741
1755
|
? TFields extends Record<string, unknown>
|
|
@@ -1760,15 +1774,15 @@ type RelationAggregateSelectionInput<TModel extends Record<string, unknown>> = {
|
|
|
1760
1774
|
_avg?: RelationAvgSelectionInput<TModel>;
|
|
1761
1775
|
};
|
|
1762
1776
|
|
|
1763
|
-
type QueryNativeWithRelationInput<TEntry> =
|
|
1777
|
+
type QueryNativeWithRelationInput<TEntry, TTargetTable> =
|
|
1764
1778
|
| (Extract<TEntry, true> extends never ? never : true)
|
|
1765
1779
|
| (Extract<TEntry, Record<string, unknown>> extends infer TRelation
|
|
1766
1780
|
? TRelation extends Record<string, unknown>
|
|
1767
1781
|
? Omit<TRelation, "where" | "with" | "_count" | "_avg"> &
|
|
1768
1782
|
RelationAggregateSelectionInput<RelationModelFromConfig<TRelation>> & {
|
|
1769
|
-
where?: WhereInput<RelationModelFromConfig<TRelation>>;
|
|
1783
|
+
where?: WhereInput<RelationModelFromConfig<TRelation>, Extract<TTargetTable, TableName>>;
|
|
1770
1784
|
with?: TRelation extends { with?: infer TNestedWith }
|
|
1771
|
-
? QueryWithInputForTable<
|
|
1785
|
+
? QueryWithInputForTable<Extract<TTargetTable, TableName>, TNestedWith>
|
|
1772
1786
|
: never;
|
|
1773
1787
|
}
|
|
1774
1788
|
: never
|
|
@@ -1778,7 +1792,7 @@ type QueryManyToManyWithRelationInput<TTargetTable extends TableName> =
|
|
|
1778
1792
|
| true
|
|
1779
1793
|
| (Omit<NonNullable<TableFindManyArgs<TTargetTable>>, "where" | "with"> &
|
|
1780
1794
|
RelationAggregateSelectionInput<TableModel<TTargetTable>> & {
|
|
1781
|
-
where?: WhereInput<TableModel<TTargetTable
|
|
1795
|
+
where?: WhereInput<TableModel<TTargetTable>, TTargetTable>;
|
|
1782
1796
|
with?: QueryWithInputForTable<
|
|
1783
1797
|
TTargetTable,
|
|
1784
1798
|
NativeFindManyWith<TTargetTable>
|
|
@@ -1790,7 +1804,7 @@ type QueryWithRelationInputForTable<
|
|
|
1790
1804
|
TRelationName extends string,
|
|
1791
1805
|
TEntry,
|
|
1792
1806
|
> = [ManyToManyTargetTableName<TSourceTable, TRelationName>] extends [never]
|
|
1793
|
-
? QueryNativeWithRelationInput<TEntry
|
|
1807
|
+
? QueryNativeWithRelationInput<TEntry, RuntimeRelationTargetTable<TSourceTable, TRelationName>>
|
|
1794
1808
|
: QueryManyToManyWithRelationInput<
|
|
1795
1809
|
Extract<ManyToManyTargetTableName<TSourceTable, TRelationName>, TableName>
|
|
1796
1810
|
>;
|
|
@@ -1813,20 +1827,28 @@ type QueryWithInput<TName extends TableName, TWith> = QueryWithInputForTable<
|
|
|
1813
1827
|
TWith
|
|
1814
1828
|
>;
|
|
1815
1829
|
|
|
1830
|
+
export type OrderByDirection = "asc" | "desc";
|
|
1831
|
+
|
|
1832
|
+
export type OrderByInput<TName extends TableName> =
|
|
1833
|
+
| { column: Extract<keyof TableModel<TName>, string>; direction?: OrderByDirection }
|
|
1834
|
+
| Array<{ column: Extract<keyof TableModel<TName>, string>; direction?: OrderByDirection }>;
|
|
1835
|
+
|
|
1816
1836
|
export type QueryFindManyArgs<TName extends TableName> = Omit<
|
|
1817
1837
|
NonNullable<TableFindManyArgs<TName>>,
|
|
1818
|
-
"where" | "with"
|
|
1838
|
+
"where" | "with" | "orderBy"
|
|
1819
1839
|
> & {
|
|
1820
|
-
where?: WhereInput<TableModel<TName
|
|
1840
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1821
1841
|
with?: QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1842
|
+
orderBy?: OrderByInput<TName>;
|
|
1822
1843
|
};
|
|
1823
1844
|
|
|
1824
1845
|
export type QueryFindFirstArgs<TName extends TableName> = Omit<
|
|
1825
1846
|
NonNullable<TableFindFirstArgs<TName>>,
|
|
1826
|
-
"where" | "with"
|
|
1847
|
+
"where" | "with" | "orderBy"
|
|
1827
1848
|
> & {
|
|
1828
|
-
where?: WhereInput<TableModel<TName
|
|
1849
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1829
1850
|
with?: QueryWithInput<TName, NativeFindFirstWith<TName>>;
|
|
1851
|
+
orderBy?: OrderByInput<TName>;
|
|
1830
1852
|
};
|
|
1831
1853
|
|
|
1832
1854
|
type RelationInsertItem<TTargetTable extends TableName> =
|
|
@@ -1893,15 +1915,15 @@ export type QueryInsertArgs<TName extends TableName> = {
|
|
|
1893
1915
|
|
|
1894
1916
|
export type QueryUpdateArgs<TName extends TableName> = {
|
|
1895
1917
|
set: Partial<TableInsertModel<TName>>;
|
|
1896
|
-
where?: WhereInput<TableModel<TName
|
|
1918
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1897
1919
|
limit?: number;
|
|
1898
1920
|
};
|
|
1899
1921
|
|
|
1900
1922
|
export type QueryDeleteArgs<TName extends TableName> = {
|
|
1901
|
-
where?: WhereInput<TableModel<TName
|
|
1923
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1902
1924
|
limit?: number;
|
|
1903
1925
|
};
|
|
1904
|
-
`}function
|
|
1926
|
+
`}function Ce(){return `type AggregateWithInput<TName extends TableName> =
|
|
1905
1927
|
QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1906
1928
|
|
|
1907
1929
|
type NumericFieldKey<TName extends TableName> = NumericModelFieldKey<
|
|
@@ -1971,14 +1993,14 @@ type ApplyFindFirstWithAggregateResult<TResult, TArgs> =
|
|
|
1971
1993
|
: TResult;
|
|
1972
1994
|
|
|
1973
1995
|
export type QueryCountArgs<TName extends TableName> = {
|
|
1974
|
-
where?: WhereInput<TableModel<TName
|
|
1996
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1975
1997
|
field?: Extract<keyof TableModel<TName>, string> | string;
|
|
1976
1998
|
distinct?: boolean;
|
|
1977
1999
|
with?: AggregateWithInput<TName>;
|
|
1978
2000
|
};
|
|
1979
2001
|
|
|
1980
2002
|
export type QueryAvgArgs<TName extends TableName> = {
|
|
1981
|
-
where?: WhereInput<TableModel<TName
|
|
2003
|
+
where?: WhereInput<TableModel<TName>, TName>;
|
|
1982
2004
|
field: NumericFieldKey<TName> | string;
|
|
1983
2005
|
distinct?: boolean;
|
|
1984
2006
|
with?: AggregateWithInput<TName>;
|
|
@@ -2033,7 +2055,7 @@ export type DbMutationEvent = {
|
|
|
2033
2055
|
export type QueryDbOptions = {
|
|
2034
2056
|
onMutation?: (event: DbMutationEvent) => void;
|
|
2035
2057
|
};
|
|
2036
|
-
`}function
|
|
2058
|
+
`}function qe(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2037
2059
|
return typeof value === "object" && value !== null;
|
|
2038
2060
|
}
|
|
2039
2061
|
|
|
@@ -2293,6 +2315,21 @@ function buildWhereFilterFromFields(
|
|
|
2293
2315
|
|
|
2294
2316
|
const field = fields[fieldName];
|
|
2295
2317
|
if (!field) {
|
|
2318
|
+
if (isRecord(fieldValue) && tableName) {
|
|
2319
|
+
const relation = getRuntimeRelation(tableName, fieldName);
|
|
2320
|
+
if (relation) {
|
|
2321
|
+
const relationFilter = buildRelationFilter(
|
|
2322
|
+
relation,
|
|
2323
|
+
fieldValue,
|
|
2324
|
+
tableName,
|
|
2325
|
+
fields,
|
|
2326
|
+
);
|
|
2327
|
+
if (relationFilter) {
|
|
2328
|
+
filters.push(relationFilter);
|
|
2329
|
+
}
|
|
2330
|
+
continue;
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2296
2333
|
continue;
|
|
2297
2334
|
}
|
|
2298
2335
|
|
|
@@ -2443,6 +2480,63 @@ function getRuntimeRelation(
|
|
|
2443
2480
|
return runtimeRelationMap[tableName]?.[relationName];
|
|
2444
2481
|
}
|
|
2445
2482
|
|
|
2483
|
+
function buildRelationFilter(
|
|
2484
|
+
relation: RuntimeRelation,
|
|
2485
|
+
whereValue: Record<string, unknown>,
|
|
2486
|
+
sourceTableName: string,
|
|
2487
|
+
sourceFields: Record<string, unknown>
|
|
2488
|
+
): SQL | undefined {
|
|
2489
|
+
const rawTargetTable = (mergedSchema as Record<string, unknown>)[relation.targetTable];
|
|
2490
|
+
if (!rawTargetTable) {
|
|
2491
|
+
return undefined;
|
|
2492
|
+
}
|
|
2493
|
+
|
|
2494
|
+
const targetFields = getTableColumns(rawTargetTable as never) as Record<string, unknown>;
|
|
2495
|
+
const relationFilter = buildWhereFilterFromFields(
|
|
2496
|
+
targetFields,
|
|
2497
|
+
whereValue,
|
|
2498
|
+
relation.targetTable,
|
|
2499
|
+
);
|
|
2500
|
+
|
|
2501
|
+
if (!relationFilter) {
|
|
2502
|
+
return undefined;
|
|
2503
|
+
}
|
|
2504
|
+
|
|
2505
|
+
if (relation.kind === "one") {
|
|
2506
|
+
const sourceField = relation.sourceField || (relation.targetTable + "Id");
|
|
2507
|
+
const targetFieldCol = targetFields[relation.referenceField || "id"];
|
|
2508
|
+
const sourceFieldCol = sourceFields[sourceField];
|
|
2509
|
+
if (!targetFieldCol || !sourceFieldCol) return undefined;
|
|
2510
|
+
return sql\`exists (select 1 from \${rawTargetTable as never} where \${eq(targetFieldCol as never, sourceFieldCol as never)} and \${relationFilter})\`;
|
|
2511
|
+
}
|
|
2512
|
+
|
|
2513
|
+
if (relation.kind === "many") {
|
|
2514
|
+
const sourceFieldCol = sourceFields[relation.sourceField || "id"];
|
|
2515
|
+
const targetFieldCol = targetFields[relation.referenceField || (sourceTableName + "Id")];
|
|
2516
|
+
if (!targetFieldCol || !sourceFieldCol) return undefined;
|
|
2517
|
+
return sql\`exists (select 1 from \${rawTargetTable as never} where \${eq(targetFieldCol as never, sourceFieldCol as never)} and \${relationFilter})\`;
|
|
2518
|
+
}
|
|
2519
|
+
|
|
2520
|
+
if (relation.kind === "manyToMany") {
|
|
2521
|
+
const junctionTableName = (relation as RuntimeRelationManyToMany).junctionTable;
|
|
2522
|
+
const junctionTable = (mergedSchema as Record<string, unknown>)[junctionTableName];
|
|
2523
|
+
if (!junctionTable) return undefined;
|
|
2524
|
+
const junctionFields = getTableColumns(junctionTable as never) as Record<string, unknown>;
|
|
2525
|
+
|
|
2526
|
+
const sourceFieldCol = sourceFields[(relation as RuntimeRelationManyToMany).sourceField || "id"];
|
|
2527
|
+
const targetFieldCol = targetFields[(relation as RuntimeRelationManyToMany).targetField || "id"];
|
|
2528
|
+
|
|
2529
|
+
const junctionSourceRefCol = junctionFields[(relation as RuntimeRelationManyToMany).referenceField || (sourceTableName + "Id")];
|
|
2530
|
+
const junctionTargetRefCol = junctionFields[(relation as RuntimeRelationManyToMany).targetReferenceField || (relation.targetTable + "Id")];
|
|
2531
|
+
|
|
2532
|
+
if (!sourceFieldCol || !targetFieldCol || !junctionSourceRefCol || !junctionTargetRefCol) return undefined;
|
|
2533
|
+
|
|
2534
|
+
return sql\`exists (select 1 from \${junctionTable as never} inner join \${rawTargetTable as never} on \${eq(junctionTargetRefCol as never, targetFieldCol as never)} where \${eq(junctionSourceRefCol as never, sourceFieldCol as never)} and \${relationFilter})\`;
|
|
2535
|
+
}
|
|
2536
|
+
|
|
2537
|
+
return undefined;
|
|
2538
|
+
}
|
|
2539
|
+
|
|
2446
2540
|
type ManyToManyRuntimeMap = Record<
|
|
2447
2541
|
string,
|
|
2448
2542
|
Record<string, ManyToManyRuntimeRelation>
|
|
@@ -3061,7 +3155,7 @@ function inferConflictTarget(table: unknown): string[] {
|
|
|
3061
3155
|
|
|
3062
3156
|
return [];
|
|
3063
3157
|
}
|
|
3064
|
-
`}function
|
|
3158
|
+
`}function Me(){return `const mergedSchema = {
|
|
3065
3159
|
...authSchema,
|
|
3066
3160
|
...schema,
|
|
3067
3161
|
};
|
|
@@ -3085,6 +3179,18 @@ type NativeFindManyWith<TName extends TableName> =
|
|
|
3085
3179
|
NonNullable<TableFindManyArgs<TName>> extends { with?: infer TWith }
|
|
3086
3180
|
? TWith
|
|
3087
3181
|
: never;
|
|
3182
|
+
type NormalizeWhereInWith<TWith, TNativeWith> = TWith extends Record<string, unknown>
|
|
3183
|
+
? {
|
|
3184
|
+
[K in keyof TWith]: K extends keyof TNativeWith
|
|
3185
|
+
? TWith[K] extends Record<string, unknown>
|
|
3186
|
+
? Omit<TWith[K], 'where'> & { where?: NonNullable<Extract<TNativeWith[K], Record<string, unknown>>['where']> } & (TWith[K] extends { with: infer TNestedWith }
|
|
3187
|
+
? { with: NormalizeWhereInWith<TNestedWith, TNativeWith[K]> }
|
|
3188
|
+
: {})
|
|
3189
|
+
: TWith[K]
|
|
3190
|
+
: TWith[K];
|
|
3191
|
+
}
|
|
3192
|
+
: TWith;
|
|
3193
|
+
|
|
3088
3194
|
type ResolveNativeFindManyWith<
|
|
3089
3195
|
TName extends TableName,
|
|
3090
3196
|
TArgs extends QueryFindManyArgs<TName> | undefined,
|
|
@@ -3092,7 +3198,7 @@ type ResolveNativeFindManyWith<
|
|
|
3092
3198
|
? Extract<TWith, NativeFindManyWith<TName>> extends infer TResolved
|
|
3093
3199
|
? [TResolved] extends [never]
|
|
3094
3200
|
? TWith extends Record<string, unknown>
|
|
3095
|
-
? NativeFindManyWith<TName
|
|
3201
|
+
? NormalizeWhereInWith<TWith, NativeFindManyWith<TName>>
|
|
3096
3202
|
: never
|
|
3097
3203
|
: TResolved
|
|
3098
3204
|
: never
|
|
@@ -3165,6 +3271,16 @@ type RuntimeRelationTargetTable<
|
|
|
3165
3271
|
}
|
|
3166
3272
|
? Extract<TTarget, TableName>
|
|
3167
3273
|
: never;
|
|
3274
|
+
|
|
3275
|
+
type TargetTableForRelation<
|
|
3276
|
+
TSource extends TableName,
|
|
3277
|
+
TRelation extends string,
|
|
3278
|
+
> = RuntimeRelationTargetTable<TSource, TRelation> extends never
|
|
3279
|
+
? ManyToManyTargetTableName<TSource, TRelation> extends never
|
|
3280
|
+
? never
|
|
3281
|
+
: Extract<ManyToManyTargetTableName<TSource, TRelation>, TableName>
|
|
3282
|
+
: RuntimeRelationTargetTable<TSource, TRelation>;
|
|
3283
|
+
|
|
3168
3284
|
type TableInsertScalarModel<TName extends TableName> = TableInsertModel<TName>;
|
|
3169
3285
|
type FindManyWithFromArgs<TArgs> = TArgs extends { with?: infer TWith }
|
|
3170
3286
|
? TWith
|
|
@@ -3186,7 +3302,7 @@ type ManyToManyRelationRows<
|
|
|
3186
3302
|
>
|
|
3187
3303
|
: Array<TableModel<TTargetTable>>;
|
|
3188
3304
|
type ReplaceManyToManyRelationsInRow<
|
|
3189
|
-
TSourceTable extends
|
|
3305
|
+
TSourceTable extends string,
|
|
3190
3306
|
TRow,
|
|
3191
3307
|
TWith,
|
|
3192
3308
|
> = TRow extends Record<string, unknown>
|
|
@@ -3194,17 +3310,27 @@ type ReplaceManyToManyRelationsInRow<
|
|
|
3194
3310
|
[K in keyof TRow]: K extends string
|
|
3195
3311
|
? TWith extends Record<string, unknown>
|
|
3196
3312
|
? K extends keyof TWith
|
|
3197
|
-
? [ManyToManyTargetTableName<TSourceTable, K>] extends [never]
|
|
3198
|
-
?
|
|
3313
|
+
? [ManyToManyTargetTableName<Extract<TSourceTable, TableName>, K>] extends [never]
|
|
3314
|
+
? ReplaceManyToManyRelationsInRow<
|
|
3315
|
+
[RuntimeRelationTargetTable<Extract<TSourceTable, TableName>, K>] extends [never]
|
|
3316
|
+
? K
|
|
3317
|
+
: RuntimeRelationTargetTable<Extract<TSourceTable, TableName>, K>,
|
|
3318
|
+
TRow[K],
|
|
3319
|
+
TWith[K] extends { with: infer TNestedWith }
|
|
3320
|
+
? TNestedWith
|
|
3321
|
+
: undefined
|
|
3322
|
+
>
|
|
3199
3323
|
: ManyToManyRelationRows<
|
|
3200
|
-
Extract<ManyToManyTargetTableName<TSourceTable, K>, TableName>,
|
|
3324
|
+
Extract<ManyToManyTargetTableName<Extract<TSourceTable, TableName>, K>, TableName>,
|
|
3201
3325
|
TWith[K]
|
|
3202
3326
|
>
|
|
3203
3327
|
: TRow[K]
|
|
3204
3328
|
: TRow[K]
|
|
3205
3329
|
: TRow[K];
|
|
3206
3330
|
}
|
|
3207
|
-
: TRow
|
|
3331
|
+
: TRow extends Array<infer TEntry>
|
|
3332
|
+
? Array<ReplaceManyToManyRelationsInRow<TSourceTable, TEntry, TWith>>
|
|
3333
|
+
: TRow;
|
|
3208
3334
|
type ApplyManyToManyFindManyResult<
|
|
3209
3335
|
TSourceTable extends TableName,
|
|
3210
3336
|
TArgs extends QueryFindManyArgs<TSourceTable> | undefined,
|
|
@@ -3269,7 +3395,7 @@ type ResolveNativeFindFirstWith<
|
|
|
3269
3395
|
? Extract<TWith, NativeFindFirstWith<TName>> extends infer TResolved
|
|
3270
3396
|
? [TResolved] extends [never]
|
|
3271
3397
|
? TWith extends Record<string, unknown>
|
|
3272
|
-
? NativeFindFirstWith<TName
|
|
3398
|
+
? NormalizeWhereInWith<TWith, NativeFindFirstWith<TName>>
|
|
3273
3399
|
: never
|
|
3274
3400
|
: TResolved
|
|
3275
3401
|
: never
|
|
@@ -3304,9 +3430,9 @@ type TableFindFirstResult<
|
|
|
3304
3430
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3305
3431
|
(typeof mergedSchema)[TName]
|
|
3306
3432
|
>;
|
|
3307
|
-
`}function
|
|
3433
|
+
`}function Ie(){return [Me(),$e(),Ce(),qe()].join(`
|
|
3308
3434
|
|
|
3309
|
-
`)}function
|
|
3435
|
+
`)}function Fe(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3310
3436
|
const withValue = args?.with;
|
|
3311
3437
|
const pathSegments = args?.field
|
|
3312
3438
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -3477,7 +3603,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3477
3603
|
},
|
|
3478
3604
|
}) as AppflareQueryDb;
|
|
3479
3605
|
}
|
|
3480
|
-
`}function
|
|
3606
|
+
`}function Pe(){return `export class AppflareHandledError extends Error {
|
|
3481
3607
|
public readonly status: number;
|
|
3482
3608
|
public readonly payload: unknown;
|
|
3483
3609
|
|
|
@@ -3487,7 +3613,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3487
3613
|
this.payload = payload;
|
|
3488
3614
|
}
|
|
3489
3615
|
}
|
|
3490
|
-
`}function
|
|
3616
|
+
`}function Ee(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
3491
3617
|
const where = isRecord(args?.where)
|
|
3492
3618
|
? (args?.where as Record<string, unknown>)
|
|
3493
3619
|
: undefined;
|
|
@@ -3497,9 +3623,14 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3497
3623
|
? (() => {
|
|
3498
3624
|
const nextArgs = { ...(args ?? {}) };
|
|
3499
3625
|
delete nextArgs.where;
|
|
3626
|
+
delete nextArgs.orderBy;
|
|
3500
3627
|
return nextArgs;
|
|
3501
3628
|
})()
|
|
3502
|
-
:
|
|
3629
|
+
: (() => {
|
|
3630
|
+
const nextArgs = { ...(args ?? {}) };
|
|
3631
|
+
delete nextArgs.orderBy;
|
|
3632
|
+
return nextArgs;
|
|
3633
|
+
})();
|
|
3503
3634
|
const withValue = args?.with;
|
|
3504
3635
|
const transformedWithResult =
|
|
3505
3636
|
withValue === undefined
|
|
@@ -3514,11 +3645,23 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3514
3645
|
tableName,
|
|
3515
3646
|
withValue,
|
|
3516
3647
|
);
|
|
3648
|
+
const orderByValue = args?.orderBy;
|
|
3649
|
+
const transformedOrderBy = orderByValue
|
|
3650
|
+
? (Array.isArray(orderByValue) ? orderByValue : [orderByValue]).map(
|
|
3651
|
+
(item: Record<string, unknown>) => {
|
|
3652
|
+
const column = item.column as string;
|
|
3653
|
+
const direction = (item.direction as string) ?? "asc";
|
|
3654
|
+
const col = (table as Record<string, { asc: () => unknown; desc: () => unknown }>)[column];
|
|
3655
|
+
return direction === "desc" ? col.desc() : col.asc();
|
|
3656
|
+
},
|
|
3657
|
+
)
|
|
3658
|
+
: undefined;
|
|
3517
3659
|
if (
|
|
3518
3660
|
!whereFilter &&
|
|
3519
3661
|
transformedWith === withValue &&
|
|
3520
3662
|
!aggregatePlan &&
|
|
3521
|
-
!requiresManyToManyFlatten
|
|
3663
|
+
!requiresManyToManyFlatten &&
|
|
3664
|
+
!transformedOrderBy
|
|
3522
3665
|
) {
|
|
3523
3666
|
return queryTable.findMany(passthroughArgs);
|
|
3524
3667
|
}
|
|
@@ -3527,6 +3670,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3527
3670
|
...(passthroughArgs ?? {}),
|
|
3528
3671
|
...(whereFilter ? { where: () => whereFilter } : {}),
|
|
3529
3672
|
...(transformedWith !== undefined ? { with: transformedWith } : {}),
|
|
3673
|
+
...(transformedOrderBy ? { orderBy: transformedOrderBy } : {}),
|
|
3530
3674
|
});
|
|
3531
3675
|
|
|
3532
3676
|
return queryPromise.then((result) => {
|
|
@@ -3556,9 +3700,14 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3556
3700
|
? (() => {
|
|
3557
3701
|
const nextArgs = { ...(args ?? {}) };
|
|
3558
3702
|
delete nextArgs.where;
|
|
3703
|
+
delete nextArgs.orderBy;
|
|
3559
3704
|
return nextArgs;
|
|
3560
3705
|
})()
|
|
3561
|
-
:
|
|
3706
|
+
: (() => {
|
|
3707
|
+
const nextArgs = { ...(args ?? {}) };
|
|
3708
|
+
delete nextArgs.orderBy;
|
|
3709
|
+
return nextArgs;
|
|
3710
|
+
})();
|
|
3562
3711
|
const withValue = args?.with;
|
|
3563
3712
|
const transformedWithResult =
|
|
3564
3713
|
withValue === undefined
|
|
@@ -3573,11 +3722,23 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3573
3722
|
tableName,
|
|
3574
3723
|
withValue,
|
|
3575
3724
|
);
|
|
3725
|
+
const orderByValue = args?.orderBy;
|
|
3726
|
+
const transformedOrderBy = orderByValue
|
|
3727
|
+
? (Array.isArray(orderByValue) ? orderByValue : [orderByValue]).map(
|
|
3728
|
+
(item: Record<string, unknown>) => {
|
|
3729
|
+
const column = item.column as string;
|
|
3730
|
+
const direction = (item.direction as string) ?? "asc";
|
|
3731
|
+
const col = (table as Record<string, { asc: () => unknown; desc: () => unknown }>)[column];
|
|
3732
|
+
return direction === "desc" ? col.desc() : col.asc();
|
|
3733
|
+
},
|
|
3734
|
+
)
|
|
3735
|
+
: undefined;
|
|
3576
3736
|
if (
|
|
3577
3737
|
!whereFilter &&
|
|
3578
3738
|
transformedWith === withValue &&
|
|
3579
3739
|
!aggregatePlan &&
|
|
3580
|
-
!requiresManyToManyFlatten
|
|
3740
|
+
!requiresManyToManyFlatten &&
|
|
3741
|
+
!transformedOrderBy
|
|
3581
3742
|
) {
|
|
3582
3743
|
return queryTable.findFirst(passthroughArgs);
|
|
3583
3744
|
}
|
|
@@ -3586,6 +3747,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3586
3747
|
...(passthroughArgs ?? {}),
|
|
3587
3748
|
...(whereFilter ? { where: () => whereFilter } : {}),
|
|
3588
3749
|
...(transformedWith !== undefined ? { with: transformedWith } : {}),
|
|
3750
|
+
...(transformedOrderBy ? { orderBy: transformedOrderBy } : {}),
|
|
3589
3751
|
});
|
|
3590
3752
|
|
|
3591
3753
|
return queryPromise.then((result) => {
|
|
@@ -3605,7 +3767,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3605
3767
|
);
|
|
3606
3768
|
});
|
|
3607
3769
|
},
|
|
3608
|
-
`}function
|
|
3770
|
+
`}function De(){return `export function createQueryDb(
|
|
3609
3771
|
$db: AppflareDb,
|
|
3610
3772
|
options?: QueryDbOptions,
|
|
3611
3773
|
): AppflareQueryDb {
|
|
@@ -3647,7 +3809,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3647
3809
|
};
|
|
3648
3810
|
|
|
3649
3811
|
const tableApi = {
|
|
3650
|
-
`}function
|
|
3812
|
+
`}function Oe(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
3651
3813
|
const transaction = ($db as any).transaction;
|
|
3652
3814
|
|
|
3653
3815
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -4341,9 +4503,9 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4341
4503
|
);
|
|
4342
4504
|
return rows;
|
|
4343
4505
|
},
|
|
4344
|
-
`}function
|
|
4506
|
+
`}function je(){return [De(),Ee(),Oe(),Fe(),Pe()].join(`
|
|
4345
4507
|
|
|
4346
|
-
`)}function
|
|
4508
|
+
`)}function Be(){return `type AuthSession = typeof auth.$Infer.Session;
|
|
4347
4509
|
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
4348
4510
|
type User = AuthSession['user']
|
|
4349
4511
|
type Session = AuthSession['session']
|
|
@@ -4432,7 +4594,7 @@ export type AppflareContext = {
|
|
|
4432
4594
|
storage: AppflareStorage;
|
|
4433
4595
|
error: (status: number, message: string, details?: unknown) => never;
|
|
4434
4596
|
};
|
|
4435
|
-
`}function
|
|
4597
|
+
`}function Ve(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
4436
4598
|
|
|
4437
4599
|
export type SchedulerEnqueueOptions = {
|
|
4438
4600
|
delaySeconds?: number;
|
|
@@ -4564,20 +4726,20 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
4564
4726
|
definition,
|
|
4565
4727
|
};
|
|
4566
4728
|
}
|
|
4567
|
-
`}function
|
|
4729
|
+
`}function We(){return [Ne(),Ie(),je(),Be(),Ve()].join(`
|
|
4568
4730
|
|
|
4569
|
-
`)}function
|
|
4731
|
+
`)}function He(e){return `import type { Context } from "hono";
|
|
4570
4732
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
4571
4733
|
import { drizzle } from "drizzle-orm/d1";
|
|
4572
4734
|
import { z, type ZodRawShape } from "zod";
|
|
4573
4735
|
import * as authSchema from "./auth.schema";
|
|
4574
4736
|
import * as schema from "${e}";
|
|
4575
4737
|
|
|
4576
|
-
${
|
|
4577
|
-
`}function
|
|
4578
|
-
`)}function
|
|
4579
|
-
`)}function
|
|
4580
|
-
`)}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 `
|
|
4581
4743
|
app.get(
|
|
4582
4744
|
"${t.routePath}",
|
|
4583
4745
|
sValidator("query", ${r}),
|
|
@@ -4590,7 +4752,7 @@ ${Fe()}
|
|
|
4590
4752
|
}
|
|
4591
4753
|
},
|
|
4592
4754
|
);`}).join(`
|
|
4593
|
-
`)}function
|
|
4755
|
+
`)}function Xn(e){return e.filter(({operation:t})=>t.kind==="mutation").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
4594
4756
|
app.post(
|
|
4595
4757
|
"${t.routePath}",
|
|
4596
4758
|
sValidator("json", ${r}),
|
|
@@ -4605,26 +4767,26 @@ ${Fe()}
|
|
|
4605
4767
|
}
|
|
4606
4768
|
},
|
|
4607
4769
|
);`}).join(`
|
|
4608
|
-
`)}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 `
|
|
4609
4771
|
${JSON.stringify(a)}: {
|
|
4610
4772
|
definition: ${n}.definition,
|
|
4611
4773
|
schema: ${r},
|
|
4612
4774
|
},`}).join(`
|
|
4613
|
-
`)}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 `
|
|
4614
4776
|
${JSON.stringify(a)}: {
|
|
4615
4777
|
definition: ${n}.definition,
|
|
4616
4778
|
schema: ${r},
|
|
4617
4779
|
},`}).join(`
|
|
4618
|
-
`)}function
|
|
4619
|
-
`)}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 `
|
|
4620
4782
|
{
|
|
4621
4783
|
taskName: ${JSON.stringify(r)},
|
|
4622
4784
|
cronTriggers: ${JSON.stringify(a)},
|
|
4623
4785
|
definition: ${n}.definition,
|
|
4624
4786
|
},`}).join(`
|
|
4625
|
-
`)}function
|
|
4787
|
+
`)}function ar(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
4626
4788
|
${t}.definition.handler,`).join(`
|
|
4627
|
-
`)}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=`
|
|
4628
4790
|
function getRealtimeStub(
|
|
4629
4791
|
env: Record<string, unknown>,
|
|
4630
4792
|
options: RegisterHandlersOptions,
|
|
@@ -4698,7 +4860,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
4698
4860
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
4699
4861
|
return url.toString();
|
|
4700
4862
|
}
|
|
4701
|
-
`;var
|
|
4863
|
+
`;var Ue=`
|
|
4702
4864
|
export class AppflareRealtimeDurableObject {
|
|
4703
4865
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
4704
4866
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -4841,7 +5003,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
4841
5003
|
return new Response("Not found", { status: 404 });
|
|
4842
5004
|
}
|
|
4843
5005
|
}
|
|
4844
|
-
`;var
|
|
5006
|
+
`;var Qe=`
|
|
4845
5007
|
async function publishMutationEvents(
|
|
4846
5008
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
4847
5009
|
options: RegisterHandlersOptions,
|
|
@@ -4942,7 +5104,7 @@ async function publishMutationEvents(
|
|
|
4942
5104
|
}
|
|
4943
5105
|
}
|
|
4944
5106
|
}
|
|
4945
|
-
`;var
|
|
5107
|
+
`;var _e=`
|
|
4946
5108
|
function registerRealtimeRoutes(
|
|
4947
5109
|
app: Hono<WorkerEnv>,
|
|
4948
5110
|
options: RegisterHandlersOptions,
|
|
@@ -5105,7 +5267,7 @@ function registerRealtimeRoutes(
|
|
|
5105
5267
|
return stub.fetch(c.req.raw);
|
|
5106
5268
|
});
|
|
5107
5269
|
}
|
|
5108
|
-
`;var
|
|
5270
|
+
`;var Ke=`
|
|
5109
5271
|
type RealtimeSubscription = {
|
|
5110
5272
|
token: string;
|
|
5111
5273
|
signature: string;
|
|
@@ -5134,7 +5296,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
5134
5296
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
5135
5297
|
? string
|
|
5136
5298
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
5137
|
-
`;var
|
|
5299
|
+
`;var Ge=`
|
|
5138
5300
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5139
5301
|
return typeof value === "object" && value !== null;
|
|
5140
5302
|
}
|
|
@@ -5649,9 +5811,9 @@ function doesSubscriptionMatchMutation(
|
|
|
5649
5811
|
|
|
5650
5812
|
return false;
|
|
5651
5813
|
}
|
|
5652
|
-
`;var
|
|
5814
|
+
`;var Je=[Ke,Ge,Le,Qe,_e,Ue].join(`
|
|
5653
5815
|
|
|
5654
|
-
`);var
|
|
5816
|
+
`);var Ze=`
|
|
5655
5817
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
5656
5818
|
if (!value) {
|
|
5657
5819
|
return undefined;
|
|
@@ -5849,7 +6011,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
5849
6011
|
}
|
|
5850
6012
|
});
|
|
5851
6013
|
}
|
|
5852
|
-
`;var
|
|
6014
|
+
`;var Ye=`
|
|
5853
6015
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
5854
6016
|
? string
|
|
5855
6017
|
: keyof typeof schedulerHandlers;
|
|
@@ -5904,7 +6066,7 @@ export async function executeScheduledBatch(
|
|
|
5904
6066
|
}
|
|
5905
6067
|
}
|
|
5906
6068
|
}
|
|
5907
|
-
`;var
|
|
6069
|
+
`;var Xe=`
|
|
5908
6070
|
export async function executeCronTriggers(
|
|
5909
6071
|
controller: { cron: string },
|
|
5910
6072
|
env: Record<string, unknown>,
|
|
@@ -5929,7 +6091,7 @@ export async function executeCronTriggers(
|
|
|
5929
6091
|
}
|
|
5930
6092
|
}
|
|
5931
6093
|
}
|
|
5932
|
-
`;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";
|
|
5933
6095
|
import type { Hono } from "hono";
|
|
5934
6096
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
5935
6097
|
import { ZodError, z } from "zod";
|
|
@@ -5986,9 +6148,9 @@ const storageHandlers = [${c||`
|
|
|
5986
6148
|
|
|
5987
6149
|
setStorageHandlers([...storageHandlers]);
|
|
5988
6150
|
|
|
5989
|
-
${
|
|
6151
|
+
${Ye}
|
|
5990
6152
|
|
|
5991
|
-
${
|
|
6153
|
+
${Je}
|
|
5992
6154
|
|
|
5993
6155
|
export function registerGeneratedHandlers(
|
|
5994
6156
|
app: Hono<WorkerEnv>,
|
|
@@ -6001,20 +6163,20 @@ export function registerGeneratedHandlers(
|
|
|
6001
6163
|
`}
|
|
6002
6164
|
}
|
|
6003
6165
|
|
|
6004
|
-
${
|
|
6166
|
+
${Ze}
|
|
6005
6167
|
|
|
6006
|
-
${
|
|
6007
|
-
`}function
|
|
6008
|
-
KV: c.env["${e}"] as KVNamespace`:""}function
|
|
6009
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6010
|
-
}`}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) => {
|
|
6011
6173
|
const auth = createAuth(
|
|
6012
|
-
${
|
|
6174
|
+
${tt(t,n)},
|
|
6013
6175
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
6014
6176
|
);
|
|
6015
6177
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6016
6178
|
});
|
|
6017
|
-
`}function
|
|
6179
|
+
`}function ir(){return `export const getHeaders = (headers: Headers) => {
|
|
6018
6180
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6019
6181
|
const headerObject: Record<string, any> = {};
|
|
6020
6182
|
let hasCookie = false;
|
|
@@ -6044,15 +6206,15 @@ ${_e}
|
|
|
6044
6206
|
|
|
6045
6207
|
return headerObject as any as Headers;
|
|
6046
6208
|
};
|
|
6047
|
-
`}function
|
|
6209
|
+
`}function sr(){return `export const getSanitizedRequest = (req: Request) => {
|
|
6048
6210
|
const newRequest = new Request(req, {
|
|
6049
6211
|
headers: getHeaders(req.headers),
|
|
6050
6212
|
});
|
|
6051
6213
|
return newRequest;
|
|
6052
6214
|
};
|
|
6053
|
-
`}function
|
|
6054
|
-
`+
|
|
6055
|
-
`+
|
|
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>();
|
|
6056
6218
|
|
|
6057
6219
|
app.use('*', cors({
|
|
6058
6220
|
origin: (origin, c) => {
|
|
@@ -6068,7 +6230,7 @@ app.use('*', cors({
|
|
|
6068
6230
|
},
|
|
6069
6231
|
credentials: true
|
|
6070
6232
|
}));
|
|
6071
|
-
`}function
|
|
6233
|
+
`}function it(){return `export { AppflareRealtimeDurableObject };
|
|
6072
6234
|
|
|
6073
6235
|
export default {
|
|
6074
6236
|
fetch: app.fetch,
|
|
@@ -6079,7 +6241,7 @@ export default {
|
|
|
6079
6241
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
6080
6242
|
},
|
|
6081
6243
|
};
|
|
6082
|
-
`}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?`
|
|
6083
6245
|
kvBinding: "${t}",`:"",c=r?`
|
|
6084
6246
|
r2Binding: "${r}",`:"",f=`
|
|
6085
6247
|
realtimeBinding: "${a}",
|
|
@@ -6093,16 +6255,16 @@ export default {
|
|
|
6093
6255
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6094
6256
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
6095
6257
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
6096
|
-
`}function
|
|
6258
|
+
`}function lt(){return `import { createAuth } from "./auth.config";
|
|
6097
6259
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
6098
6260
|
import { registerAdminDashboard } from "./admin.routes";
|
|
6099
6261
|
import { Hono } from "hono";
|
|
6100
6262
|
import { cors } from "hono/cors";
|
|
6101
6263
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6102
|
-
`}function
|
|
6264
|
+
`}function ct(){return `type WorkerEnv = {
|
|
6103
6265
|
Bindings: Record<string, unknown>;
|
|
6104
6266
|
};
|
|
6105
|
-
`}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">
|
|
6106
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">
|
|
6107
6269
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6108
6270
|
<span class="truncate">users</span>
|
|
@@ -6114,7 +6276,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6114
6276
|
<span class="truncate">${n.tableName}</span>
|
|
6115
6277
|
</a>
|
|
6116
6278
|
</li>`).join(`
|
|
6117
|
-
`)}`}function
|
|
6279
|
+
`)}`}function ft(e){let t=e.filter(o=>o.kind==="query"),n=e.filter(o=>o.kind==="mutation"),r=t.map(o=>`
|
|
6118
6280
|
<li data-name="${o.exportName}">
|
|
6119
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">
|
|
6120
6282
|
<iconify-icon icon="solar:reorder-linear" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
@@ -6148,7 +6310,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6148
6310
|
<ul class="flex flex-col gap-0.5">${a}</ul>`:""}
|
|
6149
6311
|
</nav>
|
|
6150
6312
|
</div>
|
|
6151
|
-
`}function
|
|
6313
|
+
`}function ht(e){return e.map(t=>`
|
|
6152
6314
|
<a
|
|
6153
6315
|
href="/admin/table/${t.exportName}"
|
|
6154
6316
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
@@ -6165,9 +6327,9 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6165
6327
|
</div>
|
|
6166
6328
|
</div>
|
|
6167
6329
|
</a>
|
|
6168
|
-
`.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=>`
|
|
6169
6331
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6170
|
-
`).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 `
|
|
6171
6333
|
<th>
|
|
6172
6334
|
<a href="#"
|
|
6173
6335
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -6179,7 +6341,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6179
6341
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6180
6342
|
</a>
|
|
6181
6343
|
</th>
|
|
6182
|
-
`}).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"?`
|
|
6183
6345
|
<div class="form-control">
|
|
6184
6346
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6185
6347
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6217,7 +6379,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6217
6379
|
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6218
6380
|
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm"${a} />
|
|
6219
6381
|
</div>
|
|
6220
|
-
`}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?"":`
|
|
6221
6383
|
if (raw_${n} === '') {
|
|
6222
6384
|
return c.text('${n} is required', 400);
|
|
6223
6385
|
}
|
|
@@ -6262,7 +6424,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6262
6424
|
payload.${n} = raw_${n};
|
|
6263
6425
|
}
|
|
6264
6426
|
`}).join(`
|
|
6265
|
-
`)}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">
|
|
6266
6428
|
<div class="drawer drawer-end">
|
|
6267
6429
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6268
6430
|
<div class="drawer-content">
|
|
@@ -6315,7 +6477,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6315
6477
|
</div>
|
|
6316
6478
|
</div>
|
|
6317
6479
|
</div>
|
|
6318
|
-
</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 `
|
|
6319
6481
|
<div class="flex flex-col sm:flex-row justify-between items-center mt-4 gap-3 py-3 px-1">
|
|
6320
6482
|
<div class="text-xs text-base-content/40">
|
|
6321
6483
|
Total found: <span class="font-medium text-base-content/60">\${total}</span>
|
|
@@ -6337,7 +6499,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6337
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>\`}
|
|
6338
6500
|
</div>
|
|
6339
6501
|
\` : ''}
|
|
6340
|
-
</div>`}function
|
|
6502
|
+
</div>`}function P(e,t="Search term or filter..."){return `
|
|
6341
6503
|
<div class="form-control w-full md:w-auto relative">
|
|
6342
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>
|
|
6343
6505
|
<input type="text"
|
|
@@ -6348,7 +6510,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6348
6510
|
hx-trigger="keyup changed delay:500ms, search"
|
|
6349
6511
|
hx-target="#main-content"
|
|
6350
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" />
|
|
6351
|
-
</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?`
|
|
6352
6514
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
6353
6515
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
6354
6516
|
<div class="text-xs text-base-content/70">
|
|
@@ -6600,7 +6762,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6600
6762
|
title: "${e.tableName} - Admin Dashboard",
|
|
6601
6763
|
children: content
|
|
6602
6764
|
}));
|
|
6603
|
-
});`}function
|
|
6765
|
+
});`}function St(e,t,n,r,a,o,i,s){let l=r==="number"?`
|
|
6604
6766
|
const parsedId = Number(rawId);
|
|
6605
6767
|
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
6606
6768
|
idValue = parsedId;
|
|
@@ -6733,15 +6895,15 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6733
6895
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
6734
6896
|
});
|
|
6735
6897
|
${c}
|
|
6736
|
-
`}function
|
|
6737
|
-
`+
|
|
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 `
|
|
6738
6900
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
6739
6901
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
6740
6902
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
6741
6903
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
6742
6904
|
const search = params.search ? params.search : '';
|
|
6743
6905
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
6744
|
-
};`}function
|
|
6906
|
+
};`}function Nt(){return `
|
|
6745
6907
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6746
6908
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6747
6909
|
<div class="modal">
|
|
@@ -6762,7 +6924,7 @@ ${c}
|
|
|
6762
6924
|
</div>
|
|
6763
6925
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
6764
6926
|
</div>
|
|
6765
|
-
\`}`}function
|
|
6927
|
+
\`}`}function $t(){return `
|
|
6766
6928
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6767
6929
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6768
6930
|
<div class="modal">
|
|
@@ -6783,8 +6945,8 @@ ${c}
|
|
|
6783
6945
|
</div>
|
|
6784
6946
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
6785
6947
|
</div>
|
|
6786
|
-
\`}`}var
|
|
6787
|
-
`),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 `
|
|
6788
6950
|
const tableHtml = html\`
|
|
6789
6951
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
6790
6952
|
<div class="overflow-x-auto">
|
|
@@ -6852,8 +7014,8 @@ ${c}
|
|
|
6852
7014
|
</div>
|
|
6853
7015
|
</div>
|
|
6854
7016
|
</div>
|
|
6855
|
-
${
|
|
6856
|
-
${
|
|
7017
|
+
${Nt()}
|
|
7018
|
+
${$t()}
|
|
6857
7019
|
</td>
|
|
6858
7020
|
</tr>
|
|
6859
7021
|
\`)}
|
|
@@ -6869,7 +7031,7 @@ ${Tt()}
|
|
|
6869
7031
|
${t}
|
|
6870
7032
|
</div>
|
|
6871
7033
|
\`;
|
|
6872
|
-
`}function
|
|
7034
|
+
`}function qt(){return `
|
|
6873
7035
|
const content = html\`
|
|
6874
7036
|
<div id="main-content">
|
|
6875
7037
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -6881,11 +7043,11 @@ ${Tt()}
|
|
|
6881
7043
|
<iconify-icon icon="mdi:refresh" width="14" height="14"></iconify-icon>
|
|
6882
7044
|
</button>
|
|
6883
7045
|
</div>
|
|
6884
|
-
${
|
|
7046
|
+
${P("/admin/users","Search users...")}
|
|
6885
7047
|
</div>
|
|
6886
7048
|
\${tableHtml}
|
|
6887
7049
|
</div>
|
|
6888
|
-
\`;`}function
|
|
7050
|
+
\`;`}function Mt(){let e=Ct(),t=qt();return `
|
|
6889
7051
|
adminApp.get('/users', async (c) => {
|
|
6890
7052
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
6891
7053
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -6941,7 +7103,7 @@ ${Tt()}
|
|
|
6941
7103
|
title: "users - Admin Dashboard",
|
|
6942
7104
|
children: content,
|
|
6943
7105
|
}));
|
|
6944
|
-
});`}function
|
|
7106
|
+
});`}function It(){return `
|
|
6945
7107
|
adminApp.post('/users/edit', async (c) => {
|
|
6946
7108
|
const session = await requireAdminSession(c);
|
|
6947
7109
|
if (!session) {
|
|
@@ -7084,8 +7246,8 @@ ${Tt()}
|
|
|
7084
7246
|
const resolvedPage = String(Math.min(nextPageCandidate, totalPages));
|
|
7085
7247
|
|
|
7086
7248
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7087
|
-
});`}function
|
|
7088
|
-
${
|
|
7249
|
+
});`}function G(){return `
|
|
7250
|
+
${At()}
|
|
7089
7251
|
|
|
7090
7252
|
const requireAdminSession = async (c: any) => {
|
|
7091
7253
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7096,12 +7258,12 @@ ${Tt()}
|
|
|
7096
7258
|
return session;
|
|
7097
7259
|
};
|
|
7098
7260
|
|
|
7099
|
-
${
|
|
7261
|
+
${Mt()}
|
|
7100
7262
|
|
|
7101
|
-
${
|
|
7102
|
-
`}function
|
|
7263
|
+
${It()}
|
|
7264
|
+
`}function Ft(e){return `${e.tables.map(t=>K(t)).join(`
|
|
7103
7265
|
`)}
|
|
7104
|
-
${
|
|
7266
|
+
${G()}`}function Pt(e){return `
|
|
7105
7267
|
<div class="flex items-center justify-between">
|
|
7106
7268
|
<div class="flex items-center gap-3">
|
|
7107
7269
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -7116,9 +7278,9 @@ ${Q()}`}function $t(e){return `
|
|
|
7116
7278
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
7117
7279
|
</div>
|
|
7118
7280
|
</div>
|
|
7119
|
-
`}function
|
|
7281
|
+
`}function mr(e){return e==="boolean"?"checkbox":e==="number"?"number":"text"}function gr(e){let t=e.args??[];return t.length===0?`
|
|
7120
7282
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
7121
|
-
`: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?`
|
|
7122
7284
|
<div class="flex items-center gap-3 py-1">
|
|
7123
7285
|
<input
|
|
7124
7286
|
type="checkbox"
|
|
@@ -7147,7 +7309,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7147
7309
|
/>
|
|
7148
7310
|
</div>
|
|
7149
7311
|
`}).join(`
|
|
7150
|
-
`)}function
|
|
7312
|
+
`)}function fr(e){return `
|
|
7151
7313
|
<div class="space-y-4">
|
|
7152
7314
|
<div class="flex items-center justify-between">
|
|
7153
7315
|
<div class="flex flex-col">
|
|
@@ -7160,11 +7322,11 @@ ${Q()}`}function $t(e){return `
|
|
|
7160
7322
|
</label>
|
|
7161
7323
|
</div>
|
|
7162
7324
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
7163
|
-
${
|
|
7325
|
+
${gr(e)}
|
|
7164
7326
|
</div>
|
|
7165
7327
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7166
7328
|
</div>
|
|
7167
|
-
`}function
|
|
7329
|
+
`}function hr(){return `
|
|
7168
7330
|
<div class="space-y-4">
|
|
7169
7331
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7170
7332
|
<div class="relative group">
|
|
@@ -7181,7 +7343,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7181
7343
|
</div>
|
|
7182
7344
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
7183
7345
|
</div>
|
|
7184
|
-
`}function
|
|
7346
|
+
`}function yr(){return `
|
|
7185
7347
|
<div class="space-y-4">
|
|
7186
7348
|
<div class="flex items-center justify-between">
|
|
7187
7349
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -7195,7 +7357,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7195
7357
|
</div>
|
|
7196
7358
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
7197
7359
|
</div>
|
|
7198
|
-
`}function
|
|
7360
|
+
`}function Et(e){return `
|
|
7199
7361
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
7200
7362
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
7201
7363
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -7216,13 +7378,13 @@ ${Q()}`}function $t(e){return `
|
|
|
7216
7378
|
<!-- Tab Content -->
|
|
7217
7379
|
<div class="flex-1 overflow-y-auto">
|
|
7218
7380
|
<div id="request-tab-args" class="p-5">
|
|
7219
|
-
${
|
|
7381
|
+
${fr(e)}
|
|
7220
7382
|
</div>
|
|
7221
7383
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
7222
|
-
${
|
|
7384
|
+
${hr()}
|
|
7223
7385
|
</div>
|
|
7224
7386
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
7225
|
-
${
|
|
7387
|
+
${yr()}
|
|
7226
7388
|
</div>
|
|
7227
7389
|
</div>
|
|
7228
7390
|
|
|
@@ -7240,7 +7402,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7240
7402
|
</form>
|
|
7241
7403
|
</div>
|
|
7242
7404
|
</div>
|
|
7243
|
-
`}function
|
|
7405
|
+
`}function Dt(){return `
|
|
7244
7406
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
7245
7407
|
<!-- Panel Header -->
|
|
7246
7408
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -7322,7 +7484,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7322
7484
|
|
|
7323
7485
|
</div>
|
|
7324
7486
|
</div>
|
|
7325
|
-
`}function
|
|
7487
|
+
`}function Ot(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
7326
7488
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
7327
7489
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
7328
7490
|
|
|
@@ -7864,21 +8026,21 @@ ${Q()}`}function $t(e){return `
|
|
|
7864
8026
|
_rtEnabled = false;
|
|
7865
8027
|
});
|
|
7866
8028
|
</script>
|
|
7867
|
-
`}function
|
|
8029
|
+
`}function jt(e){return `
|
|
7868
8030
|
const content = html\`
|
|
7869
8031
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
7870
|
-
${
|
|
8032
|
+
${Pt(e)}
|
|
7871
8033
|
|
|
7872
8034
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
7873
8035
|
<!-- Request Panel -->
|
|
7874
|
-
${
|
|
8036
|
+
${Et(e)}
|
|
7875
8037
|
|
|
7876
8038
|
<!-- Result Panel -->
|
|
7877
|
-
${
|
|
8039
|
+
${Dt()}
|
|
7878
8040
|
</div>
|
|
7879
8041
|
</div>
|
|
7880
8042
|
|
|
7881
|
-
${
|
|
8043
|
+
${Ot(e)}
|
|
7882
8044
|
\`;
|
|
7883
8045
|
|
|
7884
8046
|
if (c.req.header('hx-request')) {
|
|
@@ -7888,11 +8050,11 @@ ${Q()}`}function $t(e){return `
|
|
|
7888
8050
|
return c.html(Layout({
|
|
7889
8051
|
title: "${e.exportName} - Functions",
|
|
7890
8052
|
children: content
|
|
7891
|
-
}));`}function
|
|
8053
|
+
}));`}function Bt(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
7892
8054
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
7893
|
-
${
|
|
8055
|
+
${jt(n)}
|
|
7894
8056
|
});`).join(`
|
|
7895
|
-
`)}function
|
|
8057
|
+
`)}function Vt(){return `
|
|
7896
8058
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
7897
8059
|
const r2Binding = (options as any).r2Binding;
|
|
7898
8060
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -7961,7 +8123,7 @@ ${Q()}`}function $t(e){return `
|
|
|
7961
8123
|
const parts = prefix.split('/').filter(Boolean);
|
|
7962
8124
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
7963
8125
|
};
|
|
7964
|
-
`}function
|
|
8126
|
+
`}function Wt(){return `
|
|
7965
8127
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
7966
8128
|
const parts = prefix.split('/').filter(Boolean);
|
|
7967
8129
|
const breadcrumbs: any[] = [];
|
|
@@ -8088,7 +8250,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8088
8250
|
</div>
|
|
8089
8251
|
\`;
|
|
8090
8252
|
};
|
|
8091
|
-
`}function
|
|
8253
|
+
`}function Ht(){return `
|
|
8092
8254
|
const handleStorageListRoute = async (c: any) => {
|
|
8093
8255
|
const bucket = getStorageBucket(c);
|
|
8094
8256
|
if (!bucket) {
|
|
@@ -8110,7 +8272,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8110
8272
|
|
|
8111
8273
|
adminApp.get('/storage', handleStorageListRoute);
|
|
8112
8274
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
8113
|
-
`}function
|
|
8275
|
+
`}function zt(){return `
|
|
8114
8276
|
adminApp.post('/storage/upload', async (c) => {
|
|
8115
8277
|
const bucket = getStorageBucket(c);
|
|
8116
8278
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8128,7 +8290,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8128
8290
|
|
|
8129
8291
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8130
8292
|
});
|
|
8131
|
-
`}function
|
|
8293
|
+
`}function Lt(){return `
|
|
8132
8294
|
adminApp.delete('/storage/delete', async (c) => {
|
|
8133
8295
|
const bucket = getStorageBucket(c);
|
|
8134
8296
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8143,7 +8305,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8143
8305
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
8144
8306
|
return c.html('');
|
|
8145
8307
|
});
|
|
8146
|
-
`}function
|
|
8308
|
+
`}function Ut(){return `
|
|
8147
8309
|
adminApp.post('/storage/directory', async (c) => {
|
|
8148
8310
|
const bucket = getStorageBucket(c);
|
|
8149
8311
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8169,7 +8331,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8169
8331
|
|
|
8170
8332
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8171
8333
|
});
|
|
8172
|
-
`}function
|
|
8334
|
+
`}function Qt(){return `
|
|
8173
8335
|
adminApp.get('/storage/download', async (c) => {
|
|
8174
8336
|
const bucket = getStorageBucket(c);
|
|
8175
8337
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8189,7 +8351,7 @@ ${Q()}`}function $t(e){return `
|
|
|
8189
8351
|
|
|
8190
8352
|
return new Response(object.body, { headers });
|
|
8191
8353
|
});
|
|
8192
|
-
`}function
|
|
8354
|
+
`}function _t(){return `
|
|
8193
8355
|
adminApp.get('/storage/preview', async (c) => {
|
|
8194
8356
|
const bucket = getStorageBucket(c);
|
|
8195
8357
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8207,25 +8369,25 @@ ${Q()}`}function $t(e){return `
|
|
|
8207
8369
|
|
|
8208
8370
|
return new Response(object.body, { headers });
|
|
8209
8371
|
});
|
|
8210
|
-
`}function
|
|
8211
|
-
${
|
|
8372
|
+
`}function Kt(){return `
|
|
8373
|
+
${Qt()}
|
|
8212
8374
|
|
|
8213
|
-
${
|
|
8375
|
+
${_t()}
|
|
8214
8376
|
|
|
8215
|
-
${
|
|
8377
|
+
${zt()}
|
|
8216
8378
|
|
|
8217
|
-
${
|
|
8379
|
+
${Lt()}
|
|
8218
8380
|
|
|
8219
|
-
${
|
|
8381
|
+
${Ut()}
|
|
8220
8382
|
|
|
8221
|
-
${
|
|
8222
|
-
`}function
|
|
8223
|
-
${
|
|
8224
|
-
|
|
8225
|
-
${Ft()}
|
|
8383
|
+
${Ht()}
|
|
8384
|
+
`}function Gt(){return `
|
|
8385
|
+
${Vt()}
|
|
8226
8386
|
|
|
8227
8387
|
${Wt()}
|
|
8228
|
-
|
|
8388
|
+
|
|
8389
|
+
${Kt()}
|
|
8390
|
+
`}function Jt(e,t){let n=ft(t);return `
|
|
8229
8391
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
8230
8392
|
return html\`<!DOCTYPE html>
|
|
8231
8393
|
<html lang="en" data-theme="light">
|
|
@@ -8600,7 +8762,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8600
8762
|
</body>
|
|
8601
8763
|
</html>\`;
|
|
8602
8764
|
}
|
|
8603
|
-
`}function
|
|
8765
|
+
`}function Zt(){return `
|
|
8604
8766
|
// Auth Middleware
|
|
8605
8767
|
adminApp.use('*', async (c, next) => {
|
|
8606
8768
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -8659,7 +8821,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8659
8821
|
}
|
|
8660
8822
|
await next();
|
|
8661
8823
|
});
|
|
8662
|
-
`}function
|
|
8824
|
+
`}function Yt(e){return `
|
|
8663
8825
|
adminApp.get('/', (c) => {
|
|
8664
8826
|
return c.html(Layout({
|
|
8665
8827
|
title: "Admin Dashboard",
|
|
@@ -8676,7 +8838,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8676
8838
|
\`
|
|
8677
8839
|
}));
|
|
8678
8840
|
});
|
|
8679
|
-
`}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";
|
|
8680
8842
|
import { html, raw } from "hono/html";
|
|
8681
8843
|
import { drizzle } from "drizzle-orm/d1";
|
|
8682
8844
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -8705,8 +8867,8 @@ ${f}
|
|
|
8705
8867
|
app.route('/admin', adminApp);
|
|
8706
8868
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
8707
8869
|
}
|
|
8708
|
-
`}function
|
|
8709
|
-
`}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)}: {
|
|
8710
8872
|
targetTable: ${h(i.targetTable)},
|
|
8711
8873
|
junctionTable: ${h(i.junctionTable)},
|
|
8712
8874
|
sourceField: ${h(i.sourceField??"")},
|
|
@@ -8719,7 +8881,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8719
8881
|
${t.map(n=>` ${n}`).join(`
|
|
8720
8882
|
`)}
|
|
8721
8883
|
} as const;
|
|
8722
|
-
`}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)}: {
|
|
8723
8885
|
kind: "one",
|
|
8724
8886
|
targetTable: ${h(i.targetTable)},
|
|
8725
8887
|
sourceField: ${h(i.field??"")},
|
|
@@ -8745,7 +8907,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8745
8907
|
${t.map(n=>` ${n}`).join(`
|
|
8746
8908
|
`)}
|
|
8747
8909
|
} as const;
|
|
8748
|
-
`}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(
|
|
8749
8911
|
${h(l)},
|
|
8750
8912
|
{
|
|
8751
8913
|
${u.join(`
|
|
@@ -8758,7 +8920,7 @@ ${c.join(`,
|
|
|
8758
8920
|
);`):a.push(`export const ${i} = table(${h(l)}, {
|
|
8759
8921
|
${u.join(`
|
|
8760
8922
|
`)}
|
|
8761
|
-
});`);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}, {
|
|
8762
8924
|
fields: [${i}.${x.sourceField}],
|
|
8763
8925
|
references: [${m.targetTable}.${x.targetField}],
|
|
8764
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 }) => ({
|
|
@@ -8767,7 +8929,7 @@ ${w.join(`
|
|
|
8767
8929
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
8768
8930
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
8769
8931
|
import { relations } from "drizzle-orm";
|
|
8770
|
-
${
|
|
8932
|
+
${Cr(r)}
|
|
8771
8933
|
${a.join(`
|
|
8772
8934
|
|
|
8773
8935
|
`)}
|
|
@@ -8776,10 +8938,10 @@ ${o.join(`
|
|
|
8776
8938
|
|
|
8777
8939
|
`)}
|
|
8778
8940
|
|
|
8779
|
-
${
|
|
8941
|
+
${Ir(e)}
|
|
8780
8942
|
|
|
8781
|
-
${
|
|
8782
|
-
`}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({
|
|
8783
8945
|
${o.join(`
|
|
8784
8946
|
`)}
|
|
8785
8947
|
});
|
|
@@ -8793,7 +8955,7 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
8793
8955
|
`);}return `import { z } from "zod";
|
|
8794
8956
|
|
|
8795
8957
|
${t.join(`
|
|
8796
|
-
`)}`}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} = {
|
|
8797
8959
|
${o.join(`
|
|
8798
8960
|
`)}
|
|
8799
8961
|
};
|
|
@@ -8804,11 +8966,12 @@ ${i.join(`
|
|
|
8804
8966
|
};`);}return `${t.join(`
|
|
8805
8967
|
|
|
8806
8968
|
`)}
|
|
8807
|
-
`}function Cr(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=resolve(e.configDir,t.entry),a=resolve(e.configDir,t.outFile??resolve(e.outDirAbs,"schema.compiled.ts")),o=resolve(e.configDir,t.typesOutFile??resolve(e.outDirAbs,"schema.types.ts")),i=resolve(e.configDir,t.zodOutFile??resolve(e.outDirAbs,"schema.zod.ts")),l=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),u=Cr(l,t.exportName),c=br(u);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(dirname(i),{recursive:true})]);let f=Ar(c,n),d=qr(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 Mr(e){return e.replaceAll("\\","/")}function A(e,t){let n=Mr(relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Er=new Set([".ts",".tsx",".mts",".cts"]);async function an(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await an(a));continue}r.isFile()&&Er.has(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.isCallExpression(n);){let i=n.expression;if(!g.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.isStringLiteral(l)||g.isNumericLiteral(l)?a=l.text:l.kind===g.SyntaxKind.TrueKeyword?a="true":l.kind===g.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.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g.isPropertyAssignment(r)&&g.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)||n.push(Or(r.initializer,r.name.text));return n}function Vr(e){return g.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g.SyntaxKind.ExportKeyword)??false:false}function on(e){return g.isIdentifier(e)?e.text:g.isParenthesizedExpression(e)?on(e.expression):null}function Br(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g.isPropertyAssignment(t))return [];let n=t.initializer;return g.isStringLiteral(n)||g.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g.isArrayLiteralExpression(n)?n.elements.map(r=>g.isStringLiteral(r)||g.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Hr(e,t){let n=g.createSourceFile(t,e,g.ScriptTarget.Latest,true,g.ScriptKind.TS),r=[];for(let a of n.statements)if(Vr(a))for(let o of a.declarationList.declarations){if(!g.isIdentifier(o.name)||!o.initializer||!g.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"?Br(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 Wr(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=relative(e.scanDirAbs,a),l=Hr(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=Wr(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(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 zr(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=zr(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 readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await 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=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=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=resolve(t,"client"),l=A(s,a);await Promise.all([mkdir(t,{recursive:true}),mkdir(s,{recursive:true}),mkdir(n,{recursive:true})]);let u=resolve(t,"server.ts"),c=resolve(t,"client.ts"),f=resolve(t,"auth.config.ts"),d=resolve(t,"auth.schema.ts"),b=resolve(t,"drizzle.config.ts"),w=resolve(n,"wrangler.json"),y=await en(e),m=await un(e,y?[y.schemaPath]:[]),x=A(t,m.schemaPath),T=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),vn=ce(l,T),Tn=H(x,T,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,T),Nn=_t(x,m,T),$n=resolve(t,"admin.routes.ts"),qn=Tn.map(k=>Bun.write(resolve(t,k.relativePath),k.source)),Cn=vn.map(k=>Bun.write(resolve(t,k.relativePath),k.source));await Promise.all([Bun.write(u,R),Bun.write(c,`export * from "./client/index";
|
|
8808
|
-
`),...
|
|
8809
|
-
`),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=resolve(e.configDir,t.entry),a=resolve(e.configDir,t.outFile??resolve(e.outDirAbs,"schema.compiled.ts")),o=resolve(e.configDir,t.typesOutFile??resolve(e.outDirAbs,"schema.types.ts")),i=resolve(e.configDir,t.zodOutFile??resolve(e.outDirAbs,"schema.zod.ts")),l=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),u=jr(l,t.exportName),c=Ar(u);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(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(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 readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await dn(a));continue}r.isFile()&&Lr.has(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.isCallExpression(n);){let i=n.expression;if(!g.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.isStringLiteral(l)||g.isNumericLiteral(l)?a=l.text:l.kind===g.SyntaxKind.TrueKeyword?a="true":l.kind===g.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.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g.isPropertyAssignment(r)&&g.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)||n.push(Ur(r.initializer,r.name.text));return n}function _r(e){return g.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g.SyntaxKind.ExportKeyword)??false:false}function pn(e){return g.isIdentifier(e)?e.text:g.isParenthesizedExpression(e)?pn(e.expression):null}function Kr(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g.isPropertyAssignment(t))return [];let n=t.initializer;return g.isStringLiteral(n)||g.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g.isArrayLiteralExpression(n)?n.elements.map(r=>g.isStringLiteral(r)||g.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Gr(e,t){let n=g.createSourceFile(t,e,g.ScriptTarget.Latest,true,g.ScriptKind.TS),r=[];for(let a of n.statements)if(_r(a))for(let o of a.declarationList.declarations){if(!g.isIdentifier(o.name)||!o.initializer||!g.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=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(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 readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await 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=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=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=resolve(t,"client"),l=A(s,a);await Promise.all([mkdir(t,{recursive:true}),mkdir(s,{recursive:true}),mkdir(n,{recursive:true})]);let u=resolve(t,"server.ts"),c=resolve(t,"client.ts"),f=resolve(t,"auth.config.ts"),d=resolve(t,"auth.schema.ts"),b=resolve(t,"drizzle.config.ts"),w=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=resolve(t,"admin.routes.ts"),En=$n.map(v=>Bun.write(resolve(t,v.relativePath),v.source)),Dn=Nn.map(v=>Bun.write(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=relative(o,f).replace(/\\/g,"/"),On=V.startsWith(".")?V:`./${V}`,W=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=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 readdir(v,{withFileTypes:true});for(let $ of M){let I=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 rm(I);}}await se(o);let Wn=resolve(o,"tsconfig.json");if(e.config.build&&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=z$1.object({binding:z$1.string().min(1),databaseName:z$1.string().min(1),databaseId:z$1.string().min(1),previewDatabaseId:z$1.string().min(1).optional(),migrationsDir:z$1.string().min(1).optional()}).strict(),wn=z$1.object({binding:z$1.string().min(1),id:z$1.string().min(1),previewId:z$1.string().min(1).optional()}).strict(),xn=z$1.object({binding:z$1.string().min(1),bucketName:z$1.string().min(1),previewBucketName:z$1.string().min(1).optional(),jurisdiction:z$1.string().min(1).optional()}).strict(),Tn=z$1.object({enabled:z$1.boolean().optional(),binding:z$1.string().min(1).optional(),queue:z$1.string().min(1).optional()}).strict(),da=z$1.object({enabled:z$1.boolean().optional(),binding:z$1.string().min(1).optional(),className:z$1.string().min(1).optional(),objectName:z$1.string().min(1).optional(),subscribePath:z$1.string().min(1).optional(),websocketPath:z$1.string().min(1).optional(),protocol:z$1.string().min(1).optional()}).strict(),pa=z$1.object({scanDir:z$1.string().min(1),outDir:z$1.string().min(1),wranglerOutDir:z$1.string().min(1).optional(),wranglerOutPath:z$1.string().min(1).optional(),schema:z$1.array(z$1.string()).min(1),schemaDsl:z$1.object({entry:z$1.string().min(1),exportName:z$1.string().min(1).optional(),outFile:z$1.string().min(1).optional(),typesOutFile:z$1.string().min(1).optional(),zodOutFile:z$1.string().min(1).optional(),namingStrategy:z$1.literal("camelToSnake").optional()}).strict().optional(),database:z$1.union([bn,z$1.array(bn).min(1)]),kv:z$1.union([wn,z$1.array(wn)]).optional(),r2:z$1.union([xn,z$1.array(xn)]).optional(),auth:z$1.object({enabled:z$1.boolean(),basePath:z$1.string().min(1),options:z$1.custom(e=>typeof e=="object"&&e!==null),clientOptions:z$1.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:Tn.optional(),realtime:da.optional(),wranglerOverrides:z$1.record(z$1.string(),z$1.unknown()).optional(),build:z$1.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=isAbsolute(e??"")?e:resolve(process.cwd(),e??"appflare.config.ts"),n=dirname(t),o=(await import(pathToFileURL(t).href)).default,i=pa.parse(o),s=fa(i);return {configPath:t,configDir:n,scanDirAbs:resolve(n,s.scanDir),outDirAbs:resolve(n,s.outDir),wranglerOutDirAbs:resolve(n,s.wranglerOutDir),config:s}}function wa(e){let t=e;for(;;){if(existsSync(resolve(t,"package.json")))return t;let n=dirname(t);if(n===t)return e;t=n;}}async function 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}
|
|
8810
8973
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
8811
|
-
`);}async function
|
|
8812
|
-
`);}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.watch(n.scanDirAbs,{ignoreInitial:true}).on("all",async(s,l)=>{process.stdout.write(`\u{1F504} Change detected: ${l}
|
|
8813
8976
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
8814
|
-
`);}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=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 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);});
|