@stacksjs/defaults 0.75.539 → 0.75.542

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 (152) hide show
  1. package/ai/AGENTS.md +2 -0
  2. package/ai/skills/stacks-actions/SKILL.md +1 -1
  3. package/ai/skills/stacks-auth/SKILL.md +8 -1
  4. package/ai/skills/stacks-dashboard/SKILL.md +196 -3
  5. package/ai/skills/stacks-dependencies/SKILL.md +46 -0
  6. package/ai/skills/stacks-development/SKILL.md +1 -1
  7. package/ai/skills/stacks-flow/SKILL.md +7 -0
  8. package/ai/skills/stacks-hq/SKILL.md +146 -0
  9. package/ai/skills/stacks-models/SKILL.md +21 -3
  10. package/ai/skills/stacks-native/CATALOG.md +22 -9
  11. package/ai/skills/stacks-new-app/SKILL.md +175 -0
  12. package/ai/skills/stacks-repl/SKILL.md +76 -43
  13. package/ai/skills/stacks-stx/SKILL.md +6 -2
  14. package/ai/skills/stacks-upstream/SKILL.md +188 -0
  15. package/ai/skills/stacks-writing-for-agents/SKILL.md +1 -1
  16. package/app/Actions/Dashboard/Data/UserIndexAction.ts +20 -2
  17. package/app/Actions/Dashboard/Models/ModelDestroyAction.ts +48 -12
  18. package/app/Actions/Dashboard/Models/ModelOptionsAction.ts +103 -0
  19. package/app/Actions/Dashboard/Models/ModelRelatedAction.ts +42 -0
  20. package/app/Actions/Dashboard/Models/ModelShowAction.ts +75 -12
  21. package/app/Actions/Dashboard/Models/ModelStoreAction.ts +7 -1
  22. package/app/Actions/Dashboard/Models/ModelUpdateAction.ts +16 -2
  23. package/app/Actions/Dashboard/Models/model-destroy.ts +75 -0
  24. package/app/Actions/Dashboard/Models/model-options.ts +56 -0
  25. package/app/Actions/Dashboard/Models/model-related.ts +202 -0
  26. package/app/Actions/Dashboard/Models/model-relations.ts +172 -0
  27. package/app/Actions/Dashboard/Models/model-write.ts +240 -51
  28. package/app/Actions/Dashboard/Users/UserInviteAction.ts +50 -0
  29. package/app/Actions/Dashboard/Users/user-invitation.ts +110 -0
  30. package/app/Models/Activity.ts +4 -0
  31. package/app/Models/AnalyticsEvent.ts +4 -0
  32. package/app/Models/Automation.ts +4 -0
  33. package/app/Models/AutomationRun.ts +4 -0
  34. package/app/Models/Board.ts +4 -1
  35. package/app/Models/BoardColumn.ts +4 -1
  36. package/app/Models/Campaign.ts +4 -0
  37. package/app/Models/CampaignSend.ts +4 -0
  38. package/app/Models/CampaignVariant.ts +4 -0
  39. package/app/Models/Card.ts +4 -1
  40. package/app/Models/CardAttachment.ts +4 -0
  41. package/app/Models/CommunicationSuppression.ts +4 -0
  42. package/app/Models/ConsentEvent.ts +4 -0
  43. package/app/Models/Deployment.ts +1 -0
  44. package/app/Models/EmailList.ts +4 -0
  45. package/app/Models/EmailListSubscriber.ts +4 -0
  46. package/app/Models/Error.ts +4 -0
  47. package/app/Models/FailedJob.ts +4 -0
  48. package/app/Models/FeedbackToken.ts +4 -0
  49. package/app/Models/GdprRequest.ts +4 -0
  50. package/app/Models/Job.ts +4 -0
  51. package/app/Models/Log.ts +4 -0
  52. package/app/Models/MagicLinkToken.ts +4 -0
  53. package/app/Models/MailPreference.ts +4 -0
  54. package/app/Models/Notification.ts +4 -0
  55. package/app/Models/NotificationDelivery.ts +4 -0
  56. package/app/Models/PersonalAccessToken.ts +4 -0
  57. package/app/Models/QueryLog.ts +4 -0
  58. package/app/Models/Referral.ts +4 -0
  59. package/app/Models/Release.ts +1 -0
  60. package/app/Models/Request.ts +4 -0
  61. package/app/Models/SenderDomain.ts +4 -0
  62. package/app/Models/Site.ts +1 -0
  63. package/app/Models/SiteDomain.ts +4 -0
  64. package/app/Models/SocialPost.ts +4 -0
  65. package/app/Models/StorageItemTask.ts +4 -1
  66. package/app/Models/Subscriber.ts +4 -0
  67. package/app/Models/Subscription.ts +4 -0
  68. package/app/Models/Team.ts +1 -0
  69. package/app/Models/TeamInvitation.ts +1 -0
  70. package/app/Models/TeamMember.ts +1 -0
  71. package/app/Models/UsageEvent.ts +4 -0
  72. package/app/Models/User.ts +15 -3
  73. package/functions/dashboard-model-record.test.ts +276 -18
  74. package/functions/dashboard-model-record.ts +412 -55
  75. package/functions/data.ts +2 -0
  76. package/ide/vscode/package.json +1 -1
  77. package/package.json +5 -5
  78. package/resources/components/Dashboard/Analytics/AnalyticsHub.stx +1 -1
  79. package/resources/components/Dashboard/Analytics/CampaignAnalytics.stx +1 -1
  80. package/resources/components/Dashboard/Analytics/EventAnalytics.stx +1 -1
  81. package/resources/components/Dashboard/Analytics/SalesAnalytics.stx +1 -1
  82. package/resources/components/Dashboard/Analytics/WebAnalyticsBreakdown.stx +1 -1
  83. package/resources/components/Dashboard/App/RequestsOverview.stx +1 -1
  84. package/resources/components/Dashboard/App/SourceInventory.stx +1 -1
  85. package/resources/components/Dashboard/Auth/AccessTokens.stx +1 -1
  86. package/resources/components/Dashboard/Buddy/BuddyAssistant.stx +1 -1
  87. package/resources/components/Dashboard/Ci/CiDashboard.stx +1 -1
  88. package/resources/components/Dashboard/Commerce/Delivery/DeliveryPagination.stx +1 -1
  89. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +1 -1
  90. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +1 -1
  91. package/resources/components/Dashboard/Content/BlogDashboard.stx +1 -1
  92. package/resources/components/Dashboard/DashboardLayout.stx +1 -1
  93. package/resources/components/Dashboard/Data/DataRecords.stx +43 -22
  94. package/resources/components/Dashboard/Data/UserInvite.stx +107 -0
  95. package/resources/components/Dashboard/Email/CapturedMailDashboard.stx +1 -1
  96. package/resources/components/Dashboard/Email/EmailActivityDashboard.stx +1 -1
  97. package/resources/components/Dashboard/Email/InboxDashboard.stx +1 -1
  98. package/resources/components/Dashboard/Email/InboxMessageDetail.stx +2 -2
  99. package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +1 -1
  100. package/resources/components/Dashboard/Home/DashboardHome.stx +6 -1
  101. package/resources/components/Dashboard/Infrastructure/CloudDashboard.stx +1 -1
  102. package/resources/components/Dashboard/Infrastructure/DnsDashboard.stx +1 -1
  103. package/resources/components/Dashboard/Infrastructure/HealthDashboard.stx +1 -1
  104. package/resources/components/Dashboard/Infrastructure/InsightsDashboard.stx +1 -1
  105. package/resources/components/Dashboard/Infrastructure/LogsDashboard.stx +1 -1
  106. package/resources/components/Dashboard/Infrastructure/MailboxesDashboard.stx +1 -1
  107. package/resources/components/Dashboard/Infrastructure/ServerDetailsDashboard.stx +1 -1
  108. package/resources/components/Dashboard/Infrastructure/ServerlessDashboard.stx +1 -1
  109. package/resources/components/Dashboard/Infrastructure/ServersDashboard.stx +1 -1
  110. package/resources/components/Dashboard/Jobs/JobDetail.stx +1 -1
  111. package/resources/components/Dashboard/Jobs/JobTable.stx +2 -2
  112. package/resources/components/Dashboard/Kanban/KanbanBoardDashboard.stx +1 -1
  113. package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +1 -1
  114. package/resources/components/Dashboard/Management/PermissionsDashboard.stx +1 -1
  115. package/resources/components/Dashboard/Marketing/AbandonedCartsDashboard.stx +1 -1
  116. package/resources/components/Dashboard/Marketing/CampaignsDashboard.stx +1 -1
  117. package/resources/components/Dashboard/Marketing/MarketingListsDashboard.stx +1 -1
  118. package/resources/components/Dashboard/Marketing/SocialPostsDashboard.stx +1 -1
  119. package/resources/components/Dashboard/Models/ModelFieldInputs.stx +125 -0
  120. package/resources/components/Dashboard/Models/ModelRecordCreate.stx +24 -66
  121. package/resources/components/Dashboard/Models/ModelRecordDetail.stx +36 -8
  122. package/resources/components/Dashboard/Models/ModelRecordEdit.stx +36 -32
  123. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +72 -28
  124. package/resources/components/Dashboard/Models/ModelRelatedPanels.stx +99 -0
  125. package/resources/components/Dashboard/Models/ModelRelationPicker.stx +247 -0
  126. package/resources/components/Dashboard/Models/ModelsOverview.stx +1 -1
  127. package/resources/components/Dashboard/Notifications/NotificationDeliveries.stx +1 -1
  128. package/resources/components/Dashboard/Notifications/NotificationDeliveryHistory.stx +1 -1
  129. package/resources/components/Dashboard/Notifications/NotificationDeliveryOverview.stx +1 -1
  130. package/resources/components/Dashboard/Queries/QueryDashboard.stx +1 -1
  131. package/resources/components/Dashboard/Queries/QueryDetail.stx +1 -1
  132. package/resources/components/Dashboard/Queue/QueueDashboard.stx +1 -1
  133. package/resources/components/Dashboard/Realtime/RealtimeDashboard.stx +1 -1
  134. package/resources/components/Dashboard/Releases/ReleaseDashboard.stx +1 -1
  135. package/resources/components/Dashboard/Search/SearchEngineDashboard.stx +1 -1
  136. package/resources/components/Dashboard/Settings/MailSettingsDashboard.stx +1 -1
  137. package/resources/components/Dashboard/Settings/SettingsDashboard.stx +1 -1
  138. package/resources/components/Dashboard/Teams/TeamPeopleDashboard.stx +1 -1
  139. package/resources/components/Dashboard/UI/Drawer.stx +1 -1
  140. package/resources/components/Dashboard/UI/Input.stx +3 -2
  141. package/resources/components/Dashboard/UI/Modal.stx +1 -1
  142. package/resources/components/Dashboard/UI/Select.stx +8 -4
  143. package/resources/components/Dashboard/UI/Textarea.stx +18 -12
  144. package/resources/emails/password-reset.stx +3 -1
  145. package/routes/dashboard-api.ts +9 -0
  146. package/scaffold/config/analytics.ts +5 -3
  147. package/scaffold/resources/components/NextStep.stx +13 -0
  148. package/scaffold/resources/partials/head.stx +31 -0
  149. package/scaffold/resources/views/index.stx +23 -47
  150. package/scaffold/resources/views/layouts/default.stx +23 -0
  151. package/views/dashboard/data/users/invite.stx +8 -0
  152. package/views/dashboard/layouts/default.stx +21 -2
@@ -12,11 +12,16 @@
12
12
  * the eye and nothing else.
13
13
  */
14
14
  import { DashboardApiError, dashboardApi } from './dashboard-api'
15
+ import { parseDashboardDate } from './dashboard-dates'
15
16
 
16
17
  export interface ModelWriteCapabilities {
17
18
  create: boolean
18
19
  update: boolean
19
20
  destroy: boolean
21
+ /** New records are added by invitation (users): see {@link inviteUser}. */
22
+ invite: boolean
23
+ /** A delete other records block anonymizes the record instead (users). */
24
+ anonymize: boolean
20
25
  }
21
26
 
22
27
  export interface ModelColumn {
@@ -33,46 +38,82 @@ export interface ModelRecord {
33
38
  columns: ModelColumn[]
34
39
  /** The columns an edit may change: fillable attributes and declared keys. */
35
40
  updateColumns: string[]
41
+ /** The fields an edit may change, with how each is asked for. */
42
+ fields: ModelCreateField[]
43
+ /** The columns that hold another model's id, and whose. */
44
+ relations: Record<string, ModelRelationTarget>
45
+ /** What the records this one points at are called, by column: `{ team_id: 'PrimeSoft Ltd' }`. */
46
+ relationNames: ModelRelationNames
36
47
  writeCapabilities: ModelWriteCapabilities
37
- }
38
-
39
- export interface ModelRecordField {
40
- name: string
41
- label: string
42
- value: string
43
- readonly: boolean
48
+ /** Erased under the app's data-subject rules: its personal details are placeholders. */
49
+ anonymized: boolean
44
50
  }
45
51
 
46
52
  interface ModelShowResponse {
47
53
  modelName?: string
54
+ modelLabel?: string
48
55
  tableName?: string
49
56
  createFields?: ModelCreateField[]
50
57
  rows?: Array<Record<string, unknown>>
51
58
  columnMeta?: ModelColumn[]
52
59
  updateColumns?: string[]
60
+ updateFields?: ModelCreateField[]
61
+ relations?: Record<string, ModelRelationTarget>
62
+ listColumns?: string[]
63
+ relationNames?: Record<string, Record<string, string>>
53
64
  writeCapabilities?: ModelWriteCapabilities
65
+ anonymizedIds?: Array<number | string>
54
66
  error?: string | null
55
67
  }
56
68
 
57
69
  /** A field of the create form, from the model's fillable attributes. */
70
+ /** How a field is asked for: see `modelFieldType` on the server. */
71
+ export type ModelFieldType = 'boolean' | 'date' | 'datetime' | 'email' | 'enum' | 'json' | 'longtext' | 'number' | 'relation' | 'text'
72
+
73
+ /** The model a field or column points at: `team_id` is a Team. */
74
+ export interface ModelRelationTarget {
75
+ model: string
76
+ /** Its place in dashboard URLs: `team`, `board-column`. */
77
+ slug: string
78
+ /** Its name in words: "Board Column". */
79
+ label: string
80
+ }
81
+
82
+ /** One record of a related model, as a picker lists it. */
83
+ export interface ModelOption {
84
+ id: number | string
85
+ /** What the record is called: its name, title or address. */
86
+ label: string
87
+ /** A second line that tells two of the same name apart: a user's email. */
88
+ hint: string
89
+ }
90
+
58
91
  export interface ModelCreateField {
59
92
  name: string
60
93
  label: string
61
- type: 'boolean' | 'date' | 'datetime' | 'email' | 'enum' | 'number' | 'text'
94
+ type: ModelFieldType
62
95
  required: boolean
63
96
  defaultValue: unknown
64
97
  options: string[]
98
+ /** For a `relation`: the model whose records the picker lists. */
99
+ relation?: ModelRelationTarget
65
100
  }
66
101
 
102
+ /** What a form holds for each field: a checkbox's state, or an input's text. */
103
+ export type ModelFormValues = Record<string, string | boolean>
104
+
67
105
  export interface ModelCreateForm {
68
106
  modelName: string
69
107
  tableName?: string
70
108
  fields: ModelCreateField[]
71
109
  /** Whether the model's API has a store route at all. */
72
110
  canCreate: boolean
111
+ /** New records are added by invitation instead (users). */
112
+ canInvite: boolean
73
113
  }
74
114
 
75
- const NO_WRITES: ModelWriteCapabilities = { create: false, update: false, destroy: false }
115
+ /** What a model offers before its capabilities are known, or when it has none. */
116
+ export const NO_WRITES: ModelWriteCapabilities = { create: false, update: false, destroy: false, invite: false, anonymize: false }
76
117
 
77
118
  function modelPath(slug: string): string {
78
119
  return `/api/dashboard/models/${encodeURIComponent(slug)}`
@@ -81,7 +122,7 @@ function modelPath(slug: string): string {
81
122
  /** What the model lets the dashboard do, without loading any rows of note. */
82
123
  export async function fetchModelCapabilities(slug: string): Promise<ModelWriteCapabilities> {
83
124
  const data = await dashboardApi<ModelShowResponse>(`${modelPath(slug)}?perPage=1`)
84
- return data.writeCapabilities ?? NO_WRITES
125
+ return { ...NO_WRITES, ...data.writeCapabilities }
85
126
  }
86
127
 
87
128
  /** What the create page needs: the model's name and the fields a new record takes. */
@@ -90,10 +131,12 @@ export async function fetchModelCreateForm(slug: string): Promise<ModelCreateFor
90
131
  if (data.error)
91
132
  throw new Error(data.error)
92
133
  return {
93
- modelName: data.modelName || 'Record',
134
+ // What the pages call the model: "Social Post", not the class name.
135
+ modelName: data.modelLabel || data.modelName || 'Record',
94
136
  tableName: data.tableName,
95
137
  fields: data.createFields ?? [],
96
138
  canCreate: Boolean(data.writeCapabilities?.create),
139
+ canInvite: Boolean(data.writeCapabilities?.invite),
97
140
  }
98
141
  }
99
142
 
@@ -107,12 +150,19 @@ export async function fetchModelRecord(slug: string, id: string | number): Promi
107
150
  if (!row)
108
151
  throw new Error(`${data.modelName || 'Record'} ${id} was not found.`)
109
152
  return {
110
- modelName: data.modelName || 'Record',
153
+ // What the pages call the model: "Social Post", not the class name.
154
+ modelName: data.modelLabel || data.modelName || 'Record',
111
155
  tableName: data.tableName,
112
156
  row,
113
157
  columns: data.columnMeta ?? [],
114
158
  updateColumns: data.updateColumns ?? [],
115
- writeCapabilities: data.writeCapabilities ?? NO_WRITES,
159
+ fields: data.updateFields ?? [],
160
+ relations: data.relations ?? {},
161
+ relationNames: Object.fromEntries(Object.entries(data.relationNames ?? {})
162
+ .map(([column, names]) => [column, names[String(row[column])]] as const)
163
+ .filter((entry): entry is readonly [string, string] => typeof entry[1] === 'string')),
164
+ writeCapabilities: { ...NO_WRITES, ...data.writeCapabilities },
165
+ anonymized: (data.anonymizedIds ?? []).some(candidate => String(candidate) === String(id)),
116
166
  }
117
167
  }
118
168
 
@@ -120,19 +170,6 @@ function text(value: unknown): string {
120
170
  return value === null || value === undefined ? '' : String(value)
121
171
  }
122
172
 
123
- /**
124
- * The edit dialog's fields for a record: the writable columns can change, and
125
- * the rest stay visible, read-only, as context.
126
- */
127
- export function modelRecordFields(record: ModelRecord): ModelRecordField[] {
128
- return record.columns.map(column => ({
129
- name: column.name,
130
- label: column.label,
131
- value: text(record.row[column.name]),
132
- readonly: !record.updateColumns.includes(column.name),
133
- }))
134
- }
135
-
136
173
  export interface ModelRecordDetail {
137
174
  name: string
138
175
  label: string
@@ -142,9 +179,12 @@ export interface ModelRecordDetail {
142
179
  empty: boolean
143
180
  /**
144
181
  * How the value is drawn: plain text, an outlined badge for a status-like
145
- * word, a check or cross for a boolean, a preformatted block for JSON.
182
+ * word, a check or cross for a boolean, a preformatted block for JSON, a
183
+ * link to the record another model's id points at.
146
184
  */
147
- kind: 'text' | 'badge' | 'boolean' | 'json'
185
+ kind: 'text' | 'badge' | 'boolean' | 'json' | 'link'
186
+ /** For a link: the page of the record this one points at. */
187
+ href?: string
148
188
  /** A boolean's answer, for the icon. */
149
189
  yes: boolean
150
190
  /** Takes the card's full width: long text and JSON. */
@@ -190,10 +230,25 @@ function titleCase(words: string): string {
190
230
  return words.replace(/[_-]+/g, ' ').replace(/\b[a-z]/g, letter => letter.toUpperCase())
191
231
  }
192
232
 
193
- function detail(record: ModelRecord, column: ModelColumn): ModelRecordDetail {
233
+ /** The names of the records a record points at, by column: `{ team_id: 'PrimeSoft Ltd' }`. */
234
+ export type ModelRelationNames = Record<string, string>
235
+
236
+ function detail(record: ModelRecord, column: ModelColumn, names: ModelRelationNames = {}): ModelRecordDetail {
194
237
  const stored = record.row[column.name]
195
- const label = detailLabel(column)
238
+ const relation = record.relations?.[column.name]
239
+ // "Team", not "Team ID": the page says which team, and the id is its link.
240
+ const label = relation ? relation.label : detailLabel(column)
196
241
  const base = { name: column.name, label, yes: false, wide: false }
242
+ if (relation && stored !== null && stored !== undefined && stored !== '') {
243
+ return {
244
+ ...base,
245
+ // Until the name arrives, and for a record that is gone, the id says which.
246
+ value: names[column.name] || `${relation.label} #${String(stored)}`,
247
+ empty: false,
248
+ kind: 'link',
249
+ href: modelRecordHref(relation.slug, stored as number | string),
250
+ }
251
+ }
197
252
  if (column.type === 'boolean') {
198
253
  const yes = stored === true || stored === 1 || stored === '1'
199
254
  return { ...base, value: yes ? 'Yes' : 'No', empty: false, kind: 'boolean', yes }
@@ -224,10 +279,10 @@ function detail(record: ModelRecord, column: ModelColumn): ModelRecordDetail {
224
279
  * ids that tie it to other records, and when things happened to it. A card
225
280
  * with nothing in it is left out.
226
281
  */
227
- export function modelRecordSections(record: ModelRecord): ModelRecordSection[] {
282
+ export function modelRecordSections(record: ModelRecord, names: ModelRelationNames = record.relationNames ?? {}): ModelRecordSection[] {
228
283
  const groups: Record<ModelRecordSection['id'], ModelRecordDetail[]> = { information: [], details: [], identifiers: [], timestamps: [] }
229
284
  for (const column of record.columns) {
230
- const entry = detail(record, column)
285
+ const entry = detail(record, column, names)
231
286
  if (isIdentifier(column.name))
232
287
  groups.identifiers.push(entry)
233
288
  else if (isDate(column))
@@ -251,6 +306,11 @@ export function modelRecordListLabel(record: { tableName?: string } | null, back
251
306
  const last = backHref.split('/').filter(Boolean).pop() || ''
252
307
  if (backHref.startsWith('/data/') && last)
253
308
  return titleCase(last)
309
+ // Opened from a record's page (a panel's "Add"): the way back is that
310
+ // record, and calling it by this model's list would name the wrong place.
311
+ const opener = /^\/models\/([\w-]+)\/(\d+)$/.exec(backHref)
312
+ if (opener)
313
+ return `${titleCase(opener[1]!)} ${opener[2]}`
254
314
  return record?.tableName ? titleCase(record.tableName) : 'Records'
255
315
  }
256
316
 
@@ -298,42 +358,153 @@ export function modelRecordBackHref(slug: string, from: string | null | undefine
298
358
  return from && /^\/(?!\/)[\w\-/]*$/.test(from) ? from : `/models/${encodeURIComponent(slug)}`
299
359
  }
300
360
 
361
+ /** The column a field is stored in: `firstName` is `first_name`. */
362
+ export function modelFieldColumn(name: string): string {
363
+ return name.replace(/([a-z\d])([A-Z])/g, '$1_$2').replace(/[\s-]+/g, '_').toLowerCase()
364
+ }
365
+
366
+ function pad(value: number): string {
367
+ return String(value).padStart(2, '0')
368
+ }
369
+
370
+ /** A moment as a `datetime-local` input takes it: the visitor's own clock, to the minute. */
371
+ function localMoment(stored: unknown): string {
372
+ // A number is a unix time, in seconds unless it is too large to be.
373
+ const date = typeof stored === 'number'
374
+ ? new Date(stored < 1e12 ? stored * 1000 : stored)
375
+ : parseDashboardDate(stored)
376
+ if (Number.isNaN(date.getTime()))
377
+ return ''
378
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`
379
+ }
380
+
301
381
  /**
302
- * The fields an edit actually changed, as the model API takes them: a value
303
- * the editor merely displayed is never sent, and an emptied field is null.
382
+ * A stored value as its input holds it.
383
+ *
384
+ * Each kind of input wants its own spelling: a checkbox a boolean, a date
385
+ * input `2026-10-01`, a date-and-time input the visitor's local time, JSON
386
+ * indented so it can be read. Handing them the stored text instead is how an
387
+ * edit form came to show `true`, `2026-10-01T00:00:00.000Z` and one long line
388
+ * of braces in plain text boxes.
304
389
  */
305
- export function changedModelFields(row: Record<string, unknown>, values: Record<string, string>): Record<string, unknown> {
306
- const fields: Record<string, unknown> = {}
307
- for (const [column, value] of Object.entries(values)) {
308
- if (value !== text(row[column]))
309
- fields[column] = value === '' ? null : value
390
+ export function modelFieldInputValue(field: ModelCreateField, stored: unknown): string | boolean {
391
+ if (field.type === 'boolean')
392
+ return stored === true || stored === 1 || stored === '1' || stored === 'true'
393
+ if (stored === null || stored === undefined || stored === '')
394
+ return ''
395
+ if (field.type === 'date') {
396
+ // A calendar day, however the driver returned it. Never through `Date`:
397
+ // midnight UTC is the day before for everyone west of it.
398
+ const day = /^\d{4}-\d{2}-\d{2}/.exec(stored instanceof Date ? stored.toISOString() : String(stored))
399
+ return day ? day[0] : ''
400
+ }
401
+ if (field.type === 'datetime')
402
+ return localMoment(stored)
403
+ if (field.type === 'json') {
404
+ try {
405
+ return JSON.stringify(typeof stored === 'string' ? JSON.parse(stored) : stored, null, 2)
406
+ }
407
+ catch {
408
+ return String(stored)
409
+ }
410
+ }
411
+ return typeof stored === 'object' ? JSON.stringify(stored) : String(stored)
412
+ }
413
+
414
+ /** What an input holds, as the model API takes it. An emptied field is null. */
415
+ export function modelFieldPayloadValue(field: ModelCreateField, value: string | boolean | undefined): unknown {
416
+ if (field.type === 'boolean')
417
+ return value === true
418
+ if (value === undefined || value === '' || value === false || value === true)
419
+ return null
420
+ if (field.type === 'relation') {
421
+ // The picker holds the id as text; the API takes the number.
422
+ const id = Number(value)
423
+ return Number.isSafeInteger(id) && id > 0 ? id : value
424
+ }
425
+ if (field.type === 'datetime') {
426
+ // With its offset, so the moment is the one the visitor picked whatever
427
+ // zone the server runs in.
428
+ const moment = new Date(value)
429
+ return Number.isNaN(moment.getTime()) ? value : moment.toISOString()
310
430
  }
311
- return fields
431
+ return value
312
432
  }
313
433
 
314
- export async function updateModelRecord(slug: string, id: string | number, fields: Record<string, unknown>): Promise<void> {
315
- const result = await dashboardApi<{ ok: boolean, error?: string }>(`${modelPath(slug)}/${encodeURIComponent(String(id))}`, { method: 'PATCH', body: { fields } })
316
- if (!result?.ok)
317
- throw new Error(result?.error || 'The update was rejected.')
434
+ /**
435
+ * What a form starts with. An edit starts from the record's stored values, a
436
+ * create from each field's default.
437
+ */
438
+ export function modelFormValues(fields: ModelCreateField[], row?: Record<string, unknown>): ModelFormValues {
439
+ return Object.fromEntries(fields.map(field => [
440
+ field.name,
441
+ modelFieldInputValue(field, row ? row[modelFieldColumn(field.name)] ?? row[field.name] : field.defaultValue),
442
+ ]))
318
443
  }
319
444
 
320
- export type ModelCreateResult
321
- = | { ok: true, id: string | number | null }
322
- | { ok: false, error: string, errors: Record<string, string[]> }
445
+ /**
446
+ * What a form sends. Given what it started with, only the fields that were
447
+ * changed: a value the editor merely displayed is never written back.
448
+ */
449
+ export function modelFormPayload(fields: ModelCreateField[], values: ModelFormValues, initial?: ModelFormValues): Record<string, unknown> {
450
+ const payload: Record<string, unknown> = {}
451
+ for (const field of fields) {
452
+ if (initial && values[field.name] === initial[field.name])
453
+ continue
454
+ payload[field.name] = modelFieldPayloadValue(field, values[field.name])
455
+ }
456
+ return payload
457
+ }
458
+
459
+ export type ModelWriteFailure = { ok: false, error: string, errors: Record<string, string[]> }
460
+
461
+ export type ModelUpdateResult = { ok: true } | ModelWriteFailure
462
+
463
+ export type ModelCreateResult = { ok: true, id: string | number | null } | ModelWriteFailure
323
464
 
324
465
  /**
325
- * Why a create was refused, in one shape: the message for the top of the form
326
- * and the messages under each field. The API answers a refusal two ways, as a
327
- * body with `ok: false` or as an error status carrying `fields`.
466
+ * Why a create or an edit was refused, in one shape: the message for the top
467
+ * of the form and the messages under each field. The API answers a refusal
468
+ * two ways, as a body with `ok: false` or as an error status carrying
469
+ * `fields`.
328
470
  */
329
- export function modelCreateFailure(reason: unknown): { ok: false, error: string, errors: Record<string, string[]> } {
471
+ export function modelWriteFailure(reason: unknown): ModelWriteFailure {
330
472
  if (reason instanceof DashboardApiError) {
331
473
  const errors = Object.fromEntries(Object.entries(reason.fields ?? {}).map(([field, message]) => [field, [message]]))
332
- return { ok: false, error: reason.message, errors }
474
+ // With field messages to show, the top of the form points at them. The
475
+ // server's own summary for these is "Validation failed", which names
476
+ // nothing the visitor can look for.
477
+ const marked = Object.keys(errors).length
478
+ const summary = marked === 1 ? 'Check the field marked below.' : `Check the ${marked} fields marked below.`
479
+ return { ok: false, error: marked > 0 ? summary : reason.message, errors }
333
480
  }
334
481
  return { ok: false, error: reason instanceof Error ? reason.message : String(reason), errors: {} }
335
482
  }
336
483
 
484
+ /**
485
+ * The message for one input, from the errors a refused write came back with.
486
+ *
487
+ * The API names fields as the model does (`firstName`); an edit form's inputs
488
+ * are the row's columns (`first_name`). Either spelling finds its message.
489
+ */
490
+ export function modelFieldError(errors: Record<string, string[]>, field: string): string {
491
+ const column = (name: string) => name.replace(/([a-z\d])([A-Z])/g, '$1_$2').toLowerCase()
492
+ const key = Object.keys(errors).find(name => name === field || column(name) === column(field))
493
+ return key ? errors[key]?.[0] || '' : ''
494
+ }
495
+
496
+ export async function updateModelRecord(slug: string, id: string | number, fields: Record<string, unknown>): Promise<ModelUpdateResult> {
497
+ try {
498
+ const result = await dashboardApi<{ ok: boolean, error?: string, errors?: Record<string, string[]> }>(`${modelPath(slug)}/${encodeURIComponent(String(id))}`, { method: 'PATCH', body: { fields } })
499
+ if (!result?.ok)
500
+ return { ok: false, error: result?.error || 'The update was rejected.', errors: result?.errors ?? {} }
501
+ return { ok: true }
502
+ }
503
+ catch (reason) {
504
+ return modelWriteFailure(reason)
505
+ }
506
+ }
507
+
337
508
  export async function createModelRecord(slug: string, fields: Record<string, unknown>): Promise<ModelCreateResult> {
338
509
  try {
339
510
  const result = await dashboardApi<{ ok: boolean, id?: number | string | null, error?: string, errors?: Record<string, string[]> }>(modelPath(slug), { method: 'POST', body: { fields } })
@@ -342,12 +513,198 @@ export async function createModelRecord(slug: string, fields: Record<string, unk
342
513
  return { ok: true, id: result.id ?? null }
343
514
  }
344
515
  catch (reason) {
345
- return modelCreateFailure(reason)
516
+ return modelWriteFailure(reason)
346
517
  }
347
518
  }
348
519
 
349
- export async function deleteModelRecord(slug: string, id: string | number): Promise<void> {
350
- const result = await dashboardApi<{ ok: boolean, error?: string }>(`${modelPath(slug)}/${encodeURIComponent(String(id))}`, { method: 'DELETE' })
520
+ /**
521
+ * What the confirmation says before a record is deleted.
522
+ *
523
+ * True whichever way the model deletes: a soft-deleted row stays in the
524
+ * database, and the dashboard still has no way to bring it back. Where a
525
+ * blocked delete anonymizes instead (users), it says that too, before the
526
+ * button is pressed and not only afterwards.
527
+ */
528
+ export function modelDeleteWarning(name: string, anonymizes = false): string {
529
+ const warning = `${name} will be deleted. This cannot be undone from the dashboard.`
530
+ return anonymizes
531
+ ? `${warning} If other records still refer to this account, it is anonymized instead: the name and email are removed, sign-in is revoked and those records are kept.`
532
+ : warning
533
+ }
534
+
535
+ /** What became of the record: gone, or kept with its personal details removed. */
536
+ export type ModelDeleteOutcome = 'deleted' | 'anonymized'
537
+
538
+ export async function deleteModelRecord(slug: string, id: string | number): Promise<ModelDeleteOutcome> {
539
+ const result = await dashboardApi<{ ok: boolean, anonymized?: boolean, error?: string }>(`${modelPath(slug)}/${encodeURIComponent(String(id))}`, { method: 'DELETE' })
351
540
  if (!result?.ok)
352
541
  throw new Error(result?.error || 'The delete was rejected.')
542
+ return result.anonymized ? 'anonymized' : 'deleted'
543
+ }
544
+
545
+ /**
546
+ * The toast after a delete. An anonymized account is still in the list, so
547
+ * "deleted" would be contradicted by the page the visitor is looking at.
548
+ */
549
+ export function modelDeleteNotice(name: string, outcome: ModelDeleteOutcome): { title: string, detail?: string } {
550
+ if (outcome === 'anonymized')
551
+ return { title: `${name} anonymized`, detail: 'Other records still refer to this account, so it was kept with its name and email removed. It can no longer sign in.' }
552
+ return { title: `${name} deleted` }
553
+ }
554
+
555
+ /** Where the invite page lives, remembering the list to return to. */
556
+ export function userInviteHref(from?: string): string {
557
+ return from ? `/data/users/invite?from=${encodeURIComponent(from)}` : '/data/users/invite'
558
+ }
559
+
560
+ export type UserInviteResult = { ok: true, id: string | number, email: string, expiresInDays: number } | ModelWriteFailure
561
+
562
+ /**
563
+ * Add a user by invitation: the account is created and its holder is mailed
564
+ * a link to choose their password. A refusal comes back in the same shape as
565
+ * a refused create, so the form shows it the same way.
566
+ */
567
+ export async function inviteUser(name: string, email: string): Promise<UserInviteResult> {
568
+ try {
569
+ const result = await dashboardApi<{ ok: boolean, id?: number | string, email?: string, expiresInDays?: number, error?: string, errors?: Record<string, string[]> }>('/api/dashboard/users/invitations', { method: 'POST', body: { name, email } })
570
+ if (!result?.ok || result.id === undefined)
571
+ return { ok: false, error: result?.error || 'The invitation was rejected.', errors: result?.errors ?? {} }
572
+ return { ok: true, id: result.id, email: result.email || email, expiresInDays: result.expiresInDays ?? 7 }
573
+ }
574
+ catch (reason) {
575
+ return modelWriteFailure(reason)
576
+ }
577
+ }
578
+
579
+ /**
580
+ * A model's records by name, for choosing one in a form. `q` searches by
581
+ * what a record is called; `ids` asks what exactly those are called, which is
582
+ * how a form and a record's page name the record a field already points at.
583
+ */
584
+ export async function fetchModelOptions(slug: string, search: { q?: string, ids?: Array<number | string> } = {}): Promise<ModelOption[]> {
585
+ const params = new URLSearchParams()
586
+ if (search.ids && search.ids.length > 0)
587
+ params.set('ids', search.ids.map(String).join(','))
588
+ else if (search.q)
589
+ params.set('q', search.q)
590
+ const query = params.toString()
591
+ const data = await dashboardApi<{ options?: ModelOption[] }>(`${modelPath(slug)}/options${query ? `?${query}` : ''}`)
592
+ return data.options ?? []
593
+ }
594
+
595
+ /**
596
+ * The columns a model's list draws, in order.
597
+ *
598
+ * The ones the model named in `dashboard.columns`, or every column when it
599
+ * named none. A column the list is being filtered on is drawn as well, even
600
+ * when the model left it out: a list opened from a record's panel arrives
601
+ * narrowed by that record, and what narrowed it has to be in view to clear.
602
+ */
603
+ export function modelListColumnNames(all: string[], chosen: string[] | undefined, filters: Record<string, string> = {}): string[] {
604
+ const list = chosen && chosen.length > 0 ? chosen.filter(column => all.includes(column)) : all
605
+ const filtered = Object.entries(filters).filter(([column, value]) => value !== '' && all.includes(column) && !list.includes(column)).map(([column]) => column)
606
+ return [...list, ...filtered]
607
+ }
608
+
609
+ /**
610
+ * A cell that holds another model's id, as the list shows it: that record's
611
+ * name and the page it links to. Null for any other cell, and for an empty
612
+ * one. Named by its id when the name is not known, which is still true.
613
+ */
614
+ export function modelRelationCell(
615
+ column: string,
616
+ value: unknown,
617
+ relations: Record<string, ModelRelationTarget>,
618
+ names: Record<string, Record<string, string>>,
619
+ ): { text: string, href: string } | null {
620
+ const relation = relations[column]
621
+ if (!relation || value === null || value === undefined || value === '')
622
+ return null
623
+ return {
624
+ text: names[column]?.[String(value)] || `${relation.label} #${String(value)}`,
625
+ href: modelRecordHref(relation.slug, value as number | string),
626
+ }
627
+ }
628
+
629
+ /** A column of a related-records panel. */
630
+ export interface ModelRelatedColumn {
631
+ key: string
632
+ label: string
633
+ type: 'text' | 'badge' | 'datetime'
634
+ }
635
+
636
+ /**
637
+ * The records of one model that point at a record: a team's members. From the
638
+ * model's own `hasMany` or `hasOne`.
639
+ */
640
+ export interface ModelRelatedPanel {
641
+ kind: 'many' | 'one'
642
+ model: string
643
+ slug: string
644
+ /** The panel's heading: "Team Members", or "Subscriber" for a `hasOne`. */
645
+ title: string
646
+ /** One of them, in words: "Team Member". */
647
+ label: string
648
+ /** The column on the related model that holds this record's id. */
649
+ foreignKey: string
650
+ /** That column as the related model's form field. */
651
+ field: string
652
+ total: number
653
+ columns: ModelRelatedColumn[]
654
+ /** The newest few, each with its `id` and a value per column. */
655
+ rows: Array<Record<string, unknown>>
656
+ canCreate: boolean
657
+ }
658
+
659
+ /** The panels of a record's page: who points at it. None when it cannot be asked. */
660
+ export async function fetchModelRelated(slug: string, id: string | number): Promise<ModelRelatedPanel[]> {
661
+ const data = await dashboardApi<{ panels?: ModelRelatedPanel[] }>(`${modelPath(slug)}/${encodeURIComponent(String(id))}/related`)
662
+ return data.panels ?? []
663
+ }
664
+
665
+ /** The related model's own list, narrowed to the records that point at this one. */
666
+ export function modelRelatedListHref(panel: ModelRelatedPanel, parentId: string | number): string {
667
+ return `/models/${encodeURIComponent(panel.slug)}?filters=${encodeURIComponent(JSON.stringify({ [panel.foreignKey]: String(parentId) }))}`
668
+ }
669
+
670
+ /** The related model's create page, with this record already chosen, coming back here. */
671
+ export function modelRelatedCreateHref(panel: ModelRelatedPanel, parentId: string | number, from: string): string {
672
+ return `${modelRecordCreateHref(panel.slug, from)}&${encodeURIComponent(panel.field)}=${encodeURIComponent(String(parentId))}`
673
+ }
674
+
675
+ /**
676
+ * The filters a list starts with, from its address: `?filters={"team_id":"3"}`.
677
+ * Anything that is not a flat object of text is ignored, never trusted.
678
+ */
679
+ export function modelListFilters(raw: string | null): Record<string, string> {
680
+ if (!raw)
681
+ return {}
682
+ try {
683
+ const parsed = JSON.parse(raw) as unknown
684
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
685
+ return {}
686
+ return Object.fromEntries(Object.entries(parsed as Record<string, unknown>)
687
+ .filter(([column, value]) => /^[a-z_][a-z0-9_]*$/i.test(column) && (typeof value === 'string' || typeof value === 'number') && String(value) !== '')
688
+ .map(([column, value]) => [column, String(value)]))
689
+ }
690
+ catch {
691
+ return {}
692
+ }
693
+ }
694
+
695
+ /**
696
+ * What a create form is given to start with, from its address: the record it
697
+ * was opened from (`?teamId=3`). Only fields the form has, and never a
698
+ * checkbox, so an address cannot set what the form does not show.
699
+ */
700
+ export function modelFormPrefill(fields: ModelCreateField[], query: (name: string) => string | null): ModelFormValues {
701
+ const values: ModelFormValues = {}
702
+ for (const field of fields) {
703
+ if (field.type === 'boolean')
704
+ continue
705
+ const given = query(field.name)
706
+ if (given !== null && given !== '')
707
+ values[field.name] = given
708
+ }
709
+ return values
353
710
  }
package/functions/data.ts CHANGED
@@ -19,6 +19,8 @@ export interface DashboardUser {
19
19
  id: number
20
20
  name: string
21
21
  email: string
22
+ /** Erased under the app's data-subject rules: the name and email are placeholders. */
23
+ anonymized?: boolean
22
24
  emailVerifiedAt: string
23
25
  createdAt: string
24
26
  updatedAt: string
@@ -2,7 +2,7 @@
2
2
  "publisher": "Stacks",
3
3
  "name": "vscode-stacks",
4
4
  "displayName": "Stacks",
5
- "version": "0.75.539",
5
+ "version": "0.75.542",
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.539",
5
+ "version": "0.75.542",
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.539",
49
- "@stacksjs/sanitizer": "0.2.842",
50
- "@stacksjs/stx": "0.2.842",
51
- "@stacksjs/strings": "0.75.539",
48
+ "@stacksjs/mobile": "0.75.542",
49
+ "@stacksjs/sanitizer": "^0.2.842",
50
+ "@stacksjs/stx": "^0.2.842",
51
+ "@stacksjs/strings": "0.75.542",
52
52
  "@xterm/addon-fit": "^0.11.0",
53
53
  "@xterm/xterm": "^6.0.0",
54
54
  "ts-qr-codes": "^0.1.8"
@@ -58,7 +58,7 @@ onMount(() => {
58
58
  <div class="space-y-6">
59
59
  <header class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
60
60
  <div>
61
- <h1 class="font-semibold text-2xl text-neutral-900 tracking-tight dark:text-white">Analytics</h1>
61
+ <h1 class="font-bold text-2xl text-neutral-900 tracking-tight dark:text-white">Analytics</h1>
62
62
  <p class="mt-1 text-neutral-500 text-sm dark:text-neutral-400">Persisted business metrics and privacy-safe request telemetry.</p>
63
63
  </div>
64
64
  <Button variant="secondary" :loading="loading()" @click="loadOverview">