@alxia/create 0.1.7 → 0.2.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 (65) 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 +15 -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 +171 -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 +34 -0
  42. package/templates/graphql/schema.graphql +26 -0
  43. package/templates/graphql/src/app.spec.ts +119 -0
  44. package/templates/graphql/src/app.ts +14 -0
  45. package/templates/graphql/src/context.ts +24 -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/resolvers.ts +42 -0
  50. package/templates/graphql/src/schema.ts +6 -0
  51. package/templates/graphql/src/server.ts +10 -0
  52. package/templates/graphql/src/store.ts +25 -0
  53. package/templates/graphql/tsconfig.json +25 -0
  54. package/templates/minimal/.dockerignore +6 -0
  55. package/templates/minimal/.vscode/extensions.json +3 -0
  56. package/templates/minimal/.vscode/settings.json +8 -0
  57. package/templates/minimal/Dockerfile +26 -0
  58. package/templates/minimal/README.md +107 -0
  59. package/templates/minimal/_biome.json +32 -0
  60. package/templates/minimal/gitignore +6 -0
  61. package/templates/minimal/package.json +25 -0
  62. package/templates/minimal/src/index.spec.ts +12 -0
  63. package/templates/minimal/src/index.ts +17 -0
  64. package/templates/minimal/tsconfig.json +25 -0
  65. package/templates/react-router/package.json +2 -2
@@ -0,0 +1,119 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { app } from "./app";
3
+ import { db, pubsub } from "./store";
4
+
5
+ interface Result {
6
+ data?: Record<string, unknown>;
7
+ errors?: { message: string; extensions?: { code?: string } }[];
8
+ }
9
+
10
+ // POST /graphql in process, as a client would: no port.
11
+ async function query(
12
+ source: string,
13
+ options: { token?: string; variables?: Record<string, unknown> } = {},
14
+ ): Promise<Result> {
15
+ const response = await app.request("/graphql", {
16
+ method: "POST",
17
+ headers: {
18
+ "content-type": "application/json",
19
+ ...(options.token && { authorization: `Bearer ${options.token}` }),
20
+ },
21
+ body: JSON.stringify({ query: source, variables: options.variables }),
22
+ });
23
+ return response.json();
24
+ }
25
+
26
+ const ADD =
27
+ "mutation ($text: String!) { addNote(text: $text) { id text author { name } } }";
28
+
29
+ describe("queries", () => {
30
+ test("answers { __typename }", async () => {
31
+ expect(await query("{ __typename }")).toEqual({
32
+ data: { __typename: "Query" },
33
+ });
34
+ });
35
+
36
+ test("me is null with no token, and the user a token names", async () => {
37
+ expect((await query("{ me { name } }")).data).toEqual({ me: null });
38
+ expect((await query("{ me { name } }", { token: "wrong" })).data).toEqual({
39
+ me: null,
40
+ });
41
+ expect(
42
+ (await query("{ me { name } }", { token: "ada-token" })).data,
43
+ ).toEqual({
44
+ me: { name: "Ada" },
45
+ });
46
+ });
47
+ });
48
+
49
+ describe("mutations", () => {
50
+ test("addNote refuses a request with no token", async () => {
51
+ const { errors } = await query(ADD, { variables: { text: "Hello" } });
52
+ expect(errors?.[0]?.extensions?.code).toBe("UNAUTHENTICATED");
53
+ });
54
+
55
+ test("addNote stores the note for the viewer, and notes lists it", async () => {
56
+ const added = await query(ADD, {
57
+ token: "ada-token",
58
+ variables: { text: "Hello" },
59
+ });
60
+ expect(added.errors).toBeUndefined();
61
+ expect(added.data).toEqual({
62
+ addNote: {
63
+ id: expect.any(String),
64
+ text: "Hello",
65
+ author: { name: "Ada" },
66
+ },
67
+ });
68
+ const listed = await query("{ notes { text author { id } } }");
69
+ expect(listed.data?.["notes"]).toContainEqual({
70
+ text: "Hello",
71
+ author: { id: "1" },
72
+ });
73
+ expect(db.notes.length).toBeGreaterThan(0);
74
+ });
75
+
76
+ test("a query the schema does not have is refused", async () => {
77
+ expect((await query("{ nothing }")).errors?.[0]?.message).toContain(
78
+ "nothing",
79
+ );
80
+ });
81
+ });
82
+
83
+ describe("subscriptions", () => {
84
+ test("noteAdded streams each note over server-sent events", async () => {
85
+ const response = await app.request("/graphql", {
86
+ method: "POST",
87
+ headers: {
88
+ "content-type": "application/json",
89
+ accept: "text/event-stream",
90
+ },
91
+ body: JSON.stringify({ query: "subscription { noteAdded { text } }" }),
92
+ });
93
+ expect(response.headers.get("content-type")).toContain("text/event-stream");
94
+ const reader = response.body?.getReader();
95
+ if (reader === undefined) throw new Error("no body");
96
+ // Publish until the stream carries it: the subscription starts as it is read.
97
+ const publish = setInterval(
98
+ () =>
99
+ pubsub.publish("noteAdded", {
100
+ id: "9",
101
+ text: "Streamed",
102
+ authorId: "1",
103
+ }),
104
+ 20,
105
+ );
106
+ try {
107
+ let seen = "";
108
+ while (!seen.includes("Streamed")) {
109
+ const { done, value } = await reader.read();
110
+ if (done) throw new Error(`the stream ended: ${seen}`);
111
+ seen += new TextDecoder().decode(value);
112
+ }
113
+ expect(seen).toContain('"noteAdded":{"text":"Streamed"}');
114
+ } finally {
115
+ clearInterval(publish);
116
+ await reader.cancel();
117
+ }
118
+ });
119
+ });
@@ -0,0 +1,14 @@
1
+ import { health } from "@alxia/core";
2
+ import { graphql } from "@alxia/graphql";
3
+ import { base } from "./context";
4
+ import { schema } from "./schema";
5
+
6
+ // The probes (GET /health, GET /ready), then POST and GET /graphql, behind
7
+ // the base's middlewares. Subscriptions are served over server-sent events.
8
+ // The IDE (GraphiQL, on a browser's GET) follows alxia's dev switch: on
9
+ // under `bun dev` (NODE_ENV=development), off otherwise.
10
+ export const app = base
11
+ .plugin(health())
12
+ .plugin((app) => graphql(app, { schema }));
13
+
14
+ export type App = typeof app;
@@ -0,0 +1,24 @@
1
+ import { alxia, defineMiddleware } from "@alxia/core";
2
+ import type { GraphQLContext } from "@alxia/graphql";
3
+ import { env } from "./env";
4
+ import { db } from "./store";
5
+
6
+ // Reads the bearer token: `viewer` is the user it names, or null. A query
7
+ // may be anonymous, so this refuses nothing; a resolver that needs a user
8
+ // refuses (`addNote`). `viewer` is typed in every resolver.
9
+ const viewerOf = defineMiddleware(({ request }, next) => {
10
+ const token = request.headers
11
+ .get("authorization")
12
+ ?.match(/^Bearer (.+)$/i)?.[1];
13
+ const id = token === undefined ? undefined : db.tokens.get(token);
14
+ return next({
15
+ viewer: (id === undefined ? undefined : db.users.get(id)) ?? null,
16
+ });
17
+ });
18
+
19
+ // The base: what every resolver reads, decorated or derived here.
20
+ export const base = alxia().decorate({ env, db }).use(viewerOf);
21
+
22
+ // A resolver's context: Yoga's, and the base's (`env`, `db`, `viewer`).
23
+ // The generated `Resolvers` takes it (codegen.ts: `contextType`).
24
+ export type Context = GraphQLContext<typeof base>;
@@ -0,0 +1,8 @@
1
+ import { defineEnv } from "@alxia/env";
2
+ import { z } from "zod";
3
+
4
+ // Checked once, when this module is first imported: a malformed variable
5
+ // stops the process, with every issue, before it listens.
6
+ export const env = defineEnv({
7
+ PORT: z.coerce.number().default(3000),
8
+ });
@@ -0,0 +1,180 @@
1
+ import type { GraphQLResolveInfo } from 'graphql';
2
+ import type { NoteRecord } from '../store';
3
+ import type { Context } from '../context';
4
+ export type Maybe<T> = T | null;
5
+ export type InputMaybe<T> = Maybe<T>;
6
+ export type RequireFields<T, K extends keyof T> = Omit<T, K> & { [P in K]-?: NonNullable<T[P]> };
7
+ /** All built-in and custom scalars, mapped to their actual values */
8
+ export type Scalars = {
9
+ ID: { input: string; output: string; }
10
+ String: { input: string; output: string; }
11
+ Boolean: { input: boolean; output: boolean; }
12
+ Int: { input: number; output: number; }
13
+ Float: { input: number; output: number; }
14
+ };
15
+
16
+ export type Mutation = {
17
+ __typename?: 'Mutation';
18
+ /** Needs a token: `Authorization: Bearer ada-token`. */
19
+ addNote: Note;
20
+ };
21
+
22
+
23
+ export type MutationAddNoteArgs = {
24
+ text: Scalars['String']['input'];
25
+ };
26
+
27
+ export type Note = {
28
+ __typename?: 'Note';
29
+ author: User;
30
+ id: Scalars['ID']['output'];
31
+ text: Scalars['String']['output'];
32
+ };
33
+
34
+ export type Query = {
35
+ __typename?: 'Query';
36
+ /** The signed-in user, or null with no valid token. */
37
+ me?: Maybe<User>;
38
+ notes: Array<Note>;
39
+ };
40
+
41
+ export type Subscription = {
42
+ __typename?: 'Subscription';
43
+ /** Each note added, as it is added, over server-sent events. */
44
+ noteAdded: Note;
45
+ };
46
+
47
+ export type User = {
48
+ __typename?: 'User';
49
+ id: Scalars['ID']['output'];
50
+ name: Scalars['String']['output'];
51
+ };
52
+
53
+ export type WithIndex<TObject> = TObject & Record<string, any>;
54
+ export type ResolversObject<TObject> = WithIndex<TObject>;
55
+
56
+ export type ResolverTypeWrapper<T> = Promise<T> | T;
57
+
58
+
59
+ export type ResolverWithResolve<TResult, TParent, TContext, TArgs> = {
60
+ resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
61
+ };
62
+ export type Resolver<TResult, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>, TArgs = Record<PropertyKey, never>> = ResolverFn<TResult, TParent, TContext, TArgs> | ResolverWithResolve<TResult, TParent, TContext, TArgs>;
63
+
64
+ export type ResolverFn<TResult, TParent, TContext, TArgs> = (
65
+ parent: TParent,
66
+ args: TArgs,
67
+ context: TContext,
68
+ info: GraphQLResolveInfo
69
+ ) => Promise<TResult> | TResult;
70
+
71
+ export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
72
+ parent: TParent,
73
+ args: TArgs,
74
+ context: TContext,
75
+ info: GraphQLResolveInfo
76
+ ) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>;
77
+
78
+ export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
79
+ parent: TParent,
80
+ args: TArgs,
81
+ context: TContext,
82
+ info: GraphQLResolveInfo
83
+ ) => TResult | Promise<TResult>;
84
+
85
+ export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> {
86
+ subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>;
87
+ resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>;
88
+ }
89
+
90
+ export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
91
+ subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
92
+ resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
93
+ }
94
+
95
+ export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
96
+ | SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
97
+ | SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
98
+
99
+ export type SubscriptionResolver<TResult, TKey extends string, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>, TArgs = Record<PropertyKey, never>> =
100
+ | ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
101
+ | SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
102
+
103
+ export type TypeResolveFn<TTypes, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>> = (
104
+ parent: TParent,
105
+ context: TContext,
106
+ info: GraphQLResolveInfo
107
+ ) => Maybe<TTypes> | Promise<Maybe<TTypes>>;
108
+
109
+ export type IsTypeOfResolverFn<T = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>> = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise<boolean>;
110
+
111
+ export type NextResolverFn<T> = () => Promise<T>;
112
+
113
+ export type DirectiveResolverFn<TResult = Record<PropertyKey, never>, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>, TArgs = Record<PropertyKey, never>> = (
114
+ next: NextResolverFn<TResult>,
115
+ parent: TParent,
116
+ args: TArgs,
117
+ context: TContext,
118
+ info: GraphQLResolveInfo
119
+ ) => TResult | Promise<TResult>;
120
+
121
+
122
+
123
+
124
+
125
+ /** Mapping between all available schema types and the resolvers types */
126
+ export type ResolversTypes = ResolversObject<{
127
+ Boolean: ResolverTypeWrapper<Scalars['Boolean']['output']>;
128
+ ID: ResolverTypeWrapper<Scalars['ID']['output']>;
129
+ Mutation: ResolverTypeWrapper<Record<PropertyKey, never>>;
130
+ Note: ResolverTypeWrapper<NoteRecord>;
131
+ Query: ResolverTypeWrapper<Record<PropertyKey, never>>;
132
+ String: ResolverTypeWrapper<Scalars['String']['output']>;
133
+ Subscription: ResolverTypeWrapper<Record<PropertyKey, never>>;
134
+ User: ResolverTypeWrapper<User>;
135
+ }>;
136
+
137
+ /** Mapping between all available schema types and the resolvers parents */
138
+ export type ResolversParentTypes = ResolversObject<{
139
+ Boolean: Scalars['Boolean']['output'];
140
+ ID: Scalars['ID']['output'];
141
+ Mutation: Record<PropertyKey, never>;
142
+ Note: NoteRecord;
143
+ Query: Record<PropertyKey, never>;
144
+ String: Scalars['String']['output'];
145
+ Subscription: Record<PropertyKey, never>;
146
+ User: User;
147
+ }>;
148
+
149
+ export type MutationResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']> = ResolversObject<{
150
+ addNote?: Resolver<ResolversTypes['Note'], ParentType, ContextType, RequireFields<MutationAddNoteArgs, 'text'>>;
151
+ }>;
152
+
153
+ export type NoteResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Note'] = ResolversParentTypes['Note']> = ResolversObject<{
154
+ author?: Resolver<ResolversTypes['User'], ParentType, ContextType>;
155
+ id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>;
156
+ text?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
157
+ }>;
158
+
159
+ export type QueryResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = ResolversObject<{
160
+ me?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
161
+ notes?: Resolver<Array<ResolversTypes['Note']>, ParentType, ContextType>;
162
+ }>;
163
+
164
+ export type SubscriptionResolvers<ContextType = Context, ParentType extends ResolversParentTypes['Subscription'] = ResolversParentTypes['Subscription']> = ResolversObject<{
165
+ noteAdded?: SubscriptionResolver<ResolversTypes['Note'], "noteAdded", ParentType, ContextType>;
166
+ }>;
167
+
168
+ export type UserResolvers<ContextType = Context, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = ResolversObject<{
169
+ id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>;
170
+ name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
171
+ }>;
172
+
173
+ export type Resolvers<ContextType = Context> = ResolversObject<{
174
+ Mutation?: MutationResolvers<ContextType>;
175
+ Note?: NoteResolvers<ContextType>;
176
+ Query?: QueryResolvers<ContextType>;
177
+ Subscription?: SubscriptionResolvers<ContextType>;
178
+ User?: UserResolvers<ContextType>;
179
+ }>;
180
+
@@ -0,0 +1,6 @@
1
+ // `import typeDefs from "../schema.graphql" with { type: "text" }`: Bun
2
+ // reads the file as text, and `bun run build` puts it in dist/server.js.
3
+ declare module "*.graphql" {
4
+ const source: string;
5
+ export default source;
6
+ }
@@ -0,0 +1,42 @@
1
+ import { GraphQLError } from "graphql";
2
+ import type { Resolvers } from "./generated/resolvers";
3
+ import { type NoteRecord, pubsub } from "./store";
4
+
5
+ // `Resolvers` is generated from schema.graphql: a field the schema lacks, or
6
+ // a return the schema's type refuses, is a compile error.
7
+ export const resolvers: Resolvers = {
8
+ Query: {
9
+ me: (_, __, { viewer }) => viewer,
10
+ notes: (_, __, { db }) => db.notes,
11
+ },
12
+ Mutation: {
13
+ addNote: (_, { text }, { viewer, db }) => {
14
+ if (viewer === null) {
15
+ throw new GraphQLError("Sign in to add a note", {
16
+ extensions: { code: "UNAUTHENTICATED" },
17
+ });
18
+ }
19
+ const note = {
20
+ id: String(db.notes.length + 1),
21
+ text,
22
+ authorId: viewer.id,
23
+ };
24
+ db.notes.push(note);
25
+ pubsub.publish("noteAdded", note);
26
+ return note;
27
+ },
28
+ },
29
+ Subscription: {
30
+ noteAdded: {
31
+ subscribe: () => pubsub.subscribe("noteAdded"),
32
+ resolve: (note: NoteRecord) => note,
33
+ },
34
+ },
35
+ Note: {
36
+ author: (note, _, { db }) => {
37
+ const author = db.users.get(note.authorId);
38
+ if (author === undefined) throw new Error(`No user ${note.authorId}`);
39
+ return author;
40
+ },
41
+ },
42
+ };
@@ -0,0 +1,6 @@
1
+ import { createSchema } from "graphql-yoga";
2
+ import typeDefs from "../schema.graphql" with { type: "text" };
3
+ import type { Context } from "./context";
4
+ import { resolvers } from "./resolvers";
5
+
6
+ export const schema = createSchema<Context>({ typeDefs, resolvers });
@@ -0,0 +1,10 @@
1
+ import { app } from "./app";
2
+ import { env } from "./env";
3
+
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,25 @@
1
+ import { createPubSub } from "graphql-yoga";
2
+
3
+ export interface UserRecord {
4
+ id: string;
5
+ name: string;
6
+ }
7
+
8
+ export interface NoteRecord {
9
+ id: string;
10
+ text: string;
11
+ authorId: string;
12
+ }
13
+
14
+ // An in-memory store, for the example: swap it for your database.
15
+ export const db = {
16
+ users: new Map<string, UserRecord>([["1", { id: "1", name: "Ada" }]]),
17
+ // Bearer tokens and the user each one is: for development. Use a real
18
+ // session or a JWT (`@alxia/jwt`'s `bearer`) outside it.
19
+ tokens: new Map([["ada-token", "1"]]),
20
+ notes: [] as NoteRecord[],
21
+ };
22
+
23
+ // What a subscription streams: `addNote` publishes, `noteAdded` subscribes.
24
+ // One process only: across several, back it with a broker.
25
+ export const pubsub = createPubSub<{ noteAdded: [NoteRecord] }>();
@@ -0,0 +1,25 @@
1
+ {
2
+ "compilerOptions": {
3
+ "types": ["bun"],
4
+ "lib": ["ESNext", "DOM"],
5
+ "target": "ESNext",
6
+ "module": "ESNext",
7
+ "moduleDetection": "force",
8
+ "moduleResolution": "bundler",
9
+ "verbatimModuleSyntax": true,
10
+ "noEmit": true,
11
+ "skipLibCheck": true,
12
+ "resolveJsonModule": true,
13
+ "strict": true,
14
+ "noImplicitOverride": true,
15
+ "noImplicitReturns": true,
16
+ "noFallthroughCasesInSwitch": true,
17
+ "noUncheckedIndexedAccess": true,
18
+ "exactOptionalPropertyTypes": true,
19
+ "noPropertyAccessFromIndexSignature": true,
20
+ "noUnusedLocals": true,
21
+ "noUnusedParameters": true,
22
+ "forceConsistentCasingInFileNames": true
23
+ },
24
+ "include": ["src"]
25
+ }
@@ -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
+ {
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/index.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/index.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 lighter: the
18
+ # bundle is JavaScript, which runs the same on musl. A native addon built
19
+ # 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/index.js"]
@@ -0,0 +1,107 @@
1
+ # A minimal alxia app
2
+
3
+ An [alxia](https://github.com/softistx/alxia) app in one route, made with
4
+ `bun create @alxia`: the quickest way to see alxia run. Nothing else is set
5
+ up: no OpenAPI, no code generation, no validator.
6
+
7
+ ```ts
8
+ // src/index.ts
9
+ export const app = alxia().get("/", ({ reply }) =>
10
+ reply(200, { hello: "world" }),
11
+ );
12
+ ```
13
+
14
+ ```sh
15
+ bun dev # NODE_ENV=development: http://localhost:3000, reloaded on every change
16
+ curl localhost:3000 # {"hello":"world"}
17
+ ```
18
+
19
+ `bun dev` sets `NODE_ENV=development`, alxia's dev switch: `listen`
20
+ prints the route table, a 404 hints at the closest route and a 500 shows
21
+ its error. Under any other `NODE_ENV`, none of them is.
22
+
23
+ - `src/index.ts`: the app, and `app.listen()` on `PORT` (3000 by default)
24
+ when the file is run, not when a test imports it. `listen` shuts the app
25
+ down gracefully on `SIGINT` and `SIGTERM`.
26
+ - `src/index.spec.ts`: `app.request()`, no port: the request goes through
27
+ the app and the response comes back.
28
+ - `biome.json`: Biome's lint and format settings ([Lint and format](#lint-and-format)).
29
+
30
+ ## Where next
31
+
32
+ - Add a route: `.get("/users/:id", ({ params, reply }) => …)` after the
33
+ first. Order is meaning: a middleware given to `use` applies to the routes
34
+ after it.
35
+ - Validate a body with `validate` and Zod (`bun add zod`), see
36
+ [Routes and validation](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/routes.md).
37
+ - Describe the API first, with an OpenAPI document and the operations
38
+ generated from it: `bun create @alxia my-service --template api`.
39
+ - Serve GraphQL: `bun create @alxia my-service --template graphql`.
40
+
41
+ ## Test
42
+
43
+ ```sh
44
+ bun test # src/index.spec.ts: in process, no port
45
+ bun run typecheck
46
+ ```
47
+
48
+ ## Lint and format
49
+
50
+ [Biome](https://biomejs.dev) lints and formats the project, as `biome.json`
51
+ sets it: Biome's recommended rules, spaces, double quotes, imports
52
+ sorted. What the build writes, `dist/`, is skipped.
53
+
54
+ ```sh
55
+ bun run check # lint, format and sort imports, fixing what it can
56
+ bun run lint # lint only
57
+ bun run format # format only, in place
58
+ bun run check:ci # what CI runs: changes nothing, fails on an error
59
+ bun run verify # check:ci, typecheck, then test
60
+ ```
61
+
62
+ `bun run check:ci`, not `bun ci`: `bun ci` is Bun's frozen-lockfile
63
+ install. In VS Code, `.vscode/` recommends Biome's extension and formats
64
+ on save with it.
65
+
66
+ `@biomejs/biome` is pinned exactly, since a release of Biome may format
67
+ differently. To move it:
68
+
69
+ ```sh
70
+ bun add --dev --exact @biomejs/biome@latest
71
+ bunx biome migrate --write
72
+ ```
73
+
74
+ ## Build
75
+
76
+ `bun run build` bundles the server and its dependencies into one file,
77
+ `dist/index.js`, minified, with its source map beside it, and `bun start`
78
+ runs it: what production and the image run.
79
+
80
+ ```sh
81
+ bun run build # dist/index.js and dist/index.js.map
82
+ bun start # NODE_ENV=production bun dist/index.js
83
+ ```
84
+
85
+ `bun start` before any build fails with `Module not found
86
+ "dist/index.js"`: build first. `dist/` needs Bun and nothing else, no
87
+ `node_modules`. A dependency that cannot be bundled, a native addon, is
88
+ left out with `--external <name>` in the `build` script, and must then be
89
+ installed beside `dist/`.
90
+
91
+ ## Docker
92
+
93
+ The `Dockerfile` builds in a stage of its own, on `oven/bun:1`, and runs
94
+ on `oven/bun:1-alpine`. The build stage installs every dependency with
95
+ `--frozen-lockfile`, from the `bun.lock` that `bun install` wrote (commit
96
+ it), and runs `bun run build`. The image holds `dist/` alone, no
97
+ `node_modules` and no `src/`, and runs `bun --no-install dist/index.js` as
98
+ its non-root `bun` user. `listen` drains the app and exits on `SIGTERM`,
99
+ so `docker stop` is immediate.
100
+
101
+ ```sh
102
+ docker build -t my-app .
103
+ docker run --rm -p 3000:3000 my-app
104
+ ```
105
+
106
+ Next: [Getting started](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/getting-started.md)
107
+ and the rest of [`@alxia/core`'s guide](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"]
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,6 @@
1
+ node_modules
2
+ dist
3
+ *.log
4
+ .DS_Store
5
+ .env
6
+ .env.local