appflare 0.2.32 → 0.2.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/commands/index.ts +9 -0
- package/cli/generate.ts +86 -40
- package/dist/cli/index.js +243 -232
- package/dist/cli/index.mjs +243 -232
- package/dist/react/index.js +1 -1
- package/dist/react/index.mjs +1 -1
- package/package.json +3 -3
- package/react/use-infinite-query.ts +2 -2
- package/react/use-query.ts +2 -2
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
'use strict';var commander=require('commander'),
|
|
2
|
+
'use strict';var commander=require('commander'),va=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 va__default=/*#__PURE__*/_interopDefault(va);var g__namespace=/*#__PURE__*/_interopNamespace(g);function pe(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 me(){return `import { createAuthClient, type BetterAuthClientOptions } from "better-auth/client";
|
|
61
61
|
import type {
|
|
62
62
|
AppflareAuth,
|
|
63
63
|
AppflareAuthTokenResolver,
|
|
@@ -166,8 +166,8 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
166
166
|
): Appflare<Options> {
|
|
167
167
|
return new Appflare(options);
|
|
168
168
|
}
|
|
169
|
-
`}function
|
|
170
|
-
`)}function
|
|
169
|
+
`}function Jn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function ge(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Zn(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function fe(e){let t={children:new Map};for(let n of e){let r=t;for(let a of n.segments){let o=r.children.get(a);o||(o={children:new Map},r.children.set(a,o)),r=o;}r.operation=n;}return t}function L(e,t=1){let n=" ".repeat(t),r=" ".repeat(t+1),a=Array.from(e.children.entries()).sort(([s],[i])=>s.localeCompare(i));if(a.length===0)return e.operation?`${e.operation.alias}Route(runtime)`:"{}";let o=["{"];for(let[s,i]of a)o.push(`${r}${Zn(s)}: ${L(i,t+1)},`);return e.operation&&(o.push(`${r}run: ${e.operation.alias}Route(runtime).run,`),o.push(`${r}schema: ${e.operation.alias}Route(runtime).schema,`),e.operation.kind==="query"&&o.push(`${r}subscribe: ${e.operation.alias}Route(runtime).subscribe,`)),o.push(`${n}}`),o.join(`
|
|
170
|
+
`)}function Yn(e,t){if(e.kind!=="query"&&e.kind!=="mutation")return null;let n=e.clientSegments&&e.clientSegments.length>0?e.clientSegments:e.routePath.replace(/^\//,"").split("/").filter(Boolean).slice(1);if(n.length===0)return null;let r=Jn(`op_${t}_${e.kind}_${n.join("_")}`);return {kind:e.kind,routePath:e.routePath,queryName:e.handlerName??n.join("/"),segments:n,importPath:e.clientImportPath,exportName:e.exportName,alias:r,schemaConst:`${r}Schema`,typeBase:`${ge(e.kind)}${ge(n.join("_"))}`}}function Xn(e){let t=`${e.typeBase}Input`,n=`${e.typeBase}Output`,r=`${e.typeBase}Schema`,a=e.kind==="query"?"GET":"POST";return e.kind==="query"?`const ${e.alias}Route = (
|
|
171
171
|
runtime: RequestRuntime,
|
|
172
172
|
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}> => {
|
|
173
173
|
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}>["run"] = async (
|
|
@@ -353,15 +353,15 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
353
353
|
schema: ${r},
|
|
354
354
|
run,
|
|
355
355
|
};
|
|
356
|
-
};`}function
|
|
357
|
-
`),o=t.map(
|
|
358
|
-
export type ${
|
|
359
|
-
export type ${f} = Awaited<ReturnType<typeof ${
|
|
360
|
-
export const ${d} = ${
|
|
356
|
+
};`}function U(e){let t=e.map((c,u)=>Yn(c,u)).filter(c=>c!==null),n=t.filter(c=>c.kind==="query"),r=t.filter(c=>c.kind==="mutation"),a=t.map(c=>`import { ${c.exportName} as ${c.alias} } from "${c.importPath}";`).join(`
|
|
357
|
+
`),o=t.map(c=>{let u=`${c.typeBase}Input`,f=`${c.typeBase}Output`,d=`${c.typeBase}Schema`;return `const ${c.schemaConst} = z.object(${c.alias}.definition.args);
|
|
358
|
+
export type ${u} = z.input<typeof ${c.schemaConst}>;
|
|
359
|
+
export type ${f} = Awaited<ReturnType<typeof ${c.alias}.definition.handler>>;
|
|
360
|
+
export const ${d} = ${c.schemaConst};`}).join(`
|
|
361
361
|
|
|
362
|
-
`),
|
|
362
|
+
`),s=t.map(c=>Xn(c)).join(`
|
|
363
363
|
|
|
364
|
-
`),
|
|
364
|
+
`),i=L(fe(n)),l=L(fe(r));return `import { z } from "zod";
|
|
365
365
|
import type {
|
|
366
366
|
AppflareErrorMode,
|
|
367
367
|
AppflareRequestError,
|
|
@@ -703,7 +703,7 @@ async function requestRoute<TOutput>(
|
|
|
703
703
|
return body as TOutput;
|
|
704
704
|
}
|
|
705
705
|
|
|
706
|
-
${
|
|
706
|
+
${s}
|
|
707
707
|
|
|
708
708
|
export function createQueriesClient(
|
|
709
709
|
endpoint: string,
|
|
@@ -718,7 +718,7 @@ export function createQueriesClient(
|
|
|
718
718
|
options,
|
|
719
719
|
};
|
|
720
720
|
|
|
721
|
-
return ${
|
|
721
|
+
return ${i} as const;
|
|
722
722
|
}
|
|
723
723
|
|
|
724
724
|
export function createMutationsClient(
|
|
@@ -737,11 +737,11 @@ export function createMutationsClient(
|
|
|
737
737
|
|
|
738
738
|
export type QueriesClient = ReturnType<typeof createQueriesClient>;
|
|
739
739
|
export type MutationsClient = ReturnType<typeof createMutationsClient>;
|
|
740
|
-
`}function
|
|
740
|
+
`}function he(){return `export * from "./types";
|
|
741
741
|
export * from "./appflare";
|
|
742
742
|
export * from "./storage";
|
|
743
743
|
export * from "./handlers";
|
|
744
|
-
`}function
|
|
744
|
+
`}function ye(){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 be(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 we(e,t){return [{relativePath:"client/index.ts",source:he()},{relativePath:"client/types.ts",source:be(e)},{relativePath:"client/storage.ts",source:ye()},{relativePath:"client/handlers.ts",source:U(t)},{relativePath:"client/appflare.ts",source:me()}]}function xe(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 Te(){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 ve(){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 Re(){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 ke(){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 Se(){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 Ae(){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 Ne(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 $e(e){return `import type { Context } from "hono";
|
|
1465
1465
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
1466
1466
|
import { createAuth } from "./auth.config";
|
|
1467
1467
|
import {
|
|
@@ -1480,20 +1480,20 @@ import {
|
|
|
1480
1480
|
createQueryDb,
|
|
1481
1481
|
} from "./handlers";
|
|
1482
1482
|
|
|
1483
|
-
${
|
|
1483
|
+
${ve()}
|
|
1484
1484
|
|
|
1485
|
-
${
|
|
1485
|
+
${Te()}
|
|
1486
1486
|
|
|
1487
|
-
${
|
|
1487
|
+
${Re()}
|
|
1488
1488
|
|
|
1489
|
-
${
|
|
1489
|
+
${ke()}
|
|
1490
1490
|
|
|
1491
|
-
${
|
|
1491
|
+
${Se()}
|
|
1492
1492
|
|
|
1493
|
-
${
|
|
1493
|
+
${Ae()}
|
|
1494
1494
|
|
|
1495
|
-
${
|
|
1496
|
-
`}function
|
|
1495
|
+
${Ne(e)}
|
|
1496
|
+
`}function Ce(){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 qe(){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
|
+
${Ce()}
|
|
1545
|
+
`}function Me(){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 Ie(){return `type Primitive = string | number | boolean | Date;
|
|
1649
1649
|
type NonNil<T> = Exclude<T, null | undefined>;
|
|
1650
1650
|
type Friendly<T> = T extends Date ? Date | number : T;
|
|
1651
1651
|
type Comparable<T> = Friendly<Extract<NonNil<T>, Primitive>>;
|
|
@@ -1923,7 +1923,7 @@ export type QueryDeleteArgs<TName extends TableName> = {
|
|
|
1923
1923
|
where?: WhereInput<TableModel<TName>, TName>;
|
|
1924
1924
|
limit?: number;
|
|
1925
1925
|
};
|
|
1926
|
-
`}function
|
|
1926
|
+
`}function Fe(){return `type AggregateWithInput<TName extends TableName> =
|
|
1927
1927
|
QueryWithInput<TName, NativeFindManyWith<TName>>;
|
|
1928
1928
|
|
|
1929
1929
|
type NumericFieldKey<TName extends TableName> = NumericModelFieldKey<
|
|
@@ -2055,7 +2055,7 @@ export type DbMutationEvent = {
|
|
|
2055
2055
|
export type QueryDbOptions = {
|
|
2056
2056
|
onMutation?: (event: DbMutationEvent) => void;
|
|
2057
2057
|
};
|
|
2058
|
-
`}function
|
|
2058
|
+
`}function Pe(){return `function isRecord(value: unknown): value is Record<string, unknown> {
|
|
2059
2059
|
return typeof value === "object" && value !== null;
|
|
2060
2060
|
}
|
|
2061
2061
|
|
|
@@ -3155,7 +3155,7 @@ function inferConflictTarget(table: unknown): string[] {
|
|
|
3155
3155
|
|
|
3156
3156
|
return [];
|
|
3157
3157
|
}
|
|
3158
|
-
`}function
|
|
3158
|
+
`}function De(){return `const mergedSchema = {
|
|
3159
3159
|
...authSchema,
|
|
3160
3160
|
...schema,
|
|
3161
3161
|
};
|
|
@@ -3430,9 +3430,9 @@ type TableFindFirstResult<
|
|
|
3430
3430
|
type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
3431
3431
|
(typeof mergedSchema)[TName]
|
|
3432
3432
|
>;
|
|
3433
|
-
`}function
|
|
3433
|
+
`}function Ee(){return [De(),Ie(),Fe(),Pe()].join(`
|
|
3434
3434
|
|
|
3435
|
-
`)}function
|
|
3435
|
+
`)}function Oe(){return ` count: async (args?: QueryCountArgs<TableName>) => {
|
|
3436
3436
|
const withValue = args?.with;
|
|
3437
3437
|
const pathSegments = args?.field
|
|
3438
3438
|
? splitAggregateFieldPath(String(args.field))
|
|
@@ -3603,7 +3603,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3603
3603
|
},
|
|
3604
3604
|
}) as AppflareQueryDb;
|
|
3605
3605
|
}
|
|
3606
|
-
`}function
|
|
3606
|
+
`}function je(){return `export class AppflareHandledError extends Error {
|
|
3607
3607
|
public readonly status: number;
|
|
3608
3608
|
public readonly payload: unknown;
|
|
3609
3609
|
|
|
@@ -3613,7 +3613,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3613
3613
|
this.payload = payload;
|
|
3614
3614
|
}
|
|
3615
3615
|
}
|
|
3616
|
-
`}function
|
|
3616
|
+
`}function Be(){return ` findMany: (args?: Record<string, unknown>) => {
|
|
3617
3617
|
const where = isRecord(args?.where)
|
|
3618
3618
|
? (args?.where as Record<string, unknown>)
|
|
3619
3619
|
: undefined;
|
|
@@ -3767,7 +3767,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3767
3767
|
);
|
|
3768
3768
|
});
|
|
3769
3769
|
},
|
|
3770
|
-
`}function
|
|
3770
|
+
`}function Ve(){return `export function createQueryDb(
|
|
3771
3771
|
$db: AppflareDb,
|
|
3772
3772
|
options?: QueryDbOptions,
|
|
3773
3773
|
): AppflareQueryDb {
|
|
@@ -3809,7 +3809,7 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
3809
3809
|
};
|
|
3810
3810
|
|
|
3811
3811
|
const tableApi = {
|
|
3812
|
-
`}function
|
|
3812
|
+
`}function We(){return ` insert: async <TArgs extends QueryInsertArgs<TableName>>(args: TArgs) => {
|
|
3813
3813
|
const transaction = ($db as any).transaction;
|
|
3814
3814
|
|
|
3815
3815
|
const valuesArray = Array.isArray(args.values)
|
|
@@ -4503,9 +4503,9 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4503
4503
|
);
|
|
4504
4504
|
return rows;
|
|
4505
4505
|
},
|
|
4506
|
-
`}function
|
|
4506
|
+
`}function He(){return [Ve(),Be(),We(),Oe(),je()].join(`
|
|
4507
4507
|
|
|
4508
|
-
`)}function
|
|
4508
|
+
`)}function ze(){return `type AuthSession = typeof auth.$Infer.Session;
|
|
4509
4509
|
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
4510
4510
|
type User = AuthSession['user']
|
|
4511
4511
|
type Session = AuthSession['session']
|
|
@@ -4594,7 +4594,7 @@ export type AppflareContext = {
|
|
|
4594
4594
|
storage: AppflareStorage;
|
|
4595
4595
|
error: (status: number, message: string, details?: unknown) => never;
|
|
4596
4596
|
};
|
|
4597
|
-
`}function
|
|
4597
|
+
`}function Le(){return `type InferOperationArgs<TShape extends ZodRawShape> = z.output<z.ZodObject<TShape>>;
|
|
4598
4598
|
|
|
4599
4599
|
export type SchedulerEnqueueOptions = {
|
|
4600
4600
|
delaySeconds?: number;
|
|
@@ -4726,20 +4726,20 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
4726
4726
|
definition,
|
|
4727
4727
|
};
|
|
4728
4728
|
}
|
|
4729
|
-
`}function
|
|
4729
|
+
`}function Ue(){return [Me(),Ee(),He(),ze(),Le()].join(`
|
|
4730
4730
|
|
|
4731
|
-
`)}function
|
|
4731
|
+
`)}function Qe(e){return `import type { Context } from "hono";
|
|
4732
4732
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
4733
4733
|
import { drizzle } from "drizzle-orm/d1";
|
|
4734
4734
|
import { z, type ZodRawShape } from "zod";
|
|
4735
4735
|
import * as authSchema from "./auth.schema";
|
|
4736
4736
|
import * as schema from "${e}";
|
|
4737
4737
|
|
|
4738
|
-
${
|
|
4739
|
-
`}function
|
|
4740
|
-
`)}function
|
|
4741
|
-
`)}function
|
|
4742
|
-
`)}function
|
|
4738
|
+
${Ue()}
|
|
4739
|
+
`}function er(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function tr(e,t){let n=e.routePath.replace(/^\//,"").replace(/\//g,"_");return er(`op_${t}_${n}`)}function nr(e){return e.map((t,n)=>({operation:t,index:n,alias:tr(t,n)}))}function rr(e){return e.map(({operation:t,alias:n})=>`import { ${t.exportName} as ${n} } from "${t.importPath}";`).join(`
|
|
4740
|
+
`)}function ar(e){return e.filter(({operation:t})=>t.kind==="query"||t.kind==="mutation").map(({alias:t})=>`const ${`${t}Schema`} = z.object(${t}.definition.args);`).join(`
|
|
4741
|
+
`)}function or(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({alias:t})=>`const ${`${t}SchedulerSchema`} = ${t}.definition.args ? z.object(${t}.definition.args) : z.undefined();`).join(`
|
|
4742
|
+
`)}function ir(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
4743
4743
|
app.get(
|
|
4744
4744
|
"${t.routePath}",
|
|
4745
4745
|
sValidator("query", ${r}),
|
|
@@ -4752,7 +4752,7 @@ ${We()}
|
|
|
4752
4752
|
}
|
|
4753
4753
|
},
|
|
4754
4754
|
);`}).join(`
|
|
4755
|
-
`)}function
|
|
4755
|
+
`)}function sr(e){return e.filter(({operation:t})=>t.kind==="mutation").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
4756
4756
|
app.post(
|
|
4757
4757
|
"${t.routePath}",
|
|
4758
4758
|
sValidator("json", ${r}),
|
|
@@ -4767,26 +4767,26 @@ ${We()}
|
|
|
4767
4767
|
}
|
|
4768
4768
|
},
|
|
4769
4769
|
);`}).join(`
|
|
4770
|
-
`)}function
|
|
4770
|
+
`)}function lr(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`,a=t.handlerName??t.routePath;return `
|
|
4771
4771
|
${JSON.stringify(a)}: {
|
|
4772
4772
|
definition: ${n}.definition,
|
|
4773
4773
|
schema: ${r},
|
|
4774
4774
|
},`}).join(`
|
|
4775
|
-
`)}function
|
|
4775
|
+
`)}function cr(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=`${n}SchedulerSchema`,a=t.taskName??`${t.routePath}`;return `
|
|
4776
4776
|
${JSON.stringify(a)}: {
|
|
4777
4777
|
definition: ${n}.definition,
|
|
4778
4778
|
schema: ${r},
|
|
4779
4779
|
},`}).join(`
|
|
4780
|
-
`)}function
|
|
4781
|
-
`)}function
|
|
4780
|
+
`)}function ur(e){return e.filter(({operation:t})=>t.kind==="scheduler").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`;return ` ${JSON.stringify(r)}: Parameters<typeof ${n}.definition.handler>[1];`}).join(`
|
|
4781
|
+
`)}function dr(e){return e.filter(({operation:t})=>t.kind==="cron").map(({operation:t,alias:n})=>{let r=t.taskName??`${t.routePath}`,a=t.cronTriggers??[];return `
|
|
4782
4782
|
{
|
|
4783
4783
|
taskName: ${JSON.stringify(r)},
|
|
4784
4784
|
cronTriggers: ${JSON.stringify(a)},
|
|
4785
4785
|
definition: ${n}.definition,
|
|
4786
4786
|
},`}).join(`
|
|
4787
|
-
`)}function
|
|
4787
|
+
`)}function pr(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
4788
4788
|
${t}.definition.handler,`).join(`
|
|
4789
|
-
`)}function
|
|
4789
|
+
`)}function _e(e){let t=nr(e);return {imports:rr(t),operationSchemas:ar(t),schedulerSchemas:or(t),queryRoutes:ir(t),mutationRoutes:sr(t),queryRegistryEntries:lr(t),schedulerEntries:cr(t),schedulerPayloadMapEntries:ur(t),cronEntries:dr(t),storageHandlersEntries:pr(t)}}var Ke=`
|
|
4790
4790
|
function getRealtimeStub(
|
|
4791
4791
|
env: Record<string, unknown>,
|
|
4792
4792
|
options: RegisterHandlersOptions,
|
|
@@ -4860,7 +4860,7 @@ function buildRealtimeWsUrl(requestUrl: string, websocketPath: string): string {
|
|
|
4860
4860
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
4861
4861
|
return url.toString();
|
|
4862
4862
|
}
|
|
4863
|
-
`;var
|
|
4863
|
+
`;var Ge=`
|
|
4864
4864
|
export class AppflareRealtimeDurableObject {
|
|
4865
4865
|
private readonly subscriptions = new Map<string, RealtimeSubscription>();
|
|
4866
4866
|
private readonly sockets = new Map<string, WebSocket>();
|
|
@@ -5003,7 +5003,7 @@ export class AppflareRealtimeDurableObject {
|
|
|
5003
5003
|
return new Response("Not found", { status: 404 });
|
|
5004
5004
|
}
|
|
5005
5005
|
}
|
|
5006
|
-
`;var
|
|
5006
|
+
`;var Je=`
|
|
5007
5007
|
async function publishMutationEvents(
|
|
5008
5008
|
c: { req: { raw: Request }; env: Record<string, unknown> },
|
|
5009
5009
|
options: RegisterHandlersOptions,
|
|
@@ -5104,7 +5104,7 @@ async function publishMutationEvents(
|
|
|
5104
5104
|
}
|
|
5105
5105
|
}
|
|
5106
5106
|
}
|
|
5107
|
-
`;var
|
|
5107
|
+
`;var Ze=`
|
|
5108
5108
|
function registerRealtimeRoutes(
|
|
5109
5109
|
app: Hono<WorkerEnv>,
|
|
5110
5110
|
options: RegisterHandlersOptions,
|
|
@@ -5267,7 +5267,7 @@ function registerRealtimeRoutes(
|
|
|
5267
5267
|
return stub.fetch(c.req.raw);
|
|
5268
5268
|
});
|
|
5269
5269
|
}
|
|
5270
|
-
`;var
|
|
5270
|
+
`;var Ye=`
|
|
5271
5271
|
type RealtimeSubscription = {
|
|
5272
5272
|
token: string;
|
|
5273
5273
|
signature: string;
|
|
@@ -5296,7 +5296,7 @@ type RealtimeDurableObjectNamespace = {
|
|
|
5296
5296
|
type RealtimeQueryName = keyof typeof realtimeQueryHandlers extends never
|
|
5297
5297
|
? string
|
|
5298
5298
|
: Extract<keyof typeof realtimeQueryHandlers, string>;
|
|
5299
|
-
`;var
|
|
5299
|
+
`;var Xe=`
|
|
5300
5300
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5301
5301
|
return typeof value === "object" && value !== null;
|
|
5302
5302
|
}
|
|
@@ -5811,9 +5811,9 @@ function doesSubscriptionMatchMutation(
|
|
|
5811
5811
|
|
|
5812
5812
|
return false;
|
|
5813
5813
|
}
|
|
5814
|
-
`;var
|
|
5814
|
+
`;var et=[Ye,Xe,Ke,Je,Ze,Ge].join(`
|
|
5815
5815
|
|
|
5816
|
-
`);var
|
|
5816
|
+
`);var tt=`
|
|
5817
5817
|
function parseExpiresIn(value: string | undefined): number | undefined {
|
|
5818
5818
|
if (!value) {
|
|
5819
5819
|
return undefined;
|
|
@@ -6011,7 +6011,7 @@ export function registerGeneratedStorageRoutes(
|
|
|
6011
6011
|
}
|
|
6012
6012
|
});
|
|
6013
6013
|
}
|
|
6014
|
-
`;var
|
|
6014
|
+
`;var nt=`
|
|
6015
6015
|
type SchedulerTaskName = keyof typeof schedulerHandlers extends never
|
|
6016
6016
|
? string
|
|
6017
6017
|
: keyof typeof schedulerHandlers;
|
|
@@ -6066,7 +6066,7 @@ export async function executeScheduledBatch(
|
|
|
6066
6066
|
}
|
|
6067
6067
|
}
|
|
6068
6068
|
}
|
|
6069
|
-
`;var
|
|
6069
|
+
`;var rt=`
|
|
6070
6070
|
export async function executeCronTriggers(
|
|
6071
6071
|
controller: { cron: string },
|
|
6072
6072
|
env: Record<string, unknown>,
|
|
@@ -6091,7 +6091,7 @@ export async function executeCronTriggers(
|
|
|
6091
6091
|
}
|
|
6092
6092
|
}
|
|
6093
6093
|
}
|
|
6094
|
-
`;function
|
|
6094
|
+
`;function at(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:s,schedulerEntries:i,schedulerPayloadMapEntries:l,cronEntries:c,storageHandlersEntries:u}=_e(e);return `import { sValidator } from "@hono/standard-validator";
|
|
6095
6095
|
import type { Hono } from "hono";
|
|
6096
6096
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6097
6097
|
import { ZodError, z } from "zod";
|
|
@@ -6114,11 +6114,11 @@ ${t}`:""}
|
|
|
6114
6114
|
${n}
|
|
6115
6115
|
${r}
|
|
6116
6116
|
|
|
6117
|
-
const realtimeQueryHandlers = {${
|
|
6117
|
+
const realtimeQueryHandlers = {${s||`
|
|
6118
6118
|
`}
|
|
6119
6119
|
} as const;
|
|
6120
6120
|
|
|
6121
|
-
const schedulerHandlers = {${
|
|
6121
|
+
const schedulerHandlers = {${i||`
|
|
6122
6122
|
`}
|
|
6123
6123
|
} as const;
|
|
6124
6124
|
|
|
@@ -6138,19 +6138,19 @@ type CronHandlerEntry = {
|
|
|
6138
6138
|
};
|
|
6139
6139
|
};
|
|
6140
6140
|
|
|
6141
|
-
const cronHandlers: readonly CronHandlerEntry[] = [${
|
|
6141
|
+
const cronHandlers: readonly CronHandlerEntry[] = [${c||`
|
|
6142
6142
|
`}
|
|
6143
6143
|
];
|
|
6144
6144
|
|
|
6145
|
-
const storageHandlers = [${
|
|
6145
|
+
const storageHandlers = [${u||`
|
|
6146
6146
|
`}
|
|
6147
6147
|
] as const;
|
|
6148
6148
|
|
|
6149
6149
|
setStorageHandlers([...storageHandlers]);
|
|
6150
6150
|
|
|
6151
|
-
${
|
|
6151
|
+
${nt}
|
|
6152
6152
|
|
|
6153
|
-
${
|
|
6153
|
+
${et}
|
|
6154
6154
|
|
|
6155
6155
|
export function registerGeneratedHandlers(
|
|
6156
6156
|
app: Hono<WorkerEnv>,
|
|
@@ -6163,20 +6163,20 @@ export function registerGeneratedHandlers(
|
|
|
6163
6163
|
`}
|
|
6164
6164
|
}
|
|
6165
6165
|
|
|
6166
|
-
${
|
|
6166
|
+
${tt}
|
|
6167
6167
|
|
|
6168
|
-
${
|
|
6169
|
-
`}function
|
|
6170
|
-
KV: c.env["${e}"] as KVNamespace`:""}function
|
|
6171
|
-
DATABASE: c.env["${e}"] as D1Database${
|
|
6172
|
-
}`}function
|
|
6168
|
+
${rt}
|
|
6169
|
+
`}function Q(e,t,n){let r=Qe(e),a=$e(n),o=qe(),s=at(t);return [{relativePath:"handlers.ts",source:r},{relativePath:"handlers.context.ts",source:a},{relativePath:"handlers.execution.ts",source:o},{relativePath:"handlers.routes.ts",source:s}]}function mr(e){return e?`,
|
|
6170
|
+
KV: c.env["${e}"] as KVNamespace`:""}function ot(e,t){return `{
|
|
6171
|
+
DATABASE: c.env["${e}"] as D1Database${mr(t)}
|
|
6172
|
+
}`}function it(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
6173
6173
|
const auth = createAuth(
|
|
6174
|
-
${
|
|
6174
|
+
${ot(t,n)},
|
|
6175
6175
|
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
6176
6176
|
);
|
|
6177
6177
|
return auth.handler(getSanitizedRequest(c.req.raw));
|
|
6178
6178
|
});
|
|
6179
|
-
`}function
|
|
6179
|
+
`}function gr(){return `export const getHeaders = (headers: Headers) => {
|
|
6180
6180
|
const newHeaders = Object.fromEntries(headers as any);
|
|
6181
6181
|
const headerObject: Record<string, any> = {};
|
|
6182
6182
|
let hasCookie = false;
|
|
@@ -6206,15 +6206,15 @@ ${Xe}
|
|
|
6206
6206
|
|
|
6207
6207
|
return headerObject as any as Headers;
|
|
6208
6208
|
};
|
|
6209
|
-
`}function
|
|
6209
|
+
`}function fr(){return `export const getSanitizedRequest = (req: Request) => {
|
|
6210
6210
|
const newRequest = new Request(req, {
|
|
6211
6211
|
headers: getHeaders(req.headers),
|
|
6212
6212
|
});
|
|
6213
6213
|
return newRequest;
|
|
6214
6214
|
};
|
|
6215
|
-
`}function
|
|
6216
|
-
`+
|
|
6217
|
-
`+
|
|
6215
|
+
`}function st(){return gr()+`
|
|
6216
|
+
`+fr()}function lt(e,t,n){return it(e,t,n)+`
|
|
6217
|
+
`+st()}function ct(){return `const app = new Hono<WorkerEnv>();
|
|
6218
6218
|
|
|
6219
6219
|
app.use('*', cors({
|
|
6220
6220
|
origin: (origin, c) => {
|
|
@@ -6230,7 +6230,7 @@ app.use('*', cors({
|
|
|
6230
6230
|
},
|
|
6231
6231
|
credentials: true
|
|
6232
6232
|
}));
|
|
6233
|
-
`}function
|
|
6233
|
+
`}function ut(){return `export { AppflareRealtimeDurableObject };
|
|
6234
6234
|
|
|
6235
6235
|
export default {
|
|
6236
6236
|
fetch: app.fetch,
|
|
@@ -6241,30 +6241,30 @@ export default {
|
|
|
6241
6241
|
await executeCronTriggers(controller, env, generatedHandlerOptions);
|
|
6242
6242
|
},
|
|
6243
6243
|
};
|
|
6244
|
-
`}function
|
|
6245
|
-
kvBinding: "${t}",`:"",
|
|
6244
|
+
`}function dt(e,t,n="APPFLARE_SCHEDULER_QUEUE",r,a="APPFLARE_REALTIME",o="global",s="/realtime/subscribe",i="/realtime/ws",l="appflare.realtime.v1"){let c=t?`
|
|
6245
|
+
kvBinding: "${t}",`:"",u=r?`
|
|
6246
6246
|
r2Binding: "${r}",`:"",f=`
|
|
6247
6247
|
realtimeBinding: "${a}",
|
|
6248
6248
|
realtimeObjectName: "${o}",
|
|
6249
|
-
realtimeSubscribePath: "${
|
|
6250
|
-
realtimeWebsocketPath: "${
|
|
6249
|
+
realtimeSubscribePath: "${s}",
|
|
6250
|
+
realtimeWebsocketPath: "${i}",
|
|
6251
6251
|
realtimeProtocol: "${l}",`;return `const generatedHandlerOptions = {
|
|
6252
|
-
databaseBinding: "${e}",${
|
|
6253
|
-
schedulerBinding: "${n}",${
|
|
6252
|
+
databaseBinding: "${e}",${c}
|
|
6253
|
+
schedulerBinding: "${n}",${u}${f}
|
|
6254
6254
|
};
|
|
6255
6255
|
registerGeneratedHandlers(app, generatedHandlerOptions);
|
|
6256
6256
|
registerGeneratedStorageRoutes(app, generatedHandlerOptions);
|
|
6257
6257
|
registerAdminDashboard(app, generatedHandlerOptions);
|
|
6258
|
-
`}function
|
|
6258
|
+
`}function pt(){return `import { createAuth } from "./auth.config";
|
|
6259
6259
|
import { AppflareRealtimeDurableObject, executeCronTriggers, executeScheduledBatch, registerGeneratedHandlers, registerGeneratedStorageRoutes } from "./handlers.routes";
|
|
6260
6260
|
import { registerAdminDashboard } from "./admin.routes";
|
|
6261
6261
|
import { Hono } from "hono";
|
|
6262
6262
|
import { cors } from "hono/cors";
|
|
6263
6263
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
6264
|
-
`}function
|
|
6264
|
+
`}function mt(){return `type WorkerEnv = {
|
|
6265
6265
|
Bindings: Record<string, unknown>;
|
|
6266
6266
|
};
|
|
6267
|
-
`}function
|
|
6267
|
+
`}function gt(e,t,n,r,a,o,s,i,l,c){return pt()+mt()+ct()+dt(t,n,r,a,o,s,i,l,c)+lt(e,t,n)+ut()}function ft(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function _(e,t){let n={...e};for(let[r,a]of Object.entries(t)){let o=n[r];if(ft(o)&&ft(a)){n[r]=_(o,a);continue}n[r]=a;}return n}function hr(e){return Array.from(new Set(e.filter(t=>t.length>0)))}function ht(e,t){let n=t.filter(d=>d.kind==="scheduler"||d.kind==="cron"),r=hr(t.filter(d=>d.kind==="cron").flatMap(d=>d.cronTriggers??[])),a=e.config.scheduler.enabled&&n.length>0,o=e.config.realtime.enabled,i=(typeof e.config.wranglerOverrides?.name=="string"?e.config.wranglerOverrides.name:void 0)??"appflare-worker",l=e.config.scheduler.queue??`${i}-scheduler`,c={name:i,main:"./src/index.ts",d1_databases:e.config.database.map(d=>({binding:d.binding,database_name:d.databaseName,database_id:d.databaseId,preview_database_id:d.previewDatabaseId??d.databaseId,...d.migrationsDir?{migrations_dir:d.migrationsDir}:{}})),kv_namespaces:e.config.kv.map(d=>({binding:d.binding,id:d.id,...d.previewId?{preview_id:d.previewId}:{}})),r2_buckets:e.config.r2.map(d=>({binding:d.binding,bucket_name:d.bucketName,...d.previewBucketName?{preview_bucket_name:d.previewBucketName}:{},...d.jurisdiction?{jurisdiction:d.jurisdiction}:{}})),...a?{queues:{producers:[{binding:e.config.scheduler.binding,queue:l}],consumers:[{queue:l}]}}:{},...r.length>0?{triggers:{crons:r}}:{},...o?{durable_objects:{bindings:[{name:e.config.realtime.binding,class_name:e.config.realtime.className}]},migrations:[{tag:"appflare-realtime-v1",new_sqlite_classes:[e.config.realtime.className]}]}:{}};if(!e.config.wranglerOverrides)return c;let{scheduler:u,...f}=e.config.wranglerOverrides;return _(c,f)}function yt(e){return e.tables.map(t=>({exportName:t.exportName,tableName:t.tableName,columns:t.columns.map(n=>n.name)}))}function bt(e){return `<li data-name="users">
|
|
6268
6268
|
<a href="/admin/users" hx-get="/admin/users" hx-target="#main-content" hx-push-url="true" hx-swap="outerHTML" class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full">
|
|
6269
6269
|
<iconify-icon icon="mdi:account-group" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
6270
6270
|
<span class="truncate">users</span>
|
|
@@ -6276,7 +6276,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6276
6276
|
<span class="truncate">${n.tableName}</span>
|
|
6277
6277
|
</a>
|
|
6278
6278
|
</li>`).join(`
|
|
6279
|
-
`)}`}function
|
|
6279
|
+
`)}`}function wt(e){let t=e.filter(o=>o.kind==="query"),n=e.filter(o=>o.kind==="mutation"),r=t.map(o=>`
|
|
6280
6280
|
<li data-name="${o.exportName}">
|
|
6281
6281
|
<a href="/admin/functions${o.routePath}" hx-get="/admin/functions${o.routePath}" hx-target="#main-content" hx-push-url="true" hx-swap="outerHTML" class="sidebar-link flex items-center gap-2 px-3 py-2 text-sm rounded-lg w-full">
|
|
6282
6282
|
<iconify-icon icon="solar:reorder-linear" width="16" height="16" class="opacity-50 shrink-0"></iconify-icon>
|
|
@@ -6310,7 +6310,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6310
6310
|
<ul class="flex flex-col gap-0.5">${a}</ul>`:""}
|
|
6311
6311
|
</nav>
|
|
6312
6312
|
</div>
|
|
6313
|
-
`}function
|
|
6313
|
+
`}function xt(e){return e.map(t=>`
|
|
6314
6314
|
<a
|
|
6315
6315
|
href="/admin/table/${t.exportName}"
|
|
6316
6316
|
class="card bg-base-100 border border-base-200 hover:border-primary/30 hover:shadow-md transition-all cursor-pointer group"
|
|
@@ -6327,9 +6327,9 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6327
6327
|
</div>
|
|
6328
6328
|
</div>
|
|
6329
6329
|
</a>
|
|
6330
|
-
`.replace(/\n/g,"\\n")).join("")}function
|
|
6330
|
+
`.replace(/\n/g,"\\n")).join("")}function Tt(e){return e.columns.filter(t=>t.type==="string").map(t=>`
|
|
6331
6331
|
try { searchConditions.push(like(tableSchema.${t.name}, \`%\${search}%\`)); } catch (e) {}
|
|
6332
|
-
`).join("")}function
|
|
6332
|
+
`).join("")}function yr(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 vt(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n),a=r?yr(r.type):"mdi:format-text";return `
|
|
6333
6333
|
<th>
|
|
6334
6334
|
<a href="#"
|
|
6335
6335
|
hx-get="/admin/table/${e.exportName}?page=\${page}&search=\${search}&sort=${n}&order=\${sort === '${n}' && order === 'asc' ? 'desc' : 'asc'}"
|
|
@@ -6341,7 +6341,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6341
6341
|
<span class="text-[10px] opacity-30">\${sort === '${n}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span>
|
|
6342
6342
|
</a>
|
|
6343
6343
|
</th>
|
|
6344
|
-
`}).join("")}function
|
|
6344
|
+
`}).join("")}function Rt(e,t){return e.map(n=>t&&n===t?`<td><button type="button" class="truncate max-w-[200px] text-sm font-mono text-xs opacity-70 hover:opacity-100 cursor-copy text-left" title="Click to copy: \${String((row as any).${n} ?? '')}" data-copy-value="\${String((row as any).${n} ?? '')}" onclick="navigator.clipboard?.writeText(this.dataset.copyValue || '')">\${String((row as any).${n} ?? '')}</button></td>`:`<td><div class="truncate max-w-[200px] text-sm" title="\${String((row as any).${n} ?? '')}">\${String((row as any).${n} ?? '')}</div></td>`).join("")}function K(e,t,n){let r=e.columns.find(s=>s.name===t);if(!r)return "";let a=r.optional?"":" required",o=r.type==="number"?"number":r.type==="date"?"date":"text";if(r.type==="boolean")return n==="edit"?`
|
|
6345
6345
|
<div class="form-control">
|
|
6346
6346
|
<label class="label cursor-pointer justify-start gap-3">
|
|
6347
6347
|
<input type="checkbox" name="${t}" value="true" class="checkbox checkbox-sm checkbox-primary" \${(row as any).${t} ? 'checked' : ''} />
|
|
@@ -6355,7 +6355,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6355
6355
|
<span class="label-text text-sm">${t}</span>
|
|
6356
6356
|
</label>
|
|
6357
6357
|
</div>
|
|
6358
|
-
`;if(n==="edit"){let
|
|
6358
|
+
`;if(n==="edit"){let s=r.type==="date"?`\${(() => {
|
|
6359
6359
|
const value = (row as any).${t};
|
|
6360
6360
|
if (value == null || value === '') return '';
|
|
6361
6361
|
|
|
@@ -6372,14 +6372,14 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6372
6372
|
})()}`:`\${String((row as any).${t} ?? '')}`;return `
|
|
6373
6373
|
<div class="form-control">
|
|
6374
6374
|
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6375
|
-
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm" value="${
|
|
6375
|
+
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm" value="${s}"${a} />
|
|
6376
6376
|
</div>
|
|
6377
6377
|
`}return `
|
|
6378
6378
|
<div class="form-control">
|
|
6379
6379
|
<label class="label"><span class="label-text text-sm font-medium">${t}</span></label>
|
|
6380
6380
|
<input type="${o}" name="${t}" class="input input-bordered w-full text-sm"${a} />
|
|
6381
6381
|
</div>
|
|
6382
|
-
`}function
|
|
6382
|
+
`}function G(e,t){return t.map(n=>{let r=e.columns.find(o=>o.name===n);if(!r)return "";let a=r.optional?"":`
|
|
6383
6383
|
if (raw_${n} === '') {
|
|
6384
6384
|
return c.text('${n} is required', 400);
|
|
6385
6385
|
}
|
|
@@ -6424,7 +6424,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6424
6424
|
payload.${n} = raw_${n};
|
|
6425
6425
|
}
|
|
6426
6426
|
`}).join(`
|
|
6427
|
-
`)}function
|
|
6427
|
+
`)}function kt(e){return e.columns.find(t=>t.primaryKey)?.name||e.columns[0]?.name||""}function St(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.autoIncrement||n.primaryKey)}function At(e,t){let n=e.columns.find(r=>r.name===t);return !(!n||n.primaryKey||n.autoIncrement)}function Nt(e,t,n,r){return t?`<td class="text-right">
|
|
6428
6428
|
<div class="drawer drawer-end">
|
|
6429
6429
|
<input id="edit-drawer-${e.exportName}-\${rowIndex}" type="checkbox" class="drawer-toggle" />
|
|
6430
6430
|
<div class="drawer-content">
|
|
@@ -6477,7 +6477,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6477
6477
|
</div>
|
|
6478
6478
|
</div>
|
|
6479
6479
|
</div>
|
|
6480
|
-
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function
|
|
6480
|
+
</td>`:'<td class="text-right"><span class="text-xs opacity-30">No primary key</span></td>'}function P(e){return `
|
|
6481
6481
|
<div class="flex flex-col sm:flex-row justify-between items-center mt-4 gap-3 py-3 px-1">
|
|
6482
6482
|
<div class="text-xs text-base-content/40">
|
|
6483
6483
|
Total found: <span class="font-medium text-base-content/60">\${total}</span>
|
|
@@ -6499,7 +6499,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6499
6499
|
\` : html\`<button class="join-item btn btn-sm btn-ghost btn-disabled"><iconify-icon icon="mdi:chevron-right" width="16" height="16"></iconify-icon></button>\`}
|
|
6500
6500
|
</div>
|
|
6501
6501
|
\` : ''}
|
|
6502
|
-
</div>`}function
|
|
6502
|
+
</div>`}function D(e,t="Search term or filter..."){return `
|
|
6503
6503
|
<div class="form-control w-full md:w-auto relative">
|
|
6504
6504
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
6505
6505
|
<input type="text"
|
|
@@ -6510,7 +6510,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6510
6510
|
hx-trigger="keyup changed delay:500ms, search"
|
|
6511
6511
|
hx-target="#main-content"
|
|
6512
6512
|
class="input input-sm md:input-md input-bordered pl-9 w-full md:w-72 bg-base-200/50 border-base-200 focus:bg-base-100 focus:border-primary transition-all text-sm" />
|
|
6513
|
-
</div>`}function
|
|
6513
|
+
</div>`}function $t(e,t,n,r,a,o,s,i,l,c){let u=P(`/admin/table/${e.exportName}`),f=D(`/admin/table/${e.exportName}`,"Search term or filter..."),d=r?`<th class="w-10"><input id="select-all-${e.exportName}" type="checkbox" class="checkbox checkbox-xs" /></th>`:'<th class="w-10"><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></th>',b=r?`<td><input type="checkbox" class="checkbox checkbox-xs row-select-checkbox" value="\${String((row as any).${n} ?? '')}" /></td>`:'<td><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></td>',x=r?`
|
|
6514
6514
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
6515
6515
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
6516
6516
|
<div class="text-xs text-base-content/70">
|
|
@@ -6669,7 +6669,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6669
6669
|
<thead>
|
|
6670
6670
|
<tr class="border-b border-base-200">
|
|
6671
6671
|
${d}
|
|
6672
|
-
${
|
|
6672
|
+
${s}
|
|
6673
6673
|
<th class="w-[100px] text-right">
|
|
6674
6674
|
<iconify-icon icon="mdi:dots-horizontal" width="16" height="16" class="opacity-30"></iconify-icon>
|
|
6675
6675
|
</th>
|
|
@@ -6679,7 +6679,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6679
6679
|
\${data.map((row, rowIndex) => html\`
|
|
6680
6680
|
<tr class="hover:bg-base-200/30 transition-colors">
|
|
6681
6681
|
${b}
|
|
6682
|
-
${
|
|
6682
|
+
${i}
|
|
6683
6683
|
${l}
|
|
6684
6684
|
</tr>
|
|
6685
6685
|
\`)}
|
|
@@ -6700,7 +6700,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6700
6700
|
</tbody>
|
|
6701
6701
|
</table>
|
|
6702
6702
|
</div>
|
|
6703
|
-
${
|
|
6703
|
+
${u}
|
|
6704
6704
|
</div>
|
|
6705
6705
|
\`;
|
|
6706
6706
|
|
|
@@ -6729,7 +6729,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6729
6729
|
${f}
|
|
6730
6730
|
</div>
|
|
6731
6731
|
\${tableHtml}
|
|
6732
|
-
${
|
|
6732
|
+
${x}
|
|
6733
6733
|
</div>
|
|
6734
6734
|
<div class="drawer-side z-50">
|
|
6735
6735
|
<label for="create-drawer-${e.exportName}" aria-label="close sidebar" class="drawer-overlay"></label>
|
|
@@ -6745,7 +6745,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6745
6745
|
<input type="hidden" name="order" value="\${order}" />
|
|
6746
6746
|
<input type="hidden" name="search" value="\${search}" />
|
|
6747
6747
|
<input type="hidden" name="page" value="\${page}" />
|
|
6748
|
-
${
|
|
6748
|
+
${c}
|
|
6749
6749
|
<button type="submit" class="btn btn-primary btn-sm mt-2">Create record</button>
|
|
6750
6750
|
</form>
|
|
6751
6751
|
</div>
|
|
@@ -6762,11 +6762,11 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6762
6762
|
title: "${e.tableName} - Admin Dashboard",
|
|
6763
6763
|
children: content
|
|
6764
6764
|
}));
|
|
6765
|
-
});`}function
|
|
6765
|
+
});`}function Ct(e,t,n,r,a,o,s,i){let l=r==="number"?`
|
|
6766
6766
|
const parsedId = Number(rawId);
|
|
6767
6767
|
if (Number.isNaN(parsedId)) return c.text('${n} must be a valid number', 400);
|
|
6768
6768
|
idValue = parsedId;
|
|
6769
|
-
`:"",
|
|
6769
|
+
`:"",u=a?`
|
|
6770
6770
|
adminApp.post('/table/${e}/edit', async (c) => {
|
|
6771
6771
|
const db = drizzle(c.env[options.databaseBinding], { schema });
|
|
6772
6772
|
const tableSchema = (schema as any).${e};
|
|
@@ -6779,7 +6779,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6779
6779
|
|
|
6780
6780
|
const payload: Record<string, unknown> = {};
|
|
6781
6781
|
|
|
6782
|
-
${
|
|
6782
|
+
${i}
|
|
6783
6783
|
|
|
6784
6784
|
let idValue: unknown = rawId;
|
|
6785
6785
|
${l}
|
|
@@ -6882,7 +6882,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6882
6882
|
const getValue = (value: unknown) => (typeof value === 'string' ? value : '');
|
|
6883
6883
|
const payload: Record<string, unknown> = {};
|
|
6884
6884
|
|
|
6885
|
-
${
|
|
6885
|
+
${s}
|
|
6886
6886
|
|
|
6887
6887
|
await db.insert(tableSchema).values(payload as any).execute();
|
|
6888
6888
|
|
|
@@ -6894,16 +6894,16 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6894
6894
|
});
|
|
6895
6895
|
return c.redirect('/admin/table/${e}?' + query.toString());
|
|
6896
6896
|
});
|
|
6897
|
-
${
|
|
6898
|
-
`}function
|
|
6899
|
-
`+
|
|
6897
|
+
${u}
|
|
6898
|
+
`}function J(e){let t=kt(e),n=!!t,r=e.columns.map(m=>m.name),a=r.filter(m=>St(e,m)),o=r.filter(m=>At(e,m)),s=Tt(e),i=vt(e,r),l=Rt(r,t),c=a.map(m=>K(e,m,"create")).join(""),u=o.map(m=>K(e,m,"edit")).join(""),f=G(e,a),d=G(e,o),b=n?t:r[0]||"id",x=e.columns.find(m=>m.name===t)?.type,y=Nt(e,n,t,u);return $t(e,b,t,n,r,s,i,l,y,c)+`
|
|
6899
|
+
`+Ct(e.exportName,b,t,x,n,s,f,d)}function qt(){return `
|
|
6900
6900
|
const buildUsersRedirect = (params: { page?: string; sort?: string; order?: string; search?: string }) => {
|
|
6901
6901
|
const page = params.page && params.page.trim() ? params.page : '1';
|
|
6902
6902
|
const sort = params.sort && params.sort.trim() ? params.sort : 'createdAt';
|
|
6903
6903
|
const order = params.order === 'asc' ? 'asc' : 'desc';
|
|
6904
6904
|
const search = params.search ? params.search : '';
|
|
6905
6905
|
return '/admin/users?page=' + encodeURIComponent(page) + '&sort=' + encodeURIComponent(sort) + '&order=' + encodeURIComponent(order) + '&search=' + encodeURIComponent(search);
|
|
6906
|
-
};`}function
|
|
6906
|
+
};`}function Mt(){return `
|
|
6907
6907
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6908
6908
|
<input type="checkbox" id="ban-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6909
6909
|
<div class="modal">
|
|
@@ -6924,7 +6924,7 @@ ${c}
|
|
|
6924
6924
|
</div>
|
|
6925
6925
|
<label class="modal-backdrop" for="ban-user-modal-\${String((row as any).id)}">Close</label>
|
|
6926
6926
|
</div>
|
|
6927
|
-
\`}`}function
|
|
6927
|
+
\`}`}function It(){return `
|
|
6928
6928
|
\${(row as any).id === currentUserId ? '' : html\`
|
|
6929
6929
|
<input type="checkbox" id="delete-user-modal-\${String((row as any).id)}" class="modal-toggle" />
|
|
6930
6930
|
<div class="modal">
|
|
@@ -6945,8 +6945,8 @@ ${c}
|
|
|
6945
6945
|
</div>
|
|
6946
6946
|
<label class="modal-backdrop" for="delete-user-modal-\${String((row as any).id)}">Close</label>
|
|
6947
6947
|
</div>
|
|
6948
|
-
\`}`}var
|
|
6949
|
-
`),t=
|
|
6948
|
+
\`}`}var br=["id","name","email","role","createdAt","banned"],wr={id:"mdi:pound",name:"mdi:format-text",email:"mdi:at",role:"mdi:shield-account-outline",createdAt:"mdi:calendar",banned:"mdi:toggle-switch-outline"};function xr(e){let t=wr[e]||"mdi:format-text";return `<th><a href="#" hx-get="/admin/users?page=\${page}&search=\${search}&sort=${e}&order=\${sort === '${e}' && order === 'asc' ? 'desc' : 'asc'}" hx-target="#main-content" hx-push-url="true" class="hover:text-primary flex items-center gap-1.5 transition-colors whitespace-nowrap"><iconify-icon icon="${t}" width="14" height="14" class="opacity-40"></iconify-icon>${e} <span class="text-[10px] opacity-30">\${sort === '${e}' ? (order === 'asc' ? '\u25B2' : '\u25BC') : ''}</span></a></th>`}function Ft(){let e=br.map(xr).join(`
|
|
6949
|
+
`),t=P("/admin/users");return `
|
|
6950
6950
|
const tableHtml = html\`
|
|
6951
6951
|
<div class="bg-base-100 rounded-xl border border-base-200 overflow-hidden">
|
|
6952
6952
|
<div class="overflow-x-auto">
|
|
@@ -7014,8 +7014,8 @@ ${c}
|
|
|
7014
7014
|
</div>
|
|
7015
7015
|
</div>
|
|
7016
7016
|
</div>
|
|
7017
|
-
${
|
|
7018
|
-
${
|
|
7017
|
+
${Mt()}
|
|
7018
|
+
${It()}
|
|
7019
7019
|
</td>
|
|
7020
7020
|
</tr>
|
|
7021
7021
|
\`)}
|
|
@@ -7031,7 +7031,7 @@ ${$t()}
|
|
|
7031
7031
|
${t}
|
|
7032
7032
|
</div>
|
|
7033
7033
|
\`;
|
|
7034
|
-
`}function
|
|
7034
|
+
`}function Pt(){return `
|
|
7035
7035
|
const content = html\`
|
|
7036
7036
|
<div id="main-content">
|
|
7037
7037
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-5 gap-3">
|
|
@@ -7043,11 +7043,11 @@ ${$t()}
|
|
|
7043
7043
|
<iconify-icon icon="mdi:refresh" width="14" height="14"></iconify-icon>
|
|
7044
7044
|
</button>
|
|
7045
7045
|
</div>
|
|
7046
|
-
${
|
|
7046
|
+
${D("/admin/users","Search users...")}
|
|
7047
7047
|
</div>
|
|
7048
7048
|
\${tableHtml}
|
|
7049
7049
|
</div>
|
|
7050
|
-
\`;`}function
|
|
7050
|
+
\`;`}function Dt(){let e=Ft(),t=Pt();return `
|
|
7051
7051
|
adminApp.get('/users', async (c) => {
|
|
7052
7052
|
const db = drizzle(c.env[options.databaseBinding]);
|
|
7053
7053
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7103,7 +7103,7 @@ ${$t()}
|
|
|
7103
7103
|
title: "users - Admin Dashboard",
|
|
7104
7104
|
children: content,
|
|
7105
7105
|
}));
|
|
7106
|
-
});`}function
|
|
7106
|
+
});`}function Et(){return `
|
|
7107
7107
|
adminApp.post('/users/edit', async (c) => {
|
|
7108
7108
|
const session = await requireAdminSession(c);
|
|
7109
7109
|
if (!session) {
|
|
@@ -7246,8 +7246,8 @@ ${$t()}
|
|
|
7246
7246
|
const resolvedPage = String(Math.min(nextPageCandidate, totalPages));
|
|
7247
7247
|
|
|
7248
7248
|
return c.redirect(buildUsersRedirect({ page: resolvedPage, search, sort, order }));
|
|
7249
|
-
});`}function
|
|
7250
|
-
${
|
|
7249
|
+
});`}function Z(){return `
|
|
7250
|
+
${qt()}
|
|
7251
7251
|
|
|
7252
7252
|
const requireAdminSession = async (c: any) => {
|
|
7253
7253
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -7258,12 +7258,12 @@ ${$t()}
|
|
|
7258
7258
|
return session;
|
|
7259
7259
|
};
|
|
7260
7260
|
|
|
7261
|
-
${
|
|
7261
|
+
${Dt()}
|
|
7262
7262
|
|
|
7263
|
-
${
|
|
7264
|
-
`}function
|
|
7263
|
+
${Et()}
|
|
7264
|
+
`}function Ot(e){return `${e.tables.map(t=>J(t)).join(`
|
|
7265
7265
|
`)}
|
|
7266
|
-
${
|
|
7266
|
+
${Z()}`}function jt(e){return `
|
|
7267
7267
|
<div class="flex items-center justify-between">
|
|
7268
7268
|
<div class="flex items-center gap-3">
|
|
7269
7269
|
<div class="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
|
|
@@ -7278,9 +7278,9 @@ ${G()}`}function Pt(e){return `
|
|
|
7278
7278
|
<span class="badge badge-sm badge-ghost font-mono opacity-50 px-2 py-3">/api${e.routePath}</span>
|
|
7279
7279
|
</div>
|
|
7280
7280
|
</div>
|
|
7281
|
-
`}function
|
|
7281
|
+
`}function Tr(e){return e==="boolean"?"checkbox":e==="number"?"number":"text"}function vr(e){let t=e.args??[];return t.length===0?`
|
|
7282
7282
|
<div class="text-[11px] opacity-30 italic py-2">No arguments defined for this ${e.kind}.</div>
|
|
7283
|
-
`:t.map(n=>{let r=
|
|
7283
|
+
`:t.map(n=>{let r=Tr(n.type),a=r==="checkbox",o=`${n.name}${n.optional?"":" *"}`,s=n.type!=="unknown"?`<span class="badge badge-xs badge-ghost font-mono opacity-40 ml-1">${n.type}</span>`:"";return a?`
|
|
7284
7284
|
<div class="flex items-center gap-3 py-1">
|
|
7285
7285
|
<input
|
|
7286
7286
|
type="checkbox"
|
|
@@ -7289,13 +7289,13 @@ ${G()}`}function Pt(e){return `
|
|
|
7289
7289
|
class="checkbox checkbox-sm checkbox-primary"
|
|
7290
7290
|
${n.defaultValue==="true"?"checked":""}
|
|
7291
7291
|
/>
|
|
7292
|
-
<span class="text-sm font-mono opacity-70">${n.name}${
|
|
7292
|
+
<span class="text-sm font-mono opacity-70">${n.name}${s}</span>
|
|
7293
7293
|
${n.optional?'<span class="text-[10px] opacity-30 italic ml-auto">optional</span>':""}
|
|
7294
7294
|
</div>
|
|
7295
7295
|
`:`
|
|
7296
7296
|
<div class="form-control">
|
|
7297
7297
|
<label class="label py-0.5">
|
|
7298
|
-
<span class="label-text text-[11px] font-mono font-semibold">${o}${
|
|
7298
|
+
<span class="label-text text-[11px] font-mono font-semibold">${o}${s}</span>
|
|
7299
7299
|
${n.optional?'<span class="label-text-alt text-[10px] opacity-30 italic">optional</span>':""}
|
|
7300
7300
|
</label>
|
|
7301
7301
|
<input
|
|
@@ -7309,7 +7309,7 @@ ${G()}`}function Pt(e){return `
|
|
|
7309
7309
|
/>
|
|
7310
7310
|
</div>
|
|
7311
7311
|
`}).join(`
|
|
7312
|
-
`)}function
|
|
7312
|
+
`)}function Rr(e){return `
|
|
7313
7313
|
<div class="space-y-4">
|
|
7314
7314
|
<div class="flex items-center justify-between">
|
|
7315
7315
|
<div class="flex flex-col">
|
|
@@ -7322,11 +7322,11 @@ ${G()}`}function Pt(e){return `
|
|
|
7322
7322
|
</label>
|
|
7323
7323
|
</div>
|
|
7324
7324
|
<div id="args-rows" class="flex flex-col gap-3">
|
|
7325
|
-
${
|
|
7325
|
+
${vr(e)}
|
|
7326
7326
|
</div>
|
|
7327
7327
|
<p class="text-[11px] opacity-30 mt-2 italic">Values are sent as ${e.kind==="query"?"query string params":"JSON request body"}.</p>
|
|
7328
7328
|
</div>
|
|
7329
|
-
`}function
|
|
7329
|
+
`}function kr(){return `
|
|
7330
7330
|
<div class="space-y-4">
|
|
7331
7331
|
<label class="text-[11px] font-bold uppercase tracking-wider opacity-40 block">Bearer Token <span class="font-normal normal-case">(optional)</span></label>
|
|
7332
7332
|
<div class="relative group">
|
|
@@ -7343,7 +7343,7 @@ ${G()}`}function Pt(e){return `
|
|
|
7343
7343
|
</div>
|
|
7344
7344
|
<p class="text-[10px] opacity-30 italic">Token will be included in the Authorization header.</p>
|
|
7345
7345
|
</div>
|
|
7346
|
-
`}function
|
|
7346
|
+
`}function Sr(){return `
|
|
7347
7347
|
<div class="space-y-4">
|
|
7348
7348
|
<div class="flex items-center justify-between">
|
|
7349
7349
|
<span class="text-[11px] font-bold uppercase tracking-wider opacity-40">Custom Headers</span>
|
|
@@ -7357,7 +7357,7 @@ ${G()}`}function Pt(e){return `
|
|
|
7357
7357
|
</div>
|
|
7358
7358
|
<p id="headers-error" class="text-[11px] text-error mt-1.5 hidden"></p>
|
|
7359
7359
|
</div>
|
|
7360
|
-
`}function
|
|
7360
|
+
`}function Bt(e){return `
|
|
7361
7361
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col h-full">
|
|
7362
7362
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between flex-none">
|
|
7363
7363
|
<h3 class="text-xs font-bold uppercase tracking-widest opacity-40">Request</h3>
|
|
@@ -7378,13 +7378,13 @@ ${G()}`}function Pt(e){return `
|
|
|
7378
7378
|
<!-- Tab Content -->
|
|
7379
7379
|
<div class="flex-1 overflow-y-auto">
|
|
7380
7380
|
<div id="request-tab-args" class="p-5">
|
|
7381
|
-
${
|
|
7381
|
+
${Rr(e)}
|
|
7382
7382
|
</div>
|
|
7383
7383
|
<div id="request-tab-auth" class="p-5 hidden">
|
|
7384
|
-
${
|
|
7384
|
+
${kr()}
|
|
7385
7385
|
</div>
|
|
7386
7386
|
<div id="request-tab-headers" class="p-5 hidden">
|
|
7387
|
-
${
|
|
7387
|
+
${Sr()}
|
|
7388
7388
|
</div>
|
|
7389
7389
|
</div>
|
|
7390
7390
|
|
|
@@ -7402,7 +7402,7 @@ ${G()}`}function Pt(e){return `
|
|
|
7402
7402
|
</form>
|
|
7403
7403
|
</div>
|
|
7404
7404
|
</div>
|
|
7405
|
-
`}function
|
|
7405
|
+
`}function Vt(){return `
|
|
7406
7406
|
<div class="card bg-base-100 border border-base-200 shadow-sm overflow-hidden flex flex-col">
|
|
7407
7407
|
<!-- Panel Header -->
|
|
7408
7408
|
<div class="px-5 py-3 border-b border-base-200 bg-base-200/20 flex items-center justify-between">
|
|
@@ -7484,7 +7484,7 @@ ${G()}`}function Pt(e){return `
|
|
|
7484
7484
|
|
|
7485
7485
|
</div>
|
|
7486
7486
|
</div>
|
|
7487
|
-
`}function
|
|
7487
|
+
`}function Wt(e){let t=e.kind==="query",n=e.routePath,r=e.handlerName??e.routePath;return `
|
|
7488
7488
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
|
|
7489
7489
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
|
7490
7490
|
|
|
@@ -8026,21 +8026,21 @@ ${G()}`}function Pt(e){return `
|
|
|
8026
8026
|
_rtEnabled = false;
|
|
8027
8027
|
});
|
|
8028
8028
|
</script>
|
|
8029
|
-
`}function
|
|
8029
|
+
`}function Ht(e){return `
|
|
8030
8030
|
const content = html\`
|
|
8031
8031
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
8032
|
-
${
|
|
8032
|
+
${jt(e)}
|
|
8033
8033
|
|
|
8034
8034
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
8035
8035
|
<!-- Request Panel -->
|
|
8036
|
-
${
|
|
8036
|
+
${Bt(e)}
|
|
8037
8037
|
|
|
8038
8038
|
<!-- Result Panel -->
|
|
8039
|
-
${
|
|
8039
|
+
${Vt()}
|
|
8040
8040
|
</div>
|
|
8041
8041
|
</div>
|
|
8042
8042
|
|
|
8043
|
-
${
|
|
8043
|
+
${Wt(e)}
|
|
8044
8044
|
\`;
|
|
8045
8045
|
|
|
8046
8046
|
if (c.req.header('hx-request')) {
|
|
@@ -8050,11 +8050,11 @@ ${G()}`}function Pt(e){return `
|
|
|
8050
8050
|
return c.html(Layout({
|
|
8051
8051
|
title: "${e.exportName} - Functions",
|
|
8052
8052
|
children: content
|
|
8053
|
-
}));`}function
|
|
8053
|
+
}));`}function zt(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
8054
8054
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
8055
|
-
${
|
|
8055
|
+
${Ht(n)}
|
|
8056
8056
|
});`).join(`
|
|
8057
|
-
`)}function
|
|
8057
|
+
`)}function Lt(){return `
|
|
8058
8058
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
8059
8059
|
const r2Binding = (options as any).r2Binding;
|
|
8060
8060
|
if (!r2Binding || !c.env[r2Binding]) return null;
|
|
@@ -8123,7 +8123,7 @@ ${G()}`}function Pt(e){return `
|
|
|
8123
8123
|
const parts = prefix.split('/').filter(Boolean);
|
|
8124
8124
|
return parts.slice(0, -1).join('/') + (parts.length > 1 ? '/' : '');
|
|
8125
8125
|
};
|
|
8126
|
-
`}function
|
|
8126
|
+
`}function Ut(){return `
|
|
8127
8127
|
const buildStorageListingContent = (listed: any, prefix: string) => {
|
|
8128
8128
|
const parts = prefix.split('/').filter(Boolean);
|
|
8129
8129
|
const breadcrumbs: any[] = [];
|
|
@@ -8250,7 +8250,7 @@ ${G()}`}function Pt(e){return `
|
|
|
8250
8250
|
</div>
|
|
8251
8251
|
\`;
|
|
8252
8252
|
};
|
|
8253
|
-
`}function
|
|
8253
|
+
`}function Qt(){return `
|
|
8254
8254
|
const handleStorageListRoute = async (c: any) => {
|
|
8255
8255
|
const bucket = getStorageBucket(c);
|
|
8256
8256
|
if (!bucket) {
|
|
@@ -8272,7 +8272,7 @@ ${G()}`}function Pt(e){return `
|
|
|
8272
8272
|
|
|
8273
8273
|
adminApp.get('/storage', handleStorageListRoute);
|
|
8274
8274
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
8275
|
-
`}function
|
|
8275
|
+
`}function _t(){return `
|
|
8276
8276
|
adminApp.post('/storage/upload', async (c) => {
|
|
8277
8277
|
const bucket = getStorageBucket(c);
|
|
8278
8278
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8290,7 +8290,7 @@ ${G()}`}function Pt(e){return `
|
|
|
8290
8290
|
|
|
8291
8291
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8292
8292
|
});
|
|
8293
|
-
`}function
|
|
8293
|
+
`}function Kt(){return `
|
|
8294
8294
|
adminApp.delete('/storage/delete', async (c) => {
|
|
8295
8295
|
const bucket = getStorageBucket(c);
|
|
8296
8296
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8305,7 +8305,7 @@ ${G()}`}function Pt(e){return `
|
|
|
8305
8305
|
c.header('HX-Redirect', prefixToStoragePath(prefix));
|
|
8306
8306
|
return c.html('');
|
|
8307
8307
|
});
|
|
8308
|
-
`}function
|
|
8308
|
+
`}function Gt(){return `
|
|
8309
8309
|
adminApp.post('/storage/directory', async (c) => {
|
|
8310
8310
|
const bucket = getStorageBucket(c);
|
|
8311
8311
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8331,7 +8331,7 @@ ${G()}`}function Pt(e){return `
|
|
|
8331
8331
|
|
|
8332
8332
|
return c.redirect(prefixToStoragePath(prefix));
|
|
8333
8333
|
});
|
|
8334
|
-
`}function
|
|
8334
|
+
`}function Jt(){return `
|
|
8335
8335
|
adminApp.get('/storage/download', async (c) => {
|
|
8336
8336
|
const bucket = getStorageBucket(c);
|
|
8337
8337
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8351,7 +8351,7 @@ ${G()}`}function Pt(e){return `
|
|
|
8351
8351
|
|
|
8352
8352
|
return new Response(object.body, { headers });
|
|
8353
8353
|
});
|
|
8354
|
-
`}function
|
|
8354
|
+
`}function Zt(){return `
|
|
8355
8355
|
adminApp.get('/storage/preview', async (c) => {
|
|
8356
8356
|
const bucket = getStorageBucket(c);
|
|
8357
8357
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8369,25 +8369,25 @@ ${G()}`}function Pt(e){return `
|
|
|
8369
8369
|
|
|
8370
8370
|
return new Response(object.body, { headers });
|
|
8371
8371
|
});
|
|
8372
|
-
`}function
|
|
8373
|
-
${
|
|
8372
|
+
`}function Yt(){return `
|
|
8373
|
+
${Jt()}
|
|
8374
|
+
|
|
8375
|
+
${Zt()}
|
|
8374
8376
|
|
|
8375
8377
|
${_t()}
|
|
8376
8378
|
|
|
8377
|
-
${
|
|
8379
|
+
${Kt()}
|
|
8380
|
+
|
|
8381
|
+
${Gt()}
|
|
8378
8382
|
|
|
8383
|
+
${Qt()}
|
|
8384
|
+
`}function Xt(){return `
|
|
8379
8385
|
${Lt()}
|
|
8380
8386
|
|
|
8381
8387
|
${Ut()}
|
|
8382
8388
|
|
|
8383
|
-
${
|
|
8384
|
-
`}function
|
|
8385
|
-
${Vt()}
|
|
8386
|
-
|
|
8387
|
-
${Wt()}
|
|
8388
|
-
|
|
8389
|
-
${Kt()}
|
|
8390
|
-
`}function Jt(e,t){let n=ft(t);return `
|
|
8389
|
+
${Yt()}
|
|
8390
|
+
`}function en(e,t){let n=wt(t);return `
|
|
8391
8391
|
function Layout(props: { children: any; title: string; hideSidebar?: boolean }) {
|
|
8392
8392
|
return html\`<!DOCTYPE html>
|
|
8393
8393
|
<html lang="en" data-theme="light">
|
|
@@ -8762,7 +8762,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8762
8762
|
</body>
|
|
8763
8763
|
</html>\`;
|
|
8764
8764
|
}
|
|
8765
|
-
`}function
|
|
8765
|
+
`}function tn(){return `
|
|
8766
8766
|
// Auth Middleware
|
|
8767
8767
|
adminApp.use('*', async (c, next) => {
|
|
8768
8768
|
const auth = createAuth({ DATABASE: c.env[options.databaseBinding] } as any, c.req.raw.cf as any);
|
|
@@ -8821,7 +8821,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8821
8821
|
}
|
|
8822
8822
|
await next();
|
|
8823
8823
|
});
|
|
8824
|
-
`}function
|
|
8824
|
+
`}function nn(e){return `
|
|
8825
8825
|
adminApp.get('/', (c) => {
|
|
8826
8826
|
return c.html(Layout({
|
|
8827
8827
|
title: "Admin Dashboard",
|
|
@@ -8838,7 +8838,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8838
8838
|
\`
|
|
8839
8839
|
}));
|
|
8840
8840
|
});
|
|
8841
|
-
`}function
|
|
8841
|
+
`}function rn(e,t,n){let r=yt(t),a=bt(r),o=xt(r),s=Ot(t),i=zt(n),l=Xt(),c=en(a,n),u=tn(),f=nn(o);return `import { Hono } from "hono";
|
|
8842
8842
|
import { html, raw } from "hono/html";
|
|
8843
8843
|
import { drizzle } from "drizzle-orm/d1";
|
|
8844
8844
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -8846,20 +8846,20 @@ import { createAuth } from "./auth.config";
|
|
|
8846
8846
|
import * as schema from "${e}";
|
|
8847
8847
|
import { users } from "./auth.schema";
|
|
8848
8848
|
|
|
8849
|
-
${
|
|
8849
|
+
${c}
|
|
8850
8850
|
|
|
8851
8851
|
export function registerAdminDashboard(app: Hono<any>, options: { databaseBinding: string, r2Binding?: string }) {
|
|
8852
8852
|
const adminApp = new Hono<any>();
|
|
8853
8853
|
|
|
8854
|
-
${
|
|
8854
|
+
${u}
|
|
8855
8855
|
|
|
8856
8856
|
${f}
|
|
8857
8857
|
|
|
8858
8858
|
// Generate table routes
|
|
8859
|
-
${
|
|
8859
|
+
${s}
|
|
8860
8860
|
|
|
8861
8861
|
// Generate function routes
|
|
8862
|
-
${
|
|
8862
|
+
${i}
|
|
8863
8863
|
|
|
8864
8864
|
// Generate storage routes
|
|
8865
8865
|
${l}
|
|
@@ -8867,12 +8867,12 @@ ${f}
|
|
|
8867
8867
|
app.route('/admin', adminApp);
|
|
8868
8868
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
8869
8869
|
}
|
|
8870
|
-
`}function
|
|
8871
|
-
`}function
|
|
8872
|
-
targetTable: ${h(
|
|
8873
|
-
junctionTable: ${h(
|
|
8874
|
-
sourceField: ${h(
|
|
8875
|
-
targetField: ${h(
|
|
8870
|
+
`}function Y(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"}function E(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function j(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(t,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(t,n)=>n.toUpperCase())}function te(e){return e.endsWith("ies")?`${e.slice(0,-3)}y`:e.endsWith("ses")?e.slice(0,-2):e.endsWith("s")&&e.length>1?e.slice(0,-1):e}function h(e){return JSON.stringify(e)}function Nr(e){if(typeof e=="string")return h(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(e===null)return "null";if(e instanceof Date)return h(e.toISOString());throw new Error(`Unsupported SQL default value '${String(e)}'. Use string, number, boolean, null, or Date.`)}function $r(e){return {kind:"schema",tables:Object.fromEntries(Object.entries(e.tables).map(([t,n])=>[t,{kind:"table",sqlName:n.sqlName,columns:Object.fromEntries(Object.entries(n.columns).map(([r,a])=>[r,{...a}])),relations:Object.fromEntries(Object.entries(n.relations).map(([r,a])=>[r,{...a}]))}]))}}function O(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function an(e,t,n,r,a,o,s){let i=t.columns[n];if(i){if(i.references&&(i.references.table!==r||i.references.column!==a))throw new Error(`Inferred relation '${e}.${n}' conflicts with explicit references(${i.references.table}.${i.references.column}).`);t.columns[n]={...i,notNull:i.notNull??(i.nullable===true?false:o.notNull),nullable:i.nullable??(o.notNull===false?true:void 0),references:{table:r,column:a,onDelete:i.references?.onDelete??o.onDelete,onUpdate:i.references?.onUpdate??o.onUpdate}};return}t.columns[n]={kind:"column",type:o.fkType??s,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 on(e,t,n){if(t.notNull===true&&t.nullable===true)throw new Error(`Invalid nullable configuration on '${e}': cannot set both notNull and nullable to true.`);return t.notNull===true?true:t.nullable===true||t.notNull===false?false:n}function sn(e,t){return `${e}:${t}`}function Cr(e,t,n,r){let a=sn(e,t),o=sn(n,r);return a<=o?{key:`${a}|${o}`,leftTable:e,leftReferenceField:t,rightTable:n,rightReferenceField:r,sourceIsLeft:true}:{key:`${o}|${a}`,leftTable:n,leftReferenceField:r,rightTable:e,rightReferenceField:t,sourceIsLeft:false}}function qr(e,t){return `${e}${j(t)}Links`}function ln(e,t,n){let r=te(e),a=te(t);return r===a?`${n}${j(r)}Id`:`${r}Id`}function Mr(e,t,n){if(e.junctionTable!==t.junctionTable)throw new Error(`manyToMany pair '${n}' has conflicting junctionTable values ('${e.junctionTable}' vs '${t.junctionTable}').`);if(e.leftField!==t.leftField)throw new Error(`manyToMany pair '${n}' has conflicting left field values ('${e.leftField}' vs '${t.leftField}').`);if(e.rightField!==t.rightField)throw new Error(`manyToMany pair '${n}' has conflicting right field values ('${e.rightField}' vs '${t.rightField}').`);if(e.leftSqlName!==t.leftSqlName)throw new Error(`manyToMany pair '${n}' has conflicting left sql name values ('${e.leftSqlName}' vs '${t.leftSqlName}').`);if(e.rightSqlName!==t.rightSqlName)throw new Error(`manyToMany pair '${n}' has conflicting right sql name values ('${e.rightSqlName}' vs '${t.rightSqlName}').`);if(e.onDelete!==t.onDelete)throw new Error(`manyToMany pair '${n}' has conflicting onDelete values ('${e.onDelete}' vs '${t.onDelete}').`);if(e.onUpdate!==t.onUpdate)throw new Error(`manyToMany pair '${n}' has conflicting onUpdate values ('${e.onUpdate}' vs '${t.onUpdate}').`);return e}function Ir(e){let t=new Map;for(let[n,r]of Object.entries(e.tables))for(let a of Object.values(r.relations)){if(a.relation!=="manyToMany")continue;let o=a.referenceField??"id",s=a.targetReferenceField??"id",i=Cr(n,o,a.targetTable,s),l=ln(i.leftTable,i.rightTable,"source"),c=ln(i.rightTable,i.leftTable,"target"),u={leftTable:i.leftTable,leftReferenceField:i.leftReferenceField,rightTable:i.rightTable,rightReferenceField:i.rightReferenceField,junctionTable:a.junctionTable??qr(i.leftTable,i.rightTable),leftField:i.sourceIsLeft?a.sourceField??l:a.targetField??l,rightField:i.sourceIsLeft?a.targetField??c:a.sourceField??c,leftSqlName:i.sourceIsLeft?a.sourceSqlName:a.targetSqlName,rightSqlName:i.sourceIsLeft?a.targetSqlName:a.sourceSqlName,onDelete:a.onDelete,onUpdate:a.onUpdate};if(u.leftField===u.rightField)throw new Error(`manyToMany pair '${i.key}' resolves to duplicate junction fields '${u.leftField}'. Set sourceField/targetField explicitly.`);let f=t.get(i.key);f?Mr(f,u,i.key):t.set(i.key,u),a.referenceField=o,a.targetReferenceField=s,a.junctionTable=u.junctionTable,a.sourceField=i.sourceIsLeft?u.leftField:u.rightField,a.targetField=i.sourceIsLeft?u.rightField:u.leftField,a.sourceSqlName=i.sourceIsLeft?u.leftSqlName:u.rightSqlName,a.targetSqlName=i.sourceIsLeft?u.rightSqlName:u.leftSqlName;}for(let n of t.values()){if(n.junctionTable in e.tables)throw new Error(`manyToMany auto junction table '${n.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`);let r=O(e,n.leftTable,n.leftReferenceField)??"string",a=O(e,n.rightTable,n.rightReferenceField)??"string";e.tables[n.junctionTable]={kind:"table",columns:{[n.leftField]:{kind:"column",type:r,sqlName:n.leftSqlName,notNull:true,nullable:false,references:{table:n.leftTable,column:n.leftReferenceField,onDelete:n.onDelete,onUpdate:n.onUpdate},index:true},[n.rightField]:{kind:"column",type:a,sqlName:n.rightSqlName,notNull:true,nullable:false,references:{table:n.rightTable,column:n.rightReferenceField,onDelete:n.onDelete,onUpdate:n.onUpdate},index:true}},relations:{[n.leftTable]:{kind:"relation",relation:"one",targetTable:n.leftTable,field:n.leftField,referenceField:n.leftReferenceField},[n.rightTable]:{kind:"relation",relation:"one",targetTable:n.rightTable,field:n.rightField,referenceField:n.rightReferenceField}}};}}function Fr(e){for(let[t,n]of Object.entries(e.tables)){for(let[r,a]of Object.entries(n.columns))if(a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${t}.${r}': cannot set both notNull and nullable to true.`);for(let[r,a]of Object.entries(n.relations))if(a.relation!=="manyToMany"&&a.notNull===true&&a.nullable===true)throw new Error(`Invalid nullable configuration on '${t}.${r}': cannot set both notNull and nullable to true.`)}}function Pr(e){Fr(e);let t=$r(e);for(let[n,r]of Object.entries(t.tables))for(let[a,o]of Object.entries(r.relations)){if(o.relation!=="one")continue;let s=o.referenceField??"id",i=o.field??`${a}Id`;o.field=i;let l=O(t,o.targetTable,s)??o.fkType??"string";an(n,r,i,o.targetTable,s,{fkType:o.fkType,sqlName:o.sqlName,notNull:on(`${n}.${a}`,o,true),onDelete:o.onDelete,onUpdate:o.onUpdate},l);}for(let[n,r]of Object.entries(t.tables))for(let a of Object.values(r.relations)){if(a.relation!=="many")continue;let o=t.tables[a.targetTable];if(!o)continue;let s=a.referenceField??"id",i=a.field??`${te(n)}Id`;a.field=i;let l=O(t,n,s)??a.fkType??"string";an(a.targetTable,o,i,n,s,{fkType:a.fkType,sqlName:a.sqlName,notNull:on(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},l);}return Ir(t),t}function un(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function I(e){return e.notNull!==true}function Dr(e,t,n){let r=t.sqlName??E(e),a=r!==e;return t.type==="int"?a?`t.int(${h(r)})`:"t.int()":t.type==="string"?t.length!==void 0?a?`t.text(${h(r)}, { length: ${t.length} })`:`t.text({ length: ${t.length} })`:a?`t.text(${h(r)})`:"t.text()":t.type==="boolean"?a?`t.int(${h(r)}, { mode: "boolean" })`:'t.int({ mode: "boolean" })':t.type==="date"?a?`t.int(${h(r)}, { mode: "timestamp_ms" })`:'t.int({ mode: "timestamp_ms" })':n==="camelToSnake"&&a?`t.text(${h(r)})`:"t.text()"}function Er(e,t,n){let r=n.field,a=n.referenceField??"id";if(!r)throw new Error(`Relation on '${e}' targeting '${n.targetTable}' is missing a local field.`);if(!(r in t.columns))throw new Error(`Relation '${e}.${r}' references missing local field '${r}'.`);return {sourceField:r,targetField:a}}function Or(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
8871
|
+
`}function jr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function Br(e,t,n){if(t.references)return {tableName:t.references.table,fieldName:t.references.column};let r=Object.values(n.relations).find(a=>a.relation==="one"&&a.field===e);if(r)return {tableName:r.targetTable,fieldName:r.referenceField??"id"}}function Vr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,s]of Object.entries(r.relations))s.relation==="manyToMany"&&s.junctionTable&&a.push(`${h(o)}: {
|
|
8872
|
+
targetTable: ${h(s.targetTable)},
|
|
8873
|
+
junctionTable: ${h(s.junctionTable)},
|
|
8874
|
+
sourceField: ${h(s.sourceField??"")},
|
|
8875
|
+
targetField: ${h(s.targetField??"")},
|
|
8876
8876
|
},`);a.length!==0&&t.push(`${h(n)}: {
|
|
8877
8877
|
${a.map(o=>` ${o}`).join(`
|
|
8878
8878
|
`)}
|
|
@@ -8881,24 +8881,24 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8881
8881
|
${t.map(n=>` ${n}`).join(`
|
|
8882
8882
|
`)}
|
|
8883
8883
|
} as const;
|
|
8884
|
-
`}function
|
|
8884
|
+
`}function Wr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,s]of Object.entries(r.relations)){if(s.relation==="one"){a.push(`${h(o)}: {
|
|
8885
8885
|
kind: "one",
|
|
8886
|
-
targetTable: ${h(
|
|
8887
|
-
sourceField: ${h(
|
|
8888
|
-
referenceField: ${h(
|
|
8889
|
-
},`);continue}if(
|
|
8886
|
+
targetTable: ${h(s.targetTable)},
|
|
8887
|
+
sourceField: ${h(s.field??"")},
|
|
8888
|
+
referenceField: ${h(s.referenceField??"id")},
|
|
8889
|
+
},`);continue}if(s.relation==="many"){a.push(`${h(o)}: {
|
|
8890
8890
|
kind: "many",
|
|
8891
|
-
targetTable: ${h(
|
|
8892
|
-
sourceField: ${h(
|
|
8893
|
-
referenceField: ${h(
|
|
8891
|
+
targetTable: ${h(s.targetTable)},
|
|
8892
|
+
sourceField: ${h(s.field??"")},
|
|
8893
|
+
referenceField: ${h(s.referenceField??"id")},
|
|
8894
8894
|
},`);continue}a.push(`${h(o)}: {
|
|
8895
8895
|
kind: "manyToMany",
|
|
8896
|
-
targetTable: ${h(
|
|
8897
|
-
junctionTable: ${h(
|
|
8898
|
-
sourceField: ${h(
|
|
8899
|
-
targetField: ${h(
|
|
8900
|
-
referenceField: ${h(
|
|
8901
|
-
targetReferenceField: ${h(
|
|
8896
|
+
targetTable: ${h(s.targetTable)},
|
|
8897
|
+
junctionTable: ${h(s.junctionTable??"")},
|
|
8898
|
+
sourceField: ${h(s.sourceField??"")},
|
|
8899
|
+
targetField: ${h(s.targetField??"")},
|
|
8900
|
+
referenceField: ${h(s.referenceField??"id")},
|
|
8901
|
+
targetReferenceField: ${h(s.targetReferenceField??"id")},
|
|
8902
8902
|
},`);}a.length!==0&&t.push(`${h(n)}: {
|
|
8903
8903
|
${a.map(o=>` ${o}`).join(`
|
|
8904
8904
|
`)}
|
|
@@ -8907,29 +8907,29 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8907
8907
|
${t.map(n=>` ${n}`).join(`
|
|
8908
8908
|
`)}
|
|
8909
8909
|
} as const;
|
|
8910
|
-
`}function
|
|
8910
|
+
`}function Hr(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let s of Object.values(e.tables)){for(let i of jr(s))n.has(i)||r.add(i);for(let i of Object.values(s.columns))i.references&&!n.has(i.references.table)&&r.add(i.references.table);}let a=[],o=[];for(let[s,i]of Object.entries(e.tables)){let l=i.sqlName??E(s),c=[],u=[];for(let[y,m]of Object.entries(i.columns)){let v=Dr(y,m,t);m.uuidPrimaryKey&&(v+=".$defaultFn(() => crypto.randomUUID())"),m.primaryKey&&(v+=m.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),m.notNull&&(v+=".notNull()"),m.sqlDefault!==void 0&&(v+=`.default(${Nr(m.sqlDefault)})`);let N=Br(y,m,i);if(N)if(m.references?.onDelete||m.references?.onUpdate){let R=[];m.references.onDelete&&R.push(`onDelete: ${h(m.references.onDelete)}`),m.references.onUpdate&&R.push(`onUpdate: ${h(m.references.onUpdate)}`),v+=`.references(() => ${N.tableName}.${N.fieldName}, { ${R.join(", ")} })`;}else v+=`.references(() => ${N.tableName}.${N.fieldName})`;if(m.unique){let R=typeof m.unique=="object"&&m.unique.name?m.unique.name:`${l}_${E(y)}_unique_idx`;u.push(` t.uniqueIndex(${h(R)}).on(table.${y})`);}if(m.index){let R=typeof m.index=="object"&&m.index.name?m.index.name:`${l}_${E(y)}_idx`;u.push(` t.index(${h(R)}).on(table.${y})`);}c.push(` ${y}: ${v},`);}u.length>0?a.push(`export const ${s} = table(
|
|
8911
8911
|
${h(l)},
|
|
8912
8912
|
{
|
|
8913
|
-
${
|
|
8913
|
+
${c.join(`
|
|
8914
8914
|
`)}
|
|
8915
8915
|
},
|
|
8916
8916
|
(table) => [
|
|
8917
|
-
${
|
|
8917
|
+
${u.join(`,
|
|
8918
8918
|
`)}
|
|
8919
8919
|
],
|
|
8920
|
-
);`):a.push(`export const ${
|
|
8921
|
-
${
|
|
8920
|
+
);`):a.push(`export const ${s} = table(${h(l)}, {
|
|
8921
|
+
${c.join(`
|
|
8922
8922
|
`)}
|
|
8923
|
-
});`);let f=Object.entries(
|
|
8924
|
-
fields: [${
|
|
8925
|
-
references: [${m.targetTable}.${
|
|
8926
|
-
}),`);}for(let[y,m]of d)
|
|
8927
|
-
${
|
|
8923
|
+
});`);let f=Object.entries(i.relations).filter(([,y])=>y.relation==="one"),d=Object.entries(i.relations).filter(([,y])=>y.relation==="many"),b=Object.entries(i.relations).filter(([,y])=>y.relation==="manyToMany");if(f.length===0&&d.length===0&&b.length===0)continue;let x=[];for(let[y,m]of f){let v=Er(s,i,m);x.push(` ${y}: one(${m.targetTable}, {
|
|
8924
|
+
fields: [${s}.${v.sourceField}],
|
|
8925
|
+
references: [${m.targetTable}.${v.targetField}],
|
|
8926
|
+
}),`);}for(let[y,m]of d)x.push(` ${y}: many(${m.targetTable}),`);for(let[y,m]of b){if(!m.junctionTable)throw new Error(`manyToMany relation '${s}.${y}' is missing junctionTable after normalization.`);x.push(` ${y}: many(${m.junctionTable}),`);}o.push(`export const ${s}Relations = relations(${s}, ({ one, many }) => ({
|
|
8927
|
+
${x.join(`
|
|
8928
8928
|
`)}
|
|
8929
8929
|
}));`);}return `import * as t from "drizzle-orm/sqlite-core";
|
|
8930
8930
|
import { sqliteTable as table } from "drizzle-orm/sqlite-core";
|
|
8931
8931
|
import { relations } from "drizzle-orm";
|
|
8932
|
-
${
|
|
8932
|
+
${Or(r)}
|
|
8933
8933
|
${a.join(`
|
|
8934
8934
|
|
|
8935
8935
|
`)}
|
|
@@ -8938,15 +8938,15 @@ ${o.join(`
|
|
|
8938
8938
|
|
|
8939
8939
|
`)}
|
|
8940
8940
|
|
|
8941
|
-
${
|
|
8941
|
+
${Vr(e)}
|
|
8942
8942
|
|
|
8943
|
-
${
|
|
8944
|
-
`}function
|
|
8943
|
+
${Wr(e)}
|
|
8944
|
+
`}function cn(e,t,n){let r="z.unknown()";return e.type==="int"?r="z.number().int()":e.type==="string"?(r="z.string()",e.length!==void 0&&(r+=`.max(${e.length})`)):e.type==="boolean"?r="z.boolean()":e.type==="date"&&(r="z.date()"),t&&(r+=".optional()"),n&&(r+=".nullable()"),r}function zr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=j(n),o=[],s=[];for(let[i,l]of Object.entries(r.columns))o.push(` ${i}: ${cn(l,un(l),I(l))},`),s.push(` ${i}: ${cn(l,I(l),I(l))},`);t.push(`export const ${n}InsertSchema = z.object({
|
|
8945
8945
|
${o.join(`
|
|
8946
8946
|
`)}
|
|
8947
8947
|
});
|
|
8948
8948
|
export const ${n}SelectSchema = z.object({
|
|
8949
|
-
${
|
|
8949
|
+
${s.join(`
|
|
8950
8950
|
`)}
|
|
8951
8951
|
});
|
|
8952
8952
|
|
|
@@ -8955,23 +8955,34 @@ export type ${a}Select = z.infer<typeof ${n}SelectSchema>;
|
|
|
8955
8955
|
`);}return `import { z } from "zod";
|
|
8956
8956
|
|
|
8957
8957
|
${t.join(`
|
|
8958
|
-
`)}`}function
|
|
8958
|
+
`)}`}function Lr(e){return e.type==="int"?"number":e.type==="string"?"string":e.type==="boolean"?"boolean":e.type==="date"?"Date":"unknown"}function Ur(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=j(n),o=[],s=[];for(let[i,l]of Object.entries(r.columns)){let c=Lr(l),u=I(l)?" | null":"";o.push(` ${i}${I(l)?"?":""}: ${c}${u};`),s.push(` ${i}${un(l)?"?":""}: ${c}${u};`);}t.push(`export type ${a} = {
|
|
8959
8959
|
${o.join(`
|
|
8960
8960
|
`)}
|
|
8961
8961
|
};
|
|
8962
8962
|
|
|
8963
8963
|
export type New${a} = {
|
|
8964
|
-
${
|
|
8964
|
+
${s.join(`
|
|
8965
8965
|
`)}
|
|
8966
8966
|
};`);}return `${t.join(`
|
|
8967
8967
|
|
|
8968
8968
|
`)}
|
|
8969
|
-
`}function jr(e,t){if(t){let n=e[t];if(!J(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(J(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function sn(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=path.resolve(e.configDir,t.entry),a=path.resolve(e.configDir,t.outFile??path.resolve(e.outDirAbs,"schema.compiled.ts")),o=path.resolve(e.configDir,t.typesOutFile??path.resolve(e.outDirAbs,"schema.types.ts")),i=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),l=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),u=jr(l,t.exportName),c=Ar(u);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.dirname(i),{recursive:true})]);let f=Pr(c,n),d=Or(c),b=Er(c);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(i,b)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function Vr(e){return e.replaceAll("\\","/")}function A(e,t){let n=Vr(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Lr=new Set([".ts",".tsx",".mts",".cts"]);async function dn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await dn(a));continue}r.isFile()&&Lr.has(path.extname(r.name))&&n.push(a);}return n}function ee(e){return e.replace(/\.[cm]?tsx?$/,"")}function Ur(e,t){let n=e,r=false,a,o="unknown";for(;g__namespace.isCallExpression(n);){let i=n.expression;if(!g__namespace.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,n=i.expression;else if(s==="default"){r=true;let l=n.arguments[0];l&&(g__namespace.isStringLiteral(l)||g__namespace.isNumericLiteral(l)?a=l.text:l.kind===g__namespace.SyntaxKind.TrueKeyword?a="true":l.kind===g__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else n=i.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function Qr(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g__namespace.isPropertyAssignment(r)&&g__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)||n.push(Ur(r.initializer,r.name.text));return n}function _r(e){return g__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g__namespace.SyntaxKind.ExportKeyword)??false:false}function pn(e){return g__namespace.isIdentifier(e)?e.text:g__namespace.isParenthesizedExpression(e)?pn(e.expression):null}function Kr(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return g__namespace.isStringLiteral(n)||g__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>g__namespace.isStringLiteral(r)||g__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Gr(e,t){let n=g__namespace.createSourceFile(t,e,g__namespace.ScriptTarget.Latest,true,g__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(_r(a))for(let o of a.declarationList.declarations){if(!g__namespace.isIdentifier(o.name)||!o.initializer||!g__namespace.isCallExpression(o.initializer))continue;let i=pn(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?Kr(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?Qr(o.initializer.arguments[0]):[]});}return r}function ln(e,t,n){let r=t.replace(/\\/g,"/"),o=ee(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Jr(e,t){let n=e.replace(/\\/g,"/"),r=`${t}/`,a=n.indexOf(r);return a>=0?n.slice(a+r.length):n===t?"index.ts":n}function cn(e,t){let n=e.replace(/\\/g,"/"),a=ee(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function mn(e){let t=[],n=await dn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=path.relative(e.scanDirAbs,a),l=Gr(i,a),u=[{kind:"query",kindDirectory:"queries",exports:l.filter(c=>c.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:l.filter(c=>c.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:l.filter(c=>c.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:l.filter(c=>c.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:l.filter(c=>c.kind==="storage")}];for(let c of u){if(c.exports.length===0)continue;let f=Jr(s,c.kindDirectory);for(let d of c.exports){let b=c.kind==="query"||c.kind==="mutation"?cn(f,d.exportName):void 0,w=c.kind==="scheduler"||c.kind==="cron"?cn(f,d.exportName):void 0,y=c.kind==="query"||c.kind==="mutation"?[...ee(f).split("/").filter(Boolean),d.exportName]:void 0,m=c.kind==="query"?ln("queries",f,d.exportName):c.kind==="mutation"?ln("mutations",f,d.exportName):c.kind==="storage"?`/storage/managers/${d.exportName}`:`/${c.kindDirectory}/${w}`;t.push({kind:c.kind,exportName:d.exportName,filePath:a,importPath:A(e.outDirAbs,a),clientImportPath:A(path.resolve(e.outDirAbs,"client"),a),routePath:m,handlerName:b,clientSegments:y,taskName:w,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,i=r.get(o);if(i)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${i} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function Yr(e){let t=[],n="",r=0,a=0,o=0,i=false,s=false,l=false,u=false;for(let f=0;f<e.length;f+=1){let d=e[f];if(u){n+=d,u=false;continue}if(d==="\\"){n+=d,u=true;continue}if(!s&&!l&&d==="'"){i=!i,n+=d;continue}if(!i&&!l&&d==='"'){s=!s,n+=d;continue}if(!i&&!s&&d==="`"){l=!l,n+=d;continue}if(i||s||l){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let b=n.trim();b.length>0&&t.push(b),n="";continue}n+=d;}let c=n.trim();return c.length>0&&t.push(c),t}function Xr(e){let t=0,n=0,r=0,a=false,o=false,i=false,s=false;for(let l=0;l<e.length;l+=1){let u=e[l];if(s){s=false;continue}if(u==="\\"){s=true;continue}if(!o&&!i&&u==="'"){a=!a;continue}if(!a&&!i&&u==='"'){o=!o;continue}if(!a&&!o&&u==="`"){i=!i;continue}if(!(a||o||i)){if(u==="("){t+=1;continue}if(u===")"){t-=1;continue}if(u==="{"){n+=1;continue}if(u==="}"){n-=1;continue}if(u==="["){r+=1;continue}if(u==="]"){r-=1;continue}if(u===":"&&t===0&&n===0&&r===0)return l}}return -1}function ea(e){let t=e.toLowerCase();return /mode\s*:\s*["'`](timestamp|timestamp_ms)["'`]/.test(t)?"date":/mode\s*:\s*["'`]boolean["'`]/.test(t)?"boolean":/\.(date|datetime|timestamp)\s*\(/.test(t)?"date":/\.(int|integer|real|numeric|decimal|float|double)\s*\(/.test(t)?"number":/\.(text|varchar|char)\s*\(/.test(t)?"string":/\.(boolean|bool)\s*\(/.test(t)?"boolean":"unknown"}function ta(e){let t=Yr(e),n=[];for(let r of t){let a=Xr(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let i=r.slice(a+1).trim(),s=/\.primarykey\s*\(/i.test(i),l=/autoincrement\s*:\s*true/i.test(i),u=/\.default\s*\(/i.test(i),f=!/\.notnull\s*\(/i.test(i)||u||l||s;n.push({name:o,expression:i,type:ea(i),optional:f,primaryKey:s,autoIncrement:l});}return n}function na(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,i)=>{let s=0,l=false,u=false,c=false,f=false;for(let d=i;d<o.length;d+=1){let b=o[d];if(f){f=false;continue}if(b==="\\"){f=true;continue}if(!u&&!c&&b==="'"){l=!l;continue}if(!l&&!c&&b==='"'){u=!u;continue}if(!l&&!u&&b==="`"){c=!c;continue}if(!(l||u||c)){if(b==="{"){s+=1;continue}if(b==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let l=r(e,s);if(l===-1){a=t.exec(e);continue}let u=e.slice(s+1,l);n.push({exportName:o,tableName:i,columns:ta(u)}),a=t.exec(e);}return n}async function fn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await fn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function hn(e,t=[]){let n=await fn(e.scanDirAbs).catch(()=>[]),r=path.resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),l=na(s);if(l.length>0)return {schemaPath:o,tables:l}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function sa(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function yn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=A(t,a),s=path.resolve(t,"client"),l=A(s,a);await Promise.all([promises.mkdir(t,{recursive:true}),promises.mkdir(s,{recursive:true}),promises.mkdir(n,{recursive:true})]);let u=path.resolve(t,"server.ts"),c=path.resolve(t,"client.ts"),f=path.resolve(t,"auth.config.ts"),d=path.resolve(t,"auth.schema.ts"),b=path.resolve(t,"drizzle.config.ts"),w=path.resolve(n,"wrangler.json"),y=await sn(e),m=await hn(e,y?[y.schemaPath]:[]),x=A(t,m.schemaPath),R=await mn(e),k=ut(r.auth.basePath,r.database[0].binding,r.kv[0]?.binding,r.scheduler.binding,r.r2[0]?.binding,r.realtime.binding,r.realtime.objectName,r.realtime.subscribePath,r.realtime.websocketPath,r.realtime.protocol),Nn=fe(l,R),$n=L(x,R,r.r2[0]?.binding),Cn=le(i),qn=y?[sa(o,y.schemaPath),...r.schema.filter(v=>!/(^|\/)schema\.ts$/.test(v))]:r.schema,Mn=he(qn),In=pt(e,R),Fn=Xt(x,m,R),Pn=path.resolve(t,"admin.routes.ts"),En=$n.map(v=>Bun.write(path.resolve(t,v.relativePath),v.source)),Dn=Nn.map(v=>Bun.write(path.resolve(t,v.relativePath),v.source));await Promise.all([Bun.write(u,k),Bun.write(c,`export * from "./client/index";
|
|
8970
|
-
`)
|
|
8971
|
-
`)
|
|
8972
|
-
`)
|
|
8969
|
+
`}function Qr(e,t){if(t){let n=e[t];if(!Y(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(Y(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function dn(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")),s=path.resolve(e.configDir,t.zodOutFile??path.resolve(e.outDirAbs,"schema.zod.ts")),l=await import(`${url.pathToFileURL(r).href}?t=${Date.now()}`),c=Qr(l,t.exportName),u=Pr(c);await Promise.all([promises.mkdir(path.dirname(a),{recursive:true}),promises.mkdir(path.dirname(o),{recursive:true}),promises.mkdir(path.dirname(s),{recursive:true})]);let f=Hr(u,n),d=Ur(u),b=zr(u);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(s,b)]),{schemaPath:a,typesPath:o,zodPath:s,tableNames:Object.keys(u.tables)}}function Kr(e){return e.replaceAll("\\","/")}function C(e,t){let n=Kr(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Yr=new Set([".ts",".tsx",".mts",".cts"]);async function fn(e){let t=await promises.readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=path.resolve(e,r.name);if(r.isDirectory()){n.push(...await fn(a));continue}r.isFile()&&Yr.has(path.extname(r.name))&&n.push(a);}return n}function ne(e){return e.replace(/\.[cm]?tsx?$/,"")}function Xr(e,t){let n=e,r=false,a,o="unknown";for(;g__namespace.isCallExpression(n);){let s=n.expression;if(!g__namespace.isPropertyAccessExpression(s))break;let i=s.name.text;if(i==="optional"||i==="nullable")r=true,n=s.expression;else if(i==="default"){r=true;let l=n.arguments[0];l&&(g__namespace.isStringLiteral(l)||g__namespace.isNumericLiteral(l)?a=l.text:l.kind===g__namespace.SyntaxKind.TrueKeyword?a="true":l.kind===g__namespace.SyntaxKind.FalseKeyword&&(a="false")),n=s.expression;}else if(i==="string"||i==="uuid"||i==="email"||i==="url"){o="string";break}else if(i==="number"||i==="int"||i==="float"){o="number";break}else if(i==="boolean"){o="boolean";break}else n=s.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function ea(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g__namespace.isPropertyAssignment(r)&&g__namespace.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g__namespace.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)||n.push(Xr(r.initializer,r.name.text));return n}function ta(e){return g__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g__namespace.SyntaxKind.ExportKeyword)??false:false}function hn(e){return g__namespace.isIdentifier(e)?e.text:g__namespace.isParenthesizedExpression(e)?hn(e.expression):null}function na(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g__namespace.isPropertyAssignment(t))return [];let n=t.initializer;return g__namespace.isStringLiteral(n)||g__namespace.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g__namespace.isArrayLiteralExpression(n)?n.elements.map(r=>g__namespace.isStringLiteral(r)||g__namespace.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function ra(e,t){let n=g__namespace.createSourceFile(t,e,g__namespace.ScriptTarget.Latest,true,g__namespace.ScriptKind.TS),r=[];for(let a of n.statements)if(ta(a))for(let o of a.declarationList.declarations){if(!g__namespace.isIdentifier(o.name)||!o.initializer||!g__namespace.isCallExpression(o.initializer))continue;let s=hn(o.initializer.expression);s!=="query"&&s!=="mutation"&&s!=="scheduler"&&s!=="cron"&&s!=="storageManager"||r.push({exportName:o.name.text,kind:s==="storageManager"?"storage":s,cronTriggers:s==="cron"?na(o.initializer.arguments[0]):[],args:s==="query"||s==="mutation"?ea(o.initializer.arguments[0]):[]});}return r}function pn(e,t,n){let r=t.replace(/\\/g,"/"),o=ne(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(i=>i.trim()).filter(i=>i.length>0).join("/")}`}function aa(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 mn(e,t){let n=e.replace(/\\/g,"/"),a=ne(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(i=>i.trim()).filter(i=>i.length>0).join("/")}async function yn(e){let t=[],n=await fn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let s=await o.text(),i=path.relative(e.scanDirAbs,a),l=ra(s,a),c=[{kind:"query",kindDirectory:"queries",exports:l.filter(u=>u.kind==="query")},{kind:"mutation",kindDirectory:"mutations",exports:l.filter(u=>u.kind==="mutation")},{kind:"scheduler",kindDirectory:"schedulers",exports:l.filter(u=>u.kind==="scheduler")},{kind:"cron",kindDirectory:"crons",exports:l.filter(u=>u.kind==="cron")},{kind:"storage",kindDirectory:"queries",exports:l.filter(u=>u.kind==="storage")}];for(let u of c){if(u.exports.length===0)continue;let f=aa(i,u.kindDirectory);for(let d of u.exports){let b=u.kind==="query"||u.kind==="mutation"?mn(f,d.exportName):void 0,x=u.kind==="scheduler"||u.kind==="cron"?mn(f,d.exportName):void 0,y=u.kind==="query"||u.kind==="mutation"?[...ne(f).split("/").filter(Boolean),d.exportName]:void 0,m=u.kind==="query"?pn("queries",f,d.exportName):u.kind==="mutation"?pn("mutations",f,d.exportName):u.kind==="storage"?`/storage/managers/${d.exportName}`:`/${u.kindDirectory}/${x}`;t.push({kind:u.kind,exportName:d.exportName,filePath:a,importPath:C(e.outDirAbs,a),clientImportPath:C(path.resolve(e.outDirAbs,"client"),a),routePath:m,handlerName:b,clientSegments:y,taskName:x,cronTriggers:d.cronTriggers,args:d.args});}}}t.sort((a,o)=>a.routePath.localeCompare(o.routePath));let r=new Map;for(let a of t){let o=a.taskName?`task:${a.taskName}`:`route:${a.routePath}`,s=r.get(o);if(s)throw new Error(`Duplicate handler operation discovered: ${a.taskName??a.routePath} (${s} and ${a.filePath}#${a.exportName}).`);r.set(o,`${a.filePath}#${a.exportName}`);}return t}function ia(e){let t=[],n="",r=0,a=0,o=0,s=false,i=false,l=false,c=false;for(let f=0;f<e.length;f+=1){let d=e[f];if(c){n+=d,c=false;continue}if(d==="\\"){n+=d,c=true;continue}if(!i&&!l&&d==="'"){s=!s,n+=d;continue}if(!s&&!l&&d==='"'){i=!i,n+=d;continue}if(!s&&!i&&d==="`"){l=!l,n+=d;continue}if(s||i||l){n+=d;continue}if(d==="("?r+=1:d===")"?r-=1:d==="{"?a+=1:d==="}"?a-=1:d==="["?o+=1:d==="]"&&(o-=1),d===","&&r===0&&a===0&&o===0){let b=n.trim();b.length>0&&t.push(b),n="";continue}n+=d;}let u=n.trim();return u.length>0&&t.push(u),t}function sa(e){let t=0,n=0,r=0,a=false,o=false,s=false,i=false;for(let l=0;l<e.length;l+=1){let c=e[l];if(i){i=false;continue}if(c==="\\"){i=true;continue}if(!o&&!s&&c==="'"){a=!a;continue}if(!a&&!s&&c==='"'){o=!o;continue}if(!a&&!o&&c==="`"){s=!s;continue}if(!(a||o||s)){if(c==="("){t+=1;continue}if(c===")"){t-=1;continue}if(c==="{"){n+=1;continue}if(c==="}"){n-=1;continue}if(c==="["){r+=1;continue}if(c==="]"){r-=1;continue}if(c===":"&&t===0&&n===0&&r===0)return l}}return -1}function la(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 ca(e){let t=ia(e),n=[];for(let r of t){let a=sa(r);if(a===-1)continue;let o=r.slice(0,a).trim().replace(/^['"]|['"]$/g,"");if(!o)continue;let s=r.slice(a+1).trim(),i=/\.primarykey\s*\(/i.test(s),l=/autoincrement\s*:\s*true/i.test(s),c=/\.default\s*\(/i.test(s),f=!/\.notnull\s*\(/i.test(s)||c||l||i;n.push({name:o,expression:s,type:la(s),optional:f,primaryKey:i,autoIncrement:l});}return n}function ua(e){let t=/export\s+const\s+(\w+)\s*=\s*table\s*\(\s*["'`]([^"'`]+)["'`]/g,n=[],r=(o,s)=>{let i=0,l=false,c=false,u=false,f=false;for(let d=s;d<o.length;d+=1){let b=o[d];if(f){f=false;continue}if(b==="\\"){f=true;continue}if(!c&&!u&&b==="'"){l=!l;continue}if(!l&&!u&&b==='"'){c=!c;continue}if(!l&&!c&&b==="`"){u=!u;continue}if(!(l||c||u)){if(b==="{"){i+=1;continue}if(b==="}"&&(i-=1,i===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],s=a[2],i=e.indexOf("{",t.lastIndex);if(i===-1){a=t.exec(e);continue}let l=r(e,i);if(l===-1){a=t.exec(e);continue}let c=e.slice(i+1,l);n.push({exportName:o,tableName:s,columns:ca(c)}),a=t.exec(e);}return n}async function wn(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 wn(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function xn(e,t=[]){let n=await wn(e.scanDirAbs).catch(()=>[]),r=path.resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let s=Bun.file(o);if(!await s.exists())continue;let i=await s.text(),l=ua(i);if(l.length>0)return {schemaPath:o,tables:l}}throw new Error(`Unable to discover schema.ts under scanDir (${e.scanDirAbs}) or fallback (${r}).`)}function ma(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function Rn(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,s=C(t,a),i=path.resolve(t,"client"),l=C(i,a),c=performance.now();await Promise.all([promises.mkdir(t,{recursive:true}),promises.mkdir(i,{recursive:true}),promises.mkdir(n,{recursive:true})]),process.stdout.write(`\u{1F4C1} Directories (${(performance.now()-c).toFixed(0)}ms)
|
|
8970
|
+
`);let u=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)))),f=path.join(path.dirname(Bun.resolveSync("typescript/package.json",u)),"bin","tsc"),d=path.join(path.dirname(Bun.resolveSync("@better-auth/cli/package.json",u)),"dist","index.mjs"),b=path.resolve(t,"server.ts"),x=path.resolve(t,"client.ts"),y=path.resolve(t,"auth.config.ts"),m=path.resolve(t,"auth.schema.ts"),v=path.resolve(t,"drizzle.config.ts"),N=path.resolve(n,"wrangler.json"),R=await dn(e),ie=await xn(e,R?[R.schemaPath]:[]),se=C(t,ie.schemaPath),M=await yn(e);process.stdout.write(`\u{1F50D} ${M.length} handler(s) (${(performance.now()-c).toFixed(0)}ms)
|
|
8971
|
+
`);let Fn=gt(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),Pn=we(l,M),Dn=Q(se,M,r.r2[0]?.binding),En=pe(s),On=R?[ma(o,R.schemaPath),...r.schema.filter(w=>!/(^|\/)schema\.ts$/.test(w))]:r.schema,jn=xe(On),Bn=ht(e,M),Vn=rn(se,ie,M),Wn=path.resolve(t,"admin.routes.ts"),Hn=Dn.map(w=>Bun.write(path.resolve(t,w.relativePath),w.source)),zn=Pn.map(w=>Bun.write(path.resolve(t,w.relativePath),w.source));await Promise.all([Bun.write(b,Fn),Bun.write(x,`export * from "./client/index";
|
|
8972
|
+
`),...zn,...Hn,Bun.write(y,En),Bun.write(m,""),Bun.write(v,jn),Bun.write(N,`${JSON.stringify(Bn,null,2)}
|
|
8973
|
+
`),Bun.write(Wn,Vn)]),process.stdout.write(`\u{1F4DD} Source artifacts (${(performance.now()-c).toFixed(0)}ms)
|
|
8974
|
+
`);let H=path.relative(o,y).replace(/\\/g,"/"),Ln=H.startsWith(".")?H:`./${H}`,z=path.relative(o,m).replace(/\\/g,"/"),Un=z.startsWith(".")?z:`./${z}`,le=await Bun.spawn([process.execPath,d,"generate","--config",Ln,"--output",Un,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(le!==0)throw new Error(`better-auth generation failed with exit code ${le}`);process.stdout.write(`\u{1F510} Auth schema (${(performance.now()-c).toFixed(0)}ms)
|
|
8975
|
+
`);function Qn(w={}){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/*":["./*"]},...w},include:["./*.ts","./client/*.ts"]}}let ce=path.resolve(t,"tsconfig.js.json");await Promise.all([Bun.write(ce,`${JSON.stringify(Qn({declaration:true,emitDeclarationOnly:false}),null,2)}
|
|
8976
|
+
`)]),process.stdout.write(`\u{1F4C4} TS configs (${(performance.now()-c).toFixed(0)}ms)
|
|
8977
|
+
`);async function _n(w,A){process.stdout.write(`\u2699\uFE0F ${A}... (${(performance.now()-c).toFixed(0)}ms)
|
|
8978
|
+
`);let S=await Bun.spawn([process.execPath,f,"-p",w],{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(S!==0)throw new Error(`tsc ${A} failed with exit code ${S}`)}await _n(ce,"JS files"),process.stdout.write(`\u2705 JS + declarations (${(performance.now()-c).toFixed(0)}ms)
|
|
8979
|
+
`);async function ue(w){let A=await promises.readdir(w,{withFileTypes:true});for(let T of A){let S=path.join(w,T.name);if(T.isDirectory()){if(T.name==="node_modules"||T.name.startsWith("."))continue;await ue(S);}else T.name.endsWith(".ts")&&!T.name.endsWith(".d.ts")&&await promises.rm(S);}}await ue(t),process.stdout.write(`\u{1F4E6} Cleaned .ts files (${(performance.now()-c).toFixed(0)}ms)
|
|
8980
|
+
`);let Kn=t+"/";async function de(w){let A=await promises.readdir(w,{withFileTypes:true});for(let T of A){let S=path.join(w,T.name);if(T.isDirectory()){if(T.name==="node_modules"||T.name.startsWith(".")||S===t)continue;await de(S);}else !S.startsWith(Kn)&&(T.name.endsWith(".d.ts")||T.name.endsWith(".js"))&&await promises.rm(S);}}await de(o),process.stdout.write(`\u{1F9F9} Cleanup (${(performance.now()-c).toFixed(0)}ms)
|
|
8981
|
+
`);let Gn=path.resolve(o,"tsconfig.json");if(e.config.build&&fs.existsSync(Gn)){process.stdout.write(`\u2699\uFE0F Building project... (${(performance.now()-c).toFixed(0)}ms)
|
|
8982
|
+
`);let A=await Bun.spawn([process.execPath,f,"--build"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(A!==0)throw new Error(`TypeScript build failed with exit code ${A}`);process.stdout.write(`\u2705 Build complete (${(performance.now()-c).toFixed(0)}ms)
|
|
8983
|
+
`);}}var kn=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(),Sn=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),An=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(),Nn=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),queue:zod.z.string().min(1).optional()}).strict(),ya=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(),ba=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([kn,zod.z.array(kn).min(1)]),kv:zod.z.union([Sn,zod.z.array(Sn)]).optional(),r2:zod.z.union([An,zod.z.array(An)]).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:Nn.optional(),realtime:ya.optional(),wranglerOverrides:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),build:zod.z.boolean().optional()}).strict();function $n(e){return typeof e=="object"&&e!==null}function wa(e){let t=$n(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=Nn.safeParse(t);return n.success?n.data:{}}function xa(e){if(!$n(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function Ta(e){let n={...wa(e)??{},...e.scheduler??{}},r=e.realtime??{};return {...e,database:Array.isArray(e.database)?e.database:[e.database],kv:e.kv?Array.isArray(e.kv)?e.kv:[e.kv]:[],r2:e.r2?Array.isArray(e.r2)?e.r2:[e.r2]:[],scheduler:{enabled:n.enabled??true,binding:n.binding??"APPFLARE_SCHEDULER_QUEUE",queue:n.queue},realtime:{enabled:r.enabled??true,binding:r.binding??"APPFLARE_REALTIME",className:r.className??"AppflareRealtimeDurableObject",objectName:r.objectName??"global",subscribePath:r.subscribePath??"/realtime/subscribe",websocketPath:r.websocketPath??"/realtime/ws",protocol:r.protocol??"appflare.realtime.v1"},wranglerOverrides:xa(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir,build:e.build??true}}async function F(e){let t=path.isAbsolute(e??"")?e:path.resolve(process.cwd(),e??"appflare.config.ts"),n=path.dirname(t),o=(await import(url.pathToFileURL(t).href)).default,s=ba.parse(o),i=Ta(s);return {configPath:t,configDir:n,scanDirAbs:path.resolve(n,i.scanDir),outDirAbs:path.resolve(n,i.outDir),wranglerOutDirAbs:path.resolve(n,i.wranglerOutDir),config:i}}function Sa(e){let t=e;for(;;){if(fs.existsSync(path.resolve(t,"package.json")))return t;let n=path.dirname(t);if(n===t)return e;t=n;}}async function W(e,t={}){let n=await F(e);if(t.build!==void 0&&(n.config.build=t.build),await Rn(n),n.wranglerOutDirAbs===n.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${n.outDirAbs}
|
|
8973
8984
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${n.outDirAbs} and wrangler.json in ${n.wranglerOutDirAbs}
|
|
8974
|
-
`);}async function
|
|
8975
|
-
`);}finally{r=false,a&&(a=false,await o());}};
|
|
8985
|
+
`);}async function qn(e,t={}){if(await W(e,{build:t.build}),!t.watch)return;let n=await F(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await W(e,{build:t.build});}catch(i){process.stderr.write(`\u274C Build failed: ${i.message}
|
|
8986
|
+
`);}finally{r=false,a&&(a=false,await o());}};va__default.default.watch(n.scanDirAbs,{ignoreInitial:true,ignored:i=>i.includes("/_generated/")||i.includes("/dist/")||i.includes("/out/")||i.includes("/node_modules/")||i.endsWith(".d.ts")}).on("all",async(i,l)=>{process.stdout.write(`\u{1F504} Change detected: ${l}
|
|
8976
8987
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
8977
|
-
`);}async function
|
|
8988
|
+
`);}async function Mn(e,t={}){let n=await F(e),r=Sa(process.cwd());if([!!t.local,!!t.remote,!!t.preview].filter(Boolean).length>1)throw new Error("Only one of --local, --remote, or --preview can be set.");let o=path.resolve(n.outDirAbs,"drizzle.config.ts"),s=process.platform==="win32"?"npx.cmd":"npx",l=await Bun.spawn([s,"drizzle-kit","generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(l!==0)throw new Error(`drizzle-kit generate failed with exit code ${l}`);let c=n.config.database[0].databaseName,u=[s,"wrangler","d1","migrations","apply",c];t.local?u.push("--local"):t.remote?u.push("--remote"):t.preview&&u.push("--preview");let d=await Bun.spawn(u,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(d!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${d}`)}async function In(e,t={name:"",email:"",password:""}){let n=await F(e);if([!!t.local,!!t.remote].filter(Boolean).length>1)throw new Error("Only one of --local or --remote can be set.");let{hashPassword:a}=await import('better-auth/crypto'),o=await a(t.password),s=crypto.randomUUID(),i=crypto.randomUUID(),l=Date.now(),c=t.name.replace(/'/g,"''"),u=t.email.replace(/'/g,"''"),f=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${s}', '${c}', '${u}', 1, ${l}, ${l}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${i}', '${u}', 'credential', '${s}', '${o}', ${l}, ${l});`].join(" "),d=n.config.database[0].databaseName,x=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${f}`];t.local?x.push("--local"):t.remote&&x.push("--remote");let m=await Bun.spawn(x,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(m!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${m}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var q=new commander.Command;q.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");q.command("build").description("Generate server.ts, client.ts, auth.config.ts, drizzle.config.ts, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--no-build","Skip TypeScript build step").action(async e=>{await W(e.config,{build:e.build});});q.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 qn(e.config,{watch:e.watch,build:e.build});});q.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 Mn(e.config,{local:e.local,remote:e.remote,preview:e.preview});});q.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 In(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 q.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|