@ultimat3/cli 31.25.0 → 31.27.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 (123) hide show
  1. package/CLAUDE.md +44 -36
  2. package/README.md +5 -4
  3. package/package.json +29 -29
  4. package/src/app-mcp.ts +17 -3
  5. package/src/cmd-cache-spec.ts +5 -2
  6. package/src/cmd-db-recount.ts +7 -0
  7. package/src/cmd-db-spec.ts +2 -3
  8. package/src/cmd-db.ts +0 -2
  9. package/src/cmd-deploy-verify-sample.ts +93 -0
  10. package/src/cmd-deploy-verify.ts +2 -41
  11. package/src/cmd-dev-spec.ts +15 -1
  12. package/src/cmd-dev.ts +31 -4
  13. package/src/cmd-doctor.ts +4 -1
  14. package/src/cmd-exercise-spec.ts +7 -1
  15. package/src/cmd-exercise.ts +22 -10
  16. package/src/cmd-generate.ts +2 -0
  17. package/src/cmd-jobs-spec.ts +3 -6
  18. package/src/cmd-jobs.ts +1 -7
  19. package/src/cmd-logs-spec.ts +2 -1
  20. package/src/cmd-logs.ts +9 -28
  21. package/src/cmd-planned.ts +11 -45
  22. package/src/cmd-profile-frames.ts +99 -0
  23. package/src/cmd-profile-spec.ts +24 -0
  24. package/src/cmd-profile.ts +164 -0
  25. package/src/cmd-status-sample.ts +57 -0
  26. package/src/cmd-status-spec.ts +30 -0
  27. package/src/cmd-status.ts +108 -0
  28. package/src/cmd-token-spec.ts +5 -2
  29. package/src/cmd-token.ts +7 -3
  30. package/src/coverage-island.ts +121 -0
  31. package/src/coverage-lcov.ts +49 -5
  32. package/src/coverage-remap.ts +146 -0
  33. package/src/db-replay-engine-prepared.ts +66 -0
  34. package/src/db-replay-engine-template.ts +156 -0
  35. package/src/db-replay-engine.ts +4 -0
  36. package/src/db-replay-scratch-reap.ts +54 -0
  37. package/src/deploy-verify-flags.ts +9 -2
  38. package/src/deploy-verify-grade.ts +10 -3
  39. package/src/dev-boot.ts +14 -1
  40. package/src/dev-dashboard-guard.ts +57 -10
  41. package/src/dev-host.ts +46 -0
  42. package/src/dev-tls-cache.ts +103 -0
  43. package/src/dev-tls-der.ts +69 -0
  44. package/src/dev-tls.ts +120 -0
  45. package/src/dispatch.ts +6 -1
  46. package/src/doctor-browser.ts +60 -0
  47. package/src/error-codes-verify.ts +47 -0
  48. package/src/error-codes.ts +14 -23
  49. package/src/exercise-database.ts +40 -7
  50. package/src/exercise-push-device.ts +51 -0
  51. package/src/exercise-route-api.ts +74 -0
  52. package/src/exercise-routes.ts +14 -5
  53. package/src/exercise-services.ts +3 -1
  54. package/src/exercise-shard-flag.ts +47 -0
  55. package/src/fix-command.ts +2 -2
  56. package/src/generate-factories.ts +9 -11
  57. package/src/generate-feature-required.ts +9 -4
  58. package/src/generate-files.ts +20 -2
  59. package/src/generate-kinds.ts +5 -1
  60. package/src/guards.ts +21 -6
  61. package/src/island-bundle-options.ts +48 -0
  62. package/src/island-bundle.ts +18 -46
  63. package/src/island-link.ts +5 -0
  64. package/src/island-outputs.ts +5 -0
  65. package/src/mcp-errors-verify.ts +35 -0
  66. package/src/mcp-errors.ts +10 -19
  67. package/src/mcp-host-logs.ts +121 -0
  68. package/src/mcp-host.ts +12 -73
  69. package/src/messages-floor.ts +19 -0
  70. package/src/messages-status.ts +10 -0
  71. package/src/messages.ts +21 -0
  72. package/src/registry.ts +4 -0
  73. package/src/role-start-types.ts +7 -0
  74. package/src/role-start.ts +4 -0
  75. package/src/serve-boot.ts +7 -1
  76. package/src/serve-env-tls.ts +57 -0
  77. package/src/solid-loader.ts +27 -10
  78. package/src/templates/generate-export-rows.ts +136 -0
  79. package/src/templates/generate-import-rows.ts +186 -0
  80. package/src/templates/generate-rows-slice.ts +95 -0
  81. package/src/templates/github/ci.yml.ts +4 -0
  82. package/src/templates/scaffold-db-package.ts +3 -0
  83. package/src/templates/scaffold-docs.ts +8 -6
  84. package/src/templates/scaffold-repo.ts +2 -7
  85. package/src/templates/scaffold-site.ts +4 -1
  86. package/src/templates/scaffold-suites.ts +72 -0
  87. package/src/templates/scaffold-test-services.ts +35 -10
  88. package/src/templates/scaffold-verify-floor.ts +53 -31
  89. package/src/templates/shapes/api.ts +4 -0
  90. package/src/templates/slice-foundation.ts +3 -3
  91. package/src/unthrown-codes.ts +1 -1
  92. package/src/upgrade-gate.ts +6 -1
  93. package/src/upgrade-guards-baseline.ts +43 -0
  94. package/src/upgrade-guards.ts +37 -2
  95. package/src/upgrade-report.ts +3 -0
  96. package/src/verify-coverage-run.ts +42 -11
  97. package/src/verify-e2e.ts +115 -4
  98. package/src/verify-floor.ts +27 -0
  99. package/src/verify-guard-baseline.ts +109 -0
  100. package/src/verify-live.ts +72 -0
  101. package/src/verify-merge-skips.ts +51 -0
  102. package/src/verify-merge.ts +36 -2
  103. package/src/verify-run.ts +48 -7
  104. package/src/verify-services.ts +287 -0
  105. package/src/verify-skip-reason.ts +53 -0
  106. package/src/verify-strict.ts +108 -0
  107. package/src/verify-test-command.ts +129 -0
  108. package/src/verify-tests.ts +39 -126
  109. package/types/babel-modules.d.ts +2 -0
  110. package/wiki/Agents.md +2 -5
  111. package/wiki/CLI-Reference.md +142 -23
  112. package/wiki/Caching-And-Invalidation.md +1 -1
  113. package/wiki/Entities-And-Migrations.md +1 -1
  114. package/wiki/Interface-Rules.md +5 -0
  115. package/wiki/Jobs-And-Workflows.md +3 -3
  116. package/wiki/Known-Gaps.md +5 -1
  117. package/wiki/MCP-And-AI.md +103 -2
  118. package/wiki/Mail.md +52 -0
  119. package/wiki/PWA-And-Offline.md +1 -1
  120. package/wiki/Scraping.md +19 -4
  121. package/wiki/Troubleshooting.md +3 -3
  122. package/wiki/Tutorial-05-Deploy-Free.md +2 -2
  123. package/wiki/Upgrading.md +3 -0
package/src/registry.ts CHANGED
@@ -27,6 +27,7 @@ import { explainSpec } from './cmd-explain-spec';
27
27
  import { fixSpec } from './cmd-fix-spec';
28
28
  import { generateSpec } from './cmd-generate-spec';
29
29
  import { graphSpec } from './cmd-graph-spec';
30
+ import { profileSpec } from './cmd-profile-spec';
30
31
  // Registered here, not by whichever command body happens to load: `dispatch` renders a CLI code's
31
32
  // title for a refusal raised before any body is imported.
32
33
  import './error-codes';
@@ -47,6 +48,7 @@ import { reproSpec } from './cmd-repro-spec';
47
48
  import { routesSpec } from './cmd-routes-spec';
48
49
  import { secretsSpec } from './cmd-secrets-spec';
49
50
  import { shotSpec } from './cmd-shot-spec';
51
+ import { statusSpec } from './cmd-status-spec';
50
52
  import { stopSpec } from './cmd-stop-spec';
51
53
  import { tasksSpec } from './cmd-tasks-spec';
52
54
  import { testSpec } from './cmd-test-spec';
@@ -135,6 +137,8 @@ export const LAZY_COMMANDS: readonly LazyCommand[] = [
135
137
  lazy(logsSpec, async () => (await import('./cmd-logs')).logsCommand),
136
138
  lazy(cacheSpec, async () => (await import('./cmd-cache')).cacheCommand),
137
139
  lazy(explainSpec, async () => (await import('./cmd-explain')).explainCommand),
140
+ lazy(profileSpec, async () => (await import('./cmd-profile')).profileCommand),
141
+ lazy(statusSpec, async () => (await import('./cmd-status')).statusCommand),
138
142
  ];
139
143
 
140
144
  /**
@@ -11,6 +11,7 @@ import type { Env } from './runtime-bindings';
11
11
  import type { LiveFeed } from './runtime-live-feed';
12
12
  import type { RuntimeOverrides } from './runtime-overrides';
13
13
  import type { RunningServices } from './runtime-services';
14
+ import type { ListenerTls } from './serve-env-tls';
14
15
  import type { WebBinding } from './web-binding';
15
16
 
16
17
  /** The roles `x dev` starts when `--role` names none, in boot order. */
@@ -33,6 +34,12 @@ export interface StartRolesOptions {
33
34
  * probe, which is the same failure in four costumes.
34
35
  */
35
36
  readonly http?: WebBinding;
37
+ /**
38
+ * The web role's certificate and key, PEM: its listener serves TLS. Absent is plaintext, the
39
+ * default — `x dev --tls` and `TLS_CERT`/`TLS_KEY` are the two callers. Never the `sync` node or
40
+ * the metrics endpoint: the sync socket is served on the web port too (`role-sync`).
41
+ */
42
+ readonly tls?: ListenerTls;
36
43
  /**
37
44
  * The app's `auth.signInPath`. Threaded rather than read from the config here because
38
45
  * `startRoles` takes plain values — a test starts a web role with no `app.config.ts` at all.
package/src/role-start.ts CHANGED
@@ -207,6 +207,7 @@ function startWeb(
207
207
  dev: binding.dev,
208
208
  buildId: options.buildId,
209
209
  hostname: binding.hostname,
210
+ ...(options.tls === undefined ? {} : { tls: options.tls }),
210
211
  signInPath: options.signInPath ?? null,
211
212
  // One declaration, never half of one: `defineHttpConfig` refuses `trustProxy` without hops.
212
213
  ...(hops === null ? {} : { trustProxy: true, trustedProxyHops: hops }),
@@ -223,6 +224,9 @@ function startWeb(
223
224
  // document that carries an island, so `script-src 'self'` meant no island booted anywhere
224
225
  // the policy is enforced — every container, and never `x dev`, where it is report-only.
225
226
  security: {
227
+ // A dev listener on TLS sends no HSTS: browsers pin it per HOST, so a two-year policy
228
+ // from `https://localhost:3000` would force every other localhost port onto https.
229
+ ...(binding.dev && options.tls !== undefined ? { hsts: null } : {}),
226
230
  csp: {
227
231
  extend: {
228
232
  'style-src': inlineStyleSources(options.inlineStyles ?? []),
package/src/serve-boot.ts CHANGED
@@ -27,6 +27,7 @@ import { bootTimeline } from './serve-boot-phases';
27
27
  import { bootWarningConcerns, warnAtBoot } from './serve-boot-warnings';
28
28
  import { loadDrainConfig, loadHealthConfig } from './serve-drain';
29
29
  import { configureReporting, containerBinding, metricsPortFor, portFromEnv } from './serve-env';
30
+ import { type ListenerTls, tlsFromEnv } from './serve-env-tls';
30
31
  import { adoptPrebuiltStyles, reportBootBuilds, watchBootBuilds } from './serve-prebuilt';
31
32
  import type { ServedApp, ServeOptions } from './serve-types';
32
33
 
@@ -92,6 +93,8 @@ export async function bootServing(boot: {
92
93
  readonly metrics: MetricsEndpoint;
93
94
  }): Promise<ServedApp> {
94
95
  const { options } = boot;
96
+ // Before any service starts: a half-declared pair is refused while there is nothing to unwind.
97
+ const tls = boot.role === 'web' ? await tlsFromEnv(options.env) : undefined;
95
98
  // One `boot.phase` line as each step ends, so a slow boot names its slow step (U12).
96
99
  const timeline = bootTimeline(boot.role, options.runtime?.clock);
97
100
  const services = resolveServices(options.root, options.env);
@@ -103,7 +106,7 @@ export async function bootServing(boot: {
103
106
  const runtime = await startServices(services, options.env, options.runtime, schema, [boot.role]);
104
107
  boot.acquired.push(() => runtime.stop());
105
108
  timeline.phase('services');
106
- return bootRoles({ ...boot, runtime, timeline });
109
+ return bootRoles({ ...boot, runtime, timeline, ...(tls === undefined ? {} : { tls }) });
107
110
  }
108
111
 
109
112
  /**
@@ -138,6 +141,8 @@ async function bootRoles(boot: {
138
141
  /** The scrape listener `serveApp` opened before any of this work; `startRoles` adopts it. */
139
142
  readonly metrics: MetricsEndpoint;
140
143
  readonly timeline: BootTimeline;
144
+ /** `TLS_CERT`/`TLS_KEY`, read by `bootServing`; the web role's listener serves TLS with it. */
145
+ readonly tls?: ListenerTls;
141
146
  }): Promise<ServedApp> {
142
147
  const { options, role, runtime, acquired, metrics, timeline } = boot;
143
148
  // Before the app's modules, because importing one may register a `close` hook, and that phase
@@ -239,6 +244,7 @@ async function bootRoles(boot: {
239
244
  // process and `x dev` cannot answer a browser differently.
240
245
  root: options.root,
241
246
  http: containerBinding(options.env, options.hostname),
247
+ ...(boot.tls === undefined ? {} : { tls: boot.tls }),
242
248
  // `app.config.ts`'s drain section: the readiness grace the chart's grace period is sized for.
243
249
  ...(drain === undefined ? {} : { drain }),
244
250
  // The read-replica scope rides in FRONT of whatever the host supplied, or the host's own value
@@ -0,0 +1,57 @@
1
+ // `TLS_CERT` / `TLS_KEY`: the paths of the PEM pair a container's `web` role serves TLS with, read
2
+ // once at boot. Both or neither — a listener that silently stayed plaintext because one variable
3
+ // was mistyped is the failure this refuses. Absent, nothing changes: the ingress terminates TLS.
4
+
5
+ import { renderFixShellArg, UltimateError } from '@ultimat3/core';
6
+ import type { HttpConfigInput } from '@ultimat3/http';
7
+ import type { Env } from './runtime-bindings';
8
+
9
+ export type ListenerTls = NonNullable<HttpConfigInput['tls']>;
10
+
11
+ export const TLS_CERT_ENV = 'TLS_CERT';
12
+ export const TLS_KEY_ENV = 'TLS_KEY';
13
+
14
+ /** `X_CONFIG_INVALID`, http's own code for a listener it cannot build. Never the file's bytes. */
15
+ export class ListenerTlsInvalidError extends UltimateError {
16
+ constructor(input: { name: string; reason: string }) {
17
+ super({
18
+ code: 'X_CONFIG_INVALID',
19
+ cause: `${input.name} ${input.reason}; the web role serves TLS with ${TLS_CERT_ENV} and ${TLS_KEY_ENV} together — two PEM file paths — or with neither`,
20
+ fix: `docker run -e TLS_CERT=/run/secrets/tls.crt -e TLS_KEY=/run/secrets/tls.key <image> # or unset both and terminate TLS at the ingress`,
21
+ meta: { key: input.name },
22
+ });
23
+ }
24
+ }
25
+
26
+ const setValue = (env: Env, name: string): string | undefined => {
27
+ const raw = env[name]?.trim();
28
+ return raw === undefined || raw.length === 0 ? undefined : raw;
29
+ };
30
+
31
+ async function readPem(name: string, path: string): Promise<string> {
32
+ const file = Bun.file(path);
33
+ const text = (await file.exists()) ? await file.text().catch(() => '') : '';
34
+ if (text.length === 0) {
35
+ throw new ListenerTlsInvalidError({
36
+ name,
37
+ reason: `names ${renderFixShellArg(path, '<path>')}, which is missing, empty or unreadable`,
38
+ });
39
+ }
40
+ return text;
41
+ }
42
+
43
+ /** The pair, read; `undefined` when neither is set. `defineHttpConfig` judges the PEM itself. */
44
+ export async function tlsFromEnv(env: Env): Promise<ListenerTls | undefined> {
45
+ const certPath = setValue(env, TLS_CERT_ENV);
46
+ const keyPath = setValue(env, TLS_KEY_ENV);
47
+ if (certPath === undefined && keyPath === undefined) return undefined;
48
+ if (certPath === undefined || keyPath === undefined) {
49
+ const [missing, present] =
50
+ certPath === undefined ? [TLS_CERT_ENV, TLS_KEY_ENV] : [TLS_KEY_ENV, TLS_CERT_ENV];
51
+ throw new ListenerTlsInvalidError({
52
+ name: missing,
53
+ reason: `is unset while ${present} is set`,
54
+ });
55
+ }
56
+ return { cert: await readPem(TLS_CERT_ENV, certPath), key: await readPem(TLS_KEY_ENV, keyPath) };
57
+ }
@@ -56,8 +56,9 @@ const babel = () => {
56
56
  };
57
57
 
58
58
  interface CacheEntry {
59
- /** `contentHash` of the source the code was compiled from. */
59
+ /** `contentHash` of the source the code was compiled from, and the flag it was compiled under. */
60
60
  readonly hash: string;
61
+ readonly retainLines: boolean;
61
62
  readonly code: string;
62
63
  }
63
64
 
@@ -88,11 +89,20 @@ export function clearIslandTransformCache(): void {
88
89
  *
89
90
  * The output is still TypeScript — Babel PARSES the annotations here and does not strip them,
90
91
  * which is why the plugin declares `loader: 'ts'` and lets Bun remove them.
92
+ *
93
+ * `retainLines` is a coverage build's alone (`solidJsxPluginFor`): Babel then keeps each source
94
+ * line at its own line number, so the island chunk's map names lines the file really holds there
95
+ * (`coverage-remap.ts`). Never on a shipped build — it is a layout, and a layout is bytes.
91
96
  */
92
- export async function transformIslandTsx(source: string, path: string): Promise<string> {
97
+ export async function transformIslandTsx(
98
+ source: string,
99
+ path: string,
100
+ options: { readonly retainLines?: boolean } = {},
101
+ ): Promise<string> {
102
+ const retainLines = options.retainLines === true;
93
103
  const hash = contentHash(source);
94
104
  const hit = cache.get(path);
95
- if (hit !== undefined && hit.hash === hash) return hit.code;
105
+ if (hit !== undefined && hit.hash === hash && hit.retainLines === retainLines) return hit.code;
96
106
 
97
107
  // Babel installs its own `prepareStackTrace` on the first TRANSFORM — not on import, which is
98
108
  // where this guard was first put — and leaving it installed makes `Error.captureStackTrace`
@@ -114,6 +124,7 @@ export async function transformIslandTsx(source: string, path: string): Promise<
114
124
  // have one must not change what its islands compile to.
115
125
  babelrc: false,
116
126
  configFile: false,
127
+ retainLines,
117
128
  parserOpts: { plugins: [...PARSER_PLUGINS] },
118
129
  presets: [[solidPreset, PRESET_OPTIONS]],
119
130
  });
@@ -131,14 +142,14 @@ export async function transformIslandTsx(source: string, path: string): Promise<
131
142
  logs: 'the Solid JSX transform emitted no code',
132
143
  });
133
144
  }
134
- cache.set(path, { hash, code });
145
+ cache.set(path, { hash, retainLines, code });
135
146
  return code;
136
147
  }
137
148
 
138
149
  /**
139
- * The plugin `island-bundle.ts` hands `Bun.build`. It carries no state of its own, so one frozen
140
- * descriptor serves every concurrent island build — `Bun.build` calls `setup` once per build with
141
- * that build's own builder.
150
+ * The plugin `island-bundle.ts` hands `Bun.build`. It carries no state of its own, so one
151
+ * descriptor per `retainLines` serves every concurrent island build — `Bun.build` calls `setup`
152
+ * once per build with that build's own builder.
142
153
  *
143
154
  * `.tsx`, NOT `.island.tsx`. The narrow filter looks like axiom 6 and is the opposite of it: an
144
155
  * island that imports a plain `.tsx` component — the most ordinary thing an author does, and what
@@ -149,12 +160,18 @@ export async function transformIslandTsx(source: string, path: string): Promise<
149
160
  * names its island by SPECIFIER and never imports one. So `.tsx` here already means exactly the
150
161
  * set that ships to a browser — the filter never had to do that work.
151
162
  */
152
- export const solidJsxPlugin: BunPlugin = {
163
+ export const solidJsxPluginFor = (retainLines: boolean): BunPlugin => ({
153
164
  name: 'ultimate-island-solid',
154
165
  setup(build): void {
155
166
  build.onLoad({ filter: /\.tsx$/ }, async ({ path }) => ({
156
- contents: await transformIslandTsx(await Bun.file(path).text(), path),
167
+ contents: await transformIslandTsx(await Bun.file(path).text(), path, { retainLines }),
157
168
  loader: 'ts',
158
169
  }));
159
170
  },
160
- };
171
+ });
172
+
173
+ /** The shipped build's transform. */
174
+ export const solidJsxPlugin: BunPlugin = solidJsxPluginFor(false);
175
+
176
+ /** A coverage build's (`buildIslands({ coverage: true })`): the same compile, lines kept. */
177
+ export const solidJsxCoveragePlugin: BunPlugin = solidJsxPluginFor(true);
@@ -0,0 +1,136 @@
1
+ // `x g export-rows` — one org's rows of the slice's table, streamed to storage a page at a time.
2
+ // `exportRows()` is a factory over `job()`, never a ninth primitive: the export is retried,
3
+ // resumed from its cursor, deduped per artifact and in the manifest like any job.
4
+
5
+ import type { RowsOptions } from './generate-rows-slice';
6
+ import { assertScaffoldRow, rowsTestHead } from './generate-rows-slice';
7
+ import { sortedImports } from './imports';
8
+ import type { GeneratedFile, NameSet } from './naming';
9
+ import { names } from './naming';
10
+ import { PLACEHOLDER_DB_MODULE } from './scaffold-db-client';
11
+ import { sliceFoundation } from './slice-foundation';
12
+
13
+ const source = (
14
+ name: NameSet,
15
+ feature: NameSet,
16
+ dbModule: string,
17
+ ): string => `// ${name.camel}: one org's ${feature.plural}, as csv parts in storage. \`exportRows()\` is a
18
+ // factory over job(), so the export is retried, resumes from its cursor and is in the manifest.
19
+ // List this module in apps/web/api/index.ts's \`jobs:\` to register it.
20
+
21
+ ${sortedImports([
22
+ "import { exportRows, t } from '@ultimat3/jobs';",
23
+ "import { disk } from '@ultimat3/storage';",
24
+ `import { db } from '${dbModule}';`,
25
+ ])}
26
+ import type { ${feature.pascal} } from '../entity';
27
+
28
+ /** The columns, in order: the csv header, and the only keys a row may answer. */
29
+ export const ${name.camel}Columns = ['id', 'title', 'priceMinor', 'priceCurrency', 'createdAt'];
30
+
31
+ /**
32
+ * One row's cells. Money as its integer minor units beside its currency, never a float; a date
33
+ * as a UTC instant, never a zone-less format. Add a column here and in the list above together.
34
+ */
35
+ export const ${name.camel}Row = (row: ${feature.pascal}) => ({
36
+ id: row.id,
37
+ title: row.title,
38
+ priceMinor: row.price.minor,
39
+ priceCurrency: row.price.currency,
40
+ createdAt: row.createdAt.toISOString(),
41
+ });
42
+
43
+ export const ${name.camel} = exportRows({
44
+ // Pinned: the queue row, the step trace and every part's step carry this name.
45
+ name: '${name.kebab}',
46
+ input: t.object({ orgId: t.uuid, exportId: t.string }),
47
+ // The security boundary: an export concentrates one org's rows into one downloadable object,
48
+ // so the run is scoped to the org its input names — and the read below to the same org.
49
+ tenant: ({ orgId }) => orgId,
50
+ prefix: ({ orgId, exportId }) => \`exports/${name.kebab}/\${orgId}/\${exportId}\`,
51
+ source: ({ input }) => db.${feature.plural}.where({ orgId: input.orgId }),
52
+ format: 'csv',
53
+ columns: ${name.camel}Columns,
54
+ row: ${name.camel}Row,
55
+ // A thunk, read per write: the app's disks exist after boot, never at import.
56
+ sink: () => disk(),
57
+ });
58
+ `;
59
+
60
+ const jobSuite = (
61
+ name: NameSet,
62
+ ): string => `// ${name.camel}'s durable identity: a job, one live pass per artifact. The pass itself — the rows it
63
+ // writes and the org it keeps to — is the unit suite's, next door.
64
+
65
+ import { memoryJobDriver } from '@ultimat3/jobs';
66
+ import { beforeAll, expect, jobTest, swapAdapter } from '@ultimat3/testing';
67
+ import { ${name.camel} } from './${name.kebab}';
68
+
69
+ // The queue is a process-global adapter port, so it is swapped for this file and put back after.
70
+ beforeAll(() => swapAdapter('jobs', memoryJobDriver()));
71
+
72
+ const input = { orgId: '00000000-0000-4000-8000-000000000002', exportId: 'weekly' };
73
+
74
+ jobTest('is a job scoped to the org its input names', () => {
75
+ expect(${name.camel}.kind).toBe('job');
76
+ expect(${name.camel}.tenantFor(input)).toBe(input.orgId);
77
+ expect(${name.camel}.retry.attempts).toBeGreaterThan(1);
78
+ });
79
+
80
+ jobTest('enqueues once per artifact, and dedupes a second while one is live', async () => {
81
+ const first = await ${name.camel}.enqueue(input);
82
+ expect(first.deduped).toBe(false);
83
+ const again = await ${name.camel}.enqueue(input);
84
+ expect(again.deduped).toBe(true);
85
+ });
86
+ `;
87
+
88
+ const unitSuite = (
89
+ name: NameSet,
90
+ feature: NameSet,
91
+ dbModule: string,
92
+ ): string => `// ${name.camel}, RUN: one pass by a worker in this process, over rows in the in-memory driver, into
93
+ // a memory disk. What is worth failing on: the header, one org's rows and never another's.
94
+ ${rowsTestHead(name, feature, dbModule, [name.camel, `${name.camel}Row`])}
95
+ const partText = async (orgId: string, exportId: string): Promise<string> => {
96
+ const read = await disk.get(\`exports/${name.kebab}/\${orgId}/\${exportId}/part-00000.csv\`);
97
+ return new TextDecoder().decode(read.bytes);
98
+ };
99
+
100
+ unitTest('one pass writes the org rows as csv, and no other org', async ({ runJobs }) => {
101
+ await store(orgA, 'ours');
102
+ await store(orgB, 'theirs');
103
+ const trace = await runJobs(${name.camel}, { orgId: orgA, exportId: 'weekly' });
104
+ expect(trace.executions.map((run) => run.outcome)).toEqual(['completed']);
105
+ const text = await partText(orgA, 'weekly');
106
+ expect(text.split('\\n')[0]).toBe('id,title,priceMinor,priceCurrency,createdAt');
107
+ expect(text).toContain('ours,1250,USD');
108
+ expect(text).not.toContain('theirs');
109
+ });
110
+
111
+ unitTest('a row is its cells: integer minor units, its currency, a UTC instant', async () => {
112
+ const stored = await store(orgA, 'one');
113
+ expect(${name.camel}Row(stored)).toEqual({
114
+ id: stored.id,
115
+ title: 'one',
116
+ priceMinor: 1250,
117
+ priceCurrency: 'USD',
118
+ createdAt: stored.createdAt.toISOString(),
119
+ });
120
+ });
121
+ `;
122
+
123
+ /** The export and its job/unit suites in the feature's `jobs/`, the entity planted when absent. */
124
+ export function exportRowsFiles(rawName: string, target: RowsOptions): readonly GeneratedFile[] {
125
+ const name = names(rawName);
126
+ const feature = names(target.feature);
127
+ assertScaffoldRow('export-rows', name, target);
128
+ const dir = `${target.surfaceDir}/${target.feature}/jobs`;
129
+ const dbModule = target.dbModule ?? PLACEHOLDER_DB_MODULE;
130
+ return [
131
+ ...sliceFoundation(target, ['entity'], target.locales),
132
+ { path: `${dir}/${name.kebab}.ts`, contents: source(name, feature, dbModule) },
133
+ { path: `${dir}/${name.kebab}.job.test.ts`, contents: jobSuite(name) },
134
+ { path: `${dir}/${name.kebab}.test.ts`, contents: unitSuite(name, feature, dbModule) },
135
+ ];
136
+ }
@@ -0,0 +1,186 @@
1
+ // `x g import-rows` — an uploaded csv read a page at a time, through a schema, into the slice's
2
+ // table. `importRows()` is a factory over `job()`, never a ninth primitive: a killed attempt
3
+ // resumes at its byte offset, and a refused row is reported by line, never by value.
4
+
5
+ import type { ExerciseEntry } from '../exercise-entry-edit';
6
+ import type { RowsOptions } from './generate-rows-slice';
7
+ import { assertScaffoldRow, rowsTestHead } from './generate-rows-slice';
8
+ import { sortedImports } from './imports';
9
+ import type { GeneratedFile, NameSet } from './naming';
10
+ import { names } from './naming';
11
+ import { PLACEHOLDER_DB_MODULE } from './scaffold-db-client';
12
+ import { sliceFoundation } from './slice-foundation';
13
+
14
+ const source = (
15
+ name: NameSet,
16
+ feature: NameSet,
17
+ dbModule: string,
18
+ ): string => `// ${name.camel}: an uploaded csv of ${feature.plural}, into one org's rows. \`importRows()\` is a
19
+ // factory over job(), so a killed attempt resumes at its byte offset and the run is in the manifest.
20
+ // List this module in apps/web/api/index.ts's \`jobs:\` to register it.
21
+
22
+ ${sortedImports([
23
+ "import { importRows, t } from '@ultimat3/jobs';",
24
+ "import { disk } from '@ultimat3/storage';",
25
+ `import { db } from '${dbModule}';`,
26
+ ])}
27
+
28
+ /** Where one org's uploads for this import sit: the only keys an import for that org may read. */
29
+ export const ${name.camel}Prefix = (orgId: string): string => \`imports/${name.kebab}/\${orgId}/\`;
30
+
31
+ export const ${name.camel} = importRows({
32
+ // Pinned: the queue row, the step trace and every page's step carry this name.
33
+ name: '${name.kebab}',
34
+ // A pointer to the upload, never its rows. The key is the CALLER'S, so it is held to the org the
35
+ // run is scoped to: \`tenant\` scopes the writes, and nothing else stops an import reading
36
+ // another org's upload into this one. The run's dedupe key is the upload key, so it is per org.
37
+ input: t.object({ orgId: t.uuid, key: t.string }).refine({
38
+ name: 'key-in-own-org',
39
+ message: 'key must sit under imports/${name.kebab}/<orgId>/ for the orgId this import names',
40
+ check: ({ orgId, key }) => key.startsWith(${name.camel}Prefix(orgId)) && !key.includes('..'),
41
+ path: ['key'],
42
+ }),
43
+ // The org the rows are written under is the input's: a scoped write fails closed without it.
44
+ tenant: ({ orgId }) => orgId,
45
+ // Thunks, read per page: the app's disks exist after boot, never at import.
46
+ source: () => disk(),
47
+ key: ({ key }) => key,
48
+ format: 'csv',
49
+ // The header must name exactly these, in any order.
50
+ columns: ['id', 'title', 'priceMinor', 'priceCurrency'],
51
+ // A row that fails this is reported by line and rule in the errors part, never by its value.
52
+ schema: t.object({
53
+ id: t.uuid,
54
+ title: t.string,
55
+ priceMinor: t.number.int(),
56
+ priceCurrency: t.string,
57
+ }),
58
+ // At least once per page, so the write is idempotent: a replayed row collides on its primary
59
+ // key and \`onMatch: 'nothing'\` writes nothing — never a row of another org.
60
+ handle: async ({ rows, input }) => {
61
+ await db.${feature.plural}.upsertAll(
62
+ rows.map((row) => ({
63
+ id: row.id,
64
+ orgId: input.orgId,
65
+ title: row.title,
66
+ price: { minor: row.priceMinor, currency: row.priceCurrency },
67
+ })),
68
+ { onConflict: ['id'], onMatch: 'nothing' },
69
+ );
70
+ },
71
+ errors: { sink: () => disk(), prefix: ({ orgId }) => \`imports/${name.kebab}/\${orgId}/errors\` },
72
+ });
73
+ `;
74
+
75
+ const jobSuite = (
76
+ name: NameSet,
77
+ ): string => `// ${name.camel}'s durable identity: a job scoped to the org its input names. The pass itself —
78
+ // the rows it writes and the rows it refuses — is the unit suite's, next door.
79
+
80
+ import { memoryJobDriver } from '@ultimat3/jobs';
81
+ import { beforeAll, expect, jobTest, swapAdapter } from '@ultimat3/testing';
82
+ import { ${name.camel} } from './${name.kebab}';
83
+
84
+ // The queue is a process-global adapter port, so it is swapped for this file and put back after.
85
+ beforeAll(() => swapAdapter('jobs', memoryJobDriver()));
86
+
87
+ const orgId = '00000000-0000-4000-8000-000000000002';
88
+ const input = { orgId, key: \`imports/${name.kebab}/\${orgId}/one.csv\` };
89
+
90
+ jobTest('is a job scoped to the org its input names', () => {
91
+ expect(${name.camel}.kind).toBe('job');
92
+ expect(${name.camel}.tenantFor(input)).toBe(input.orgId);
93
+ expect(${name.camel}.retry.attempts).toBeGreaterThan(1);
94
+ });
95
+ `;
96
+
97
+ const unitSuite = (
98
+ name: NameSet,
99
+ feature: NameSet,
100
+ dbModule: string,
101
+ ): string => `// ${name.camel}, RUN: one pass by a worker in this process, from a memory disk into the in-memory
102
+ // driver. What is worth failing on: rows land under the input's org, a bad row is refused by line,
103
+ // and a replay writes nothing twice.
104
+ ${rowsTestHead(name, feature, dbModule, [name.camel, `${name.camel}Prefix`])}
105
+ const idA = '00000000-0000-4000-8000-0000000000a1';
106
+ const idB = '00000000-0000-4000-8000-0000000000b2';
107
+
108
+ const upload = (key: string, lines: readonly string[]) =>
109
+ disk.put(key, new TextEncoder().encode(\`\${lines.join('\\n')}\\n\`));
110
+
111
+ /** An upload key under \`orgId\`'s own prefix: the only kind an import for that org may read. */
112
+ const keyOf = (orgId: string, file: string): string => \`\${${name.camel}Prefix(orgId)}\${file}\`;
113
+
114
+ const titlesOf = (orgId: string): Promise<readonly string[]> =>
115
+ inOrg(orgId, async () => (await db.${feature.plural}.all()).map((row) => row.title).toSorted());
116
+
117
+ unitTest('writes the valid rows under the input org, refuses the rest', async ({ runJobs }) => {
118
+ await upload(keyOf(orgA, 'one.csv'), [
119
+ 'id,title,priceMinor,priceCurrency',
120
+ \`\${idA},first,1250,USD\`,
121
+ 'not-a-uuid,second,1,USD',
122
+ \`\${idB},third,0,EUR\`,
123
+ ]);
124
+ const trace = await runJobs(${name.camel}, { orgId: orgA, key: keyOf(orgA, 'one.csv') });
125
+ expect(trace.executions.map((run) => run.outcome)).toEqual(['completed']);
126
+ expect(trace.executions[0]?.result).toMatchObject({ rows: 2, rejected: 1 });
127
+ expect(await titlesOf(orgA)).toEqual(['first', 'third']);
128
+ expect(await titlesOf(orgB)).toEqual([]);
129
+ });
130
+
131
+ unitTest('a replayed upload writes nothing twice', async ({ runJobs }) => {
132
+ await store(orgA, 'existing');
133
+ const key = keyOf(orgA, 'again.csv');
134
+ await upload(key, ['id,title,priceMinor,priceCurrency', \`\${idA},once,1,USD\`]);
135
+ await runJobs(${name.camel}, { orgId: orgA, key });
136
+ await runJobs(${name.camel}, { orgId: orgA, key });
137
+ expect(await titlesOf(orgA)).toEqual(['existing', 'once']);
138
+ });
139
+
140
+ // The key is the caller's: an import for org A naming org B's upload is refused at the input,
141
+ // before a byte is read — so B's rows never land under A, and whether B's object exists is not said.
142
+ unitTest('another org upload is refused at the input, and nothing is read', async ({ runJobs }) => {
143
+ await upload(keyOf(orgB, 'theirs.csv'), ['id,title,priceMinor,priceCurrency', \`\${idB},b,1,USD\`]);
144
+ const theirs = keyOf(orgB, 'theirs.csv');
145
+ for (const key of [theirs, \`\${keyOf(orgA, '..')}/\${orgB}/theirs.csv\`]) {
146
+ const [run] = (await runJobs(${name.camel}, { orgId: orgA, key })).executions;
147
+ // Terminal on its first attempt, with no step run: the object was never opened.
148
+ expect(run?.outcome).toBe('dead-lettered');
149
+ expect(run?.code).toBe('X_VALIDATION_FAILED');
150
+ expect(run?.steps).toEqual([]);
151
+ }
152
+ expect(await titlesOf(orgA)).toEqual([]);
153
+ });
154
+ `;
155
+
156
+ /**
157
+ * The job's entry in `apps/web/exercise.ts`: off, with its why. A draw names an upload key no
158
+ * object sits at, and the pass seeds no storage — so the run is proven in its unit suite instead.
159
+ */
160
+ const exerciseEntry = (name: NameSet): ExerciseEntry => ({
161
+ name: name.kebab,
162
+ value: [
163
+ '{',
164
+ ` off: 'reads an uploaded object, and the exercise pass seeds no storage — the whole pass runs in jobs/${name.kebab}.test.ts against a memory disk',`,
165
+ '}',
166
+ ].join('\n'),
167
+ });
168
+
169
+ /** The import and its job/unit suites in the feature's `jobs/`, the entity planted when absent. */
170
+ export function importRowsFiles(rawName: string, target: RowsOptions): readonly GeneratedFile[] {
171
+ const name = names(rawName);
172
+ const feature = names(target.feature);
173
+ assertScaffoldRow('import-rows', name, target);
174
+ const dir = `${target.surfaceDir}/${target.feature}/jobs`;
175
+ const dbModule = target.dbModule ?? PLACEHOLDER_DB_MODULE;
176
+ return [
177
+ ...sliceFoundation(target, ['entity'], target.locales),
178
+ {
179
+ path: `${dir}/${name.kebab}.ts`,
180
+ contents: source(name, feature, dbModule),
181
+ exercise: exerciseEntry(name),
182
+ },
183
+ { path: `${dir}/${name.kebab}.job.test.ts`, contents: jobSuite(name) },
184
+ { path: `${dir}/${name.kebab}.test.ts`, contents: unitSuite(name, feature, dbModule) },
185
+ ];
186
+ }
@@ -0,0 +1,95 @@
1
+ // What `x g export-rows` and `x g import-rows` share: both move the slice's OWN scaffolded table
2
+ // (`db.<plural>`, its `title` and `price`) through storage, so a slice whose entity is shaped
3
+ // otherwise is refused before a file is planned, and the test helpers are spelled once.
4
+
5
+ import { stripComments, UltimateError } from '@ultimat3/core';
6
+ import type { FeatureTarget } from './entity';
7
+ import { sortedImports } from './imports';
8
+ import type { NameSet } from './naming';
9
+ import { sliceTakesScaffoldRow } from './slice-foundation';
10
+ import { wrapImport } from './wrap';
11
+
12
+ /** The slice's files as `x g` read them off the disk: absent when the feature has none yet. */
13
+ export interface RowsOptions extends FeatureTarget {
14
+ readonly locales?: readonly string[];
15
+ readonly sliceEntity?: string;
16
+ readonly sliceRepo?: string;
17
+ }
18
+
19
+ /** Declared beside its two throwers' shared check: `errors.ts` sits at its ceiling. */
20
+ export class RowsSliceEntityError extends UltimateError {
21
+ constructor(input: {
22
+ readonly kind: string;
23
+ readonly name: string;
24
+ readonly feature: string;
25
+ readonly tables: readonly string[];
26
+ }) {
27
+ const declared = input.tables.length === 0 ? 'no table' : input.tables.join(', ');
28
+ super({
29
+ code: 'X_ROWS_SLICE_ENTITY',
30
+ cause: `x g ${input.kind} moves the ${input.feature} slice's own scaffolded table, and its entity.ts declares ${declared} instead — the generated columns would name fields that table does not have`,
31
+ fix: `x g job ${input.name} --feature ${input.feature} # then declare ${input.kind === 'export-rows' ? 'exportRows' : 'importRows'}({ … }) from @ultimat3/jobs in it over db.<one of: ${declared}>`,
32
+ meta: { feature: input.feature, tables: [...input.tables] },
33
+ });
34
+ }
35
+ }
36
+
37
+ /** Every table an `entity.ts` declares, in source order. */
38
+ const declaredTables = (source: string): readonly string[] =>
39
+ [...stripComments(source).matchAll(/\bentity\(\s*['"]([^'"]+)['"]/g)].map(
40
+ (match) => match[1] ?? '',
41
+ );
42
+
43
+ /** Refuses a slice whose entity is not the scaffolded row; a slice with none gets it planted. */
44
+ export function assertScaffoldRow(kind: string, name: NameSet, target: RowsOptions): void {
45
+ if (target.sliceEntity === undefined) return;
46
+ if (sliceTakesScaffoldRow(target, target.sliceEntity, target.sliceRepo)) return;
47
+ throw new RowsSliceEntityError({
48
+ kind,
49
+ name: name.kebab,
50
+ feature: target.feature,
51
+ tables: declaredTables(target.sliceEntity),
52
+ });
53
+ }
54
+
55
+ /** The unit suite's head: two orgs, a memory disk installed per test, both torn down after. */
56
+ export const rowsTestHead = (
57
+ name: NameSet,
58
+ feature: NameSet,
59
+ dbModule: string,
60
+ bindings: readonly string[] = [name.camel],
61
+ ): string => `${sortedImports([
62
+ "import { ctxOf, runWithContext } from '@ultimat3/core';",
63
+ "import { testActor } from '@ultimat3/policy';",
64
+ "import { defineStorage, memoryStorageDriver, resetStorage } from '@ultimat3/storage';",
65
+ "import { afterEach, beforeEach, expect, unitTest } from '@ultimat3/testing';",
66
+ `import { db, driver } from '${dbModule}';`,
67
+ ])}
68
+ import type { ${feature.pascal} } from '../entity';
69
+ ${wrapImport(bindings, `./${name.kebab}`)}
70
+
71
+ const orgA = '00000000-0000-4000-8000-000000000002';
72
+ const orgB = '00000000-0000-4000-8000-000000000009';
73
+
74
+ /** What a request is to the handle: an actor, whose org every read and write runs under. */
75
+ const inOrg = <T>(orgId: string, run: () => Promise<T>): Promise<T> =>
76
+ runWithContext(ctxOf({ actor: testActor('member', { orgId }).actor }), run);
77
+
78
+ const store = (orgId: string, title: string): Promise<${feature.pascal}> => {
79
+ const draft = { orgId, title, price: { minor: 1250, currency: 'USD' } };
80
+ return inOrg(orgId, () => db.${feature.plural}.insert(draft));
81
+ };
82
+
83
+ // A memory disk per test, installed as the app's storage: the job resolves \`disk()\` per page.
84
+ let disk = memoryStorageDriver();
85
+ beforeEach(() => {
86
+ disk = memoryStorageDriver();
87
+ defineStorage({ disks: { local: disk } });
88
+ });
89
+
90
+ // One store per process: without this, one test's rows and objects are the next test's fixtures.
91
+ afterEach(() => {
92
+ driver.reset?.();
93
+ resetStorage();
94
+ });
95
+ `;