appflare 0.2.17 → 0.2.19
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/templates/handlers/generators/context/context-creation.ts +24 -3
- package/cli/templates/handlers/generators/registration/modules/cron.ts +1 -1
- package/cli/templates/handlers/generators/registration/modules/scheduler.ts +1 -1
- package/cli/templates/handlers/generators/types/context.ts +2 -0
- package/dist/cli/index.js +56 -33
- package/dist/cli/index.mjs +56 -33
- package/package.json +5 -5
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
export function generateContextCreation(defaultR2Binding?: string): string {
|
|
2
2
|
return `
|
|
3
|
-
export function createSchedulerExecutionContext(
|
|
3
|
+
export async function createSchedulerExecutionContext(
|
|
4
4
|
env: Record<string, unknown>,
|
|
5
5
|
options: RegisterHandlersOptions,
|
|
6
|
-
): AppflareContext {
|
|
6
|
+
): Promise<AppflareContext> {
|
|
7
7
|
const database = env[options.databaseBinding] as D1Database;
|
|
8
8
|
const r2Binding = options.r2Binding ?? ${JSON.stringify(defaultR2Binding ?? "")};
|
|
9
9
|
const storageBucket = r2Binding
|
|
@@ -11,9 +11,20 @@ export function createSchedulerExecutionContext(
|
|
|
11
11
|
: undefined;
|
|
12
12
|
const db = createDb(database);
|
|
13
13
|
const mutationEvents = [] as AppflareContext["mutationEvents"];
|
|
14
|
+
const kvNamespace = options.kvBinding
|
|
15
|
+
? (env[options.kvBinding] as KVNamespace)
|
|
16
|
+
: undefined;
|
|
14
17
|
const schedulerBinding = options.schedulerBinding ?? "APPFLARE_SCHEDULER_QUEUE";
|
|
15
18
|
const schedulerQueue = env[schedulerBinding] as SchedulerQueueBinding | undefined;
|
|
16
19
|
const helpers = createContextErrorHelpers();
|
|
20
|
+
const auth = createAuth({
|
|
21
|
+
DATABASE: database,
|
|
22
|
+
KV: kvNamespace,
|
|
23
|
+
});
|
|
24
|
+
const authAdapter = (await auth.$context).internalAdapter;
|
|
25
|
+
const schedulerContext = {
|
|
26
|
+
env: env as WorkerEnv["Bindings"],
|
|
27
|
+
} as unknown as Context<WorkerEnv>;
|
|
17
28
|
const ctx = {
|
|
18
29
|
$db: db,
|
|
19
30
|
db: createQueryDb(db, {
|
|
@@ -24,7 +35,8 @@ export function createSchedulerExecutionContext(
|
|
|
24
35
|
mutationEvents,
|
|
25
36
|
user: null as never,
|
|
26
37
|
session: null as never,
|
|
27
|
-
|
|
38
|
+
auth: authAdapter,
|
|
39
|
+
context: schedulerContext,
|
|
28
40
|
scheduler: createScheduler(schedulerQueue),
|
|
29
41
|
storage: null as never,
|
|
30
42
|
...helpers,
|
|
@@ -57,6 +69,14 @@ export async function createExecutionContext(
|
|
|
57
69
|
const schedulerBinding = options.schedulerBinding ?? "APPFLARE_SCHEDULER_QUEUE";
|
|
58
70
|
const schedulerQueue = c.env[schedulerBinding] as SchedulerQueueBinding | undefined;
|
|
59
71
|
const helpers = createContextErrorHelpers();
|
|
72
|
+
const auth = createAuth(
|
|
73
|
+
{
|
|
74
|
+
DATABASE: database,
|
|
75
|
+
KV: kvNamespace,
|
|
76
|
+
},
|
|
77
|
+
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
78
|
+
);
|
|
79
|
+
const authAdapter = (await auth.$context).internalAdapter;
|
|
60
80
|
const ctx = {
|
|
61
81
|
$db: db,
|
|
62
82
|
db: createQueryDb(db, {
|
|
@@ -67,6 +87,7 @@ export async function createExecutionContext(
|
|
|
67
87
|
mutationEvents,
|
|
68
88
|
user,
|
|
69
89
|
session,
|
|
90
|
+
auth: authAdapter,
|
|
70
91
|
context: c,
|
|
71
92
|
scheduler: createScheduler(schedulerQueue),
|
|
72
93
|
storage: null as never,
|
|
@@ -13,7 +13,7 @@ export async function executeCronTriggers(
|
|
|
13
13
|
return;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
const ctx = createSchedulerExecutionContext(env, options);
|
|
16
|
+
const ctx = await createSchedulerExecutionContext(env, options);
|
|
17
17
|
|
|
18
18
|
for (const cronEntry of cronHandlers) {
|
|
19
19
|
if (!cronEntry.cronTriggers.includes(cronValue)) {
|
|
@@ -17,7 +17,7 @@ export async function executeScheduledBatch(
|
|
|
17
17
|
return;
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
-
const ctx = createSchedulerExecutionContext(env, options);
|
|
20
|
+
const ctx = await createSchedulerExecutionContext(env, options);
|
|
21
21
|
|
|
22
22
|
for (const message of batch.messages) {
|
|
23
23
|
const body = (message?.body ?? {}) as QueueMessageBody;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export function generateTypesContextSection(): string {
|
|
2
2
|
return `type AuthSession = typeof auth.$Infer.Session;
|
|
3
|
+
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
3
4
|
type User = AuthSession['user']
|
|
4
5
|
type Session = AuthSession['session']
|
|
5
6
|
|
|
@@ -55,6 +56,7 @@ export type AppflareContext = {
|
|
|
55
56
|
mutationEvents: DbMutationEvent[];
|
|
56
57
|
user: User;
|
|
57
58
|
session: Session;
|
|
59
|
+
auth: AuthAdapter;
|
|
58
60
|
context: Context<WorkerEnv>;
|
|
59
61
|
scheduler: Scheduler;
|
|
60
62
|
storage: AppflareStorage;
|
package/dist/cli/index.js
CHANGED
|
@@ -164,8 +164,8 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
164
164
|
): Appflare<Options> {
|
|
165
165
|
return new Appflare(options);
|
|
166
166
|
}
|
|
167
|
-
`}function
|
|
168
|
-
`)}function Dn(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=
|
|
167
|
+
`}function Mn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function re(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Pn(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function ae(e){let t={children:new Map};for(let n of e){let r=t;for(let a of n.segments){let o=r.children.get(a);o||(o={children:new Map},r.children.set(a,o)),r=o;}r.operation=n;}return t}function V(e,t=1){let n=" ".repeat(t),r=" ".repeat(t+1),a=Array.from(e.children.entries()).sort(([i],[s])=>i.localeCompare(s));if(a.length===0)return e.operation?`${e.operation.alias}Route(runtime)`:"{}";let o=["{"];for(let[i,s]of a)o.push(`${r}${Pn(i)}: ${V(s,t+1)},`);return e.operation&&(o.push(`${r}run: ${e.operation.alias}Route(runtime).run,`),o.push(`${r}schema: ${e.operation.alias}Route(runtime).schema,`),e.operation.kind==="query"&&o.push(`${r}subscribe: ${e.operation.alias}Route(runtime).subscribe,`)),o.push(`${n}}`),o.join(`
|
|
168
|
+
`)}function Dn(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=Mn(`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:`${re(e.kind)}${re(n.join("_"))}`}}function En(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 = (
|
|
169
169
|
runtime: RequestRuntime,
|
|
170
170
|
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}> => {
|
|
171
171
|
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}>["run"] = async (
|
|
@@ -357,7 +357,7 @@ export type ${c} = z.input<typeof ${u.schemaConst}>;
|
|
|
357
357
|
export type ${f} = Awaited<ReturnType<typeof ${u.alias}.definition.handler>>;
|
|
358
358
|
export const ${d} = ${u.schemaConst};`}).join(`
|
|
359
359
|
|
|
360
|
-
`),i=t.map(u=>
|
|
360
|
+
`),i=t.map(u=>En(u)).join(`
|
|
361
361
|
|
|
362
362
|
`),s=V(ae(n)),l=V(ae(r));return `import betterFetch from "better-fetch";
|
|
363
363
|
import { z } from "zod";
|
|
@@ -1354,10 +1354,10 @@ function createStorageApi(
|
|
|
1354
1354
|
};
|
|
1355
1355
|
}
|
|
1356
1356
|
`}function he(e){return `
|
|
1357
|
-
export function createSchedulerExecutionContext(
|
|
1357
|
+
export async function createSchedulerExecutionContext(
|
|
1358
1358
|
env: Record<string, unknown>,
|
|
1359
1359
|
options: RegisterHandlersOptions,
|
|
1360
|
-
): AppflareContext {
|
|
1360
|
+
): Promise<AppflareContext> {
|
|
1361
1361
|
const database = env[options.databaseBinding] as D1Database;
|
|
1362
1362
|
const r2Binding = options.r2Binding ?? ${JSON.stringify(e??"")};
|
|
1363
1363
|
const storageBucket = r2Binding
|
|
@@ -1365,9 +1365,20 @@ export function createSchedulerExecutionContext(
|
|
|
1365
1365
|
: undefined;
|
|
1366
1366
|
const db = createDb(database);
|
|
1367
1367
|
const mutationEvents = [] as AppflareContext["mutationEvents"];
|
|
1368
|
+
const kvNamespace = options.kvBinding
|
|
1369
|
+
? (env[options.kvBinding] as KVNamespace)
|
|
1370
|
+
: undefined;
|
|
1368
1371
|
const schedulerBinding = options.schedulerBinding ?? "APPFLARE_SCHEDULER_QUEUE";
|
|
1369
1372
|
const schedulerQueue = env[schedulerBinding] as SchedulerQueueBinding | undefined;
|
|
1370
1373
|
const helpers = createContextErrorHelpers();
|
|
1374
|
+
const auth = createAuth({
|
|
1375
|
+
DATABASE: database,
|
|
1376
|
+
KV: kvNamespace,
|
|
1377
|
+
});
|
|
1378
|
+
const authAdapter = (await auth.$context).internalAdapter;
|
|
1379
|
+
const schedulerContext = {
|
|
1380
|
+
env: env as WorkerEnv["Bindings"],
|
|
1381
|
+
} as unknown as Context<WorkerEnv>;
|
|
1371
1382
|
const ctx = {
|
|
1372
1383
|
$db: db,
|
|
1373
1384
|
db: createQueryDb(db, {
|
|
@@ -1378,7 +1389,8 @@ export function createSchedulerExecutionContext(
|
|
|
1378
1389
|
mutationEvents,
|
|
1379
1390
|
user: null as never,
|
|
1380
1391
|
session: null as never,
|
|
1381
|
-
|
|
1392
|
+
auth: authAdapter,
|
|
1393
|
+
context: schedulerContext,
|
|
1382
1394
|
scheduler: createScheduler(schedulerQueue),
|
|
1383
1395
|
storage: null as never,
|
|
1384
1396
|
...helpers,
|
|
@@ -1411,6 +1423,14 @@ export async function createExecutionContext(
|
|
|
1411
1423
|
const schedulerBinding = options.schedulerBinding ?? "APPFLARE_SCHEDULER_QUEUE";
|
|
1412
1424
|
const schedulerQueue = c.env[schedulerBinding] as SchedulerQueueBinding | undefined;
|
|
1413
1425
|
const helpers = createContextErrorHelpers();
|
|
1426
|
+
const auth = createAuth(
|
|
1427
|
+
{
|
|
1428
|
+
DATABASE: database,
|
|
1429
|
+
KV: kvNamespace,
|
|
1430
|
+
},
|
|
1431
|
+
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
1432
|
+
);
|
|
1433
|
+
const authAdapter = (await auth.$context).internalAdapter;
|
|
1414
1434
|
const ctx = {
|
|
1415
1435
|
$db: db,
|
|
1416
1436
|
db: createQueryDb(db, {
|
|
@@ -1421,6 +1441,7 @@ export async function createExecutionContext(
|
|
|
1421
1441
|
mutationEvents,
|
|
1422
1442
|
user,
|
|
1423
1443
|
session,
|
|
1444
|
+
auth: authAdapter,
|
|
1424
1445
|
context: c,
|
|
1425
1446
|
scheduler: createScheduler(schedulerQueue),
|
|
1426
1447
|
storage: null as never,
|
|
@@ -4290,9 +4311,10 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4290
4311
|
);
|
|
4291
4312
|
return rows;
|
|
4292
4313
|
},
|
|
4293
|
-
`}function
|
|
4314
|
+
`}function Ce(){return [qe(),$e(),Ie(),Ae(),Ne()].join(`
|
|
4294
4315
|
|
|
4295
|
-
`)}function
|
|
4316
|
+
`)}function Me(){return `type AuthSession = typeof auth.$Infer.Session;
|
|
4317
|
+
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
4296
4318
|
type User = AuthSession['user']
|
|
4297
4319
|
type Session = AuthSession['session']
|
|
4298
4320
|
|
|
@@ -4348,6 +4370,7 @@ export type AppflareContext = {
|
|
|
4348
4370
|
mutationEvents: DbMutationEvent[];
|
|
4349
4371
|
user: User;
|
|
4350
4372
|
session: Session;
|
|
4373
|
+
auth: AuthAdapter;
|
|
4351
4374
|
context: Context<WorkerEnv>;
|
|
4352
4375
|
scheduler: Scheduler;
|
|
4353
4376
|
storage: AppflareStorage;
|
|
@@ -4485,9 +4508,9 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
4485
4508
|
definition,
|
|
4486
4509
|
};
|
|
4487
4510
|
}
|
|
4488
|
-
`}function De(){return [xe(),Se(),
|
|
4511
|
+
`}function De(){return [xe(),Se(),Ce(),Me(),Pe()].join(`
|
|
4489
4512
|
|
|
4490
|
-
`)}function
|
|
4513
|
+
`)}function Ee(e){return `import type { Context } from "hono";
|
|
4491
4514
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
4492
4515
|
import { drizzle } from "drizzle-orm/d1";
|
|
4493
4516
|
import { z, type ZodRawShape } from "zod";
|
|
@@ -4495,7 +4518,7 @@ import * as authSchema from "./auth.schema";
|
|
|
4495
4518
|
import * as schema from "${e}";
|
|
4496
4519
|
|
|
4497
4520
|
${De()}
|
|
4498
|
-
`}function
|
|
4521
|
+
`}function Fn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function On(e,t){let n=e.routePath.replace(/^\//,"").replace(/\//g,"_");return Fn(`op_${t}_${n}`)}function jn(e){return e.map((t,n)=>({operation:t,index:n,alias:On(t,n)}))}function Vn(e){return e.map(({operation:t,alias:n})=>`import { ${t.exportName} as ${n} } from "${t.importPath}";`).join(`
|
|
4499
4522
|
`)}function Bn(e){return e.filter(({operation:t})=>t.kind==="query"||t.kind==="mutation").map(({alias:t})=>`const ${`${t}Schema`} = z.object(${t}.definition.args);`).join(`
|
|
4500
4523
|
`)}function Hn(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(`
|
|
4501
4524
|
`)}function Wn(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
@@ -4545,7 +4568,7 @@ ${De()}
|
|
|
4545
4568
|
},`}).join(`
|
|
4546
4569
|
`)}function Kn(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
4547
4570
|
${t}.definition.handler,`).join(`
|
|
4548
|
-
`)}function
|
|
4571
|
+
`)}function Fe(e){let t=jn(e);return {imports:Vn(t),operationSchemas:Bn(t),schedulerSchemas:Hn(t),queryRoutes:Wn(t),mutationRoutes:Ln(t),queryRegistryEntries:zn(t),schedulerEntries:Un(t),schedulerPayloadMapEntries:Qn(t),cronEntries:_n(t),storageHandlersEntries:Kn(t)}}var Oe=`
|
|
4549
4572
|
function getRealtimeStub(
|
|
4550
4573
|
env: Record<string, unknown>,
|
|
4551
4574
|
options: RegisterHandlersOptions,
|
|
@@ -5784,7 +5807,7 @@ export async function executeScheduledBatch(
|
|
|
5784
5807
|
return;
|
|
5785
5808
|
}
|
|
5786
5809
|
|
|
5787
|
-
const ctx = createSchedulerExecutionContext(env, options);
|
|
5810
|
+
const ctx = await createSchedulerExecutionContext(env, options);
|
|
5788
5811
|
|
|
5789
5812
|
for (const message of batch.messages) {
|
|
5790
5813
|
const body = (message?.body ?? {}) as QueueMessageBody;
|
|
@@ -5835,7 +5858,7 @@ export async function executeCronTriggers(
|
|
|
5835
5858
|
return;
|
|
5836
5859
|
}
|
|
5837
5860
|
|
|
5838
|
-
const ctx = createSchedulerExecutionContext(env, options);
|
|
5861
|
+
const ctx = await createSchedulerExecutionContext(env, options);
|
|
5839
5862
|
|
|
5840
5863
|
for (const cronEntry of cronHandlers) {
|
|
5841
5864
|
if (!cronEntry.cronTriggers.includes(cronValue)) {
|
|
@@ -5849,7 +5872,7 @@ export async function executeCronTriggers(
|
|
|
5849
5872
|
}
|
|
5850
5873
|
}
|
|
5851
5874
|
}
|
|
5852
|
-
`;function _e(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:l,cronEntries:u,storageHandlersEntries:c}=
|
|
5875
|
+
`;function _e(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:l,cronEntries:u,storageHandlersEntries:c}=Fe(e);return `import { sValidator } from "@hono/standard-validator";
|
|
5853
5876
|
import type { Hono } from "hono";
|
|
5854
5877
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
5855
5878
|
import { ZodError, z } from "zod";
|
|
@@ -5916,7 +5939,7 @@ export function registerGeneratedHandlers(
|
|
|
5916
5939
|
${ze}
|
|
5917
5940
|
|
|
5918
5941
|
${Qe}
|
|
5919
|
-
`}function H(e,t,n){let r=
|
|
5942
|
+
`}function H(e,t,n){let r=Ee(e),a=be(n),o=we(),i=_e(t);return [{relativePath:"handlers.ts",source:r},{relativePath:"handlers.context.ts",source:a},{relativePath:"handlers.execution.ts",source:o},{relativePath:"handlers.routes.ts",source:i}]}function Gn(e){return e?`,
|
|
5920
5943
|
KV: c.env["${e}"] as KVNamespace`:""}function Ke(e,t){return `{
|
|
5921
5944
|
DATABASE: c.env["${e}"] as D1Database${Gn(t)}
|
|
5922
5945
|
}`}function Ge(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
@@ -6249,7 +6272,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6249
6272
|
\` : 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>\`}
|
|
6250
6273
|
</div>
|
|
6251
6274
|
\` : ''}
|
|
6252
|
-
</div>`}function
|
|
6275
|
+
</div>`}function C(e,t="Search term or filter..."){return `
|
|
6253
6276
|
<div class="form-control w-full md:w-auto relative">
|
|
6254
6277
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
6255
6278
|
<input type="text"
|
|
@@ -6260,7 +6283,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6260
6283
|
hx-trigger="keyup changed delay:500ms, search"
|
|
6261
6284
|
hx-target="#main-content"
|
|
6262
6285
|
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" />
|
|
6263
|
-
</div>`}function bt(e,t,n,r,a,o,i,s,l,u){let c=I(`/admin/table/${e.exportName}`),f=
|
|
6286
|
+
</div>`}function bt(e,t,n,r,a,o,i,s,l,u){let c=I(`/admin/table/${e.exportName}`),f=C(`/admin/table/${e.exportName}`,"Search term or filter..."),d=r?`<th class="w-10"><input id="select-all-${e.exportName}" type="checkbox" class="checkbox checkbox-xs" /></th>`:'<th class="w-10"><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></th>',y=r?`<td><input type="checkbox" class="checkbox checkbox-xs row-select-checkbox" value="\${String((row as any).${n} ?? '')}" /></td>`:'<td><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></td>',w=r?`
|
|
6264
6287
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
6265
6288
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
6266
6289
|
<div class="text-xs text-base-content/70">
|
|
@@ -6793,7 +6816,7 @@ ${vt()}
|
|
|
6793
6816
|
<iconify-icon icon="mdi:refresh" width="14" height="14"></iconify-icon>
|
|
6794
6817
|
</button>
|
|
6795
6818
|
</div>
|
|
6796
|
-
${
|
|
6819
|
+
${C("/admin/users","Search users...")}
|
|
6797
6820
|
</div>
|
|
6798
6821
|
\${tableHtml}
|
|
6799
6822
|
</div>
|
|
@@ -7776,7 +7799,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7776
7799
|
_rtEnabled = false;
|
|
7777
7800
|
});
|
|
7778
7801
|
</script>
|
|
7779
|
-
`}function
|
|
7802
|
+
`}function Ct(e){return `
|
|
7780
7803
|
const content = html\`
|
|
7781
7804
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
7782
7805
|
${Nt(e)}
|
|
@@ -7800,9 +7823,9 @@ ${Q()}`}function Nt(e){return `
|
|
|
7800
7823
|
return c.html(Layout({
|
|
7801
7824
|
title: "${e.exportName} - Functions",
|
|
7802
7825
|
children: content
|
|
7803
|
-
}));`}function
|
|
7826
|
+
}));`}function Mt(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
7804
7827
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
7805
|
-
${
|
|
7828
|
+
${Ct(n)}
|
|
7806
7829
|
});`).join(`
|
|
7807
7830
|
`)}function Pt(){return `
|
|
7808
7831
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
@@ -8000,7 +8023,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8000
8023
|
</div>
|
|
8001
8024
|
\`;
|
|
8002
8025
|
};
|
|
8003
|
-
`}function
|
|
8026
|
+
`}function Et(){return `
|
|
8004
8027
|
const handleStorageListRoute = async (c: any) => {
|
|
8005
8028
|
const bucket = getStorageBucket(c);
|
|
8006
8029
|
if (!bucket) {
|
|
@@ -8022,7 +8045,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8022
8045
|
|
|
8023
8046
|
adminApp.get('/storage', handleStorageListRoute);
|
|
8024
8047
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
8025
|
-
`}function
|
|
8048
|
+
`}function Ft(){return `
|
|
8026
8049
|
adminApp.post('/storage/upload', async (c) => {
|
|
8027
8050
|
const bucket = getStorageBucket(c);
|
|
8028
8051
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8124,13 +8147,13 @@ ${Q()}`}function Nt(e){return `
|
|
|
8124
8147
|
|
|
8125
8148
|
${Bt()}
|
|
8126
8149
|
|
|
8127
|
-
${
|
|
8150
|
+
${Ft()}
|
|
8128
8151
|
|
|
8129
8152
|
${Ot()}
|
|
8130
8153
|
|
|
8131
8154
|
${jt()}
|
|
8132
8155
|
|
|
8133
|
-
${
|
|
8156
|
+
${Et()}
|
|
8134
8157
|
`}function Wt(){return `
|
|
8135
8158
|
${Pt()}
|
|
8136
8159
|
|
|
@@ -8588,7 +8611,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8588
8611
|
\`
|
|
8589
8612
|
}));
|
|
8590
8613
|
});
|
|
8591
|
-
`}function Qt(e,t,n){let r=it(t),a=st(r),o=ct(r),i=At(t),s=
|
|
8614
|
+
`}function Qt(e,t,n){let r=it(t),a=st(r),o=ct(r),i=At(t),s=Mt(n),l=Wt(),u=Lt(a,n),c=zt(),f=Ut(o);return `import { Hono } from "hono";
|
|
8592
8615
|
import { html, raw } from "hono/html";
|
|
8593
8616
|
import { drizzle } from "drizzle-orm/d1";
|
|
8594
8617
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -8617,7 +8640,7 @@ ${f}
|
|
|
8617
8640
|
app.route('/admin', adminApp);
|
|
8618
8641
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
8619
8642
|
}
|
|
8620
|
-
`}function _(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"}function
|
|
8643
|
+
`}function _(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"}function M(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function D(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(t,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(t,n)=>n.toUpperCase())}function J(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 cr(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 ur(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 P(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function _t(e,t,n,r,a,o,i){let s=t.columns[n];if(s){if(s.references&&(s.references.table!==r||s.references.column!==a))throw new Error(`Inferred relation '${e}.${n}' conflicts with explicit references(${s.references.table}.${s.references.column}).`);t.columns[n]={...s,notNull:s.notNull??(s.nullable===true?false:o.notNull),nullable:s.nullable??(o.notNull===false?true:void 0),references:{table:r,column:a,onDelete:s.references?.onDelete??o.onDelete,onUpdate:s.references?.onUpdate??o.onUpdate}};return}t.columns[n]={kind:"column",type:o.fkType??i,sqlName:o.sqlName,notNull:o.notNull??true,nullable:o.notNull===false?true:void 0,references:{table:r,column:a,onDelete:o.onDelete,onUpdate:o.onUpdate}};}function Kt(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 Gt(e,t){return `${e}:${t}`}function dr(e,t,n,r){let a=Gt(e,t),o=Gt(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 pr(e,t){return `${e}${D(t)}Links`}function Jt(e,t,n){let r=J(e),a=J(t);return r===a?`${n}${D(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 gr(e){let t=new Map;for(let[n,r]of Object.entries(e.tables))for(let a of Object.values(r.relations)){if(a.relation!=="manyToMany")continue;let o=a.referenceField??"id",i=a.targetReferenceField??"id",s=dr(n,o,a.targetTable,i),l=Jt(s.leftTable,s.rightTable,"source"),u=Jt(s.rightTable,s.leftTable,"target"),c={leftTable:s.leftTable,leftReferenceField:s.leftReferenceField,rightTable:s.rightTable,rightReferenceField:s.rightReferenceField,junctionTable:a.junctionTable??pr(s.leftTable,s.rightTable),leftField:s.sourceIsLeft?a.sourceField??l:a.targetField??l,rightField:s.sourceIsLeft?a.targetField??u:a.sourceField??u,leftSqlName:s.sourceIsLeft?a.sourceSqlName:a.targetSqlName,rightSqlName:s.sourceIsLeft?a.targetSqlName:a.sourceSqlName,onDelete:a.onDelete,onUpdate:a.onUpdate};if(c.leftField===c.rightField)throw new Error(`manyToMany pair '${s.key}' resolves to duplicate junction fields '${c.leftField}'. Set sourceField/targetField explicitly.`);let f=t.get(s.key);f?mr(f,c,s.key):t.set(s.key,c),a.referenceField=o,a.targetReferenceField=i,a.junctionTable=c.junctionTable,a.sourceField=s.sourceIsLeft?c.leftField:c.rightField,a.targetField=s.sourceIsLeft?c.rightField:c.leftField,a.sourceSqlName=s.sourceIsLeft?c.leftSqlName:c.rightSqlName,a.targetSqlName=s.sourceIsLeft?c.rightSqlName:c.leftSqlName;}for(let n of t.values()){if(n.junctionTable in e.tables)throw new Error(`manyToMany auto junction table '${n.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`);let r=P(e,n.leftTable,n.leftReferenceField)??"string",a=P(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 hr(e){fr(e);let t=ur(e);for(let[n,r]of Object.entries(t.tables))for(let[a,o]of Object.entries(r.relations)){if(o.relation!=="one")continue;let i=o.referenceField??"id",s=o.field??`${a}Id`;o.field=s;let l=P(t,o.targetTable,i)??o.fkType??"string";_t(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:Kt(`${n}.${a}`,o,true),onDelete:o.onDelete,onUpdate:o.onUpdate},l);}for(let[n,r]of Object.entries(t.tables))for(let a of Object.values(r.relations)){if(a.relation!=="many")continue;let o=t.tables[a.targetTable];if(!o)continue;let i=a.referenceField??"id",s=a.field??`${J(n)}Id`;a.field=s;let l=P(t,n,i)??a.fkType??"string";_t(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:Kt(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},l);}return gr(t),t}function Yt(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function $(e){return e.notNull!==true}function br(e,t,n){let r=t.sqlName??M(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 yr(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 wr(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
8621
8644
|
`}function xr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function vr(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 Tr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations))i.relation==="manyToMany"&&i.junctionTable&&a.push(`${h(o)}: {
|
|
8622
8645
|
targetTable: ${h(i.targetTable)},
|
|
8623
8646
|
junctionTable: ${h(i.junctionTable)},
|
|
@@ -8657,7 +8680,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8657
8680
|
${t.map(n=>` ${n}`).join(`
|
|
8658
8681
|
`)}
|
|
8659
8682
|
} as const;
|
|
8660
|
-
`}function kr(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let i of Object.values(e.tables)){for(let s of xr(i))n.has(s)||r.add(s);for(let s of Object.values(i.columns))s.references&&!n.has(s.references.table)&&r.add(s.references.table);}let a=[],o=[];for(let[i,s]of Object.entries(e.tables)){let l=s.sqlName??
|
|
8683
|
+
`}function kr(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let i of Object.values(e.tables)){for(let s of xr(i))n.has(s)||r.add(s);for(let s of Object.values(i.columns))s.references&&!n.has(s.references.table)&&r.add(s.references.table);}let a=[],o=[];for(let[i,s]of Object.entries(e.tables)){let l=s.sqlName??M(i),u=[],c=[];for(let[b,m]of Object.entries(s.columns)){let x=br(b,m,t);m.uuidPrimaryKey&&(x+=".$defaultFn(() => crypto.randomUUID())"),m.primaryKey&&(x+=m.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),m.notNull&&(x+=".notNull()"),m.sqlDefault!==void 0&&(x+=`.default(${cr(m.sqlDefault)})`);let v=vr(b,m,s);if(v)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)}`),x+=`.references(() => ${v.tableName}.${v.fieldName}, { ${R.join(", ")} })`;}else x+=`.references(() => ${v.tableName}.${v.fieldName})`;if(m.unique){let R=typeof m.unique=="object"&&m.unique.name?m.unique.name:`${l}_${M(b)}_unique_idx`;c.push(` t.uniqueIndex(${h(R)}).on(table.${b})`);}if(m.index){let R=typeof m.index=="object"&&m.index.name?m.index.name:`${l}_${M(b)}_idx`;c.push(` t.index(${h(R)}).on(table.${b})`);}u.push(` ${b}: ${x},`);}c.length>0?a.push(`export const ${i} = table(
|
|
8661
8684
|
${h(l)},
|
|
8662
8685
|
{
|
|
8663
8686
|
${u.join(`
|
|
@@ -8716,11 +8739,11 @@ ${i.join(`
|
|
|
8716
8739
|
};`);}return `${t.join(`
|
|
8717
8740
|
|
|
8718
8741
|
`)}
|
|
8719
|
-
`}function $r(e,t){if(t){let n=e[t];if(!_(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(_(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function Xt(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=$r(l,t.exportName),c=hr(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=kr(c,n),d=Nr(c),y=Sr(c);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function Ir(e){return e.replaceAll("\\","/")}function A(e,t){let n=Ir(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Dr=new Set([".ts",".tsx",".mts",".cts"]);async function rn(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 rn(a));continue}r.isFile()&&Dr.has(path.extname(r.name))&&n.push(a);}return n}function Z(e){return e.replace(/\.[cm]?tsx?$/,"")}function Fr(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 Er(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(Fr(r.initializer,r.name.text));return n}function Or(e){return g__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g__namespace.SyntaxKind.ExportKeyword)??false:false}function an(e){return g__namespace.isIdentifier(e)?e.text:g__namespace.isParenthesizedExpression(e)?an(e.expression):null}function jr(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)?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 Vr(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(Or(a))for(let o of a.declarationList.declarations){if(!g__namespace.isIdentifier(o.name)||!o.initializer||!g__namespace.isCallExpression(o.initializer))continue;let i=an(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?jr(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?Er(o.initializer.arguments[0]):[]});}return r}function en(e,t,n){let r=t.replace(/\\/g,"/"),o=Z(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Br(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 tn(e,t){let n=e.replace(/\\/g,"/"),a=Z(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function on(e){let t=[],n=await rn(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=Vr(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=Br(s,c.kindDirectory);for(let d of c.exports){let y=c.kind==="query"||c.kind==="mutation"?tn(f,d.exportName):void 0,w=c.kind==="scheduler"||c.kind==="cron"?tn(f,d.exportName):void 0,b=c.kind==="query"||c.kind==="mutation"?[...Z(f).split("/").filter(Boolean),d.exportName]:void 0,m=c.kind==="query"?en("queries",f,d.exportName):c.kind==="mutation"?en("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:y,clientSegments:b,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 Wr(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 y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let c=n.trim();return c.length>0&&t.push(c),t}function Lr(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 zr(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 Ur(e){let t=Wr(e),n=[];for(let r of t){let a=Lr(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:zr(i),optional:f,primaryKey:s,autoIncrement:l});}return n}function Qr(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 y=o[d];if(f){f=false;continue}if(y==="\\"){f=true;continue}if(!u&&!c&&y==="'"){l=!l;continue}if(!l&&!c&&y==='"'){u=!u;continue}if(!l&&!u&&y==="`"){c=!c;continue}if(!(l||u||c)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let 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:Ur(u)}),a=t.exec(e);}return n}async function ln(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 ln(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function cn(e,t=[]){let n=await ln(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=Qr(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 _r(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function un(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"),y=path.resolve(t,"drizzle.config.ts"),w=path.resolve(n,"wrangler.json"),b=await Xt(e),m=await cn(e,b?[b.schemaPath]:[]),x=A(t,m.schemaPath),v=await on(e),R=rt(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),xn=le(l,v),vn=H(x,v,r.r2[0]?.binding),Tn=te(i),Rn=b?[_r(o,b.schemaPath),...r.schema.filter(k=>!/(^|\/)schema\.ts$/.test(k))]:r.schema,kn=ce(Rn),Sn=ot(e,v),An=Qt(x,m,v),Nn=path.resolve(t,"admin.routes.ts"),$n=vn.map(k=>Bun.write(path.resolve(t,k.relativePath),k.source)),qn=xn.map(k=>Bun.write(path.resolve(t,k.relativePath),k.source));await Promise.all([Bun.write(u,R),Bun.write(c,`export * from "./client/index";
|
|
8742
|
+
`}function $r(e,t){if(t){let n=e[t];if(!_(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(_(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function Xt(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=$r(l,t.exportName),c=hr(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=kr(c,n),d=Nr(c),y=Sr(c);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function Ir(e){return e.replaceAll("\\","/")}function A(e,t){let n=Ir(path.relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Dr=new Set([".ts",".tsx",".mts",".cts"]);async function rn(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 rn(a));continue}r.isFile()&&Dr.has(path.extname(r.name))&&n.push(a);}return n}function Z(e){return e.replace(/\.[cm]?tsx?$/,"")}function Er(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 Fr(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(Er(r.initializer,r.name.text));return n}function Or(e){return g__namespace.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g__namespace.SyntaxKind.ExportKeyword)??false:false}function an(e){return g__namespace.isIdentifier(e)?e.text:g__namespace.isParenthesizedExpression(e)?an(e.expression):null}function jr(e){if(!e||!g__namespace.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g__namespace.isPropertyAssignment(r)||!g__namespace.isIdentifier(r.name)?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 Vr(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(Or(a))for(let o of a.declarationList.declarations){if(!g__namespace.isIdentifier(o.name)||!o.initializer||!g__namespace.isCallExpression(o.initializer))continue;let i=an(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?jr(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?Fr(o.initializer.arguments[0]):[]});}return r}function en(e,t,n){let r=t.replace(/\\/g,"/"),o=Z(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Br(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 tn(e,t){let n=e.replace(/\\/g,"/"),a=Z(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function on(e){let t=[],n=await rn(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=Vr(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=Br(s,c.kindDirectory);for(let d of c.exports){let y=c.kind==="query"||c.kind==="mutation"?tn(f,d.exportName):void 0,w=c.kind==="scheduler"||c.kind==="cron"?tn(f,d.exportName):void 0,b=c.kind==="query"||c.kind==="mutation"?[...Z(f).split("/").filter(Boolean),d.exportName]:void 0,m=c.kind==="query"?en("queries",f,d.exportName):c.kind==="mutation"?en("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:y,clientSegments:b,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 Wr(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 y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let c=n.trim();return c.length>0&&t.push(c),t}function Lr(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 zr(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 Ur(e){let t=Wr(e),n=[];for(let r of t){let a=Lr(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:zr(i),optional:f,primaryKey:s,autoIncrement:l});}return n}function Qr(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 y=o[d];if(f){f=false;continue}if(y==="\\"){f=true;continue}if(!u&&!c&&y==="'"){l=!l;continue}if(!l&&!c&&y==='"'){u=!u;continue}if(!l&&!u&&y==="`"){c=!c;continue}if(!(l||u||c)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let 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:Ur(u)}),a=t.exec(e);}return n}async function ln(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 ln(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function cn(e,t=[]){let n=await ln(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=Qr(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 _r(e,t){let n=path.relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function un(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"),y=path.resolve(t,"drizzle.config.ts"),w=path.resolve(n,"wrangler.json"),b=await Xt(e),m=await cn(e,b?[b.schemaPath]:[]),x=A(t,m.schemaPath),v=await on(e),R=rt(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),xn=le(l,v),vn=H(x,v,r.r2[0]?.binding),Tn=te(i),Rn=b?[_r(o,b.schemaPath),...r.schema.filter(k=>!/(^|\/)schema\.ts$/.test(k))]:r.schema,kn=ce(Rn),Sn=ot(e,v),An=Qt(x,m,v),Nn=path.resolve(t,"admin.routes.ts"),$n=vn.map(k=>Bun.write(path.resolve(t,k.relativePath),k.source)),qn=xn.map(k=>Bun.write(path.resolve(t,k.relativePath),k.source));await Promise.all([Bun.write(u,R),Bun.write(c,`export * from "./client/index";
|
|
8720
8743
|
`),...qn,...$n,Bun.write(f,Tn),Bun.write(d,""),Bun.write(y,kn),Bun.write(w,`${JSON.stringify(Sn,null,2)}
|
|
8721
|
-
`),Bun.write(Nn,An)]);let O=path.relative(o,f).replace(/\\/g,"/"),In=O.startsWith(".")?O:`./${O}`,j=path.relative(o,d).replace(/\\/g,"/"),
|
|
8744
|
+
`),Bun.write(Nn,An)]);let O=path.relative(o,f).replace(/\\/g,"/"),In=O.startsWith(".")?O:`./${O}`,j=path.relative(o,d).replace(/\\/g,"/"),Cn=j.startsWith(".")?j:`./${j}`,ee=await Bun.spawn(["npx","@better-auth/cli","generate","--config",In,"--output",Cn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(ee!==0)throw new Error(`better-auth generation failed with exit code ${ee}`)}var dn=zod.z.object({binding:zod.z.string().min(1),databaseName:zod.z.string().min(1),databaseId:zod.z.string().min(1),previewDatabaseId:zod.z.string().min(1).optional(),migrationsDir:zod.z.string().min(1).optional()}).strict(),pn=zod.z.object({binding:zod.z.string().min(1),id:zod.z.string().min(1),previewId:zod.z.string().min(1).optional()}).strict(),mn=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(),gn=zod.z.object({enabled:zod.z.boolean().optional(),binding:zod.z.string().min(1).optional(),queue:zod.z.string().min(1).optional()}).strict(),Zr=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(),Yr=zod.z.object({scanDir:zod.z.string().min(1),outDir:zod.z.string().min(1),wranglerOutDir:zod.z.string().min(1).optional(),wranglerOutPath:zod.z.string().min(1).optional(),schema:zod.z.array(zod.z.string()).min(1),schemaDsl:zod.z.object({entry:zod.z.string().min(1),exportName:zod.z.string().min(1).optional(),outFile:zod.z.string().min(1).optional(),typesOutFile:zod.z.string().min(1).optional(),zodOutFile:zod.z.string().min(1).optional(),namingStrategy:zod.z.literal("camelToSnake").optional()}).strict().optional(),database:zod.z.union([dn,zod.z.array(dn).min(1)]),kv:zod.z.union([pn,zod.z.array(pn)]).optional(),r2:zod.z.union([mn,zod.z.array(mn)]).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:gn.optional(),realtime:Zr.optional(),wranglerOverrides:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}).strict();function fn(e){return typeof e=="object"&&e!==null}function Xr(e){let t=fn(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=gn.safeParse(t);return n.success?n.data:{}}function ea(e){if(!fn(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function ta(e){let n={...Xr(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:ea(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir}}async function q(e){let t=path.isAbsolute(e??"")?e:path.resolve(process.cwd(),e??"appflare.config.ts"),n=path.dirname(t),o=(await import(url.pathToFileURL(t).href)).default,i=Yr.parse(o),s=ta(i);return {configPath:t,configDir:n,scanDirAbs:path.resolve(n,s.scanDir),outDirAbs:path.resolve(n,s.outDir),wranglerOutDirAbs:path.resolve(n,s.wranglerOutDir),config:s}}function oa(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 F(e){let t=await q(e);if(await un(t),t.wranglerOutDirAbs===t.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${t.outDirAbs}
|
|
8722
8745
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${t.outDirAbs} and wrangler.json in ${t.wranglerOutDirAbs}
|
|
8723
|
-
`);}async function bn(e,t=false){if(await
|
|
8746
|
+
`);}async function bn(e,t=false){if(await F(e),!t)return;let n=await q(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await F(e);}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
8724
8747
|
`);}finally{r=false,a&&(a=false,await o());}};na__default.default.watch(n.scanDirAbs,{ignoreInitial:true}).on("all",async(s,l)=>{process.stdout.write(`\u{1F504} Change detected: ${l}
|
|
8725
8748
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
8726
|
-
`);}async function yn(e,t={}){let n=await q(e),r=oa(process.cwd());if([!!t.local,!!t.remote,!!t.preview].filter(Boolean).length>1)throw new Error("Only one of --local, --remote, or --preview can be set.");let o=path.resolve(n.outDirAbs,"drizzle.config.ts"),i=process.platform==="win32"?"npx.cmd":"npx",l=await Bun.spawn([i,"drizzle-kit","generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(l!==0)throw new Error(`drizzle-kit generate failed with exit code ${l}`);let u=n.config.database[0].databaseName,c=[i,"wrangler","d1","migrations","apply",u];t.local?c.push("--local"):t.remote?c.push("--remote"):t.preview&&c.push("--preview");let d=await Bun.spawn(c,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(d!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${d}`)}async function wn(e,t={name:"",email:"",password:""}){let n=await q(e);if([!!t.local,!!t.remote].filter(Boolean).length>1)throw new Error("Only one of --local or --remote can be set.");let{hashPassword:a}=await import('better-auth/crypto'),o=await a(t.password),i=crypto.randomUUID(),s=crypto.randomUUID(),l=Date.now(),u=t.name.replace(/'/g,"''"),c=t.email.replace(/'/g,"''"),f=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${u}', '${c}', 1, ${l}, ${l}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${c}', 'credential', '${i}', '${o}', ${l}, ${l});`].join(" "),d=n.config.database[0].databaseName,w=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${f}`];t.local?w.push("--local"):t.remote&&w.push("--remote");let m=await Bun.spawn(w,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(m!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${m}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var N=new commander.Command;N.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");N.command("build").description("Generate server.ts, client.ts, auth.config.ts, drizzle.config.ts, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").action(async e=>{await
|
|
8749
|
+
`);}async function yn(e,t={}){let n=await q(e),r=oa(process.cwd());if([!!t.local,!!t.remote,!!t.preview].filter(Boolean).length>1)throw new Error("Only one of --local, --remote, or --preview can be set.");let o=path.resolve(n.outDirAbs,"drizzle.config.ts"),i=process.platform==="win32"?"npx.cmd":"npx",l=await Bun.spawn([i,"drizzle-kit","generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(l!==0)throw new Error(`drizzle-kit generate failed with exit code ${l}`);let u=n.config.database[0].databaseName,c=[i,"wrangler","d1","migrations","apply",u];t.local?c.push("--local"):t.remote?c.push("--remote"):t.preview&&c.push("--preview");let d=await Bun.spawn(c,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(d!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${d}`)}async function wn(e,t={name:"",email:"",password:""}){let n=await q(e);if([!!t.local,!!t.remote].filter(Boolean).length>1)throw new Error("Only one of --local or --remote can be set.");let{hashPassword:a}=await import('better-auth/crypto'),o=await a(t.password),i=crypto.randomUUID(),s=crypto.randomUUID(),l=Date.now(),u=t.name.replace(/'/g,"''"),c=t.email.replace(/'/g,"''"),f=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${u}', '${c}', 1, ${l}, ${l}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${c}', 'credential', '${i}', '${o}', ${l}, ${l});`].join(" "),d=n.config.database[0].databaseName,w=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${f}`];t.local?w.push("--local"):t.remote&&w.push("--remote");let m=await Bun.spawn(w,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(m!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${m}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var N=new commander.Command;N.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");N.command("build").description("Generate server.ts, client.ts, auth.config.ts, drizzle.config.ts, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").action(async e=>{await F(e.config);});N.command("dev").description("Run generator in development mode").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("-w, --watch","Watch scanDir and regenerate on changes",false).action(async e=>{await bn(e.config,e.watch);});N.command("migrate").description("Generate drizzle migration files from outDir/auth.schema.ts and apply them to the configured D1 database").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute commands/files against a local DB for use with wrangler dev",false).option("--remote","Execute commands/files against a remote DB for use with wrangler dev --remote",false).option("--preview","Execute commands/files against a preview D1 DB",false).action(async e=>{await yn(e.config,{local:e.local,remote:e.remote,preview:e.preview});});N.command("add-admin").description("Add an admin user to the database").requiredOption("-n, --name <name>","Admin's display name").requiredOption("-e, --email <email>","Admin's email address").requiredOption("-p, --password <password>","Admin's password").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute command against a local DB for use with wrangler dev",false).option("--remote","Execute command against a remote DB for use with wrangler dev --remote",false).action(async e=>{await wn(e.config,{name:e.name,email:e.email,password:e.password,local:e.local,remote:e.remote});});(async()=>{process.versions.bun||(console.error("Appflare CLI must be run with Bun."),process.exit(1)),await N.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|
package/dist/cli/index.mjs
CHANGED
|
@@ -164,8 +164,8 @@ export function createAppflare<Options extends BetterAuthClientOptions = Inferre
|
|
|
164
164
|
): Appflare<Options> {
|
|
165
165
|
return new Appflare(options);
|
|
166
166
|
}
|
|
167
|
-
`}function
|
|
168
|
-
`)}function Dn(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=
|
|
167
|
+
`}function Mn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t||"_route"}function re(e){return e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Pn(e){return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function ae(e){let t={children:new Map};for(let n of e){let r=t;for(let a of n.segments){let o=r.children.get(a);o||(o={children:new Map},r.children.set(a,o)),r=o;}r.operation=n;}return t}function V(e,t=1){let n=" ".repeat(t),r=" ".repeat(t+1),a=Array.from(e.children.entries()).sort(([i],[s])=>i.localeCompare(s));if(a.length===0)return e.operation?`${e.operation.alias}Route(runtime)`:"{}";let o=["{"];for(let[i,s]of a)o.push(`${r}${Pn(i)}: ${V(s,t+1)},`);return e.operation&&(o.push(`${r}run: ${e.operation.alias}Route(runtime).run,`),o.push(`${r}schema: ${e.operation.alias}Route(runtime).schema,`),e.operation.kind==="query"&&o.push(`${r}subscribe: ${e.operation.alias}Route(runtime).subscribe,`)),o.push(`${n}}`),o.join(`
|
|
168
|
+
`)}function Dn(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=Mn(`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:`${re(e.kind)}${re(n.join("_"))}`}}function En(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 = (
|
|
169
169
|
runtime: RequestRuntime,
|
|
170
170
|
): AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}> => {
|
|
171
171
|
const run: AppflareQueryRouteClient<typeof ${e.schemaConst}, ${n}>["run"] = async (
|
|
@@ -357,7 +357,7 @@ export type ${c} = z.input<typeof ${u.schemaConst}>;
|
|
|
357
357
|
export type ${f} = Awaited<ReturnType<typeof ${u.alias}.definition.handler>>;
|
|
358
358
|
export const ${d} = ${u.schemaConst};`}).join(`
|
|
359
359
|
|
|
360
|
-
`),i=t.map(u=>
|
|
360
|
+
`),i=t.map(u=>En(u)).join(`
|
|
361
361
|
|
|
362
362
|
`),s=V(ae(n)),l=V(ae(r));return `import betterFetch from "better-fetch";
|
|
363
363
|
import { z } from "zod";
|
|
@@ -1354,10 +1354,10 @@ function createStorageApi(
|
|
|
1354
1354
|
};
|
|
1355
1355
|
}
|
|
1356
1356
|
`}function he(e){return `
|
|
1357
|
-
export function createSchedulerExecutionContext(
|
|
1357
|
+
export async function createSchedulerExecutionContext(
|
|
1358
1358
|
env: Record<string, unknown>,
|
|
1359
1359
|
options: RegisterHandlersOptions,
|
|
1360
|
-
): AppflareContext {
|
|
1360
|
+
): Promise<AppflareContext> {
|
|
1361
1361
|
const database = env[options.databaseBinding] as D1Database;
|
|
1362
1362
|
const r2Binding = options.r2Binding ?? ${JSON.stringify(e??"")};
|
|
1363
1363
|
const storageBucket = r2Binding
|
|
@@ -1365,9 +1365,20 @@ export function createSchedulerExecutionContext(
|
|
|
1365
1365
|
: undefined;
|
|
1366
1366
|
const db = createDb(database);
|
|
1367
1367
|
const mutationEvents = [] as AppflareContext["mutationEvents"];
|
|
1368
|
+
const kvNamespace = options.kvBinding
|
|
1369
|
+
? (env[options.kvBinding] as KVNamespace)
|
|
1370
|
+
: undefined;
|
|
1368
1371
|
const schedulerBinding = options.schedulerBinding ?? "APPFLARE_SCHEDULER_QUEUE";
|
|
1369
1372
|
const schedulerQueue = env[schedulerBinding] as SchedulerQueueBinding | undefined;
|
|
1370
1373
|
const helpers = createContextErrorHelpers();
|
|
1374
|
+
const auth = createAuth({
|
|
1375
|
+
DATABASE: database,
|
|
1376
|
+
KV: kvNamespace,
|
|
1377
|
+
});
|
|
1378
|
+
const authAdapter = (await auth.$context).internalAdapter;
|
|
1379
|
+
const schedulerContext = {
|
|
1380
|
+
env: env as WorkerEnv["Bindings"],
|
|
1381
|
+
} as unknown as Context<WorkerEnv>;
|
|
1371
1382
|
const ctx = {
|
|
1372
1383
|
$db: db,
|
|
1373
1384
|
db: createQueryDb(db, {
|
|
@@ -1378,7 +1389,8 @@ export function createSchedulerExecutionContext(
|
|
|
1378
1389
|
mutationEvents,
|
|
1379
1390
|
user: null as never,
|
|
1380
1391
|
session: null as never,
|
|
1381
|
-
|
|
1392
|
+
auth: authAdapter,
|
|
1393
|
+
context: schedulerContext,
|
|
1382
1394
|
scheduler: createScheduler(schedulerQueue),
|
|
1383
1395
|
storage: null as never,
|
|
1384
1396
|
...helpers,
|
|
@@ -1411,6 +1423,14 @@ export async function createExecutionContext(
|
|
|
1411
1423
|
const schedulerBinding = options.schedulerBinding ?? "APPFLARE_SCHEDULER_QUEUE";
|
|
1412
1424
|
const schedulerQueue = c.env[schedulerBinding] as SchedulerQueueBinding | undefined;
|
|
1413
1425
|
const helpers = createContextErrorHelpers();
|
|
1426
|
+
const auth = createAuth(
|
|
1427
|
+
{
|
|
1428
|
+
DATABASE: database,
|
|
1429
|
+
KV: kvNamespace,
|
|
1430
|
+
},
|
|
1431
|
+
c.req.raw.cf as IncomingRequestCfProperties | undefined,
|
|
1432
|
+
);
|
|
1433
|
+
const authAdapter = (await auth.$context).internalAdapter;
|
|
1414
1434
|
const ctx = {
|
|
1415
1435
|
$db: db,
|
|
1416
1436
|
db: createQueryDb(db, {
|
|
@@ -1421,6 +1441,7 @@ export async function createExecutionContext(
|
|
|
1421
1441
|
mutationEvents,
|
|
1422
1442
|
user,
|
|
1423
1443
|
session,
|
|
1444
|
+
auth: authAdapter,
|
|
1424
1445
|
context: c,
|
|
1425
1446
|
scheduler: createScheduler(schedulerQueue),
|
|
1426
1447
|
storage: null as never,
|
|
@@ -4290,9 +4311,10 @@ type TableInsertModel<TName extends TableName> = InferInsertModel<
|
|
|
4290
4311
|
);
|
|
4291
4312
|
return rows;
|
|
4292
4313
|
},
|
|
4293
|
-
`}function
|
|
4314
|
+
`}function Ce(){return [qe(),$e(),Ie(),Ae(),Ne()].join(`
|
|
4294
4315
|
|
|
4295
|
-
`)}function
|
|
4316
|
+
`)}function Me(){return `type AuthSession = typeof auth.$Infer.Session;
|
|
4317
|
+
type AuthAdapter = Awaited<typeof auth.$context>["internalAdapter"];
|
|
4296
4318
|
type User = AuthSession['user']
|
|
4297
4319
|
type Session = AuthSession['session']
|
|
4298
4320
|
|
|
@@ -4348,6 +4370,7 @@ export type AppflareContext = {
|
|
|
4348
4370
|
mutationEvents: DbMutationEvent[];
|
|
4349
4371
|
user: User;
|
|
4350
4372
|
session: Session;
|
|
4373
|
+
auth: AuthAdapter;
|
|
4351
4374
|
context: Context<WorkerEnv>;
|
|
4352
4375
|
scheduler: Scheduler;
|
|
4353
4376
|
storage: AppflareStorage;
|
|
@@ -4485,9 +4508,9 @@ export function cron(definition: CronDefinition): RegisteredCron {
|
|
|
4485
4508
|
definition,
|
|
4486
4509
|
};
|
|
4487
4510
|
}
|
|
4488
|
-
`}function De(){return [xe(),Se(),
|
|
4511
|
+
`}function De(){return [xe(),Se(),Ce(),Me(),Pe()].join(`
|
|
4489
4512
|
|
|
4490
|
-
`)}function
|
|
4513
|
+
`)}function Ee(e){return `import type { Context } from "hono";
|
|
4491
4514
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
4492
4515
|
import { drizzle } from "drizzle-orm/d1";
|
|
4493
4516
|
import { z, type ZodRawShape } from "zod";
|
|
@@ -4495,7 +4518,7 @@ import * as authSchema from "./auth.schema";
|
|
|
4495
4518
|
import * as schema from "${e}";
|
|
4496
4519
|
|
|
4497
4520
|
${De()}
|
|
4498
|
-
`}function
|
|
4521
|
+
`}function Fn(e){let t=e.replace(/[^A-Za-z0-9_]/g,"_");return /^[0-9]/.test(t)?`_${t}`:t}function On(e,t){let n=e.routePath.replace(/^\//,"").replace(/\//g,"_");return Fn(`op_${t}_${n}`)}function jn(e){return e.map((t,n)=>({operation:t,index:n,alias:On(t,n)}))}function Vn(e){return e.map(({operation:t,alias:n})=>`import { ${t.exportName} as ${n} } from "${t.importPath}";`).join(`
|
|
4499
4522
|
`)}function Bn(e){return e.filter(({operation:t})=>t.kind==="query"||t.kind==="mutation").map(({alias:t})=>`const ${`${t}Schema`} = z.object(${t}.definition.args);`).join(`
|
|
4500
4523
|
`)}function Hn(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(`
|
|
4501
4524
|
`)}function Wn(e){return e.filter(({operation:t})=>t.kind==="query").map(({operation:t,alias:n})=>{let r=`${n}Schema`;return `
|
|
@@ -4545,7 +4568,7 @@ ${De()}
|
|
|
4545
4568
|
},`}).join(`
|
|
4546
4569
|
`)}function Kn(e){return e.filter(({operation:t})=>t.kind==="storage").map(({alias:t})=>`
|
|
4547
4570
|
${t}.definition.handler,`).join(`
|
|
4548
|
-
`)}function
|
|
4571
|
+
`)}function Fe(e){let t=jn(e);return {imports:Vn(t),operationSchemas:Bn(t),schedulerSchemas:Hn(t),queryRoutes:Wn(t),mutationRoutes:Ln(t),queryRegistryEntries:zn(t),schedulerEntries:Un(t),schedulerPayloadMapEntries:Qn(t),cronEntries:_n(t),storageHandlersEntries:Kn(t)}}var Oe=`
|
|
4549
4572
|
function getRealtimeStub(
|
|
4550
4573
|
env: Record<string, unknown>,
|
|
4551
4574
|
options: RegisterHandlersOptions,
|
|
@@ -5784,7 +5807,7 @@ export async function executeScheduledBatch(
|
|
|
5784
5807
|
return;
|
|
5785
5808
|
}
|
|
5786
5809
|
|
|
5787
|
-
const ctx = createSchedulerExecutionContext(env, options);
|
|
5810
|
+
const ctx = await createSchedulerExecutionContext(env, options);
|
|
5788
5811
|
|
|
5789
5812
|
for (const message of batch.messages) {
|
|
5790
5813
|
const body = (message?.body ?? {}) as QueueMessageBody;
|
|
@@ -5835,7 +5858,7 @@ export async function executeCronTriggers(
|
|
|
5835
5858
|
return;
|
|
5836
5859
|
}
|
|
5837
5860
|
|
|
5838
|
-
const ctx = createSchedulerExecutionContext(env, options);
|
|
5861
|
+
const ctx = await createSchedulerExecutionContext(env, options);
|
|
5839
5862
|
|
|
5840
5863
|
for (const cronEntry of cronHandlers) {
|
|
5841
5864
|
if (!cronEntry.cronTriggers.includes(cronValue)) {
|
|
@@ -5849,7 +5872,7 @@ export async function executeCronTriggers(
|
|
|
5849
5872
|
}
|
|
5850
5873
|
}
|
|
5851
5874
|
}
|
|
5852
|
-
`;function _e(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:l,cronEntries:u,storageHandlersEntries:c}=
|
|
5875
|
+
`;function _e(e){let{imports:t,operationSchemas:n,schedulerSchemas:r,queryRoutes:a,mutationRoutes:o,queryRegistryEntries:i,schedulerEntries:s,schedulerPayloadMapEntries:l,cronEntries:u,storageHandlersEntries:c}=Fe(e);return `import { sValidator } from "@hono/standard-validator";
|
|
5853
5876
|
import type { Hono } from "hono";
|
|
5854
5877
|
import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@cloudflare/workers-types";
|
|
5855
5878
|
import { ZodError, z } from "zod";
|
|
@@ -5916,7 +5939,7 @@ export function registerGeneratedHandlers(
|
|
|
5916
5939
|
${ze}
|
|
5917
5940
|
|
|
5918
5941
|
${Qe}
|
|
5919
|
-
`}function H(e,t,n){let r=
|
|
5942
|
+
`}function H(e,t,n){let r=Ee(e),a=be(n),o=we(),i=_e(t);return [{relativePath:"handlers.ts",source:r},{relativePath:"handlers.context.ts",source:a},{relativePath:"handlers.execution.ts",source:o},{relativePath:"handlers.routes.ts",source:i}]}function Gn(e){return e?`,
|
|
5920
5943
|
KV: c.env["${e}"] as KVNamespace`:""}function Ke(e,t){return `{
|
|
5921
5944
|
DATABASE: c.env["${e}"] as D1Database${Gn(t)}
|
|
5922
5945
|
}`}function Ge(e,t,n){return `app.on(["GET", "POST"], "${e}/*", async (c) => {
|
|
@@ -6249,7 +6272,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6249
6272
|
\` : 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>\`}
|
|
6250
6273
|
</div>
|
|
6251
6274
|
\` : ''}
|
|
6252
|
-
</div>`}function
|
|
6275
|
+
</div>`}function C(e,t="Search term or filter..."){return `
|
|
6253
6276
|
<div class="form-control w-full md:w-auto relative">
|
|
6254
6277
|
<iconify-icon icon="mdi:magnify" width="18" height="18" class="absolute left-3 top-1/2 -translate-y-1/2 opacity-40"></iconify-icon>
|
|
6255
6278
|
<input type="text"
|
|
@@ -6260,7 +6283,7 @@ import type { D1Database, IncomingRequestCfProperties, KVNamespace } from "@clou
|
|
|
6260
6283
|
hx-trigger="keyup changed delay:500ms, search"
|
|
6261
6284
|
hx-target="#main-content"
|
|
6262
6285
|
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" />
|
|
6263
|
-
</div>`}function bt(e,t,n,r,a,o,i,s,l,u){let c=I(`/admin/table/${e.exportName}`),f=
|
|
6286
|
+
</div>`}function bt(e,t,n,r,a,o,i,s,l,u){let c=I(`/admin/table/${e.exportName}`),f=C(`/admin/table/${e.exportName}`,"Search term or filter..."),d=r?`<th class="w-10"><input id="select-all-${e.exportName}" type="checkbox" class="checkbox checkbox-xs" /></th>`:'<th class="w-10"><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></th>',y=r?`<td><input type="checkbox" class="checkbox checkbox-xs row-select-checkbox" value="\${String((row as any).${n} ?? '')}" /></td>`:'<td><input type="checkbox" class="checkbox checkbox-xs opacity-30" disabled /></td>',w=r?`
|
|
6264
6287
|
<div id="bulk-delete-bar-${e.exportName}" class="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 hidden">
|
|
6265
6288
|
<div class="bg-base-100 border border-base-200 rounded-xl shadow-lg px-3 py-2 flex items-center gap-3">
|
|
6266
6289
|
<div class="text-xs text-base-content/70">
|
|
@@ -6793,7 +6816,7 @@ ${vt()}
|
|
|
6793
6816
|
<iconify-icon icon="mdi:refresh" width="14" height="14"></iconify-icon>
|
|
6794
6817
|
</button>
|
|
6795
6818
|
</div>
|
|
6796
|
-
${
|
|
6819
|
+
${C("/admin/users","Search users...")}
|
|
6797
6820
|
</div>
|
|
6798
6821
|
\${tableHtml}
|
|
6799
6822
|
</div>
|
|
@@ -7776,7 +7799,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
7776
7799
|
_rtEnabled = false;
|
|
7777
7800
|
});
|
|
7778
7801
|
</script>
|
|
7779
|
-
`}function
|
|
7802
|
+
`}function Ct(e){return `
|
|
7780
7803
|
const content = html\`
|
|
7781
7804
|
<div class="flex flex-col gap-6 max-w-5xl mx-auto" id="main-content">
|
|
7782
7805
|
${Nt(e)}
|
|
@@ -7800,9 +7823,9 @@ ${Q()}`}function Nt(e){return `
|
|
|
7800
7823
|
return c.html(Layout({
|
|
7801
7824
|
title: "${e.exportName} - Functions",
|
|
7802
7825
|
children: content
|
|
7803
|
-
}));`}function
|
|
7826
|
+
}));`}function Mt(e){return e.map(n=>n.kind!=="query"&&n.kind!=="mutation"?"":`
|
|
7804
7827
|
adminApp.get('/functions${n.routePath}', (c) => {
|
|
7805
|
-
${
|
|
7828
|
+
${Ct(n)}
|
|
7806
7829
|
});`).join(`
|
|
7807
7830
|
`)}function Pt(){return `
|
|
7808
7831
|
const getStorageBucket = (c: any): R2Bucket | null => {
|
|
@@ -8000,7 +8023,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8000
8023
|
</div>
|
|
8001
8024
|
\`;
|
|
8002
8025
|
};
|
|
8003
|
-
`}function
|
|
8026
|
+
`}function Et(){return `
|
|
8004
8027
|
const handleStorageListRoute = async (c: any) => {
|
|
8005
8028
|
const bucket = getStorageBucket(c);
|
|
8006
8029
|
if (!bucket) {
|
|
@@ -8022,7 +8045,7 @@ ${Q()}`}function Nt(e){return `
|
|
|
8022
8045
|
|
|
8023
8046
|
adminApp.get('/storage', handleStorageListRoute);
|
|
8024
8047
|
adminApp.get('/storage/*', handleStorageListRoute);
|
|
8025
|
-
`}function
|
|
8048
|
+
`}function Ft(){return `
|
|
8026
8049
|
adminApp.post('/storage/upload', async (c) => {
|
|
8027
8050
|
const bucket = getStorageBucket(c);
|
|
8028
8051
|
if (!bucket) return c.text("Storage not configured", 400);
|
|
@@ -8124,13 +8147,13 @@ ${Q()}`}function Nt(e){return `
|
|
|
8124
8147
|
|
|
8125
8148
|
${Bt()}
|
|
8126
8149
|
|
|
8127
|
-
${
|
|
8150
|
+
${Ft()}
|
|
8128
8151
|
|
|
8129
8152
|
${Ot()}
|
|
8130
8153
|
|
|
8131
8154
|
${jt()}
|
|
8132
8155
|
|
|
8133
|
-
${
|
|
8156
|
+
${Et()}
|
|
8134
8157
|
`}function Wt(){return `
|
|
8135
8158
|
${Pt()}
|
|
8136
8159
|
|
|
@@ -8588,7 +8611,7 @@ function Layout(props: { children: any; title: string; hideSidebar?: boolean })
|
|
|
8588
8611
|
\`
|
|
8589
8612
|
}));
|
|
8590
8613
|
});
|
|
8591
|
-
`}function Qt(e,t,n){let r=it(t),a=st(r),o=ct(r),i=At(t),s=
|
|
8614
|
+
`}function Qt(e,t,n){let r=it(t),a=st(r),o=ct(r),i=At(t),s=Mt(n),l=Wt(),u=Lt(a,n),c=zt(),f=Ut(o);return `import { Hono } from "hono";
|
|
8592
8615
|
import { html, raw } from "hono/html";
|
|
8593
8616
|
import { drizzle } from "drizzle-orm/d1";
|
|
8594
8617
|
import { eq, desc, asc, sql, like, or, inArray } from "drizzle-orm";
|
|
@@ -8617,7 +8640,7 @@ ${f}
|
|
|
8617
8640
|
app.route('/admin', adminApp);
|
|
8618
8641
|
app.get('/admin/', (c) => c.redirect('/admin'));
|
|
8619
8642
|
}
|
|
8620
|
-
`}function _(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"}function
|
|
8643
|
+
`}function _(e){if(typeof e!="object"||e===null)return false;let t=e;return t.kind==="schema"&&typeof t.tables=="object"}function M(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function D(e){return e.replace(/[_-]+/g," ").replace(/\s+(.)/g,(t,n)=>n.toUpperCase()).replace(/\s/g,"").replace(/^(.)/,(t,n)=>n.toUpperCase())}function J(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 cr(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 ur(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 P(e,t,n){let r=e.tables[t];return r?r.columns[n]?.type:void 0}function _t(e,t,n,r,a,o,i){let s=t.columns[n];if(s){if(s.references&&(s.references.table!==r||s.references.column!==a))throw new Error(`Inferred relation '${e}.${n}' conflicts with explicit references(${s.references.table}.${s.references.column}).`);t.columns[n]={...s,notNull:s.notNull??(s.nullable===true?false:o.notNull),nullable:s.nullable??(o.notNull===false?true:void 0),references:{table:r,column:a,onDelete:s.references?.onDelete??o.onDelete,onUpdate:s.references?.onUpdate??o.onUpdate}};return}t.columns[n]={kind:"column",type:o.fkType??i,sqlName:o.sqlName,notNull:o.notNull??true,nullable:o.notNull===false?true:void 0,references:{table:r,column:a,onDelete:o.onDelete,onUpdate:o.onUpdate}};}function Kt(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 Gt(e,t){return `${e}:${t}`}function dr(e,t,n,r){let a=Gt(e,t),o=Gt(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 pr(e,t){return `${e}${D(t)}Links`}function Jt(e,t,n){let r=J(e),a=J(t);return r===a?`${n}${D(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 gr(e){let t=new Map;for(let[n,r]of Object.entries(e.tables))for(let a of Object.values(r.relations)){if(a.relation!=="manyToMany")continue;let o=a.referenceField??"id",i=a.targetReferenceField??"id",s=dr(n,o,a.targetTable,i),l=Jt(s.leftTable,s.rightTable,"source"),u=Jt(s.rightTable,s.leftTable,"target"),c={leftTable:s.leftTable,leftReferenceField:s.leftReferenceField,rightTable:s.rightTable,rightReferenceField:s.rightReferenceField,junctionTable:a.junctionTable??pr(s.leftTable,s.rightTable),leftField:s.sourceIsLeft?a.sourceField??l:a.targetField??l,rightField:s.sourceIsLeft?a.targetField??u:a.sourceField??u,leftSqlName:s.sourceIsLeft?a.sourceSqlName:a.targetSqlName,rightSqlName:s.sourceIsLeft?a.targetSqlName:a.sourceSqlName,onDelete:a.onDelete,onUpdate:a.onUpdate};if(c.leftField===c.rightField)throw new Error(`manyToMany pair '${s.key}' resolves to duplicate junction fields '${c.leftField}'. Set sourceField/targetField explicitly.`);let f=t.get(s.key);f?mr(f,c,s.key):t.set(s.key,c),a.referenceField=o,a.targetReferenceField=i,a.junctionTable=c.junctionTable,a.sourceField=s.sourceIsLeft?c.leftField:c.rightField,a.targetField=s.sourceIsLeft?c.rightField:c.leftField,a.sourceSqlName=s.sourceIsLeft?c.leftSqlName:c.rightSqlName,a.targetSqlName=s.sourceIsLeft?c.rightSqlName:c.leftSqlName;}for(let n of t.values()){if(n.junctionTable in e.tables)throw new Error(`manyToMany auto junction table '${n.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`);let r=P(e,n.leftTable,n.leftReferenceField)??"string",a=P(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 hr(e){fr(e);let t=ur(e);for(let[n,r]of Object.entries(t.tables))for(let[a,o]of Object.entries(r.relations)){if(o.relation!=="one")continue;let i=o.referenceField??"id",s=o.field??`${a}Id`;o.field=s;let l=P(t,o.targetTable,i)??o.fkType??"string";_t(n,r,s,o.targetTable,i,{fkType:o.fkType,sqlName:o.sqlName,notNull:Kt(`${n}.${a}`,o,true),onDelete:o.onDelete,onUpdate:o.onUpdate},l);}for(let[n,r]of Object.entries(t.tables))for(let a of Object.values(r.relations)){if(a.relation!=="many")continue;let o=t.tables[a.targetTable];if(!o)continue;let i=a.referenceField??"id",s=a.field??`${J(n)}Id`;a.field=s;let l=P(t,n,i)??a.fkType??"string";_t(a.targetTable,o,s,n,i,{fkType:a.fkType,sqlName:a.sqlName,notNull:Kt(`${n}.${a.targetTable}`,a,true),onDelete:a.onDelete,onUpdate:a.onUpdate},l);}return gr(t),t}function Yt(e){return e.primaryKey===true||e.notNull!==true||e.autoIncrement===true||e.sqlDefault!==void 0||e.runtimeDefaultFn!==void 0}function $(e){return e.notNull!==true}function br(e,t,n){let r=t.sqlName??M(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 yr(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 wr(e){return e.size===0?"":`import { ${Array.from(e).sort().join(", ")} } from "./auth.schema";
|
|
8621
8644
|
`}function xr(e){return Object.values(e.relations).filter(t=>t.relation==="one").map(t=>t.targetTable)}function vr(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 Tr(e){let t=[];for(let[n,r]of Object.entries(e.tables)){let a=[];for(let[o,i]of Object.entries(r.relations))i.relation==="manyToMany"&&i.junctionTable&&a.push(`${h(o)}: {
|
|
8622
8645
|
targetTable: ${h(i.targetTable)},
|
|
8623
8646
|
junctionTable: ${h(i.junctionTable)},
|
|
@@ -8657,7 +8680,7 @@ ${a.map(o=>` ${o}`).join(`
|
|
|
8657
8680
|
${t.map(n=>` ${n}`).join(`
|
|
8658
8681
|
`)}
|
|
8659
8682
|
} as const;
|
|
8660
|
-
`}function kr(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let i of Object.values(e.tables)){for(let s of xr(i))n.has(s)||r.add(s);for(let s of Object.values(i.columns))s.references&&!n.has(s.references.table)&&r.add(s.references.table);}let a=[],o=[];for(let[i,s]of Object.entries(e.tables)){let l=s.sqlName??
|
|
8683
|
+
`}function kr(e,t){let n=new Set(Object.keys(e.tables)),r=new Set;for(let i of Object.values(e.tables)){for(let s of xr(i))n.has(s)||r.add(s);for(let s of Object.values(i.columns))s.references&&!n.has(s.references.table)&&r.add(s.references.table);}let a=[],o=[];for(let[i,s]of Object.entries(e.tables)){let l=s.sqlName??M(i),u=[],c=[];for(let[b,m]of Object.entries(s.columns)){let x=br(b,m,t);m.uuidPrimaryKey&&(x+=".$defaultFn(() => crypto.randomUUID())"),m.primaryKey&&(x+=m.autoIncrement?".primaryKey({ autoIncrement: true })":".primaryKey()"),m.notNull&&(x+=".notNull()"),m.sqlDefault!==void 0&&(x+=`.default(${cr(m.sqlDefault)})`);let v=vr(b,m,s);if(v)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)}`),x+=`.references(() => ${v.tableName}.${v.fieldName}, { ${R.join(", ")} })`;}else x+=`.references(() => ${v.tableName}.${v.fieldName})`;if(m.unique){let R=typeof m.unique=="object"&&m.unique.name?m.unique.name:`${l}_${M(b)}_unique_idx`;c.push(` t.uniqueIndex(${h(R)}).on(table.${b})`);}if(m.index){let R=typeof m.index=="object"&&m.index.name?m.index.name:`${l}_${M(b)}_idx`;c.push(` t.index(${h(R)}).on(table.${b})`);}u.push(` ${b}: ${x},`);}c.length>0?a.push(`export const ${i} = table(
|
|
8661
8684
|
${h(l)},
|
|
8662
8685
|
{
|
|
8663
8686
|
${u.join(`
|
|
@@ -8716,11 +8739,11 @@ ${i.join(`
|
|
|
8716
8739
|
};`);}return `${t.join(`
|
|
8717
8740
|
|
|
8718
8741
|
`)}
|
|
8719
|
-
`}function $r(e,t){if(t){let n=e[t];if(!_(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(_(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function Xt(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=resolve(e.configDir,t.entry),a=resolve(e.configDir,t.outFile??resolve(e.outDirAbs,"schema.compiled.ts")),o=resolve(e.configDir,t.typesOutFile??resolve(e.outDirAbs,"schema.types.ts")),i=resolve(e.configDir,t.zodOutFile??resolve(e.outDirAbs,"schema.zod.ts")),l=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),u=$r(l,t.exportName),c=hr(u);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(dirname(i),{recursive:true})]);let f=kr(c,n),d=Nr(c),y=Sr(c);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function Ir(e){return e.replaceAll("\\","/")}function A(e,t){let n=Ir(relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Dr=new Set([".ts",".tsx",".mts",".cts"]);async function rn(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await rn(a));continue}r.isFile()&&Dr.has(extname(r.name))&&n.push(a);}return n}function Z(e){return e.replace(/\.[cm]?tsx?$/,"")}function Fr(e,t){let n=e,r=false,a,o="unknown";for(;g.isCallExpression(n);){let i=n.expression;if(!g.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,n=i.expression;else if(s==="default"){r=true;let l=n.arguments[0];l&&(g.isStringLiteral(l)||g.isNumericLiteral(l)?a=l.text:l.kind===g.SyntaxKind.TrueKeyword?a="true":l.kind===g.SyntaxKind.FalseKeyword&&(a="false")),n=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else n=i.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function Er(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g.isPropertyAssignment(r)&&g.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)||n.push(Fr(r.initializer,r.name.text));return n}function Or(e){return g.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g.SyntaxKind.ExportKeyword)??false:false}function an(e){return g.isIdentifier(e)?e.text:g.isParenthesizedExpression(e)?an(e.expression):null}function jr(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g.isPropertyAssignment(t))return [];let n=t.initializer;return g.isStringLiteral(n)||g.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g.isArrayLiteralExpression(n)?n.elements.map(r=>g.isStringLiteral(r)||g.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Vr(e,t){let n=g.createSourceFile(t,e,g.ScriptTarget.Latest,true,g.ScriptKind.TS),r=[];for(let a of n.statements)if(Or(a))for(let o of a.declarationList.declarations){if(!g.isIdentifier(o.name)||!o.initializer||!g.isCallExpression(o.initializer))continue;let i=an(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?jr(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?Er(o.initializer.arguments[0]):[]});}return r}function en(e,t,n){let r=t.replace(/\\/g,"/"),o=Z(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Br(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 tn(e,t){let n=e.replace(/\\/g,"/"),a=Z(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function on(e){let t=[],n=await rn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=relative(e.scanDirAbs,a),l=Vr(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=Br(s,c.kindDirectory);for(let d of c.exports){let y=c.kind==="query"||c.kind==="mutation"?tn(f,d.exportName):void 0,w=c.kind==="scheduler"||c.kind==="cron"?tn(f,d.exportName):void 0,b=c.kind==="query"||c.kind==="mutation"?[...Z(f).split("/").filter(Boolean),d.exportName]:void 0,m=c.kind==="query"?en("queries",f,d.exportName):c.kind==="mutation"?en("mutations",f,d.exportName):c.kind==="storage"?`/storage/managers/${d.exportName}`:`/${c.kindDirectory}/${w}`;t.push({kind:c.kind,exportName:d.exportName,filePath:a,importPath:A(e.outDirAbs,a),clientImportPath:A(resolve(e.outDirAbs,"client"),a),routePath:m,handlerName:y,clientSegments:b,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 Wr(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 y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let c=n.trim();return c.length>0&&t.push(c),t}function Lr(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 zr(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 Ur(e){let t=Wr(e),n=[];for(let r of t){let a=Lr(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:zr(i),optional:f,primaryKey:s,autoIncrement:l});}return n}function Qr(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 y=o[d];if(f){f=false;continue}if(y==="\\"){f=true;continue}if(!u&&!c&&y==="'"){l=!l;continue}if(!l&&!c&&y==='"'){u=!u;continue}if(!l&&!u&&y==="`"){c=!c;continue}if(!(l||u||c)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let 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:Ur(u)}),a=t.exec(e);}return n}async function ln(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await ln(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function cn(e,t=[]){let n=await ln(e.scanDirAbs).catch(()=>[]),r=resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),l=Qr(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 _r(e,t){let n=relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function un(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=A(t,a),s=resolve(t,"client"),l=A(s,a);await Promise.all([mkdir(t,{recursive:true}),mkdir(s,{recursive:true}),mkdir(n,{recursive:true})]);let u=resolve(t,"server.ts"),c=resolve(t,"client.ts"),f=resolve(t,"auth.config.ts"),d=resolve(t,"auth.schema.ts"),y=resolve(t,"drizzle.config.ts"),w=resolve(n,"wrangler.json"),b=await Xt(e),m=await cn(e,b?[b.schemaPath]:[]),x=A(t,m.schemaPath),v=await on(e),R=rt(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),xn=le(l,v),vn=H(x,v,r.r2[0]?.binding),Tn=te(i),Rn=b?[_r(o,b.schemaPath),...r.schema.filter(k=>!/(^|\/)schema\.ts$/.test(k))]:r.schema,kn=ce(Rn),Sn=ot(e,v),An=Qt(x,m,v),Nn=resolve(t,"admin.routes.ts"),$n=vn.map(k=>Bun.write(resolve(t,k.relativePath),k.source)),qn=xn.map(k=>Bun.write(resolve(t,k.relativePath),k.source));await Promise.all([Bun.write(u,R),Bun.write(c,`export * from "./client/index";
|
|
8742
|
+
`}function $r(e,t){if(t){let n=e[t];if(!_(n))throw new Error(`schemaDsl.exportName '${t}' does not point to a schema() export.`);return n}for(let n of Object.values(e))if(_(n))return n;throw new Error("No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.")}async function Xt(e){let t=e.config.schemaDsl;if(!t)return;let n=t.namingStrategy??"camelToSnake",r=resolve(e.configDir,t.entry),a=resolve(e.configDir,t.outFile??resolve(e.outDirAbs,"schema.compiled.ts")),o=resolve(e.configDir,t.typesOutFile??resolve(e.outDirAbs,"schema.types.ts")),i=resolve(e.configDir,t.zodOutFile??resolve(e.outDirAbs,"schema.zod.ts")),l=await import(`${pathToFileURL(r).href}?t=${Date.now()}`),u=$r(l,t.exportName),c=hr(u);await Promise.all([mkdir(dirname(a),{recursive:true}),mkdir(dirname(o),{recursive:true}),mkdir(dirname(i),{recursive:true})]);let f=kr(c,n),d=Nr(c),y=Sr(c);return await Promise.all([Bun.write(a,f),Bun.write(o,d),Bun.write(i,y)]),{schemaPath:a,typesPath:o,zodPath:i,tableNames:Object.keys(c.tables)}}function Ir(e){return e.replaceAll("\\","/")}function A(e,t){let n=Ir(relative(e,t)).replace(/\.tsx?$/,"");return n.startsWith(".")?n:`./${n}`}var Dr=new Set([".ts",".tsx",".mts",".cts"]);async function rn(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await rn(a));continue}r.isFile()&&Dr.has(extname(r.name))&&n.push(a);}return n}function Z(e){return e.replace(/\.[cm]?tsx?$/,"")}function Er(e,t){let n=e,r=false,a,o="unknown";for(;g.isCallExpression(n);){let i=n.expression;if(!g.isPropertyAccessExpression(i))break;let s=i.name.text;if(s==="optional"||s==="nullable")r=true,n=i.expression;else if(s==="default"){r=true;let l=n.arguments[0];l&&(g.isStringLiteral(l)||g.isNumericLiteral(l)?a=l.text:l.kind===g.SyntaxKind.TrueKeyword?a="true":l.kind===g.SyntaxKind.FalseKeyword&&(a="false")),n=i.expression;}else if(s==="string"||s==="uuid"||s==="email"||s==="url"){o="string";break}else if(s==="number"||s==="int"||s==="float"){o="number";break}else if(s==="boolean"){o="boolean";break}else n=i.expression;}return {name:t,type:o,optional:r,defaultValue:a}}function Fr(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>g.isPropertyAssignment(r)&&g.isIdentifier(r.name)&&r.name.text==="args");if(!t||!g.isObjectLiteralExpression(t.initializer))return [];let n=[];for(let r of t.initializer.properties)!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)||n.push(Er(r.initializer,r.name.text));return n}function Or(e){return g.isVariableStatement(e)?e.modifiers?.some(t=>t.kind===g.SyntaxKind.ExportKeyword)??false:false}function an(e){return g.isIdentifier(e)?e.text:g.isParenthesizedExpression(e)?an(e.expression):null}function jr(e){if(!e||!g.isObjectLiteralExpression(e))return [];let t=e.properties.find(r=>!g.isPropertyAssignment(r)||!g.isIdentifier(r.name)?false:r.name.text==="cronTrigger");if(!t||!g.isPropertyAssignment(t))return [];let n=t.initializer;return g.isStringLiteral(n)||g.isNoSubstitutionTemplateLiteral(n)?[n.text.trim()].filter(r=>r.length>0):g.isArrayLiteralExpression(n)?n.elements.map(r=>g.isStringLiteral(r)||g.isNoSubstitutionTemplateLiteral(r)?r.text.trim():"").filter(r=>r.length>0):[]}function Vr(e,t){let n=g.createSourceFile(t,e,g.ScriptTarget.Latest,true,g.ScriptKind.TS),r=[];for(let a of n.statements)if(Or(a))for(let o of a.declarationList.declarations){if(!g.isIdentifier(o.name)||!o.initializer||!g.isCallExpression(o.initializer))continue;let i=an(o.initializer.expression);i!=="query"&&i!=="mutation"&&i!=="scheduler"&&i!=="cron"&&i!=="storageManager"||r.push({exportName:o.name.text,kind:i==="storageManager"?"storage":i,cronTriggers:i==="cron"?jr(o.initializer.arguments[0]):[],args:i==="query"||i==="mutation"?Fr(o.initializer.arguments[0]):[]});}return r}function en(e,t,n){let r=t.replace(/\\/g,"/"),o=Z(r).split("/").filter(Boolean);return `/${[e,...o,n].filter(Boolean).map(s=>s.trim()).filter(s=>s.length>0).join("/")}`}function Br(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 tn(e,t){let n=e.replace(/\\/g,"/"),a=Z(n).split("/").filter(Boolean),o=a[a.length-1]??"index";return [a.length>1?a[a.length-2]:"root",o,t].map(s=>s.trim()).filter(s=>s.length>0).join("/")}async function on(e){let t=[],n=await rn(e.scanDirAbs).catch(()=>[]);for(let a of n){let o=Bun.file(a);if(!await o.exists())continue;let i=await o.text(),s=relative(e.scanDirAbs,a),l=Vr(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=Br(s,c.kindDirectory);for(let d of c.exports){let y=c.kind==="query"||c.kind==="mutation"?tn(f,d.exportName):void 0,w=c.kind==="scheduler"||c.kind==="cron"?tn(f,d.exportName):void 0,b=c.kind==="query"||c.kind==="mutation"?[...Z(f).split("/").filter(Boolean),d.exportName]:void 0,m=c.kind==="query"?en("queries",f,d.exportName):c.kind==="mutation"?en("mutations",f,d.exportName):c.kind==="storage"?`/storage/managers/${d.exportName}`:`/${c.kindDirectory}/${w}`;t.push({kind:c.kind,exportName:d.exportName,filePath:a,importPath:A(e.outDirAbs,a),clientImportPath:A(resolve(e.outDirAbs,"client"),a),routePath:m,handlerName:y,clientSegments:b,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 Wr(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 y=n.trim();y.length>0&&t.push(y),n="";continue}n+=d;}let c=n.trim();return c.length>0&&t.push(c),t}function Lr(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 zr(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 Ur(e){let t=Wr(e),n=[];for(let r of t){let a=Lr(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:zr(i),optional:f,primaryKey:s,autoIncrement:l});}return n}function Qr(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 y=o[d];if(f){f=false;continue}if(y==="\\"){f=true;continue}if(!u&&!c&&y==="'"){l=!l;continue}if(!l&&!c&&y==='"'){u=!u;continue}if(!l&&!u&&y==="`"){c=!c;continue}if(!(l||u||c)){if(y==="{"){s+=1;continue}if(y==="}"&&(s-=1,s===0))return d}}return -1},a=t.exec(e);for(;a;){let o=a[1],i=a[2],s=e.indexOf("{",t.lastIndex);if(s===-1){a=t.exec(e);continue}let 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:Ur(u)}),a=t.exec(e);}return n}async function ln(e){let t=await readdir(e,{withFileTypes:true}),n=[];for(let r of t){if(r.name.startsWith(".")||r.name==="node_modules"||r.name==="_generated")continue;let a=resolve(e,r.name);if(r.isDirectory()){n.push(...await ln(a));continue}r.isFile()&&r.name==="schema.ts"&&n.push(a);}return n}async function cn(e,t=[]){let n=await ln(e.scanDirAbs).catch(()=>[]),r=resolve(e.configDir,"schema.ts"),a=[...t,...n.length?n:[r]];for(let o of a){let i=Bun.file(o);if(!await i.exists())continue;let s=await i.text(),l=Qr(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 _r(e,t){let n=relative(e,t).replace(/\\/g,"/");return n.startsWith(".")?n:`./${n}`}async function un(e){let{outDirAbs:t,wranglerOutDirAbs:n,config:r,configPath:a,configDir:o}=e,i=A(t,a),s=resolve(t,"client"),l=A(s,a);await Promise.all([mkdir(t,{recursive:true}),mkdir(s,{recursive:true}),mkdir(n,{recursive:true})]);let u=resolve(t,"server.ts"),c=resolve(t,"client.ts"),f=resolve(t,"auth.config.ts"),d=resolve(t,"auth.schema.ts"),y=resolve(t,"drizzle.config.ts"),w=resolve(n,"wrangler.json"),b=await Xt(e),m=await cn(e,b?[b.schemaPath]:[]),x=A(t,m.schemaPath),v=await on(e),R=rt(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),xn=le(l,v),vn=H(x,v,r.r2[0]?.binding),Tn=te(i),Rn=b?[_r(o,b.schemaPath),...r.schema.filter(k=>!/(^|\/)schema\.ts$/.test(k))]:r.schema,kn=ce(Rn),Sn=ot(e,v),An=Qt(x,m,v),Nn=resolve(t,"admin.routes.ts"),$n=vn.map(k=>Bun.write(resolve(t,k.relativePath),k.source)),qn=xn.map(k=>Bun.write(resolve(t,k.relativePath),k.source));await Promise.all([Bun.write(u,R),Bun.write(c,`export * from "./client/index";
|
|
8720
8743
|
`),...qn,...$n,Bun.write(f,Tn),Bun.write(d,""),Bun.write(y,kn),Bun.write(w,`${JSON.stringify(Sn,null,2)}
|
|
8721
|
-
`),Bun.write(Nn,An)]);let O=relative(o,f).replace(/\\/g,"/"),In=O.startsWith(".")?O:`./${O}`,j=relative(o,d).replace(/\\/g,"/"),
|
|
8744
|
+
`),Bun.write(Nn,An)]);let O=relative(o,f).replace(/\\/g,"/"),In=O.startsWith(".")?O:`./${O}`,j=relative(o,d).replace(/\\/g,"/"),Cn=j.startsWith(".")?j:`./${j}`,ee=await Bun.spawn(["npx","@better-auth/cli","generate","--config",In,"--output",Cn,"--yes"],{cwd:o,stdout:"inherit",stderr:"inherit"}).exited;if(ee!==0)throw new Error(`better-auth generation failed with exit code ${ee}`)}var dn=z$1.object({binding:z$1.string().min(1),databaseName:z$1.string().min(1),databaseId:z$1.string().min(1),previewDatabaseId:z$1.string().min(1).optional(),migrationsDir:z$1.string().min(1).optional()}).strict(),pn=z$1.object({binding:z$1.string().min(1),id:z$1.string().min(1),previewId:z$1.string().min(1).optional()}).strict(),mn=z$1.object({binding:z$1.string().min(1),bucketName:z$1.string().min(1),previewBucketName:z$1.string().min(1).optional(),jurisdiction:z$1.string().min(1).optional()}).strict(),gn=z$1.object({enabled:z$1.boolean().optional(),binding:z$1.string().min(1).optional(),queue:z$1.string().min(1).optional()}).strict(),Zr=z$1.object({enabled:z$1.boolean().optional(),binding:z$1.string().min(1).optional(),className:z$1.string().min(1).optional(),objectName:z$1.string().min(1).optional(),subscribePath:z$1.string().min(1).optional(),websocketPath:z$1.string().min(1).optional(),protocol:z$1.string().min(1).optional()}).strict(),Yr=z$1.object({scanDir:z$1.string().min(1),outDir:z$1.string().min(1),wranglerOutDir:z$1.string().min(1).optional(),wranglerOutPath:z$1.string().min(1).optional(),schema:z$1.array(z$1.string()).min(1),schemaDsl:z$1.object({entry:z$1.string().min(1),exportName:z$1.string().min(1).optional(),outFile:z$1.string().min(1).optional(),typesOutFile:z$1.string().min(1).optional(),zodOutFile:z$1.string().min(1).optional(),namingStrategy:z$1.literal("camelToSnake").optional()}).strict().optional(),database:z$1.union([dn,z$1.array(dn).min(1)]),kv:z$1.union([pn,z$1.array(pn)]).optional(),r2:z$1.union([mn,z$1.array(mn)]).optional(),auth:z$1.object({enabled:z$1.boolean(),basePath:z$1.string().min(1),options:z$1.custom(e=>typeof e=="object"&&e!==null),clientOptions:z$1.custom(e=>typeof e=="object"&&e!==null)}).strict(),scheduler:gn.optional(),realtime:Zr.optional(),wranglerOverrides:z$1.record(z$1.string(),z$1.unknown()).optional()}).strict();function fn(e){return typeof e=="object"&&e!==null}function Xr(e){let t=fn(e.wranglerOverrides)?e.wranglerOverrides.scheduler:void 0,n=gn.safeParse(t);return n.success?n.data:{}}function ea(e){if(!fn(e)||!("scheduler"in e))return e;let{scheduler:t,...n}=e;return n}function ta(e){let n={...Xr(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:ea(e.wranglerOverrides),wranglerOutDir:e.wranglerOutDir??e.wranglerOutPath??e.outDir}}async function q(e){let t=isAbsolute(e??"")?e:resolve(process.cwd(),e??"appflare.config.ts"),n=dirname(t),o=(await import(pathToFileURL(t).href)).default,i=Yr.parse(o),s=ta(i);return {configPath:t,configDir:n,scanDirAbs:resolve(n,s.scanDir),outDirAbs:resolve(n,s.outDir),wranglerOutDirAbs:resolve(n,s.wranglerOutDir),config:s}}function oa(e){let t=e;for(;;){if(existsSync(resolve(t,"package.json")))return t;let n=dirname(t);if(n===t)return e;t=n;}}async function F(e){let t=await q(e);if(await un(t),t.wranglerOutDirAbs===t.outDirAbs){process.stdout.write(`\u2705 Generated artifacts in ${t.outDirAbs}
|
|
8722
8745
|
`);return}process.stdout.write(`\u2705 Generated server/client in ${t.outDirAbs} and wrangler.json in ${t.wranglerOutDirAbs}
|
|
8723
|
-
`);}async function bn(e,t=false){if(await
|
|
8746
|
+
`);}async function bn(e,t=false){if(await F(e),!t)return;let n=await q(e),r=false,a=false,o=async()=>{if(r){a=true;return}r=true;try{await F(e);}catch(s){process.stderr.write(`\u274C Build failed: ${s.message}
|
|
8724
8747
|
`);}finally{r=false,a&&(a=false,await o());}};na.watch(n.scanDirAbs,{ignoreInitial:true}).on("all",async(s,l)=>{process.stdout.write(`\u{1F504} Change detected: ${l}
|
|
8725
8748
|
`),await o();}),process.stdout.write(`\u{1F440} Watching ${n.scanDirAbs}
|
|
8726
|
-
`);}async function yn(e,t={}){let n=await q(e),r=oa(process.cwd());if([!!t.local,!!t.remote,!!t.preview].filter(Boolean).length>1)throw new Error("Only one of --local, --remote, or --preview can be set.");let o=resolve(n.outDirAbs,"drizzle.config.ts"),i=process.platform==="win32"?"npx.cmd":"npx",l=await Bun.spawn([i,"drizzle-kit","generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(l!==0)throw new Error(`drizzle-kit generate failed with exit code ${l}`);let u=n.config.database[0].databaseName,c=[i,"wrangler","d1","migrations","apply",u];t.local?c.push("--local"):t.remote?c.push("--remote"):t.preview&&c.push("--preview");let d=await Bun.spawn(c,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(d!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${d}`)}async function wn(e,t={name:"",email:"",password:""}){let n=await q(e);if([!!t.local,!!t.remote].filter(Boolean).length>1)throw new Error("Only one of --local or --remote can be set.");let{hashPassword:a}=await import('better-auth/crypto'),o=await a(t.password),i=crypto.randomUUID(),s=crypto.randomUUID(),l=Date.now(),u=t.name.replace(/'/g,"''"),c=t.email.replace(/'/g,"''"),f=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${u}', '${c}', 1, ${l}, ${l}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${c}', 'credential', '${i}', '${o}', ${l}, ${l});`].join(" "),d=n.config.database[0].databaseName,w=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${f}`];t.local?w.push("--local"):t.remote&&w.push("--remote");let m=await Bun.spawn(w,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(m!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${m}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var N=new Command;N.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");N.command("build").description("Generate server.ts, client.ts, auth.config.ts, drizzle.config.ts, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").action(async e=>{await
|
|
8749
|
+
`);}async function yn(e,t={}){let n=await q(e),r=oa(process.cwd());if([!!t.local,!!t.remote,!!t.preview].filter(Boolean).length>1)throw new Error("Only one of --local, --remote, or --preview can be set.");let o=resolve(n.outDirAbs,"drizzle.config.ts"),i=process.platform==="win32"?"npx.cmd":"npx",l=await Bun.spawn([i,"drizzle-kit","generate","--config",o],{cwd:r,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(l!==0)throw new Error(`drizzle-kit generate failed with exit code ${l}`);let u=n.config.database[0].databaseName,c=[i,"wrangler","d1","migrations","apply",u];t.local?c.push("--local"):t.remote?c.push("--remote"):t.preview&&c.push("--preview");let d=await Bun.spawn(c,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(d!==0)throw new Error(`wrangler d1 migrations apply failed with exit code ${d}`)}async function wn(e,t={name:"",email:"",password:""}){let n=await q(e);if([!!t.local,!!t.remote].filter(Boolean).length>1)throw new Error("Only one of --local or --remote can be set.");let{hashPassword:a}=await import('better-auth/crypto'),o=await a(t.password),i=crypto.randomUUID(),s=crypto.randomUUID(),l=Date.now(),u=t.name.replace(/'/g,"''"),c=t.email.replace(/'/g,"''"),f=["INSERT INTO users (id, name, email, email_verified, created_at, updated_at, role, banned)",`VALUES ('${i}', '${u}', '${c}', 1, ${l}, ${l}, 'admin', 0);`,"INSERT INTO accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)",`VALUES ('${s}', '${c}', 'credential', '${i}', '${o}', ${l}, ${l});`].join(" "),d=n.config.database[0].databaseName,w=[process.platform==="win32"?"npx.cmd":"npx","wrangler","d1","execute",d,`--command=${f}`];t.local?w.push("--local"):t.remote&&w.push("--remote");let m=await Bun.spawn(w,{cwd:n.configDir,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited;if(m!==0)throw new Error(`Failed to add admin user. wrangler d1 execute exited with code ${m}`);console.log("\u2705 Admin user "+t.email+" created successfully!");}var N=new Command;N.name("appflare").description("Appflare compiler/bundler for Cloudflare-native backends and SDK generation").version("0.0.28");N.command("build").description("Generate server.ts, client.ts, auth.config.ts, drizzle.config.ts, and wrangler.json artifacts").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").action(async e=>{await F(e.config);});N.command("dev").description("Run generator in development mode").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("-w, --watch","Watch scanDir and regenerate on changes",false).action(async e=>{await bn(e.config,e.watch);});N.command("migrate").description("Generate drizzle migration files from outDir/auth.schema.ts and apply them to the configured D1 database").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute commands/files against a local DB for use with wrangler dev",false).option("--remote","Execute commands/files against a remote DB for use with wrangler dev --remote",false).option("--preview","Execute commands/files against a preview D1 DB",false).action(async e=>{await yn(e.config,{local:e.local,remote:e.remote,preview:e.preview});});N.command("add-admin").description("Add an admin user to the database").requiredOption("-n, --name <name>","Admin's display name").requiredOption("-e, --email <email>","Admin's email address").requiredOption("-p, --password <password>","Admin's password").option("-c, --config <path>","Path to appflare.config.ts","appflare.config.ts").option("--local","Execute command against a local DB for use with wrangler dev",false).option("--remote","Execute command against a remote DB for use with wrangler dev --remote",false).action(async e=>{await wn(e.config,{name:e.name,email:e.email,password:e.password,local:e.local,remote:e.remote});});(async()=>{process.versions.bun||(console.error("Appflare CLI must be run with Bun."),process.exit(1)),await N.parseAsync(process.argv);})().catch(e=>{console.error(e),process.exit(1);});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "appflare",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.19",
|
|
4
4
|
"main": "./dist/index.js",
|
|
5
5
|
"module": "./dist/index.mjs",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -40,9 +40,9 @@
|
|
|
40
40
|
"tsup": "^8.3.6"
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@better-auth/cli": "1.4.
|
|
43
|
+
"@better-auth/cli": "^1.4.21",
|
|
44
|
+
"better-auth": "^1.5.5",
|
|
44
45
|
"@hono/standard-validator": "0.2.2",
|
|
45
|
-
"better-auth": "1.4.18",
|
|
46
46
|
"better-auth-cloudflare": "0.2.9",
|
|
47
47
|
"better-fetch": "1.1.2",
|
|
48
48
|
"bun": "1.3.9",
|
|
@@ -51,8 +51,8 @@
|
|
|
51
51
|
"drizzle-kit": "0.31.9",
|
|
52
52
|
"drizzle-orm": "0.45.1",
|
|
53
53
|
"hono": "4.12.0",
|
|
54
|
+
"typescript": "^5.9.3",
|
|
54
55
|
"wrangler": "4.67.0",
|
|
55
|
-
"zod": "4.3.6"
|
|
56
|
-
"typescript": "^5.9.3"
|
|
56
|
+
"zod": "4.3.6"
|
|
57
57
|
}
|
|
58
58
|
}
|