@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
@@ -0,0 +1,188 @@
1
+ ---
2
+ name: stacks-upstream
3
+ description: Use when a problem found in an app turns out to live in a dependency - a framework package, stx, ts-css, the router, the query builder, pantry, or any sibling library. Covers finding the owning repository from the package name, reproducing and fixing it there, releasing, and proving the fix from an installed version.
4
+ license: MIT
5
+ compatibility: Bun >= 1.3.0, TypeScript
6
+ allowed-tools: Read Edit Write Bash Grep Glob
7
+ ---
8
+
9
+ # Fix it at the source
10
+
11
+ The rule: a defect in a dependency is fixed in the repository that owns it,
12
+ released, and consumed as a version. The app carries a version bump and nothing
13
+ else. Every dependency in this stack is homegrown, so the owner is always
14
+ reachable.
15
+
16
+ That rules in exactly one shape of change, and these are the shapes it replaces:
17
+ a vendored tarball, a patched copy under `node_modules`, a `file:` or `link:`
18
+ dependency that outlives the session, a shim in the app that corrects the
19
+ dependency's output. Each one fixes one app and leaves the next to find the
20
+ defect again.
21
+
22
+ ## The loop
23
+
24
+ ### 1. Name the owner
25
+
26
+ Read the `repository` field of the package that misbehaves, at the version the
27
+ app actually has installed:
28
+
29
+ ```bash
30
+ bun -e "const p = require('./node_modules/<package>/package.json'); console.log(p.version, JSON.stringify(p.repository))"
31
+ ```
32
+
33
+ The stack trace or the log prefix names the package: `[stx]` is `@stacksjs/stx`,
34
+ a frame under `node_modules/bun-query-builder` is that package. A monorepo's
35
+ `repository.directory` says which folder. The map at the end lists the owners
36
+ confirmed from those fields.
37
+
38
+ Done when you have a repository, a directory inside it and the installed version.
39
+
40
+ ### 2. Check it is not already fixed
41
+
42
+ ```bash
43
+ bun pm view <package> version
44
+ ```
45
+
46
+ If the registry is ahead of the app, read that repository's changelog for the
47
+ symptom before writing anything. An upgrade may be the whole fix.
48
+
49
+ ### 3. Reproduce it there, in isolation
50
+
51
+ In a checkout of the owning repository, on a branch, write the smallest failing
52
+ test that shows the defect with none of the app around it: the template, the
53
+ query, the config value, and the wrong result. Put it beside the package's
54
+ existing tests and copy their harness.
55
+
56
+ A reproduction that needs the app is not finished. Keep cutting until the
57
+ package's own test runner goes red on it. If it will not reproduce there, the
58
+ defect is in how the app or the framework calls the package: return to step 1
59
+ with the caller as the suspect.
60
+
61
+ Done when the new test is red, for the reason you saw in the app.
62
+
63
+ ### 4. Fix and test in that repository
64
+
65
+ Fix the cause. Run that package's suite, and its lint and typecheck, with the
66
+ Bun version that repository pins. Commit in that repository's convention.
67
+
68
+ When the framework should have caught the problem (a config the scaffold wrote,
69
+ an option a harness passed), fix that in the framework too, with its own test.
70
+ The dependency fix makes the failure impossible or loud; the framework fix
71
+ stops it from being triggered.
72
+
73
+ Done when the reproduction is green and the suite is no worse than before.
74
+
75
+ ### 5. Release
76
+
77
+ Use the owning repository's own release script (`bun run release:patch` in most
78
+ of these). A release is published work with the maintainer's name on it: do it
79
+ only when you have been asked to, otherwise stop here and hand over the branch
80
+ and the test.
81
+
82
+ ### 6. Consume the version
83
+
84
+ A just-published version can be absent from Bun's cached manifest, and from the
85
+ registry's tarball store for a few minutes after the version is listed:
86
+
87
+ ```bash
88
+ bun pm cache rm
89
+ bun pm view <package> version # the new version is listed
90
+ bun add <package>@<version> # or raise the range in package.json and install
91
+ ```
92
+
93
+ An app pins the framework through the `stacks` package and `./buddy upgrade`;
94
+ read `stacks-dependencies` for where each range lives. One range per tool: do
95
+ not add a second declaration of something `better-dx` or `stacks` already ships.
96
+
97
+ ### 7. Prove it from an installed version
98
+
99
+ A workspace link or `bun link` reads the package's source. The published
100
+ package is its `dist/` and whatever `files` allows, so a fix can pass every
101
+ linked test and be missing from what users install. Verify against the
102
+ registry's artifact:
103
+
104
+ - the version in `node_modules/<package>/package.json` is the released one, and
105
+ the path is a real directory, not a symlink into a checkout;
106
+ - the original symptom is gone in the app, by the same observation that showed
107
+ it (the log line, the rendered page, the failing command);
108
+ - for a change to build output, read the built file under
109
+ `node_modules/<package>/dist/` and find the fix in it.
110
+
111
+ Done when the app's lockfile names the new version and the symptom is gone with
112
+ nothing local standing in for the release.
113
+
114
+ ## While the fix is in flight
115
+
116
+ The app may need to keep moving before the release lands. Prefer writing the
117
+ app code in the form that is correct either way (compute a value in
118
+ `<script server>` instead of leaning on the broken expression). Where a
119
+ temporary workaround is unavoidable, mark it with the upstream branch or issue
120
+ and delete it in the commit that raises the version.
121
+
122
+ ## Owners
123
+
124
+ Confirmed from the `repository` field of each installed package. Paths are in
125
+ that repository.
126
+
127
+ | Package | Repository |
128
+ |---|---|
129
+ | `stacks`, every `@stacksjs/<core package>` (`actions`, `auth`, `buddy`, `cli`, `config`, `database`, `defaults`, `orm`, `router`, `server`, ...) | `stacksjs/stacks`, `storage/framework/core/<name>` |
130
+ | `@stacksjs/stx`, `bun-plugin-stx`, `stx-router`, `@stacksjs/sanitizer`, `@stacksjs/desktop` | `stacksjs/stx` |
131
+ | `@stacksjs/components` | `stacksjs/stx`, `packages/components` |
132
+ | `@stacksjs/ts-css` | `stacksjs/ts-css`, `packages/toolkit` |
133
+ | `@cwcss/crosswind` | `cwcss/crosswind` |
134
+ | `@stacksjs/bun-router` | `stacksjs/bun-router` |
135
+ | `bun-query-builder` | `stacksjs/bun-query-builder` |
136
+ | `@stacksjs/bun-queue` | `stacksjs/bun-queue` |
137
+ | `@stacksjs/ts-validation` | `stacksjs/ts-validation` |
138
+ | `@stacksjs/ts-auth` | `stacksjs/ts-auth` |
139
+ | `@stacksjs/ts-cache` | `stacksjs/ts-cache` |
140
+ | `@stacksjs/ts-i18n` | `stacksjs/ts-i18n` |
141
+ | `@stacksjs/ts-cloud`, `@ts-cloud/*` | `stacksjs/ts-cloud` |
142
+ | `ts-broadcasting` | `stacksjs/ts-broadcasting`, `packages/ts-broadcasting` |
143
+ | `ts-collect` | `stacksjs/ts-collect` |
144
+ | `ts-error-handling` | `stacksjs/ts-error-handling` |
145
+ | `ts-rate-limiter` | `stacksjs/ts-rate-limiter` |
146
+ | `@stacksjs/httx` | `stacksjs/ts-http` |
147
+ | `@stacksjs/ts-faker` | `stacksjs/ts-mocker` |
148
+ | `@stacksjs/ts-md`, `@stacksjs/ts-xml`, `ts-slug`, `ts-spreadsheets`, `ts-qr-codes`, `ts-syntax-highlighter`, `ts-medium-editor`, `ts-video-player` | `stacksjs/<the same name without the scope>` |
149
+ | `ts-images`, `ts-jpeg`, `ts-gif`, `@stacksjs/ts-png`, `@stacksjs/ts-webp`, `@stacksjs/ts-avif`, `@stacksjs/ts-heic`, `@stacksjs/ts-bmp`, `@stacksjs/ts-svg` | `stacksjs/<the same name without the scope>` |
150
+ | `@ts-audio/*` | `stacksjs/ts-audio` |
151
+ | `ts-videos`, `@ts-videos/*` | `stacksjs/ts-videos` |
152
+ | `@ts-charts/*` | `stacksjs/ts-charts`, `packages/<name>` |
153
+ | `@stacksjs/clapp` | `stacksjs/clapp` |
154
+ | `bunfig` | `stacksjs/bunfig` |
155
+ | `@stacksjs/gitit` | `stacksjs/gitit` |
156
+ | `@stacksjs/gitlint` | `stacksjs/gitlint` |
157
+ | `bun-git-hooks` | `stacksjs/bun-git-hooks` |
158
+ | `@stacksjs/bumpx` | `stacksjs/bumpx` |
159
+ | `@stacksjs/logsmith` | `stacksjs/logsmith` |
160
+ | `@stacksjs/clarity` | `stacksjs/clarity` |
161
+ | `@stacksjs/rpx` | `stacksjs/rpx` |
162
+ | `@stacksjs/tlsx` | `stacksjs/tlsx` |
163
+ | `@stacksjs/dnsx` | `stacksjs/dnsx` |
164
+ | `localtunnels` | `stacksjs/localtunnels`, `packages/localtunnels` |
165
+ | `@stacksjs/bunpress` | `stacksjs/bunpress`, `packages/bunpress` |
166
+ | `bun-plugin-dtsx`, `@dtsx/*` | `stacksjs/dtsx` |
167
+ | `bun-plugin-auto-imports` | `stacksjs/bun-plugin-auto-imports` |
168
+ | `dynamodb-tooling` | `stacksjs/dynamodb-tooling` |
169
+ | `very-happy-dom` | `stacksjs/very-happy-dom` |
170
+ | `better-dx` | `stacksjs/better-dx` |
171
+ | `@buddysh/buddy` (buddy-bot) | `stacksjs/buddy` |
172
+ | `pickier` | `pickier/pickier` |
173
+ | `ts-pantry` | `pantry-pm/pantry`, `packages/ts-pantry` |
174
+ | `craft-native` | `craft-native/craft`, `packages/typescript` |
175
+
176
+ A package missing from the table is read the same way as step 1. Add it here
177
+ once confirmed.
178
+
179
+ ## Gotchas
180
+
181
+ - **The framework has two install trees in an app that uses Pantry.** Check the
182
+ version in the tree the failing process resolves from before concluding a
183
+ bump did nothing.
184
+ - **A dependency that bundles another needs its own release.** A fix in a
185
+ library that a second package inlines at build time reaches users only when
186
+ that second package is rebuilt and released too.
187
+ - **Renamed or scoped spellings.** `@stacksjs/httx` lives in `ts-http` and
188
+ `@stacksjs/ts-faker` in `ts-mocker`. Trust the `repository` field over the name.
@@ -13,7 +13,7 @@ project `AGENTS.md`, a doc reached by a pointer. The packaging differs, the
13
13
  writing does not. The same levers make each one predictable, because the agent
14
14
  takes the same *process* every run rather than producing the same output.
15
15
 
16
- Stacks ships 207 skills and expects projects to add their own under
16
+ Stacks ships 210 skills and expects projects to add their own under
17
17
  `app/Skills/`, so this is the skill that keeps that set from turning to sludge.
18
18
  The Stacks-specific mechanics (frontmatter, invocation, the override model,
19
19
  what `buddy setup:ai` does with the result) are in
@@ -1,5 +1,5 @@
1
1
  import { Action } from '@stacksjs/actions/runtime'
2
- import { User } from '@stacksjs/orm'
2
+ import { anonymizedRows, GDPR_SUBJECT_MODEL, User } from '@stacksjs/orm'
3
3
  import { safeGet } from '../../../../resources/functions/dashboard/data'
4
4
  import { dashboardOperationalError } from '../dashboard-response'
5
5
  import { dateValue, daysAgoIso, numberValue, textValue } from './data-records'
@@ -12,10 +12,28 @@ export default new Action({
12
12
  async handle() {
13
13
  try {
14
14
  const rows = await User.orderByDesc('created_at').limit(100).get()
15
- const users = rows.map(row => ({
15
+ // An account erased under the app's data-subject rules stays in the
16
+ // table with its personal details replaced. Listed as it is stored it
17
+ // reads "[erased] / erased-13", which looks like corrupt data, so each
18
+ // row says whether it is one and the page names it for what it is.
19
+ const erased = await anonymizedRows(GDPR_SUBJECT_MODEL, rows.map(row => ({
20
+ // As stored: an emptied column is NULL, and `safeGet` would otherwise
21
+ // hand back its empty-string fallback, which is not what erasure wrote.
22
+ id: safeGet(row, 'id', 0),
23
+ name: safeGet(row, 'name', null),
24
+ email: safeGet(row, 'email', null),
25
+ avatar: safeGet(row, 'avatar', null),
26
+ }))).catch((error) => {
27
+ // The list is still worth showing when the rules cannot be read.
28
+ console.warn('[dashboard/api] UserIndexAction: could not tell which users are anonymized:', error)
29
+ return rows.map(() => false)
30
+ })
31
+
32
+ const users = rows.map((row, index) => ({
16
33
  id: numberValue(safeGet(row, 'id', 0)),
17
34
  name: textValue(safeGet(row, 'name'), 'Unnamed user'),
18
35
  email: textValue(safeGet(row, 'email')),
36
+ anonymized: erased[index] === true,
19
37
  emailVerifiedAt: dateValue(safeGet(row, 'email_verified_at', safeGet(row, 'emailVerifiedAt'))),
20
38
  createdAt: dateValue(safeGet(row, 'created_at', safeGet(row, 'createdAt'))),
21
39
  updatedAt: dateValue(safeGet(row, 'updated_at', safeGet(row, 'updatedAt'))),
@@ -1,15 +1,31 @@
1
1
  import type { RequestInstance } from '@stacksjs/types'
2
2
  import { Action } from '@stacksjs/actions/runtime'
3
+ import { eraseSubject, GDPR_SUBJECT_MODEL } from '@stacksjs/orm'
3
4
  import { response } from '@stacksjs/router'
4
5
  import { dashboardOperationalError } from '../dashboard-response'
5
- import { parseRowId, resolveWritableModel } from './model-write'
6
+ import { destroyModelRecord } from './model-destroy'
7
+ import { isAccountModel, parseRowId, resolveWritableModel } from './model-write'
8
+
9
+ /** The id of the account making this request, when there is one. */
10
+ async function signedInId(request: RequestInstance): Promise<number | null> {
11
+ try {
12
+ const id = Number((await request.user())?.id)
13
+ return Number.isSafeInteger(id) && id > 0 ? id : null
14
+ }
15
+ catch {
16
+ // The local dashboard runs without a session, and then there is no
17
+ // account to protect.
18
+ return null
19
+ }
20
+ }
6
21
 
7
22
  /**
8
23
  * `DELETE /api/dashboard/models/{slug}/{id}`.
9
24
  *
10
25
  * Deletes one row from the dashboard's generic model browser. Goes through
11
26
  * the model rather than the table so soft deletes, observers and cascade
12
- * behaviour all apply exactly as they would anywhere else in the app.
27
+ * behaviour all apply exactly as they would anywhere else in the app. A user
28
+ * other records still point at is anonymized instead: see `./model-destroy`.
13
29
  */
14
30
  export default new Action({
15
31
  name: 'Dashboard Model Destroy',
@@ -25,15 +41,35 @@ export default new Action({
25
41
  if (id === null)
26
42
  return response.json({ message: 'A numeric row id is required.' }, 400)
27
43
 
28
- try {
29
- const row = await resolved.Model.find(id)
30
- if (!row)
31
- return response.json({ message: `${resolved.modelName} ${id} not found.` }, 404)
32
- await row.delete()
33
- return { ok: true, id }
34
- }
35
- catch (error) {
36
- return dashboardOperationalError(error, 'The model record could not be deleted.', 'ModelDestroyAction', 500)
37
- }
44
+ // Deleting the account you are signed in with ends your own access in the
45
+ // middle of using it, and for the last admin there is no way back in.
46
+ const viewer = await signedInId(request)
47
+ if (isAccountModel(resolved.Model) && viewer === id)
48
+ return response.json({ message: 'You are signed in with this account, so it cannot be deleted from here. Ask another admin to remove it.' }, 409)
49
+
50
+ const result = await destroyModelRecord(id, {
51
+ Model: resolved.Model,
52
+ actor: viewer === null ? 'dashboard' : `dashboard:user:${viewer}`,
53
+ erase: async (subject, actor) => {
54
+ const erased = await eraseSubject(subject, { actor })
55
+ const own = erased.changes.find(change => change.model === GDPR_SUBJECT_MODEL)
56
+ return { action: (own?.action ?? 'keep') as 'anonymize' | 'delete' | 'keep' }
57
+ },
58
+ })
59
+
60
+ if (result.ok)
61
+ return { ok: true, id, anonymized: result.outcome === 'anonymized' }
62
+ if (result.reason === 'missing')
63
+ return response.json({ message: `${resolved.modelName} ${id} not found.` }, 404)
64
+ // The database kept the row because others still point at it. Nothing
65
+ // failed: the answer is to deal with those records first, and saying
66
+ // "could not be deleted" sent people to the server logs for it.
67
+ if (result.reason === 'referenced')
68
+ return response.json({ message: `This ${resolved.modelName.toLowerCase()} cannot be deleted while other records still refer to it. Remove or reassign those records first.` }, 409)
69
+ // Erasure is one transaction and repeating it changes nothing it already
70
+ // changed, so "try again" is a real answer here.
71
+ if (result.reason === 'erasure-failed')
72
+ return dashboardOperationalError(result.cause, 'Other records still refer to this user, and anonymizing the account did not finish. Try again: repeating it is safe.', 'ModelDestroyAction.erase', 500)
73
+ return dashboardOperationalError(result.cause, 'The model record could not be deleted.', 'ModelDestroyAction', 500)
38
74
  },
39
75
  })
@@ -0,0 +1,103 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
2
+ import type { ModelOption } from './model-relations'
3
+ import { Action } from '@stacksjs/actions/runtime'
4
+ import { response } from '@stacksjs/router'
5
+ import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
6
+ import { dashboardOperationalError } from '../dashboard-response'
7
+ import { optionsFromRows } from './model-options'
8
+ import { modelHintColumn, modelLabelColumn } from './model-relations'
9
+ import { humanizeIdentifier, isValidModelSlug, slugToPascal } from './model-write'
10
+
11
+ /** How many records a search offers. A picker is for finding one, not browsing. */
12
+ const OPTION_LIMIT = 20
13
+ /** How many ids one request may ask the names of. */
14
+ const ID_LIMIT = 50
15
+
16
+ interface OptionsInput {
17
+ q?: unknown
18
+ ids?: unknown
19
+ }
20
+
21
+ function parseIds(raw: unknown): number[] {
22
+ const parts = Array.isArray(raw) ? raw : String(raw ?? '').split(',')
23
+ const ids = parts.map(part => Number.parseInt(String(part).trim(), 10)).filter(id => Number.isSafeInteger(id) && id > 0)
24
+ return [...new Set(ids)].slice(0, ID_LIMIT)
25
+ }
26
+
27
+ /**
28
+ * `GET /api/dashboard/models/{slug}/options`.
29
+ *
30
+ * The records of a model as a picker lists them: an id and what the record
31
+ * is called. `?q=` searches by that name (and by a person's email, and by id
32
+ * when the term is a number); `?ids=3,7` answers for exactly those, which is
33
+ * how a form shows the name of the record a field already points at.
34
+ *
35
+ * Its own endpoint, not the model browser's: that one returns every column of
36
+ * every row it matches, and a picker asks on every keystroke.
37
+ */
38
+ export default new Action({
39
+ name: 'Dashboard Model Options',
40
+ description: 'Lists a model\'s records by name, for choosing one in a form.',
41
+ method: 'GET',
42
+ apiResponse: true,
43
+ async handle(request: RequestInstance<OptionsInput>) {
44
+ const slug = String(request.getParam('slug') ?? '')
45
+ if (!isValidModelSlug(slug))
46
+ return response.json({ message: 'Model slug must be lowercase kebab-case.' }, 400)
47
+
48
+ const modelName = slugToPascal(slug)
49
+ let Model: any
50
+ try {
51
+ Model = await resolveDashboardModel(modelName)
52
+ }
53
+ catch (error) {
54
+ return dashboardOperationalError(error, `${modelName} could not be loaded.`, 'ModelOptionsAction.resolve')
55
+ }
56
+ if (!Model || typeof Model.where !== 'function')
57
+ return response.json({ message: `No ORM model named ${modelName}.` }, 404)
58
+
59
+ const input = request.all()
60
+ const q = String(input.q ?? '').trim().slice(0, 100)
61
+ const ids = parseIds(input.ids)
62
+ const labelColumn = modelLabelColumn(Model)
63
+ const hintColumn = modelHintColumn(Model)
64
+ const modelLabel = humanizeIdentifier(modelName)
65
+
66
+ try {
67
+ // Built the way the model browser builds its search: from the model's
68
+ // own query, with raw conditions inside the group.
69
+ let query = Model.query() as any
70
+ if (ids.length > 0) {
71
+ query = query.whereIn('id', ids)
72
+ }
73
+ else if (q) {
74
+ const numeric = /^\d+$/.test(q) ? Number(q) : null
75
+ const conditions: Array<[string, string | number]> = [labelColumn, hintColumn]
76
+ .filter((column): column is string => Boolean(column))
77
+ // Lowercased on both sides: a model query's LIKE is case-sensitive
78
+ // on PostgreSQL (stacksjs/stacks#3202).
79
+ .map(column => [`LOWER(${column}) LIKE LOWER(?)`, `%${q}%`])
80
+ if (numeric !== null)
81
+ conditions.push(['id = ?', numeric])
82
+ // Nothing to search by name and the term is not an id: no match, not everything.
83
+ if (conditions.length === 0)
84
+ return { options: [], modelLabel, labelColumn }
85
+ query = query.whereGroup((group: any) => {
86
+ for (const [index, [condition, value]] of conditions.entries())
87
+ group = index === 0 ? group.whereRaw(condition, value) : group.orWhereRaw(condition, value)
88
+ return group
89
+ })
90
+ }
91
+
92
+ const rows = await query.orderBy(labelColumn ?? 'id', 'asc').take(ids.length > 0 ? ID_LIMIT : OPTION_LIMIT).get() as any[]
93
+ const list = Array.isArray(rows) ? rows : []
94
+
95
+ const options: ModelOption[] = await optionsFromRows(Model, modelName, list)
96
+
97
+ return { options, modelLabel, labelColumn }
98
+ }
99
+ catch (error) {
100
+ return dashboardOperationalError(error, `${modelLabel} records could not be listed.`, 'ModelOptionsAction.query')
101
+ }
102
+ },
103
+ })
@@ -0,0 +1,42 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
2
+ import { Action } from '@stacksjs/actions/runtime'
3
+ import { response } from '@stacksjs/router'
4
+ import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
5
+ import { dashboardOperationalError } from '../dashboard-response'
6
+ import { relatedPanels } from './model-related'
7
+ import { isValidModelSlug, parseRowId, slugToPascal } from './model-write'
8
+
9
+ /**
10
+ * `GET /api/dashboard/models/{slug}/{id}/related`.
11
+ *
12
+ * The records that point at one record, as the panels of its page: for each
13
+ * `hasMany` and `hasOne` the model declares, a count and the newest few. See
14
+ * `./model-related`.
15
+ */
16
+ export default new Action({
17
+ name: 'Dashboard Model Related',
18
+ description: 'Lists the records that point at one record, by the model\'s hasMany and hasOne.',
19
+ method: 'GET',
20
+ apiResponse: true,
21
+ async handle(request: RequestInstance) {
22
+ const slug = String(request.getParam('slug') ?? '')
23
+ if (!isValidModelSlug(slug))
24
+ return response.json({ message: 'Model slug must be lowercase kebab-case.' }, 400)
25
+ const id = parseRowId(request.getParam('id'))
26
+ if (id === null)
27
+ return response.json({ message: 'A numeric row id is required.' }, 400)
28
+
29
+ const modelName = slugToPascal(slug)
30
+ try {
31
+ const Model = await resolveDashboardModel(modelName)
32
+ if (!Model || typeof Model.find !== 'function')
33
+ return response.json({ message: `No ORM model named ${modelName}.` }, 404)
34
+ if (!(await Model.find(id)))
35
+ return response.json({ message: `${modelName} ${id} not found.` }, 404)
36
+ return { panels: await relatedPanels(Model, modelName, id) }
37
+ }
38
+ catch (error) {
39
+ return dashboardOperationalError(error, 'The related records could not be loaded.', 'ModelRelatedAction')
40
+ }
41
+ },
42
+ })
@@ -1,12 +1,18 @@
1
1
  import { hiddenModelColumns } from '../../../../resources/functions/dashboard/model-columns'
2
2
  import type { RequestInstance } from '@stacksjs/types'
3
3
  import { Action } from '@stacksjs/actions/runtime'
4
+ import { anonymizedRows } from '@stacksjs/orm'
4
5
  import { response as routerResponse } from '@stacksjs/router'
5
6
  import { safeGet } from '../../../../resources/functions/dashboard/data'
6
7
  import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
7
8
  import { dashboardOperationalError } from '../dashboard-response'
8
9
  import { isUnmigratedTable } from './model-migration'
9
- import { isValidModelSlug, type ModelCreateField, type ModelWriteCapabilities, modelCreateFields, modelSchemaColumns, modelWritableColumns, modelWriteCapabilities, slugToPascal } from './model-write'
10
+ import { recordNames } from './model-options'
11
+ import { belongsToRelations } from './model-relations'
12
+ import { humanizeIdentifier, isErasureSubject, isValidModelSlug, type ModelCreateField, type ModelWriteCapabilities, modelCreateFields, modelListColumns, modelSchemaColumns, modelWritableColumns, modelWriteCapabilities, slugToPascal } from './model-write'
13
+
14
+ /** Models already told, this process, that `dashboard.columns` names a column they lack. */
15
+ const warnedColumns = new Set<string>()
10
16
 
11
17
  /**
12
18
  * `GET /api/dashboard/models/{slug}` (stacksjs/stacks#1838).
@@ -39,6 +45,8 @@ interface ColumnMeta {
39
45
 
40
46
  interface ResponseShape {
41
47
  modelName: string
48
+ /** The model's name as a person reads it: "Social Post" for `SocialPost`. */
49
+ modelLabel: string
42
50
  tableName: string
43
51
  rows: Array<Record<string, unknown>>
44
52
  columns: string[]
@@ -56,7 +64,17 @@ interface ResponseShape {
56
64
  writable: boolean
57
65
  writeCapabilities: ModelWriteCapabilities
58
66
  createFields: ModelCreateField[]
67
+ /** The fields an edit may change, described the way the create form's are. */
68
+ updateFields: ModelCreateField[]
69
+ /** The columns that hold another model's id, and whose: `team_id` is a Team. */
70
+ relations: Record<string, { model: string, slug: string, label: string }>
71
+ /** The columns the list draws, in order: the model's `dashboard.columns`, or all of them. */
72
+ listColumns: string[]
73
+ /** What the records these rows point at are called, by column and then id. */
74
+ relationNames: Record<string, Record<string, string>>
59
75
  updateColumns: string[]
76
+ /** Rows whose personal details erasure has replaced with placeholders (the subject model only). */
77
+ anonymizedIds?: Array<number | string>
60
78
  /** False when the model's table does not exist yet: `./buddy migrate` creates it. */
61
79
  migrated: boolean
62
80
  error: string | null
@@ -75,14 +93,6 @@ function pluralize(word: string): string {
75
93
  return `${word}s`
76
94
  }
77
95
 
78
- function humanize(column: string): string {
79
- return column
80
- .replace(/_/g, ' ')
81
- .replace(/\b\w/g, c => c.toUpperCase())
82
- .replace(/\bId\b/g, 'ID')
83
- .replace(/\bUrl\b/g, 'URL')
84
- }
85
-
86
96
  // Hide credential / token columns + private fields by default. These are
87
97
  // dropped from the response body AND from the sort/filter allowlist: a
88
98
  // column you cannot see is still an enumeration oracle if you can sort or
@@ -199,6 +209,7 @@ export default new Action({
199
209
 
200
210
  const response: ResponseShape = {
201
211
  modelName,
212
+ modelLabel: humanizeIdentifier(modelName),
202
213
  tableName,
203
214
  rows: [],
204
215
  columns: [],
@@ -214,8 +225,12 @@ export default new Action({
214
225
  q,
215
226
  filters,
216
227
  writable: false,
217
- writeCapabilities: { create: false, update: false, destroy: false },
228
+ writeCapabilities: { create: false, update: false, destroy: false, invite: false, anonymize: false },
218
229
  createFields: [],
230
+ updateFields: [],
231
+ relations: {},
232
+ listColumns: [],
233
+ relationNames: {},
219
234
  updateColumns: [],
220
235
  migrated: true,
221
236
  error: null,
@@ -298,6 +313,17 @@ export default new Action({
298
313
  flat[col] = safeGet(row, col, null)
299
314
  return flat
300
315
  })
316
+
317
+ // An account erased under the app's data-subject rules is stored as
318
+ // placeholders ("[erased]", "erased-13"). The page says which rows those
319
+ // are, so it can explain them and not show what looks like corrupt data.
320
+ if (isErasureSubject(Model) && response.rows.length > 0) {
321
+ const erased = await anonymizedRows(modelName, response.rows).catch((error) => {
322
+ console.warn(`[dashboard/api] ModelShowAction: could not tell which ${modelName} rows are anonymized:`, error)
323
+ return [] as boolean[]
324
+ })
325
+ response.anonymizedIds = response.rows.filter((_row, index) => erased[index] === true).map(row => row.id as number | string)
326
+ }
301
327
  }
302
328
  catch (error) {
303
329
  // Not an error to report: the table simply has not been created yet, and
@@ -309,14 +335,51 @@ export default new Action({
309
335
 
310
336
  response.writeCapabilities = modelWriteCapabilities(Model)
311
337
  response.writable = Object.values(response.writeCapabilities).some(Boolean)
312
- response.createFields = response.writeCapabilities.create ? modelCreateFields(Model) : []
338
+ // A relation is only worth a picker when the dashboard can list the model
339
+ // it points at. One whose feature is off, or that is kept out of the
340
+ // dashboard, stays the plain id it was.
341
+ const reachable = new Set<string>()
342
+ for (const relation of belongsToRelations(Model)) {
343
+ const related = await resolveDashboardModel(relation.model).catch(() => null)
344
+ if (related && typeof related.where === 'function') {
345
+ reachable.add(relation.model)
346
+ response.relations[relation.column] = { model: relation.model, slug: relation.slug, label: humanizeIdentifier(relation.model) }
347
+ }
348
+ }
349
+ const formFields = (): ModelCreateField[] => modelCreateFields(Model).map((field) => {
350
+ if (field.type !== 'relation' || reachable.has(field.relation?.model ?? ''))
351
+ return field
352
+ const { relation: _unreachable, ...plain } = field
353
+ return { ...plain, type: 'number', label: humanizeIdentifier(field.name) }
354
+ })
355
+ response.createFields = response.writeCapabilities.create ? formFields() : []
313
356
  response.updateColumns = response.writeCapabilities.update ? modelWritableColumns(Model) : []
357
+ response.updateFields = response.writeCapabilities.update ? formFields() : []
314
358
  response.displayColumns = response.columns.filter(col => !col.startsWith('_'))
315
359
  response.columnMeta = response.displayColumns.map(name => ({
316
360
  name,
317
- label: humanize(name),
361
+ // "Team", not "Team ID": the column shows which team.
362
+ label: response.relations[name]?.label ?? humanizeIdentifier(name),
318
363
  type: typeForColumn(name, response.rows.map(r => r[name])),
319
364
  }))
365
+
366
+ const list = modelListColumns(Model, response.displayColumns)
367
+ response.listColumns = list.columns
368
+ // Only with a real row to judge by: an empty table's columns come from the
369
+ // model alone, which does not know the ones its traits add.
370
+ if (list.unknown.length > 0 && response.rows.length > 0 && !warnedColumns.has(modelName)) {
371
+ warnedColumns.add(modelName)
372
+ console.warn(`[dashboard] ${modelName} names ${list.unknown.map(name => `'${name}'`).join(', ')} in dashboard.columns, which its table does not have (or hides). ${list.unknown.length === 1 ? 'It is' : 'They are'} left out of the list.`)
373
+ }
374
+
375
+ // The records these rows point at, named: one lookup per related model,
376
+ // for the rows on this page. A list then reads "PrimeSoft Ltd" where it
377
+ // read "3", and a record's page has its names without asking again.
378
+ for (const [column, relation] of Object.entries(response.relations)) {
379
+ const ids = response.rows.map(row => row[column]).filter(id => id !== null && id !== undefined && id !== '') as Array<number | string>
380
+ if (ids.length > 0)
381
+ response.relationNames[column] = Object.fromEntries(await recordNames(relation.model, ids))
382
+ }
320
383
  response.searchable = response.columnMeta.filter(c => c.type === 'text').map(c => c.name)
321
384
  response.lastPage = Math.max(1, Math.ceil(response.totalCount / perPage))
322
385
 
@@ -3,7 +3,8 @@ import { Action } from '@stacksjs/actions/runtime'
3
3
  import { ModelValidationError, toSnakeCaseKeys } from '@stacksjs/orm'
4
4
  import { response } from '@stacksjs/router'
5
5
  import { dashboardOperationalError } from '../dashboard-response'
6
- import { prepareModelFields, resolveWritableModel } from './model-write'
6
+ import { missingRelationErrors } from './model-relations'
7
+ import { humanizeIdentifier, prepareModelFields, resolveWritableModel } from './model-write'
7
8
 
8
9
  interface ModelWriteInput {
9
10
  fields?: unknown
@@ -39,6 +40,11 @@ export default new Action({
39
40
  // field by field, not a server failure (stacksjs/stacks#3007).
40
41
  if (error instanceof ModelValidationError)
41
42
  return response.json({ message: 'Validation failed.', errors: error.errors }, 422)
43
+ // A record this one points at was deleted while the form was open. The
44
+ // person can pick another, so it is said on that field.
45
+ const missing = missingRelationErrors(resolved.Model, error, Object.keys(toSnakeCaseKeys(data)), humanizeIdentifier)
46
+ if (Object.keys(missing).length > 0)
47
+ return response.json({ message: 'Validation failed.', errors: missing }, 422)
42
48
  return dashboardOperationalError(error, 'The model record could not be created.', 'ModelStoreAction', 500)
43
49
  }
44
50
  },