appflare 0.2.40 → 0.2.42
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 +108 -4
- package/cli/schema-compiler.ts +2 -0
- package/cli/templates/dashboard/builders/functions/tree-builder.ts +47 -0
- package/cli/templates/dashboard/builders/navigation.ts +55 -22
- package/cli/templates/dashboard/components/layout.ts +33 -1
- package/cli/templates/handlers/generators/types/query-definitions/filter-and-where-types.ts +22 -2
- package/cli/templates/handlers/generators/types/query-runtime/runtime-write.ts +275 -14
- package/dist/cli/index.js +700 -375
- package/dist/cli/index.mjs +700 -375
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/schema.ts +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
'use strict';var commander=require('commander'),
|
|
2
|
+
'use strict';var commander=require('commander'),Ia=require('chokidar'),fs=require('fs'),path=require('path'),promises=require('fs/promises'),url=require('url'),g=require('typescript'),zod=require('zod');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ia__default=/*#__PURE__*/_interopDefault(Ia);var g__namespace=/*#__PURE__*/_interopNamespace(g);function xe(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 Te(){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
61
61
|
import type {
|
|
62
62
|
AppflareAuth,
|
|
63
63
|
AppflareAuthTokenResolver,
|
|
@@ -166,21 +166,21 @@ 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 rr(e){let n=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(n)?`_${n}`:n||"_route"}function ve(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function ar(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function Re(e){let n={children:new Map};for(let t of e){let r=n;for(let a of t.segments){let o=r.children.get(a);o||(o={children:new Map},r.children.set(a,o)),r=o;}r.operation=t;}return n}function J(e,n=1){let t=" ".repeat(n),r=" ".repeat(n+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}${ar(i)}: ${J(s,n+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(`${t}}`),o.join(`
|
|
170
|
+
`)}function or(e,n){if(e.kind!=="query"&&e.kind!=="mutation")return null;let t=e.clientSegments&&e.clientSegments.length>0?e.clientSegments:e.routePath.replace(/^\//,"").split("/").filter(Boolean).slice(1);if(t.length>=2&&t[t.length-1]===t[t.length-2]&&t.pop(),t.length===0)return null;let r=rr(`op_${n}_${e.kind}_${t.join("_")}`);return {kind:e.kind,routePath:e.routePath,queryName:e.handlerName??t.join("/"),segments:t,importPath:e.clientImportPath,exportName:e.exportName,alias:r,schemaConst:`${r}Schema`,typeBase:`${ve(e.kind)}${ve(t.join("_"))}`}}function ir(e){let n=`${e.typeBase}Input`,t=`${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
|
-
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${
|
|
173
|
-
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${
|
|
174
|
-
...params: AppflareRunParams<${
|
|
172
|
+
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${t}> => {
|
|
173
|
+
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${t}>["run"] = async (
|
|
174
|
+
...params: AppflareRunParams<${n}>
|
|
175
175
|
) => {
|
|
176
|
-
const { args, options } = resolveRunParams<${
|
|
176
|
+
const { args, options } = resolveRunParams<${n}>(params);
|
|
177
177
|
const mergedOptions = mergeRouteOptions(runtime.options, options);
|
|
178
178
|
const resultOptions: AppflareRouteCallOptions<"return"> = {
|
|
179
179
|
...(mergedOptions ?? {}),
|
|
180
180
|
errorMode: "return",
|
|
181
181
|
};
|
|
182
182
|
const parsed = ${e.schemaConst}.parse(args);
|
|
183
|
-
return requestRoute<${
|
|
183
|
+
return requestRoute<${t}>(runtime.endpoint, {
|
|
184
184
|
route: ${JSON.stringify(e.routePath)},
|
|
185
185
|
method: ${JSON.stringify(a)},
|
|
186
186
|
input: parsed,
|
|
@@ -195,7 +195,7 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
195
195
|
args,
|
|
196
196
|
requestOptions,
|
|
197
197
|
signal,
|
|
198
|
-
}: AppflareQuerySubscribeOptions<${
|
|
198
|
+
}: AppflareQuerySubscribeOptions<${n}, ${t}>): AppflareRealtimeSubscription => {
|
|
199
199
|
const mergedOptions = mergeRouteOptions(runtime.options, requestOptions);
|
|
200
200
|
const parsedArgs = ${e.schemaConst}.parse(normalizeRouteInput(args));
|
|
201
201
|
const requestAuthToken = resolveRealtimeAuthToken(authToken, mergedOptions?.headers);
|
|
@@ -299,8 +299,8 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
299
299
|
const payload = (message as { payload?: unknown }).payload;
|
|
300
300
|
if (typeof payload === "object" && payload !== null && "data" in payload) {
|
|
301
301
|
onChange(
|
|
302
|
-
(payload as { data: ${
|
|
303
|
-
message as AppflareRealtimeQueryUpdate<${
|
|
302
|
+
(payload as { data: ${t} }).data,
|
|
303
|
+
message as AppflareRealtimeQueryUpdate<${t}>,
|
|
304
304
|
);
|
|
305
305
|
}
|
|
306
306
|
}
|
|
@@ -329,18 +329,18 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
329
329
|
};
|
|
330
330
|
};`:`const ${e.alias}Route = (
|
|
331
331
|
runtime: RequestRuntime,
|
|
332
|
-
): AppflareRouteClient<typeof ${e.schemaConst}, ${
|
|
333
|
-
const run: AppflareRouteClient<typeof ${e.schemaConst}, ${
|
|
334
|
-
...params: AppflareRunParams<${
|
|
332
|
+
): AppflareRouteClient<typeof ${e.schemaConst}, ${t}> => {
|
|
333
|
+
const run: AppflareRouteClient<typeof ${e.schemaConst}, ${t}>["run"] = async (
|
|
334
|
+
...params: AppflareRunParams<${n}>
|
|
335
335
|
) => {
|
|
336
|
-
const { args, options } = resolveRunParams<${
|
|
336
|
+
const { args, options } = resolveRunParams<${n}>(params);
|
|
337
337
|
const mergedOptions = mergeRouteOptions(runtime.options, options);
|
|
338
338
|
const resultOptions: AppflareRouteCallOptions<"return"> = {
|
|
339
339
|
...(mergedOptions ?? {}),
|
|
340
340
|
errorMode: "return",
|
|
341
341
|
};
|
|
342
342
|
const parsed = ${e.schemaConst}.parse(args);
|
|
343
|
-
return requestRoute<${
|
|
343
|
+
return requestRoute<${t}>(runtime.endpoint, {
|
|
344
344
|
route: ${JSON.stringify(e.routePath)},
|
|
345
345
|
method: ${JSON.stringify(a)},
|
|
346
346
|
input: parsed,
|
|
@@ -353,15 +353,15 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
353
353
|
schema: ${r},
|
|
354
354
|
run,
|
|
355
355
|
};
|
|
356
|
-
};`}function G(e){let
|
|
357
|
-
`),o=
|
|
358
|
-
export type ${
|
|
356
|
+
};`}function G(e){let n=e.map((l,c)=>or(l,c)).filter(l=>l!==null),t=n.filter(l=>l.kind==="query"),r=n.filter(l=>l.kind==="mutation"),a=n.map(l=>`import { ${l.exportName} as ${l.alias} } from "${l.importPath}";`).join(`
|
|
357
|
+
`),o=n.map(l=>{let c=`${l.typeBase}Input`,p=`${l.typeBase}Output`,d=`${l.typeBase}Schema`;return `const ${l.schemaConst} = z.object(${l.alias}.definition.args);
|
|
358
|
+
export type ${c} = z.input<typeof ${l.schemaConst}>;
|
|
359
359
|
export type ${p} = Awaited<ReturnType<typeof ${l.alias}.definition.handler>>;
|
|
360
360
|
export const ${d} = ${l.schemaConst};`}).join(`
|
|
361
361
|
|
|
362
|
-
`),i=
|
|
362
|
+
`),i=n.map(l=>ir(l)).join(`
|
|
363
363
|
|
|
364
|
-
`),s=J(
|
|
364
|
+
`),s=J(Re(t)),u=J(Re(r));return `import { z } from "zod";
|
|
365
365
|
import type {
|
|
366
366
|
AppflareErrorMode,
|
|
367
367
|
AppflareRequestError,
|
|
@@ -732,16 +732,16 @@ export function createMutationsClient(
|
|
|
732
732
|
options,
|
|
733
733
|
};
|
|
734
734
|
|
|
735
|
-
return ${
|
|
735
|
+
return ${u} as const;
|
|
736
736
|
}
|
|
737
737
|
|
|
738
738
|
export type QueriesClient = ReturnType<typeof createQueriesClient>;
|
|
739
739
|
export type MutationsClient = ReturnType<typeof createMutationsClient>;
|
|
740
|
-
`}function
|
|
740
|
+
`}function ke(){return `export * from "./types";
|
|
741
741
|
export * from "./appflare";
|
|
742
742
|
export * from "./storage";
|
|
743
743
|
export * from "./handlers";
|
|
744
|
-
`}function
|
|
744
|
+
`}function Se(){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 Ae(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 Ne(e,n){return [{relativePath:"client/index.ts",source:ke()},{relativePath:"client/types.ts",source:Ae(e)},{relativePath:"client/storage.ts",source:Se()},{relativePath:"client/handlers.ts",source:G(n)},{relativePath:"client/appflare.ts",source:Te()}]}function $e(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 Ce(){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 qe(){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 Fe(){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 Me(){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 Ie(){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 Ee(){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 Pe(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 je(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
|
-
${
|
|
1484
|
-
|
|
1485
|
-
${Ne()}
|
|
1483
|
+
${qe()}
|
|
1486
1484
|
|
|
1487
1485
|
${Ce()}
|
|
1488
1486
|
|
|
1489
|
-
${qe()}
|
|
1490
|
-
|
|
1491
1487
|
${Fe()}
|
|
1492
1488
|
|
|
1493
1489
|
${Me()}
|
|
1494
1490
|
|
|
1495
|
-
${Ie(
|
|
1496
|
-
|
|
1491
|
+
${Ie()}
|
|
1492
|
+
|
|
1493
|
+
${Ee()}
|
|
1494
|
+
|
|
1495
|
+
${Pe(e)}
|
|
1496
|
+
`}function Oe(){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 De(){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
|
+
${Oe()}
|
|
1545
|
+
`}function Ve(){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 Be(){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>>;
|
|
@@ -1692,7 +1692,7 @@ type FieldOperators<T, TFieldKey extends string = string> = {
|
|
|
1692
1692
|
lte?: Comparable<T>;
|
|
1693
1693
|
exists?: boolean;
|
|
1694
1694
|
regex?: RegexOperand<T>;
|
|
1695
|
-
options?: string;
|
|
1695
|
+
$options?: string;
|
|
1696
1696
|
geoWithin?: GeoWithinOperandForField<TFieldKey>;
|
|
1697
1697
|
includes?: T extends ReadonlyArray<infer E> ? ReadonlyArray<E> : never;
|
|
1698
1698
|
includesAny?: T extends ReadonlyArray<infer E> ? ReadonlyArray<E> : never;
|
|
@@ -1904,16 +1904,36 @@ export type QueryInsertArgs<TName extends TableName> = {
|
|
|
1904
1904
|
};
|
|
1905
1905
|
|
|
1906
1906
|
export type QueryUpdateArgs<TName extends TableName> = {
|
|
1907
|
-
set: Partial<TableInsertModel<TName
|
|
1907
|
+
set: Partial<TableInsertModel<TName>> & ManyToManyUpdateSetFields<TName>;
|
|
1908
1908
|
where?: WhereInput<TableModel<TName>, TName>;
|
|
1909
1909
|
limit?: number;
|
|
1910
1910
|
};
|
|
1911
1911
|
|
|
1912
|
+
type ManyToManyUpdateSetFields<TName extends TableName> = {
|
|
1913
|
+
[TRelationName in RuntimeRelationName<TName>]?: RuntimeRelationKind<TName, TRelationName> extends "manyToMany"
|
|
1914
|
+
? ManyToManyUpdateInput<TName, TRelationName>
|
|
1915
|
+
: never;
|
|
1916
|
+
};
|
|
1917
|
+
|
|
1918
|
+
type ManyToManyUpdateInput<
|
|
1919
|
+
TSourceTable extends TableName,
|
|
1920
|
+
TRelationName extends RuntimeRelationName<TSourceTable>,
|
|
1921
|
+
> = {
|
|
1922
|
+
items: Array<ManyToManyUpdateItem<TargetTableForRelation<TSourceTable, TRelationName>>>;
|
|
1923
|
+
mode?: "merge" | "overwrite";
|
|
1924
|
+
};
|
|
1925
|
+
|
|
1926
|
+
type ManyToManyUpdateItem<TTargetTable extends TableName> =
|
|
1927
|
+
| ("id" extends keyof TableModel<TTargetTable>
|
|
1928
|
+
? TableModel<TTargetTable>["id"]
|
|
1929
|
+
: never)
|
|
1930
|
+
| Partial<TableInsertModel<TTargetTable>>;
|
|
1931
|
+
|
|
1912
1932
|
export type QueryDeleteArgs<TName extends TableName> = {
|
|
1913
1933
|
where?: WhereInput<TableModel<TName>, TName>;
|
|
1914
1934
|
limit?: number;
|
|
1915
1935
|
};
|
|
1916
|
-
`}function
|
|
1936
|
+
`}function We(){return `type AggregateWithInput<TName extends TableName> =
|
|
1917
1937
|
QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1918
1938
|
|
|
1919
1939
|
type NumericFieldKey<TName extends TableName> = NumericModelFieldKey<
|
|
@@ -2045,7 +2065,7 @@ export type DbMutationEvent = {
|
|
|
2045
2065
|
export type QueryDbOptions = {
|
|
2046
2066
|
onMutation?: (event: DbMutationEvent) => void;
|
|
2047
2067
|
};
|
|
2048
|
-
`}function
|
|
2068
|
+
`}function He(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2049
2069
|
return typeof value === "object" && value !== null;
|
|
2050
2070
|
}
|
|
2051
2071
|
|
|
@@ -3424,7 +3444,7 @@ function inferConflictTarget(table: unknown): string[] {
|
|
|
3424
3444
|
|
|
3425
3445
|
return [];
|
|
3426
3446
|
}
|
|
3427
|
-
`}function
|
|
3447
|
+
`}function Le(){return `const mergedSchema = {
|
|
3428
3448
|
...authSchema,
|
|
3429
3449
|
...schema,
|
|
3430
3450
|
};
|
|
@@ -3699,9 +3719,9 @@ type TableFindFirstResult<
|
|
|
3699
3719
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3700
3720
|
(typeof mergedSchema)[TName]
|
|
3701
3721
|
>;
|
|
3702
|
-
`}function
|
|
3722
|
+
`}function ze(){return [Le(),Be(),We(),He()].join(`
|
|
3703
3723
|
|
|
3704
|
-
`)}function
|
|
3724
|
+
`)}function Ue(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3705
3725
|
const withValue = args?.with;
|
|
3706
3726
|
const pathSegments = args?.field
|
|
3707
3727
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -3872,7 +3892,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3872
3892
|
},
|
|
3873
3893
|
}) as AppflareQueryDb;
|
|
3874
3894
|
}
|
|
3875
|
-
`}function
|
|
3895
|
+
`}function Qe(){return `export class AppflareHandledError extends Error {
|
|
3876
3896
|
public readonly status: number;
|
|
3877
3897
|
public readonly payload: unknown;
|
|
3878
3898
|
|
|
@@ -3882,7 +3902,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3882
3902
|
this.payload = payload;
|
|
3883
3903
|
}
|
|
3884
3904
|
}
|
|
3885
|
-
`}function
|
|
3905
|
+
`}function _e(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
3886
3906
|
const where = isRecord(args?.where)
|
|
3887
3907
|
? (args?.where as Record<string, unknown>)
|
|
3888
3908
|
: undefined;
|
|
@@ -4036,7 +4056,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4036
4056
|
);
|
|
4037
4057
|
});
|
|
4038
4058
|
},
|
|
4039
|
-
`}function
|
|
4059
|
+
`}function Ke(){return `export function createQueryDb(
|
|
4040
4060
|
$db: AppflareDb,
|
|
4041
4061
|
options?: QueryDbOptions,
|
|
4042
4062
|
): AppflareQueryDb {
|
|
@@ -4078,7 +4098,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4078
4098
|
};
|
|
4079
4099
|
|
|
4080
4100
|
const tableApi = {
|
|
4081
|
-
`}function
|
|
4101
|
+
`}function Je(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
4082
4102
|
const transaction = ($db as any).transaction;
|
|
4083
4103
|
|
|
4084
4104
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -4640,6 +4660,8 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4640
4660
|
return rows;
|
|
4641
4661
|
},
|
|
4642
4662
|
update: async (args: QueryUpdateArgs<TableName>) => {
|
|
4663
|
+
const transaction = ($db as any).transaction;
|
|
4664
|
+
|
|
4643
4665
|
const whereFilter = buildWhereFilter(
|
|
4644
4666
|
table,
|
|
4645
4667
|
args.where as Record<string, unknown> | undefined,
|
|
@@ -4648,27 +4670,286 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4648
4670
|
|
|
4649
4671
|
const setPayload = args.set as Record<string, unknown>;
|
|
4650
4672
|
const cleanSetPayload: Record<string, unknown> = {};
|
|
4673
|
+
const relationPayloads: Array<{
|
|
4674
|
+
relationName: string;
|
|
4675
|
+
relation: RuntimeRelation;
|
|
4676
|
+
value: unknown;
|
|
4677
|
+
}> = [];
|
|
4678
|
+
|
|
4651
4679
|
for (const [key, value] of Object.entries(setPayload)) {
|
|
4652
|
-
if (value
|
|
4653
|
-
|
|
4680
|
+
if (value === undefined) continue;
|
|
4681
|
+
const runtimeRelation = getRuntimeRelation(tableName, key);
|
|
4682
|
+
if (runtimeRelation && runtimeRelation.kind === "manyToMany") {
|
|
4683
|
+
relationPayloads.push({
|
|
4684
|
+
relationName: key,
|
|
4685
|
+
relation: runtimeRelation,
|
|
4686
|
+
value,
|
|
4687
|
+
});
|
|
4688
|
+
continue;
|
|
4654
4689
|
}
|
|
4690
|
+
cleanSetPayload[key] = value;
|
|
4655
4691
|
}
|
|
4656
4692
|
|
|
4657
|
-
|
|
4658
|
-
|
|
4659
|
-
|
|
4693
|
+
const normalizeRelationValue = (
|
|
4694
|
+
value: unknown,
|
|
4695
|
+
): { items: unknown[]; mode: "merge" | "overwrite" } => {
|
|
4696
|
+
if (Array.isArray(value)) {
|
|
4697
|
+
return { items: value, mode: "merge" };
|
|
4698
|
+
}
|
|
4699
|
+
if (value && typeof value === "object") {
|
|
4700
|
+
const record = value as Record<string, unknown>;
|
|
4701
|
+
const items = Array.isArray(record.items) ? record.items : [];
|
|
4702
|
+
const mode = record.mode === "overwrite" ? "overwrite" : "merge";
|
|
4703
|
+
return { items, mode };
|
|
4704
|
+
}
|
|
4705
|
+
return { items: [], mode: "merge" };
|
|
4706
|
+
};
|
|
4707
|
+
|
|
4708
|
+
const executeUpdateWithRelations = async (
|
|
4709
|
+
tx: any,
|
|
4710
|
+
): Promise<Array<TableModel<TableName>>> => {
|
|
4711
|
+
let updateQuery: any = tx
|
|
4712
|
+
.update(table as any)
|
|
4713
|
+
.set(cleanSetPayload as any);
|
|
4660
4714
|
|
|
4661
|
-
|
|
4662
|
-
|
|
4663
|
-
|
|
4664
|
-
|
|
4665
|
-
|
|
4666
|
-
|
|
4667
|
-
|
|
4668
|
-
|
|
4715
|
+
if (whereFilter) {
|
|
4716
|
+
updateQuery = updateQuery.where(whereFilter);
|
|
4717
|
+
}
|
|
4718
|
+
if (
|
|
4719
|
+
typeof args.limit === "number" &&
|
|
4720
|
+
typeof updateQuery.limit === "function"
|
|
4721
|
+
) {
|
|
4722
|
+
updateQuery = updateQuery.limit(args.limit);
|
|
4723
|
+
}
|
|
4724
|
+
if (typeof updateQuery.returning === "function") {
|
|
4725
|
+
updateQuery = updateQuery.returning();
|
|
4726
|
+
}
|
|
4727
|
+
|
|
4728
|
+
const rows = (await updateQuery) as Array<TableModel<TableName>>;
|
|
4729
|
+
if (rows.length === 0) return rows;
|
|
4730
|
+
|
|
4731
|
+
for (const row of rows) {
|
|
4732
|
+
const parentId = (row as Record<string, unknown>)["id"];
|
|
4733
|
+
if (parentId === undefined || parentId === null) continue;
|
|
4734
|
+
|
|
4735
|
+
for (const { relationName, relation, value } of relationPayloads) {
|
|
4736
|
+
const { items, mode } = normalizeRelationValue(value);
|
|
4737
|
+
|
|
4738
|
+
const junctionTable = (mergedSchema as Record<string, unknown>)[
|
|
4739
|
+
relation.junctionTable
|
|
4740
|
+
];
|
|
4741
|
+
if (!junctionTable) {
|
|
4742
|
+
throw new Error(
|
|
4743
|
+
"Unknown junction table '" +
|
|
4744
|
+
relation.junctionTable +
|
|
4745
|
+
"' for relation '" +
|
|
4746
|
+
tableName +
|
|
4747
|
+
"." +
|
|
4748
|
+
relationName +
|
|
4749
|
+
"'.",
|
|
4750
|
+
);
|
|
4751
|
+
}
|
|
4752
|
+
|
|
4753
|
+
const sourceField = relation.sourceField;
|
|
4754
|
+
const targetField = relation.targetField;
|
|
4755
|
+
if (!sourceField || !targetField) {
|
|
4756
|
+
throw new Error(
|
|
4757
|
+
"Relation '" +
|
|
4758
|
+
tableName +
|
|
4759
|
+
"." +
|
|
4760
|
+
relationName +
|
|
4761
|
+
"' is missing junction metadata fields.",
|
|
4762
|
+
);
|
|
4763
|
+
}
|
|
4764
|
+
|
|
4765
|
+
const parentReferenceField = relation.referenceField ?? "id";
|
|
4766
|
+
const parentReferenceColumn = (table as Record<string, unknown>)[parentReferenceField];
|
|
4767
|
+
if (!parentReferenceColumn) {
|
|
4768
|
+
throw new Error(
|
|
4769
|
+
"Table '" +
|
|
4770
|
+
tableName +
|
|
4771
|
+
"' is missing column '" +
|
|
4772
|
+
parentReferenceField +
|
|
4773
|
+
"' for relation '" +
|
|
4774
|
+
relationName +
|
|
4775
|
+
"'.",
|
|
4776
|
+
);
|
|
4777
|
+
}
|
|
4778
|
+
|
|
4779
|
+
const junctionSourceColumn = (junctionTable as Record<string, unknown>)[sourceField];
|
|
4780
|
+
if (!junctionSourceColumn) {
|
|
4781
|
+
throw new Error(
|
|
4782
|
+
"Junction table '" +
|
|
4783
|
+
relation.junctionTable +
|
|
4784
|
+
"' is missing column '" +
|
|
4785
|
+
sourceField +
|
|
4786
|
+
"' for relation '" +
|
|
4787
|
+
relationName +
|
|
4788
|
+
"'.",
|
|
4789
|
+
);
|
|
4790
|
+
}
|
|
4791
|
+
|
|
4792
|
+
if (mode === "overwrite") {
|
|
4793
|
+
await tx
|
|
4794
|
+
.delete(junctionTable as any)
|
|
4795
|
+
.where(eq(junctionSourceColumn as any, (row as Record<string, unknown>)[parentReferenceField] as any));
|
|
4796
|
+
}
|
|
4797
|
+
|
|
4798
|
+
const referenceField = relation.targetReferenceField ?? "id";
|
|
4799
|
+
const targetTable = (mergedSchema as Record<string, unknown>)[
|
|
4800
|
+
relation.targetTable
|
|
4801
|
+
];
|
|
4802
|
+
|
|
4803
|
+
const junctionTargetColumn =
|
|
4804
|
+
(junctionTable as Record<string, unknown>)[targetField];
|
|
4805
|
+
if (!junctionTargetColumn) {
|
|
4806
|
+
throw new Error(
|
|
4807
|
+
"Junction table '" +
|
|
4808
|
+
relation.junctionTable +
|
|
4809
|
+
"' is missing column '" +
|
|
4810
|
+
targetField +
|
|
4811
|
+
"'.",
|
|
4812
|
+
);
|
|
4813
|
+
}
|
|
4814
|
+
|
|
4815
|
+
for (const item of items) {
|
|
4816
|
+
let targetId: unknown;
|
|
4817
|
+
|
|
4818
|
+
if (
|
|
4819
|
+
typeof item === "string" ||
|
|
4820
|
+
typeof item === "number" ||
|
|
4821
|
+
typeof item === "bigint"
|
|
4822
|
+
) {
|
|
4823
|
+
targetId = item;
|
|
4824
|
+
} else if (item && typeof item === "object") {
|
|
4825
|
+
const record = item as Record<string, unknown>;
|
|
4826
|
+
const existingId = record[referenceField];
|
|
4827
|
+
if (existingId !== undefined && existingId !== null) {
|
|
4828
|
+
targetId = existingId;
|
|
4829
|
+
} else {
|
|
4830
|
+
if (!targetTable) {
|
|
4831
|
+
throw new Error(
|
|
4832
|
+
"Unknown target table '" +
|
|
4833
|
+
relation.targetTable +
|
|
4834
|
+
"' for relation '" +
|
|
4835
|
+
tableName +
|
|
4836
|
+
"." +
|
|
4837
|
+
relationName +
|
|
4838
|
+
"'.",
|
|
4839
|
+
);
|
|
4840
|
+
}
|
|
4841
|
+
let createQuery: any = tx
|
|
4842
|
+
.insert(targetTable as any)
|
|
4843
|
+
.values(record as any);
|
|
4844
|
+
if (typeof createQuery.returning === "function") {
|
|
4845
|
+
createQuery = createQuery.returning();
|
|
4846
|
+
}
|
|
4847
|
+
const createdRows =
|
|
4848
|
+
(await createQuery) as Array<Record<string, unknown>>;
|
|
4849
|
+
const created = createdRows[0];
|
|
4850
|
+
if (!created) {
|
|
4851
|
+
throw new Error(
|
|
4852
|
+
"Failed to create relation target for '" +
|
|
4853
|
+
tableName +
|
|
4854
|
+
"." +
|
|
4855
|
+
relationName +
|
|
4856
|
+
"'.",
|
|
4857
|
+
);
|
|
4858
|
+
}
|
|
4859
|
+
targetId = created[referenceField];
|
|
4860
|
+
if (targetId === undefined || targetId === null) {
|
|
4861
|
+
throw new Error(
|
|
4862
|
+
"Created relation target for '" +
|
|
4863
|
+
tableName +
|
|
4864
|
+
"." +
|
|
4865
|
+
relationName +
|
|
4866
|
+
"' is missing '" +
|
|
4867
|
+
referenceField +
|
|
4868
|
+
"'.",
|
|
4869
|
+
);
|
|
4870
|
+
}
|
|
4871
|
+
}
|
|
4872
|
+
} else {
|
|
4873
|
+
throw new Error(
|
|
4874
|
+
"Relation '" +
|
|
4875
|
+
tableName +
|
|
4876
|
+
"." +
|
|
4877
|
+
relationName +
|
|
4878
|
+
"' expects an id or object payload.",
|
|
4879
|
+
);
|
|
4880
|
+
}
|
|
4881
|
+
|
|
4882
|
+
if (mode === "merge") {
|
|
4883
|
+
const parentRefValue = (row as Record<string, unknown>)[parentReferenceField];
|
|
4884
|
+
const existingLinks = await tx
|
|
4885
|
+
.select()
|
|
4886
|
+
.from(junctionTable as any)
|
|
4887
|
+
.where(
|
|
4888
|
+
and(
|
|
4889
|
+
eq(junctionSourceColumn as any, parentRefValue as any),
|
|
4890
|
+
eq(junctionTargetColumn as any, targetId as any),
|
|
4891
|
+
),
|
|
4892
|
+
);
|
|
4893
|
+
if (existingLinks.length > 0) continue;
|
|
4894
|
+
}
|
|
4895
|
+
|
|
4896
|
+
const parentRefValue = (row as Record<string, unknown>)[parentReferenceField];
|
|
4897
|
+
await tx.insert(junctionTable as any).values({
|
|
4898
|
+
[sourceField]: parentRefValue,
|
|
4899
|
+
[targetField]: targetId,
|
|
4900
|
+
} as any);
|
|
4901
|
+
}
|
|
4902
|
+
}
|
|
4903
|
+
}
|
|
4904
|
+
|
|
4905
|
+
return rows;
|
|
4906
|
+
};
|
|
4907
|
+
|
|
4908
|
+
let rows: Array<TableModel<TableName>>;
|
|
4909
|
+
if (relationPayloads.length > 0) {
|
|
4910
|
+
if (typeof transaction === "function") {
|
|
4911
|
+
try {
|
|
4912
|
+
rows = await transaction.call($db, (tx: any) =>
|
|
4913
|
+
executeUpdateWithRelations(tx),
|
|
4914
|
+
);
|
|
4915
|
+
} catch (error) {
|
|
4916
|
+
const message =
|
|
4917
|
+
error instanceof Error ? error.message : String(error);
|
|
4918
|
+
const lowered = message.toLowerCase();
|
|
4919
|
+
if (
|
|
4920
|
+
lowered.includes("failed query: begin") ||
|
|
4921
|
+
lowered.includes('near "begin"') ||
|
|
4922
|
+
lowered.includes("cannot start a transaction")
|
|
4923
|
+
) {
|
|
4924
|
+
rows = await executeUpdateWithRelations($db as any);
|
|
4925
|
+
} else {
|
|
4926
|
+
throw error;
|
|
4927
|
+
}
|
|
4928
|
+
}
|
|
4929
|
+
} else {
|
|
4930
|
+
rows = await executeUpdateWithRelations($db as any);
|
|
4931
|
+
}
|
|
4932
|
+
} else {
|
|
4933
|
+
let updateQuery: any = ($db as any)
|
|
4934
|
+
.update(table as any)
|
|
4935
|
+
.set(cleanSetPayload as any);
|
|
4936
|
+
|
|
4937
|
+
if (whereFilter) {
|
|
4938
|
+
updateQuery = updateQuery.where(whereFilter);
|
|
4939
|
+
}
|
|
4940
|
+
if (
|
|
4941
|
+
typeof args.limit === "number" &&
|
|
4942
|
+
typeof updateQuery.limit === "function"
|
|
4943
|
+
) {
|
|
4944
|
+
updateQuery = updateQuery.limit(args.limit);
|
|
4945
|
+
}
|
|
4946
|
+
if (typeof updateQuery.returning === "function") {
|
|
4947
|
+
updateQuery = updateQuery.returning();
|
|
4948
|
+
}
|
|
4949
|
+
|
|
4950
|
+
rows = (await updateQuery) as Array<TableModel<TableName>>;
|
|
4669
4951
|
}
|
|
4670
4952
|
|
|
4671
|
-
const rows = (await updateQuery) as Array<TableModel<TableName>>;
|
|
4672
4953
|
emitMutation(
|
|
4673
4954
|
"update",
|
|
4674
4955
|
{
|
|
@@ -4772,17 +5053,17 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4772
5053
|
);
|
|
4773
5054
|
return rows;
|
|
4774
5055
|
},
|
|
4775
|
-
`}function
|
|
5056
|
+
`}function Ge(){return [Ke(),_e(),Je(),Ue(),Qe()].join(`
|
|
4776
5057
|
|
|
4777
|
-
`)}function
|
|
5058
|
+
`)}function Ze(e=[],n=[]){let t=n.map(i=>` ${i.name}?: ${i.tsType} | null;`).join(`
|
|
4778
5059
|
`),a=[e.length>0?[" role: UserRole;"," banned: boolean | null;"," banReason?: string | null | undefined;"," banExpires?: Date | null | undefined;"].join(`
|
|
4779
|
-
`):"",
|
|
5060
|
+
`):"",t].filter(Boolean).join(`
|
|
4780
5061
|
`);return `type AuthSession = typeof auth.$Infer.Session;
|
|
4781
5062
|
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
4782
5063
|
${e.length>0?`export type UserRole = ${e.map(i=>`"${i}"`).join(" | ")};
|
|
4783
5064
|
type User = import("better-auth").User & {
|
|
4784
5065
|
${a}
|
|
4785
|
-
};`:
|
|
5066
|
+
};`:n.length>0?`type User = import("better-auth").User & {
|
|
4786
5067
|
${a}
|
|
4787
5068
|
};`:'type User = import("better-auth").User;'}
|
|
4788
5069
|
type Session = AuthSession['session']
|
|
@@ -4871,7 +5152,7 @@ export type AppflareContext = {
|
|
|
4871
5152
|
storage: AppflareStorage;
|
|
4872
5153
|
error: (status: number, message: string, details?: unknown) => never;
|
|
4873
5154
|
};
|
|
4874
|
-
`}function
|
|
5155
|
+
`}function Xe(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
4875
5156
|
|
|
4876
5157
|
export type SchedulerEnqueueOptions = {
|
|
4877
5158
|
delaySeconds?: number;
|
|
@@ -5003,40 +5284,40 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
5003
5284
|
definition,
|
|
5004
5285
|
};
|
|
5005
5286
|
}
|
|
5006
|
-
`}function
|
|
5287
|
+
`}function Ye(e=[],n=[]){return [Ve(),ze(),Ge(),Ze(e,n),Xe()].join(`
|
|
5007
5288
|
|
|
5008
|
-
`)}function
|
|
5289
|
+
`)}function et(e,n=[],t=[]){return `import type { Context } from "hono";
|
|
5009
5290
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5010
5291
|
import { drizzle } from "drizzle-orm/d1";
|
|
5011
5292
|
import { z, type ZodRawShape } from "zod";
|
|
5012
5293
|
import * as authSchema from "./auth.schema";
|
|
5013
5294
|
import * as schema from "${e}";
|
|
5014
5295
|
|
|
5015
|
-
${
|
|
5016
|
-
`}function
|
|
5017
|
-
`)}function
|
|
5018
|
-
`)}function
|
|
5019
|
-
`)}function
|
|
5296
|
+
${Ye(n,t)}
|
|
5297
|
+
`}function sr(e){let n=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(n)?`_${n}`:n}function lr(e,n){let t=e.routePath.replace(/^\//,"").replace(/\//g,"_");return sr(`op_${n}_${t}`)}function ur(e){return e.map((n,t)=>({operation:n,index:t,alias:lr(n,t)}))}function cr(e){return e.map(({operation:n,alias:t})=>`import { ${n.exportName} as ${t} } from "${n.importPath}";`).join(`
|
|
5298
|
+
`)}function dr(e){return e.filter(({operation:n})=>n.kind==="query"||n.kind==="mutation").map(({alias:n})=>`const ${`${n}Schema`} = z.object(${n}.definition.args);`).join(`
|
|
5299
|
+
`)}function pr(e){return e.filter(({operation:n})=>n.kind==="scheduler").map(({alias:n})=>`const ${`${n}SchedulerSchema`} = ${n}.definition.args ? z.object(${n}.definition.args) : z.undefined();`).join(`
|
|
5300
|
+
`)}function mr(e){return e.filter(({operation:n})=>n.kind==="query").map(({operation:n,alias:t})=>{let r=`${t}Schema`;return `
|
|
5020
5301
|
app.get(
|
|
5021
|
-
"${
|
|
5302
|
+
"${n.routePath}",
|
|
5022
5303
|
sValidator("query", ${r}),
|
|
5023
5304
|
async (c) => {
|
|
5024
5305
|
const ctx = await createExecutionContext(c, options);
|
|
5025
5306
|
try {
|
|
5026
|
-
return await executeOperation(c, ${
|
|
5307
|
+
return await executeOperation(c, ${t}, c.req.valid("query"), ctx);
|
|
5027
5308
|
} catch (error) {
|
|
5028
5309
|
return handleOperationError(c, error, "Invalid query arguments");
|
|
5029
5310
|
}
|
|
5030
5311
|
},
|
|
5031
5312
|
);`}).join(`
|
|
5032
|
-
`)}function
|
|
5313
|
+
`)}function fr(e){return e.filter(({operation:n})=>n.kind==="mutation").map(({operation:n,alias:t})=>{let r=`${t}Schema`;return `
|
|
5033
5314
|
app.post(
|
|
5034
|
-
"${
|
|
5315
|
+
"${n.routePath}",
|
|
5035
5316
|
sValidator("json", ${r}),
|
|
5036
5317
|
async (c) => {
|
|
5037
5318
|
const ctx = await createExecutionContext(c, options);
|
|
5038
5319
|
try {
|
|
5039
|
-
const response = await executeOperation(c, ${
|
|
5320
|
+
const response = await executeOperation(c, ${t}, c.req.valid("json"), ctx);
|
|
5040
5321
|
await publishMutationEvents(c, options, ctx.mutationEvents);
|
|
5041
5322
|
return response;
|
|
5042
5323
|
} catch (error) {
|
|
@@ -5044,26 +5325,26 @@ import * as schema from "${e}";
|
|
|
5044
5325
|
}
|
|
5045
5326
|
},
|
|
5046
5327
|
);`}).join(`
|
|
5047
|
-
`)}function
|
|
5328
|
+
`)}function gr(e){return e.filter(({operation:n})=>n.kind==="query").map(({operation:n,alias:t})=>{let r=`${t}Schema`,a=n.handlerName??n.routePath;return `
|
|
5048
5329
|
${JSON.stringify(a)}: {
|
|
5049
|
-
definition: ${
|
|
5330
|
+
definition: ${t}.definition,
|
|
5050
5331
|
schema: ${r},
|
|
5051
5332
|
},`}).join(`
|
|
5052
|
-
`)}function
|
|
5333
|
+
`)}function hr(e){return e.filter(({operation:n})=>n.kind==="scheduler").map(({operation:n,alias:t})=>{let r=`${t}SchedulerSchema`,a=n.taskName??`${n.routePath}`;return `
|
|
5053
5334
|
${JSON.stringify(a)}: {
|
|
5054
|
-
definition: ${
|
|
5335
|
+
definition: ${t}.definition,
|
|
5055
5336
|
schema: ${r},
|
|
5056
5337
|
},`}).join(`
|
|
5057
|
-
`)}function
|
|
5058
|
-
`)}function
|
|
5338
|
+
`)}function yr(e){return e.filter(({operation:n})=>n.kind==="scheduler").map(({operation:n,alias:t})=>{let r=n.taskName??`${n.routePath}`;return ` ${JSON.stringify(r)}: Parameters<typeof ${t}.definition.handler>[1];`}).join(`
|
|
5339
|
+
`)}function br(e){return e.filter(({operation:n})=>n.kind==="cron").map(({operation:n,alias:t})=>{let r=n.taskName??`${n.routePath}`,a=n.cronTriggers??[];return `
|
|
5059
5340
|
{
|
|
5060
5341
|
taskName: ${JSON.stringify(r)},
|
|
5061
5342
|
cronTriggers: ${JSON.stringify(a)},
|
|
5062
|
-
definition: ${
|
|
5343
|
+
definition: ${t}.definition,
|
|
5063
5344
|
},`}).join(`
|
|
5064
|
-
`)}function
|
|
5065
|
-
${
|
|
5066
|
-
`)}function
|
|
5345
|
+
`)}function wr(e){return e.filter(({operation:n})=>n.kind==="storage").map(({alias:n})=>`
|
|
5346
|
+
${n}.definition.handler,`).join(`
|
|
5347
|
+
`)}function tt(e){let n=ur(e);return {imports:cr(n),operationSchemas:dr(n),schedulerSchemas:pr(n),queryRoutes:mr(n),mutationRoutes:fr(n),queryRegistryEntries:gr(n),schedulerEntries:hr(n),schedulerPayloadMapEntries:yr(n),cronEntries:br(n),storageHandlersEntries:wr(n)}}var nt=`
|
|
5067
5348
|
function getRealtimeStub(
|
|
5068
5349
|
env: Record<string, unknown>,
|
|
5069
5350
|
options: RegisterHandlersOptions,
|
|
@@ -5137,7 +5418,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
5137
5418
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
5138
5419
|
return url.toString();
|
|
5139
5420
|
}
|
|
5140
|
-
`;var
|
|
5421
|
+
`;var rt=`
|
|
5141
5422
|
export class AppflareRealtimeDurableObject {
|
|
5142
5423
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
5143
5424
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -5280,7 +5561,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
5280
5561
|
return new Response("Not found", { status: 404 });
|
|
5281
5562
|
}
|
|
5282
5563
|
}
|
|
5283
|
-
`;var
|
|
5564
|
+
`;var at=`
|
|
5284
5565
|
async function publishMutationEvents(
|
|
5285
5566
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
5286
5567
|
options: RegisterHandlersOptions,
|
|
@@ -5381,7 +5662,7 @@ async function publishMutationEvents(
|
|
|
5381
5662
|
}
|
|
5382
5663
|
}
|
|
5383
5664
|
}
|
|
5384
|
-
`;var
|
|
5665
|
+
`;var ot=`
|
|
5385
5666
|
function registerRealtimeRoutes(
|
|
5386
5667
|
app: Hono<WorkerEnv>,
|
|
5387
5668
|
options: RegisterHandlersOptions,
|
|
@@ -5544,7 +5825,7 @@ function registerRealtimeRoutes(
|
|
|
5544
5825
|
return stub.fetch(c.req.raw);
|
|
5545
5826
|
});
|
|
5546
5827
|
}
|
|
5547
|
-
`;var
|
|
5828
|
+
`;var it=`
|
|
5548
5829
|
type RealtimeSubscription = {
|
|
5549
5830
|
token: string;
|
|
5550
5831
|
signature: string;
|
|
@@ -5573,7 +5854,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
5573
5854
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
5574
5855
|
? string
|
|
5575
5856
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
5576
|
-
`;var
|
|
5857
|
+
`;var st=`
|
|
5577
5858
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5578
5859
|
return typeof value === "object" && value !== null;
|
|
5579
5860
|
}
|
|
@@ -6082,9 +6363,9 @@ function doesSubscriptionMatchMutation(
|
|
|
6082
6363
|
|
|
6083
6364
|
return false;
|
|
6084
6365
|
}
|
|
6085
|
-
`;var
|
|
6366
|
+
`;var lt=[it,st,nt,at,ot,rt].join(`
|
|
6086
6367
|
|
|
6087
|
-
`);var
|
|
6368
|
+
`);var ut=`
|
|
6088
6369
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
6089
6370
|
if (!value) {
|
|
6090
6371
|
return undefined;
|
|
@@ -6282,7 +6563,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
6282
6563
|
}
|
|
6283
6564
|
});
|
|
6284
6565
|
}
|
|
6285
|
-
`;var
|
|
6566
|
+
`;var ct=`
|
|
6286
6567
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
6287
6568
|
? string
|
|
6288
6569
|
: keyof typeof schedulerHandlers;
|
|
@@ -6337,7 +6618,7 @@ export async function executeScheduledBatch(
|
|
|
6337
6618
|
}
|
|
6338
6619
|
}
|
|
6339
6620
|
}
|
|
6340
|
-
`;var
|
|
6621
|
+
`;var dt=`
|
|
6341
6622
|
export async function executeCronTriggers(
|
|
6342
6623
|
controller: { cron: string },
|
|
6343
6624
|
env: Record<string, unknown>,
|
|
@@ -6362,7 +6643,7 @@ export async function executeCronTriggers(
|
|
|
6362
6643
|
}
|
|
6363
6644
|
}
|
|
6364
6645
|
}
|
|
6365
|
-
`;function
|
|
6646
|
+
`;function pt(e){let{imports:n,operationSchemas:t,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:u,cronEntries:l,storageHandlersEntries:c}=tt(e);return `import { sValidator } from "@hono/standard-validator";
|
|
6366
6647
|
import type { Hono } from "hono";
|
|
6367
6648
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6368
6649
|
import { ZodError, z } from "zod";
|
|
@@ -6379,10 +6660,10 @@ import {
|
|
|
6379
6660
|
} from "./handlers";
|
|
6380
6661
|
import { createExecutionContext, createSchedulerExecutionContext, resolveSession } from "./handlers.context";
|
|
6381
6662
|
import { executeOperation, handleOperationError } from "./handlers.execution";
|
|
6382
|
-
${
|
|
6383
|
-
${
|
|
6663
|
+
${n?`
|
|
6664
|
+
${n}`:""}
|
|
6384
6665
|
|
|
6385
|
-
${
|
|
6666
|
+
${t}
|
|
6386
6667
|
${r}
|
|
6387
6668
|
|
|
6388
6669
|
const realtimeQueryHandlers = {${i||`
|
|
@@ -6393,8 +6674,8 @@ const schedulerHandlers = {${s||`
|
|
|
6393
6674
|
`}
|
|
6394
6675
|
} as const;
|
|
6395
6676
|
|
|
6396
|
-
type GeneratedSchedulerPayloadMap = {${
|
|
6397
|
-
${
|
|
6677
|
+
type GeneratedSchedulerPayloadMap = {${u?`
|
|
6678
|
+
${u}
|
|
6398
6679
|
`:""}};
|
|
6399
6680
|
|
|
6400
6681
|
declare global {
|
|
@@ -6413,15 +6694,15 @@ const cronHandlers: readonly CronHandlerEntry[] = [${l||`
|
|
|
6413
6694
|
`}
|
|
6414
6695
|
];
|
|
6415
6696
|
|
|
6416
|
-
const storageHandlers = [${
|
|
6697
|
+
const storageHandlers = [${c||`
|
|
6417
6698
|
`}
|
|
6418
6699
|
] as const;
|
|
6419
6700
|
|
|
6420
6701
|
setStorageHandlers([...storageHandlers]);
|
|
6421
6702
|
|
|
6422
|
-
${
|
|
6703
|
+
${ct}
|
|
6423
6704
|
|
|
6424
|
-
${
|
|
6705
|
+
${lt}
|
|
6425
6706
|
|
|
6426
6707
|
export function registerGeneratedHandlers(
|
|
6427
6708
|
app: Hono<WorkerEnv>,
|
|
@@ -6434,20 +6715,20 @@ export function registerGeneratedHandlers(
|
|
|
6434
6715
|
`}
|
|
6435
6716
|
}
|
|
6436
6717
|
|
|
6437
|
-
${st}
|
|
6438
|
-
|
|
6439
6718
|
${ut}
|
|
6440
|
-
|
|
6441
|
-
|
|
6442
|
-
|
|
6443
|
-
|
|
6719
|
+
|
|
6720
|
+
${dt}
|
|
6721
|
+
`}function Z(e,n,t,r=[],a=[]){let o=et(e,r,a),i=je(t),s=De(),u=pt(n);return [{relativePath:"handlers.ts",source:o},{relativePath:"handlers.context.ts",source:i},{relativePath:"handlers.execution.ts",source:s},{relativePath:"handlers.routes.ts",source:u}]}function xr(e){return e?`,
|
|
6722
|
+
KV: c.env["${e}"] as KVNamespace`:""}function mt(e,n){return `{
|
|
6723
|
+
DATABASE: c.env["${e}"] as D1Database${xr(n)}
|
|
6724
|
+
}`}function ft(e,n,t){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6444
6725
|
const auth = createAuth(
|
|
6445
|
-
${
|
|
6726
|
+
${mt(n,t)},
|
|
6446
6727
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
6447
6728
|
);
|
|
6448
6729
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6449
6730
|
});
|
|
6450
|
-
`}function
|
|
6731
|
+
`}function Tr(){return `export const getHeaders = (headers: Headers) => {
|
|
6451
6732
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6452
6733
|
const headerObject: Record<string, any> = {};
|
|
6453
6734
|
let hasCookie = false;
|
|
@@ -6477,15 +6758,15 @@ ${ut}
|
|
|
6477
6758
|
|
|
6478
6759
|
return headerObject as any as Headers;
|
|
6479
6760
|
};
|
|
6480
|
-
`}function
|
|
6761
|
+
`}function vr(){return `export const getSanitizedRequest = (req: Request) => {
|
|
6481
6762
|
const newRequest = new Request(req, {
|
|
6482
6763
|
headers: getHeaders(req.headers),
|
|
6483
6764
|
});
|
|
6484
6765
|
return newRequest;
|
|
6485
6766
|
};
|
|
6486
|
-
`}function
|
|
6487
|
-
`+
|
|
6488
|
-
`+
|
|
6767
|
+
`}function gt(){return Tr()+`
|
|
6768
|
+
`+vr()}function ht(e,n,t){return ft(e,n,t)+`
|
|
6769
|
+
`+gt()}function yt(){return `const app = new Hono<WorkerEnv>();
|
|
6489
6770
|
|
|
6490
6771
|
app.use('*', cors({
|
|
6491
6772
|
origin: (origin, c) => {
|
|
@@ -6501,7 +6782,7 @@ app.use('*', cors({
|
|
|
6501
6782
|
},
|
|
6502
6783
|
credentials: true
|
|
6503
6784
|
}));
|
|
6504
|
-
`}function
|
|
6785
|
+
`}function bt(){return `export { AppflareRealtimeDurableObject };
|
|
6505
6786
|
|
|
6506
6787
|
export default {
|
|
6507
6788
|
fetch: app.fetch,
|
|
@@ -6512,54 +6793,64 @@ export default {
|
|
|
6512
6793
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
6513
6794
|
},
|
|
6514
6795
|
};
|
|
6515
|
-
`}function
|
|
6516
|
-
kvBinding: "${
|
|
6796
|
+
`}function wt(e,n,t="APPFLARE_SCHEDULER_QUEUE",r,a="APPFLARE_REALTIME",o="global",i="/realtime/subscribe",s="/realtime/ws",u="appflare.realtime.v1"){let l=n?`
|
|
6797
|
+
kvBinding: "${n}",`:"",c=r?`
|
|
6517
6798
|
r2Binding: "${r}",`:"",p=`
|
|
6518
6799
|
realtimeBinding: "${a}",
|
|
6519
6800
|
realtimeObjectName: "${o}",
|
|
6520
6801
|
realtimeSubscribePath: "${i}",
|
|
6521
6802
|
realtimeWebsocketPath: "${s}",
|
|
6522
|
-
realtimeProtocol: "${
|
|
6803
|
+
realtimeProtocol: "${u}",`;return `const generatedHandlerOptions = {
|
|
6523
6804
|
databaseBinding: "${e}",${l}
|
|
6524
|
-
schedulerBinding: "${
|
|
6805
|
+
schedulerBinding: "${t}",${c}${p}
|
|
6525
6806
|
};
|
|
6526
6807
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6527
6808
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
6528
6809
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
6529
|
-
`}function
|
|
6810
|
+
`}function xt(){return `import { createAuth } from "./auth.config";
|
|
6530
6811
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
6531
6812
|
import { registerAdminDashboard } from "./admin.routes";
|
|
6532
6813
|
import { Hono } from "hono";
|
|
6533
6814
|
import { cors } from "hono/cors";
|
|
6534
6815
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6535
|
-
`}function
|
|
6816
|
+
`}function Tt(){return `type WorkerEnv = {
|
|
6536
6817
|
Bindings: Record<string, unknown>;
|
|
6537
6818
|
};
|
|
6538
|
-
`}function
|
|
6819
|
+
`}function vt(e,n,t,r,a,o,i,s,u,l){return xt()+Tt()+yt()+wt(n,t,r,a,o,i,s,u,l)+ht(e,n,t)+bt()}function Rt(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function X(e,n){let t={...e};for(let[r,a]of Object.entries(n)){let o=t[r];if(Rt(o)&&Rt(a)){t[r]=X(o,a);continue}t[r]=a;}return t}function Rr(e){return Array.from(new Set(e.filter(n=>n.length>0)))}function kt(e,n){let t=n.filter(d=>d.kind==="scheduler"||d.kind==="cron"),r=Rr(n.filter(d=>d.kind==="cron").flatMap(d=>d.cronTriggers??[])),a=e.config.scheduler.enabled&&t.length>0,o=e.config.realtime.enabled,s=(typeof e.config.wranglerOverrides?.name=="string"?e.config.wranglerOverrides.name:void 0)??"appflare-worker",u=e.config.scheduler.queue??`${s}-scheduler`,l={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:u}],consumers:[{queue:u}]}}:{},...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 l;let{scheduler:c,...p}=e.config.wranglerOverrides;return X(l,p)}function Y(e){let n={children:[],handlers:[]};for(let t of e){let r=t.clientSegments??[t.exportName],a=n;for(let o=0;o<r.length-1;o++){let i=r[o],s=a.children.find(u=>u.name===i&&u.type==="folder");s||(s={name:i,type:"folder",children:[],handlers:[]},a.children.push(s)),a=s;}a.handlers.push(t);}return n.children}function St(e){return e.tables.map(n=>({exportName:n.exportName,tableName:n.tableName,columns:n.columns.map(t=>t.name)}))}function At(e){return `<li data-name="users">
|
|
6539
6820
|
<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">
|
|
6540
6821
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6541
6822
|
<span class="truncate">users</span>
|
|
6542
6823
|
</a>
|
|
6543
6824
|
</li>
|
|
6544
|
-
${e.map(
|
|
6545
|
-
<a href="/admin/table/${
|
|
6825
|
+
${e.map(t=>`<li data-name="${t.tableName}">
|
|
6826
|
+
<a href="/admin/table/${t.exportName}" hx-get="/admin/table/${t.exportName}" 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">
|
|
6546
6827
|
<iconify-icon icon="mdi:table" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6547
|
-
<span class="truncate">${
|
|
6828
|
+
<span class="truncate">${t.tableName}</span>
|
|
6548
6829
|
</a>
|
|
6549
6830
|
</li>`).join(`
|
|
6550
|
-
`)}`}function
|
|
6551
|
-
|
|
6552
|
-
|
|
6553
|
-
|
|
6554
|
-
|
|
6555
|
-
|
|
6556
|
-
|
|
6557
|
-
|
|
6558
|
-
|
|
6559
|
-
|
|
6560
|
-
|
|
6561
|
-
|
|
6562
|
-
|
|
6831
|
+
`)}`}function ee(e,n){let t=" ".repeat(n),r=e.children.length>0,a=e.handlers.length>0,o=r||a,i="";if(o){`folder-${e.name.replace(/[^a-zA-Z0-9]/g,"-")}-${n}`;i+=`
|
|
6832
|
+
${t}<li data-name="${e.name}" class="folder-item">`,i+=`
|
|
6833
|
+
${t} <details class="group/folder" open>`,i+=`
|
|
6834
|
+
${t} <summary class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full cursor-pointer list-none">`,i+=`
|
|
6835
|
+
${t} <iconify-icon icon="solar:folder-bold-duotone" width="16" height="16" class="opacity-50 shrink-0 transition-transform group-open/folder:rotate-0"></iconify-icon>`,i+=`
|
|
6836
|
+
${t} <span class="truncate font-medium">${e.name}</span>`,i+=`
|
|
6837
|
+
${t} </summary>`,i+=`
|
|
6838
|
+
${t} <ul class="flex flex-col gap-0.5 ml-4 border-l border-base-200 pl-2">`;for(let u of e.children)i+=ee(u,n+2);for(let u of e.handlers){let l=u.kind==="query"?"solar:reorder-linear":"solar:bolt-linear";i+=`
|
|
6839
|
+
${t} <li data-name="${u.exportName}">`,i+=`
|
|
6840
|
+
${t} <a href="/admin/functions${u.routePath}" hx-get="/admin/functions${u.routePath}" hx-target="#main-content" hx-push-url="true" hx-swap="outerHTML" class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full">`,i+=`
|
|
6841
|
+
${t} <iconify-icon icon="${l}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
6842
|
+
${t} <span class="truncate">${u.exportName}</span>`,i+=`
|
|
6843
|
+
${t} </a>`,i+=`
|
|
6844
|
+
${t} </li>`;}i+=`
|
|
6845
|
+
${t} </ul>`,i+=`
|
|
6846
|
+
${t} </details>`,i+=`
|
|
6847
|
+
${t}</li>`;}else for(let s of e.handlers){let u=s.kind==="query"?"solar:reorder-linear":"solar:bolt-linear";i+=`
|
|
6848
|
+
${t}<li data-name="${s.exportName}">`,i+=`
|
|
6849
|
+
${t} <a href="/admin/functions${s.routePath}" hx-get="/admin/functions${s.routePath}" hx-target="#main-content" hx-push-url="true" hx-swap="outerHTML" class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full">`,i+=`
|
|
6850
|
+
${t} <iconify-icon icon="${u}" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>`,i+=`
|
|
6851
|
+
${t} <span class="truncate">${s.exportName}</span>`,i+=`
|
|
6852
|
+
${t} </a>`,i+=`
|
|
6853
|
+
${t}</li>`;}return i}function Nt(e){let n=e.filter(s=>s.kind==="query"),t=e.filter(s=>s.kind==="mutation"),r=Y(n),a=Y(t),o=r.map(s=>ee(s,0)).join(""),i=a.map(s=>ee(s,0)).join("");return `
|
|
6563
6854
|
<div id="pane-functions" class="flex flex-col h-full hidden">
|
|
6564
6855
|
<div class="px-3 pt-5 pb-3">
|
|
6565
6856
|
<p class="text-[10px] font-semibold uppercase tracking-widest opacity-35 mb-3 px-1">Functions</p>
|
|
@@ -6575,15 +6866,15 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6575
6866
|
</div>
|
|
6576
6867
|
</div>
|
|
6577
6868
|
<nav class="flex-1 overflow-y-auto px-2 pb-4">
|
|
6578
|
-
${
|
|
6579
|
-
<ul class="flex flex-col gap-0.5">${
|
|
6580
|
-
${
|
|
6581
|
-
<ul class="flex flex-col gap-0.5">${
|
|
6869
|
+
${n.length>0?`<p class="text-[9px] font-bold uppercase tracking-wider opacity-25 mt-4 mb-1 px-2">Queries</p>
|
|
6870
|
+
<ul class="flex flex-col gap-0.5">${o}</ul>`:""}
|
|
6871
|
+
${t.length>0?`<p class="text-[9px] font-bold uppercase tracking-wider opacity-25 mt-4 mb-1 px-2">Mutations</p>
|
|
6872
|
+
<ul class="flex flex-col gap-0.5">${i}</ul>`:""}
|
|
6582
6873
|
</nav>
|
|
6583
6874
|
</div>
|
|
6584
|
-
`}function
|
|
6875
|
+
`}function $t(e){return e.map(n=>`
|
|
6585
6876
|
<a
|
|
6586
|
-
href="/admin/table/${
|
|
6877
|
+
href="/admin/table/${n.exportName}"
|
|
6587
6878
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
6588
6879
|
>
|
|
6589
6880
|
<div class="card-body p-5">
|
|
@@ -6592,42 +6883,42 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6592
6883
|
<iconify-icon icon="mdi:table" width="20" height="20" class="text-primary"></iconify-icon>
|
|
6593
6884
|
</div>
|
|
6594
6885
|
<div>
|
|
6595
|
-
<h2 class="font-semibold text-sm capitalize group-hover:text-primary transition-colors">${
|
|
6886
|
+
<h2 class="font-semibold text-sm capitalize group-hover:text-primary transition-colors">${n.tableName}</h2>
|
|
6596
6887
|
<p class="text-xs opacity-40 mt-0.5">Manage records</p>
|
|
6597
6888
|
</div>
|
|
6598
6889
|
</div>
|
|
6599
6890
|
</div>
|
|
6600
6891
|
</a>
|
|
6601
|
-
`.replace(/\n/g,"\\n")).join("")}function
|
|
6602
|
-
try { searchConditions.push(like(tableSchema.${
|
|
6603
|
-
`).join("")}function
|
|
6892
|
+
`.replace(/\n/g,"\\n")).join("")}function Ct(e){return e.columns.filter(n=>n.type==="string").map(n=>`
|
|
6893
|
+
try { searchConditions.push(like(tableSchema.${n.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6894
|
+
`).join("")}function kr(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 qt(e,n){return n.map(t=>{let r=e.columns.find(o=>o.name===t),a=r?kr(r.type):"mdi:format-text";return `
|
|
6604
6895
|
<th>
|
|
6605
6896
|
<a href="#"
|
|
6606
|
-
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${
|
|
6897
|
+
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${t}&order=\${sort === '${t}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
6607
6898
|
hx-target="#main-content"
|
|
6608
6899
|
hx-push-url="true"
|
|
6609
6900
|
class="hover:text-primary flex items-center gap-1.5 transition-colors whitespace-nowrap">
|
|
6610
6901
|
<iconify-icon icon="${a}" width="14" height="14" class="opacity-40"></iconify-icon>
|
|
6611
|
-
${
|
|
6612
|
-
<span class="text-[10px] opacity-30">\${sort === '${
|
|
6902
|
+
${t}
|
|
6903
|
+
<span class="text-[10px] opacity-30">\${sort === '${t}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6613
6904
|
</a>
|
|
6614
6905
|
</th>
|
|
6615
|
-
`}).join("")}function
|
|
6906
|
+
`}).join("")}function Ft(e,n){return e.map(t=>n&&t===n?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${t} ?? '')}" data-copy-value="\${String((row as any).${t} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${t} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${t} ?? '')}">\${String((row as any).${t} ?? '')}</div></td>`).join("")}function te(e,n,t){let r=e.columns.find(i=>i.name===n);if(!r)return "";let a=r.optional?"":" required",o=r.type==="number"?"number":r.type==="date"?"date":"text";if(r.type==="boolean")return t==="edit"?`
|
|
6616
6907
|
<div class="form-control">
|
|
6617
6908
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6618
|
-
<input type="checkbox" name="${
|
|
6619
|
-
<span class="label-text text-sm">${
|
|
6909
|
+
<input type="checkbox" name="${n}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${n} ? 'checked' : ''} />
|
|
6910
|
+
<span class="label-text text-sm">${n}</span>
|
|
6620
6911
|
</label>
|
|
6621
6912
|
</div>
|
|
6622
6913
|
`:`
|
|
6623
6914
|
<div class="form-control">
|
|
6624
6915
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6625
|
-
<input type="checkbox" name="${
|
|
6626
|
-
<span class="label-text text-sm">${
|
|
6916
|
+
<input type="checkbox" name="${n}" value="true" class="checkbox checkbox-sm checkbox-primary" />
|
|
6917
|
+
<span class="label-text text-sm">${n}</span>
|
|
6627
6918
|
</label>
|
|
6628
6919
|
</div>
|
|
6629
|
-
`;if(
|
|
6630
|
-
const value = (row as any).${
|
|
6920
|
+
`;if(t==="edit"){let i=r.type==="date"?`\${(() => {
|
|
6921
|
+
const value = (row as any).${n};
|
|
6631
6922
|
if (value == null || value === '') return '';
|
|
6632
6923
|
|
|
6633
6924
|
const date =
|
|
@@ -6640,62 +6931,62 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6640
6931
|
const month = String(date.getMonth() + 1).padStart(2, '0');
|
|
6641
6932
|
const day = String(date.getDate()).padStart(2, '0');
|
|
6642
6933
|
return String(year) + '-' + month + '-' + day;
|
|
6643
|
-
})()}`:`\${String((row as any).${
|
|
6934
|
+
})()}`:`\${String((row as any).${n} ?? '')}`;return `
|
|
6644
6935
|
<div class="form-control">
|
|
6645
|
-
<label class="label"><span class="label-text text-sm font-medium">${
|
|
6646
|
-
<input type="${o}" name="${
|
|
6936
|
+
<label class="label"><span class="label-text text-sm font-medium">${n}</span></label>
|
|
6937
|
+
<input type="${o}" name="${n}" class="input input-bordered w-full text-sm" value="${i}"${a} />
|
|
6647
6938
|
</div>
|
|
6648
6939
|
`}return `
|
|
6649
6940
|
<div class="form-control">
|
|
6650
|
-
<label class="label"><span class="label-text text-sm font-medium">${
|
|
6651
|
-
<input type="${o}" name="${
|
|
6941
|
+
<label class="label"><span class="label-text text-sm font-medium">${n}</span></label>
|
|
6942
|
+
<input type="${o}" name="${n}" class="input input-bordered w-full text-sm"${a} />
|
|
6652
6943
|
</div>
|
|
6653
|
-
`}function
|
|
6654
|
-
if (raw_${
|
|
6655
|
-
return c.text('${
|
|
6944
|
+
`}function ne(e,n){return n.map(t=>{let r=e.columns.find(o=>o.name===t);if(!r)return "";let a=r.optional?"":`
|
|
6945
|
+
if (raw_${t} === '') {
|
|
6946
|
+
return c.text('${t} is required', 400);
|
|
6656
6947
|
}
|
|
6657
6948
|
`;return r.type==="number"?`
|
|
6658
|
-
const raw_${
|
|
6949
|
+
const raw_${t} = getValue(body['${t}']);
|
|
6659
6950
|
${a}
|
|
6660
|
-
if (raw_${
|
|
6661
|
-
const parsed_${
|
|
6662
|
-
if (Number.isNaN(parsed_${
|
|
6663
|
-
return c.text('${
|
|
6951
|
+
if (raw_${t} !== '') {
|
|
6952
|
+
const parsed_${t} = Number(raw_${t});
|
|
6953
|
+
if (Number.isNaN(parsed_${t})) {
|
|
6954
|
+
return c.text('${t} must be a valid number', 400);
|
|
6664
6955
|
}
|
|
6665
|
-
payload.${
|
|
6956
|
+
payload.${t} = parsed_${t};
|
|
6666
6957
|
}
|
|
6667
6958
|
`:r.type==="boolean"?`
|
|
6668
|
-
const raw_${
|
|
6669
|
-
payload.${
|
|
6959
|
+
const raw_${t} = getValue(body['${t}']);
|
|
6960
|
+
payload.${t} = raw_${t} === 'true' || raw_${t} === 'on' || raw_${t} === '1';
|
|
6670
6961
|
`:r.type==="date"?`
|
|
6671
|
-
const raw_${
|
|
6962
|
+
const raw_${t} = getValue(body['${t}']);
|
|
6672
6963
|
${a}
|
|
6673
|
-
if (raw_${
|
|
6674
|
-
if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(raw_${
|
|
6675
|
-
return c.text('${
|
|
6964
|
+
if (raw_${t} !== '') {
|
|
6965
|
+
if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(raw_${t})) {
|
|
6966
|
+
return c.text('${t} must be a valid date (YYYY-MM-DD)', 400);
|
|
6676
6967
|
}
|
|
6677
6968
|
|
|
6678
|
-
const [year_${
|
|
6679
|
-
const parsed_${
|
|
6969
|
+
const [year_${t}, month_${t}, day_${t}] = raw_${t}.split('-').map(Number);
|
|
6970
|
+
const parsed_${t} = new Date(year_${t}, month_${t} - 1, day_${t});
|
|
6680
6971
|
if (
|
|
6681
|
-
Number.isNaN(parsed_${
|
|
6682
|
-
parsed_${
|
|
6683
|
-
parsed_${
|
|
6684
|
-
parsed_${
|
|
6972
|
+
Number.isNaN(parsed_${t}.getTime()) ||
|
|
6973
|
+
parsed_${t}.getFullYear() !== year_${t} ||
|
|
6974
|
+
parsed_${t}.getMonth() !== month_${t} - 1 ||
|
|
6975
|
+
parsed_${t}.getDate() !== day_${t}
|
|
6685
6976
|
) {
|
|
6686
|
-
return c.text('${
|
|
6977
|
+
return c.text('${t} must be a valid date', 400);
|
|
6687
6978
|
}
|
|
6688
6979
|
|
|
6689
|
-
payload.${
|
|
6980
|
+
payload.${t} = parsed_${t};
|
|
6690
6981
|
}
|
|
6691
6982
|
`:`
|
|
6692
|
-
const raw_${
|
|
6983
|
+
const raw_${t} = getValue(body['${t}']);
|
|
6693
6984
|
${a}
|
|
6694
|
-
if (raw_${
|
|
6695
|
-
payload.${
|
|
6985
|
+
if (raw_${t} !== '') {
|
|
6986
|
+
payload.${t} = raw_${t};
|
|
6696
6987
|
}
|
|
6697
6988
|
`}).join(`
|
|
6698
|
-
`)}function
|
|
6989
|
+
`)}function Mt(e){return e.columns.find(n=>n.primaryKey)?.name||e.columns[0]?.name||""}function It(e,n){let t=e.columns.find(r=>r.name===n);return !(!t||t.autoIncrement||t.primaryKey)}function Et(e,n){let t=e.columns.find(r=>r.name===n);return !(!t||t.primaryKey||t.autoIncrement)}function Pt(e,n,t,r){return n?`<td class="text-right">
|
|
6699
6990
|
<div class="drawer drawer-end">
|
|
6700
6991
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6701
6992
|
<div class="drawer-content">
|
|
@@ -6716,7 +7007,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6716
7007
|
<button class="btn btn-ghost btn-sm">Cancel</button>
|
|
6717
7008
|
</form>
|
|
6718
7009
|
<form hx-post="/admin/table/${e.exportName}/delete" hx-target="#main-content" hx-swap="outerHTML" class="inline">
|
|
6719
|
-
<input type="hidden" name="${
|
|
7010
|
+
<input type="hidden" name="${t}" value="\${String((row as any).${t} ?? '')}" />
|
|
6720
7011
|
<input type="hidden" name="sort" value="\${sort}" />
|
|
6721
7012
|
<input type="hidden" name="order" value="\${order}" />
|
|
6722
7013
|
<input type="hidden" name="search" value="\${search}" />
|
|
@@ -6737,7 +7028,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6737
7028
|
</label>
|
|
6738
7029
|
</div>
|
|
6739
7030
|
<form hx-post="/admin/table/${e.exportName}/edit" hx-target="#main-content" hx-swap="outerHTML" class="flex flex-col gap-4">
|
|
6740
|
-
<input type="hidden" name="${
|
|
7031
|
+
<input type="hidden" name="${t}" value="\${String((row as any).${t} ?? '')}" />
|
|
6741
7032
|
<input type="hidden" name="sort" value="\${sort}" />
|
|
6742
7033
|
<input type="hidden" name="order" value="\${order}" />
|
|
6743
7034
|
<input type="hidden" name="search" value="\${search}" />
|
|
@@ -6770,18 +7061,18 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6770
7061
|
\` : 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>\`}
|
|
6771
7062
|
</div>
|
|
6772
7063
|
\` : ''}
|
|
6773
|
-
</div>`}function W(e,
|
|
7064
|
+
</div>`}function W(e,n="Search term or filter..."){return `
|
|
6774
7065
|
<div class="form-control w-full md:w-auto relative">
|
|
6775
7066
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
6776
7067
|
<input type="text"
|
|
6777
7068
|
name="search"
|
|
6778
|
-
placeholder="${
|
|
7069
|
+
placeholder="${n}"
|
|
6779
7070
|
value="\${search}"
|
|
6780
7071
|
hx-get="${e}?sort=\${sort}&order=\${order}"
|
|
6781
7072
|
hx-trigger="keyup changed delay:500ms, search"
|
|
6782
7073
|
hx-target="#main-content"
|
|
6783
7074
|
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" />
|
|
6784
|
-
</div>`}function
|
|
7075
|
+
</div>`}function jt(e,n,t,r,a,o,i,s,u,l){let c=B(`/admin/table/${e.exportName}`),p=W(`/admin/table/${e.exportName}`,"Search term or filter..."),d=r?`<th class="w-10"><input id="select-all-${e.exportName}" type="checkbox" class="checkbox checkbox-xs" /></th>`:'<th class="w-10"><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></th>',y=r?`<td><input type="checkbox" class="checkbox checkbox-xs row-select-checkbox" value="\${String((row as any).${t} ?? '')}" /></td>`:'<td><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></td>',v=r?`
|
|
6785
7076
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
6786
7077
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
6787
7078
|
<div class="text-xs text-base-content/70">
|
|
@@ -6905,7 +7196,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6905
7196
|
const page = parseInt(c.req.query('page') || '1');
|
|
6906
7197
|
const limit = 20;
|
|
6907
7198
|
const offset = (page - 1) * limit;
|
|
6908
|
-
const sort = c.req.query('sort') || '${
|
|
7199
|
+
const sort = c.req.query('sort') || '${n}';
|
|
6909
7200
|
const order = c.req.query('order') || 'desc';
|
|
6910
7201
|
const search = c.req.query('search') || '';
|
|
6911
7202
|
|
|
@@ -6951,7 +7242,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6951
7242
|
<tr class="hover:bg-base-200/30 transition-colors">
|
|
6952
7243
|
${y}
|
|
6953
7244
|
${s}
|
|
6954
|
-
${
|
|
7245
|
+
${u}
|
|
6955
7246
|
</tr>
|
|
6956
7247
|
\`)}
|
|
6957
7248
|
\${data.length === 0 ? html\`
|
|
@@ -6971,7 +7262,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6971
7262
|
</tbody>
|
|
6972
7263
|
</table>
|
|
6973
7264
|
</div>
|
|
6974
|
-
${
|
|
7265
|
+
${c}
|
|
6975
7266
|
</div>
|
|
6976
7267
|
\`;
|
|
6977
7268
|
|
|
@@ -7033,11 +7324,11 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
7033
7324
|
title: "${e.tableName} - Admin Dashboard",
|
|
7034
7325
|
children: content
|
|
7035
7326
|
}));
|
|
7036
|
-
});`}function
|
|
7327
|
+
});`}function Ot(e,n,t,r,a,o,i,s){let u=r==="number"?`
|
|
7037
7328
|
const parsedId = Number(rawId);
|
|
7038
|
-
if (Number.isNaN(parsedId)) return c.text('${
|
|
7329
|
+
if (Number.isNaN(parsedId)) return c.text('${t} must be a valid number', 400);
|
|
7039
7330
|
idValue = parsedId;
|
|
7040
|
-
`:"",
|
|
7331
|
+
`:"",c=a?`
|
|
7041
7332
|
adminApp.post('/table/${e}/edit', async (c) => {
|
|
7042
7333
|
const db = drizzle(c.env[options.databaseBinding], { schema });
|
|
7043
7334
|
const tableSchema = (schema as any).${e};
|
|
@@ -7045,27 +7336,27 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
7045
7336
|
|
|
7046
7337
|
const body = await c.req.parseBody();
|
|
7047
7338
|
const getValue = (value: unknown) => (typeof value === 'string' ? value : '');
|
|
7048
|
-
const rawId = getValue(body['${
|
|
7049
|
-
if (rawId === '') return c.text('${
|
|
7339
|
+
const rawId = getValue(body['${t}']);
|
|
7340
|
+
if (rawId === '') return c.text('${t} is required', 400);
|
|
7050
7341
|
|
|
7051
7342
|
const payload: Record<string, unknown> = {};
|
|
7052
7343
|
|
|
7053
7344
|
${s}
|
|
7054
7345
|
|
|
7055
7346
|
let idValue: unknown = rawId;
|
|
7056
|
-
${
|
|
7347
|
+
${u}
|
|
7057
7348
|
|
|
7058
7349
|
if (Object.keys(payload).length > 0) {
|
|
7059
7350
|
await db
|
|
7060
7351
|
.update(tableSchema)
|
|
7061
7352
|
.set(payload as any)
|
|
7062
|
-
.where(eq(tableSchema.${
|
|
7353
|
+
.where(eq(tableSchema.${t}, idValue as any))
|
|
7063
7354
|
.execute();
|
|
7064
7355
|
}
|
|
7065
7356
|
|
|
7066
7357
|
const query = new URLSearchParams({
|
|
7067
7358
|
page: getValue(body.page) || '1',
|
|
7068
|
-
sort: getValue(body.sort) || '${
|
|
7359
|
+
sort: getValue(body.sort) || '${n}',
|
|
7069
7360
|
order: getValue(body.order) || 'desc',
|
|
7070
7361
|
search: getValue(body.search) || '',
|
|
7071
7362
|
});
|
|
@@ -7079,20 +7370,20 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
7079
7370
|
|
|
7080
7371
|
const body = await c.req.parseBody();
|
|
7081
7372
|
const getValue = (value: unknown) => (typeof value === 'string' ? value : '');
|
|
7082
|
-
const rawId = getValue(body['${
|
|
7083
|
-
if (rawId === '') return c.text('${
|
|
7373
|
+
const rawId = getValue(body['${t}']);
|
|
7374
|
+
if (rawId === '') return c.text('${t} is required', 400);
|
|
7084
7375
|
|
|
7085
7376
|
let idValue: unknown = rawId;
|
|
7086
|
-
${
|
|
7377
|
+
${u}
|
|
7087
7378
|
|
|
7088
7379
|
await db
|
|
7089
7380
|
.delete(tableSchema)
|
|
7090
|
-
.where(eq(tableSchema.${
|
|
7381
|
+
.where(eq(tableSchema.${t}, idValue as any))
|
|
7091
7382
|
.execute();
|
|
7092
7383
|
|
|
7093
7384
|
const query = new URLSearchParams({
|
|
7094
7385
|
page: getValue(body.page) || '1',
|
|
7095
|
-
sort: getValue(body.sort) || '${
|
|
7386
|
+
sort: getValue(body.sort) || '${n}',
|
|
7096
7387
|
order: getValue(body.order) || 'desc',
|
|
7097
7388
|
search: getValue(body.search) || '',
|
|
7098
7389
|
});
|
|
@@ -7132,13 +7423,13 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
7132
7423
|
|
|
7133
7424
|
await db
|
|
7134
7425
|
.delete(tableSchema)
|
|
7135
|
-
.where(inArray(tableSchema.${
|
|
7426
|
+
.where(inArray(tableSchema.${t}, parsedIds as any))
|
|
7136
7427
|
.execute();
|
|
7137
7428
|
}
|
|
7138
7429
|
|
|
7139
7430
|
const query = new URLSearchParams({
|
|
7140
7431
|
page: getValue(body.page) || '1',
|
|
7141
|
-
sort: getValue(body.sort) || '${
|
|
7432
|
+
sort: getValue(body.sort) || '${n}',
|
|
7142
7433
|
order: getValue(body.order) || 'desc',
|
|
7143
7434
|
search: getValue(body.search) || '',
|
|
7144
7435
|
});
|
|
@@ -7159,22 +7450,22 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
7159
7450
|
|
|
7160
7451
|
const query = new URLSearchParams({
|
|
7161
7452
|
page: getValue(body.page) || '1',
|
|
7162
|
-
sort: getValue(body.sort) || '${
|
|
7453
|
+
sort: getValue(body.sort) || '${n}',
|
|
7163
7454
|
order: getValue(body.order) || 'desc',
|
|
7164
7455
|
search: getValue(body.search) || '',
|
|
7165
7456
|
});
|
|
7166
7457
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
7167
7458
|
});
|
|
7168
|
-
${
|
|
7169
|
-
`}function
|
|
7170
|
-
`+
|
|
7459
|
+
${c}
|
|
7460
|
+
`}function re(e){let n=Mt(e),t=!!n,r=e.columns.map(w=>w.name),a=r.filter(w=>It(e,w)),o=r.filter(w=>Et(e,w)),i=Ct(e),s=qt(e,r),u=Ft(r,n),l=a.map(w=>te(e,w,"create")).join(""),c=o.map(w=>te(e,w,"edit")).join(""),p=ne(e,a),d=ne(e,o),y=t?n:r[0]||"id",v=e.columns.find(w=>w.name===n)?.type,A=Pt(e,t,n,c);return jt(e,y,n,t,r,i,s,u,A,l)+`
|
|
7461
|
+
`+Ot(e.exportName,y,n,v,t,i,p,d)}function Dt(){return `
|
|
7171
7462
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
7172
7463
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
7173
7464
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
7174
7465
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
7175
7466
|
const search = params.search ? params.search : '';
|
|
7176
7467
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
7177
|
-
};`}function
|
|
7468
|
+
};`}function Vt(){return `
|
|
7178
7469
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7179
7470
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7180
7471
|
<div class="modal">
|
|
@@ -7195,7 +7486,7 @@ ${u}
|
|
|
7195
7486
|
</div>
|
|
7196
7487
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
7197
7488
|
</div>
|
|
7198
|
-
\`}`}function
|
|
7489
|
+
\`}`}function Bt(){return `
|
|
7199
7490
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
7200
7491
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
7201
7492
|
<div class="modal">
|
|
@@ -7216,8 +7507,8 @@ ${u}
|
|
|
7216
7507
|
</div>
|
|
7217
7508
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
7218
7509
|
</div>
|
|
7219
|
-
\`}`}var
|
|
7220
|
-
`),
|
|
7510
|
+
\`}`}var Sr=["id","name","email","role","createdAt","banned"],Ar={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function Nr(e){let n=Ar[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="${n}" 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 Wt(){let e=Sr.map(Nr).join(`
|
|
7511
|
+
`),n=B("/admin/users");return `
|
|
7221
7512
|
const tableHtml = html\`
|
|
7222
7513
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
7223
7514
|
<div class="overflow-x-auto">
|
|
@@ -7285,8 +7576,8 @@ ${u}
|
|
|
7285
7576
|
</div>
|
|
7286
7577
|
</div>
|
|
7287
7578
|
</div>
|
|
7288
|
-
${
|
|
7289
|
-
${
|
|
7579
|
+
${Vt()}
|
|
7580
|
+
${Bt()}
|
|
7290
7581
|
</td>
|
|
7291
7582
|
</tr>
|
|
7292
7583
|
\`)}
|
|
@@ -7299,10 +7590,10 @@ ${Dt()}
|
|
|
7299
7590
|
</tbody>
|
|
7300
7591
|
</table>
|
|
7301
7592
|
</div>
|
|
7302
|
-
${
|
|
7593
|
+
${n}
|
|
7303
7594
|
</div>
|
|
7304
7595
|
\`;
|
|
7305
|
-
`}function
|
|
7596
|
+
`}function Ht(){return `
|
|
7306
7597
|
const content = html\`
|
|
7307
7598
|
<div id="main-content">
|
|
7308
7599
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -7318,7 +7609,7 @@ ${Dt()}
|
|
|
7318
7609
|
</div>
|
|
7319
7610
|
\${tableHtml}
|
|
7320
7611
|
</div>
|
|
7321
|
-
\`;`}function
|
|
7612
|
+
\`;`}function Lt(){let e=Wt(),n=Ht();return `
|
|
7322
7613
|
adminApp.get('/users', async (c) => {
|
|
7323
7614
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
7324
7615
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7364,7 +7655,7 @@ ${Dt()}
|
|
|
7364
7655
|
|
|
7365
7656
|
${e}
|
|
7366
7657
|
|
|
7367
|
-
${
|
|
7658
|
+
${n}
|
|
7368
7659
|
|
|
7369
7660
|
if (c.req.header('hx-request')) {
|
|
7370
7661
|
return c.html(content);
|
|
@@ -7374,7 +7665,7 @@ ${Dt()}
|
|
|
7374
7665
|
title: "users - Admin Dashboard",
|
|
7375
7666
|
children: content,
|
|
7376
7667
|
}));
|
|
7377
|
-
});`}function
|
|
7668
|
+
});`}function zt(){return `
|
|
7378
7669
|
adminApp.post('/users/edit', async (c) => {
|
|
7379
7670
|
const session = await requireAdminSession(c);
|
|
7380
7671
|
if (!session) {
|
|
@@ -7517,8 +7808,8 @@ ${Dt()}
|
|
|
7517
7808
|
const resolvedPage = String(Math.min(nextPageCandidate, totalPages));
|
|
7518
7809
|
|
|
7519
7810
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7520
|
-
});`}function
|
|
7521
|
-
${
|
|
7811
|
+
});`}function ae(){return `
|
|
7812
|
+
${Dt()}
|
|
7522
7813
|
|
|
7523
7814
|
const requireAdminSession = async (c: any) => {
|
|
7524
7815
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7529,12 +7820,12 @@ ${Dt()}
|
|
|
7529
7820
|
return session;
|
|
7530
7821
|
};
|
|
7531
7822
|
|
|
7532
|
-
${
|
|
7823
|
+
${Lt()}
|
|
7533
7824
|
|
|
7534
|
-
${
|
|
7535
|
-
`}function
|
|
7825
|
+
${zt()}
|
|
7826
|
+
`}function Ut(e){return `${e.tables.map(n=>re(n)).join(`
|
|
7536
7827
|
`)}
|
|
7537
|
-
${
|
|
7828
|
+
${ae()}`}function Qt(e){return `
|
|
7538
7829
|
<div class="flex items-center justify-between">
|
|
7539
7830
|
<div class="flex items-center gap-3">
|
|
7540
7831
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -7549,38 +7840,38 @@ ${ne()}`}function zt(e){return `
|
|
|
7549
7840
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
7550
7841
|
</div>
|
|
7551
7842
|
</div>
|
|
7552
|
-
`}function
|
|
7843
|
+
`}function $r(e){return e==="boolean"?"checkbox":e==="number"?"number":"text"}function Cr(e){let n=e.args??[];return n.length===0?`
|
|
7553
7844
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
7554
|
-
`:
|
|
7845
|
+
`:n.map(t=>{let r=$r(t.type),a=r==="checkbox",o=`${t.name}${t.optional?"":" *"}`,i=t.type!=="unknown"?`<span class="badge badge-xs badge-ghost font-mono opacity-40 ml-1">${t.type}</span>`:"";return a?`
|
|
7555
7846
|
<div class="flex items-center gap-3 py-1">
|
|
7556
7847
|
<input
|
|
7557
7848
|
type="checkbox"
|
|
7558
|
-
data-arg-key="${
|
|
7849
|
+
data-arg-key="${t.name}"
|
|
7559
7850
|
data-arg-type="boolean"
|
|
7560
7851
|
class="checkbox checkbox-sm checkbox-primary"
|
|
7561
|
-
${
|
|
7852
|
+
${t.defaultValue==="true"?"checked":""}
|
|
7562
7853
|
/>
|
|
7563
|
-
<span class="text-sm font-mono opacity-70">${
|
|
7564
|
-
${
|
|
7854
|
+
<span class="text-sm font-mono opacity-70">${t.name}${i}</span>
|
|
7855
|
+
${t.optional?'<span class="text-[10px] opacity-30 italic ml-auto">optional</span>':""}
|
|
7565
7856
|
</div>
|
|
7566
7857
|
`:`
|
|
7567
7858
|
<div class="form-control">
|
|
7568
7859
|
<label class="label py-0.5">
|
|
7569
7860
|
<span class="label-text text-[11px] font-mono font-semibold">${o}${i}</span>
|
|
7570
|
-
${
|
|
7861
|
+
${t.optional?'<span class="label-text-alt text-[10px] opacity-30 italic">optional</span>':""}
|
|
7571
7862
|
</label>
|
|
7572
7863
|
<input
|
|
7573
7864
|
type="${r}"
|
|
7574
|
-
placeholder="${
|
|
7575
|
-
data-arg-key="${
|
|
7576
|
-
data-arg-type="${
|
|
7577
|
-
value="${
|
|
7865
|
+
placeholder="${t.defaultValue??""}"
|
|
7866
|
+
data-arg-key="${t.name}"
|
|
7867
|
+
data-arg-type="${t.type}"
|
|
7868
|
+
value="${t.defaultValue??""}"
|
|
7578
7869
|
class="input input-sm input-bordered font-mono w-full bg-base-200/30 focus:bg-base-100 focus:border-primary transition-all rounded-xl border-base-200"
|
|
7579
|
-
${
|
|
7870
|
+
${t.optional?"":"required"}
|
|
7580
7871
|
/>
|
|
7581
7872
|
</div>
|
|
7582
7873
|
`}).join(`
|
|
7583
|
-
`)}function
|
|
7874
|
+
`)}function qr(e){return `
|
|
7584
7875
|
<div class="space-y-4">
|
|
7585
7876
|
<div class="flex items-center justify-between">
|
|
7586
7877
|
<div class="flex flex-col">
|
|
@@ -7593,11 +7884,11 @@ ${ne()}`}function zt(e){return `
|
|
|
7593
7884
|
</label>
|
|
7594
7885
|
</div>
|
|
7595
7886
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
7596
|
-
${
|
|
7887
|
+
${Cr(e)}
|
|
7597
7888
|
</div>
|
|
7598
7889
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7599
7890
|
</div>
|
|
7600
|
-
`}function
|
|
7891
|
+
`}function Fr(){return `
|
|
7601
7892
|
<div class="space-y-4">
|
|
7602
7893
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7603
7894
|
<div class="relative group">
|
|
@@ -7614,7 +7905,7 @@ ${ne()}`}function zt(e){return `
|
|
|
7614
7905
|
</div>
|
|
7615
7906
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
7616
7907
|
</div>
|
|
7617
|
-
`}function
|
|
7908
|
+
`}function Mr(){return `
|
|
7618
7909
|
<div class="space-y-4">
|
|
7619
7910
|
<div class="flex items-center justify-between">
|
|
7620
7911
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -7628,7 +7919,7 @@ ${ne()}`}function zt(e){return `
|
|
|
7628
7919
|
</div>
|
|
7629
7920
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
7630
7921
|
</div>
|
|
7631
|
-
`}function
|
|
7922
|
+
`}function _t(e){return `
|
|
7632
7923
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
7633
7924
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
7634
7925
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -7649,13 +7940,13 @@ ${ne()}`}function zt(e){return `
|
|
|
7649
7940
|
<!-- Tab Content -->
|
|
7650
7941
|
<div class="flex-1 overflow-y-auto">
|
|
7651
7942
|
<div id="request-tab-args" class="p-5">
|
|
7652
|
-
${
|
|
7943
|
+
${qr(e)}
|
|
7653
7944
|
</div>
|
|
7654
7945
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
7655
|
-
${
|
|
7946
|
+
${Fr()}
|
|
7656
7947
|
</div>
|
|
7657
7948
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
7658
|
-
${
|
|
7949
|
+
${Mr()}
|
|
7659
7950
|
</div>
|
|
7660
7951
|
</div>
|
|
7661
7952
|
|
|
@@ -7673,7 +7964,7 @@ ${ne()}`}function zt(e){return `
|
|
|
7673
7964
|
</form>
|
|
7674
7965
|
</div>
|
|
7675
7966
|
</div>
|
|
7676
|
-
`}function
|
|
7967
|
+
`}function Kt(){return `
|
|
7677
7968
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
7678
7969
|
<!-- Panel Header -->
|
|
7679
7970
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -7755,7 +8046,7 @@ ${ne()}`}function zt(e){return `
|
|
|
7755
8046
|
|
|
7756
8047
|
</div>
|
|
7757
8048
|
</div>
|
|
7758
|
-
`}function
|
|
8049
|
+
`}function Jt(e){let n=e.kind==="query",t=e.routePath,r=e.handlerName??e.routePath;return `
|
|
7759
8050
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
7760
8051
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
7761
8052
|
|
|
@@ -7981,9 +8272,9 @@ ${ne()}`}function zt(e){return `
|
|
|
7981
8272
|
if (indicator) indicator.classList.remove('opacity-0');
|
|
7982
8273
|
showBodyLoading();
|
|
7983
8274
|
|
|
7984
|
-
var isQuery = ${
|
|
8275
|
+
var isQuery = ${n};
|
|
7985
8276
|
var method = isQuery ? 'GET' : 'POST';
|
|
7986
|
-
var pathWithQuery = '${
|
|
8277
|
+
var pathWithQuery = '${t}';
|
|
7987
8278
|
|
|
7988
8279
|
if (isQuery && Object.keys(args).length > 0) {
|
|
7989
8280
|
var params = new URLSearchParams();
|
|
@@ -8053,7 +8344,7 @@ ${ne()}`}function zt(e){return `
|
|
|
8053
8344
|
var _rtToken = null;
|
|
8054
8345
|
var _rtEnabled = false;
|
|
8055
8346
|
var _rtEventCount = 0;
|
|
8056
|
-
var _isRealtimeSupported = ${
|
|
8347
|
+
var _isRealtimeSupported = ${n};
|
|
8057
8348
|
var _realtimeQueryName = '${r}';
|
|
8058
8349
|
var _rtPingInterval = null;
|
|
8059
8350
|
|
|
@@ -8297,21 +8588,21 @@ ${ne()}`}function zt(e){return `
|
|
|
8297
8588
|
_rtEnabled = false;
|
|
8298
8589
|
});
|
|
8299
8590
|
</script>
|
|
8300
|
-
`}function
|
|
8591
|
+
`}function Gt(e){return `
|
|
8301
8592
|
const content = html\`
|
|
8302
8593
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
8303
|
-
${
|
|
8594
|
+
${Qt(e)}
|
|
8304
8595
|
|
|
8305
8596
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
8306
8597
|
<!-- Request Panel -->
|
|
8307
|
-
${
|
|
8598
|
+
${_t(e)}
|
|
8308
8599
|
|
|
8309
8600
|
<!-- Result Panel -->
|
|
8310
|
-
${
|
|
8601
|
+
${Kt()}
|
|
8311
8602
|
</div>
|
|
8312
8603
|
</div>
|
|
8313
8604
|
|
|
8314
|
-
${
|
|
8605
|
+
${Jt(e)}
|
|
8315
8606
|
\`;
|
|
8316
8607
|
|
|
8317
8608
|
if (c.req.header('hx-request')) {
|
|
@@ -8321,11 +8612,11 @@ ${ne()}`}function zt(e){return `
|
|
|
8321
8612
|
return c.html(Layout({
|
|
8322
8613
|
title: "${e.exportName} - Functions",
|
|
8323
8614
|
children: content
|
|
8324
|
-
}));`}function
|
|
8325
|
-
adminApp.get('/functions${
|
|
8326
|
-
${
|
|
8615
|
+
}));`}function Zt(e){return e.map(t=>t.kind!=="query"&&t.kind!=="mutation"?"":`
|
|
8616
|
+
adminApp.get('/functions${t.routePath}', (c) => {
|
|
8617
|
+
${Gt(t)}
|
|
8327
8618
|
});`).join(`
|
|
8328
|
-
`)}function
|
|
8619
|
+
`)}function Xt(){return `
|
|
8329
8620
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
8330
8621
|
const r2Binding = (options as any).r2Binding;
|
|
8331
8622
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -8394,7 +8685,7 @@ ${ne()}`}function zt(e){return `
|
|
|
8394
8685
|
const parts = prefix.split('/').filter(Boolean);
|
|
8395
8686
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
8396
8687
|
};
|
|
8397
|
-
`}function
|
|
8688
|
+
`}function Yt(){return `
|
|
8398
8689
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
8399
8690
|
const parts = prefix.split('/').filter(Boolean);
|
|
8400
8691
|
const breadcrumbs: any[] = [];
|
|
@@ -8521,7 +8812,7 @@ ${ne()}`}function zt(e){return `
|
|
|
8521
8812
|
</div>
|
|
8522
8813
|
\`;
|
|
8523
8814
|
};
|
|
8524
|
-
`}function
|
|
8815
|
+
`}function en(){return `
|
|
8525
8816
|
const handleStorageListRoute = async (c: any) => {
|
|
8526
8817
|
const bucket = getStorageBucket(c);
|
|
8527
8818
|
if (!bucket) {
|
|
@@ -8543,7 +8834,7 @@ ${ne()}`}function zt(e){return `
|
|
|
8543
8834
|
|
|
8544
8835
|
adminApp.get('/storage', handleStorageListRoute);
|
|
8545
8836
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
8546
|
-
`}function
|
|
8837
|
+
`}function tn(){return `
|
|
8547
8838
|
adminApp.post('/storage/upload', async (c) => {
|
|
8548
8839
|
const bucket = getStorageBucket(c);
|
|
8549
8840
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8561,7 +8852,7 @@ ${ne()}`}function zt(e){return `
|
|
|
8561
8852
|
|
|
8562
8853
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8563
8854
|
});
|
|
8564
|
-
`}function
|
|
8855
|
+
`}function nn(){return `
|
|
8565
8856
|
adminApp.delete('/storage/delete', async (c) => {
|
|
8566
8857
|
const bucket = getStorageBucket(c);
|
|
8567
8858
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8576,7 +8867,7 @@ ${ne()}`}function zt(e){return `
|
|
|
8576
8867
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
8577
8868
|
return c.html('');
|
|
8578
8869
|
});
|
|
8579
|
-
`}function
|
|
8870
|
+
`}function rn(){return `
|
|
8580
8871
|
adminApp.post('/storage/directory', async (c) => {
|
|
8581
8872
|
const bucket = getStorageBucket(c);
|
|
8582
8873
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8602,7 +8893,7 @@ ${ne()}`}function zt(e){return `
|
|
|
8602
8893
|
|
|
8603
8894
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8604
8895
|
});
|
|
8605
|
-
`}function
|
|
8896
|
+
`}function an(){return `
|
|
8606
8897
|
adminApp.get('/storage/download', async (c) => {
|
|
8607
8898
|
const bucket = getStorageBucket(c);
|
|
8608
8899
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8622,7 +8913,7 @@ ${ne()}`}function zt(e){return `
|
|
|
8622
8913
|
|
|
8623
8914
|
return new Response(object.body, { headers });
|
|
8624
8915
|
});
|
|
8625
|
-
`}function
|
|
8916
|
+
`}function on(){return `
|
|
8626
8917
|
adminApp.get('/storage/preview', async (c) => {
|
|
8627
8918
|
const bucket = getStorageBucket(c);
|
|
8628
8919
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8640,25 +8931,25 @@ ${ne()}`}function zt(e){return `
|
|
|
8640
8931
|
|
|
8641
8932
|
return new Response(object.body, { headers });
|
|
8642
8933
|
});
|
|
8643
|
-
`}function
|
|
8644
|
-
${
|
|
8934
|
+
`}function sn(){return `
|
|
8935
|
+
${an()}
|
|
8645
8936
|
|
|
8646
|
-
${
|
|
8937
|
+
${on()}
|
|
8647
8938
|
|
|
8648
|
-
${
|
|
8939
|
+
${tn()}
|
|
8649
8940
|
|
|
8650
|
-
${
|
|
8941
|
+
${nn()}
|
|
8651
8942
|
|
|
8652
|
-
${
|
|
8943
|
+
${rn()}
|
|
8653
8944
|
|
|
8945
|
+
${en()}
|
|
8946
|
+
`}function ln(){return `
|
|
8654
8947
|
${Xt()}
|
|
8655
|
-
`}function on(){return `
|
|
8656
|
-
${Gt()}
|
|
8657
8948
|
|
|
8658
|
-
${
|
|
8949
|
+
${Yt()}
|
|
8659
8950
|
|
|
8660
|
-
${
|
|
8661
|
-
`}function
|
|
8951
|
+
${sn()}
|
|
8952
|
+
`}function un(e,n){let t=Nt(n);return `
|
|
8662
8953
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
8663
8954
|
return html\`<!DOCTYPE html>
|
|
8664
8955
|
<html lang="en" data-theme="light">
|
|
@@ -8761,6 +9052,23 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8761
9052
|
}
|
|
8762
9053
|
.sidebar-link:hover iconify-icon { opacity: 0.7; }
|
|
8763
9054
|
|
|
9055
|
+
.folder-item { list-style: none; }
|
|
9056
|
+
.folder-item > details > summary { list-style: none; }
|
|
9057
|
+
.folder-item > details > summary::-webkit-details-marker { display: none; }
|
|
9058
|
+
.folder-item > details > summary::before {
|
|
9059
|
+
content: '';
|
|
9060
|
+
display: inline-block;
|
|
9061
|
+
width: 16px;
|
|
9062
|
+
height: 16px;
|
|
9063
|
+
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='currentColor'%3E%3Cpath d='M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6z'/%3E%3C/svg%3E");
|
|
9064
|
+
background-size: contain;
|
|
9065
|
+
transition: transform 0.15s ease;
|
|
9066
|
+
opacity: 0.45;
|
|
9067
|
+
}
|
|
9068
|
+
.folder-item > details[open] > summary::before {
|
|
9069
|
+
transform: rotate(90deg);
|
|
9070
|
+
}
|
|
9071
|
+
|
|
8764
9072
|
.table th {
|
|
8765
9073
|
font-weight: 500;
|
|
8766
9074
|
font-size: 0.78rem;
|
|
@@ -8862,7 +9170,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8862
9170
|
</nav>
|
|
8863
9171
|
</div>
|
|
8864
9172
|
|
|
8865
|
-
${
|
|
9173
|
+
${t}
|
|
8866
9174
|
</div>
|
|
8867
9175
|
</div>
|
|
8868
9176
|
\`) : ""}
|
|
@@ -8940,9 +9248,24 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8940
9248
|
|
|
8941
9249
|
function filterFunctions(query) {
|
|
8942
9250
|
var q = query.toLowerCase();
|
|
9251
|
+
document.querySelectorAll('#pane-functions details').forEach(function(details) {
|
|
9252
|
+
details.open = true;
|
|
9253
|
+
});
|
|
8943
9254
|
document.querySelectorAll('#pane-functions li').forEach(function(li) {
|
|
8944
9255
|
var name = (li.getAttribute('data-name') || li.textContent).toLowerCase();
|
|
8945
|
-
|
|
9256
|
+
var matches = name.includes(q);
|
|
9257
|
+
li.style.display = matches ? '' : 'none';
|
|
9258
|
+
if (!matches && li.classList.contains('folder-item')) {
|
|
9259
|
+
var childItems = li.querySelectorAll('li');
|
|
9260
|
+
childItems.forEach(function(child) {
|
|
9261
|
+
var childName = (child.getAttribute('data-name') || child.textContent).toLowerCase();
|
|
9262
|
+
if (childName.includes(q)) {
|
|
9263
|
+
li.style.display = '';
|
|
9264
|
+
var parentDetails = li.closest('details');
|
|
9265
|
+
if (parentDetails) parentDetails.open = true;
|
|
9266
|
+
}
|
|
9267
|
+
});
|
|
9268
|
+
}
|
|
8946
9269
|
});
|
|
8947
9270
|
}
|
|
8948
9271
|
|
|
@@ -9033,7 +9356,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9033
9356
|
</body>
|
|
9034
9357
|
</html>\`;
|
|
9035
9358
|
}
|
|
9036
|
-
`}function
|
|
9359
|
+
`}function cn(){return `
|
|
9037
9360
|
// Auth Middleware
|
|
9038
9361
|
adminApp.use('*', async (c, next) => {
|
|
9039
9362
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -9092,7 +9415,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9092
9415
|
}
|
|
9093
9416
|
await next();
|
|
9094
9417
|
});
|
|
9095
|
-
`}function
|
|
9418
|
+
`}function dn(e){return `
|
|
9096
9419
|
adminApp.get('/', (c) => {
|
|
9097
9420
|
return c.html(Layout({
|
|
9098
9421
|
title: "Admin Dashboard",
|
|
@@ -9109,7 +9432,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
9109
9432
|
\`
|
|
9110
9433
|
}));
|
|
9111
9434
|
});
|
|
9112
|
-
`}function
|
|
9435
|
+
`}function pn(e,n,t){let r=St(n),a=At(r),o=$t(r),i=Ut(n),s=Zt(t),u=ln(),l=un(a,t),c=cn(),p=dn(o);return `import { Hono } from "hono";
|
|
9113
9436
|
import { html, raw } from "hono/html";
|
|
9114
9437
|
import { drizzle } from "drizzle-orm/d1";
|
|
9115
9438
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -9122,7 +9445,7 @@ ${l}
|
|
|
9122
9445
|
export function registerAdminDashboard(app: Hono<any>, options: { databaseBinding: string, r2Binding?: string }) {
|
|
9123
9446
|
const adminApp = new Hono<any>();
|
|
9124
9447
|
|
|
9125
|
-
${
|
|
9448
|
+
${c}
|
|
9126
9449
|
|
|
9127
9450
|
${p}
|
|
9128
9451
|
|
|
@@ -9133,61 +9456,63 @@ ${p}
|
|
|
9133
9456
|
${s}
|
|
9134
9457
|
|
|
9135
9458
|
// Generate storage routes
|
|
9136
|
-
${
|
|
9459
|
+
${u}
|
|
9137
9460
|
|
|
9138
9461
|
app.route('/admin', adminApp);
|
|
9139
9462
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
9140
9463
|
}
|
|
9141
|
-
`}function
|
|
9142
|
-
`}function
|
|
9464
|
+
`}function oe(e){if(typeof e!="object"||e===null)return false;let n=e;return n.kind==="schema"&&typeof n.tables=="object"&&(typeof n.enums=="object"||n.enums===void 0)}function j(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function F(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(n,t)=>t.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(n,t)=>t.toUpperCase())}function le(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 f(e){return JSON.stringify(e)}function Er(e){if(typeof e=="string")return f(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return "null";if(e instanceof Date)return f(e.toISOString());throw new Error(`Unsupported SQL default value '${String(e)}'. Use string, number, boolean, null, or Date.`)}function Pr(e){return {kind:"schema",tables:Object.fromEntries(Object.entries(e.tables).map(([n,t])=>[n,{kind:"table",sqlName:t.sqlName,columns:Object.fromEntries(Object.entries(t.columns).map(([r,a])=>[r,{...a}])),relations:Object.fromEntries(Object.entries(t.relations).map(([r,a])=>[r,{...a}]))}])),enums:Object.fromEntries(Object.entries(e.enums??{}).map(([n,t])=>[n,{...t}]))}}function H(e,n,t){let r=e.tables[n];return r?r.columns[t]?.type:void 0}function mn(e,n,t,r,a,o,i){let s=n.columns[t];if(s){if(s.references&&(s.references.table!==r||s.references.column!==a))throw new Error(`Inferred relation '${e}.${t}' conflicts with explicit references(${s.references.table}.${s.references.column}).`);n.columns[t]={...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}n.columns[t]={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 fn(e,n,t){if(n.notNull===true&&n.nullable===true)throw new Error(`Invalid nullable configuration on '${e}': cannot set both notNull and nullable to true.`);return n.notNull===true?true:n.nullable===true||n.notNull===false?false:t}function gn(e,n){return `${e}:${n}`}function jr(e,n,t,r){let a=gn(e,n),o=gn(t,r);return a<=o?{key:`${a}|${o}`,leftTable:e,leftReferenceField:n,rightTable:t,rightReferenceField:r,sourceIsLeft:true}:{key:`${o}|${a}`,leftTable:t,leftReferenceField:r,rightTable:e,rightReferenceField:n,sourceIsLeft:false}}function Or(e,n){return `${e}${F(n)}Links`}function hn(e,n,t){let r=le(e),a=le(n);return r===a?`${t}${F(r)}Id`:`${r}Id`}function Dr(e,n,t){if(e.junctionTable!==n.junctionTable)throw new Error(`manyToMany pair '${t}' has conflicting junctionTable values ('${e.junctionTable}' vs '${n.junctionTable}').`);if(e.leftField!==n.leftField)throw new Error(`manyToMany pair '${t}' has conflicting left field values ('${e.leftField}' vs '${n.leftField}').`);if(e.rightField!==n.rightField)throw new Error(`manyToMany pair '${t}' has conflicting right field values ('${e.rightField}' vs '${n.rightField}').`);if(e.leftSqlName!==n.leftSqlName)throw new Error(`manyToMany pair '${t}' has conflicting left sql name values ('${e.leftSqlName}' vs '${n.leftSqlName}').`);if(e.rightSqlName!==n.rightSqlName)throw new Error(`manyToMany pair '${t}' has conflicting right sql name values ('${e.rightSqlName}' vs '${n.rightSqlName}').`);if(e.onDelete!==n.onDelete)throw new Error(`manyToMany pair '${t}' has conflicting onDelete values ('${e.onDelete}' vs '${n.onDelete}').`);if(e.onUpdate!==n.onUpdate)throw new Error(`manyToMany pair '${t}' has conflicting onUpdate values ('${e.onUpdate}' vs '${n.onUpdate}').`);return e}function Vr(e){let n=new Map;for(let[t,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=jr(t,o,a.targetTable,i),u=hn(s.leftTable,s.rightTable,"source"),l=hn(s.rightTable,s.leftTable,"target"),c={leftTable:s.leftTable,leftReferenceField:s.leftReferenceField,rightTable:s.rightTable,rightReferenceField:s.rightReferenceField,junctionTable:a.junctionTable??Or(s.leftTable,s.rightTable),leftField:s.sourceIsLeft?a.sourceField??u:a.targetField??u,rightField:s.sourceIsLeft?a.targetField??l:a.sourceField??l,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 p=n.get(s.key);p?Dr(p,c,s.key):n.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 t of n.values()){if(t.junctionTable in e.tables)throw new Error(`manyToMany auto junction table '${t.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`);let r=H(e,t.leftTable,t.leftReferenceField)??"string",a=H(e,t.rightTable,t.rightReferenceField)??"string";e.tables[t.junctionTable]={kind:"table",columns:{[t.leftField]:{kind:"column",type:r,sqlName:t.leftSqlName,notNull:true,nullable:false,references:{table:t.leftTable,column:t.leftReferenceField,onDelete:t.onDelete,onUpdate:t.onUpdate},index:true},[t.rightField]:{kind:"column",type:a,sqlName:t.rightSqlName,notNull:true,nullable:false,references:{table:t.rightTable,column:t.rightReferenceField,onDelete:t.onDelete,onUpdate:t.onUpdate},index:true}},relations:{[t.leftTable]:{kind:"relation",relation:"one",targetTable:t.leftTable,field:t.leftField,referenceField:t.leftReferenceField},[t.rightTable]:{kind:"relation",relation:"one",targetTable:t.rightTable,field:t.rightField,referenceField:t.rightReferenceField}}};}}function Br(e){for(let[n,t]of Object.entries(e.tables)){for(let[r,a]of Object.entries(t.columns))if(a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${n}.${r}': cannot set both notNull and nullable to true.`);for(let[r,a]of Object.entries(t.relations))if(a.relation!=="manyToMany"&&a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${n}.${r}': cannot set both notNull and nullable to true.`)}}function Wr(e){Br(e);let n=Pr(e);for(let[t,r]of Object.entries(n.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 u=H(n,o.targetTable,i)??o.fkType??"string";mn(t,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:fn(`${t}.${a}`,o,true),onDelete:o.onDelete,onUpdate:o.onUpdate},u);}for(let[t,r]of Object.entries(n.tables))for(let a of Object.values(r.relations)){if(a.relation!=="many")continue;let o=n.tables[a.targetTable];if(!o)continue;let i=a.referenceField??"id",s=a.field??`${le(t)}Id`;a.field=s;let u=H(n,t,i)??a.fkType??"string";mn(a.targetTable,o,s,t,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:fn(`${t}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},u);}return Vr(n),n}function bn(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function O(e){return e.notNull!==true}function Hr(e,n,t){let r=n.sqlName??j(e),a=r!==e;if(n.type==="int")return a?`t.int(${f(r)})`:"t.int()";if(n.type==="string")return n.length!==void 0?a?`t.text(${f(r)}, { length: ${n.length} })`:`t.text({ length: ${n.length} })`:a?`t.text(${f(r)})`:"t.text()";if(n.type==="boolean")return a?`t.int(${f(r)}, { mode: "boolean" })`:'t.int({ mode: "boolean" })';if(n.type==="date")return a?`t.int(${f(r)}, { mode: "timestamp_ms" })`:'t.int({ mode: "timestamp_ms" })';if(n.type==="enum"&&n.enumValues&&n.enumValues.length>0)return n.isArray?a?`t.text(${f(r)}).array()`:"t.text().array()":a?`t.text(${f(r)})`:"t.text()";if(n.type==="json"&&n.jsonShape){let o=L(n.jsonShape);return `${a?`t.text(${f(r)}, { mode: "json" })`:'t.text({ mode: "json" })'}.$type<${o}>()`}return t==="camelToSnake"&&a?`t.text(${f(r)})`:"t.text()"}function Lr(e,n,t){let r=t.field,a=t.referenceField??"id";if(!r)throw new Error(`Relation on '${e}' targeting '${t.targetTable}' is missing a local field.`);if(!(r in n.columns))throw new Error(`Relation '${e}.${r}' references missing local field '${r}'.`);return {sourceField:r,targetField:a}}function zr(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
9465
|
+
`}function Ur(e){return Object.values(e.relations).filter(n=>n.relation==="one").map(n=>n.targetTable)}function Qr(e,n,t){if(n.references)return {tableName:n.references.table,fieldName:n.references.column};let r=Object.values(t.relations).find(a=>a.relation==="one"&&a.field===e);if(r)return {tableName:r.targetTable,fieldName:r.referenceField??"id"}}function _r(e){let n=[];for(let[t,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.columns)){if(i.type!=="json"||!i.jsonShape)continue;let s=ue(i.jsonShape);a.push(`${f(o)}: { shape: ${s} },`);}a.length!==0&&n.push(`${f(t)}: {
|
|
9143
9466
|
${a.map(o=>` ${o}`).join(`
|
|
9144
9467
|
`)}
|
|
9145
|
-
},`);}return
|
|
9468
|
+
},`);}return n.length===0?`export const __appflareJsonColumns = {} as const;
|
|
9146
9469
|
`:`export const __appflareJsonColumns = {
|
|
9147
|
-
${
|
|
9470
|
+
${n.map(t=>` ${t}`).join(`
|
|
9148
9471
|
`)}
|
|
9149
9472
|
} as const;
|
|
9150
|
-
`}function
|
|
9151
|
-
targetTable: ${
|
|
9152
|
-
junctionTable: ${
|
|
9153
|
-
sourceField: ${
|
|
9154
|
-
targetField: ${
|
|
9155
|
-
|
|
9473
|
+
`}function ue(e){return e.kind==="array"?`{ kind: "array", element: ${ue(e.element)} }`:e.kind==="object"?`{ kind: "object", shape: { ${Object.entries(e.shape).map(([t,r])=>`${f(t)}: ${ue(r)}`).join(", ")} } }`:`{ kind: ${f(e.kind)} }`}function Kr(e){let n=[];for(let[t,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations))i.relation==="manyToMany"&&i.junctionTable&&a.push(`${f(o)}: {
|
|
9474
|
+
targetTable: ${f(i.targetTable)},
|
|
9475
|
+
junctionTable: ${f(i.junctionTable)},
|
|
9476
|
+
sourceField: ${f(i.sourceField??"")},
|
|
9477
|
+
targetField: ${f(i.targetField??"")},
|
|
9478
|
+
referenceField: ${f(i.referenceField??"id")},
|
|
9479
|
+
targetReferenceField: ${f(i.targetReferenceField??"id")},
|
|
9480
|
+
},`);a.length!==0&&n.push(`${f(t)}: {
|
|
9156
9481
|
${a.map(o=>` ${o}`).join(`
|
|
9157
9482
|
`)}
|
|
9158
|
-
},`);}return
|
|
9483
|
+
},`);}return n.length===0?`export const __appflareManyToMany = {} as const;
|
|
9159
9484
|
`:`export const __appflareManyToMany = {
|
|
9160
|
-
${
|
|
9485
|
+
${n.map(t=>` ${t}`).join(`
|
|
9161
9486
|
`)}
|
|
9162
9487
|
} as const;
|
|
9163
|
-
`}function
|
|
9488
|
+
`}function Jr(e){let n=[];for(let[t,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations)){if(i.relation==="one"){a.push(`${f(o)}: {
|
|
9164
9489
|
kind: "one",
|
|
9165
|
-
targetTable: ${
|
|
9166
|
-
sourceField: ${
|
|
9167
|
-
referenceField: ${
|
|
9168
|
-
},`);continue}if(i.relation==="many"){a.push(`${
|
|
9490
|
+
targetTable: ${f(i.targetTable)},
|
|
9491
|
+
sourceField: ${f(i.field??"")},
|
|
9492
|
+
referenceField: ${f(i.referenceField??"id")},
|
|
9493
|
+
},`);continue}if(i.relation==="many"){a.push(`${f(o)}: {
|
|
9169
9494
|
kind: "many",
|
|
9170
|
-
targetTable: ${
|
|
9171
|
-
sourceField: ${
|
|
9172
|
-
referenceField: ${
|
|
9173
|
-
},`);continue}a.push(`${
|
|
9495
|
+
targetTable: ${f(i.targetTable)},
|
|
9496
|
+
sourceField: ${f(i.field??"")},
|
|
9497
|
+
referenceField: ${f(i.referenceField??"id")},
|
|
9498
|
+
},`);continue}a.push(`${f(o)}: {
|
|
9174
9499
|
kind: "manyToMany",
|
|
9175
|
-
targetTable: ${
|
|
9176
|
-
junctionTable: ${
|
|
9177
|
-
sourceField: ${
|
|
9178
|
-
targetField: ${
|
|
9179
|
-
referenceField: ${
|
|
9180
|
-
targetReferenceField: ${
|
|
9181
|
-
},`);}a.length!==0&&
|
|
9500
|
+
targetTable: ${f(i.targetTable)},
|
|
9501
|
+
junctionTable: ${f(i.junctionTable??"")},
|
|
9502
|
+
sourceField: ${f(i.sourceField??"")},
|
|
9503
|
+
targetField: ${f(i.targetField??"")},
|
|
9504
|
+
referenceField: ${f(i.referenceField??"id")},
|
|
9505
|
+
targetReferenceField: ${f(i.targetReferenceField??"id")},
|
|
9506
|
+
},`);}a.length!==0&&n.push(`${f(t)}: {
|
|
9182
9507
|
${a.map(o=>` ${o}`).join(`
|
|
9183
9508
|
`)}
|
|
9184
|
-
},`);}return
|
|
9509
|
+
},`);}return n.length===0?`export const __appflareRelations = {} as const;
|
|
9185
9510
|
`:`export const __appflareRelations = {
|
|
9186
|
-
${
|
|
9511
|
+
${n.map(t=>` ${t}`).join(`
|
|
9187
9512
|
`)}
|
|
9188
9513
|
} as const;
|
|
9189
|
-
`}function
|
|
9190
|
-
${
|
|
9514
|
+
`}function Gr(e,n){let t=new Set(Object.keys(e.tables)),r=new Set;for(let l of Object.values(e.tables)){for(let c of Ur(l))t.has(c)||r.add(c);for(let c of Object.values(l.columns))c.references&&!t.has(c.references.table)&&r.add(c.references.table);}let a=new Map;for(let l of Object.values(e.tables))for(let[c,p]of Object.entries(l.columns))if(p.type==="enum"&&p.enumValues&&p.enumValues.length>0){let d=p.enumRef??`${c}`;a.has(d)||a.set(d,p);}let o=[],i=[];for(let[l,c]of a.entries()){let p=F(l),d=c.enumValues.map(y=>`"${y}"`).join(" | ");o.push(`export type ${p} = ${d};`),i.push(`export const ${p}Column = t.customType<{ data: ${p}; dataNotNull: ${p} }>({ dataType: () => "text" });`);}let s=[],u=[];for(let[l,c]of Object.entries(e.tables)){let p=c.sqlName??j(l),d=[],y=[];for(let[b,h]of Object.entries(c.columns)){let T;if(h.type==="enum"&&h.enumValues&&h.enumValues.length>0){let R=h.enumRef??b,E=F(R),V=h.sqlName??j(b);T=V!==b?`${E}Column(${f(V)})`:`${E}Column()`,h.isArray&&(T+=".array()");}else T=Hr(b,h,n);h.uuidPrimaryKey&&(T+=".$defaultFn(() => crypto.randomUUID())"),h.primaryKey&&(T+=h.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),h.notNull&&(T+=".notNull()"),h.sqlDefault!==void 0&&(T+=`.default(${Er(h.sqlDefault)})`);let C=Qr(b,h,c);if(C)if(h.references?.onDelete||h.references?.onUpdate){let R=[];h.references.onDelete&&R.push(`onDelete: ${f(h.references.onDelete)}`),h.references.onUpdate&&R.push(`onUpdate: ${f(h.references.onUpdate)}`),T+=`.references(() => ${C.tableName}.${C.fieldName}, { ${R.join(", ")} })`;}else T+=`.references(() => ${C.tableName}.${C.fieldName})`;if(h.unique){let R=typeof h.unique=="object"&&h.unique.name?h.unique.name:`${p}_${j(b)}_unique_idx`;y.push(` t.uniqueIndex(${f(R)}).on(table.${b})`);}if(h.index){let R=typeof h.index=="object"&&h.index.name?h.index.name:`${p}_${j(b)}_idx`;y.push(` t.index(${f(R)}).on(table.${b})`);}d.push(` ${b}: ${T},`);}y.length>0?s.push(`export const ${l} = table(
|
|
9515
|
+
${f(p)},
|
|
9191
9516
|
{
|
|
9192
9517
|
${d.join(`
|
|
9193
9518
|
`)}
|
|
@@ -9196,19 +9521,19 @@ ${d.join(`
|
|
|
9196
9521
|
${y.join(`,
|
|
9197
9522
|
`)}
|
|
9198
9523
|
],
|
|
9199
|
-
);`):s.push(`export const ${l} = table(${
|
|
9524
|
+
);`):s.push(`export const ${l} = table(${f(p)}, {
|
|
9200
9525
|
${d.join(`
|
|
9201
9526
|
`)}
|
|
9202
|
-
});`);let v=Object.entries(
|
|
9527
|
+
});`);let v=Object.entries(c.relations).filter(([,b])=>b.relation==="one"),A=Object.entries(c.relations).filter(([,b])=>b.relation==="many"),w=Object.entries(c.relations).filter(([,b])=>b.relation==="manyToMany");if(v.length===0&&A.length===0&&w.length===0)continue;let I=[];for(let[b,h]of v){let T=Lr(l,c,h);I.push(` ${b}: one(${h.targetTable}, {
|
|
9203
9528
|
fields: [${l}.${T.sourceField}],
|
|
9204
9529
|
references: [${h.targetTable}.${T.targetField}],
|
|
9205
|
-
}),`);}for(let[b,h]of A)I.push(` ${b}: many(${h.targetTable}),`);for(let[b,h]of w){if(!h.junctionTable)throw new Error(`manyToMany relation '${l}.${b}' is missing junctionTable after normalization.`);I.push(` ${b}: many(${h.junctionTable}),`);}
|
|
9530
|
+
}),`);}for(let[b,h]of A)I.push(` ${b}: many(${h.targetTable}),`);for(let[b,h]of w){if(!h.junctionTable)throw new Error(`manyToMany relation '${l}.${b}' is missing junctionTable after normalization.`);I.push(` ${b}: many(${h.junctionTable}),`);}u.push(`export const ${l}Relations = relations(${l}, ({ one, many }) => ({
|
|
9206
9531
|
${I.join(`
|
|
9207
9532
|
`)}
|
|
9208
9533
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
9209
9534
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
9210
9535
|
import { relations } from "drizzle-orm";
|
|
9211
|
-
${
|
|
9536
|
+
${zr(r)}
|
|
9212
9537
|
${o.join(`
|
|
9213
9538
|
`)}
|
|
9214
9539
|
${i.join(`
|
|
@@ -9218,30 +9543,30 @@ ${s.join(`
|
|
|
9218
9543
|
|
|
9219
9544
|
`)}
|
|
9220
9545
|
|
|
9221
|
-
${
|
|
9546
|
+
${u.join(`
|
|
9222
9547
|
|
|
9223
9548
|
`)}
|
|
9224
9549
|
|
|
9225
|
-
${
|
|
9550
|
+
${_r(e)}
|
|
9226
9551
|
|
|
9227
|
-
${
|
|
9552
|
+
${Kr(e)}
|
|
9228
9553
|
|
|
9229
|
-
${
|
|
9230
|
-
`}function
|
|
9554
|
+
${Jr(e)}
|
|
9555
|
+
`}function ce(e){return e.kind==="array"?`z.array(${ce(e.element)})`:e.kind==="object"?`z.object({ ${Object.entries(e.shape).map(([t,r])=>`${f(t)}: ${ce(r)}`).join(", ")} })`:e.kind==="string"?"z.string()":e.kind==="number"?"z.number()":e.kind==="boolean"?"z.boolean()":e.kind==="date"?"z.date()":"z.unknown()"}function yn(e,n,t){let r="z.unknown()";if(e.type==="int")r="z.number().int()";else if(e.type==="string")r="z.string()",e.length!==void 0&&(r+=`.max(${e.length})`);else if(e.type==="boolean")r="z.boolean()";else if(e.type==="date")r="z.date()";else if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0){let o=`z.enum([${e.enumValues.map(i=>`"${i}"`).join(", ")}])`;r=e.isArray?`z.array(${o})`:o;}else e.type==="json"&&e.jsonShape&&(r=ce(e.jsonShape));return n&&(r+=".optional()"),t&&(r+=".nullable()"),r}function Zr(e){let n=[];for(let[t,r]of Object.entries(e.tables)){let a=F(t),o=[],i=[];for(let[s,u]of Object.entries(r.columns))o.push(` ${s}: ${yn(u,bn(u),O(u))},`),i.push(` ${s}: ${yn(u,O(u),O(u))},`);n.push(`export const ${t}InsertSchema = z.object({
|
|
9231
9556
|
${o.join(`
|
|
9232
9557
|
`)}
|
|
9233
9558
|
});
|
|
9234
|
-
export const ${
|
|
9559
|
+
export const ${t}SelectSchema = z.object({
|
|
9235
9560
|
${i.join(`
|
|
9236
9561
|
`)}
|
|
9237
9562
|
});
|
|
9238
9563
|
|
|
9239
|
-
export type ${a}Insert = z.infer<typeof ${
|
|
9240
|
-
export type ${a}Select = z.infer<typeof ${
|
|
9564
|
+
export type ${a}Insert = z.infer<typeof ${t}InsertSchema>;
|
|
9565
|
+
export type ${a}Select = z.infer<typeof ${t}SelectSchema>;
|
|
9241
9566
|
`);}return `import { z } from "zod";
|
|
9242
9567
|
|
|
9243
|
-
${
|
|
9244
|
-
`)}`}function L(e){return e.kind==="array"?`Array<${L(e.element)}>`:e.kind==="object"?`{ ${Object.entries(e.shape).map(([
|
|
9568
|
+
${n.join(`
|
|
9569
|
+
`)}`}function L(e){return e.kind==="array"?`Array<${L(e.element)}>`:e.kind==="object"?`{ ${Object.entries(e.shape).map(([t,r])=>`${t}: ${L(r)}`).join("; ")} }`:e.kind==="string"?"string":e.kind==="number"?"number":e.kind==="boolean"?"boolean":e.kind==="date"?"Date":"unknown"}function Xr(e){if(e.type==="int")return "number";if(e.type==="string")return "string";if(e.type==="boolean")return "boolean";if(e.type==="date")return "Date";if(e.type==="enum"&&e.enumValues&&e.enumValues.length>0){let n=e.enumValues.map(t=>`"${t}"`).join(" | ");return e.isArray?`Array<${n}>`:n}return e.type==="json"&&e.jsonShape?L(e.jsonShape):"unknown"}function Yr(e){let n=[];for(let[r,a]of Object.entries(e.enums??{})){let o=F(r),i=a.values.map(s=>`"${s}"`).join(" | ");n.push(`export type ${o} = ${i};`);}let t=[];for(let[r,a]of Object.entries(e.tables)){let o=F(r),i=[],s=[];for(let[u,l]of Object.entries(a.columns)){let c=Xr(l),p=O(l)?" | null":"";i.push(` ${u}${O(l)?"?":""}: ${c}${p};`),s.push(` ${u}${bn(l)?"?":""}: ${c}${p};`);}t.push(`export type ${o} = {
|
|
9245
9570
|
${i.join(`
|
|
9246
9571
|
`)}
|
|
9247
9572
|
};
|
|
@@ -9249,30 +9574,30 @@ ${i.join(`
|
|
|
9249
9574
|
export type New${o} = {
|
|
9250
9575
|
${s.join(`
|
|
9251
9576
|
`)}
|
|
9252
|
-
};`);}return `${
|
|
9577
|
+
};`);}return `${n.join(`
|
|
9253
9578
|
`)}
|
|
9254
|
-
${
|
|
9579
|
+
${t.join(`
|
|
9255
9580
|
|
|
9256
9581
|
`)}
|
|
9257
|
-
`}function Xr(e,t){if(t){let n=e[t];if(!re(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(re(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function yn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=path.resolve(e.configDir,t.entry),a=path.resolve(e.configDir,t.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,t.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),c=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),l=Xr(c,t.exportName),u=Vr(l);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.dirname(i),{recursive:true})]);let p=Kr(u,n),d=Zr(u),y=Jr(u);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(u.tables)}}function ea(e){return e.replaceAll("\\","/")}function M(e,t){let n=ea(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var aa=new Set([".ts",".tsx",".mts",".cts"]);async function Tn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await Tn(a));continue}r.isFile()&&aa.has(path.extname(r.name))&&n.push(a);}return n}function ue(e){return e.replace(/\.[cm]?tsx?$/,"")}function oa(e,t){let n=e,r=false,a,o="unknown";for(;f__namespace.isCallExpression(n);){let i=n.expression;if(!f__namespace.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,n=i.expression;else if(s==="default"){r=true;let c=n.arguments[0];c&&(f__namespace.isStringLiteral(c)||f__namespace.isNumericLiteral(c)?a=c.text:c.kind===f__namespace.SyntaxKind.TrueKeyword?a="true":c.kind===f__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else n=i.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function ia(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>f__namespace.isPropertyAssignment(r)&&f__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!f__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)||n.push(oa(r.initializer,r.name.text));return n}function sa(e){return f__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===f__namespace.SyntaxKind.ExportKeyword)??false:false}function vn(e){return f__namespace.isIdentifier(e)?e.text:f__namespace.isParenthesizedExpression(e)?vn(e.expression):null}function la(e){if(!e||!f__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!f__namespace.isPropertyAssignment(r)||!f__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!f__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return f__namespace.isStringLiteral(n)||f__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):f__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>f__namespace.isStringLiteral(r)||f__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function ua(e,t){let n=f__namespace.createSourceFile(t,e,f__namespace.ScriptTarget.Latest,true,f__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(sa(a))for(let o of a.declarationList.declarations){if(!f__namespace.isIdentifier(o.name)||!o.initializer||!f__namespace.isCallExpression(o.initializer))continue;let i=vn(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"?la(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?ia(o.initializer.arguments[0]):[]});}return r}function bn(e,t,n){let r=t.replace(/\\/g,"/"),o=ue(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function ca(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 wn(e,t){let n=e.replace(/\\/g,"/"),a=ue(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 Rn(e){let t=[],n=await Tn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=path.relative(e.scanDirAbs,a),c=ua(i,a),l=[{kind:"query",kindDirectory:"queries",exports:c.filter(u=>u.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:c.filter(u=>u.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:c.filter(u=>u.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:c.filter(u=>u.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:c.filter(u=>u.kind==="storage")}];for(let u of l){if(u.exports.length===0)continue;let p=ca(s,u.kindDirectory);for(let d of u.exports){let y=u.kind==="query"||u.kind==="mutation"?wn(p,d.exportName):void 0,v=u.kind==="scheduler"||u.kind==="cron"?wn(p,d.exportName):void 0,A=u.kind==="query"||u.kind==="mutation"?[...ue(p).split("/").filter(Boolean),d.exportName]:void 0,w=u.kind==="query"?bn("queries",p,d.exportName):u.kind==="mutation"?bn("mutations",p,d.exportName):u.kind==="storage"?`/storage/managers/${d.exportName}`:`/${u.kindDirectory}/${v}`;t.push({kind:u.kind,exportName:d.exportName,filePath:a,importPath:M(e.outDirAbs,a),clientImportPath:M(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:v,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 pa(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,c=false,l=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(l){n+=d,l=false;continue}if(d==="\\"){n+=d,l=true;continue}if(!s&&!c&&d==="'"){i=!i,n+=d;continue}if(!i&&!c&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){c=!c,n+=d;continue}if(i||s||c){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let u=n.trim();return u.length>0&&t.push(u),t}function ma(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let c=0;c<e.length;c+=1){let l=e[c];if(s){s=false;continue}if(l==="\\"){s=true;continue}if(!o&&!i&&l==="'"){a=!a;continue}if(!a&&!i&&l==='"'){o=!o;continue}if(!a&&!o&&l==="`"){i=!i;continue}if(!(a||o||i)){if(l==="("){t+=1;continue}if(l===")"){t-=1;continue}if(l==="{"){n+=1;continue}if(l==="}"){n-=1;continue}if(l==="["){r+=1;continue}if(l==="]"){r-=1;continue}if(l===":"&&t===0&&n===0&&r===0)return c}}return -1}function ga(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 fa(e){let t=pa(e),n=[];for(let r of t){let a=ma(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),c=/autoincrement\s*:\s*true/i.test(i),l=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||l||c||s;n.push({name:o,expression:i,type:ga(i),optional:p,primaryKey:s,autoIncrement:c});}return n}function ha(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,c=false,l=false,u=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!l&&!u&&y==="'"){c=!c;continue}if(!c&&!u&&y==='"'){l=!l;continue}if(!c&&!l&&y==="`"){u=!u;continue}if(!(c||l||u)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let c=r(e,s);if(c===-1){a=t.exec(e);continue}let l=e.slice(s+1,c);n.push({exportName:o,tableName:i,columns:fa(l)}),a=t.exec(e);}return n}async function Sn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await Sn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function An(e,t=[]){let n=await Sn(e.scanDirAbs).catch(()=>[]),r=path.resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),c=ha(s);if(c.length>0)return {schemaPath:o,tables:c}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function wa(e){let t=e.auth.options.plugins;if(!Array.isArray(t))return [];for(let n of t)if(n&&typeof n=="object"){let r=n;if(r.id==="admin"&&"options"in r){let a=r.options;if(a&&typeof a=="object"&&"roles"in a){let o=a.roles;if(o&&typeof o=="object")return Object.keys(o)}}}return []}function xa(e){let r=e.auth.options?.user?.additionalFields;if(!r||typeof r!="object")return [];let a={string:"string",number:"number",boolean:"boolean",date:"Date"};return Object.entries(r).filter(([,o])=>o&&typeof o=="object"&&"type"in o).map(([o,i])=>({name:o,tsType:a[i.type]||"unknown"}))}async function Ta(e,t){let n=await Bun.file(e).text(),r=t.map(o=>`"${o}"`).join(" | "),a=n.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
9258
|
-
import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["']role["']\)/,`role: customType<{ data: ${r}; dataNotNull: ${r} }>({ dataType: () => "text" })("role")`);await Bun.write(e,a);}function
|
|
9259
|
-
`);let
|
|
9260
|
-
`);let
|
|
9261
|
-
`),...
|
|
9262
|
-
`),Bun.write(
|
|
9263
|
-
`);let _=path.relative(o,A).replace(/\\/g,"/"),
|
|
9264
|
-
`),
|
|
9265
|
-
`));function
|
|
9582
|
+
`}function ea(e,n){if(n){let t=e[n];if(!oe(t))throw new Error(`schemaDsl.exportName '${n}' does not point to a schema() export.`);return t}for(let t of Object.values(e))if(oe(t))return t;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function wn(e){let n=e.config.schemaDsl;if(!n)return;let t=n.namingStrategy??"camelToSnake",r=path.resolve(e.configDir,n.entry),a=path.resolve(e.configDir,n.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,n.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,n.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),u=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),l=ea(u,n.exportName),c=Wr(l);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.dirname(i),{recursive:true})]);let p=Gr(c,t),d=Yr(c),y=Zr(c);return await Promise.all([Bun.write(a,p),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function na(e){return e.replaceAll("\\","/")}function M(e,n){let t=na(path.relative(e,n)).replace(/\.tsx?$/,"");return t.startsWith(".")?t:`./${t}`}var ia=new Set([".ts",".tsx",".mts",".cts"]);async function Rn(e){let n=await promises.readdir(e,{withFileTypes:true}),t=[];for(let r of n){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){t.push(...await Rn(a));continue}r.isFile()&&ia.has(path.extname(r.name))&&t.push(a);}return t}function de(e){return e.replace(/\.[cm]?tsx?$/,"")}function sa(e,n){let t=e,r=false,a,o="unknown";for(;g__namespace.isCallExpression(t);){let i=t.expression;if(!g__namespace.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,t=i.expression;else if(s==="default"){r=true;let u=t.arguments[0];u&&(g__namespace.isStringLiteral(u)||g__namespace.isNumericLiteral(u)?a=u.text:u.kind===g__namespace.SyntaxKind.TrueKeyword?a="true":u.kind===g__namespace.SyntaxKind.FalseKeyword&&(a="false")),t=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 t=i.expression;}return {name:n,type:o,optional:r,defaultValue:a}}function la(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let n=e.properties.find(r=>g__namespace.isPropertyAssignment(r)&&g__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!n||!g__namespace.isObjectLiteralExpression(n.initializer))return [];let t=[];for(let r of n.initializer.properties)!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)||t.push(sa(r.initializer,r.name.text));return t}function ua(e){return g__namespace.isVariableStatement(e)?e.modifiers?.some(n=>n.kind===g__namespace.SyntaxKind.ExportKeyword)??false:false}function kn(e){return g__namespace.isIdentifier(e)?e.text:g__namespace.isParenthesizedExpression(e)?kn(e.expression):null}function ca(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let n=e.properties.find(r=>!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!n||!g__namespace.isPropertyAssignment(n))return [];let t=n.initializer;return g__namespace.isStringLiteral(t)||g__namespace.isNoSubstitutionTemplateLiteral(t)?[t.text.trim()].filter(r=>r.length>0):g__namespace.isArrayLiteralExpression(t)?t.elements.map(r=>g__namespace.isStringLiteral(r)||g__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function da(e,n){let t=g__namespace.createSourceFile(n,e,g__namespace.ScriptTarget.Latest,true,g__namespace.ScriptKind.TS),r=[];for(let a of t.statements)if(ua(a))for(let o of a.declarationList.declarations){if(!g__namespace.isIdentifier(o.name)||!o.initializer||!g__namespace.isCallExpression(o.initializer))continue;let i=kn(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"?ca(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?la(o.initializer.arguments[0]):[]});}return r}function xn(e,n,t){let r=n.replace(/\\/g,"/"),o=de(r).split("/").filter(Boolean);return `/${[e,...o,t].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function pa(e,n){let t=e.replace(/\\/g,"/"),r=`${n}/`,a=t.indexOf(r);return a>=0?t.slice(a+r.length):t===n?"index.ts":t}function Tn(e,n){let t=e.replace(/\\/g,"/"),a=de(t).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,n].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function Sn(e){let n=[],t=await Rn(e.scanDirAbs).catch(()=>[]);for(let a of t){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=path.relative(e.scanDirAbs,a),u=da(i,a),l=[{kind:"query",kindDirectory:"queries",exports:u.filter(c=>c.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:u.filter(c=>c.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:u.filter(c=>c.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:u.filter(c=>c.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:u.filter(c=>c.kind==="storage")}];for(let c of l){if(c.exports.length===0)continue;let p=pa(s,c.kindDirectory);for(let d of c.exports){let y=c.kind==="query"||c.kind==="mutation"?Tn(p,d.exportName):void 0,v=c.kind==="scheduler"||c.kind==="cron"?Tn(p,d.exportName):void 0,A=c.kind==="query"||c.kind==="mutation"?[...de(p).split("/").filter(Boolean),d.exportName]:void 0,w=c.kind==="query"?xn("queries",p,d.exportName):c.kind==="mutation"?xn("mutations",p,d.exportName):c.kind==="storage"?`/storage/managers/${d.exportName}`:`/${c.kindDirectory}/${v}`;n.push({kind:c.kind,exportName:d.exportName,filePath:a,importPath:M(e.outDirAbs,a),clientImportPath:M(path.resolve(e.outDirAbs,"client"),a),routePath:w,handlerName:y,clientSegments:A,taskName:v,cronTriggers:d.cronTriggers,args:d.args});}}}n.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of n){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 n}function fa(e){let n=[],t="",r=0,a=0,o=0,i=false,s=false,u=false,l=false;for(let p=0;p<e.length;p+=1){let d=e[p];if(l){t+=d,l=false;continue}if(d==="\\"){t+=d,l=true;continue}if(!s&&!u&&d==="'"){i=!i,t+=d;continue}if(!i&&!u&&d==='"'){s=!s,t+=d;continue}if(!i&&!s&&d==="`"){u=!u,t+=d;continue}if(i||s||u){t+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let y=t.trim();y.length>0&&n.push(y),t="";continue}t+=d;}let c=t.trim();return c.length>0&&n.push(c),n}function ga(e){let n=0,t=0,r=0,a=false,o=false,i=false,s=false;for(let u=0;u<e.length;u+=1){let l=e[u];if(s){s=false;continue}if(l==="\\"){s=true;continue}if(!o&&!i&&l==="'"){a=!a;continue}if(!a&&!i&&l==='"'){o=!o;continue}if(!a&&!o&&l==="`"){i=!i;continue}if(!(a||o||i)){if(l==="("){n+=1;continue}if(l===")"){n-=1;continue}if(l==="{"){t+=1;continue}if(l==="}"){t-=1;continue}if(l==="["){r+=1;continue}if(l==="]"){r-=1;continue}if(l===":"&&n===0&&t===0&&r===0)return u}}return -1}function ha(e){let n=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(n)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(n)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(n)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(n)?"number":/\.(text|varchar|char)\s*\(/.test(n)?"string":/\.(boolean|bool)\s*\(/.test(n)?"boolean":"unknown"}function ya(e){let n=fa(e),t=[];for(let r of n){let a=ga(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),u=/autoincrement\s*:\s*true/i.test(i),l=/\.default\s*\(/i.test(i),p=!/\.notnull\s*\(/i.test(i)||l||u||s;t.push({name:o,expression:i,type:ha(i),optional:p,primaryKey:s,autoIncrement:u});}return t}function ba(e){let n=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,t=[],r=(o,i)=>{let s=0,u=false,l=false,c=false,p=false;for(let d=i;d<o.length;d+=1){let y=o[d];if(p){p=false;continue}if(y==="\\"){p=true;continue}if(!l&&!c&&y==="'"){u=!u;continue}if(!u&&!c&&y==='"'){l=!l;continue}if(!u&&!l&&y==="`"){c=!c;continue}if(!(u||l||c)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=n.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",n.lastIndex);if(s===-1){a=n.exec(e);continue}let u=r(e,s);if(u===-1){a=n.exec(e);continue}let l=e.slice(s+1,u);t.push({exportName:o,tableName:i,columns:ya(l)}),a=n.exec(e);}return t}async function Nn(e){let n=await promises.readdir(e,{withFileTypes:true}),t=[];for(let r of n){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){t.push(...await Nn(a));continue}r.isFile()&&r.name==="schema.ts"&&t.push(a);}return t}async function $n(e,n=[]){let t=await Nn(e.scanDirAbs).catch(()=>[]),r=path.resolve(e.configDir,"schema.ts"),a=[...n,...t.length?t:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),u=ba(s);if(u.length>0)return {schemaPath:o,tables:u}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function Ta(e){let n=e.auth.options.plugins;if(!Array.isArray(n))return [];for(let t of n)if(t&&typeof t=="object"){let r=t;if(r.id==="admin"&&"options"in r){let a=r.options;if(a&&typeof a=="object"&&"roles"in a){let o=a.roles;if(o&&typeof o=="object")return Object.keys(o)}}}return []}function va(e){let r=e.auth.options?.user?.additionalFields;if(!r||typeof r!="object")return [];let a={string:"string",number:"number",boolean:"boolean",date:"Date"};return Object.entries(r).filter(([,o])=>o&&typeof o=="object"&&"type"in o).map(([o,i])=>({name:o,tsType:a[i.type]||"unknown"}))}async function Ra(e,n){let t=await Bun.file(e).text(),r=n.map(o=>`"${o}"`).join(" | "),a=t.replace(/(import.*?from\s+["']drizzle-orm\/sqlite-core["'])/,`$1
|
|
9583
|
+
import { customType } from "drizzle-orm/sqlite-core"`).replace(/role:\s*text\(["']role["']\)/,`role: customType<{ data: ${r}; dataNotNull: ${r} }>({ dataType: () => "text" })("role")`);await Bun.write(e,a);}function ka(e,n){let t=path.relative(e,n).replace(/\\/g,"/");return t.startsWith(".")?t:`./${t}`}async function Fn(e){let{outDirAbs:n,wranglerOutDirAbs:t,config:r,configPath:a,configDir:o}=e,i=M(n,a),s=path.resolve(n,"client"),u=M(s,a),l=performance.now();await Promise.all([promises.mkdir(n,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(t,{recursive:true})]),process.stdout.write(`\u{1F4C1} Directories (${(performance.now()-l).toFixed(0)}ms)
|
|
9584
|
+
`);let c=path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)))),p=path.join(path.dirname(Bun.resolveSync("typescript/package.json",c)),"bin","tsc"),d=path.join(path.dirname(Bun.resolveSync("@better-auth/cli/package.json",c)),"dist","index.mjs"),y=path.resolve(n,"server.ts"),v=path.resolve(n,"client.ts"),A=path.resolve(n,"auth.config.ts"),w=path.resolve(n,"auth.schema.ts"),I=path.resolve(n,"drizzle.config.ts"),b=path.resolve(t,"wrangler.json"),h=await wn(e),T=await $n(e,h?[h.schemaPath]:[]),C=M(n,T.schemaPath),R=await Sn(e);process.stdout.write(`\u{1F50D} ${R.length} handler(s) (${(performance.now()-l).toFixed(0)}ms)
|
|
9585
|
+
`);let E=Ta(r),V=va(r),ge=vt(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),Wn=Ne(u,R),Hn=Z(C,R,r.r2[0]?.binding,E,V),Ln=xe(i),zn=h?[ka(o,h.schemaPath),...r.schema.filter(x=>!/(^|\/)schema\.ts$/.test(x))]:r.schema,Un=$e(zn),Qn=kt(e,R),_n=pn(C,T,R),Kn=path.resolve(n,"admin.routes.ts"),Jn=Hn.map(x=>Bun.write(path.resolve(n,x.relativePath),x.source)),Gn=Wn.map(x=>Bun.write(path.resolve(n,x.relativePath),x.source));await Promise.all([Bun.write(y,ge),Bun.write(v,`export * from "./client/index";
|
|
9586
|
+
`),...Gn,...Jn,Bun.write(A,Ln),Bun.write(w,""),Bun.write(I,Un),Bun.write(b,`${JSON.stringify(Qn,null,2)}
|
|
9587
|
+
`),Bun.write(Kn,_n)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-l).toFixed(0)}ms)
|
|
9588
|
+
`);let _=path.relative(o,A).replace(/\\/g,"/"),Zn=_.startsWith(".")?_:`./${_}`,K=path.relative(o,w).replace(/\\/g,"/"),Xn=K.startsWith(".")?K:`./${K}`,he=await Bun.spawn([process.execPath,d,"generate","--config",Zn,"--output",Xn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(he!==0)throw new Error(`better-auth generation failed with exit code ${he}`);process.stdout.write(`\u{1F510} Auth schema (${(performance.now()-l).toFixed(0)}ms)
|
|
9589
|
+
`),E.length>0&&(await Ra(w,E),process.stdout.write(`\u{1F527} Patched role type (${(performance.now()-l).toFixed(0)}ms)
|
|
9590
|
+
`));function Yn(x={}){return {compilerOptions:{lib:["es2024"],types:["@types/node","@cloudflare/workers-types/2023-07-01"],module:"es2022",target:"es2024",moduleResolution:"bundler",strictNullChecks:true,skipLibCheck:true,declaration:true,emitDeclarationOnly:true,noCheck:true,jsx:"react-jsx",paths:{"_generated/*":["./*"]},...x},include:["./*.ts","./client/*.ts"]}}let ye=path.resolve(n,"tsconfig.js.json");await Promise.all([Bun.write(ye,`${JSON.stringify(Yn({declaration:true,emitDeclarationOnly:false}),null,2)}
|
|
9266
9591
|
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-l).toFixed(0)}ms)
|
|
9267
|
-
`);async function
|
|
9268
|
-
`);let N=await Bun.spawn([process.execPath,p,"-p",x],{cwd:
|
|
9269
|
-
`);async function
|
|
9270
|
-
`);let
|
|
9271
|
-
`);let
|
|
9592
|
+
`);async function er(x,$){process.stdout.write(`\u2699\uFE0F ${$}... (${(performance.now()-l).toFixed(0)}ms)
|
|
9593
|
+
`);let N=await Bun.spawn([process.execPath,p,"-p",x],{cwd:n,stdout:"inherit",stderr:"inherit"}).exited;if(N!==0)throw new Error(`tsc ${$} failed with exit code ${N}`)}await er(ye,"JS files"),process.stdout.write(`\u2705 JS + declarations (${(performance.now()-l).toFixed(0)}ms)
|
|
9594
|
+
`);async function be(x){let $=await promises.readdir(x,{withFileTypes:true});for(let k of $){let N=path.join(x,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith("."))continue;await be(N);}else k.name.endsWith(".ts")&&!k.name.endsWith(".d.ts")&&await promises.rm(N);}}await be(n),process.stdout.write(`\u{1F4E6} Cleaned .ts files (${(performance.now()-l).toFixed(0)}ms)
|
|
9595
|
+
`);let tr=n+"/";async function we(x){let $=await promises.readdir(x,{withFileTypes:true});for(let k of $){let N=path.join(x,k.name);if(k.isDirectory()){if(k.name==="node_modules"||k.name.startsWith(".")||N===n)continue;await we(N);}else !N.startsWith(tr)&&(k.name.endsWith(".d.ts")||k.name.endsWith(".js"))&&await promises.rm(N);}}await we(o),process.stdout.write(`\u{1F9F9} Cleanup (${(performance.now()-l).toFixed(0)}ms)
|
|
9596
|
+
`);let nr=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.existsSync(nr)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-l).toFixed(0)}ms)
|
|
9272
9597
|
`);let $=await Bun.spawn([process.execPath,p,"--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if($!==0)throw new Error(`TypeScript build failed with exit code ${$}`);process.stdout.write(`\u2705 Build complete (${(performance.now()-l).toFixed(0)}ms)
|
|
9273
|
-
`);}}var
|
|
9274
|
-
`);return}process.stdout.write(`\u2705 Generated server/client in ${
|
|
9275
|
-
`);}async function
|
|
9276
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
9277
|
-
`),await o();}),process.stdout.write(`\u{1F440} Watching ${
|
|
9278
|
-
`);}async function
|
|
9598
|
+
`);}}var Mn=zod.z.object({binding:zod.z.string().min(1),databaseName:zod.z.string().min(1),databaseId:zod.z.string().min(1),previewDatabaseId:zod.z.string().min(1).optional(),migrationsDir:zod.z.string().min(1).optional()}).strict(),In=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),En=zod.z.object({binding:zod.z.string().min(1),bucketName:zod.z.string().min(1),previewBucketName:zod.z.string().min(1).optional(),jurisdiction:zod.z.string().min(1).optional()}).strict(),Pn=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),queue:zod.z.string().min(1).optional()}).strict(),$a=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),className:zod.z.string().min(1).optional(),objectName:zod.z.string().min(1).optional(),subscribePath:zod.z.string().min(1).optional(),websocketPath:zod.z.string().min(1).optional(),protocol:zod.z.string().min(1).optional()}).strict(),Ca=zod.z.object({scanDir:zod.z.string().min(1),outDir:zod.z.string().min(1),wranglerOutDir:zod.z.string().min(1).optional(),wranglerOutPath:zod.z.string().min(1).optional(),schema:zod.z.array(zod.z.string()).min(1),schemaDsl:zod.z.object({entry:zod.z.string().min(1),exportName:zod.z.string().min(1).optional(),outFile:zod.z.string().min(1).optional(),typesOutFile:zod.z.string().min(1).optional(),zodOutFile:zod.z.string().min(1).optional(),namingStrategy:zod.z.literal("camelToSnake").optional()}).strict().optional(),database:zod.z.union([Mn,zod.z.array(Mn).min(1)]),kv:zod.z.union([In,zod.z.array(In)]).optional(),r2:zod.z.union([En,zod.z.array(En)]).optional(),auth:zod.z.object({enabled:zod.z.boolean(),basePath:zod.z.string().min(1),options:zod.z.custom(e=>typeof e=="object"&&e!==null),clientOptions:zod.z.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:Pn.optional(),realtime:$a.optional(),wranglerOverrides:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),build:zod.z.boolean().optional()}).strict();function jn(e){return typeof e=="object"&&e!==null}function qa(e){let n=jn(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,t=Pn.safeParse(n);return t.success?t.data:{}}function Fa(e){if(!jn(e)||!("scheduler"in e))return e;let{scheduler:n,...t}=e;return t}function Ma(e){let t={...qa(e)??{},...e.scheduler??{}},r=e.realtime??{};return {...e,database:Array.isArray(e.database)?e.database:[e.database],kv:e.kv?Array.isArray(e.kv)?e.kv:[e.kv]:[],r2:e.r2?Array.isArray(e.r2)?e.r2:[e.r2]:[],scheduler:{enabled:t.enabled??true,binding:t.binding??"APPFLARE_SCHEDULER_QUEUE",queue:t.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:Fa(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function D(e){let n=path.isAbsolute(e??"")?e:path.resolve(process.cwd(),e??"appflare.config.ts"),t=path.dirname(n),o=(await import(url.pathToFileURL(n).href)).default,i=Ca.parse(o),s=Ma(i);return {configPath:n,configDir:t,scanDirAbs:path.resolve(t,s.scanDir),outDirAbs:path.resolve(t,s.outDir),wranglerOutDirAbs:path.resolve(t,s.wranglerOutDir),config:s}}function ja(e){let n=e;for(;;){if(fs.existsSync(path.resolve(n,"package.json")))return n;let t=path.dirname(n);if(t===n)return e;n=t;}}async function Q(e,n={}){let t=await D(e);if(n.build!==void 0&&(t.config.build=n.build),await Fn(t),t.wranglerOutDirAbs===t.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${t.outDirAbs}
|
|
9599
|
+
`);return}process.stdout.write(`\u2705 Generated server/client in ${t.outDirAbs} and wrangler.json in ${t.wranglerOutDirAbs}
|
|
9600
|
+
`);}async function Dn(e,n={}){if(await Q(e,{build:n.build}),!n.watch)return;let t=await D(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await Q(e,{build:n.build});}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
9601
|
+
`);}finally{r=false,a&&(a=false,await o());}};Ia__default.default.watch(t.scanDirAbs,{ignoreInitial:true,ignored:s=>s.includes("/_generated/")||s.includes("/dist/")||s.includes("/out/")||s.includes("/node_modules/")||s.endsWith(".d.ts")}).on("all",async(s,u)=>{process.stdout.write(`\u{1F504} Change detected: ${u}
|
|
9602
|
+
`),await o();}),process.stdout.write(`\u{1F440} Watching ${t.scanDirAbs}
|
|
9603
|
+
`);}async function Vn(e,n={}){let t=await D(e),r=ja(process.cwd());if([!!n.local,!!n.remote,!!n.preview].filter(Boolean).length>1)throw new Error("Only one of --local, --remote, or --preview can be set.");let o=path.resolve(t.outDirAbs,"drizzle.config.js"),i=process.platform==="win32"?"npx.cmd":"npx",u=await Bun.spawn([i,"drizzle-kit","generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(u!==0)throw new Error(`drizzle-kit generate failed with exit code ${u}`);let l=t.config.database[0].databaseName,c=[i,"wrangler","d1","migrations","apply",l];n.local?c.push("--local"):n.remote?c.push("--remote"):n.preview&&c.push("--preview");let d=await Bun.spawn(c,{cwd:t.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 Bn(e,n={name:"",email:"",password:""}){let t=await D(e);if([!!n.local,!!n.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(n.password),i=crypto.randomUUID(),s=crypto.randomUUID(),u=Date.now(),l=n.name.replace(/'/g,"''"),c=n.email.replace(/'/g,"''"),p=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${l}', '${c}', 1, ${u}, ${u}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${c}', 'credential', '${i}', '${o}', ${u}, ${u});`].join(" "),d=t.config.database[0].databaseName,v=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${p}`];n.local?v.push("--local"):n.remote&&v.push("--remote");let w=await Bun.spawn(v,{cwd:t.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(w!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${w}`);console.log("\u2705 Admin user "+n.email+" created successfully!");}var P=new commander.Command;P.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");P.command("build").description("Generate server.ts, client.ts, auth.config.js, drizzle.config.js, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--no-build","Skip TypeScript build step").action(async e=>{await Q(e.config,{build:e.build});});P.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 Dn(e.config,{watch:e.watch,build:e.build});});P.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 Vn(e.config,{local:e.local,remote:e.remote,preview:e.preview});});P.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 Bn(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 P.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|