@alxia/create 0.1.7 → 0.3.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 (66) hide show
  1. package/README.md +80 -25
  2. package/dist/args.d.ts +3 -1
  3. package/dist/args.d.ts.map +1 -1
  4. package/dist/index.js +19 -9
  5. package/dist/index.js.map +7 -7
  6. package/dist/main.d.ts +1 -1
  7. package/dist/main.d.ts.map +1 -1
  8. package/dist/registry.d.ts +2 -0
  9. package/dist/registry.d.ts.map +1 -1
  10. package/dist/versions.d.ts +5 -2
  11. package/dist/versions.d.ts.map +1 -1
  12. package/docs/README.md +16 -6
  13. package/docs/guide.md +428 -47
  14. package/docs/roadmap.md +24 -0
  15. package/docs/troubleshooting.md +152 -9
  16. package/package.json +16 -5
  17. package/templates/api/.env.example +9 -1
  18. package/templates/api/README.md +40 -12
  19. package/templates/api/openapi.yaml +13 -9
  20. package/templates/api/package.json +5 -3
  21. package/templates/api/src/app.spec.ts +42 -28
  22. package/templates/api/src/app.ts +13 -3
  23. package/templates/api/src/context.ts +3 -4
  24. package/templates/api/src/env.ts +20 -0
  25. package/templates/api/src/generated/alxia.ts +3 -3
  26. package/templates/api/src/generated/operations.ts +3 -3
  27. package/templates/api/src/generated/paths.ts +6 -6
  28. package/templates/api/src/generated/types.ts +14 -10
  29. package/templates/api/src/generated/zod.ts +6 -2
  30. package/templates/api/src/routes/todos.ts +2 -2
  31. package/templates/api/src/server.ts +8 -16
  32. package/templates/graphql/.dockerignore +6 -0
  33. package/templates/graphql/.env.example +3 -0
  34. package/templates/graphql/.vscode/extensions.json +3 -0
  35. package/templates/graphql/.vscode/settings.json +8 -0
  36. package/templates/graphql/Dockerfile +26 -0
  37. package/templates/graphql/README.md +185 -0
  38. package/templates/graphql/_biome.json +32 -0
  39. package/templates/graphql/codegen.ts +22 -0
  40. package/templates/graphql/gitignore +6 -0
  41. package/templates/graphql/package.json +35 -0
  42. package/templates/graphql/schema.graphql +26 -0
  43. package/templates/graphql/src/app.spec.ts +146 -0
  44. package/templates/graphql/src/app.ts +18 -0
  45. package/templates/graphql/src/context.ts +26 -0
  46. package/templates/graphql/src/env.ts +8 -0
  47. package/templates/graphql/src/generated/resolvers.ts +180 -0
  48. package/templates/graphql/src/graphql.d.ts +6 -0
  49. package/templates/graphql/src/loaders.ts +13 -0
  50. package/templates/graphql/src/resolvers.ts +39 -0
  51. package/templates/graphql/src/schema.ts +6 -0
  52. package/templates/graphql/src/server.ts +10 -0
  53. package/templates/graphql/src/store.ts +38 -0
  54. package/templates/graphql/tsconfig.json +25 -0
  55. package/templates/minimal/.dockerignore +6 -0
  56. package/templates/minimal/.vscode/extensions.json +3 -0
  57. package/templates/minimal/.vscode/settings.json +8 -0
  58. package/templates/minimal/Dockerfile +26 -0
  59. package/templates/minimal/README.md +107 -0
  60. package/templates/minimal/_biome.json +32 -0
  61. package/templates/minimal/gitignore +6 -0
  62. package/templates/minimal/package.json +25 -0
  63. package/templates/minimal/src/index.spec.ts +12 -0
  64. package/templates/minimal/src/index.ts +17 -0
  65. package/templates/minimal/tsconfig.json +25 -0
  66. package/templates/react-router/package.json +2 -2
@@ -0,0 +1,20 @@
1
+ import { defineEnv } from "@alxia/env";
2
+ import { z } from "zod";
3
+
4
+ // `bun dev` and `bun test` run in development and test; anything else,
5
+ // production included, is a deployment.
6
+ const local = ["development", "test"].includes(Bun.env.NODE_ENV ?? "");
7
+
8
+ // Checked once, when this module is first imported: a missing or malformed
9
+ // variable stops the process, with every issue, before it listens. Secrets
10
+ // print as `***`. API_KEY defaults to `dev-key` in development and test
11
+ // alone: deployed, it is required. API_DOCS serves the API reference at
12
+ // /docs: on in development, off unless set elsewhere.
13
+ export const env = defineEnv(
14
+ {
15
+ PORT: z.coerce.number().default(3000),
16
+ API_KEY: local ? z.string().min(1).default("dev-key") : z.string().min(1),
17
+ API_DOCS: z.stringbool().default(Bun.env.NODE_ENV === "development"),
18
+ },
19
+ { secret: ["API_KEY"] },
20
+ );
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  import { z } from 'zod';
14
- import { zNewTodo, zNotFound, zTodo, zUnauthorized, zValidationError } from './zod';
14
+ import { zNewTodo, zNotFound, zTodo, zUnauthorized, zValidationProblem } from './zod';
15
15
 
16
16
  /** A number in a path, a query, a header or a cookie: digits, where z.coerce.number() would read '' as 0. */
17
17
  const numeric = z
@@ -39,7 +39,7 @@ export const createTodo = {
39
39
  body: zNewTodo,
40
40
  response: {
41
41
  201: zTodo,
42
- 400: zValidationError,
42
+ 400: zValidationProblem,
43
43
  401: zUnauthorized,
44
44
  },
45
45
  detail: { operationId: 'createTodo', summary: 'Add a todo' },
@@ -56,7 +56,7 @@ export const getTodo = {
56
56
  }),
57
57
  response: {
58
58
  200: zTodo,
59
- 400: zValidationError,
59
+ 400: zValidationProblem,
60
60
  404: zNotFound,
61
61
  },
62
62
  detail: { operationId: 'getTodo', summary: 'One todo' },
@@ -1,7 +1,7 @@
1
1
  // Generated by @nxgt/openapi-codegen from ../../openapi.yaml. Do not edit.
2
2
 
3
3
  import { z } from 'zod';
4
- import { zNewTodo, zNotFound, zTodo, zUnauthorized, zValidationError } from './zod';
4
+ import { zNewTodo, zNotFound, zTodo, zUnauthorized, zValidationProblem } from './zod';
5
5
  import type { ClientOperations, Operations } from './types';
6
6
 
7
7
  /** How a server reads a parameter, and how a client writes it. */
@@ -100,7 +100,7 @@ export const operations: {
100
100
  'application/json': { kind: 'json', schema: zTodo },
101
101
  },
102
102
  400: {
103
- 'application/json': { kind: 'json', schema: zValidationError },
103
+ 'application/problem+json': { kind: 'json', schema: zValidationProblem },
104
104
  },
105
105
  401: {
106
106
  'application/json': { kind: 'json', schema: zUnauthorized },
@@ -123,7 +123,7 @@ export const operations: {
123
123
  'application/json': { kind: 'json', schema: zTodo },
124
124
  },
125
125
  400: {
126
- 'application/json': { kind: 'json', schema: zValidationError },
126
+ 'application/problem+json': { kind: 'json', schema: zValidationProblem },
127
127
  },
128
128
  404: {
129
129
  'application/json': { kind: 'json', schema: zNotFound },
@@ -1,6 +1,6 @@
1
1
  // Generated by @nxgt/openapi-codegen from ../../openapi.yaml. Do not edit.
2
2
 
3
- import type { NewTodo, NotFound, Todo, Unauthorized, ValidationError } from './types';
3
+ import type { NewTodo, NotFound, Todo, Unauthorized, ValidationProblem } from './types';
4
4
 
5
5
  export interface paths {
6
6
  '/todos': {
@@ -50,7 +50,7 @@ export interface components {
50
50
  NewTodo: NewTodo;
51
51
  Unauthorized: Unauthorized;
52
52
  NotFound: NotFound;
53
- ValidationError: ValidationError;
53
+ ValidationProblem: ValidationProblem;
54
54
  };
55
55
  responses: never;
56
56
  parameters: never;
@@ -106,13 +106,13 @@ export interface operations {
106
106
  'application/json': Todo;
107
107
  };
108
108
  };
109
- /** alxia's own 400, for a request the schemas refuse */
109
+ /** alxia's own 400, for a request the schemas refuse, as an RFC 9457 problem */
110
110
  400: {
111
111
  headers: {
112
112
  [name: string]: unknown;
113
113
  };
114
114
  content: {
115
- 'application/json': ValidationError;
115
+ 'application/problem+json': ValidationProblem;
116
116
  };
117
117
  };
118
118
  /** No x-api-key header, or not the key */
@@ -147,13 +147,13 @@ export interface operations {
147
147
  'application/json': Todo;
148
148
  };
149
149
  };
150
- /** alxia's own 400, for a request the schemas refuse */
150
+ /** alxia's own 400, for a request the schemas refuse, as an RFC 9457 problem */
151
151
  400: {
152
152
  headers: {
153
153
  [name: string]: unknown;
154
154
  };
155
155
  content: {
156
- 'application/json': ValidationError;
156
+ 'application/problem+json': ValidationProblem;
157
157
  };
158
158
  };
159
159
  /** No todo has this id */
@@ -18,8 +18,12 @@ export interface NotFound {
18
18
  error: 'not_found';
19
19
  }
20
20
 
21
- export interface ValidationError {
22
- error: 'validation';
21
+ export interface ValidationProblem {
22
+ type: string;
23
+ title: string;
24
+ status: number;
25
+ detail: string;
26
+ instance: string;
23
27
  issues: {
24
28
  target: 'params' | 'query' | 'headers' | 'cookies' | 'body';
25
29
  path: (string | number)[];
@@ -62,9 +66,9 @@ export interface Operations {
62
66
  201: {
63
67
  'application/json': Todo;
64
68
  };
65
- /** alxia's own 400, for a request the schemas refuse */
69
+ /** alxia's own 400, for a request the schemas refuse, as an RFC 9457 problem */
66
70
  400: {
67
- 'application/json': ValidationError;
71
+ 'application/problem+json': ValidationProblem;
68
72
  };
69
73
  /** No x-api-key header, or not the key */
70
74
  401: {
@@ -85,9 +89,9 @@ export interface Operations {
85
89
  200: {
86
90
  'application/json': Todo;
87
91
  };
88
- /** alxia's own 400, for a request the schemas refuse */
92
+ /** alxia's own 400, for a request the schemas refuse, as an RFC 9457 problem */
89
93
  400: {
90
- 'application/json': ValidationError;
94
+ 'application/problem+json': ValidationProblem;
91
95
  };
92
96
  /** No todo has this id */
93
97
  404: {
@@ -116,11 +120,11 @@ export interface ClientOperations {
116
120
  }];
117
121
  reply:
118
122
  | { status: 201; type: 'application/json'; data: Todo }
119
- | { status: 400; type: 'application/json'; data: ValidationError }
123
+ | { status: 400; type: 'application/problem+json'; data: ValidationProblem }
120
124
  | { status: 401; type: 'application/json'; data: Unauthorized };
121
125
  wire:
122
126
  | { status: 201; type: 'application/json'; data: Todo }
123
- | { status: 400; type: 'application/json'; data: ValidationError }
127
+ | { status: 400; type: 'application/problem+json'; data: ValidationProblem }
124
128
  | { status: 401; type: 'application/json'; data: Unauthorized };
125
129
  };
126
130
  /** One todo */
@@ -134,11 +138,11 @@ export interface ClientOperations {
134
138
  }];
135
139
  reply:
136
140
  | { status: 200; type: 'application/json'; data: Todo }
137
- | { status: 400; type: 'application/json'; data: ValidationError }
141
+ | { status: 400; type: 'application/problem+json'; data: ValidationProblem }
138
142
  | { status: 404; type: 'application/json'; data: NotFound };
139
143
  wire:
140
144
  | { status: 200; type: 'application/json'; data: Todo }
141
- | { status: 400; type: 'application/json'; data: ValidationError }
145
+ | { status: 400; type: 'application/problem+json'; data: ValidationProblem }
142
146
  | { status: 404; type: 'application/json'; data: NotFound };
143
147
  };
144
148
  }
@@ -20,8 +20,12 @@ export const zNotFound = z.object({
20
20
  error: z.literal('not_found'),
21
21
  });
22
22
 
23
- export const zValidationError = z.object({
24
- error: z.literal('validation'),
23
+ export const zValidationProblem = z.object({
24
+ type: z.string(),
25
+ title: z.string(),
26
+ status: z.int(),
27
+ detail: z.string(),
28
+ instance: z.string(),
25
29
  issues: z.array(z.object({
26
30
  target: z.enum(['params', 'query', 'headers', 'cookies', 'body']),
27
31
  path: z.array(z.union([z.string(), z.int()])),
@@ -1,11 +1,11 @@
1
1
  import { defineMiddleware, defineRoutes } from "@alxia/core";
2
- import { apiKey } from "../context";
2
+ import { env } from "../env";
3
3
  import { operations } from "../generated/alxia";
4
4
 
5
5
  // A middleware of the routes it is given to: it answers 401 without the key,
6
6
  // before the body is read. openapi.yaml declares that 401.
7
7
  const requireKey = defineMiddleware(({ request, reply }, next) =>
8
- request.headers.get("x-api-key") === apiKey
8
+ request.headers.get("x-api-key") === env.API_KEY
9
9
  ? next()
10
10
  : reply(401, { error: "unauthorized" as const }),
11
11
  );
@@ -1,18 +1,10 @@
1
1
  import { app } from "./app";
2
+ import { env } from "./env";
2
3
 
3
- // Stop as the platform asks. In a container Bun is process 1, which a
4
- // signal with no handler does not stop: `docker stop` would wait.
5
- for (const signal of ["SIGINT", "SIGTERM"] as const) {
6
- process.once(signal, () => {
7
- void app.stop().then(
8
- () => process.exit(0),
9
- (error: unknown) => {
10
- console.error(error);
11
- process.exit(1);
12
- },
13
- );
14
- });
15
- }
16
-
17
- const server = app.listen(Number(Bun.env["PORT"] ?? 3000));
18
- console.log(`listening on ${server.url}`);
4
+ // In dev, the URL and the route table; in production, the URL alone. On
5
+ // SIGINT and SIGTERM, listen drains the requests in flight and exits.
6
+ app.listen({
7
+ port: env.PORT,
8
+ onListen: ({ dev, table, url }) =>
9
+ console.log(dev ? table : `listening on ${url}`),
10
+ });
@@ -0,0 +1,6 @@
1
+ node_modules
2
+ dist
3
+ .env
4
+ .env.local
5
+ README.md
6
+ **/*.spec.ts
@@ -0,0 +1,3 @@
1
+ # Copy to .env, which Bun loads on every command: bun dev, bun test, bun start.
2
+ # number, optional, default 3000
3
+ PORT=3000
@@ -0,0 +1,3 @@
1
+ {
2
+ "recommendations": ["biomejs.biome"]
3
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "editor.defaultFormatter": "biomejs.biome",
3
+ "editor.formatOnSave": true,
4
+ "editor.codeActionsOnSave": {
5
+ "source.fixAll.biome": "explicit",
6
+ "source.organizeImports.biome": "explicit"
7
+ }
8
+ }
@@ -0,0 +1,26 @@
1
+ # Bun bundles the app and its dependencies into dist/server.js, and the
2
+ # image holds dist/ alone: no node_modules, no src/. Pinned to Bun 1, the
3
+ # major alxia supports.
4
+
5
+ # Every dependency, then bun run build: dist/server.js and its source map.
6
+ FROM oven/bun:1 AS build
7
+ WORKDIR /app
8
+ COPY package.json bun.lock* bunfig.toml* ./
9
+ RUN bun install --frozen-lockfile
10
+ COPY . .
11
+ RUN bun run build
12
+
13
+ # The bundle, run as Bun's own non-root user with the start script's
14
+ # command, written out so that Bun is the container's process, and
15
+ # --no-install: with no node_modules, Bun would otherwise fetch a package
16
+ # the build left out from the registry at startup, where this fails. The
17
+ # server listens on PORT (3000). On Alpine, about 200 MB
18
+ # lighter: the bundle is JavaScript, which runs the same on musl. A native
19
+ # addon built for glibc alone needs oven/bun:1 here.
20
+ FROM oven/bun:1-alpine
21
+ WORKDIR /app
22
+ ENV NODE_ENV=production
23
+ COPY --from=build /app/dist ./dist
24
+ USER bun
25
+ EXPOSE 3000
26
+ CMD ["bun", "--no-install", "dist/server.js"]
@@ -0,0 +1,185 @@
1
+ # An alxia GraphQL API
2
+
3
+ An [alxia](https://github.com/softistx/alxia) app serving GraphQL with
4
+ [GraphQL Yoga](https://the-guild.dev/graphql/yoga-server), made with
5
+ `bun create @alxia`. It is schema first: `schema.graphql` is the contract,
6
+ the resolvers are typed from it, and the endpoint is a route of the app,
7
+ behind its middlewares.
8
+
9
+ ```sh
10
+ bun dev # http://localhost:3000/graphql, GraphiQL in a browser
11
+ ```
12
+
13
+ ```sh
14
+ curl localhost:3000/graphql -H 'content-type: application/json' \
15
+ -d '{"query":"{ __typename }"}'
16
+ curl localhost:3000/graphql -H 'content-type: application/json' \
17
+ -H 'authorization: Bearer ada-token' \
18
+ -d '{"query":"mutation { addNote(text: \"Hello\") { id author { name } } }"}'
19
+ ```
20
+
21
+ - `schema.graphql`: the API's types, `Query`, `Mutation` and `Subscription`.
22
+ Change it first.
23
+ - `src/generated/resolvers.ts`: what `bun run generate` writes from it, with
24
+ [GraphQL Code Generator](https://the-guild.dev/graphql/codegen)
25
+ (`codegen.ts`): the schema's types and `Resolvers`, typed with the app's
26
+ context. Never edit it.
27
+ - `src/resolvers.ts`: the resolvers, `const resolvers: Resolvers`. A field the
28
+ schema lacks, or a value its type refuses, is a compile error, and each
29
+ resolver reads `viewer`, `db` and `env` from its context, typed.
30
+ - `src/context.ts`: the base app and its middleware. `viewerOf` reads
31
+ `Authorization: Bearer <token>` and gives every resolver `viewer`: the
32
+ user, or `null`. `Context` is `GraphQLContext<typeof base, { loaders }>`, which
33
+ `codegen.ts` hands to `Resolvers`.
34
+ - `src/loaders.ts`: the DataLoaders, built per request by the `context` option
35
+ of `src/app.ts` (`Note.author` loads its users in one batch: [Batching](#batching-n1)).
36
+ - `src/schema.ts`, `src/app.ts`: `createSchema` from `schema.graphql` and the
37
+ resolvers, then `health()`'s probes (`GET /health`, `GET /ready`) and
38
+ `graphql(app, { schema })` mounted on the base.
39
+ - `src/env.ts`: `defineEnv` from
40
+ [`@alxia/env`](https://www.npmjs.com/package/@alxia/env): `PORT`, checked
41
+ once, when the module is first imported. A malformed one stops the
42
+ process with every issue, before it listens.
43
+ - `src/store.ts`: the in-memory users, tokens and notes, and the pub/sub the
44
+ subscription reads. Swap it for your database.
45
+ - `src/server.ts`: listens on `env.PORT`, 3000 by default, and shuts down
46
+ gracefully on `SIGINT` and `SIGTERM`, which `listen` handles.
47
+ - `src/app.spec.ts`: POST `/graphql` through `app.request()`, no port:
48
+ queries, the mutation with and without a token, one batch for N authors,
49
+ and the subscription.
50
+ - `biome.json`: Biome's lint and format settings ([Lint and format](#lint-and-format)).
51
+
52
+ ## The schema first
53
+
54
+ A new field starts in `schema.graphql`:
55
+
56
+ 1. Add it: `notesBy(userId: ID!): [Note!]!` on `Query`, say.
57
+ 2. `bun run generate`: `Resolvers` now has `notesBy`, with its arguments typed.
58
+ 3. Write the resolver in `src/resolvers.ts`: `notesBy: (_, { userId }, { db }) => …`.
59
+ 4. `bun test`: add a query to `src/app.spec.ts`.
60
+
61
+ `src/generated/` is committed, so the project builds with no generation step,
62
+ in Docker too. `bun run verify` runs `bun run generate --check` first: it
63
+ fails when `src/generated/` is not what `schema.graphql` gives. GraphQL Code
64
+ Generator's CLI and its two plugins are pinned exactly, since another release
65
+ may write the file differently: after moving them, run `bun run generate`.
66
+
67
+ ## Authentication
68
+
69
+ `viewerOf` in `src/context.ts` is a middleware given to `use`: it reads the
70
+ bearer token and passes `next({ viewer })`, so the base's type has `viewer`,
71
+ and `GraphQLContext<typeof base>` gives it to every resolver. It refuses
72
+ nothing, so a query may be anonymous: `me` is `null`. `addNote` throws a
73
+ `GraphQLError` with the code `UNAUTHENTICATED` when `viewer` is `null`. The
74
+ tokens in `src/store.ts` are for development (`ada-token`): verify a JWT with
75
+ [`@alxia/jwt`](https://www.npmjs.com/package/@alxia/jwt)'s `bearer`, or look
76
+ a session up, in the same place.
77
+
78
+ ## Batching (N+1)
79
+
80
+ `Note.author` runs once per note: with a database that is a query per note.
81
+ It reads `loaders.user.load(note.authorId)`, a
82
+ [DataLoader](https://github.com/graphql/dataloader) that collects the ids of
83
+ one request and calls `findUsers` in `src/store.ts` once for all of them
84
+ (`src/app.spec.ts` asserts one call for five notes). `createLoaders()` runs
85
+ for **each request**, in the `context` option: a loader caches what it loads,
86
+ so one shared between requests would keep stale data and hand one user's to
87
+ another. Add a loader for each field that loads a record by id.
88
+
89
+ ## Subscriptions
90
+
91
+ `noteAdded` is served over server-sent events, Yoga's default: a request
92
+ with `Accept: text/event-stream` gets a result each time `addNote` publishes.
93
+ WebSockets are not served.
94
+
95
+ ```sh
96
+ curl -N localhost:3000/graphql -H 'content-type: application/json' \
97
+ -H 'accept: text/event-stream' \
98
+ -d '{"query":"subscription { noteAdded { text author { name } } }"}'
99
+ ```
100
+
101
+ The pub/sub lives in one process: across several, back it with a broker, as
102
+ [Yoga's guide](https://the-guild.dev/graphql/yoga-server/docs/features/subscriptions)
103
+ describes.
104
+
105
+ ## Environment
106
+
107
+ Bun loads `.env` on every command, and `src/env.ts` checks what it finds. Copy
108
+ `.env.example` to `.env` to set `PORT`. GraphiQL follows alxia's dev
109
+ switch: on under `bun dev`, which sets `NODE_ENV=development`, off
110
+ otherwise — `bun start` and the image run with `NODE_ENV=production`.
111
+
112
+ ```sh
113
+ cp .env.example .env
114
+ ```
115
+
116
+ ## Test
117
+
118
+ ```sh
119
+ bun test # src/app.spec.ts: in process, no port
120
+ bun run typecheck
121
+ bun run generate # src/generated/, from schema.graphql
122
+ ```
123
+
124
+ ## Lint and format
125
+
126
+ [Biome](https://biomejs.dev) lints and formats the project, as `biome.json`
127
+ sets it: Biome's recommended rules, spaces, double quotes, imports
128
+ sorted. What the build writes, `dist/`, is skipped, and so is what
129
+ `bun run generate` writes, `src/generated/`.
130
+
131
+ ```sh
132
+ bun run check # lint, format and sort imports, fixing what it can
133
+ bun run lint # lint only
134
+ bun run format # format only, in place
135
+ bun run check:ci # what CI runs: changes nothing, fails on an error
136
+ bun run verify # generate --check, check:ci, typecheck, then test
137
+ ```
138
+
139
+ `bun run check:ci`, not `bun ci`: `bun ci` is Bun's frozen-lockfile
140
+ install. In VS Code, `.vscode/` recommends Biome's extension and formats
141
+ on save with it.
142
+
143
+ `@biomejs/biome` is pinned exactly, since a release of Biome may format
144
+ differently. To move it:
145
+
146
+ ```sh
147
+ bun add --dev --exact @biomejs/biome@latest
148
+ bunx biome migrate --write
149
+ ```
150
+
151
+ ## Build
152
+
153
+ `bun run build` bundles the server, its dependencies and `schema.graphql`
154
+ into one file, `dist/server.js`, minified, with its source map beside it, and
155
+ `bun start` runs it: what production and the image run.
156
+
157
+ ```sh
158
+ bun run build # dist/server.js and dist/server.js.map
159
+ bun start # NODE_ENV=production bun dist/server.js
160
+ ```
161
+
162
+ `bun start` before any build fails with `Module not found
163
+ "dist/server.js"`: build first. `dist/` needs Bun and nothing else, no
164
+ `node_modules`. A dependency that cannot be bundled, a native addon, is left
165
+ out with `--external <name>` in the `build` script, and must then be
166
+ installed beside `dist/`.
167
+
168
+ ## Docker
169
+
170
+ The `Dockerfile` builds in a stage of its own, on `oven/bun:1`, and runs
171
+ on `oven/bun:1-alpine`. The build stage installs every dependency with
172
+ `--frozen-lockfile`, from the `bun.lock` that `bun install` wrote (commit
173
+ it), and runs `bun run build`. The image holds `dist/` alone, no
174
+ `node_modules` and no `src/`, and runs `bun --no-install dist/server.js` as
175
+ its non-root `bun` user. `listen` drains the app and exits on `SIGTERM`,
176
+ so `docker stop` is immediate.
177
+
178
+ ```sh
179
+ docker build -t my-graphql-api .
180
+ docker run --rm -p 3000:3000 my-graphql-api
181
+ ```
182
+
183
+ Next: [`@alxia/graphql`'s guide](https://github.com/softistx/alxia/tree/develop/packages/graphql/docs):
184
+ Yoga's plugins, the IDE, the typed context. And
185
+ [`@alxia/core`'s](https://github.com/softistx/alxia/tree/develop/packages/core/docs).
@@ -0,0 +1,32 @@
1
+ {
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
+ "vcs": {
4
+ "enabled": true,
5
+ "clientKind": "git",
6
+ "useIgnoreFile": true
7
+ },
8
+ "files": {
9
+ "includes": ["**", "!!**/dist", "!!**/src/generated"]
10
+ },
11
+ "formatter": {
12
+ "enabled": true,
13
+ "indentStyle": "space"
14
+ },
15
+ "linter": {
16
+ "enabled": true,
17
+ "rules": {
18
+ "preset": "recommended",
19
+ "complexity": {
20
+ "useLiteralKeys": "off"
21
+ }
22
+ }
23
+ },
24
+ "assist": {
25
+ "enabled": true,
26
+ "actions": {
27
+ "source": {
28
+ "organizeImports": "on"
29
+ }
30
+ }
31
+ }
32
+ }
@@ -0,0 +1,22 @@
1
+ import type { CodegenConfig } from "@graphql-codegen/cli";
2
+
3
+ // `bun run generate` writes src/generated/resolvers.ts from schema.graphql:
4
+ // the schema's types and `Resolvers`, whose context is the app's own
5
+ // (`Context`, src/context.ts) and whose `Note` is the record the store holds
6
+ // (`NoteRecord`), so a resolver returns the record and `Note.author` reads it.
7
+ const config: CodegenConfig = {
8
+ schema: "schema.graphql",
9
+ generates: {
10
+ "src/generated/resolvers.ts": {
11
+ plugins: ["typescript", "typescript-resolvers"],
12
+ config: {
13
+ contextType: "../context#Context",
14
+ mappers: { Note: "../store#NoteRecord" },
15
+ useTypeImports: true,
16
+ useIndexSignature: true,
17
+ },
18
+ },
19
+ },
20
+ };
21
+
22
+ export default config;
@@ -0,0 +1,6 @@
1
+ node_modules
2
+ dist
3
+ *.log
4
+ .DS_Store
5
+ .env
6
+ .env.local
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "my-graphql-api",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "generate": "graphql-codegen --config codegen.ts",
7
+ "dev": "NODE_ENV=development bun --watch src/server.ts",
8
+ "build": "bun build src/server.ts --target=bun --outdir=dist --minify --sourcemap=linked",
9
+ "start": "NODE_ENV=production bun dist/server.js",
10
+ "test": "bun test",
11
+ "typecheck": "tsc --noEmit",
12
+ "lint": "biome lint",
13
+ "format": "biome format --write",
14
+ "check": "biome check --write",
15
+ "check:ci": "biome ci",
16
+ "verify": "bun run generate --check && bun run check:ci && bun run typecheck && bun run test"
17
+ },
18
+ "dependencies": {
19
+ "@alxia/core": "workspace:^",
20
+ "@alxia/env": "workspace:^",
21
+ "@alxia/graphql": "workspace:^",
22
+ "dataloader": "^2.2.3",
23
+ "graphql": "^16.11.0",
24
+ "graphql-yoga": "^5.16.0",
25
+ "zod": "^4.5.4"
26
+ },
27
+ "devDependencies": {
28
+ "@biomejs/biome": "2.5.15",
29
+ "@graphql-codegen/cli": "7.4.3",
30
+ "@graphql-codegen/typescript": "6.1.0",
31
+ "@graphql-codegen/typescript-resolvers": "6.1.0",
32
+ "@types/bun": "^1.4.2",
33
+ "typescript": "^6.0.3"
34
+ }
35
+ }
@@ -0,0 +1,26 @@
1
+ type Query {
2
+ "The signed-in user, or null with no valid token."
3
+ me: User
4
+ notes: [Note!]!
5
+ }
6
+
7
+ type Mutation {
8
+ "Needs a token: `Authorization: Bearer ada-token`."
9
+ addNote(text: String!): Note!
10
+ }
11
+
12
+ type Subscription {
13
+ "Each note added, as it is added, over server-sent events."
14
+ noteAdded: Note!
15
+ }
16
+
17
+ type User {
18
+ id: ID!
19
+ name: String!
20
+ }
21
+
22
+ type Note {
23
+ id: ID!
24
+ text: String!
25
+ author: User!
26
+ }