appflare 0.0.28 → 0.1.0

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.
Files changed (141) hide show
  1. package/cli/commands/index.ts +140 -0
  2. package/cli/generate.ts +149 -0
  3. package/cli/index.ts +56 -447
  4. package/cli/load-config.ts +182 -0
  5. package/cli/schema-compiler.ts +657 -0
  6. package/cli/templates/auth/README.md +156 -0
  7. package/cli/templates/auth/config.ts +61 -0
  8. package/cli/templates/auth/route-config.ts +18 -0
  9. package/cli/templates/auth/route-handler.ts +18 -0
  10. package/cli/templates/auth/route-request-utils.ts +55 -0
  11. package/cli/templates/auth/route.ts +14 -0
  12. package/cli/templates/core/README.md +266 -0
  13. package/cli/templates/core/app-creation.ts +19 -0
  14. package/cli/templates/core/client/appflare.ts +37 -0
  15. package/cli/templates/core/client/index.ts +6 -0
  16. package/cli/templates/core/client/storage.ts +100 -0
  17. package/cli/templates/core/client/types.ts +54 -0
  18. package/cli/templates/core/client-modules/appflare.ts +112 -0
  19. package/cli/templates/core/client-modules/handlers/index.ts +740 -0
  20. package/cli/templates/core/client-modules/handlers.ts +1 -0
  21. package/cli/templates/core/client-modules/index.ts +7 -0
  22. package/cli/templates/core/client-modules/storage.ts +180 -0
  23. package/cli/templates/core/client-modules/types.ts +145 -0
  24. package/cli/templates/core/client.ts +39 -0
  25. package/cli/templates/core/drizzle.ts +15 -0
  26. package/cli/templates/core/export.ts +14 -0
  27. package/cli/templates/core/handlers-route.ts +23 -0
  28. package/cli/templates/core/handlers.ts +1 -0
  29. package/cli/templates/core/imports.ts +8 -0
  30. package/cli/templates/core/server.ts +38 -0
  31. package/cli/templates/core/types.ts +6 -0
  32. package/cli/templates/core/wrangler.ts +109 -0
  33. package/cli/templates/handlers/README.md +265 -0
  34. package/cli/templates/handlers/auth.ts +36 -0
  35. package/cli/templates/handlers/execution.ts +39 -0
  36. package/cli/templates/handlers/generators/context/context-creation.ts +80 -0
  37. package/cli/templates/handlers/generators/context/error-helpers.ts +11 -0
  38. package/cli/templates/handlers/generators/context/scheduler.ts +24 -0
  39. package/cli/templates/handlers/generators/context/storage-api.ts +112 -0
  40. package/cli/templates/handlers/generators/context/storage-helpers.ts +59 -0
  41. package/cli/templates/handlers/generators/context/types.ts +18 -0
  42. package/cli/templates/handlers/generators/context.ts +43 -0
  43. package/cli/templates/handlers/generators/execution.ts +15 -0
  44. package/cli/templates/handlers/generators/handlers.ts +13 -0
  45. package/cli/templates/handlers/index.ts +43 -0
  46. package/cli/templates/handlers/operations.ts +116 -0
  47. package/cli/templates/handlers/registration.ts +1114 -0
  48. package/cli/templates/handlers/types.ts +960 -0
  49. package/cli/templates/handlers/utils.ts +48 -0
  50. package/cli/types.ts +108 -0
  51. package/cli/utils/handler-discovery.ts +366 -0
  52. package/cli/utils/json-utils.ts +24 -0
  53. package/cli/utils/path-utils.ts +19 -0
  54. package/cli/utils/schema-discovery.ts +390 -0
  55. package/index.ts +27 -4
  56. package/package.json +23 -20
  57. package/react/index.ts +5 -3
  58. package/react/use-infinite-query.ts +190 -0
  59. package/react/use-mutation.ts +54 -0
  60. package/react/use-query.ts +158 -0
  61. package/schema.ts +262 -0
  62. package/tsconfig.json +2 -4
  63. package/cli/README.md +0 -108
  64. package/cli/core/build.ts +0 -187
  65. package/cli/core/config.ts +0 -92
  66. package/cli/core/discover-handlers.ts +0 -143
  67. package/cli/core/handlers.ts +0 -7
  68. package/cli/core/index.ts +0 -205
  69. package/cli/generators/generate-api-client/client.ts +0 -163
  70. package/cli/generators/generate-api-client/extract-configuration.ts +0 -121
  71. package/cli/generators/generate-api-client/index.ts +0 -973
  72. package/cli/generators/generate-api-client/types.ts +0 -164
  73. package/cli/generators/generate-api-client/utils.ts +0 -22
  74. package/cli/generators/generate-api-client.ts +0 -1
  75. package/cli/generators/generate-cloudflare-worker/helpers.ts +0 -24
  76. package/cli/generators/generate-cloudflare-worker/index.ts +0 -2
  77. package/cli/generators/generate-cloudflare-worker/worker.ts +0 -148
  78. package/cli/generators/generate-cloudflare-worker/wrangler.ts +0 -108
  79. package/cli/generators/generate-cloudflare-worker.ts +0 -4
  80. package/cli/generators/generate-cron-handlers/cron-handlers-block.ts +0 -2
  81. package/cli/generators/generate-cron-handlers/handler-entries.ts +0 -29
  82. package/cli/generators/generate-cron-handlers/index.ts +0 -61
  83. package/cli/generators/generate-cron-handlers/runtime-block.ts +0 -49
  84. package/cli/generators/generate-cron-handlers/type-helpers-block.ts +0 -60
  85. package/cli/generators/generate-db-handlers/index.ts +0 -33
  86. package/cli/generators/generate-db-handlers/prepare.ts +0 -24
  87. package/cli/generators/generate-db-handlers/templates.ts +0 -189
  88. package/cli/generators/generate-db-handlers.ts +0 -1
  89. package/cli/generators/generate-hono-server/auth.ts +0 -97
  90. package/cli/generators/generate-hono-server/imports.ts +0 -55
  91. package/cli/generators/generate-hono-server/index.ts +0 -52
  92. package/cli/generators/generate-hono-server/routes.ts +0 -115
  93. package/cli/generators/generate-hono-server/template.ts +0 -371
  94. package/cli/generators/generate-hono-server.ts +0 -1
  95. package/cli/generators/generate-scheduler-handlers/constants.ts +0 -8
  96. package/cli/generators/generate-scheduler-handlers/handler-entries.ts +0 -22
  97. package/cli/generators/generate-scheduler-handlers/index.ts +0 -51
  98. package/cli/generators/generate-scheduler-handlers/runtime-block.ts +0 -68
  99. package/cli/generators/generate-scheduler-handlers/scheduler-handlers-block.ts +0 -2
  100. package/cli/generators/generate-scheduler-handlers/type-helpers-block.ts +0 -68
  101. package/cli/generators/generate-scheduler-handlers.ts +0 -1
  102. package/cli/generators/generate-websocket-durable-object/auth.ts +0 -30
  103. package/cli/generators/generate-websocket-durable-object/imports.ts +0 -55
  104. package/cli/generators/generate-websocket-durable-object/index.ts +0 -41
  105. package/cli/generators/generate-websocket-durable-object/query-handlers.ts +0 -18
  106. package/cli/generators/generate-websocket-durable-object/template.ts +0 -714
  107. package/cli/generators/generate-websocket-durable-object.ts +0 -1
  108. package/cli/schema/schema-static-types.ts +0 -702
  109. package/cli/schema/schema.ts +0 -151
  110. package/cli/utils/tsc.ts +0 -54
  111. package/cli/utils/utils.ts +0 -190
  112. package/cli/utils/zod-utils.ts +0 -121
  113. package/lib/README.md +0 -50
  114. package/lib/db.ts +0 -19
  115. package/lib/location.ts +0 -110
  116. package/lib/values.ts +0 -27
  117. package/react/README.md +0 -67
  118. package/react/hooks/useMutation.ts +0 -89
  119. package/react/hooks/usePaginatedQuery.ts +0 -213
  120. package/react/hooks/useQuery.ts +0 -106
  121. package/react/shared/queryShared.ts +0 -174
  122. package/server/README.md +0 -218
  123. package/server/auth.ts +0 -107
  124. package/server/database/builders.ts +0 -83
  125. package/server/database/context.ts +0 -327
  126. package/server/database/populate.ts +0 -234
  127. package/server/database/query-builder.ts +0 -161
  128. package/server/database/query-utils.ts +0 -25
  129. package/server/db.ts +0 -2
  130. package/server/storage/auth.ts +0 -16
  131. package/server/storage/bucket.ts +0 -22
  132. package/server/storage/context.ts +0 -34
  133. package/server/storage/index.ts +0 -38
  134. package/server/storage/operations.ts +0 -149
  135. package/server/storage/route-handler.ts +0 -60
  136. package/server/storage/types.ts +0 -55
  137. package/server/storage/utils.ts +0 -47
  138. package/server/storage.ts +0 -6
  139. package/server/types/schema-refs.ts +0 -66
  140. package/server/types/types.ts +0 -633
  141. package/server/utils/id-utils.ts +0 -230
@@ -1,33 +0,0 @@
1
- import { promises as fs } from "node:fs";
2
- import path from "node:path";
3
- import { pascalCase } from "../../utils/utils";
4
- import {
5
- buildExportLine,
6
- buildHandlerFileContent,
7
- buildIndexFileContent,
8
- } from "./templates";
9
- import { ensureHandlersDir, removeExistingHandlerFiles } from "./prepare";
10
-
11
- export type GenerateDbHandlersParams = {
12
- outDirAbs: string;
13
- tableNames: string[];
14
- };
15
-
16
- export async function generateDbHandlers(
17
- params: GenerateDbHandlersParams
18
- ): Promise<void> {
19
- const handlersDir = await ensureHandlersDir(params.outDirAbs);
20
- await removeExistingHandlerFiles(handlersDir);
21
-
22
- const exportLines: string[] = [];
23
- for (const tableName of params.tableNames) {
24
- const pascalName = pascalCase(tableName);
25
- const fileName = `${tableName}.ts`;
26
- const content = buildHandlerFileContent({ tableName, pascalName });
27
- await fs.writeFile(path.join(handlersDir, fileName), content);
28
- exportLines.push(buildExportLine({ tableName, pascalName }));
29
- }
30
-
31
- const indexTs = buildIndexFileContent(exportLines);
32
- await fs.writeFile(path.join(handlersDir, "index.ts"), indexTs);
33
- }
@@ -1,24 +0,0 @@
1
- import { promises as fs } from "node:fs";
2
- import path from "node:path";
3
-
4
- const resolveHandlersDir = (outDirAbs: string): string =>
5
- path.join(outDirAbs, "src", "handlers");
6
-
7
- export const ensureHandlersDir = async (outDirAbs: string): Promise<string> => {
8
- const handlersDir = resolveHandlersDir(outDirAbs);
9
- await fs.mkdir(handlersDir, { recursive: true });
10
- return handlersDir;
11
- };
12
-
13
- export const removeExistingHandlerFiles = async (
14
- handlersDir: string
15
- ): Promise<void> => {
16
- const existing = await fs.readdir(handlersDir).catch(() => [] as string[]);
17
- await Promise.all(
18
- existing
19
- .filter((name) => name.endsWith(".ts"))
20
- .map((name) =>
21
- fs.unlink(path.join(handlersDir, name)).catch(() => void 0)
22
- )
23
- );
24
- };
@@ -1,189 +0,0 @@
1
- type HandlerTemplateParams = {
2
- tableName: string;
3
- pascalName: string;
4
- };
5
-
6
- type ExportLineParams = {
7
- tableName: string;
8
- pascalName: string;
9
- };
10
-
11
- export const buildHandlerFileContent = (
12
- params: HandlerTemplateParams
13
- ): string => {
14
- const findFn = `find${params.pascalName}`;
15
- const findOneFn = `findOne${params.pascalName}`;
16
- const sumFn = `sum${params.pascalName}`;
17
- const avgFn = `avg${params.pascalName}`;
18
- const insertFn = `insert${params.pascalName}`;
19
- const updateFn = `update${params.pascalName}`;
20
- const deleteFn = `delete${params.pascalName}`;
21
-
22
- return `/* eslint-disable */
23
- /**
24
- * This file is auto-generated by appflare/db-build.ts.
25
- * Do not edit directly.
26
- */
27
- import { z } from "zod";
28
- import {
29
- internalMutation,
30
- internalQuery,
31
- type AppflareInclude,
32
- type EditableDoc,
33
- type Doc,
34
- type Id,
35
- type QuerySort,
36
- type QueryWhere,
37
- } from "../schema-types";
38
-
39
- export const ${findFn} = internalQuery({
40
- args: {
41
- where: z.custom<QueryWhere<${JSON.stringify(params.tableName)}>>()
42
- .optional(),
43
- sort: z.custom<QuerySort<${JSON.stringify(params.tableName)}>>()
44
- .optional(),
45
- limit: z.number().int().nonnegative().optional(),
46
- offset: z.number().int().nonnegative().optional(),
47
- include: z.custom<AppflareInclude<Doc<${JSON.stringify(params.tableName)}>>>()
48
- .optional(),
49
- },
50
- handler: async (ctx, args) => {
51
- return ctx.db[${JSON.stringify(params.tableName)} as any].findMany({
52
- where: args.where as any,
53
- orderBy: args.sort as any,
54
- skip: args.offset,
55
- take: args.limit,
56
- include: args.include as any,
57
- });
58
- },
59
- });
60
-
61
- export const ${findOneFn} = internalQuery({
62
- args: {
63
- where: z.custom<QueryWhere<${JSON.stringify(params.tableName)}>>()
64
- .optional(),
65
- sort: z.custom<QuerySort<${JSON.stringify(params.tableName)}>>()
66
- .optional(),
67
- offset: z.number().int().nonnegative().optional(),
68
- include: z.custom<AppflareInclude<Doc<${JSON.stringify(params.tableName)}>>>()
69
- .optional(),
70
- },
71
- handler: async (ctx, args) => {
72
- return ctx.db[${JSON.stringify(params.tableName)} as any].findFirst({
73
- where: args.where as any,
74
- orderBy: args.sort as any,
75
- skip: args.offset,
76
- take: 1,
77
- include: args.include as any,
78
- });
79
- },
80
- });
81
-
82
- export const ${sumFn} = internalQuery({
83
- args: {
84
- fields: z.array(z.string()).min(1),
85
- where: z.custom<QueryWhere<${JSON.stringify(params.tableName)}>>()
86
- .optional(),
87
- groupBy: z.union([z.string(), z.array(z.string())]).optional(),
88
- populate: z.custom<AppflareInclude<Doc<${JSON.stringify(params.tableName)}>>>()
89
- .optional(),
90
- },
91
- handler: async (ctx, args) => {
92
- return ctx.db[${JSON.stringify(params.tableName)} as any].aggregate({
93
- where: args.where as any,
94
- groupBy: args.groupBy as any,
95
- sum: args.fields as any,
96
- populate: args.populate as any,
97
- });
98
- },
99
- });
100
-
101
- export const ${avgFn} = internalQuery({
102
- args: {
103
- fields: z.array(z.string()).min(1),
104
- where: z.custom<QueryWhere<${JSON.stringify(params.tableName)}>>()
105
- .optional(),
106
- groupBy: z.union([z.string(), z.array(z.string())]).optional(),
107
- populate: z.custom<AppflareInclude<Doc<${JSON.stringify(params.tableName)}>>>()
108
- .optional(),
109
- },
110
- handler: async (ctx, args) => {
111
- return ctx.db[${JSON.stringify(params.tableName)} as any].aggregate({
112
- where: args.where as any,
113
- groupBy: args.groupBy as any,
114
- avg: args.fields as any,
115
- populate: args.populate as any,
116
- });
117
- },
118
- });
119
-
120
- export const ${insertFn} = internalMutation({
121
- args: {
122
- value: z.custom<EditableDoc<${JSON.stringify(params.tableName)}>>(),
123
- },
124
- handler: async (ctx, args) => {
125
- return ctx.db[${JSON.stringify(params.tableName)} as any].create({
126
- data: args.value as any,
127
- });
128
- },
129
- });
130
-
131
- export const ${updateFn} = internalMutation({
132
- args: {
133
- id: z.custom<Id<${JSON.stringify(params.tableName)}>>().optional(),
134
- where: z.custom<QueryWhere<${JSON.stringify(params.tableName)}>>()
135
- .optional(),
136
- partial: z.custom<Partial<EditableDoc<${JSON.stringify(params.tableName)}>>>(),
137
- },
138
- handler: async (ctx, args) => {
139
- const filter = (args.where ?? args.id) as any;
140
- if (!filter) {
141
- throw new Error("update requires either args.where or args.id");
142
- }
143
- await ctx.db[${JSON.stringify(params.tableName)} as any].update({
144
- where: filter,
145
- data: args.partial as any,
146
- });
147
- },
148
- });
149
-
150
- export const ${deleteFn} = internalMutation({
151
- args: {
152
- id: z.custom<Id<${JSON.stringify(params.tableName)}>>().optional(),
153
- where: z.custom<QueryWhere<${JSON.stringify(params.tableName)}>>()
154
- .optional(),
155
- },
156
- handler: async (ctx, args) => {
157
- const filter = (args.where ?? args.id) as any;
158
- if (!filter) {
159
- throw new Error("delete requires either args.where or args.id");
160
- }
161
- await ctx.db[${JSON.stringify(params.tableName)} as any].delete({
162
- where: filter,
163
- });
164
- },
165
- });
166
- `;
167
- };
168
-
169
- export const buildExportLine = (params: ExportLineParams): string => {
170
- const findFn = `find${params.pascalName}`;
171
- const findOneFn = `findOne${params.pascalName}`;
172
- const sumFn = `sum${params.pascalName}`;
173
- const avgFn = `avg${params.pascalName}`;
174
- const insertFn = `insert${params.pascalName}`;
175
- const updateFn = `update${params.pascalName}`;
176
- const deleteFn = `delete${params.pascalName}`;
177
-
178
- return `export { ${findFn}, ${findOneFn}, ${sumFn}, ${avgFn}, ${insertFn}, ${updateFn}, ${deleteFn} } from "./${params.tableName}";`;
179
- };
180
-
181
- export const buildIndexFileContent = (
182
- exportLines: string[]
183
- ): string => `/* eslint-disable */
184
- /**
185
- * This file is auto-generated by appflare/db-build.ts.
186
- * Do not edit directly.
187
- */
188
- ${exportLines.join("\n")}
189
- `;
@@ -1 +0,0 @@
1
- export { generateDbHandlers } from "./generate-db-handlers/index";
@@ -1,97 +0,0 @@
1
- import type { AppflareConfig } from "../../utils/utils";
2
-
3
- export type AuthSection = {
4
- imports: string;
5
- setupBlock: string;
6
- mountBlock: string;
7
- resolverBlock: string;
8
- };
9
-
10
- const indentBlock = (block: string): string =>
11
- block
12
- .split("\n")
13
- .map((line) => `\t${line}`)
14
- .join("\n");
15
-
16
- export function buildAuthSection(config: AppflareConfig): AuthSection {
17
- const hasAuth = Boolean(config.auth);
18
-
19
- const authImports = hasAuth
20
- ? `import { createBetterAuthRouter, getSanitizedRequest, initBetterAuth } from "appflare/server/auth";`
21
- : "";
22
-
23
- const authSetup = hasAuth
24
- ? [
25
- `const __appflareAuthConfig = (appflareConfig as any).auth;`,
26
- `const __appflareAuthBasePath = __appflareAuthConfig?.basePath ?? "/auth";`,
27
- `const __appflareStorageConfig = (appflareConfig as any).storage;`,
28
- `const __appflareKvBinding = __appflareStorageConfig?.kvBinding;`,
29
- `const __appflareAuth =`,
30
- `\t__appflareAuthConfig &&`,
31
- `\t__appflareAuthConfig.enabled !== false &&`,
32
- `\t__appflareAuthConfig.options`,
33
- `\t\t? initBetterAuth(__appflareAuthConfig.options as any, __appflareKvBinding)`,
34
- `\t\t: undefined;`,
35
- `const __appflareAuthRouter = __appflareAuth`,
36
- `\t? createBetterAuthRouter({`,
37
- `\t\tauth: __appflareAuth,`,
38
- `\t})`,
39
- `\t: undefined;`,
40
- ].join("\n")
41
- : "";
42
-
43
- const authMount = hasAuth
44
- ? `\n\tif (__appflareAuthRouter) {\n\t\tapp.route(__appflareAuthBasePath, __appflareAuthRouter);\n\t}\n`
45
- : "";
46
-
47
- const authResolver = hasAuth
48
- ? [
49
- `const resolveAuthContext = async (`,
50
- `\tc: HonoContext`,
51
- `): Promise<AppflareAuthContext> => {`,
52
- `\tif (!__appflareAuth) {`,
53
- `\t\tconst authContext: AppflareAuthContext = {`,
54
- `\t\t\tsession: null as AppflareAuthSession,`,
55
- `\t\t\tuser: null as AppflareAuthUser,`,
56
- `\t\t};`,
57
- `\t\tc.set("appflareSession", authContext.session);`,
58
- `\t\tc.set("appflareUser", authContext.user);`,
59
- `\t\treturn authContext;`,
60
- `\t}`,
61
- ``,
62
- `\tconst sessionResult = await __appflareAuth.api.getSession(`,
63
- `\t\(c.req.raw)`,
64
- `\t);`,
65
- `\tconst authContext: AppflareAuthContext = {`,
66
- `\t\tsession:`,
67
- `\t\t\t(sessionResult as any)?.session ??`,
68
- `\t\t\t(sessionResult as any) ??`,
69
- `\t\t\t(null as AppflareAuthSession),`,
70
- `\t\tuser: (sessionResult as any)?.user ?? (null as AppflareAuthUser),`,
71
- `\t};`,
72
- `\tc.set("appflareSession", authContext.session);`,
73
- `\tc.set("appflareUser", authContext.user);`,
74
- `\treturn authContext;`,
75
- `};`,
76
- ].join("\n")
77
- : [
78
- `const resolveAuthContext = async (`,
79
- `\tc: HonoContext`,
80
- `): Promise<AppflareAuthContext> => {`,
81
- `\tconst authContext: AppflareAuthContext = {`,
82
- `\t\tsession: null as AppflareAuthSession,`,
83
- `\t\tuser: null as AppflareAuthUser,`,
84
- `\t};`,
85
- `\tc.set("appflareSession", authContext.session);`,
86
- `\tc.set("appflareUser", authContext.user);`,
87
- `\treturn authContext;`,
88
- `};`,
89
- ].join("\n");
90
-
91
- return {
92
- imports: authImports,
93
- setupBlock: authSetup ? `\n${indentBlock(authSetup)}\n` : "",
94
- mountBlock: authMount,
95
- resolverBlock: `\n${indentBlock(authResolver)}\n`,
96
- };
97
- }
@@ -1,55 +0,0 @@
1
- import path from "node:path";
2
- import {
3
- DiscoveredHandler,
4
- groupBy,
5
- pascalCase,
6
- toImportPathFromGeneratedServer,
7
- } from "../../utils/utils";
8
-
9
- export type ImportSection = {
10
- schemaImportPath: string;
11
- configImportLine: string;
12
- localNameFor: (handler: DiscoveredHandler) => string;
13
- handlerImports: string[];
14
- };
15
-
16
- export function buildImportSection(params: {
17
- handlers: DiscoveredHandler[];
18
- outDirAbs: string;
19
- schemaPathAbs: string;
20
- configPathAbs: string;
21
- }): ImportSection {
22
- const generatedSchemaAbs = path.join(params.outDirAbs, "src", "schema.ts");
23
- const schemaImportPath = toImportPathFromGeneratedServer(
24
- params.outDirAbs,
25
- generatedSchemaAbs
26
- );
27
- const configImportPath = toImportPathFromGeneratedServer(
28
- params.outDirAbs,
29
- params.configPathAbs
30
- );
31
- const configImportLine = `import appflareConfig from ${JSON.stringify(configImportPath)};`;
32
- const localNameFor = (handler: DiscoveredHandler): string =>
33
- `__appflare_${pascalCase(handler.routePath)}_${handler.name}`;
34
- const grouped = groupBy(params.handlers, (handler) => handler.sourceFileAbs);
35
- const handlerImports: string[] = [];
36
- for (const [fileAbs, list] of Array.from(grouped.entries())) {
37
- const specifiers = list
38
- .slice()
39
- .sort((a, b) => a.name.localeCompare(b.name))
40
- .map((handler) => `${handler.name} as ${localNameFor(handler)}`);
41
- const importPath = toImportPathFromGeneratedServer(
42
- params.outDirAbs,
43
- fileAbs
44
- );
45
- handlerImports.push(
46
- `import { ${specifiers.join(", ")} } from ${JSON.stringify(importPath)};`
47
- );
48
- }
49
- return {
50
- schemaImportPath,
51
- configImportLine,
52
- localNameFor,
53
- handlerImports,
54
- };
55
- }
@@ -1,52 +0,0 @@
1
- import type { AppflareConfig, DiscoveredHandler } from "../../utils/utils";
2
- import { buildImportSection } from "./imports";
3
- import { buildAuthSection } from "./auth";
4
- import { buildRouteLines, buildHttpRouteLines } from "./routes";
5
- import { renderServerTemplate } from "./template";
6
-
7
- export type GenerateHonoServerParams = {
8
- handlers: DiscoveredHandler[];
9
- outDirAbs: string;
10
- schemaPathAbs: string;
11
- configPathAbs: string;
12
- config: AppflareConfig;
13
- };
14
-
15
- export function generateHonoServer(params: GenerateHonoServerParams): string {
16
- const queries = params.handlers.filter((handler) => handler.kind === "query");
17
- const mutations = params.handlers.filter(
18
- (handler) => handler.kind === "mutation"
19
- );
20
- const https = params.handlers.filter(
21
- (handler) => handler.kind === "http"
22
- );
23
-
24
- const imports = buildImportSection({
25
- handlers: params.handlers,
26
- outDirAbs: params.outDirAbs,
27
- schemaPathAbs: params.schemaPathAbs,
28
- configPathAbs: params.configPathAbs,
29
- });
30
- const auth = buildAuthSection(params.config);
31
- const routeLines = buildRouteLines({
32
- queries,
33
- mutations,
34
- localNameFor: imports.localNameFor,
35
- });
36
- const httpLines = buildHttpRouteLines({
37
- https,
38
- localNameFor: imports.localNameFor,
39
- });
40
-
41
- return renderServerTemplate({
42
- schemaImportPath: imports.schemaImportPath,
43
- configImportLine: imports.configImportLine,
44
- handlerImports: imports.handlerImports,
45
- authImports: auth.imports,
46
- authSetupBlock: auth.setupBlock,
47
- authMountBlock: auth.mountBlock,
48
- authResolverBlock: auth.resolverBlock,
49
- routeLines,
50
- httpLines,
51
- });
52
- }
@@ -1,115 +0,0 @@
1
- import type { DiscoveredHandler } from "../../utils/utils";
2
-
3
- export function buildRouteLines(params: {
4
- queries: DiscoveredHandler[];
5
- mutations: DiscoveredHandler[];
6
- localNameFor: (handler: DiscoveredHandler) => string;
7
- }): string[] {
8
- const routeLines: string[] = [];
9
- for (const query of params.queries) {
10
- const local = params.localNameFor(query);
11
- routeLines.push(
12
- `app.get(\n` +
13
- ` ${JSON.stringify(`/queries/${query.routePath}/${query.name}`)},\n` +
14
- `\tsValidator("query", z.object(${local}.args as any)),\n` +
15
- `\tasync (c) => {\n` +
16
- `\t\ttry {\n` +
17
- `\t\t\tconst query = c.req.valid("query");\n` +
18
- `\t\t\tconst ctx = await resolveContext(c);\n` +
19
- `\t\t\tconst result = await runHandlerWithMiddleware(\n` +
20
- `\t\t\t\t${local} as any,\n` +
21
- `\t\t\t\tctx as any,\n` +
22
- `\t\t\t\tquery as any\n` +
23
- `\t\t\t);\n` +
24
- `\t\t\tif (isHandlerError(result)) {\n` +
25
- `\t\t\t\tconst { status, body } = formatHandlerError(result);\n` +
26
- `\t\t\t\treturn c.json(body as any, status);\n` +
27
- `\t\t\t}\n` +
28
- `\t\t\treturn c.json(result, 200);\n` +
29
- `\t\t} catch (err) {\n` +
30
- `\t\t\tconst { status, body } = formatHandlerError(err);\n` +
31
- `\t\t\tconsole.error("Appflare query handler error", err);\n` +
32
- `\t\t\treturn c.json(body as any, status);\n` +
33
- `\t\t}\n` +
34
- `\t}\n` +
35
- `);`
36
- );
37
- }
38
- for (const mutation of params.mutations) {
39
- const local = params.localNameFor(mutation);
40
- routeLines.push(
41
- `app.post(\n` +
42
- `\t${JSON.stringify(`/mutations/${mutation.routePath}/${mutation.name}`)},\n` +
43
- `\tsValidator("json", z.object(${local}.args as any)),\n` +
44
- `\tasync (c) => {\n` +
45
- `\t\ttry {\n` +
46
- `\t\t\tconst body = c.req.valid("json");\n` +
47
- `\t\t\tconst ctx = await resolveContext(c);\n` +
48
- `\t\t\tconst result = await runHandlerWithMiddleware(\n` +
49
- `\t\t\t\t${local} as any,\n` +
50
- `\t\t\t\tctx as any,\n` +
51
- `\t\t\t\tbody as any\n` +
52
- `\t\t\t);\n` +
53
- `\t\t\tif (isHandlerError(result)) {\n` +
54
- `\t\t\t\tconst { status, body } = formatHandlerError(result);\n` +
55
- `\t\t\t\treturn c.json(body as any, status);\n` +
56
- `\t\t\t}\n` +
57
- `\t\t\tif (notifyMutation) {\n` +
58
- `\t\t\t\ttry {\n` +
59
- `\t\t\t\t\tawait notifyMutation({\n` +
60
- `\t\t\t\t\t table: normalizeTableName(${JSON.stringify(mutation.fileName)}),\n` +
61
- `\t\t\t\t\t handler: { file: ${JSON.stringify(mutation.routePath)}, name: ${JSON.stringify(mutation.name)} },\n` +
62
- `\t\t\t\t\t args: body,\n` +
63
- `\t\t\t\t\t result,\n` +
64
- `\t\t\t\t});\n` +
65
- `\t\t\t\t} catch (err) {\n` +
66
- `\t\t\t\t\tconsole.error("Appflare realtime notification failed", err);\n` +
67
- `\t\t\t\t}\n` +
68
- `\t\t\t}\n` +
69
- `\t\t\treturn c.json(result, 200);\n` +
70
- `\t\t} catch (err) {\n` +
71
- `\t\t\tconst { status, body } = formatHandlerError(err);\n` +
72
- `\t\t\tconsole.error("Appflare mutation handler error", err);\n` +
73
- `\t\t\treturn c.json(body as any, status);\n` +
74
- `\t\t}\n` +
75
- `\t}\n` +
76
- `);`
77
- );
78
- }
79
- return routeLines;
80
- }
81
-
82
- export function buildHttpRouteLines(params: {
83
- https: DiscoveredHandler[];
84
- localNameFor: (handler: DiscoveredHandler) => string;
85
- }): string[] {
86
- const routeLines: string[] = [];
87
- for (const hook of params.https) {
88
- const local = params.localNameFor(hook);
89
- routeLines.push(
90
- `app.all(\n` +
91
- ` ${JSON.stringify(`/http/${hook.routePath}/${hook.name}`)},\n` +
92
- ` async (c) => {\n` +
93
- `\t\ttry {\n` +
94
- `\t\t\tconst ctx = await resolveContext(c);\n` +
95
- `\t\t\tconst result = await runHandlerWithMiddleware(\n` +
96
- `\t\t\t\t${local} as any,\n` +
97
- `\t\t\t\tctx as any,\n` +
98
- `\t\t\t\tc.req.raw\n` +
99
- `\t\t\t);\n` +
100
- `\t\t\tif (isHandlerError(result)) {\n` +
101
- `\t\t\t\tconst { status, body } = formatHandlerError(result);\n` +
102
- `\t\t\t\treturn c.json(body as any, status);\n` +
103
- `\t\t\t}\n` +
104
- `\t\t\treturn result;\n` +
105
- `\t\t} catch (err) {\n` +
106
- `\t\t\tconst { status, body } = formatHandlerError(err);\n` +
107
- `\t\t\tconsole.error("Appflare http handler error", err);\n` +
108
- `\t\t\treturn c.json(body as any, status);\n` +
109
- `\t\t}\n` +
110
- `\t}\n` +
111
- `);`
112
- );
113
- }
114
- return routeLines;
115
- }