@stacksjs/defaults 0.75.231 → 0.75.233

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 (41) hide show
  1. package/ai/skills/stacks-native/CATALOG.md +4 -4
  2. package/ai/skills/stacks-storage/SKILL.md +43 -0
  3. package/ai/skills/stacks-testing/SKILL.md +38 -10
  4. package/functions/dashboard-form.test.ts +41 -0
  5. package/functions/dashboard-form.ts +30 -0
  6. package/functions/dashboard-list.test.ts +228 -0
  7. package/functions/dashboard-list.ts +257 -0
  8. package/ide/vscode/package.json +1 -1
  9. package/package.json +2 -2
  10. package/project/storage/framework/types/browser-composables.d.ts +56 -0
  11. package/resources/components/Dashboard/Commerce/CommerceCategoriesDashboard.stx +2 -7
  12. package/resources/components/Dashboard/Commerce/CommerceCategoryDialog.stx +2 -4
  13. package/resources/components/Dashboard/Commerce/CommerceCouponDialog.stx +2 -4
  14. package/resources/components/Dashboard/Commerce/CommerceCouponsDashboard.stx +2 -7
  15. package/resources/components/Dashboard/Commerce/CommerceCustomerDialog.stx +2 -4
  16. package/resources/components/Dashboard/Commerce/CommerceCustomersDashboard.stx +2 -7
  17. package/resources/components/Dashboard/Commerce/CommerceGiftCardDialog.stx +2 -4
  18. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +2 -7
  19. package/resources/components/Dashboard/Commerce/CommerceManufacturerDialog.stx +2 -4
  20. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +2 -4
  21. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +2 -7
  22. package/resources/components/Dashboard/Commerce/CommerceProductDialog.stx +2 -4
  23. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +2 -7
  24. package/resources/components/Dashboard/Commerce/CommerceReviewEditDialog.stx +2 -4
  25. package/resources/components/Dashboard/Commerce/CommerceTaxDialog.stx +2 -4
  26. package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +2 -4
  27. package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +2 -4
  28. package/resources/components/Dashboard/Commerce/Delivery/CouriersDashboard.stx +45 -92
  29. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +46 -92
  30. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +46 -92
  31. package/resources/components/Dashboard/Commerce/Delivery/ShippingRatesDashboard.stx +44 -90
  32. package/resources/components/Dashboard/Commerce/Delivery/ShippingZonesDashboard.stx +45 -91
  33. package/resources/components/Dashboard/Commerce/PrintDeviceDialog.stx +2 -4
  34. package/resources/components/Dashboard/Commerce/PrintDevicesDashboard.stx +2 -7
  35. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +2 -4
  36. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +2 -4
  37. package/resources/components/Dashboard/Marketing/AbandonedCartsDashboard.stx +2 -9
  38. package/resources/components/Dashboard/Marketing/CampaignsDashboard.stx +2 -9
  39. package/resources/components/Dashboard/Marketing/MarketingListsDashboard.stx +2 -9
  40. package/resources/components/Dashboard/Marketing/SocialPostsDashboard.stx +2 -9
  41. package/resources/plugins/preloader.ts +9 -1
@@ -86,9 +86,9 @@ Browser runtime bindings are documented separately in `stacks-auto-imports`.
86
86
  | `@stacksjs/slug` | [`stacks-slug`](../stacks-slug/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/slug/src/index.ts) | 4 |
87
87
  | `@stacksjs/sms` | [`stacks-sms`](../stacks-sms/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/sms/src/index.ts) | 5 |
88
88
  | `@stacksjs/socials` | [`stacks-socials`](../stacks-socials/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/socials/src/index.ts) | 17 |
89
- | `@stacksjs/storage` | [`stacks-storage`](../stacks-storage/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/index.ts) | 40 |
89
+ | `@stacksjs/storage` | [`stacks-storage`](../stacks-storage/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/index.ts) | 42 |
90
90
  | `@stacksjs/strings` | [`stacks-strings`](../stacks-strings/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/strings/src/index.ts) | 7 |
91
- | `@stacksjs/testing` | [`stacks-testing`](../stacks-testing/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/testing/src/index.ts) | 14 |
91
+ | `@stacksjs/testing` | [`stacks-testing`](../stacks-testing/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/testing/src/index.ts) | 15 |
92
92
  | `@stacksjs/tinker` | [`stacks-repl`](../stacks-repl/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/tinker/src/index.ts) | 1 |
93
93
  | `@stacksjs/tunnel` | [`stacks-tunnel`](../stacks-tunnel/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/tunnel/src/index.ts) | 1 |
94
94
  | `@stacksjs/types` | [`stacks-types`](../stacks-types/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/types/src/index.ts) | 2 |
@@ -831,7 +831,7 @@ Declared runtime exports: `PathSanitizeError`, `Storage`, `StorageManager`, `Upl
831
831
 
832
832
  Local source modules: [src/adapters/index.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/adapters/index.ts), [src/bounded-text-file.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/bounded-text-file.ts), [src/completed-artifact-directory.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/completed-artifact-directory.ts), [src/copy.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/copy.ts), [src/delete.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/delete.ts), [src/drivers/index.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/drivers/index.ts), [src/facade.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/facade.ts), [src/file-info.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/file-info.ts), [src/files.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/files.ts), [src/folders.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/folders.ts), [src/fs.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/fs.ts), [src/glob.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/glob.ts), [src/hash.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/hash.ts), [src/helpers.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/helpers.ts), [src/mime-verify.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/mime-verify.ts), [src/path-sanitize.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/path-sanitize.ts), [src/provision.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/provision.ts), [src/s3-presigned-post.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/s3-presigned-post.ts), [src/signed-url.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/signed-url.ts), [src/static-serve.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/static-serve.ts), [src/storage.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/storage.ts), [src/temporary-workspaces.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/temporary-workspaces.ts), [src/types.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/types.ts), [src/types/filesystem.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/types/filesystem.ts), [src/uploaded-file.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/uploaded-file.ts), [src/zip.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/src/zip.ts).
833
833
 
834
- Evidence directory: [40 retained tests](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/tests). These files are evidence pointers, not a claim that all tests were run for this catalog.
834
+ Evidence directory: [42 retained tests](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/storage/tests). These files are evidence pointers, not a claim that all tests were run for this catalog.
835
835
 
836
836
  ### @stacksjs/strings
837
837
 
@@ -851,7 +851,7 @@ Read the entrypoint and package export map for re-exported or type-only surfaces
851
851
 
852
852
  Local source modules: [src/console.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/testing/src/console.ts), [src/disposable-database.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/testing/src/disposable-database.ts), [src/events.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/testing/src/events.ts), [src/feature.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/testing/src/feature.ts), [src/isolated.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/testing/src/isolated.ts), [src/mail.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/testing/src/mail.ts), [src/time.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/testing/src/time.ts).
853
853
 
854
- Evidence directory: [14 retained tests](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/testing/tests). These files are evidence pointers, not a claim that all tests were run for this catalog.
854
+ Evidence directory: [15 retained tests](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/testing/tests). These files are evidence pointers, not a claim that all tests were run for this catalog.
855
855
 
856
856
  ### @stacksjs/tinker
857
857
 
@@ -85,6 +85,36 @@ parent-directory authorization and domain validation. This is a local hard-link
85
85
  and directory-fsync protocol, not a cloud-adapter transaction or tested hardware
86
86
  power-loss guarantee.
87
87
 
88
+ For a durable ownership checkpoint before private bytes, use
89
+ `prepareCompletedArtifactDirectorySync(directory, entries, manifestJson, options)`
90
+ from the same subpath or package root. Its deeply frozen handle contains only
91
+ `receipt` and single-use `publishSync()`. Preparation exclusively creates and
92
+ syncs a private empty tree, then closes every descriptor. Persist the receipt
93
+ before calling the same live handle's publication method. The receipt records
94
+ canonical parent/tree/file identities and planned lengths/SHA-256; observed
95
+ file lengths are zero and `manifest.json` is absent. Planned metadata is not
96
+ completed content or a deletion receipt.
97
+
98
+ Pass plain data records/lists and unshared Uint8Array/Buffer views. Record/list
99
+ validation refuses proxies, getters, holes and hidden/symbol aliases without
100
+ executing caller code; byte views use intrinsic offsets rather than overrides.
101
+ Publication rechecks the empty tree and identities, writes/syncs
102
+ detached bytes, verifies readback hashes and exclusively links the registered
103
+ pending-manifest inode to completion. Every attempt consumes the handle, even
104
+ on error. Errors preserve state; JSON cannot rehydrate a writer. There is no
105
+ overwrite, arbitrary existing-directory writer or implicit cleanup.
106
+
107
+ Read the storage README's prepared-artifact section before integrating an
108
+ ownership ledger. It defines decimal-string identities, planned byte semantics,
109
+ birth-time availability, prepublication-only change time and legitimate link
110
+ transitions. Parent paths must already exist, belong to the operator and remain
111
+ controlled. Canonical ancestor aliases are allowed; final targets are exclusive.
112
+ Both calls block the isolate, including while holding any caller transaction.
113
+ Caps bound bytes/files rather than I/O duration; database contention and SQL/FS
114
+ atomicity remain caller concerns. The existing async writer keeps asynchronous
115
+ filesystem execution. Real process-interruption tests do not establish hardware
116
+ power-loss, hostile same-user race, deletion or media-erasure guarantees.
117
+
88
118
  ### Recoverable temporary workspaces
89
119
 
90
120
  Use `TemporaryWorkspaceJournal` for workers that recover temporary directories after a process interruption. Keep its private journal outside job-controlled checkouts and separate it by stable worker and controller identity. `create(key)` returns a frozen live ownership handle; stop its resources, then call `complete(handle)` for normal disposal. A restarted instance cannot forge this capability from a listed record.
@@ -106,6 +136,19 @@ await journal.retire(recovered.id, record => controllerConfirmsFinished(record.k
106
136
 
107
137
  The `Storage` singleton is a pre-instantiated `StorageManager`. It lazily builds its config from `@stacksjs/config` (which reads `config/filesystems.ts` and env vars).
108
138
 
139
+ ### Directory mounts without retirement
140
+
141
+ Use `inspectDirectoryMounts(canonicalDirectory)` for read-only current-namespace
142
+ mount checks where legitimate readers may stay open. Supply an existing,
143
+ checked canonical directory. An unmounted result means only that the native
144
+ mount table did not reference that directory or a descendant. Unavailable,
145
+ unsupported, aliased or missing paths never return `unmounted: true`.
146
+
147
+ Keep `inspectTemporaryWorkspace` and journal retirement for deletion: they also
148
+ check process references and inspection permissions. Mount inspection alone
149
+ grants no ownership, quiescence or retirement authority and does not inspect
150
+ other namespaces or prevent later host changes.
151
+
109
152
  ### Basic Operations
110
153
 
111
154
  ```typescript
@@ -169,7 +169,8 @@ expect(result.exitCode).toBe(0)
169
169
 
170
170
  Retained implementation evidence lives under `core/testing/tests/`:
171
171
  `http-client`, `acting-as`, `database-assertions`, `events`, `mail`, `time`,
172
- `console`, `isolated`, `disposable-database` and `browser` test files. Fixture mechanics live in `core/testing/src/`;
172
+ `console`, `isolated`, `disposable-database`, `browser` and `declarations` (what dtsx
173
+ publishes for `browser.ts` / `isolated.ts`: no `unknown` fields) test files. Fixture mechanics live in `core/testing/src/`;
173
174
  `package.json` declares the root and database/DynamoDB/browser export boundaries.
174
175
 
175
176
  ## Isolated processes and disposable databases
@@ -191,7 +192,7 @@ for (const dialect of ['sqlite', 'postgres'] as const) {
191
192
  env: { APP_ENV: 'test', ...database.env },
192
193
  timeoutMs: 45_000,
193
194
  envFile: false, // --no-env-file
194
- preload: [], // replace bunfig preloads (none)
195
+ preload: [], // replace bunfig preloads (none); or bunfig: 'tests/isolated/bunfig.toml'
195
196
  })
196
197
  assertIsolatedOk(result, 'checkout flow OK') // throws with stdout + stderr otherwise
197
198
  })
@@ -199,10 +200,14 @@ for (const dialect of ['sqlite', 'postgres'] as const) {
199
200
  }
200
201
  ```
201
202
 
202
- - `runIsolated(file, { env, timeoutMs = 60_000, args, cwd, mode, preload, envFile, inheritEnv, stdin })`
203
+ - `runIsolated(file, { env, timeoutMs = 60_000, args, cwd, mode, preload, bunfig, envFile, inheritEnv, stdin })`
203
204
  resolves `{ code, signal, stdout, stderr, timedOut, durationMs, command }`. `mode: 'auto'` runs
204
205
  `*.test.*` / `*.spec.*` with `bun test`, anything else as a script; `env` values of `undefined`
205
206
  remove a variable. The watchdog sends SIGTERM at the timeout and SIGKILL 2 s later.
207
+ - `bunfig: 'path/bunfig.toml'` runs the child with that config (`--config=`), resolved against
208
+ `cwd`; it must exist. `preload` instead generates a config holding only those preloads. They are
209
+ exclusive (a TypeError): list the preloads in your bunfig. Bun resolves a bunfig's relative
210
+ `preload` paths against the child's cwd, not the bunfig's directory.
206
211
  - `withDisposableDatabase(dialect, fn, { url?, prefix? })`: SQLite is a file in a fresh temp
207
212
  directory; Postgres is `CREATE DATABASE` on `url` or `STACKS_TEST_POSTGRES_URL`, dropped with
208
213
  `DROP DATABASE ... WITH (FORCE)` after `fn`, even when it throws (the test's error wins over a
@@ -236,18 +241,41 @@ expect(pageAuditClean(report)).toBe(true) // no duplicate /api/ requests, failed
236
241
  ```
237
242
 
238
243
  - `Cdp`: `send`, `evaluate`, `on(method, fn)` (any number of listeners per method; returns an
239
- unsubscribe), `off`, `once(method, match?, timeoutMs?)`, `errors`, `inFlight` (event streams
240
- leave it when their response starts, so a page with live updates can still settle), `closed`
241
- (every pending command fails at once when Chrome goes away).
244
+ unsubscribe), `off`, `once(method, match?, timeoutMs?)`, `intercept(patterns, handler)`,
245
+ `errors`, `inFlight: Map<requestId, 'METHOD url'>` (event streams leave it when their response
246
+ starts, so a page with live updates can still settle), `closed` (every pending command fails at
247
+ once when Chrome goes away).
242
248
  - `launch(options)` enables Page/Runtime/Network/Log, sets a 1440x1000 viewport, answers stx's
243
249
  live-reload stream (`*/_stx/hmr*`) with a day-long retry so a save mid-run cannot reload the
244
250
  page, accepts JavaScript dialogs and records them in `errors`, removes "HeadlessChrome" from the
245
251
  user agent, and passes `--use-mock-keychain`. `profile` keeps one profile across relaunches.
252
+ - **Pausing requests next to live reload.** Chrome keeps one `Fetch.enable` pattern set per
253
+ session (a second call replaces it, `Fetch.disable` drops all) and sends every paused request to
254
+ every listener, so the session layers them. `await cdp.intercept([{ urlPattern: '*/api/slow*' }],
255
+ (paused, cdp) => ...)` hands a handler only what its own patterns match and resolves with an
256
+ async remover; `quietLiveReload(cdp, patterns?)` is one (what `launch()` runs). Your own
257
+ `cdp.send('Fetch.enable' | 'Fetch.disable')` sets one more layer and the session enables the
258
+ union, so a journey that holds its own request needs no `quietLiveReload: false`.
259
+ `on('Fetch.requestPaused')` listeners see the requests your patterns match, not the live-reload
260
+ stream. The first answer wins: a second `continueRequest`/`fulfillRequest`/`failRequest` for one
261
+ pause resolves without reaching Chrome. A pause nobody could answer is continued; one your own
262
+ pattern holds with no listener stays held (a hanging request on purpose).
263
+ `matchesUrlPattern(pattern, url)` and `pausedRequestMatches(pattern, paused)` are Chrome's
264
+ matching rules (`*`, `?`, `\` escape; stage and resource type).
246
265
  - `settle(cdp, { quietMs, timeoutMs })` resolves false (not throws) when a page never goes quiet.
247
- - `auditPage(url, { cdp?, launch?, viewport?, isApiRequest?, beforeNavigate?, quietMs, timeoutMs })`
248
- returns `{ apiRequests, duplicates, failed, errors, settled, durationMs }` and never throws for a
249
- page problem. `beforeNavigate` is where to seed a token (`Page.addScriptToEvaluateOnNewDocument`).
250
- `formatPageAudit(report)` prints one line.
266
+ - `auditPage(url, { cdp?, launch?, viewport?, isApiRequest?, beforeNavigate?, pageLoads?, quietMs, timeoutMs })`
267
+ returns `{ url, finalUrl, apiRequests, duplicates, loads, failed, errors, settled, durationMs }`
268
+ and never throws for a page problem. `beforeNavigate` is where to seed a token
269
+ (`Page.addScriptToEvaluateOnNewDocument`). `formatPageAudit(report)` prints one line, with
270
+ `/today -> /home` when the page landed elsewhere.
271
+ - Duplicates are counted **per page load**: a page that sends you on (`/today` replacing itself with
272
+ `/home`) is two loads, so `/api/me` once in each is not a duplicate. A load starts with each new
273
+ main-frame document after the first and each same-document (history API) navigation to a
274
+ different path; a query or hash change stays in the load. `loads` lists them
275
+ (`{ url, apiRequests, duplicates }`), `duplicates` is the highest count any one load reached,
276
+ `finalUrl` is `location.href` once settled. `pageLoads: 'visit'` counts the whole visit as one
277
+ load (the old behaviour). `splitPageLoads(url, events, mode)` and `loadDuplicates(loads)` are the
278
+ pure logic. `finalUrl` and `loads` are optional on the type, so hand-built reports still compile.
251
279
  - **macOS: the installed Chrome quits about 30 s in.** GoogleUpdater SIGTERMs every process with
252
280
  Chrome's bundle id while an update is pending; to a test that looks like a hung page. When
253
281
  `CHROME_PATH` is not set, `launch()` runs `prepareMacChrome()`: a `cp -cR` clone in the temp
@@ -0,0 +1,41 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+ import { formErrorMessages } from './dashboard-form'
3
+
4
+ /**
5
+ * stacksjs/stacks#2918 — this was duplicated across fourteen dialogs. The
6
+ * cases below are the formatting those copies encoded; they are pinned here
7
+ * so the single definition cannot quietly change what a user reads.
8
+ */
9
+ describe('formErrorMessages', () => {
10
+ it('turns a snake_case field into a sentence-case label', () => {
11
+ expect(formErrorMessages({ first_name: 'is required' })).toEqual(['First name: is required'])
12
+ })
13
+
14
+ it('splits camelCase, but not to the same result', () => {
15
+ // Pinning a wart, not endorsing it. The split inserts a space without
16
+ // lowering the second word, so `firstName` and `first_name` do not read
17
+ // alike. Changing that is a product call; this test exists so the change
18
+ // is deliberate when it happens.
19
+ expect(formErrorMessages({ firstName: 'is required' })).toEqual(['First Name: is required'])
20
+ })
21
+
22
+ it('splits every word, not just the first', () => {
23
+ expect(formErrorMessages({ shipping_zone_name: 'is taken' })).toEqual(['Shipping zone name: is taken'])
24
+ expect(formErrorMessages({ taxRateCode: 'is invalid' })).toEqual(['Tax Rate Code: is invalid'])
25
+ })
26
+
27
+ it('keeps one line per field, in the order given', () => {
28
+ expect(formErrorMessages({ name: 'is required', code: 'is taken' })).toEqual([
29
+ 'Name: is required',
30
+ 'Code: is taken',
31
+ ])
32
+ })
33
+
34
+ it('has nothing to say about an empty map', () => {
35
+ expect(formErrorMessages({})).toEqual([])
36
+ })
37
+
38
+ it('leaves an already-capitalised single word alone', () => {
39
+ expect(formErrorMessages({ Name: 'is required' })).toEqual(['Name: is required'])
40
+ })
41
+ })
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Form helpers shared by the dashboard's editor dialogs.
3
+ *
4
+ * `formErrorMessages` was copied verbatim into fourteen Commerce dialogs
5
+ * (stacksjs/stacks#2918). It is a pure function of a validation-error map with
6
+ * no reactive dependency and no markup, so a component was the wrong home for
7
+ * it: the label formatting it encodes had fourteen definitions, and a change
8
+ * to how a field name becomes a label had to be made in all of them or drift.
9
+ */
10
+
11
+ /**
12
+ * Turn a map of field errors into lines a person can read.
13
+ *
14
+ * Behaviour is the fourteen copies' behaviour, unchanged, including one wart
15
+ * worth naming rather than silently fixing: the two spellings do not read
16
+ * alike. `first_name` becomes "First name", while `firstName` becomes
17
+ * "First Name", because the split inserts a space without lowering the second
18
+ * word. A server reporting snake_case and a client reporting camelCase
19
+ * therefore render differently for the same field.
20
+ *
21
+ * Left as-is here because extracting and changing at once makes a regression
22
+ * impossible to attribute. Fixing it is a one-line change in one place now,
23
+ * which is the point of the extraction.
24
+ */
25
+ export function formErrorMessages(errors: Record<string, string>): string[] {
26
+ return Object.entries(errors).map(([field, message]) => {
27
+ const label = field.replace(/([a-z])([A-Z])/g, '$1 $2').replaceAll('_', ' ')
28
+ return `${label.charAt(0).toUpperCase()}${label.slice(1)}: ${message}`
29
+ })
30
+ }
@@ -0,0 +1,228 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+ import { pageControls, useRecordsDashboard } from './dashboard-list'
3
+
4
+ /** The smallest thing with the two members `pageControls` reads. */
5
+ function pageSignal(initial: number) {
6
+ let value = initial
7
+ const signal = (() => value) as { (): number, set: (next: number) => void }
8
+ signal.set = (next: number) => { value = next }
9
+ return signal
10
+ }
11
+
12
+ describe('pageControls', () => {
13
+ it('moves a page back and forward', () => {
14
+ const page = pageSignal(2)
15
+ const { previousPage, nextPage } = pageControls(page, () => 5)
16
+ previousPage()
17
+ expect(page()).toBe(1)
18
+ nextPage()
19
+ nextPage()
20
+ expect(page()).toBe(3)
21
+ })
22
+
23
+ it('will not go below the first page', () => {
24
+ const page = pageSignal(1)
25
+ const { previousPage } = pageControls(page, () => 5)
26
+ previousPage()
27
+ previousPage()
28
+ expect(page()).toBe(1)
29
+ })
30
+
31
+ it('will not go past the last page', () => {
32
+ const page = pageSignal(5)
33
+ const { nextPage } = pageControls(page, () => 5)
34
+ nextPage()
35
+ expect(page()).toBe(5)
36
+ })
37
+
38
+ it('reads the last page at click time, not when it was wired up', () => {
39
+ // A filter that shrinks the result set has to shrink the range too.
40
+ const page = pageSignal(1)
41
+ let last = 9
42
+ const { nextPage } = pageControls(page, () => last)
43
+ last = 2
44
+ nextPage()
45
+ nextPage()
46
+ nextPage()
47
+ expect(page()).toBe(2)
48
+ })
49
+
50
+ it('clamps an out-of-range page back into the range', () => {
51
+ // The guard style the Marketing dashboards used could not do this: a page
52
+ // already past the end stayed there.
53
+ const page = pageSignal(40)
54
+ const { nextPage, previousPage } = pageControls(page, () => 3)
55
+ nextPage()
56
+ expect(page()).toBe(3)
57
+ page.set(40)
58
+ previousPage()
59
+ expect(page()).toBe(39)
60
+ })
61
+
62
+ it('survives an empty result set, where the last page is zero', () => {
63
+ const page = pageSignal(1)
64
+ const { nextPage } = pageControls(page, () => 0)
65
+ nextPage()
66
+ expect(page()).toBe(1)
67
+ })
68
+ })
69
+
70
+ interface Row { id: number, name: string }
71
+
72
+ const byName = (rows: Row[], query: string) => rows.filter(r => r.name.toLowerCase().includes(query))
73
+
74
+ function seeded(count: number, perPage = 10) {
75
+ const d = useRecordsDashboard<Row>({ filter: byName, perPage })
76
+ d.records.set(Array.from({ length: count }, (_, i) => ({ id: i + 1, name: `row ${i + 1}` })))
77
+ return d
78
+ }
79
+
80
+ describe('useRecordsDashboard', () => {
81
+ it('starts loading, empty, on the first page', () => {
82
+ const d = useRecordsDashboard<Row>({ filter: byName })
83
+ expect(d.loading()).toBe(true)
84
+ expect(d.records()).toEqual([])
85
+ expect(d.page()).toBe(1)
86
+ expect(d.pageCount()).toBe(1)
87
+ expect(d.paginatedRecords()).toEqual([])
88
+ })
89
+
90
+ it('pages through the records', () => {
91
+ const d = seeded(25)
92
+ expect(d.pageCount()).toBe(3)
93
+ expect(d.paginatedRecords().map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
94
+ d.nextPage()
95
+ expect(d.paginatedRecords()[0]!.id).toBe(11)
96
+ d.page.set(3)
97
+ expect(d.paginatedRecords()).toHaveLength(5)
98
+ })
99
+
100
+ it('searching returns to the first page, because page 3 of a new result set is meaningless', () => {
101
+ const d = seeded(25)
102
+ d.page.set(3)
103
+ d.handleSearch('row 1')
104
+ expect(d.page()).toBe(1)
105
+ // row 1, 10-19
106
+ expect(d.filteredRecords()).toHaveLength(11)
107
+ })
108
+
109
+ it('an edit replaces in place and does not move the page', () => {
110
+ const d = seeded(25)
111
+ d.page.set(2)
112
+ const target = d.records()[4]!
113
+ d.upsert({ id: target.id, name: 'renamed' }, target)
114
+ expect(d.records()[4]!.name).toBe('renamed')
115
+ expect(d.records()).toHaveLength(25)
116
+ expect(d.page()).toBe(2)
117
+ })
118
+
119
+ it('a create appends and lands on the page the new row is on', () => {
120
+ const d = seeded(20)
121
+ expect(d.pageCount()).toBe(2)
122
+ d.upsert({ id: 99, name: 'new' }, null)
123
+ expect(d.records()).toHaveLength(21)
124
+ expect(d.page()).toBe(3)
125
+ expect(d.paginatedRecords()).toEqual([{ id: 99, name: 'new' }])
126
+ })
127
+
128
+ it('removing the last row on the last page pulls the page back', () => {
129
+ const d = seeded(11)
130
+ d.page.set(2)
131
+ expect(d.paginatedRecords()).toHaveLength(1)
132
+ d.remove(d.records()[10]!)
133
+ expect(d.page()).toBe(1)
134
+ expect(d.records()).toHaveLength(10)
135
+ })
136
+
137
+ it('removing elsewhere leaves the page alone', () => {
138
+ const d = seeded(25)
139
+ d.page.set(2)
140
+ d.remove(d.records()[0]!)
141
+ expect(d.page()).toBe(2)
142
+ expect(d.records()).toHaveLength(24)
143
+ })
144
+
145
+ it('clampPage pulls a page back into range after a filter shrinks the list', () => {
146
+ const d = seeded(25)
147
+ d.page.set(3)
148
+ d.search.set('row 7')
149
+ d.clampPage()
150
+ expect(d.page()).toBe(1)
151
+ })
152
+
153
+ it('the editor opens for a create and for an edit, and remembers which', () => {
154
+ const d = seeded(3)
155
+ d.openCreate()
156
+ expect(d.editorOpen()).toBe(true)
157
+ expect(d.editorMode()).toBe('create')
158
+ expect(d.editing()).toBeNull()
159
+
160
+ const row = d.records()[1]!
161
+ d.openEdit(row)
162
+ expect(d.editorMode()).toBe('edit')
163
+ expect(d.editing()).toBe(row)
164
+ })
165
+
166
+ it('will not close the editor mid-save', () => {
167
+ // Otherwise a slow PATCH can land on a dialog the user already dismissed.
168
+ const d = seeded(3)
169
+ d.openEdit(d.records()[0]!)
170
+ d.editorError.set('something went wrong')
171
+ d.saving.set(true)
172
+ d.closeEditor()
173
+ expect(d.editorOpen()).toBe(true)
174
+ expect(d.editorError()).toBe('something went wrong')
175
+
176
+ d.saving.set(false)
177
+ d.closeEditor()
178
+ expect(d.editorOpen()).toBe(false)
179
+ expect(d.editing()).toBeNull()
180
+ expect(d.editorError()).toBe('')
181
+ })
182
+
183
+ it('will not close the delete confirmation mid-delete', () => {
184
+ const d = seeded(3)
185
+ d.requestDelete(d.records()[0]!)
186
+ d.deleteBusy.set(true)
187
+ d.closeDelete()
188
+ expect(d.deleting()).not.toBeNull()
189
+
190
+ d.deleteBusy.set(false)
191
+ d.closeDelete()
192
+ expect(d.deleting()).toBeNull()
193
+ })
194
+
195
+ it('honours a custom identity instead of id', () => {
196
+ const d = useRecordsDashboard<{ sku: string }>({
197
+ filter: rows => rows,
198
+ sameRecord: (a, b) => a.sku === b.sku,
199
+ })
200
+ d.records.set([{ sku: 'a' }, { sku: 'b' }])
201
+ d.remove({ sku: 'a' })
202
+ expect(d.records()).toEqual([{ sku: 'b' }])
203
+ })
204
+ })
205
+
206
+ describe('useRecordsDashboard goToPage', () => {
207
+ it('jumps to a page', () => {
208
+ const d = seeded(25)
209
+ d.goToPage(3)
210
+ expect(d.page()).toBe(3)
211
+ })
212
+
213
+ it('clamps a page that does not exist', () => {
214
+ const d = seeded(25)
215
+ d.goToPage(99)
216
+ expect(d.page()).toBe(3)
217
+ d.goToPage(0)
218
+ expect(d.page()).toBe(1)
219
+ d.goToPage(-4)
220
+ expect(d.page()).toBe(1)
221
+ })
222
+
223
+ it('survives a non-number from a component that emitted one', () => {
224
+ const d = seeded(25)
225
+ d.goToPage(Number.NaN)
226
+ expect(d.page()).toBe(1)
227
+ })
228
+ })