@ultimat3/cli 31.37.0 → 31.38.1

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 (44) hide show
  1. package/package.json +29 -29
  2. package/src/cmd-planned.ts +5 -28
  3. package/src/generate-sign-in-runtime.ts +70 -0
  4. package/src/generate-sign-in.ts +19 -6
  5. package/src/generate-write.ts +12 -0
  6. package/src/island-plugin-path.ts +35 -0
  7. package/src/island-realtime.ts +11 -8
  8. package/src/island-runtime.ts +4 -1
  9. package/src/new-shapes.ts +10 -1
  10. package/src/templates/shapes/agent-actions.ts +224 -0
  11. package/src/templates/shapes/agent-job.ts +171 -0
  12. package/src/templates/shapes/agent-model.ts +271 -0
  13. package/src/templates/shapes/agent-prompt.ts +254 -0
  14. package/src/templates/shapes/agent-scripted.ts +56 -0
  15. package/src/templates/shapes/agent.ts +138 -0
  16. package/src/templates/shapes/content-admin-es.ts +95 -0
  17. package/src/templates/shapes/content-pages.ts +221 -0
  18. package/src/templates/shapes/content-site.ts +343 -0
  19. package/src/templates/shapes/content.ts +133 -0
  20. package/src/templates/shapes/index.ts +10 -0
  21. package/src/templates/shapes/offline-e2e.ts +123 -0
  22. package/src/templates/shapes/offline-form.ts +334 -0
  23. package/src/templates/shapes/offline.ts +118 -0
  24. package/src/templates/shapes/realtime-mutator.ts +136 -0
  25. package/src/templates/shapes/realtime-nodes.ts +203 -0
  26. package/src/templates/shapes/realtime-slice.ts +166 -0
  27. package/src/templates/shapes/realtime.ts +162 -0
  28. package/src/templates/shapes/saas-billing-tests.ts +135 -0
  29. package/src/templates/shapes/saas-billing.ts +137 -0
  30. package/src/templates/shapes/saas-receiver.ts +136 -0
  31. package/src/templates/shapes/saas.ts +112 -0
  32. package/src/templates/sign-in-oidc.ts +2 -4
  33. package/src/templates/sign-in-runtime.ts +172 -0
  34. package/src/templates/sign-in-shared.ts +5 -36
  35. package/wiki/Building-Your-Own-Base.md +339 -0
  36. package/wiki/CLI-Reference.md +1 -14
  37. package/wiki/Caching-And-Invalidation.md +1 -1
  38. package/wiki/Entities-And-Migrations.md +2 -2
  39. package/wiki/Known-Gaps.md +8 -2
  40. package/wiki/MCP-And-AI.md +3 -3
  41. package/wiki/Money.md +1 -1
  42. package/wiki/Shapes.md +18 -9
  43. package/wiki/Troubleshooting.md +1 -1
  44. package/wiki/Upgrading.md +1 -1
@@ -0,0 +1,133 @@
1
+ // `x new <name> --shape content`: a docs or marketing site built from files. Markdown under
2
+ // `apps/web/content/<locale>/` becomes one `site/` page per file per locale at
3
+ // `x build --target static`, zero JavaScript on every route, a sitemap with its hreflang cluster.
4
+ // Its pages read no table and no one writes them at `/admin`: a page is a committed file.
5
+
6
+ import { catalogJson } from '../catalog-json';
7
+ import { catalogPath } from '../locales';
8
+ import type { GeneratedFile, NameSet } from '../naming';
9
+ import { i18nIndex } from '../scaffold-i18n';
10
+ import { ADMIN_SPANISH } from './content-admin-es';
11
+ import { CONTENT_LOCALES, contentPageFiles } from './content-pages';
12
+ import { contentSiteFiles } from './content-site';
13
+ import type { ShapeEdit, ShapeOverlay } from './overlay';
14
+ import { claudeRows, shapeLines } from './shared-edits';
15
+
16
+ const edits = (): readonly ShapeEdit[] => [
17
+ ...claudeRows({
18
+ page: '`apps/web/site/page.test.ts`',
19
+ island: 'none in this shape: `bunx x g island <name>` writes one with its states',
20
+ }),
21
+ ...shapeLines(
22
+ 'content',
23
+ 'a site built from files — each `apps/web/content/<locale>/<slug>.md` is a 0 KB page per locale (`apps/web/site/[page]/page.tsx`), read by `apps/web/shared/content.ts`, with no table behind it',
24
+ ),
25
+ ];
26
+
27
+ /**
28
+ * The keys this shape's pages read, plus the design system's strings a page shows (the language
29
+ * switcher's label, a code fence's controls): the framework's own catalog is English only, so a
30
+ * Spanish page would print `⟦ui.language⟧` unless the app's catalogs carry them.
31
+ */
32
+ const SHAPE_KEYS = {
33
+ en: {
34
+ 'site.content.title': '{name} documentation',
35
+ 'site.content.description': 'Guides and reference, built from files and served with no script.',
36
+ 'site.content.headline': 'Every page here is a file.',
37
+ 'site.content.lede':
38
+ 'Write markdown under apps/web/content, one folder per language. The build renders each page in every language, with no JavaScript.',
39
+ 'site.content.pages': 'Pages',
40
+ 'site.content.home': 'Home',
41
+ 'site.content.back': 'All pages',
42
+ 'ui.language': 'Language',
43
+ 'ui.copy': 'Copy',
44
+ 'ui.copied': 'Copied',
45
+ 'ui.code.region': 'Code',
46
+ 'ui.code.wrap': 'Wrap lines',
47
+ },
48
+ es: {
49
+ 'site.content.title': 'Documentación de {name}',
50
+ 'site.content.description':
51
+ 'Guías y referencia, construidas a partir de archivos y sin scripts.',
52
+ 'site.content.headline': 'Cada página es un archivo.',
53
+ 'site.content.lede':
54
+ 'Escribe markdown en apps/web/content, una carpeta por idioma. La compilación genera cada página en cada idioma, sin JavaScript.',
55
+ 'site.content.pages': 'Páginas',
56
+ 'site.content.home': 'Inicio',
57
+ 'site.content.back': 'Todas las páginas',
58
+ 'ui.language': 'Idioma',
59
+ 'ui.copy': 'Copiar',
60
+ 'ui.copied': 'Copiado',
61
+ 'ui.code.region': 'Código',
62
+ 'ui.code.wrap': 'Ajustar líneas',
63
+ },
64
+ } as const satisfies Record<(typeof CONTENT_LOCALES)[number], Record<string, string>>;
65
+
66
+ /** The base scaffold's keys this shape keeps, in Spanish: `es` holds every key `en` does. */
67
+ const baseSpanish = (app: NameSet): Readonly<Record<string, string>> => ({
68
+ 'admin.home.title': 'Administración',
69
+ 'admin.home.description': `Operaciones de ${app.pascal}.`,
70
+ 'app.offline.title': 'Sin conexión',
71
+ 'app.offline.description': 'Esta página se actualizará sola cuando vuelva la conexión.',
72
+ });
73
+
74
+ /**
75
+ * The base scaffold's parity test asks every locale for EXACTLY the default's keys; with a second
76
+ * locale that is false by one namespace — `admin.*`, which English reads from the framework's own
77
+ * catalog and every other locale owes in the app's.
78
+ */
79
+ const i18nIndexTest =
80
+ (): string => `// Every locale carries every key the default one does. A key present in en and missing in es
81
+ // renders ⟦key⟧ to a reader, and nothing else in the app can notice. A locale holds more than the
82
+ // default by one namespace: \`admin.*\`, which English takes from the framework's own catalog.
83
+ import { expect } from 'bun:test';
84
+ import { unitTest } from '@ultimat3/testing';
85
+ import { catalogs } from './index';
86
+
87
+ unitTest('every locale has every key of the default one', () => {
88
+ const base = Object.keys(catalogs.catalogs[catalogs.default]);
89
+ expect(catalogs.locales.length).toBeGreaterThan(1);
90
+ for (const locale of catalogs.locales) {
91
+ const keys = new Set(Object.keys(catalogs.catalogs[locale]));
92
+ expect({ locale, missing: base.filter((key) => !keys.has(key)) }).toEqual({
93
+ locale,
94
+ missing: [],
95
+ });
96
+ }
97
+ });
98
+
99
+ unitTest('no catalog value is empty', () => {
100
+ for (const catalog of Object.values(catalogs.catalogs)) {
101
+ for (const value of Object.values(catalog)) expect(value.length).toBeGreaterThan(0);
102
+ }
103
+ });
104
+ `;
105
+
106
+ const catalogs = (app: NameSet): readonly GeneratedFile[] => [
107
+ { path: catalogPath('en'), merge: 'json', contents: catalogJson(SHAPE_KEYS.en) },
108
+ {
109
+ path: catalogPath('es'),
110
+ merge: 'json',
111
+ contents: catalogJson({ ...ADMIN_SPANISH, ...baseSpanish(app), ...SHAPE_KEYS.es }),
112
+ },
113
+ // The one registration module, regenerated for both locales by the generator's own template.
114
+ { path: 'packages/i18n/src/index.ts', contents: i18nIndex(CONTENT_LOCALES) },
115
+ { path: 'packages/i18n/src/index.test.ts', contents: i18nIndexTest() },
116
+ ];
117
+
118
+ export const contentShape: ShapeOverlay = {
119
+ example: false,
120
+ drop: [
121
+ 'apps/web/app/dashboard/',
122
+ 'apps/web/shared/shell',
123
+ 'apps/web/shared/theme-toggle.island',
124
+ 'apps/web/shared/browser-client',
125
+ ],
126
+ dropKeys: ['app.dashboard', 'shell', 'site.home'],
127
+ edits,
128
+ files: (app): readonly GeneratedFile[] => [
129
+ ...contentPageFiles(app),
130
+ ...contentSiteFiles(app),
131
+ ...catalogs(app),
132
+ ],
133
+ };
@@ -2,15 +2,25 @@
2
2
  // overlay (or an overlay with no name) is a compile error rather than a shape `x new` half-writes.
3
3
 
4
4
  import type { NewShape } from '../../new-shapes';
5
+ import { agentShape } from './agent';
5
6
  import { apiShape } from './api';
6
7
  import { blogShape } from './blog';
8
+ import { contentShape } from './content';
7
9
  import { dashboardShape } from './dashboard';
10
+ import { offlineShape } from './offline';
8
11
  import type { ShapeOverlay } from './overlay';
12
+ import { realtimeShape } from './realtime';
13
+ import { saasShape } from './saas';
9
14
 
10
15
  export const SHAPE_OVERLAYS: { readonly [S in NewShape]: ShapeOverlay } = {
11
16
  api: apiShape,
12
17
  blog: blogShape,
13
18
  dashboard: dashboardShape,
19
+ saas: saasShape,
20
+ agent: agentShape,
21
+ realtime: realtimeShape,
22
+ content: contentShape,
23
+ offline: offlineShape,
14
24
  };
15
25
 
16
26
  export type { ShapeEdit, ShapeOverlay } from './overlay';
@@ -0,0 +1,123 @@
1
+ // `--shape offline`'s browser proofs, both against the built app with the network cut by the e2e
2
+ // driver's `offline()` (which cuts the service worker's network too): the offline document answers
3
+ // a page the cache cannot, and a post written offline is queued, then sent once on reconnect.
4
+
5
+ import type { GeneratedFile, NameSet } from '../naming';
6
+
7
+ export const FALLBACK_E2E = 'apps/web/site/offline/page.e2e.test.ts';
8
+ export const WRITE_E2E = 'apps/web/app/posts/offline-write.e2e.test.ts';
9
+
10
+ const fallback = (
11
+ app: NameSet,
12
+ ): string => `// The offline fallback in a real browser, with the network CUT — what \`page.test.ts\` cannot see:
13
+ // that the service worker installed, precached this document, and answers a navigation with it
14
+ // when neither the network nor the cache has the page. Its own file because the gate types a test
15
+ // by its FILENAME — an e2eTest in page.test.ts is a unit test.
16
+ import { useT } from '@${app.kebab}/i18n';
17
+ import { e2eTest, expect } from '@ultimat3/testing';
18
+
19
+ e2eTest(
20
+ 'with the network cut, a page no cache holds is answered by the offline document',
21
+ async ({ page, offline, online }) => {
22
+ const t = useT();
23
+ // One browser serves the whole run, and a suite before this one may have left it offline.
24
+ await online();
25
+ await page.goto('/');
26
+ // The worker must control the page before the cut, or nothing is there to answer.
27
+ await page.waitForServiceWorker();
28
+ await offline();
29
+ try {
30
+ // \`/posts\` is personal (a policy, \`stream\`): never cached, so offline it is the fallback.
31
+ await page.goto('/posts');
32
+ expect(await page.title()).toContain(t('app.offline.title'));
33
+ // And the fallback itself is precached, so it answers by its own URL too.
34
+ await page.goto('/offline');
35
+ expect(await page.title()).toContain(t('app.offline.title'));
36
+ } finally {
37
+ await online();
38
+ }
39
+ },
40
+ );
41
+ `;
42
+
43
+ const write =
44
+ (): string => `// A post written with the network CUT, in a real browser: the form takes it, realtime's outbox
45
+ // holds it in IndexedDB, and on reconnect it is sent — once, under its idempotency key — so the
46
+ // list shows it exactly one time. Its own file because the gate types a test by its FILENAME.
47
+ import { e2eTest, expect, type PageLike } from '@ultimat3/testing';
48
+
49
+ const TITLE = 'Written in a tunnel';
50
+
51
+ /**
52
+ * Asks \`probe\` until it holds, ~20 s at most. Counted in turns, never read off \`Date.now()\`: the
53
+ * test preload freezes the clock, so a deadline computed from it never arrives.
54
+ */
55
+ async function until(what: string, probe: () => Promise<boolean>): Promise<void> {
56
+ for (let turn = 0; turn < 200; turn += 1) {
57
+ if (await probe()) return;
58
+ await Bun.sleep(100);
59
+ }
60
+ expect({ waitedFor: what, held: await probe() }).toEqual({ waitedFor: what, held: true });
61
+ }
62
+
63
+ /** How many writes the form says are queued on this device — the outbox's live size. */
64
+ const queued = (page: PageLike): Promise<string | null> =>
65
+ page.evaluate(
66
+ () =>
67
+ document.querySelector('[data-x-island] [data-role="status"]')?.getAttribute('data-queued') ??
68
+ null,
69
+ );
70
+
71
+ e2eTest(
72
+ 'a post written offline is queued on the device, and sent once the network returns',
73
+ async ({ page, offline, online }) => {
74
+ // One browser serves the whole run, and a suite before this one may have left it offline.
75
+ await online();
76
+ await page.goto('/posts');
77
+ await page.waitForServiceWorker();
78
+ // Mounted, and the page boot has opened the outbox: the status line reports its size.
79
+ await until('the form to mount', async () => (await queued(page)) === '0');
80
+
81
+ await offline();
82
+ try {
83
+ await page.evaluate(() => {
84
+ const [title, price] = Array.from(
85
+ document.querySelectorAll<HTMLInputElement>('[data-x-island] form input'),
86
+ );
87
+ if (title === undefined || price === undefined) return false;
88
+ title.value = 'Written in a tunnel';
89
+ title.dispatchEvent(new Event('input', { bubbles: true }));
90
+ price.value = '3.50';
91
+ price.dispatchEvent(new Event('input', { bubbles: true }));
92
+ document.querySelector<HTMLButtonElement>('[data-x-island] form button')?.click();
93
+ return true;
94
+ });
95
+ // On disk, not in memory: the outbox is IndexedDB, so a reload or a closed tab keeps it.
96
+ await until('the write to queue', async () => (await queued(page)) === '1');
97
+ } finally {
98
+ await online();
99
+ }
100
+
101
+ // Back online, the outbox replays by itself — no reload, no second submit.
102
+ await until('the replay', async () => (await queued(page)) === '0');
103
+ await page.reload();
104
+ // Sent ONCE: the replay carried the write's own key, so the list holds one row, not two.
105
+ const rows = (): Promise<number> =>
106
+ page.evaluate(
107
+ () =>
108
+ Array.from(document.querySelectorAll('tr[data-row]')).filter((row) =>
109
+ row.textContent?.includes('Written in a tunnel'),
110
+ ).length,
111
+ );
112
+ await until('the row to list', async () => (await rows()) > 0);
113
+ const shown = await rows();
114
+ expect({ title: TITLE, shown }).toEqual({ title: TITLE, shown: 1 });
115
+ },
116
+ );
117
+ `;
118
+
119
+ /** Both suites: the fallback beside the page it proves, the write beside the list it lands in. */
120
+ export const offlineE2eFiles = (app: NameSet): readonly GeneratedFile[] => [
121
+ { path: FALLBACK_E2E, contents: fallback(app) },
122
+ { path: WRITE_E2E, contents: write() },
123
+ ];
@@ -0,0 +1,334 @@
1
+ // `--shape offline`'s post form: the default form, written through realtime's ONE outbox instead of
2
+ // a bare transport call. Online it posts at once; offline — or when the request never answered —
3
+ // the write lands in IndexedDB under its idempotency key and is replayed when the network returns.
4
+
5
+ import type { GeneratedFile } from '../naming';
6
+
7
+ const DIR = 'apps/web/app/post';
8
+
9
+ const island =
10
+ (): string => `// PostForm: the only module of the post slice a browser downloads — and the write that survives
11
+ // a lost network. The page names this file by SPECIFIER, never by import:
12
+ // const PostForm = island({
13
+ // src: '../post/post-form.island.tsx',
14
+ // props: ['locale', 'currency', 'labels'],
15
+ // });
16
+ // A string has no import edge, so the page's bundle graph stays the page's (axiom 6).
17
+ //
18
+ // \`useMutation\` from \`@ultimat3/realtime\` is the one way a page writes: online it POSTs
19
+ // \`createPost\` under an idempotency key; offline, or when a POST never got an answer, the write
20
+ // goes to the page's outbox (IndexedDB, per signed-in member) and is replayed IN ORDER, under the
21
+ // same key, when the browser is back online or the service worker wakes it. \`createPost\` declares
22
+ // \`idempotent: true\`, so a replay of a write that did land answers the first result, never a
23
+ // second row. No queue, retry loop or \`navigator.onLine\` check lives here: the outbox owns them.
24
+
25
+ import { fromDecimal } from '@ultimat3/money';
26
+ import { type MutatorLike, useMutation, useOutbox } from '@ultimat3/realtime';
27
+ import { mountOver } from '@ultimat3/render/client';
28
+ import { Button, Form, Input, setSolidRuntime, UiProvider } from '@ultimat3/ui';
29
+ import type { JSX } from 'solid-js';
30
+ import {
31
+ createContext,
32
+ createEffect,
33
+ createMemo,
34
+ createRoot,
35
+ createSignal,
36
+ onCleanup,
37
+ useContext,
38
+ } from 'solid-js';
39
+ import { render } from 'solid-js/web';
40
+ import type { Api } from '../../api';
41
+ import styles from './ui.module.scss';
42
+
43
+ /** Every string this module renders. An island's props cross the seam as JSON inside the
44
+ * document, so \`t()\`'s catalog cannot travel — the server translates. */
45
+ export interface PostFormProps {
46
+ /** The request's own locale. A browser has no ambient one the server ever agreed to. */
47
+ readonly locale: string;
48
+ /** The ISO code the price is entered in. The amount is typed as a decimal and sent as minor units. */
49
+ readonly currency: string;
50
+ readonly labels: {
51
+ readonly title: string;
52
+ readonly price: string;
53
+ readonly submit: string;
54
+ readonly saved: string;
55
+ /** Held on this device, sent when the network returns: information, not an error. */
56
+ readonly queued: string;
57
+ readonly retry: string;
58
+ };
59
+ }
60
+
61
+ /**
62
+ * \`createPost\` as the browser can name it. The action module cannot cross into a chunk (it reaches
63
+ * the policy and the database client), so the NAME does — typed against \`Api\`, which is imported
64
+ * as a type and erased, so a rename is a compile error and never a 404 at replay time.
65
+ */
66
+ export const CREATE_POST: MutatorLike = {
67
+ name: 'createPost' satisfies keyof Api['actions'],
68
+ };
69
+
70
+ type SaveState = 'idle' | 'sent' | 'failed';
71
+
72
+ /**
73
+ * Presentation only: the action owns validation server-side, so the form never re-implements the
74
+ * invariant — a blank title fails at the boundary, not in the DOM.
75
+ */
76
+ function PostFormBody(props: PostFormProps): JSX.Element {
77
+ const [title, setTitle] = createSignal('');
78
+ const [amount, setAmount] = createSignal('');
79
+ const [state, setState] = createSignal<SaveState>('idle');
80
+ // Both release with the component: \`useMutation\`'s count and \`useOutbox\`'s subscription.
81
+ const create = useMutation(CREATE_POST);
82
+ const outbox = useOutbox();
83
+
84
+ // A refusal — the server's, or \`fromDecimal\`'s for an amount that is not a number — rejects
85
+ // here and is \`retry\`. A write the network could not take resolves: it is in the outbox now.
86
+ const send = async (): Promise<void> => {
87
+ try {
88
+ const price = fromDecimal(amount(), props.currency);
89
+ await create({ title: title(), price: { minor: price.minor, currency: price.currency } });
90
+ setState('sent');
91
+ } catch {
92
+ setState('failed');
93
+ }
94
+ };
95
+
96
+ // Queued wins over sent: the outbox's size is live, so the line turns to \`saved\` by itself the
97
+ // moment the replay is acknowledged — no reload, no second submit.
98
+ const status = (): string => {
99
+ if (state() === 'failed') return props.labels.retry;
100
+ if (outbox.size > 0) return props.labels.queued;
101
+ return state() === 'sent' ? props.labels.saved : '';
102
+ };
103
+
104
+ return (
105
+ <Form
106
+ class={styles.item}
107
+ onSubmit={(event) => {
108
+ event.preventDefault();
109
+ void send();
110
+ }}
111
+ >
112
+ <Input
113
+ aria-label={props.labels.title}
114
+ value={title()}
115
+ onInput={(event) => setTitle(event.currentTarget.value)}
116
+ />
117
+ <Input
118
+ aria-label={props.labels.price}
119
+ inputmode="decimal"
120
+ value={amount()}
121
+ onInput={(event) => setAmount(event.currentTarget.value)}
122
+ />
123
+ <Button type="submit">{props.labels.submit}</Button>
124
+ <p data-role="status" role="status" aria-live="polite" data-queued={outbox.size}>
125
+ {status()}
126
+ </p>
127
+ </Form>
128
+ );
129
+ }
130
+
131
+ /**
132
+ * The one export the hydration runtime calls. \`setSolidRuntime\` comes FIRST — \`@ultimat3/ui\`
133
+ * imports solid-js types only, so the reactive graph is the one this entry registers (else
134
+ * X_UI_RUNTIME_MISSING). Seven NAMED imports, never \`import * as\`: a namespace keeps every export
135
+ * of solid-js alive in the chunk. \`mountOver\` clears the server's shell and restores it if the
136
+ * render throws; the disposer it returns is what the client router calls on navigation.
137
+ */
138
+ export function mount(el: HTMLElement, props: PostFormProps): () => void {
139
+ setSolidRuntime({
140
+ createContext,
141
+ useContext,
142
+ createSignal,
143
+ createMemo,
144
+ createEffect,
145
+ onCleanup,
146
+ createRoot,
147
+ });
148
+ return mountOver(el, (root) =>
149
+ render(
150
+ () => (
151
+ <UiProvider locale={props.locale}>
152
+ <PostFormBody {...props} />
153
+ </UiProvider>
154
+ ),
155
+ root,
156
+ ),
157
+ );
158
+ }
159
+ `;
160
+
161
+ const states =
162
+ (): string => `// The states the post form can be photographed in. \`x shot --island post-form --json\`
163
+ // takes one picture per state per theme into \`.x/shot/island/post-form/\`.
164
+ //
165
+ // PURE DATA. No JSX, no \`solid-js\`, and the one import below is \`import type\`, which
166
+ // \`verbatimModuleSyntax\` erases (\`X_TEST_ISLAND_STATES_NOT_PURE\` is the refusal). The labels are
167
+ // literals and that is not a \`t()\` violation: they are the text the server would have handed it.
168
+
169
+ import { defineIslandStates } from '@ultimat3/testing';
170
+ import type { PostFormProps } from './post-form.island';
171
+
172
+ /** What a working render hands the form — the baseline the state below departs from. */
173
+ const BASE = {
174
+ locale: 'en',
175
+ currency: 'USD',
176
+ labels: {
177
+ title: 'Title',
178
+ price: 'Price',
179
+ submit: 'Save',
180
+ saved: 'Saved',
181
+ queued: 'Saved on this device. It will send when you are back online.',
182
+ retry: 'That did not save. Try again.',
183
+ },
184
+ } satisfies PostFormProps;
185
+
186
+ export const postFormStates = defineIslandStates({
187
+ island: 'apps/web/app/post/post-form.island.tsx',
188
+ states: [
189
+ {
190
+ id: 'idle',
191
+ title: 'the first paint, before anything has been typed',
192
+ props: BASE satisfies PostFormProps,
193
+ },
194
+ {
195
+ id: 'long-labels',
196
+ title: 'the same form in a locale whose words are three times as long',
197
+ note: 'you cannot reach this by clicking: it needs a translation, and the locale this was written in is the one that fits',
198
+ props: {
199
+ ...BASE,
200
+ locale: 'de',
201
+ labels: {
202
+ title: 'Bezeichnung des Beitrags',
203
+ price: 'Preis',
204
+ submit: 'Änderungen speichern',
205
+ saved: 'Änderungen gespeichert',
206
+ queued: 'Auf diesem Gerät gespeichert. Wird gesendet, sobald Sie wieder online sind.',
207
+ retry: 'Das konnte nicht gespeichert werden. Bitte erneut versuchen.',
208
+ },
209
+ } satisfies PostFormProps,
210
+ },
211
+ ],
212
+ });
213
+ `;
214
+
215
+ const islandTest =
216
+ (): string => `// The form the browser actually runs, in every state its manifest declares: built with the same
217
+ // \`buildIslands\` that \`x build\` and \`x dev\` use — the realtime bootstrap included — imported the
218
+ // way the hydration runtime imports it, and driven against a DOM small enough to read.
219
+ //
220
+ // What it proves here, online: the write goes over HTTP as \`createPost\` under an idempotency key
221
+ // (the one a replay reuses), and a refusal reaches \`retry\`. That the SAME write survives a cut
222
+ // network, a reload and a replay is the browser's to prove: \`apps/web/app/posts/offline-write.e2e.test.ts\`.
223
+
224
+ import { join } from 'node:path';
225
+ import { buildIslands } from '@ultimat3/cli';
226
+ import { resetPageRealtime } from '@ultimat3/realtime';
227
+ import {
228
+ describeIslandState,
229
+ expect,
230
+ type FakeElement,
231
+ type MountedIsland,
232
+ test,
233
+ } from '@ultimat3/testing';
234
+ import { postFormStates } from './post-form.island.states';
235
+
236
+ interface Call {
237
+ readonly url: string;
238
+ readonly key: string | null;
239
+ readonly body: Record<string, unknown>;
240
+ }
241
+ const calls: Call[] = [];
242
+
243
+ /** What the next POST answers: the created row, or the server's refusal. */
244
+ let refuse = false;
245
+
246
+ const island = {
247
+ build: buildIslands,
248
+ root: join(import.meta.dir, '..', '..', '..', '..'),
249
+ // The island's page connection outlives its DOM: reset with the block, never a raw afterAll.
250
+ teardown: resetPageRealtime,
251
+ // What the server rendered inside the island's wrapper. \`mount\` replaces it.
252
+ shell: '<p>Loading</p>',
253
+ globals: {
254
+ fetch: (url: string, init: RequestInit): Promise<Response> => {
255
+ calls.push({
256
+ url,
257
+ key: new Headers(init.headers).get('idempotency-key'),
258
+ body: JSON.parse(String(init.body)) as Record<string, unknown>,
259
+ });
260
+ return Promise.resolve(
261
+ refuse
262
+ ? Response.json(
263
+ { code: 'X_FORBIDDEN', cause: 'denied', fix: 'bunx x policy explain --json' },
264
+ { status: 403, headers: { 'content-type': 'application/problem+json' } },
265
+ )
266
+ : Response.json({ id: 'created' }),
267
+ );
268
+ },
269
+ },
270
+ };
271
+
272
+ /** Until the status line changes, a bounded number of macrotasks: the send is several awaits deep. */
273
+ async function statusSettled(mounted: MountedIsland): Promise<void> {
274
+ const before = mounted.text('[data-role="status"]');
275
+ for (let tick = 0; tick < 200; tick += 1) {
276
+ if (mounted.text('[data-role="status"]') !== before) return;
277
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
278
+ }
279
+ }
280
+
281
+ describeIslandState(postFormStates, 'idle', island, (mounted) => {
282
+ test('mount replaces the server shell with the editor', () => {
283
+ expect(mounted().find('p')?.getAttribute('data-role')).toBe('status');
284
+ expect(mounted().text('button')).toBe('Save');
285
+ expect(mounted().code).not.toMatch(/\\bReact\\b/);
286
+ });
287
+
288
+ test('submit sends createPost under an idempotency key, and the status answers', async () => {
289
+ refuse = false;
290
+ const title: FakeElement | null = mounted().find('input[aria-label="Title"]');
291
+ const price: FakeElement | null = mounted().find('input[aria-label="Price"]');
292
+ expect(title).not.toBeNull();
293
+ expect(price).not.toBeNull();
294
+ if (title !== null) title.value = 'First post';
295
+ if (price !== null) price.value = '12.50';
296
+ expect(mounted().fire(title, 'input')).toBe(true);
297
+ expect(mounted().fire(price, 'input')).toBe(true);
298
+ expect(mounted().fire('form', 'submit', { preventDefault: () => {} })).toBe(true);
299
+ await statusSettled(mounted());
300
+
301
+ const sent = calls.at(-1);
302
+ expect(sent?.url).toContain('/api/posts/create');
303
+ expect(sent?.body).toEqual({ title: 'First post', price: { minor: 1250, currency: 'USD' } });
304
+ // The key IS the write's identity: a replay of it is answered, never run twice.
305
+ expect(sent?.key).toMatch(/^createPost:/);
306
+ expect(mounted().text('[data-role="status"]')).toBe('Saved');
307
+ });
308
+
309
+ test('a refusal reaches retry, and is never queued for a replay', async () => {
310
+ refuse = true;
311
+ expect(mounted().fire('form', 'submit', { preventDefault: () => {} })).toBe(true);
312
+ await statusSettled(mounted());
313
+
314
+ expect(mounted().text('[data-role="status"]')).toBe('That did not save. Try again.');
315
+ expect(mounted().find('[data-role="status"]')?.getAttribute('data-queued')).toBe('0');
316
+ });
317
+ });
318
+
319
+ describeIslandState(postFormStates, 'long-labels', island, (mounted) => {
320
+ test('every label is the state’s own, in the locale it names', () => {
321
+ expect(mounted().find('input[aria-label="Bezeichnung des Beitrags"]')).not.toBeNull();
322
+ expect(mounted().find('input[aria-label="Title"]')).toBeNull();
323
+ expect(mounted().text('button')).toBe('Änderungen speichern');
324
+ expect(mounted().documentElement.getAttribute('lang')).toBe('de');
325
+ });
326
+ });
327
+ `;
328
+
329
+ /** The island, its states and its test — each REPLACING the default form's file of the same path. */
330
+ export const offlineFormFiles = (): readonly GeneratedFile[] => [
331
+ { path: `${DIR}/post-form.island.tsx`, contents: island() },
332
+ { path: `${DIR}/post-form.island.states.ts`, contents: states() },
333
+ { path: `${DIR}/post-form.island.test.ts`, contents: islandTest() },
334
+ ];