@stacksjs/defaults 0.75.562 → 0.75.568

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.
@@ -671,6 +671,8 @@ buddy telemetry # telemetry management
671
671
  buddy list # list all available commands
672
672
  buddy version # display version (flags: --version, -v)
673
673
  buddy saas # SaaS management
674
+ buddy hq:connect [services] # connect to HQ services, write keys to .env (--no-open, --no-verify)
675
+ buddy hq:status # usage against each connected HQ service's allowance
674
676
  buddy sms # SMS commands
675
677
  buddy phone # phone commands
676
678
  buddy http # HTTP commands
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: stacks-hq
3
- description: Use when metering usage against a plan allowance, answering the X-HQ-Usage header, mounting an HQ service's connect and usage endpoints, or reading an HQ service from an app. Covers @stacksjs/hq (meter, service, client, testing).
3
+ description: Use when metering usage against a plan allowance, answering the X-HQ-Usage header, mounting an HQ service's connect and usage endpoints, connecting an app with buddy hq:connect, or reading an HQ service from an app. Covers @stacksjs/hq (meter, service, client, testing), the HQ entries in config/services.ts and buddy hq:status.
4
4
  license: MIT
5
5
  compatibility: Bun >= 1.3.0, TypeScript
6
6
  allowed-tools: Read Edit Write Bash Grep Glob
@@ -136,6 +136,44 @@ if (usage.ok)
136
136
  - `AnalyticsReader`, `UptimeReader` and `CommsReader` are interfaces only; the
137
137
  package README lists the endpoint each service must expose first.
138
138
 
139
+ ## Connecting an app
140
+
141
+ An app connects with `buddy hq:connect [service...]` (BugHQ and LogHQ when none
142
+ is named). For each service the command starts a connect, prints the approve
143
+ link and any confirmation code, opens the browser, waits for the approval, and
144
+ writes that service's keys to `.env`: `BUGHQ_KEY`, `BUGHQ_READ_KEY`,
145
+ `BUGHQ_PROJECT_ID`, `LOGHQ_KEY`, `LOGHQ_READ_KEY`, `LOGHQ_PROJECT_ID`. A key is
146
+ never printed. It then sends one test error and one test log and reads each
147
+ back with the read key. `--no-open` and `--no-verify` skip those steps, and a
148
+ service that answers 404 on the connect route is reported as not available yet
149
+ without failing the others.
150
+
151
+ `config/services.ts` lists each service's URL, keys and project, as
152
+ `services.bughq`, `services.loghq` and so on. `config/logging.ts` and
153
+ `config/monitoring.ts` take their LogHQ and BugHQ settings from it.
154
+ `buddy hq:status` prints used, limit, period and state
155
+ for every connected service, with the upgrade link from 80% of an allowance.
156
+
157
+ ReportsHQ is the odd one out: it runs inside the app against the app's own
158
+ database, so it has no ingest or read key and meters nothing. Its entry is
159
+ `services.reportshq` with a `license` from `REPORTSHQ_LICENSE`, which
160
+ `buddy hq:status` checks offline (shape only) and never prints.
161
+ `buddy hq:connect reportshq` runs the same approval and writes the licence to
162
+ `REPORTSHQ_LICENSE`, with nothing to send or read back.
163
+
164
+ A licence-only service answers a `LicenseGrant` (`{ project, licenseKey,
165
+ dashboardUrl }`) from `provision` and leaves `authenticateReadKey` and `usage`
166
+ off its adapter. `createHqService` then mounts the two connect routes and no
167
+ usage route. `isLicenseGrant` tells the two kinds of approved answer apart.
168
+
169
+ The dashboard's Logs and Errors sections read LogHQ and BugHQ when
170
+ `config/dashboard.ts` sets `providers.logs` or `providers.errors` to
171
+ `{ driver: 'hq' }`.
172
+
173
+ In tests, `createFakeHqService()` and `fakeHqFetch()` from
174
+ `@stacksjs/testing/hq` stand in for a service: the contract routes, ingest and
175
+ the two project readers, with no port.
176
+
139
177
  ## Limits
140
178
 
141
179
  - The counter is approximate by one flush interval per instance. Use a
@@ -21,7 +21,7 @@ Browser runtime bindings are documented separately in `stacks-auto-imports`.
21
21
  | `@stacksjs/auth` | [`stacks-auth`](../stacks-auth/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/auth/src/index.ts) | 132 |
22
22
  | `@stacksjs/browser` | [`stacks-browser`](../stacks-browser/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/browser/src/index.ts) | 10 |
23
23
  | `@stacksjs/browser-extension` | [`stacks-browser-extension`](../stacks-browser-extension/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/browser-extension/src/index.ts) | 9 |
24
- | `@stacksjs/buddy` | [`stacks-buddy`](../stacks-buddy/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/src/index.ts) | 193 |
24
+ | `@stacksjs/buddy` | [`stacks-buddy`](../stacks-buddy/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/src/index.ts) | 194 |
25
25
  | `@stacksjs/build` | [`stacks-build`](../stacks-build/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/build/src/index.ts) | 7 |
26
26
  | `@stacksjs/cache` | [`stacks-cache`](../stacks-cache/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/cache/src/index.ts) | 24 |
27
27
  | `@stacksjs/calendar-api` | [`stacks-calendar`](../stacks-calendar/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/calendar-api/src/index.ts) | 5 |
@@ -220,7 +220,7 @@ Read the entrypoint and package export map for re-exported or type-only surfaces
220
220
 
221
221
  Local source modules: [src/commands/index.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/src/commands/index.ts).
222
222
 
223
- Evidence directory: [193 retained tests](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/tests). These files are evidence pointers, not a claim that all tests were run for this catalog.
223
+ Evidence directory: [194 retained tests](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/buddy/tests). These files are evidence pointers, not a claim that all tests were run for this catalog.
224
224
 
225
225
  ### @stacksjs/build
226
226
 
@@ -34,9 +34,9 @@ const open = WorkItem.where('done', false).orderBy('id', 'desc').get()
34
34
  load lazily; server boot waits for model initialization. A feature-disabled
35
35
  model is not made usable merely by an ambient declaration.
36
36
 
37
- ## Reads answer in place, writes are promises
37
+ ## Model calls answer in place
38
38
 
39
- A model read returns its value where it is written, on SQLite, MySQL and
39
+ A model call returns its value where it is written, on SQLite, MySQL and
40
40
  Postgres:
41
41
 
42
42
  ```ts
@@ -48,7 +48,7 @@ if (User.where('email', email).exists()) return response.badRequest('Taken')
48
48
  for (const post of Post.where('published', true).get()) titles.push(post.title)
49
49
  ```
50
50
 
51
- - **Which calls:** every read. `find`, `findOrFail`, `findMany`, `first`,
51
+ - **Every read, on every model.** `find`, `findOrFail`, `findMany`, `first`,
52
52
  `firstOrFail`, `last`, `all`, `get`, `count`, `exists`, `pluck`, `sum`,
53
53
  `avg`, `min`, `max`, `paginate`, `simplePaginate`, `cursorPaginate`, eager
54
54
  loading through `with()`, and reads of encrypted attributes.
@@ -59,18 +59,59 @@ for (const post of Post.where('published', true).get()) titles.push(post.title)
59
59
  row throws; wrap it in `try`/`catch`. `.catch()` and `.then()` do not exist
60
60
  on a row. In a test, `expect(() => User.findOrFail(0)).toThrow()`, not
61
61
  `await expect(...).rejects`.
62
- - **A write is a promise, on every model.** `create`, `createMany`,
63
- `firstOrCreate`, `updateOrCreate`, `update`, `save`, `delete`, `forceDelete`
64
- and a query's `delete()` run setters, validation, encryption and lifecycle
65
- events, any of which may wait. Keep their `await`.
66
62
  - **How.** SQLite runs a query in place. MySQL and Postgres run on Bun's
67
63
  driver, held by a worker thread the caller waits on, so nothing else runs on
68
64
  the calling thread while a query is in flight (the cost `bun:sqlite` always
69
- had). `models: { execution: 'async' }` in the query-builder config makes
70
- MySQL and Postgres reads promises again for an app that needs the event loop
71
- free during queries; every read then has to be awaited.
65
+ had). `models: { execution: 'async' }` in `config/qb.ts` makes MySQL and
66
+ Postgres calls promises again for an app that needs the event loop free
67
+ during queries; every call then has to be awaited.
72
68
  - **Not covered.** The `db` query builder (`db.selectFrom(...)`) and
73
69
  `transaction()` still return promises.
70
+ - **Inside `db.transaction()`, write through `tx`, not through a model.** A
71
+ model call runs on its own connection, and on MySQL and Postgres the thread
72
+ waits for it. One that needs a row the open transaction has locked can never
73
+ finish, because the transaction cannot commit while its thread is waiting.
74
+ It throws `StatementTimeoutError` after `models.timeoutMs` (30 seconds by
75
+ default, `0` for no limit) instead of stopping the process. Postgres cancels
76
+ the abandoned statement; MySQL cannot, so there it may still be applied once
77
+ the lock is gone.
78
+
79
+ ### Writes: in place unless the model asks for work around them
80
+
81
+ ```ts
82
+ // Declares nothing to wait for: the write is the row.
83
+ const note = Note.create({ title: 'Draft' })
84
+ note.update({ title: 'Final' })
85
+ Note.delete(note.id)
86
+
87
+ // Declares `observe`: every write is a promise.
88
+ const order = await Order.create({ total: 1200 })
89
+ ```
90
+
91
+ A model's writes wait, and are typed as promises, when its definition
92
+ declares any of:
93
+
94
+ | Declaration | What the write waits for |
95
+ |---|---|
96
+ | `traits.observe` | lifecycle event listeners |
97
+ | `traits.useSearch` | the search index update |
98
+ | `traits.broadcastOn` | the broadcast |
99
+ | `traits.useSoftDeletes` / `softDeletable` | the soft-delete transaction |
100
+ | `traits.useAudit`, `traits.useActivityLog` | the audit or activity row |
101
+ | `set: { ... }` | a setter, which may hash or call out |
102
+ | `hooks: { ... }` | the model's own hooks |
103
+
104
+ It is decided from the declaration, not from what happens to run: on such a
105
+ model `create`, `createMany`, `firstOrCreate`, `updateOrCreate`, `update`,
106
+ `save`, `delete`, `forceDelete` and a query's `delete()` are promises every
107
+ time, and a failure is a rejection. On a model with none of these they return
108
+ the value, and a failure (a guarded column, a validation rule) throws where
109
+ the call stands. `modelWritesWait(definition)` answers it at runtime and
110
+ `ModelWritesWait<typeof Model>` in the types. Reads never wait on either kind.
111
+
112
+ When in doubt, `await` the write: it is correct on every model. An instance
113
+ write on a model with an async setter still goes through `saveAsync()` /
114
+ `updateAsync()`.
74
115
 
75
116
  ## Write behavior
76
117
 
@@ -107,11 +107,12 @@ if (User.where('active', true).exists()) dump(User.count())
107
107
  for (const post of Post.latest().limit(5).get()) dump(post.title)
108
108
  ```
109
109
 
110
- A model read is a value everywhere, in app code as well as here (see
111
- `stacks-orm`). What a session adds is the rest: outside a function, a call
112
- that returns a promise is waited for where it stands, and so is a promise a
113
- statement names (the value of a line, of a declaration, of an assignment). So
114
- a write (`User.create(...)`), a `fetch` or a job dispatch reads the same way a
110
+ A model read is a value everywhere, in app code as well as here, and so is a
111
+ write on a model that declares nothing to wait for (see `stacks-orm`). What a
112
+ session adds is the rest: outside a function, a call that returns a promise is
113
+ waited for where it stands, and so is a promise a statement names (the value
114
+ of a line, of a declaration, of an assignment). So a write on a model with
115
+ events or a search index, a `fetch` or a job dispatch reads the same way a
115
116
  query does. A rejection is thrown there.
116
117
 
117
118
  - **Inside a function nothing changes.** `await` there is yours to write:
@@ -1,7 +1,8 @@
1
+ import type { HqClient } from '@stacksjs/hq/client'
1
2
  import type { DashboardProviderUnavailable } from '../dashboard-provider'
2
3
  import type { DashboardLogRecord, DashboardLogSummary } from './log-dashboard'
3
4
  import { db } from '@stacksjs/database/runtime'
4
- import { HQ_READ_UNAVAILABLE, readThroughProvider, resolveDashboardDriver } from '../dashboard-provider'
5
+ import { dashboardHqClient, hqUnavailableReason, readThroughProvider, resolveDashboardDriver } from '../dashboard-provider'
5
6
  import { DASHBOARD_LOG_TYPES, normalizeDashboardLog, summarizeDashboardLogTypes } from './log-dashboard'
6
7
 
7
8
  /**
@@ -173,6 +174,102 @@ export const localLogsProvider: DashboardLogsProvider = {
173
174
  },
174
175
  }
175
176
 
177
+ /**
178
+ * LogHQ's levels, as the four types this section filters and counts by.
179
+ *
180
+ * LogHQ has no `success`: the framework's logger sends one as `info`, so that
181
+ * filter matches nothing here rather than guessing.
182
+ */
183
+ const HQ_LEVELS_BY_TYPE: Record<string, string[]> = {
184
+ error: ['error', 'critical', 'alert', 'emergency'],
185
+ warning: ['warning'],
186
+ info: ['info', 'notice', 'debug'],
187
+ success: [],
188
+ }
189
+
190
+ function typeOfHqLevel(level: string): string {
191
+ const normalized = level.toLowerCase()
192
+ return Object.keys(HQ_LEVELS_BY_TYPE).find(type => HQ_LEVELS_BY_TYPE[type]!.includes(normalized)) ?? normalized
193
+ }
194
+
195
+ /** How many of LogHQ's pages a numbered page may walk to. It pages by cursor, not by number. */
196
+ const HQ_MAX_PAGE_WALK = 10
197
+
198
+ /**
199
+ * LogHQ, read with the project's read key.
200
+ *
201
+ * Two things differ from the local table and are answered honestly rather
202
+ * than faked. LogHQ pages by cursor and reports no total, so `total` is what
203
+ * has been seen so far plus one when there is more, which is enough for the
204
+ * pager to offer the next page. And the summary counts the page shown, not
205
+ * the whole stream.
206
+ */
207
+ export function hqLogsProvider(client: Pick<HqClient, 'logs'>, now: () => number = Date.now): DashboardLogsProvider {
208
+ return {
209
+ async logs(query: DashboardLogQuery): Promise<DashboardLogPayload> {
210
+ const levels = query.type ? HQ_LEVELS_BY_TYPE[query.type] ?? [query.type] : undefined
211
+ if (levels && !levels.length)
212
+ return { ...emptyLogPayload('', query), unavailable: undefined }
213
+
214
+ const cutoff = query.range === 'all' ? 0 : now() - Number(query.range) * 86400000
215
+ let page = 1
216
+ let cursor: string | undefined
217
+ let entries: Awaited<ReturnType<HqClient['logs']['list']>> & { ok: true } | undefined
218
+
219
+ for (; page <= Math.min(query.page, HQ_MAX_PAGE_WALK); page++) {
220
+ const result = await client.logs.list({
221
+ level: levels,
222
+ channel: query.source || undefined,
223
+ search: query.search || undefined,
224
+ before: cursor,
225
+ limit: query.perPage,
226
+ })
227
+ if (!result.ok)
228
+ return emptyLogPayload(hqUnavailableReason(result), query)
229
+ entries = result
230
+ if (!result.data.nextCursor || page === Math.min(query.page, HQ_MAX_PAGE_WALK))
231
+ break
232
+ cursor = result.data.nextCursor
233
+ }
234
+
235
+ const all = entries?.data.logs ?? []
236
+ // Newest first, so everything after the first entry older than the range is older too.
237
+ const inRange = cutoff ? all.filter(log => !(Date.parse(log.timestamp) < cutoff)) : all
238
+ const hasMore = Boolean(entries?.data.nextCursor) && inRange.length === all.length
239
+ const offset = (page - 1) * query.perPage
240
+
241
+ const logs = inRange.map((log, index) => normalizeDashboardLog({
242
+ // LogHQ's ids are strings and this section keys rows by number.
243
+ id: offset + index + 1,
244
+ timestamp: log.timestamp,
245
+ type: typeOfHqLevel(log.level),
246
+ source: log.channel ?? '',
247
+ message: log.message,
248
+ // LogHQ's project is the one the read key opens; an entry carries no other.
249
+ project: '',
250
+ created_at: log.createdAt ?? log.timestamp,
251
+ }))
252
+ const total = offset + logs.length + (hasMore ? 1 : 0)
253
+ const typeCounts = new Map<string, number>()
254
+ for (const log of logs)
255
+ typeCounts.set(log.type, (typeCounts.get(log.type) ?? 0) + 1)
256
+
257
+ return {
258
+ logs,
259
+ summary: summarizeDashboardLogTypes([...typeCounts].map(([type, count]) => ({ type, count })), total),
260
+ pagination: { page, perPage: query.perPage, total, totalPages: page + (hasMore ? 1 : 0) },
261
+ options: {
262
+ sources: [...new Set(logs.map(log => log.source).filter(Boolean))].sort(),
263
+ projects: [],
264
+ types: [...DASHBOARD_LOG_TYPES],
265
+ ranges: [...DASHBOARD_LOG_RANGES],
266
+ },
267
+ generatedAt: new Date(now()).toISOString(),
268
+ }
269
+ },
270
+ }
271
+ }
272
+
176
273
  /** Reads the Logs section through whichever provider config selects. */
177
274
  export async function readDashboardLogs(query: DashboardLogQuery): Promise<DashboardLogPayload> {
178
275
  const driver = await resolveDashboardDriver('logs')
@@ -183,7 +280,7 @@ export async function readDashboardLogs(query: DashboardLogQuery): Promise<Dashb
183
280
  return readThroughProvider(
184
281
  'logs',
185
282
  reason => emptyLogPayload(reason, query),
186
- async () => emptyLogPayload(HQ_READ_UNAVAILABLE, query),
283
+ async () => hqLogsProvider(await dashboardHqClient('logs', driver.options)).logs(query),
187
284
  isLogPayload,
188
285
  )
189
286
  }
@@ -1,4 +1,6 @@
1
- import type { DashboardHqDriverOptions, DashboardProviderName, DashboardProviderSelection } from '@stacksjs/types'
1
+ import type { HqClient, HqUnavailable } from '@stacksjs/hq/client'
2
+ import type { DashboardHqDriverOptions, DashboardProviderName, DashboardProviderSelection, HqServiceName, HqServiceOptions } from '@stacksjs/types'
3
+ import { createHqClient } from '@stacksjs/hq/client'
2
4
 
3
5
  /**
4
6
  * The seam between a dashboard section and the data behind it.
@@ -155,16 +157,92 @@ export async function readThroughProvider<T>(
155
157
  }
156
158
 
157
159
  /**
158
- * The reason an `hq` provider has no data yet.
160
+ * The reason the Analytics section has no data from `hq` yet.
159
161
  *
160
- * Both published SDKs are ingest clients. `@loghq/stacks` and `@bughq/stacks`
161
- * send records and expose no function that reads any back, and a project's
162
- * ingest key grants no read access by design. The hosted read APIs do exist,
163
- * but they authenticate a person rather than a machine, so wiring one needs a
164
- * product decision about service credentials before any code here can help.
165
- *
166
- * Selecting `hq` today therefore yields an empty section that says so, which
167
- * is the honest answer and keeps the degrade path real rather than theoretical.
162
+ * Logs and Errors read from LogHQ and BugHQ with a project read key (see
163
+ * `dashboardHqClient` below). AnalyticsHQ has no read-key endpoint, so
164
+ * selecting `hq` for analytics still yields an empty section that says so.
168
165
  */
169
166
  export const HQ_READ_UNAVAILABLE
170
167
  = 'No data. The hosted provider has no read API yet, so this section cannot be filled from it.'
168
+
169
+ /** The hosted service behind each domain that can be read today. */
170
+ const HQ_DOMAIN_SERVICE = { logs: 'loghq', errors: 'bughq' } as const satisfies Partial<Record<DashboardProviderDomain, HqServiceName>>
171
+
172
+ const HQ_LABELS: Record<HqServiceName, string> = {
173
+ bughq: 'BugHQ',
174
+ loghq: 'LogHQ',
175
+ analyticshq: 'AnalyticsHQ',
176
+ statushq: 'StatusHQ',
177
+ commshq: 'CommsHQ',
178
+ reportshq: 'ReportsHQ',
179
+ }
180
+
181
+ export type DashboardHqDomain = keyof typeof HQ_DOMAIN_SERVICE
182
+
183
+ /**
184
+ * A hosted read that came back with nothing, and the sentence to show for it.
185
+ *
186
+ * Thrown by an `hq` provider so its methods keep the same signatures as the
187
+ * local one's; the section's reader turns it into an empty payload carrying
188
+ * `reason`.
189
+ */
190
+ export class DashboardProviderUnavailableError extends Error {
191
+ constructor(public readonly reason: string) {
192
+ super(reason)
193
+ this.name = 'DashboardProviderUnavailableError'
194
+ }
195
+ }
196
+
197
+ /** Why a hosted read has no data, for whoever is looking at the dashboard. */
198
+ export function hqUnavailableReason(result: HqUnavailable): string {
199
+ const label = HQ_LABELS[result.service]
200
+ const connect = `Run \`buddy hq:connect ${result.service}\``
201
+ switch (result.reason) {
202
+ case 'not_configured':
203
+ return `${label} is not connected. ${connect} to connect it.`
204
+ case 'unauthorized':
205
+ return `${label} refused the read key. ${connect} to get a new one.`
206
+ case 'timeout':
207
+ case 'network':
208
+ return `${label} could not be reached. This section will fill in once it answers again.`
209
+ case 'http':
210
+ // The services answer 404, not 401, for a key that does not open the project.
211
+ return result.status === 404
212
+ ? `${label} has no project that this read key opens. ${connect} to connect it again.`
213
+ : `${label} could not be read (it answered ${result.status}).`
214
+ default:
215
+ return `${label} answered something this section cannot show.`
216
+ }
217
+ }
218
+
219
+ /**
220
+ * The client a domain's `hq` provider reads with.
221
+ *
222
+ * Credentials come from `config/services.ts`, where `buddy hq:connect` put them.
223
+ * The domain's own `drivers.hq` settings win where set, so one section can
224
+ * point at another project or a self-hosted instance.
225
+ */
226
+ export async function dashboardHqClient(domain: DashboardHqDomain, options: DashboardHqDriverOptions = {}): Promise<HqClient> {
227
+ const service = HQ_DOMAIN_SERVICE[domain]
228
+ let configured: HqServiceOptions | undefined
229
+ try {
230
+ const { config, overridesReady } = await import('@stacksjs/config')
231
+ await overridesReady.catch(() => {})
232
+ configured = config.services?.[service]
233
+ }
234
+ catch (error) {
235
+ console.warn(`[dashboard/api] config.services could not be read for ${domain}:`, error)
236
+ }
237
+
238
+ return createHqClient({
239
+ services: {
240
+ [service]: {
241
+ url: options.baseUrl || configured?.url || '',
242
+ readKey: options.token || configured?.readKey || '',
243
+ project: options.project || configured?.project,
244
+ },
245
+ },
246
+ timeoutMs: options.timeoutMs ?? 5000,
247
+ })
248
+ }
@@ -1,8 +1,9 @@
1
+ import type { HqClient, Issue } from '@stacksjs/hq/client'
1
2
  import type { DashboardProviderUnavailable } from '../Dashboard/dashboard-provider'
2
3
  import { errors } from '@stacksjs/commerce'
3
4
  import type { QueryReader } from '../Dashboard/Content/content-list'
4
5
  import { LIST_PAGE_SIZES, queryText } from '../Dashboard/Content/content-list'
5
- import { HQ_READ_UNAVAILABLE, readThroughProvider, resolveDashboardDriver } from '../Dashboard/dashboard-provider'
6
+ import { dashboardHqClient, DashboardProviderUnavailableError, hqUnavailableReason, readThroughProvider, resolveDashboardDriver } from '../Dashboard/dashboard-provider'
6
7
 
7
8
  /**
8
9
  * Where the Errors section reads from.
@@ -230,9 +231,114 @@ const EMPTY_STATS: DashboardErrorStats = {
230
231
  trend: 0,
231
232
  }
232
233
 
233
- async function resolveErrorsProvider(): Promise<{ provider: DashboardErrorsProvider, remote: boolean }> {
234
- const driver = await resolveDashboardDriver('errors')
235
- return { provider: localErrorsProvider, remote: driver.name !== 'local' }
234
+ /**
235
+ * BugHQ, read with the project's read key.
236
+ *
237
+ * BugHQ already groups occurrences into issues, so an issue is a group here.
238
+ * Its read API is the issue list (the hundred most recently seen), which is
239
+ * what every answer below is built from:
240
+ *
241
+ * - a group's `message` is the issue title and it has no stack, because the
242
+ * list carries none
243
+ * - `stats` counts occurrences across those issues; `last_24h` is the number
244
+ * of issues seen in the last day, since the list has no per-hour counts
245
+ * - there is no timeline to read, so that panel says so
246
+ *
247
+ * A read that comes back unavailable throws
248
+ * `DashboardProviderUnavailableError`, which `readErrors` turns into the empty
249
+ * value plus its reason.
250
+ */
251
+ export function hqErrorsProvider(client: Pick<HqClient, 'issues'>, now: () => number = Date.now): DashboardErrorsProvider {
252
+ const issues = async (status?: string): Promise<Issue[]> => {
253
+ const result = await client.issues.list(status ? { status } : {})
254
+ if (!result.ok)
255
+ throw new DashboardProviderUnavailableError(hqUnavailableReason(result))
256
+ return result.data
257
+ }
258
+
259
+ const typeOf = (issue: Issue): string => issue.errorType || 'Error'
260
+ // BugHQ titles an issue `Type: message`.
261
+ const messageOf = (issue: Issue): string =>
262
+ issue.title.startsWith(`${typeOf(issue)}: `) ? issue.title.slice(typeOf(issue).length + 2) : issue.title
263
+
264
+ const toGroup = (issue: Issue): DashboardGroupedError => ({
265
+ id: issue.id,
266
+ type: typeOf(issue),
267
+ message: messageOf(issue),
268
+ stack: null,
269
+ status: toErrorStatus(issue.status),
270
+ count: issue.count,
271
+ first_seen: issue.firstSeen ?? '',
272
+ last_seen: issue.lastSeen ?? '',
273
+ })
274
+
275
+ const toRecord = (issue: Issue): DashboardErrorRecord => ({
276
+ id: issue.id,
277
+ type: typeOf(issue),
278
+ message: messageOf(issue),
279
+ stack: null,
280
+ status: null,
281
+ resolution: toErrorStatus(issue.status),
282
+ additional_info: issue.culprit,
283
+ created_at: issue.firstSeen ?? '',
284
+ updated_at: issue.lastSeen,
285
+ })
286
+
287
+ return {
288
+ async grouped(query) {
289
+ const all = await issues(query.status === 'all' ? undefined : query.status)
290
+ const search = query.search.toLowerCase()
291
+ const matching = all
292
+ .filter(issue => !query.type || typeOf(issue) === query.type)
293
+ .filter(issue => !search || `${issue.title} ${issue.culprit ?? ''}`.toLowerCase().includes(search))
294
+ .map(toGroup)
295
+
296
+ const direction = query.direction === 'asc' ? 1 : -1
297
+ const key = (group: DashboardGroupedError): string | number =>
298
+ query.sort === 'count' ? group.count : query.sort === 'type' ? group.type : query.sort === 'status' ? group.status : group.last_seen
299
+ matching.sort((a, b) => {
300
+ const left = key(a)
301
+ const right = key(b)
302
+ return (left < right ? -1 : left > right ? 1 : 0) * direction
303
+ })
304
+
305
+ const page = Math.min(query.page, Math.max(1, Math.ceil(matching.length / query.perPage)))
306
+ return {
307
+ groups: matching.slice((page - 1) * query.perPage, page * query.perPage),
308
+ total: matching.length,
309
+ page,
310
+ types: [...new Set(all.map(typeOf))].sort(),
311
+ }
312
+ },
313
+
314
+ async stats() {
315
+ const all = await issues()
316
+ const since = now() - 86400000
317
+ const sum = (status: DashboardErrorStatus): number =>
318
+ all.filter(issue => toErrorStatus(issue.status) === status).reduce((total, issue) => total + issue.count, 0)
319
+ return {
320
+ total: all.reduce((total, issue) => total + issue.count, 0),
321
+ unresolved: sum('unresolved'),
322
+ resolved: sum('resolved'),
323
+ ignored: sum('ignored'),
324
+ last_24h: all.filter(issue => issue.lastSeen && Date.parse(issue.lastSeen) >= since).length,
325
+ trend: 0,
326
+ }
327
+ },
328
+
329
+ async timeline() {
330
+ throw new DashboardProviderUnavailableError('BugHQ has no hourly timeline to read yet. Open BugHQ for the full history.')
331
+ },
332
+
333
+ async byGroup(type, message) {
334
+ return (await issues()).filter(issue => typeOf(issue) === type && messageOf(issue) === message).map(toRecord)
335
+ },
336
+
337
+ async byId(id) {
338
+ const issue = (await issues()).find(candidate => candidate.id === String(id))
339
+ return issue ? toRecord(issue) : undefined
340
+ },
341
+ }
236
342
  }
237
343
 
238
344
  /**
@@ -247,19 +353,26 @@ async function readErrors<T>(
247
353
  read: (provider: DashboardErrorsProvider) => Promise<T>,
248
354
  isValid: (payload: unknown) => boolean,
249
355
  ): Promise<DashboardErrorsEnvelope<T>> {
250
- const { provider, remote } = await resolveErrorsProvider()
356
+ const driver = await resolveDashboardDriver('errors')
251
357
 
252
- if (!remote)
253
- return { data: await read(provider) }
358
+ if (driver.name === 'local')
359
+ return { data: await read(localErrorsProvider) }
254
360
 
255
- const payload = await readThroughProvider<DashboardErrorsEnvelope<T>>(
361
+ return readThroughProvider<DashboardErrorsEnvelope<T>>(
256
362
  'errors',
257
363
  reason => ({ data: empty, unavailable: reason }),
258
- async () => ({ data: empty, unavailable: HQ_READ_UNAVAILABLE }),
364
+ async () => {
365
+ try {
366
+ return { data: await read(hqErrorsProvider(await dashboardHqClient('errors', driver.options))) }
367
+ }
368
+ catch (error) {
369
+ if (error instanceof DashboardProviderUnavailableError)
370
+ return { data: empty, unavailable: error.reason }
371
+ throw error
372
+ }
373
+ },
259
374
  candidate => isValid((candidate as DashboardErrorsEnvelope<T>)?.data),
260
375
  )
261
-
262
- return payload
263
376
  }
264
377
 
265
378
  const EMPTY_GROUP_PAGE: DashboardGroupedErrorPage = { groups: [], total: 0, page: 1, types: [] }
@@ -2,7 +2,7 @@
2
2
  "publisher": "Stacks",
3
3
  "name": "vscode-stacks",
4
4
  "displayName": "Stacks",
5
- "version": "0.75.562",
5
+ "version": "0.75.568",
6
6
  "description": "Stacks, built into VS Code: stx templates, pickier linting and formatting, encrypted env files, the dev server preview and every buddy command. No other extensions required.",
7
7
  "license": "MIT",
8
8
  "funding": "https://github.com/sponsors/chrisbbreuer",
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/defaults",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.562",
5
+ "version": "0.75.568",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/stacksjs/stacks.git",
@@ -45,10 +45,10 @@
45
45
  "dependencies": {
46
46
  "@iconify-json/f7": "^1.2.2",
47
47
  "@iconify-json/hugeicons": "^1.2.35",
48
- "@stacksjs/mobile": "0.75.562",
48
+ "@stacksjs/mobile": "0.75.568",
49
49
  "@stacksjs/sanitizer": "^0.2.864",
50
50
  "@stacksjs/stx": "^0.2.864",
51
- "@stacksjs/strings": "0.75.562",
51
+ "@stacksjs/strings": "0.75.568",
52
52
  "@xterm/addon-fit": "^0.11.0",
53
53
  "@xterm/xterm": "^6.0.0",
54
54
  "ts-qr-codes": "^0.1.8"