@stacksjs/defaults 0.75.487 → 0.75.490

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 (141) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-dashboard/SKILL.md +27 -2
  3. package/ai/skills/stacks-native/CATALOG.md +9 -9
  4. package/ai/skills/stacks-search-engine/SKILL.md +14 -0
  5. package/app/Actions/Dashboard/Commerce/CommerceCategoriesAction.ts +7 -13
  6. package/app/Actions/Dashboard/Commerce/CommerceCustomerChoicesAction.ts +34 -0
  7. package/app/Actions/Dashboard/Commerce/CommerceDeliveryAction.ts +7 -16
  8. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsAction.ts +21 -15
  9. package/app/Actions/Dashboard/Commerce/CommerceGiftCardsExportAction.ts +41 -0
  10. package/app/Actions/Dashboard/Commerce/CommerceOrderCustomersAction.ts +37 -0
  11. package/app/Actions/Dashboard/Commerce/CommerceOrdersAction.ts +26 -41
  12. package/app/Actions/Dashboard/Commerce/CommerceOrdersExportAction.ts +43 -0
  13. package/app/Actions/Dashboard/Commerce/CommercePaymentsAction.ts +24 -21
  14. package/app/Actions/Dashboard/Commerce/CommercePaymentsExportAction.ts +41 -0
  15. package/app/Actions/Dashboard/Commerce/CommercePosAction.ts +18 -48
  16. package/app/Actions/Dashboard/Commerce/CommercePosProductsAction.ts +39 -0
  17. package/app/Actions/Dashboard/Commerce/CommercePrintLogsAction.ts +14 -104
  18. package/app/Actions/Dashboard/Commerce/CommercePrintLogsExportAction.ts +41 -0
  19. package/app/Actions/Dashboard/Commerce/CommerceProductChoicesAction.ts +32 -0
  20. package/app/Actions/Dashboard/Commerce/CommerceProductsAction.ts +24 -43
  21. package/app/Actions/Dashboard/Commerce/CommerceProductsExportAction.ts +44 -0
  22. package/app/Actions/Dashboard/Commerce/CourierIndexAction.ts +3 -1
  23. package/app/Actions/Dashboard/Commerce/DeliveryRouteIndexAction.ts +23 -12
  24. package/app/Actions/Dashboard/Commerce/DigitalDeliveryIndexAction.ts +3 -1
  25. package/app/Actions/Dashboard/Commerce/LicenseKeyIndexAction.ts +24 -23
  26. package/app/Actions/Dashboard/Commerce/LicenseKeyOptionsAction.ts +35 -16
  27. package/app/Actions/Dashboard/Commerce/ProductWaitlistIndexAction.ts +22 -22
  28. package/app/Actions/Dashboard/Commerce/RestaurantWaitlistIndexAction.ts +22 -17
  29. package/app/Actions/Dashboard/Commerce/ReviewIndexAction.ts +22 -31
  30. package/app/Actions/Dashboard/Commerce/ShippingMethodIndexAction.ts +3 -1
  31. package/app/Actions/Dashboard/Commerce/ShippingRateIndexAction.ts +3 -1
  32. package/app/Actions/Dashboard/Commerce/ShippingZoneIndexAction.ts +3 -1
  33. package/app/Actions/Dashboard/Commerce/commerce-category-list.test.ts +100 -0
  34. package/app/Actions/Dashboard/Commerce/commerce-category-list.ts +26 -0
  35. package/app/Actions/Dashboard/Commerce/commerce-choice-records.ts +56 -0
  36. package/app/Actions/Dashboard/Commerce/commerce-choices.test.ts +88 -0
  37. package/app/Actions/Dashboard/Commerce/commerce-choices.ts +70 -0
  38. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.test.ts +151 -0
  39. package/app/Actions/Dashboard/Commerce/commerce-delivery-overview.ts +85 -0
  40. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.test.ts +153 -0
  41. package/app/Actions/Dashboard/Commerce/commerce-delivery-route-list.ts +180 -0
  42. package/app/Actions/Dashboard/Commerce/commerce-delivery.ts +24 -9
  43. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.test.ts +221 -0
  44. package/app/Actions/Dashboard/Commerce/commerce-gift-card-list.ts +259 -0
  45. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.test.ts +184 -0
  46. package/app/Actions/Dashboard/Commerce/commerce-license-key-list.ts +217 -0
  47. package/app/Actions/Dashboard/Commerce/commerce-order-list.test.ts +183 -0
  48. package/app/Actions/Dashboard/Commerce/commerce-order-list.ts +278 -0
  49. package/app/Actions/Dashboard/Commerce/commerce-order-records.test.ts +29 -0
  50. package/app/Actions/Dashboard/Commerce/commerce-payment-list.test.ts +180 -0
  51. package/app/Actions/Dashboard/Commerce/commerce-payment-list.ts +272 -0
  52. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +171 -0
  53. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +152 -0
  54. package/app/Actions/Dashboard/Commerce/commerce-pos.test.ts +1 -12
  55. package/app/Actions/Dashboard/Commerce/commerce-pos.ts +0 -26
  56. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.test.ts +202 -0
  57. package/app/Actions/Dashboard/Commerce/commerce-print-log-list.ts +286 -0
  58. package/app/Actions/Dashboard/Commerce/commerce-product-list.test.ts +174 -0
  59. package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +276 -0
  60. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.test.ts +183 -0
  61. package/app/Actions/Dashboard/Commerce/commerce-product-waitlist-list.ts +170 -0
  62. package/app/Actions/Dashboard/Commerce/commerce-record.ts +21 -0
  63. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.test.ts +189 -0
  64. package/app/Actions/Dashboard/Commerce/commerce-restaurant-waitlist-list.ts +177 -0
  65. package/app/Actions/Dashboard/Commerce/commerce-review-list.test.ts +193 -0
  66. package/app/Actions/Dashboard/Commerce/commerce-review-list.ts +220 -0
  67. package/app/Actions/Dashboard/Commerce/commerce-sql.ts +57 -0
  68. package/app/Actions/Dashboard/Commerce/payment-records.test.ts +16 -0
  69. package/app/Actions/Dashboard/Commerce/product-waitlist-records.test.ts +6 -5
  70. package/app/Actions/Dashboard/Commerce/product-waitlist-records.ts +16 -45
  71. package/app/Actions/Dashboard/Commerce/restaurant-waitlist-records.ts +4 -24
  72. package/app/Actions/Dashboard/Content/content-list.ts +10 -0
  73. package/app/Actions/Dashboard/Content/file-listing-metadata.test.ts +46 -0
  74. package/app/Actions/Dashboard/Content/file-manager.ts +51 -10
  75. package/app/Actions/Dashboard/DashboardHomeAction.test.ts +13 -9
  76. package/app/Actions/Dashboard/DashboardHomeAction.ts +42 -21
  77. package/app/Actions/Dashboard/Jobs/JobStatsAction.ts +5 -2
  78. package/app/Actions/Dashboard/Kanban/UsersListAction.ts +13 -9
  79. package/app/Actions/Dashboard/Kanban/kanban-response.test.ts +40 -0
  80. package/app/Actions/Dashboard/Kanban/kanban-response.ts +53 -1
  81. package/app/Actions/Dashboard/Kanban/kanban-users.test.ts +114 -0
  82. package/app/Actions/Dashboard/Kanban/kanban-users.ts +32 -0
  83. package/app/Actions/Dashboard/Models/ModelShowAction.ts +8 -0
  84. package/app/Actions/Dashboard/Models/ModelsIndexAction.ts +16 -2
  85. package/app/Actions/Dashboard/Models/model-migration.test.ts +27 -0
  86. package/app/Actions/Dashboard/Models/model-migration.ts +23 -0
  87. package/app/Actions/Dashboard/Queue/QueueStatsAction.ts +9 -6
  88. package/app/Actions/Dashboard/Queue/QueueWorkersAction.ts +3 -2
  89. package/app/Actions/Dashboard/Queue/queue-stats.ts +10 -0
  90. package/app/Actions/Dashboard/Queue/worker-snapshots.test.ts +31 -0
  91. package/app/Actions/Dashboard/Queue/worker-snapshots.ts +33 -0
  92. package/app/Actions/Dashboard/named-search.test.ts +36 -0
  93. package/app/Actions/Dashboard/named-search.ts +80 -0
  94. package/app/Models/QueueWorker.ts +1 -0
  95. package/app/Models/Request.ts +4 -2
  96. package/bootstrap.ts +6 -1
  97. package/functions/commerce/shippings/dashboard-resource.ts +12 -1
  98. package/functions/commerce/shippings/delivery-routes.ts +1 -0
  99. package/functions/commerce/shippings/license-keys.ts +1 -0
  100. package/functions/dashboard-list.test.ts +132 -1
  101. package/functions/dashboard-list.ts +198 -1
  102. package/functions/queue.ts +2 -0
  103. package/ide/vscode/package.json +1 -1
  104. package/package.json +2 -2
  105. package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +38 -12
  106. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +122 -68
  107. package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +29 -6
  108. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +59 -2
  109. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +126 -80
  110. package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +28 -3
  111. package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -29
  112. package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +139 -60
  113. package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +27 -2
  114. package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -1
  115. package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +47 -3
  116. package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +59 -49
  117. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +116 -82
  118. package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +28 -4
  119. package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +120 -69
  120. package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +29 -6
  121. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +79 -52
  122. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +31 -8
  123. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +71 -13
  124. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +69 -81
  125. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +31 -8
  126. package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +21 -17
  127. package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +23 -22
  128. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +116 -20
  129. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +100 -12
  130. package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +34 -16
  131. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +107 -19
  132. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +65 -6
  133. package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +29 -3
  134. package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +10 -1
  135. package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +21 -1
  136. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +24 -4
  137. package/resources/components/Dashboard/Models/ModelsOverview.stx +13 -2
  138. package/resources/components/Dashboard/Queue/QueueDashboard.stx +8 -2
  139. package/resources/functions/dashboard/sidebar.ts +26 -1
  140. package/routes/dashboard-api.ts +11 -0
  141. package/views/dashboard/stores/kanban.ts +38 -6
@@ -1,8 +1,9 @@
1
1
  import { Action } from '@stacksjs/actions/runtime'
2
2
  import { FailedJob, Job } from '@stacksjs/orm'
3
- import { aggregateWorkerMetrics, readWorkerSnapshots } from '@stacksjs/queue'
3
+ import { aggregateWorkerMetrics, discoverJobs } from '@stacksjs/queue'
4
4
  import { dashboardOperationalError } from '../dashboard-response'
5
- import { readQueueCounts } from './queue-stats'
5
+ import { readQueueCounts, withDeclaredQueues } from './queue-stats'
6
+ import { readDashboardWorkerSnapshots } from './worker-snapshots'
6
7
 
7
8
  // A queued job has no `status` column - `queuedJobState` in @stacksjs/queue
8
9
  // holds the rule (reserved_at means a worker has it; available_at in the
@@ -12,7 +13,7 @@ import { readQueueCounts } from './queue-stats'
12
13
 
13
14
  export default new Action({
14
15
  name: 'QueueStatsAction',
15
- description: 'Returns aggregated queue statistics from the jobs/failed_jobs tables and the in-memory metrics tracker.',
16
+ description: 'Returns declared queues, database job counts and shared worker metrics.',
16
17
  method: 'GET',
17
18
  async handle() {
18
19
  try {
@@ -22,7 +23,8 @@ export default new Action({
22
23
  readQueueCounts(),
23
24
  ])
24
25
 
25
- const queues = counts.map(queue => ({
26
+ const definitions = await discoverJobs()
27
+ const queues = withDeclaredQueues(counts, definitions.map(job => job.config.queue ?? 'default')).map(queue => ({
26
28
  name: queue.name,
27
29
  status: queue.active > 0 ? 'active' : 'idle',
28
30
  pending: queue.pending,
@@ -35,7 +37,8 @@ export default new Action({
35
37
 
36
38
  // Workers publish bounded snapshots through their native QueueWorker model.
37
39
  // The dashboard reads those across processes rather than its own empty tracker.
38
- const metrics = aggregateWorkerMetrics(await readWorkerSnapshots())
40
+ const workers = await readDashboardWorkerSnapshots()
41
+ const metrics = aggregateWorkerMetrics(workers.snapshots)
39
42
 
40
43
  const stats = {
41
44
  totalQueues: queues.length,
@@ -47,7 +50,7 @@ export default new Action({
47
50
  averageProcessingTimeMs: Math.round(metrics.averageDuration),
48
51
  }
49
52
 
50
- return { queues, stats, queueConnected: true }
53
+ return { queues, stats, queueConnected: true, workersMigrated: workers.migrated }
51
54
  }
52
55
  catch (error) {
53
56
  return dashboardOperationalError(error, 'Queue statistics could not be loaded.', 'QueueStatsAction')
@@ -1,6 +1,6 @@
1
1
  import { Action } from '@stacksjs/actions/runtime'
2
- import { readWorkerSnapshots } from '@stacksjs/queue'
3
2
  import { dashboardOperationalError } from '../dashboard-response'
3
+ import { readDashboardWorkerSnapshots } from './worker-snapshots'
4
4
 
5
5
  export default new Action({
6
6
  name: 'QueueWorkersAction',
@@ -8,7 +8,7 @@ export default new Action({
8
8
  method: 'GET',
9
9
  async handle() {
10
10
  try {
11
- const snapshots = await readWorkerSnapshots()
11
+ const { snapshots, migrated } = await readDashboardWorkerSnapshots()
12
12
  const tracked = snapshots.map(snapshot => snapshot.worker)
13
13
 
14
14
  // Translate the tracker's internal status into the dashboard's vocabulary
@@ -38,6 +38,7 @@ export default new Action({
38
38
  data,
39
39
  worker_running: tracked.some(worker => worker.status !== 'stopped'),
40
40
  active_jobs: snapshots.reduce((sum, snapshot) => sum + snapshot.activeJobs, 0),
41
+ workers_migrated: migrated,
41
42
  }
42
43
  }
43
44
  catch (error) {
@@ -14,6 +14,16 @@ export interface QueueCounts {
14
14
 
15
15
  const queueName = (value: unknown): string => String(value || 'default')
16
16
 
17
+ /** Declared queues remain discoverable before their first job is dispatched. */
18
+ export function withDeclaredQueues(counts: QueueCounts[], names: Iterable<string>): QueueCounts[] {
19
+ const queues = new Map(counts.map(row => [row.name, row]))
20
+ for (const name of [...new Set(names)].sort()) {
21
+ const key = queueName(name)
22
+ if (!queues.has(key)) queues.set(key, { name: key, pending: 0, active: 0, failed: 0, total: 0 })
23
+ }
24
+ return [...queues.values()]
25
+ }
26
+
17
27
  /**
18
28
  * Every queue that has jobs, counted by the database (stacksjs/stacks#3200).
19
29
  *
@@ -0,0 +1,31 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import type { WorkerSnapshot } from '@stacksjs/queue'
3
+ import { readDashboardWorkerSnapshots } from './worker-snapshots'
4
+
5
+ /**
6
+ * Worker heartbeats are telemetry beside the jobs. A missing `queue_workers`
7
+ * table must leave the Queue and Jobs pages their counts; any other failure
8
+ * must still fail them.
9
+ */
10
+ describe('readDashboardWorkerSnapshots', () => {
11
+ test('reads the heartbeats when the table exists, without asking the catalog', async () => {
12
+ const snapshot = { worker: { id: 'w1' } } as unknown as WorkerSnapshot
13
+ const read = await readDashboardWorkerSnapshots(async () => [snapshot], async () => { throw new Error('the catalog must not be asked') })
14
+ expect(read).toEqual({ snapshots: [snapshot], migrated: true })
15
+ })
16
+
17
+ test('a missing queue_workers table answers no workers and migrated: false', async () => {
18
+ const asked: string[] = []
19
+ const read = await readDashboardWorkerSnapshots(
20
+ async () => { throw new Error('relation "queue_workers" does not exist') },
21
+ async (table) => { asked.push(table); return true },
22
+ )
23
+ expect(read).toEqual({ snapshots: [], migrated: false })
24
+ expect(asked).toEqual(['queue_workers'])
25
+ })
26
+
27
+ test('any other failure is rethrown', async () => {
28
+ const outage = new Error('connection refused')
29
+ await expect(readDashboardWorkerSnapshots(async () => { throw outage }, async () => false)).rejects.toBe(outage)
30
+ })
31
+ })
@@ -0,0 +1,33 @@
1
+ import type { WorkerSnapshot } from '@stacksjs/queue'
2
+ import { readWorkerSnapshots } from '@stacksjs/queue'
3
+ import { isUnmigratedTable } from '../Models/model-migration'
4
+
5
+ /** Where workers publish their heartbeats (`app/Models/QueueWorker.ts`). */
6
+ export const WORKER_TABLE = 'queue_workers'
7
+
8
+ /**
9
+ * The worker heartbeats, for the Queue and Jobs pages.
10
+ *
11
+ * Heartbeats are telemetry beside the jobs, not the jobs: the queue counts and
12
+ * job totals come from `jobs` and `failed_jobs`, and a worker already runs
13
+ * without its telemetry table ("Queue worker telemetry unavailable"). So an app
14
+ * that has not migrated `queue_workers` gets its counts with no workers and
15
+ * `migrated: false`, where all three endpoints used to answer 503 and take the
16
+ * page's counts down with them.
17
+ *
18
+ * Only a missing table, as the catalog reports it, is treated that way. Any
19
+ * other failure is rethrown.
20
+ */
21
+ export async function readDashboardWorkerSnapshots(
22
+ read: () => Promise<WorkerSnapshot[]> = readWorkerSnapshots,
23
+ isMissing: (table: string) => Promise<boolean> = isUnmigratedTable,
24
+ ): Promise<{ snapshots: WorkerSnapshot[], migrated: boolean }> {
25
+ try {
26
+ return { snapshots: await read(), migrated: true }
27
+ }
28
+ catch (error) {
29
+ if (await isMissing(WORKER_TABLE))
30
+ return { snapshots: [], migrated: false }
31
+ throw error
32
+ }
33
+ }
@@ -0,0 +1,36 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { describe, expect, test } from 'bun:test'
3
+ import type { NamedSearchRunner, NamedSearchTable } from './named-search'
4
+ import { searchNamedRows } from './named-search'
5
+
6
+ /**
7
+ * The shared picker search. kanban-users.test.ts runs it against users on
8
+ * SQLite, PostgreSQL and MySQL; this pins what that does not: the table name
9
+ * is SQL, so only the fixed list is accepted, and customers search the same way.
10
+ */
11
+ function sqlite(): { database: Database, run: NamedSearchRunner } {
12
+ const database = new Database(':memory:')
13
+ return { database, run: { unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as string[])) }) } }
14
+ }
15
+
16
+ describe('searchNamedRows', () => {
17
+ test('searches customers by name or email, bounded, with the full count', async () => {
18
+ const { database, run } = sqlite()
19
+ database.run('CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT)')
20
+ for (let index = 1; index <= 40; index++)
21
+ database.query('INSERT INTO customers (name, email) VALUES (?, ?)').run(`Customer ${String(index).padStart(2, '0')}`, `c${index}@example.com`)
22
+ database.query('INSERT INTO customers (name, email) VALUES (?, ?)').run('Zed Ortiz', 'ZED@shop.test')
23
+
24
+ const page = await searchNamedRows('customers', { search: 'customer', limit: 25 }, run, 'sqlite')
25
+ expect(page.rows).toHaveLength(25)
26
+ expect(page.total).toBe(40)
27
+ expect((await searchNamedRows('customers', { search: 'zed@SHOP', limit: 25 }, run, 'sqlite')).rows.map(row => row.name)).toEqual(['Zed Ortiz'])
28
+ })
29
+
30
+ test('refuses a table that is not on the list, before running anything', async () => {
31
+ let ran = false
32
+ const run: NamedSearchRunner = { unsafe: () => ({ execute: async () => { ran = true; return [] } }) }
33
+ await expect(searchNamedRows('users; DROP TABLE users' as NamedSearchTable, { search: '', limit: 5 }, run, 'sqlite')).rejects.toThrow('is not a searchable table')
34
+ expect(ran).toBeFalse()
35
+ })
36
+ })
@@ -0,0 +1,80 @@
1
+ import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
2
+ import { db, getDatabaseDialect, sqlHelpers } from '@stacksjs/database/runtime'
3
+ import type { QueryReader } from './Content/content-list'
4
+ import { containsPattern, countOf, queryText } from './Content/content-list'
5
+
6
+ /**
7
+ * A search over a table's `name` and `email`, for the dashboard's pickers: the
8
+ * Kanban assignee picker (users, stacksjs/stacks#3216) and the order dialog's
9
+ * customer (customers, stacksjs/stacks#3218). Each used to load the first 500
10
+ * rows once, so nobody past the 500th could be chosen.
11
+ *
12
+ * Case is ignored on both columns, `%` and `_` are characters to find, the
13
+ * answer is bounded, and `total` says how many matched.
14
+ */
15
+ export const NAMED_SEARCH_TABLES = ['users', 'customers'] as const
16
+ export type NamedSearchTable = typeof NAMED_SEARCH_TABLES[number]
17
+
18
+ export const NAMED_SEARCH_LIMIT = 25
19
+ export const NAMED_SEARCH_MAX_LIMIT = 100
20
+
21
+ export interface NamedSearchQuery {
22
+ search: string
23
+ limit: number
24
+ }
25
+
26
+ export interface NamedRow {
27
+ id: number
28
+ name: string | null
29
+ email: string | null
30
+ }
31
+
32
+ /** What runs the two queries: the configured `db`, or a test's own connection. */
33
+ export interface NamedSearchRunner {
34
+ unsafe: (sql: string, values?: unknown[]) => { execute: () => Promise<unknown> }
35
+ }
36
+
37
+ export function parseNamedSearchQuery(read: QueryReader): NamedSearchQuery | { error: string } {
38
+ const search = queryText(read, 'q')
39
+ if (search.length > 200)
40
+ return { error: 'q must be 200 characters or fewer.' }
41
+
42
+ const limitText = queryText(read, 'limit')
43
+ const limit = limitText === '' ? NAMED_SEARCH_LIMIT : Number(limitText)
44
+ if (!Number.isInteger(limit) || limit < 1 || limit > NAMED_SEARCH_MAX_LIMIT)
45
+ return { error: `limit must be a whole number from 1 to ${NAMED_SEARCH_MAX_LIMIT}.` }
46
+
47
+ return { search, limit }
48
+ }
49
+
50
+ export async function searchNamedRows(
51
+ table: NamedSearchTable,
52
+ query: NamedSearchQuery,
53
+ runner: NamedSearchRunner = db,
54
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
55
+ ): Promise<{ rows: NamedRow[], total: number }> {
56
+ // The table name is SQL, not a value, so only the fixed list is accepted.
57
+ if (!(NAMED_SEARCH_TABLES as readonly string[]).includes(table))
58
+ throw new TypeError(`${table} is not a searchable table.`)
59
+
60
+ const sql = sqlHelpers(dialect)
61
+ const values: unknown[] = []
62
+ let where = ''
63
+ if (query.search) {
64
+ const pattern = containsPattern(query.search)
65
+ values.push(pattern, pattern)
66
+ where = ` WHERE LOWER(COALESCE(name, '')) LIKE ${sql.param(1)} ESCAPE '!' OR LOWER(COALESCE(email, '')) LIKE ${sql.param(2)} ESCAPE '!'`
67
+ }
68
+
69
+ const counted = await runner.unsafe(`SELECT COUNT(*) AS total_count FROM ${table}${where}`, values).execute() as Array<{ total_count: unknown }>
70
+ const found = await runner.unsafe(
71
+ // LOWER, so the order is the same on every dialect: each collates case its own way.
72
+ `SELECT id, name, email FROM ${table}${where} ORDER BY LOWER(COALESCE(name, '')) ASC, id ASC LIMIT ${query.limit}`,
73
+ values,
74
+ ).execute() as Array<{ id: unknown, name: string | null, email: string | null }>
75
+
76
+ return {
77
+ rows: (Array.isArray(found) ? found : []).map(row => ({ id: Number(row.id), name: row.name ?? null, email: row.email ?? null })),
78
+ total: countOf(Array.isArray(counted) ? counted[0]?.total_count : 0),
79
+ }
80
+ }
@@ -7,6 +7,7 @@ export default defineModel({
7
7
  table: 'queue_workers',
8
8
  primaryKey: 'worker_id',
9
9
  autoIncrement: false,
10
+ traits: { useTimestamps: false },
10
11
  dashboard: { access: false },
11
12
  indexes: [{ name: 'queue_workers_heartbeat_at_index', columns: ['heartbeat_at'] }],
12
13
  attributes: {
@@ -48,9 +48,11 @@ export default defineModel({
48
48
  method: {
49
49
  fillable: true,
50
50
  validation: {
51
- rule: schema.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD']),
51
+ // Observations include rejected methods (for example PROPFIND -> 405).
52
+ // An enum of application verbs silently lost those requests at insert.
53
+ rule: schema.string().max(255),
52
54
  message: {
53
- enum: 'method must be a valid HTTP method',
55
+ string: 'method must be an HTTP method token',
54
56
  required: 'method is required',
55
57
  },
56
58
  },
package/bootstrap.ts CHANGED
@@ -22,6 +22,7 @@
22
22
  */
23
23
 
24
24
  import { config, feature } from '@stacksjs/config'
25
+ import process from 'node:process'
25
26
  import { frameworkPath } from '@stacksjs/path'
26
27
  import { log } from '@stacksjs/logging/runtime'
27
28
  import { bundleMounts, DEFAULT_ROUTE_BUNDLE_FEATURES, route, withRouteAdmission } from '@stacksjs/router'
@@ -108,7 +109,11 @@ async function registerDefaultBundles(): Promise<void> {
108
109
  await route.register(frameworkPath('defaults/routes/dashboard.ts'))
109
110
  // JSON endpoints for the dev dashboard UI. Kept separate from the view
110
111
  // routes above so the data layer is one obvious file to grep.
111
- await route.register(frameworkPath('defaults/routes/dashboard-api.ts'))
112
+ // The standalone dashboard registers this after the app loader finishes,
113
+ // outside table admission. Its home endpoint intentionally reports optional
114
+ // stores as unavailable instead of disappearing when Request is not used.
115
+ if (process.env.STACKS_DASHBOARD_WORKER !== '1')
116
+ await route.register(frameworkPath('defaults/routes/dashboard-api.ts'))
112
117
  // The dev dashboard boots through this file rather than the application
113
118
  // router's importRoutes() path, so load model-declared useApi routes here too.
114
119
  //
@@ -1,4 +1,5 @@
1
1
  import { dashboardApi } from '../../dashboard-api'
2
+ import { readEveryPage } from '../../dashboard-list'
2
3
  import { pushToast } from '../../toasts'
3
4
  import { useStorage } from '@stacksjs/browser/composables/useStorage'
4
5
 
@@ -11,6 +12,13 @@ interface DashboardResourceOptions {
11
12
  storageKey: string
12
13
  singular: string
13
14
  plural: string
15
+ /**
16
+ * The endpoint answers one page at a time (`{ records, total }`, with
17
+ * `page` and `per_page`) instead of a bare array, as the dashboard's
18
+ * delivery routes do (stacksjs/stacks#3218). `fetchAll` then reads every
19
+ * page, so it still returns every record.
20
+ */
21
+ paged?: boolean
14
22
  }
15
23
 
16
24
  export function createDashboardResource<
@@ -19,9 +27,12 @@ export function createDashboardResource<
19
27
  >(options: DashboardResourceOptions) {
20
28
  const items = useStorage<TRecord[]>(options.storageKey, [])
21
29
 
30
+ const fetchPages = (): Promise<TRecord[]> => readEveryPage((page, perPage) =>
31
+ dashboardApi<{ records?: TRecord[], total?: number }>(`${options.path}?page=${page}&per_page=${perPage}`))
32
+
22
33
  async function fetchAll(): Promise<TRecord[]> {
23
34
  try {
24
- const data = await dashboardApi<TRecord[]>(options.path)
35
+ const data = options.paged ? await fetchPages() : await dashboardApi<TRecord[]>(options.path)
25
36
  if (!Array.isArray(data))
26
37
  throw new TypeError('Server returned a non-array response')
27
38
 
@@ -6,6 +6,7 @@ const resource = createDashboardResource<DeliveryRoutes, NewDeliveryRoute>({
6
6
  storageKey: 'deliveryRoutes',
7
7
  singular: 'delivery route',
8
8
  plural: 'delivery routes',
9
+ paged: true,
9
10
  })
10
11
 
11
12
  export function useDeliveryRoutes() {
@@ -20,6 +20,7 @@ const resource = createDashboardResource<LicenseKeys, NewLicenseKey>({
20
20
  storageKey: 'licenseKeys',
21
21
  singular: 'license key',
22
22
  plural: 'license keys',
23
+ paged: true,
23
24
  })
24
25
 
25
26
  const options = useStorage<LicenseKeyOptions>('licenseKeyOptions', {
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, it } from 'bun:test'
2
- import { pageControls, useRecordsDashboard } from './dashboard-list'
2
+ import { state } from '@stacksjs/stx'
3
+ import { LARGEST_PAGE, pageControls, readEveryPage, useRecordsDashboard, useServerList } from './dashboard-list'
3
4
 
4
5
  /** The smallest thing with the two members `pageControls` reads. */
5
6
  function pageSignal(initial: number) {
@@ -226,3 +227,133 @@ describe('useRecordsDashboard goToPage', () => {
226
227
  expect(d.page()).toBe(1)
227
228
  })
228
229
  })
230
+
231
+ describe('useServerList', () => {
232
+ /** A fetch that records what it was asked and answers when told to. */
233
+ function server() {
234
+ const asked: URLSearchParams[] = []
235
+ const pending: Array<(answer: { records: string[], total: number, page: number }) => void> = []
236
+ const fetch = (params: URLSearchParams) => {
237
+ asked.push(params)
238
+ return new Promise<{ records: string[], total: number, page: number }>(resolve => pending.push(resolve))
239
+ }
240
+ return { asked, pending, fetch }
241
+ }
242
+ const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
243
+
244
+ it('asks for the default order and lands the answer', async () => {
245
+ const api = server()
246
+ const list = useServerList<string>({ fetch: api.fetch, defaultSort: { sort: 'created', direction: 'desc' } })
247
+ const loading = list.load()
248
+ expect(api.asked[0]!.toString()).toBe('sort=created&direction=desc&page=1&per_page=25')
249
+ api.pending[0]!({ records: ['a', 'b'], total: 30, page: 1 })
250
+ await loading
251
+ expect(list.records()).toEqual(['a', 'b'])
252
+ expect(list.total()).toBe(30)
253
+ expect(list.loading()).toBe(false)
254
+ })
255
+
256
+ it('keeps only the newest answer when two overlap', async () => {
257
+ const api = server()
258
+ const list = useServerList<string>({ fetch: api.fetch, defaultSort: { sort: 'created', direction: 'desc' } })
259
+ const first = list.load()
260
+ const second = list.load()
261
+ api.pending[1]!({ records: ['new'], total: 1, page: 1 })
262
+ api.pending[0]!({ records: ['old'], total: 9, page: 1 })
263
+ await Promise.all([first, second])
264
+ expect(list.records()).toEqual(['new'])
265
+ expect(list.total()).toBe(1)
266
+ })
267
+
268
+ it('asks for page 1 when a filter changes, and leaves out "all"', async () => {
269
+ const api = server()
270
+ const status = state('all')
271
+ const list = useServerList<string>({ fetch: api.fetch, defaultSort: { sort: 'id', direction: 'asc' }, filters: () => ({ status: status() }) })
272
+ list.page.set(3)
273
+ status.set('active')
274
+ expect(api.asked.length).toBe(1)
275
+ expect(api.asked[0]!.get('status')).toBe('active')
276
+ expect(api.asked[0]!.get('page')).toBe('1')
277
+ status.set('all')
278
+ expect(api.asked[1]!.has('status')).toBe(false)
279
+ })
280
+
281
+ it('sends the search once typing pauses', async () => {
282
+ const api = server()
283
+ const list = useServerList<string>({ fetch: api.fetch, defaultSort: { sort: 'id', direction: 'asc' }, searchDelay: 20 })
284
+ list.search.set('a')
285
+ list.search.set('ab')
286
+ list.search.set('abc ')
287
+ expect(api.asked.length).toBe(0)
288
+ await sleep(40)
289
+ expect(api.asked.length).toBe(1)
290
+ expect(api.asked[0]!.get('q')).toBe('abc')
291
+ expect(list.params().get('q')).toBe('abc')
292
+ })
293
+
294
+ it('maps a column header to the server sort, and an unknown one back to the default', () => {
295
+ const api = server()
296
+ const list = useServerList<string>({ fetch: api.fetch, defaultSort: { sort: 'created', direction: 'desc' }, columnSorts: { stopsLabel: 'stops' } })
297
+ list.changeSort({ key: 'stopsLabel', direction: 'asc' })
298
+ expect(api.asked[0]!.get('sort')).toBe('stops')
299
+ expect(api.asked[0]!.get('direction')).toBe('asc')
300
+ list.changeSort({ key: 'notes', direction: 'asc' })
301
+ expect(api.asked[1]!.get('sort')).toBe('created')
302
+ expect(api.asked[1]!.get('direction')).toBe('desc')
303
+ })
304
+
305
+ it('reports a failed load, and ignores one that a newer load replaced', async () => {
306
+ const errors: unknown[] = []
307
+ let calls = 0
308
+ const list = useServerList<string>({
309
+ fetch: async () => {
310
+ calls++
311
+ if (calls === 1)
312
+ throw new Error('boom')
313
+ return { records: ['ok'], total: 1, page: 1 }
314
+ },
315
+ defaultSort: { sort: 'id', direction: 'asc' },
316
+ onError: error => errors.push(error),
317
+ })
318
+ await list.load()
319
+ expect(list.loadError()).toBe('boom')
320
+ expect(errors.length).toBe(1)
321
+ await list.load()
322
+ expect(list.loadError()).toBe('')
323
+ expect(list.records()).toEqual(['ok'])
324
+ })
325
+ })
326
+
327
+ describe('readEveryPage', () => {
328
+ /** A paged endpoint over `count` numbered rows. */
329
+ function endpoint(count: number) {
330
+ const asked: number[] = []
331
+ const get = async (page: number, perPage: number) => {
332
+ asked.push(page)
333
+ const records = Array.from({ length: count }, (_, i) => i + 1).slice((page - 1) * perPage, page * perPage)
334
+ return { records, total: count }
335
+ }
336
+ return { asked, get }
337
+ }
338
+
339
+ it('reads every page, past the 500 a single read used to stop at', async () => {
340
+ const api = endpoint(523)
341
+ const rows = await readEveryPage(api.get)
342
+ expect(rows.length).toBe(523)
343
+ expect(rows.at(-1)).toBe(523)
344
+ expect(api.asked).toEqual([1, 2, 3, 4, 5, 6])
345
+ })
346
+
347
+ it('stops at an exact multiple of the page size, and on an empty list', async () => {
348
+ const exact = endpoint(LARGEST_PAGE * 2)
349
+ expect((await readEveryPage(exact.get)).length).toBe(LARGEST_PAGE * 2)
350
+ expect(exact.asked).toEqual([1, 2])
351
+ const empty = endpoint(0)
352
+ expect(await readEveryPage(empty.get)).toEqual([])
353
+ expect(empty.asked).toEqual([1])
354
+ })
355
+
356
+ it('refuses an answer that is not a page', async () => {
357
+ await expect(readEveryPage(async () => ({ total: 3 }) as never)).rejects.toThrow('without records')
358
+ })
359
+ })