create-amoxi-app 0.0.0-stage → 0.5.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 (38) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +5 -0
  3. package/README.md +14 -2
  4. package/index.js +319 -0
  5. package/package.json +40 -4
  6. package/templates/LICENSE +22 -0
  7. package/templates/agent/README.md +34 -0
  8. package/templates/agent/src/agent/assistant.ts +18 -0
  9. package/templates/agent/src/agent/note-tools.ts +33 -0
  10. package/templates/agent/src/islands/Assistant.tsx +69 -0
  11. package/templates/agent/src/islands/NoteList.tsx +17 -0
  12. package/templates/agent/src/pages/assistant-page.tsx +27 -0
  13. package/templates/agent/src/styles/assistant.css +33 -0
  14. package/templates/agent/src/ui/layout.tsx +36 -0
  15. package/templates/agent/test/agent.test.ts +67 -0
  16. package/templates/api/src/notes/note-controller.ts +19 -0
  17. package/templates/api/src/notes/note-service.ts +27 -0
  18. package/templates/api/src/notes/note.ts +19 -0
  19. package/templates/api/test/app.test.ts +25 -0
  20. package/templates/shared/Dockerfile +38 -0
  21. package/templates/shared/README.md +25 -0
  22. package/templates/shared/_dockerignore +10 -0
  23. package/templates/shared/_env.example +4 -0
  24. package/templates/shared/_gitignore +14 -0
  25. package/templates/shared/application-production.json +3 -0
  26. package/templates/shared/application.json +4 -0
  27. package/templates/shared/src/main.ts +8 -0
  28. package/templates/shared/tsconfig.json +21 -0
  29. package/templates/web/public/favicon.svg +1 -0
  30. package/templates/web/src/islands/AddNote.tsx +40 -0
  31. package/templates/web/src/islands/Counter.tsx +11 -0
  32. package/templates/web/src/notes/note-controller.ts +19 -0
  33. package/templates/web/src/notes/note-service.ts +27 -0
  34. package/templates/web/src/notes/note.ts +19 -0
  35. package/templates/web/src/pages/home-page.tsx +105 -0
  36. package/templates/web/src/styles/app.css +105 -0
  37. package/templates/web/src/ui/layout.tsx +34 -0
  38. package/templates/web/test/app.test.ts +33 -0
@@ -0,0 +1,33 @@
1
+ import { Singleton } from 'amoxi';
2
+ import { Tool, type ToolContext } from 'amoxi/ai';
3
+ import type { Note } from '../notes/note';
4
+ import { NoteService } from '../notes/note-service';
5
+
6
+ /**
7
+ * Tools the assistant can call. Their JSON Schemas and argument validators are generated at
8
+ * build time from the parameter types and JSDoc, like request-body validation.
9
+ */
10
+ @Singleton()
11
+ export class NoteTools {
12
+ constructor(private readonly notes: NoteService) {}
13
+
14
+ /** List the saved notes, newest first, and show them as cards. */
15
+ @Tool({ readOnly: true })
16
+ listNotes(_input: {}, ctx: ToolContext): { notes: Note[] } {
17
+ const notes = this.notes.list();
18
+ ctx.ui('NoteList', { title: 'Your notes', notes });
19
+ return { notes };
20
+ }
21
+
22
+ @Tool('Save a new note with the given text')
23
+ addNote(input: {
24
+ /**
25
+ * What to write down, e.g. "Buy coffee beans"
26
+ * @minLength 1
27
+ * @maxLength 280
28
+ */
29
+ content: string;
30
+ }): Note {
31
+ return this.notes.add({ text: input.content });
32
+ }
33
+ }
@@ -0,0 +1,69 @@
1
+ import { agentChat, For, mountComponent, type ChatItem } from 'amoxi';
2
+
3
+ /**
4
+ * A chat with the `assistant` agent. Answers stream in token by token; tool steps, approvals and
5
+ * components the agent shows (generative UI) appear in the conversation.
6
+ */
7
+ export default function Assistant(props: { examples: string[] }) {
8
+ const chat = agentChat('assistant');
9
+ let input: HTMLInputElement | undefined;
10
+
11
+ const send = (text: string): void => {
12
+ void chat.send(text);
13
+ if (input) input.value = '';
14
+ };
15
+
16
+ const render = (item: ChatItem) => {
17
+ switch (item.kind) {
18
+ case 'user':
19
+ return <p class="msg user">{item.text}</p>;
20
+ case 'assistant':
21
+ return <p class="msg assistant">{item.text}</p>;
22
+ case 'tool':
23
+ return <p class="msg step">{item.status === 'running' ? 'Working: ' : 'Used '}{item.tool.replace(/_/g, ' ')}</p>;
24
+ case 'ui':
25
+ return <div class="msg ui" ref={(el: HTMLElement) => mountComponent(el, item.component, item.props)} />;
26
+ case 'approval':
27
+ return (
28
+ <div class="msg approval">
29
+ <p>Allow “{item.tool.replace(/_/g, ' ')}”?</p>
30
+ {item.status === 'pending' ? (
31
+ <p>
32
+ <button type="button" onClick={() => void chat.decide(item.callId, true)}>Allow</button>{' '}
33
+ <button type="button" onClick={() => void chat.decide(item.callId, false)}>Decline</button>
34
+ </p>
35
+ ) : (
36
+ <p class="muted">{item.status === 'approved' ? 'Allowed' : 'Declined'}</p>
37
+ )}
38
+ </div>
39
+ );
40
+ default:
41
+ return <p class={`msg ${item.kind}`}>{'text' in item ? item.text : ''}</p>;
42
+ }
43
+ };
44
+
45
+ return (
46
+ <section class="assistant" aria-label="Assistant">
47
+ <div class="conversation" aria-live="polite">
48
+ <For each={chat.items} key={(i) => i.id}>{render}</For>
49
+ {() => (chat.status() === 'working' ? <p class="msg step">Thinking…</p> : null)}
50
+ </div>
51
+ <div class="examples">
52
+ {props.examples.map((e) => (
53
+ <button type="button" onClick={() => send(e)}>{e}</button>
54
+ ))}
55
+ </div>
56
+ <form
57
+ class="composer"
58
+ onSubmit={(e: Event) => {
59
+ e.preventDefault();
60
+ if (input?.value.trim()) send(input.value);
61
+ }}
62
+ >
63
+ <label for="message" class="visually-hidden">Message</label>
64
+ <input id="message" ref={(el: HTMLInputElement) => (input = el)} placeholder="Ask about your notes…" autocomplete="off" />
65
+ <button type="submit" disabled={() => chat.status() !== 'idle'}>Send</button>
66
+ </form>
67
+ </section>
68
+ );
69
+ }
@@ -0,0 +1,17 @@
1
+ /** @generative Shows a list of notes as cards */
2
+ export default function NoteList(props: { title: string; notes: Array<{ id: number; text: string; createdAt: string }> }) {
3
+ return (
4
+ <section class="note-cards" aria-label={props.title}>
5
+ <h3>{props.title}</h3>
6
+ {props.notes.length === 0 ? <p class="muted">No notes yet.</p> : null}
7
+ <ul>
8
+ {props.notes.map((n) => (
9
+ <li>
10
+ <p>{n.text}</p>
11
+ <time datetime={n.createdAt}>{new Date(n.createdAt).toLocaleString()}</time>
12
+ </li>
13
+ ))}
14
+ </ul>
15
+ </section>
16
+ );
17
+ }
@@ -0,0 +1,27 @@
1
+ import { Controller, Island, Page } from 'amoxi';
2
+ import Assistant from '../islands/Assistant';
3
+ import { Layout } from '../ui/layout';
4
+
5
+ @Controller()
6
+ export class AssistantPage {
7
+ @Page('/assistant')
8
+ assistant() {
9
+ return (
10
+ <Layout title="Assistant" active="assistant">
11
+ <div class="split">
12
+ <section class="intro">
13
+ <h1>Assistant</h1>
14
+ <p>
15
+ An AI agent with tools from <code>src/agent/</code>. Without an API key it uses Amoxi's offline demo model; put{' '}
16
+ <code>ANTHROPIC_API_KEY</code> or <code>OPENAI_API_KEY</code> in <code>.env</code> to use a real one.
17
+ </p>
18
+ <p>
19
+ Agents also answer over HTTP: <code>POST /agents/assistant/runs</code>.
20
+ </p>
21
+ </section>
22
+ <Island of={Assistant} examples={['Show my notes', 'Add a note "Buy coffee beans"']} />
23
+ </div>
24
+ </Layout>
25
+ );
26
+ }
27
+ }
@@ -0,0 +1,33 @@
1
+ /* The assistant chat: uses the colours defined in app.css. */
2
+ .assistant {
3
+ display: grid;
4
+ gap: 0.75rem;
5
+ background: var(--surface);
6
+ border: 1px solid var(--line);
7
+ border-radius: 12px;
8
+ padding: 1rem;
9
+ min-height: 24rem;
10
+ align-content: start;
11
+ }
12
+ .conversation { display: grid; gap: 0.6rem; max-height: 60vh; overflow-y: auto; }
13
+ .msg { margin: 0; padding: 0.6rem 0.8rem; border-radius: 10px; max-width: 85%; white-space: pre-wrap; line-height: 1.5; }
14
+ .msg.user { justify-self: end; background: var(--accent); color: var(--accent-text); }
15
+ .msg.assistant { background: var(--bg); }
16
+ .msg.step, .msg.progress { color: var(--muted); font-size: 0.875rem; padding-block: 0.1rem; }
17
+ .msg.error { color: var(--danger); }
18
+ .msg.ui { max-width: 100%; padding: 0; }
19
+ .msg.approval { border: 1px solid var(--accent); }
20
+ .examples { display: flex; flex-wrap: wrap; gap: 0.5rem; }
21
+ .examples button, .composer button, .approval button {
22
+ font: inherit; padding: 0.45rem 0.8rem; border-radius: 8px; border: 1px solid var(--line); background: var(--surface); color: var(--text); cursor: pointer;
23
+ }
24
+ .composer { display: flex; gap: 0.5rem; }
25
+ .composer input { flex: 1; font: inherit; padding: 0.55rem 0.75rem; border: 1px solid var(--line); border-radius: 8px; background: var(--bg); color: var(--text); }
26
+ .composer button[type='submit'] { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
27
+ .composer button:disabled { opacity: 0.6; cursor: default; }
28
+ .note-cards h3 { margin: 0 0 0.5rem; font-size: 1rem; }
29
+ .note-cards ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.5rem; }
30
+ .note-cards li { border: 1px solid var(--line); border-radius: 8px; padding: 0.6rem 0.8rem; background: var(--surface); }
31
+ .note-cards li p { margin: 0 0 0.25rem; }
32
+ .note-cards time, .muted { color: var(--muted); font-size: 0.8rem; }
33
+ .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
@@ -0,0 +1,36 @@
1
+ import { asset } from 'amoxi';
2
+
3
+ export interface LayoutProps {
4
+ title: string;
5
+ active?: 'home' | 'assistant' | 'about';
6
+ children?: unknown;
7
+ }
8
+
9
+ /** The HTML document shared by every page. Links between pages navigate without full reloads. */
10
+ export function Layout(props: LayoutProps) {
11
+ return (
12
+ <html lang="en">
13
+ <head>
14
+ <meta charset="utf-8" />
15
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
16
+ <meta name="color-scheme" content="light dark" />
17
+ <title>{props.title} | {{APP_TITLE}}</title>
18
+ <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
19
+ <link rel="stylesheet" href={asset('app.css')} />
20
+ <link rel="stylesheet" href={asset('assistant.css')} />
21
+ </head>
22
+ <body>
23
+ <header class="site-header">
24
+ <a class="brand" href="/">{{APP_TITLE}}</a>
25
+ <nav aria-label="Main">
26
+ <a href="/" aria-current={props.active === 'home' ? 'page' : undefined}>Home</a>
27
+ <a href="/assistant" aria-current={props.active === 'assistant' ? 'page' : undefined}>Assistant</a>
28
+ <a href="/about" aria-current={props.active === 'about' ? 'page' : undefined}>About</a>
29
+ </nav>
30
+ </header>
31
+ <main id="main" tabindex="-1">{props.children}</main>
32
+ <footer class="site-footer">Built with Amoxi</footer>
33
+ </body>
34
+ </html>
35
+ );
36
+ }
@@ -0,0 +1,67 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { Config, AmoxiApplication } from 'amoxi';
4
+ import { AiServices, ScriptedChatModel, type AgentPlatform, type RunEvent } from 'amoxi/ai';
5
+ import { applicationModule } from '../src/generated/amoxi.generated';
6
+
7
+ async function start(model?: ScriptedChatModel) {
8
+ const app = await AmoxiApplication.run(applicationModule, {
9
+ config: Config.of({ server: { port: 0, host: '127.0.0.1' } }), // 'test' profile: offline model, in-memory stores
10
+ silent: true,
11
+ shutdownHook: false,
12
+ overrides: model ? [['ChatModel', model]] : [],
13
+ });
14
+ return { app, platform: AiServices.of(app.context).platform() };
15
+ }
16
+
17
+ async function finished(platform: AgentPlatform, id: string) {
18
+ for (let i = 0; i < 200; i++) {
19
+ const run = await platform.getRun(id);
20
+ if (run && ['completed', 'failed', 'cancelled', 'awaiting_approval'].includes(run.status)) return run;
21
+ await new Promise((r) => setTimeout(r, 20));
22
+ }
23
+ throw new Error('run did not finish');
24
+ }
25
+
26
+ test('the offline demo model saves and lists notes with the tools', async () => {
27
+ const { app, platform } = await start();
28
+ try {
29
+ const added = await finished(platform, (await platform.startRun({ agent: 'assistant', input: 'Add a note "Buy coffee beans"', owner: 'me' })).id);
30
+ assert.equal(added.status, 'completed');
31
+ const listed = await platform.startRun({ agent: 'assistant', input: 'Show my notes', owner: 'me' });
32
+ const events: RunEvent[] = [];
33
+ for await (const e of platform.subscribe(listed.id, 0)) events.push(e);
34
+ const ui = events.find((e) => e.type === 'ui');
35
+ assert.equal(ui?.data.component, 'NoteList');
36
+ assert.match(JSON.stringify(ui?.data.props), /Buy coffee beans/);
37
+ } finally {
38
+ await app.close();
39
+ }
40
+ });
41
+
42
+ test('a scripted model drives the agent loop deterministically', async () => {
43
+ const model = new ScriptedChatModel([{ toolCalls: [{ name: 'add_note', input: { content: 'Call the bank' } }] }, { text: 'Saved.' }]);
44
+ const { app, platform } = await start(model);
45
+ try {
46
+ const run = await finished(platform, (await platform.startRun({ agent: 'assistant', input: 'remind me to call the bank', owner: 'me' })).id);
47
+ assert.equal(run.output, 'Saved.');
48
+ assert.match(model.requests[0].system ?? '', /notes app/);
49
+ assert.deepEqual(model.requests[0].tools?.map((t) => t.name).sort(), ['add_note', 'list_notes', 'show_note_list']);
50
+ } finally {
51
+ await app.close();
52
+ }
53
+ });
54
+
55
+ test('the assistant page renders and the agent is listed', async () => {
56
+ const { app } = await start();
57
+ const base = `http://127.0.0.1:${app.port}`;
58
+ try {
59
+ const page = await fetch(`${base}/assistant`, { headers: { accept: 'text/html' } });
60
+ assert.equal(page.status, 200);
61
+ assert.match(await page.text(), /<amoxi-island data-c="Assistant"/);
62
+ const agents = (await (await fetch(`${base}/agents`)).json()) as { agents: Array<{ name: string }> };
63
+ assert.deepEqual(agents.agents.map((a) => a.name), ['assistant']);
64
+ } finally {
65
+ await app.close();
66
+ }
67
+ });
@@ -0,0 +1,19 @@
1
+ import { Body, Controller, Get, HttpResponse, Post } from 'amoxi';
2
+ import type { NewNote, Note } from './note';
3
+ import { NoteService } from './note-service';
4
+
5
+ @Controller('/api/notes')
6
+ export class NoteController {
7
+ constructor(private readonly notes: NoteService) {}
8
+
9
+ @Get()
10
+ list(): Note[] {
11
+ return this.notes.list();
12
+ }
13
+
14
+ // Invalid bodies are rejected with a 400 listing every problem before this runs.
15
+ @Post()
16
+ create(@Body() body: NewNote): HttpResponse<Note> {
17
+ return HttpResponse.created(this.notes.add(body));
18
+ }
19
+ }
@@ -0,0 +1,27 @@
1
+ import { PostConstruct, Singleton, Value } from 'amoxi';
2
+ import type { NewNote, Note } from './note';
3
+
4
+ /** Keeps notes in memory. Replace with a database-backed service when you need persistence. */
5
+ @Singleton()
6
+ export class NoteService {
7
+ private readonly notes: Note[] = [];
8
+ private nextId = 1;
9
+
10
+ constructor(@Value('${notes.max:100}') private readonly max: number) {}
11
+
12
+ @PostConstruct()
13
+ seed(): void {
14
+ this.add({ text: 'Welcome to Amoxi. Edit a file in src/ and save to see it update.' });
15
+ }
16
+
17
+ list(): Note[] {
18
+ return [...this.notes].reverse();
19
+ }
20
+
21
+ add(input: NewNote): Note {
22
+ if (this.notes.length >= this.max) this.notes.shift();
23
+ const note: Note = { id: this.nextId++, text: input.text.trim(), createdAt: new Date().toISOString() };
24
+ this.notes.push(note);
25
+ return note;
26
+ }
27
+ }
@@ -0,0 +1,19 @@
1
+ export interface Note {
2
+ readonly id: number;
3
+ readonly text: string;
4
+ readonly createdAt: string;
5
+ }
6
+
7
+ /**
8
+ * Body of `POST /api/notes`. Amoxi generates a validator from this type at build time,
9
+ * including the JSDoc rules below, and strips any other properties.
10
+ */
11
+ export interface NewNote {
12
+ /**
13
+ * @minLength 1
14
+ * @maxLength 280
15
+ * @pattern \S
16
+ * @patternMessage must not be blank
17
+ */
18
+ readonly text: string;
19
+ }
@@ -0,0 +1,25 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { Config, AmoxiApplication } from 'amoxi';
4
+ import { applicationModule } from '../src/generated/amoxi.generated';
5
+
6
+ test('notes API validates input and stores notes', async () => {
7
+ const app = await AmoxiApplication.run(applicationModule, {
8
+ config: Config.of({ server: { port: 0, host: '127.0.0.1' } }),
9
+ silent: true,
10
+ shutdownHook: false,
11
+ });
12
+ const base = `http://127.0.0.1:${app.port}`;
13
+ const json = { 'content-type': 'application/json' };
14
+ try {
15
+ const bad = await fetch(`${base}/api/notes`, { method: 'POST', headers: json, body: JSON.stringify({ text: 42 }) });
16
+ assert.equal(bad.status, 400);
17
+ const ok = await fetch(`${base}/api/notes`, { method: 'POST', headers: json, body: JSON.stringify({ text: 'Hello' }) });
18
+ assert.equal(ok.status, 201);
19
+ const notes = (await (await fetch(`${base}/api/notes`)).json()) as Array<{ text: string }>;
20
+ assert.equal(notes[0].text, 'Hello');
21
+ assert.deepEqual(await (await fetch(`${base}/amoxi/health/ready`)).json(), { status: 'UP' });
22
+ } finally {
23
+ await app.close();
24
+ }
25
+ });
@@ -0,0 +1,38 @@
1
+ # syntax=docker/dockerfile:1
2
+ # docker build -t {{APP_NAME}} .
3
+ # docker run -p 8080:8080 {{APP_NAME}}
4
+
5
+ FROM node:22-alpine AS build
6
+ WORKDIR /app
7
+ COPY . .
8
+ # Installs exactly what the lockfile pins, with the package manager that wrote it, builds, then
9
+ # keeps only the production dependencies. Run your package manager's install once before building
10
+ # the image, so the lockfile exists.
11
+ RUN set -e; \
12
+ if [ -f package-lock.json ]; then \
13
+ npm ci && npm run build && npm prune --omit=dev; \
14
+ elif [ -f pnpm-lock.yaml ]; then \
15
+ corepack enable pnpm && pnpm install --frozen-lockfile && pnpm run build && pnpm prune --prod; \
16
+ elif [ -f yarn.lock ]; then \
17
+ corepack enable yarn && yarn install --frozen-lockfile && yarn run build && yarn install --production --frozen-lockfile --ignore-scripts; \
18
+ elif [ -f bun.lock ] || [ -f bun.lockb ]; then \
19
+ npm install -g bun && bun install --frozen-lockfile && bun run build && rm -rf node_modules && bun install --production --frozen-lockfile; \
20
+ else \
21
+ echo "No lockfile found: run npm install (or pnpm, yarn or bun install) once, then build the image again." >&2; exit 1; \
22
+ fi
23
+
24
+ FROM node:22-alpine
25
+ ENV NODE_ENV=production
26
+ WORKDIR /app
27
+ COPY --from=build --chown=node:node /app/package.json /app/application*.json ./
28
+ COPY --from=build --chown=node:node /app/node_modules ./node_modules
29
+ COPY --from=build --chown=node:node /app/dist ./dist
30
+ COPY --from=build --chown=node:node /app/public ./public
31
+ # Agent runs, conversations and memory are saved under /app/data (the default file store);
32
+ # the app runs as the unprivileged "node" user, so that folder must belong to it.
33
+ RUN mkdir -p /app/data && chown node:node /app/data
34
+ USER node
35
+ EXPOSE 8080
36
+ HEALTHCHECK --interval=10s --timeout=3s --start-period=5s \
37
+ CMD wget -qO- http://127.0.0.1:8080/amoxi/health/ready || exit 1
38
+ CMD ["node", "node_modules/amoxi/bin/amoxi.js", "start", "dist/src/main.js", "--workers", "auto"]
@@ -0,0 +1,25 @@
1
+ # {{APP_TITLE}}
2
+
3
+ Created with `create-amoxi-app`.
4
+
5
+ ## Commands
6
+
7
+ | | |
8
+ |---|---|
9
+ | `npm run dev` | Development server on http://localhost:8080; rebuilds and refreshes the browser on save |
10
+ | `npm run build` | Production build: `amoxi build` (wiring, validators, browser bundles) then `tsc` |
11
+ | `npm start` | Run the production build on every CPU core (`NODE_ENV=production`) |
12
+ | `npm test` | Build, then run the tests in `test/` |
13
+
14
+ ## Configuration
15
+
16
+ No environment variables are required. Settings come from `application.json`, then `application-<profile>.json`, then `.env` files, then environment variables. The profile is `production` under `npm start` and `development` under `npm run dev`.
17
+
18
+ ## Deploy
19
+
20
+ ```bash
21
+ docker build -t {{APP_NAME}} .
22
+ docker run -p 8080:8080 {{APP_NAME}}
23
+ ```
24
+
25
+ Health checks: `GET /amoxi/health/live` and `GET /amoxi/health/ready`.
@@ -0,0 +1,10 @@
1
+ node_modules
2
+ dist
3
+ .amoxi
4
+ public/_amoxi
5
+ src/generated
6
+ .git
7
+ .env
8
+ .env.*
9
+ !.env.example
10
+ data
@@ -0,0 +1,4 @@
1
+ # Optional settings. Nothing here is required: the app runs without any environment variables.
2
+ # Copy to .env.local for local overrides (git-ignored), or set them in your hosting environment.
3
+ # Any configuration key works; dots become underscores, e.g. server.port:
4
+ # SERVER_PORT=8080
@@ -0,0 +1,14 @@
1
+ node_modules/
2
+ dist/
3
+ .amoxi/
4
+ public/_amoxi/
5
+ src/generated/
6
+ *.tsbuildinfo
7
+
8
+ # Secrets such as API keys live in .env files. Never commit them; .env.example (no secrets) is kept.
9
+ .env
10
+ .env.*
11
+ !.env.example
12
+
13
+ # Agent runs, conversations and memory (amoxi/ai file store)
14
+ data/
@@ -0,0 +1,3 @@
1
+ {
2
+ "amoxi": { "log": { "format": "json" } }
3
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "app": { "name": "{{APP_NAME}}" },
3
+ "server": { "port": 8080 }
4
+ }
@@ -0,0 +1,8 @@
1
+ import { AmoxiApplication, PortInUseError } from 'amoxi';
2
+ // Generated by `amoxi build` / `amoxi dev`: the app's fully resolved wiring.
3
+ import { applicationModule } from './generated/amoxi.generated';
4
+
5
+ AmoxiApplication.run(applicationModule).catch((err) => {
6
+ console.error(err instanceof PortInUseError ? err.message : err);
7
+ process.exit(1);
8
+ });
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "commonjs",
5
+ "moduleResolution": "node10",
6
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
7
+ "types": ["node"],
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "forceConsistentCasingInFileNames": true,
12
+ "experimentalDecorators": true,
13
+ "emitDecoratorMetadata": false,
14
+ "jsx": "react-jsx",
15
+ "jsxImportSource": "amoxi",
16
+ "sourceMap": true,
17
+ "rootDir": ".",
18
+ "outDir": "dist"
19
+ },
20
+ "include": ["src", "test"]
21
+ }
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#2F4A66"/><path d="M9 24h14.5a5.5 5.5 0 0 0 .6-10.97A8 8 0 0 0 8.5 14.6 4.75 4.75 0 0 0 9 24Z" fill="none" stroke="#F4F6F9" stroke-width="1.8"/><path d="M17.5 15 13 21h4l-1.5 5 5-7h-4l1-4Z" fill="#E9B52C"/></svg>
@@ -0,0 +1,40 @@
1
+ import { navigate, signal } from 'amoxi';
2
+
3
+ /** Posts to the JSON API, then re-renders the current page in place to show the new note. */
4
+ export default function AddNote() {
5
+ let input!: HTMLInputElement;
6
+ const [error, setError] = signal('');
7
+ const [busy, setBusy] = signal(false);
8
+
9
+ const submit = async (e: Event): Promise<void> => {
10
+ e.preventDefault();
11
+ setBusy(true);
12
+ setError('');
13
+ try {
14
+ const res = await fetch('/api/notes', {
15
+ method: 'POST',
16
+ headers: { 'content-type': 'application/json' },
17
+ body: JSON.stringify({ text: input.value }),
18
+ });
19
+ if (!res.ok) {
20
+ const body = (await res.json().catch(() => ({}))) as { details?: Array<{ message: string }>; error?: string };
21
+ throw new Error(body.details?.[0] ? `Note ${body.details[0].message}.` : (body.error ?? `Request failed (${res.status}).`));
22
+ }
23
+ input.value = '';
24
+ await navigate(location.pathname, { replace: true, keepScroll: true });
25
+ } catch (err) {
26
+ setError((err as Error).message);
27
+ } finally {
28
+ setBusy(false);
29
+ }
30
+ };
31
+
32
+ return (
33
+ <form class="add-note" onSubmit={submit}>
34
+ <label for="note-text" class="visually-hidden">New note</label>
35
+ <input id="note-text" ref={(el: HTMLInputElement) => (input = el)} placeholder="Write a note" maxlength="280" autocomplete="off" />
36
+ <button type="submit" class="button" disabled={busy}>Add note</button>
37
+ <p class="error" role="alert">{error}</p>
38
+ </form>
39
+ );
40
+ }
@@ -0,0 +1,11 @@
1
+ import { signal } from 'amoxi';
2
+
3
+ /** An island: rendered on the server, then made interactive in the browser. */
4
+ export default function Counter(props: { start: number }) {
5
+ const [count, setCount] = signal(props.start);
6
+ return (
7
+ <button type="button" class="button" onClick={() => setCount((c) => c + 1)}>
8
+ Clicked {count} {() => (count() === 1 ? 'time' : 'times')}
9
+ </button>
10
+ );
11
+ }
@@ -0,0 +1,19 @@
1
+ import { Body, Controller, Get, HttpResponse, Post } from 'amoxi';
2
+ import type { NewNote, Note } from './note';
3
+ import { NoteService } from './note-service';
4
+
5
+ @Controller('/api/notes')
6
+ export class NoteController {
7
+ constructor(private readonly notes: NoteService) {}
8
+
9
+ @Get()
10
+ list(): Note[] {
11
+ return this.notes.list();
12
+ }
13
+
14
+ // Invalid bodies are rejected with a 400 listing every problem before this runs.
15
+ @Post()
16
+ create(@Body() body: NewNote): HttpResponse<Note> {
17
+ return HttpResponse.created(this.notes.add(body));
18
+ }
19
+ }
@@ -0,0 +1,27 @@
1
+ import { PostConstruct, Singleton, Value } from 'amoxi';
2
+ import type { NewNote, Note } from './note';
3
+
4
+ /** Keeps notes in memory. Replace with a database-backed service when you need persistence. */
5
+ @Singleton()
6
+ export class NoteService {
7
+ private readonly notes: Note[] = [];
8
+ private nextId = 1;
9
+
10
+ constructor(@Value('${notes.max:100}') private readonly max: number) {}
11
+
12
+ @PostConstruct()
13
+ seed(): void {
14
+ this.add({ text: 'Welcome to Amoxi. Edit a file in src/ and save to see it update.' });
15
+ }
16
+
17
+ list(): Note[] {
18
+ return [...this.notes].reverse();
19
+ }
20
+
21
+ add(input: NewNote): Note {
22
+ if (this.notes.length >= this.max) this.notes.shift();
23
+ const note: Note = { id: this.nextId++, text: input.text.trim(), createdAt: new Date().toISOString() };
24
+ this.notes.push(note);
25
+ return note;
26
+ }
27
+ }
@@ -0,0 +1,19 @@
1
+ export interface Note {
2
+ readonly id: number;
3
+ readonly text: string;
4
+ readonly createdAt: string;
5
+ }
6
+
7
+ /**
8
+ * Body of `POST /api/notes`. Amoxi generates a validator from this type at build time,
9
+ * including the JSDoc rules below, and strips any other properties.
10
+ */
11
+ export interface NewNote {
12
+ /**
13
+ * @minLength 1
14
+ * @maxLength 280
15
+ * @pattern \S
16
+ * @patternMessage must not be blank
17
+ */
18
+ readonly text: string;
19
+ }