@stacksjs/defaults 0.75.552 → 0.75.555
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.
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +347 -14
- package/ai/skills/stacks-desktop/SKILL.md +19 -0
- package/ai/skills/stacks-models/SKILL.md +19 -0
- package/ai/skills/stacks-native/CATALOG.md +5 -5
- package/app/Actions/Dashboard/Content/file-manager.ts +9 -3
- package/app/Actions/Dashboard/Data/SubscriberIndexAction.ts +6 -3
- package/app/Actions/Dashboard/Data/TeamIndexAction.ts +6 -3
- package/app/Actions/Dashboard/Data/UserIndexAction.ts +6 -3
- package/app/Actions/Dashboard/Data/data-records.ts +12 -0
- package/app/Actions/Dashboard/Models/ModelActionRunAction.ts +77 -0
- package/app/Actions/Dashboard/Models/ModelMarkdownAction.ts +42 -0
- package/app/Actions/Dashboard/Models/ModelShowAction.ts +63 -21
- package/app/Actions/Dashboard/Models/ModelUploadAction.ts +83 -0
- package/app/Actions/Dashboard/Models/model-actions.ts +393 -0
- package/app/Actions/Dashboard/Models/model-fields.ts +198 -0
- package/app/Actions/Dashboard/Models/model-forms.ts +36 -0
- package/app/Actions/Dashboard/Models/model-related.ts +62 -11
- package/app/Actions/Dashboard/Models/model-upload.ts +81 -0
- package/app/Actions/Dashboard/Models/model-write.ts +92 -5
- package/app/Actions/Dashboard/Users/UserPasswordResetAction.ts +50 -0
- package/app/Actions/Desktop/UpdateArtifactAction.ts +37 -0
- package/app/Models/CardAttachment.ts +5 -0
- package/app/Models/Deployment.ts +5 -0
- package/app/Models/QueryLog.ts +5 -0
- package/app/Models/Request.ts +4 -0
- package/app/Models/Team.ts +4 -0
- package/app/Models/User.ts +18 -0
- package/functions/dashboard-markdown.ts +132 -0
- package/functions/dashboard-model-bulk.ts +224 -0
- package/functions/dashboard-model-format.ts +201 -0
- package/functions/dashboard-model-record.test.ts +53 -30
- package/functions/dashboard-model-record.ts +267 -19
- package/functions/data.ts +9 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +3 -3
- package/resources/components/Dashboard/Data/ActivityLog.stx +212 -0
- package/resources/components/Dashboard/Data/DataModelRecords.stx +89 -0
- package/resources/components/Dashboard/Models/ModelActionForm.stx +85 -0
- package/resources/components/Dashboard/Models/ModelBadge.stx +22 -0
- package/resources/components/Dashboard/Models/ModelFieldInputs.stx +43 -9
- package/resources/components/Dashboard/Models/ModelMarkdownInput.stx +139 -0
- package/resources/components/Dashboard/Models/ModelRecordActions.stx +32 -1
- package/resources/components/Dashboard/Models/ModelRecordCreate.stx +1 -1
- package/resources/components/Dashboard/Models/ModelRecordDetail.stx +114 -7
- package/resources/components/Dashboard/Models/ModelRecordEdit.stx +1 -1
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +387 -20
- package/resources/components/Dashboard/Models/ModelRelatedPanels.stx +197 -27
- package/resources/components/Dashboard/Models/ModelRelationPicker.stx +3 -0
- package/resources/components/Dashboard/Models/ModelUploadInput.stx +97 -0
- package/routes/dashboard-api.ts +9 -0
- package/routes/desktop-updates.ts +7 -0
- package/views/dashboard/data/activity/index.stx +1 -1
- package/views/dashboard/data/subscribers.stx +1 -3
- package/views/dashboard/data/teams.stx +1 -3
- package/views/dashboard/data/users.stx +1 -3
- package/resources/components/Dashboard/Data/DataRecords.stx +0 -427
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a model lets an operator do to one of its records beyond creating,
|
|
3
|
+
* editing and deleting it: "Mark as shipped", "Send password reset".
|
|
4
|
+
*
|
|
5
|
+
* A model describes data, and these are operations, so the model does not
|
|
6
|
+
* describe them. It names them: each entry of `dashboard.actions` points at an
|
|
7
|
+
* action under `app/Actions`, which is where behaviour already lives, and the
|
|
8
|
+
* dashboard offers it as a button on the record's page and in its row, and
|
|
9
|
+
* where the model asks, for the rows selected in a list. One guarded endpoint
|
|
10
|
+
* runs whichever was pressed, on one record, the way that action's own route
|
|
11
|
+
* would: its `validations`, `authorize` and `before` all apply. A selection is
|
|
12
|
+
* that endpoint once per record, so nothing about an action changes for it.
|
|
13
|
+
*
|
|
14
|
+
* `when` narrows an action to the records it makes sense for, and is checked
|
|
15
|
+
* here both times: to decide which rows are sent a button, and again before
|
|
16
|
+
* the action runs, so a hidden button is never the only thing in the way.
|
|
17
|
+
*/
|
|
18
|
+
import type { ResponseStatus } from '@stacksjs/bun-router'
|
|
19
|
+
import { response } from '@stacksjs/router'
|
|
20
|
+
import { safeGet } from '../../../../resources/functions/dashboard/data'
|
|
21
|
+
import { type FieldAsking, MODEL_FIELD_INPUTS, readFieldAsking } from './model-fields'
|
|
22
|
+
import { humanizeIdentifier, type ModelCreateField, modelFieldType } from './model-write'
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Where an action is offered: on the record's own page, in its row of a
|
|
26
|
+
* list, and for the rows selected in a list.
|
|
27
|
+
*/
|
|
28
|
+
export type ModelActionPlace = 'record' | 'row' | 'bulk'
|
|
29
|
+
|
|
30
|
+
/** A value a `when` compares a column to. `null` is "nothing stored". */
|
|
31
|
+
export type ModelActionValue = string | number | boolean | null
|
|
32
|
+
|
|
33
|
+
/** An action as the page is told about it: enough to draw the button and ask first. */
|
|
34
|
+
export interface ModelCustomAction {
|
|
35
|
+
/** Its place in the URL that runs it. */
|
|
36
|
+
name: string
|
|
37
|
+
/** What the button says. */
|
|
38
|
+
label: string
|
|
39
|
+
/** An iconify class, or empty for the default. */
|
|
40
|
+
icon: string
|
|
41
|
+
/** What the confirmation says before it runs. Empty runs it at once. */
|
|
42
|
+
confirm: string
|
|
43
|
+
/** Drawn in red: it removes or revokes something. */
|
|
44
|
+
destructive: boolean
|
|
45
|
+
places: ModelActionPlace[]
|
|
46
|
+
/**
|
|
47
|
+
* What the action has to be told before it runs, from its own
|
|
48
|
+
* `validations`: a refund's reason. Empty for one that takes nothing. With
|
|
49
|
+
* any, pressing the button opens a form and not a confirmation.
|
|
50
|
+
*/
|
|
51
|
+
fields: ModelCreateField[]
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The same, with what only the server needs: which action runs, and for which records. */
|
|
55
|
+
export interface ModelActionDefinition extends ModelCustomAction {
|
|
56
|
+
/** The handler string a route would take: `Actions/Orders/ShipOrderAction`. */
|
|
57
|
+
handler: string
|
|
58
|
+
when: Array<{ column: string, values: ModelActionValue[] }>
|
|
59
|
+
/** How the model says the action's input is asked for, by the input's name. */
|
|
60
|
+
asking: Record<string, FieldAsking>
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The parameters of the route that runs an action. They are part of what an
|
|
65
|
+
* action can validate, and never something to ask a person: the record is
|
|
66
|
+
* the one whose button was pressed.
|
|
67
|
+
*/
|
|
68
|
+
const ROUTE_PARAMETERS: ReadonlySet<string> = new Set(['id', 'dashboardModel', 'dashboardAction'])
|
|
69
|
+
|
|
70
|
+
/** Kinds of value no form input can supply: a list, a structure, a file's bytes, a secret. */
|
|
71
|
+
const UNASKABLE: ReadonlySet<string> = new Set(['array', 'binary', 'blob', 'file', 'object', 'password'])
|
|
72
|
+
|
|
73
|
+
/** The kinds that are text, and may be given another text input. */
|
|
74
|
+
const TEXT_KINDS: ReadonlySet<string> = new Set(['email', 'longtext', 'markdown', 'text', 'url'])
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The inputs an action's field can be given. Not a file chooser: an upload
|
|
78
|
+
* is stored against a model's field, and an action's input is not one.
|
|
79
|
+
*/
|
|
80
|
+
const ACTION_INPUTS = MODEL_FIELD_INPUTS.filter(input => input !== 'upload')
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The form an action's input is asked for in, from the action's own
|
|
84
|
+
* `validations`: one field per rule, in the control the rule calls for,
|
|
85
|
+
* required where the rule is.
|
|
86
|
+
*
|
|
87
|
+
* `asking` is the model's say on how each is asked (`fields` on the
|
|
88
|
+
* declaration). `unaskable` names what the action requires that no form can
|
|
89
|
+
* give; with any, the action cannot be run from a form at all. `ignored`
|
|
90
|
+
* says which of the model's settings could not be applied, and why.
|
|
91
|
+
*/
|
|
92
|
+
export function modelActionFields(validations: unknown, asking: Record<string, FieldAsking> = {}): { fields: ModelCreateField[], unaskable: string[], ignored: string[] } {
|
|
93
|
+
const fields: ModelCreateField[] = []
|
|
94
|
+
const unaskable: string[] = []
|
|
95
|
+
// What the model asked for that cannot be done, in words that name the field.
|
|
96
|
+
const ignored: string[] = []
|
|
97
|
+
if (!validations || typeof validations !== 'object' || Array.isArray(validations))
|
|
98
|
+
return { fields, unaskable, ignored: Object.keys(asking).map(name => `describes a field '${name}' that the action does not take`) }
|
|
99
|
+
|
|
100
|
+
for (const [name, entry] of Object.entries(validations as Record<string, any>)) {
|
|
101
|
+
const rule = entry?.rule
|
|
102
|
+
if (ROUTE_PARAMETERS.has(name) || !rule || typeof rule.validate !== 'function')
|
|
103
|
+
continue
|
|
104
|
+
// A file rule carries no name at all.
|
|
105
|
+
const kind = rule.name === null || rule.name === undefined ? 'file' : String(rule.name)
|
|
106
|
+
if (UNASKABLE.has(kind)) {
|
|
107
|
+
// Optional: left out of the form. Required: there is no asking for it.
|
|
108
|
+
if (rule.isRequired === true)
|
|
109
|
+
unaskable.push(name)
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
const said = asking[name]
|
|
113
|
+
const derived = modelFieldType(name, { validation: { rule } })
|
|
114
|
+
const type = said?.input && TEXT_KINDS.has(derived) ? said.input : derived
|
|
115
|
+
// What a value is stays the rule's to say: a number is not asked for as prose.
|
|
116
|
+
if (said?.input && !TEXT_KINDS.has(derived))
|
|
117
|
+
ignored.push(`field '${name}' asks for the '${said.input}' input, but it is not a field of text (it is asked for as ${derived})`)
|
|
118
|
+
fields.push({
|
|
119
|
+
name,
|
|
120
|
+
label: said?.label ?? modelActionLabel(name),
|
|
121
|
+
type,
|
|
122
|
+
required: rule.isRequired === true,
|
|
123
|
+
defaultValue: type === 'boolean' ? false : '',
|
|
124
|
+
options: Array.isArray(rule.allowedValues) ? rule.allowedValues.map(String) : [],
|
|
125
|
+
...(said?.help ? { help: said.help } : {}),
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
for (const name of Object.keys(asking)) {
|
|
129
|
+
if (!fields.some(field => field.name === name))
|
|
130
|
+
ignored.push(`describes a field '${name}' that the action does not take`)
|
|
131
|
+
}
|
|
132
|
+
return { fields, unaskable, ignored }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const PLACES: readonly ModelActionPlace[] = ['record', 'row', 'bulk']
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Where an action is offered when the model does not say: one record at a
|
|
139
|
+
* time. Acting on a whole selection is asked for by name, since a press then
|
|
140
|
+
* runs on many records.
|
|
141
|
+
*/
|
|
142
|
+
const DEFAULT_PLACES: readonly ModelActionPlace[] = ['record', 'row']
|
|
143
|
+
|
|
144
|
+
function column(name: string): string {
|
|
145
|
+
return name
|
|
146
|
+
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
|
|
147
|
+
.replace(/[\s-]+/g, '_')
|
|
148
|
+
.toLowerCase()
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* A button's words from an action's name: `markShipped` is "Mark shipped",
|
|
153
|
+
* `sync-api-keys` is "Sync API keys". Sentence case, as every other button in
|
|
154
|
+
* the dashboard is written.
|
|
155
|
+
*/
|
|
156
|
+
export function modelActionLabel(name: string): string {
|
|
157
|
+
return humanizeIdentifier(name)
|
|
158
|
+
.split(' ')
|
|
159
|
+
.map((word, index) => index === 0 || word === word.toUpperCase() ? word : word.toLowerCase())
|
|
160
|
+
.join(' ')
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function isValue(value: unknown): value is ModelActionValue {
|
|
164
|
+
return value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Read a `when`: each column with the values it may hold. Null when it cannot
|
|
169
|
+
* be read, which is not the same as no condition: an action whose condition
|
|
170
|
+
* is unreadable is left out, never offered for every record.
|
|
171
|
+
*/
|
|
172
|
+
function conditions(when: unknown): ModelActionDefinition['when'] | null {
|
|
173
|
+
if (when === undefined || when === null)
|
|
174
|
+
return []
|
|
175
|
+
if (typeof when !== 'object' || Array.isArray(when))
|
|
176
|
+
return null
|
|
177
|
+
const parsed: ModelActionDefinition['when'] = []
|
|
178
|
+
for (const [name, wanted] of Object.entries(when as Record<string, unknown>)) {
|
|
179
|
+
const values = Array.isArray(wanted) ? wanted : [wanted]
|
|
180
|
+
if (!/^[A-Z_]\w*$/i.test(name) || values.length === 0 || !values.every(isValue))
|
|
181
|
+
return null
|
|
182
|
+
parsed.push({ column: column(name), values })
|
|
183
|
+
}
|
|
184
|
+
return parsed
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* The actions a model declares, and what is wrong with the ones it declares
|
|
189
|
+
* badly. A declaration that cannot be read is left out and said so, in words
|
|
190
|
+
* that name it: a button that could only fail is worse than no button.
|
|
191
|
+
*/
|
|
192
|
+
export function modelActionDefinitions(Model: any): { actions: ModelActionDefinition[], problems: string[] } {
|
|
193
|
+
const declared = Model?.dashboard?.actions
|
|
194
|
+
if (declared === undefined || declared === null)
|
|
195
|
+
return { actions: [], problems: [] }
|
|
196
|
+
if (!Array.isArray(declared))
|
|
197
|
+
return { actions: [], problems: ['dashboard.actions is not a list'] }
|
|
198
|
+
|
|
199
|
+
const actions: ModelActionDefinition[] = []
|
|
200
|
+
const problems: string[] = []
|
|
201
|
+
for (const [index, entry] of declared.entries()) {
|
|
202
|
+
const name = typeof entry?.name === 'string' ? entry.name.trim() : ''
|
|
203
|
+
const called = name ? `'${name}'` : `actions[${index}]`
|
|
204
|
+
if (!/^[a-z][a-z\d]*(?:-[a-z\d]+)*$/i.test(name)) {
|
|
205
|
+
problems.push(name ? `${called} is not a usable name: letters and digits, in camelCase or kebab-case` : `${called} has no name`)
|
|
206
|
+
continue
|
|
207
|
+
}
|
|
208
|
+
if (actions.some(action => action.name === name)) {
|
|
209
|
+
problems.push(`${called} is declared twice`)
|
|
210
|
+
continue
|
|
211
|
+
}
|
|
212
|
+
const handler = typeof entry.action === 'string' ? entry.action.trim().replace(/\.ts$/, '') : ''
|
|
213
|
+
if (!/^Actions\/[\w/-]+$/.test(handler)) {
|
|
214
|
+
problems.push(`${called} does not name an action to run: \`action\` is its path under app/, as in 'Actions/Orders/ShipOrderAction'`)
|
|
215
|
+
continue
|
|
216
|
+
}
|
|
217
|
+
const when = conditions(entry.when)
|
|
218
|
+
if (!when) {
|
|
219
|
+
problems.push(`${called} has a \`when\` that cannot be read: it maps a field to the value, or list of values, a record must hold`)
|
|
220
|
+
continue
|
|
221
|
+
}
|
|
222
|
+
// How the action's input is asked for, in the words `dashboard.fields` uses.
|
|
223
|
+
const asking: Record<string, FieldAsking> = {}
|
|
224
|
+
if (entry.fields !== undefined) {
|
|
225
|
+
if (!entry.fields || typeof entry.fields !== 'object' || Array.isArray(entry.fields)) {
|
|
226
|
+
problems.push(`${called} has \`fields\` that is not an object keyed by the input's name`)
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
for (const [field, settings] of Object.entries(entry.fields as Record<string, unknown>)) {
|
|
230
|
+
if (settings && typeof settings === 'object' && !Array.isArray(settings))
|
|
231
|
+
asking[field] = readFieldAsking(`${called} field '${field}'`, settings as Record<string, unknown>, problems, ACTION_INPUTS)
|
|
232
|
+
else
|
|
233
|
+
problems.push(`${called} field '${field}' is not an object of settings`)
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
const on: unknown[] = entry.on === undefined ? [...DEFAULT_PLACES] : Array.isArray(entry.on) ? entry.on : [entry.on]
|
|
238
|
+
const places = PLACES.filter(place => on.includes(place))
|
|
239
|
+
if (places.length === 0 || places.length !== on.length) {
|
|
240
|
+
problems.push(`${called} lists a place under \`on\` that is not 'record', 'row' or 'bulk'`)
|
|
241
|
+
continue
|
|
242
|
+
}
|
|
243
|
+
actions.push({
|
|
244
|
+
name,
|
|
245
|
+
label: typeof entry.label === 'string' && entry.label.trim() ? entry.label.trim() : modelActionLabel(name),
|
|
246
|
+
icon: typeof entry.icon === 'string' && /^i-[\w-]+$/.test(entry.icon.trim()) ? entry.icon.trim() : '',
|
|
247
|
+
confirm: typeof entry.confirm === 'string' ? entry.confirm.trim() : '',
|
|
248
|
+
destructive: entry.destructive === true,
|
|
249
|
+
places,
|
|
250
|
+
fields: [],
|
|
251
|
+
handler,
|
|
252
|
+
when,
|
|
253
|
+
asking,
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
return { actions, problems }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function holds(stored: unknown, wanted: ModelActionValue): boolean {
|
|
260
|
+
if (wanted === null)
|
|
261
|
+
return stored === null || stored === undefined || stored === ''
|
|
262
|
+
if (typeof wanted === 'boolean')
|
|
263
|
+
return (stored === true || stored === 1 || stored === '1' || stored === 'true') === wanted
|
|
264
|
+
return stored !== null && stored !== undefined && String(stored) === String(wanted)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Whether a record is one the action is for: every `when` column holds one of its values. */
|
|
268
|
+
export function modelActionApplies(action: ModelActionDefinition, row: unknown): boolean {
|
|
269
|
+
return action.when.every(condition => condition.values.some(wanted => holds(safeGet(row, condition.column, null), wanted)))
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** What the page is told: the button, without the file it runs or the rule that narrows it. */
|
|
273
|
+
export function publicModelAction(action: ModelActionDefinition): ModelCustomAction {
|
|
274
|
+
const { handler: _handler, when: _when, asking: _asking, ...shown } = action
|
|
275
|
+
return shown
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
type ResolveHandler = (handler: string) => Promise<unknown>
|
|
279
|
+
|
|
280
|
+
/** What an action's input is called when the model does not say. */
|
|
281
|
+
function describeUnaskable(names: string[]): string {
|
|
282
|
+
return names.map(name => `'${name}'`).join(', ')
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** What loading an action came to: what it takes, or why it could not be loaded. */
|
|
286
|
+
type Loaded = { validations: unknown } | { failure: string }
|
|
287
|
+
|
|
288
|
+
const loadable = new Map<string, Promise<Loaded>>()
|
|
289
|
+
const warned = new Set<string>()
|
|
290
|
+
|
|
291
|
+
/** Load the action as the router would, and say what it validates. */
|
|
292
|
+
async function resolveWithRouter(handler: string): Promise<{ validations?: unknown }> {
|
|
293
|
+
const { resolveActionValidations } = await import('@stacksjs/router')
|
|
294
|
+
return { validations: await resolveActionValidations(handler) }
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* The actions a model offers: the ones it declares that can be read and whose
|
|
299
|
+
* action can be loaded. The rest are said once, by name, with what to change.
|
|
300
|
+
*
|
|
301
|
+
* Each comes back with the form its input is asked for in, read from the
|
|
302
|
+
* action's own `validations`.
|
|
303
|
+
*
|
|
304
|
+
* Loading is checked when the list is drawn, not when the button is pressed.
|
|
305
|
+
* A handler string is not checked by the compiler, so a renamed or mistyped
|
|
306
|
+
* action would otherwise be a button every operator can press and nobody can
|
|
307
|
+
* use, found the first time someone needed it.
|
|
308
|
+
*/
|
|
309
|
+
export async function modelActions(Model: any, modelName: string, resolve: ResolveHandler = resolveWithRouter): Promise<ModelActionDefinition[]> {
|
|
310
|
+
const { actions, problems } = modelActionDefinitions(Model)
|
|
311
|
+
const offered: ModelActionDefinition[] = []
|
|
312
|
+
for (const action of actions) {
|
|
313
|
+
const key = `${modelName}:${action.name}:${action.handler}`
|
|
314
|
+
let checked = loadable.get(key)
|
|
315
|
+
if (!checked) {
|
|
316
|
+
checked = resolve(action.handler).then(
|
|
317
|
+
resolved => ({ validations: (resolved as { validations?: unknown } | null | undefined)?.validations }),
|
|
318
|
+
error => ({ failure: error instanceof Error ? error.message : String(error) }),
|
|
319
|
+
)
|
|
320
|
+
loadable.set(key, checked)
|
|
321
|
+
}
|
|
322
|
+
const loaded = await checked
|
|
323
|
+
if ('failure' in loaded) {
|
|
324
|
+
problems.push(`'${action.name}' names ${action.handler}, which could not be loaded (${loaded.failure})`)
|
|
325
|
+
continue
|
|
326
|
+
}
|
|
327
|
+
// What the action takes, as a form. One that requires what no form can
|
|
328
|
+
// give is a button that could only be refused.
|
|
329
|
+
const { fields, unaskable, ignored } = modelActionFields(loaded.validations, action.asking)
|
|
330
|
+
if (unaskable.length > 0) {
|
|
331
|
+
problems.push(`'${action.name}' runs ${action.handler}, which requires ${describeUnaskable(unaskable)}: ${unaskable.length === 1 ? 'a value' : 'values'} a form cannot give (a list, a structure, a file or a password)`)
|
|
332
|
+
continue
|
|
333
|
+
}
|
|
334
|
+
// The action is still offered; only that setting is.
|
|
335
|
+
for (const note of ignored)
|
|
336
|
+
problems.push(`'${action.name}' ${note}`)
|
|
337
|
+
offered.push({ ...action, fields })
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
for (const problem of problems) {
|
|
341
|
+
const key = `${modelName}:${problem}`
|
|
342
|
+
if (warned.has(key))
|
|
343
|
+
continue
|
|
344
|
+
warned.add(key)
|
|
345
|
+
console.warn(`[dashboard] ${modelName} dashboard.actions: ${problem}. It is left out.`)
|
|
346
|
+
}
|
|
347
|
+
return offered
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** A dashboard path an action may send the page to afterwards. Never an outside address. */
|
|
351
|
+
function dashboardPath(value: unknown): string {
|
|
352
|
+
return typeof value === 'string' && /^\/(?!\/)[\w\-/]*(?:\?[\w\-=&%.]*)?$/.test(value) ? value : ''
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* What the page is told came of running an action, from the response its own
|
|
357
|
+
* route would have sent.
|
|
358
|
+
*
|
|
359
|
+
* A refusal keeps its status and its words, so the page can say why. A
|
|
360
|
+
* success is reduced to the two things the page acts on: `message`, shown as
|
|
361
|
+
* the confirmation, and `redirect`, a dashboard path to open (the copy that
|
|
362
|
+
* "Duplicate" made). Whatever else the action answers with is its API's
|
|
363
|
+
* business and is not passed along.
|
|
364
|
+
*/
|
|
365
|
+
export async function modelActionOutcome(result: Response, label: string): Promise<Response | { ok: true, message: string, redirect: string }> {
|
|
366
|
+
const text = await result.text().catch(() => '')
|
|
367
|
+
let body: Record<string, unknown> = {}
|
|
368
|
+
let json = false
|
|
369
|
+
try {
|
|
370
|
+
const parsed = text ? JSON.parse(text) as unknown : null
|
|
371
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
372
|
+
body = parsed as Record<string, unknown>
|
|
373
|
+
json = true
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
catch {}
|
|
377
|
+
|
|
378
|
+
if (result.status >= 400) {
|
|
379
|
+
const said = [body.message, body.error].find(value => typeof value === 'string' && value.trim()) as string | undefined
|
|
380
|
+
// A page of HTML or a stack trace is not a sentence for a toast.
|
|
381
|
+
const plain = !json && text.length <= 300 && !text.trimStart().startsWith('<') ? text.trim() : ''
|
|
382
|
+
return response.json({
|
|
383
|
+
message: said || plain || `${label} was refused.`,
|
|
384
|
+
...(body.errors && typeof body.errors === 'object' ? { errors: body.errors } : {}),
|
|
385
|
+
}, result.status as ResponseStatus)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
return {
|
|
389
|
+
ok: true,
|
|
390
|
+
message: typeof body.message === 'string' ? body.message.trim() : '',
|
|
391
|
+
redirect: dashboardPath(body.redirect),
|
|
392
|
+
}
|
|
393
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a model says about how one of its fields is shown and asked for in
|
|
3
|
+
* the dashboard: its heading, the help under its input, how its value reads
|
|
4
|
+
* ("$12.00" for 1200, "1.5 KB" for 1536) and which text input it gets.
|
|
5
|
+
*
|
|
6
|
+
* A model's definition says what a field is. It cannot say that `amount` is
|
|
7
|
+
* money and `sizeBytes` is a size: both are numbers. `dashboard.fields` is
|
|
8
|
+
* where the model says so, one field at a time, and everything it leaves out
|
|
9
|
+
* stays derived. This file only reads the declaration; `./model-write` is
|
|
10
|
+
* what applies it, since that is where a field's kind and columns are known.
|
|
11
|
+
*/
|
|
12
|
+
import { belongsToRelations } from './model-relations'
|
|
13
|
+
|
|
14
|
+
/** How a stored value is shown. */
|
|
15
|
+
export const MODEL_FIELD_FORMATS = ['badge', 'bytes', 'code', 'date', 'datetime', 'duration', 'image', 'link', 'money', 'number', 'percent', 'text'] as const
|
|
16
|
+
export type ModelFieldFormat = typeof MODEL_FIELD_FORMATS[number]
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The inputs a field of text can be given instead of the one derived for it.
|
|
20
|
+
* All of them type or produce text: a line, a tall box, an address, Markdown
|
|
21
|
+
* with a toolbar and a preview, and a file chooser whose value is the
|
|
22
|
+
* address the chosen file was stored at.
|
|
23
|
+
*/
|
|
24
|
+
export const MODEL_FIELD_INPUTS = ['email', 'longtext', 'markdown', 'text', 'upload', 'url'] as const
|
|
25
|
+
export type ModelFieldInput = typeof MODEL_FIELD_INPUTS[number]
|
|
26
|
+
|
|
27
|
+
/** A format, with what it needs to be read: the currency of an amount, the unit of a duration. */
|
|
28
|
+
export interface ModelFieldDisplay {
|
|
29
|
+
format: ModelFieldFormat
|
|
30
|
+
/** For `money`: the ISO code every amount is in. */
|
|
31
|
+
currency?: string
|
|
32
|
+
/** For `money`: the column that holds each row's own ISO code. Wins over `currency` for a row that has one. */
|
|
33
|
+
currencyColumn?: string
|
|
34
|
+
/** For `duration`: what the stored number counts. Milliseconds unless said. */
|
|
35
|
+
unit?: 'ms' | 's'
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ModelFieldOverride {
|
|
39
|
+
/** The name as the model wrote it, for a message about it. */
|
|
40
|
+
declared: string
|
|
41
|
+
label?: string
|
|
42
|
+
help?: string
|
|
43
|
+
display?: ModelFieldDisplay
|
|
44
|
+
input?: ModelFieldInput
|
|
45
|
+
/** For `upload`: the kinds of file that may be chosen. */
|
|
46
|
+
accept?: string
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function snakeCase(name: string): string {
|
|
50
|
+
return name
|
|
51
|
+
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
|
|
52
|
+
.replace(/[\s-]+/g, '_')
|
|
53
|
+
.toLowerCase()
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const parsed = new WeakMap<object, { fields: Record<string, ModelFieldOverride>, problems: string[] }>()
|
|
57
|
+
|
|
58
|
+
/** How a field is asked for in a form: what it is called, the help under it, the text input it gets. */
|
|
59
|
+
export interface FieldAsking {
|
|
60
|
+
label?: string
|
|
61
|
+
help?: string
|
|
62
|
+
input?: ModelFieldInput
|
|
63
|
+
/** For `upload`: the kinds of file that may be chosen, as a file input's `accept` spells them. */
|
|
64
|
+
accept?: string
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** One entry of an `accept`: a type (`image/png`), a family (`image/*`) or an extension (`.pdf`). */
|
|
68
|
+
const ACCEPT_ENTRY = /^(?:[a-z]+\/(?:\*|[\w.+-]+)|\.[a-z\d]+)$/i
|
|
69
|
+
|
|
70
|
+
/** Whether every kind an `accept` names is an image. */
|
|
71
|
+
export function acceptsOnlyImages(accept: string | undefined): boolean {
|
|
72
|
+
const entries = (accept ?? '').split(',').map(entry => entry.trim().toLowerCase()).filter(Boolean)
|
|
73
|
+
return entries.length > 0 && entries.every(entry => entry.startsWith('image/') || /^\.(?:avif|gif|jpe?g|png|svg|webp)$/.test(entry))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Read the settings that say how a field is asked for. The same three for a
|
|
78
|
+
* model's own field (`dashboard.fields`) and for a field of an action's
|
|
79
|
+
* input (`dashboard.actions[].fields`), so they are spelled the same way in
|
|
80
|
+
* both. One that cannot be read is dropped on its own and said so.
|
|
81
|
+
*/
|
|
82
|
+
export function readFieldAsking(called: string, settings: Record<string, unknown>, problems: string[], inputs: readonly ModelFieldInput[] = MODEL_FIELD_INPUTS): FieldAsking {
|
|
83
|
+
const asking: FieldAsking = {}
|
|
84
|
+
if (settings.label !== undefined) {
|
|
85
|
+
if (typeof settings.label === 'string' && settings.label.trim())
|
|
86
|
+
asking.label = settings.label.trim()
|
|
87
|
+
else
|
|
88
|
+
problems.push(`${called} has a label that is not text`)
|
|
89
|
+
}
|
|
90
|
+
if (settings.help !== undefined) {
|
|
91
|
+
if (typeof settings.help === 'string' && settings.help.trim())
|
|
92
|
+
asking.help = settings.help.trim()
|
|
93
|
+
else
|
|
94
|
+
problems.push(`${called} has help that is not text`)
|
|
95
|
+
}
|
|
96
|
+
if (settings.input !== undefined) {
|
|
97
|
+
if (inputs.includes(settings.input as ModelFieldInput))
|
|
98
|
+
asking.input = settings.input as ModelFieldInput
|
|
99
|
+
else
|
|
100
|
+
problems.push(`${called} asks for an input the dashboard does not have: '${String(settings.input)}' (it has ${list(inputs)})`)
|
|
101
|
+
}
|
|
102
|
+
if (settings.accept !== undefined) {
|
|
103
|
+
const entries = typeof settings.accept === 'string' ? settings.accept.split(',').map(entry => entry.trim()).filter(Boolean) : []
|
|
104
|
+
if (asking.input !== 'upload')
|
|
105
|
+
problems.push(`${called} names the files it accepts, which only \`input: 'upload'\` reads`)
|
|
106
|
+
else if (entries.length > 0 && entries.every(entry => ACCEPT_ENTRY.test(entry)))
|
|
107
|
+
asking.accept = entries.join(',')
|
|
108
|
+
else
|
|
109
|
+
problems.push(`${called} names the files it accepts in a way that cannot be read: a list such as 'image/*' or 'application/pdf,.csv'`)
|
|
110
|
+
}
|
|
111
|
+
return asking
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function list(values: readonly string[]): string {
|
|
115
|
+
return values.join(', ')
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The model's `dashboard.fields`, by column, with what is wrong with the
|
|
120
|
+
* parts it declares badly.
|
|
121
|
+
*
|
|
122
|
+
* A name is an attribute (`createdAt`), its column (`created_at`), or a
|
|
123
|
+
* `belongsTo` (`team` for `team_id`), as in `dashboard.columns`. A setting
|
|
124
|
+
* that cannot be read is dropped on its own and said so: a misspelled format
|
|
125
|
+
* does not cost the field its heading.
|
|
126
|
+
*/
|
|
127
|
+
export function modelFieldOverrides(Model: any): { fields: Record<string, ModelFieldOverride>, problems: string[] } {
|
|
128
|
+
const cached = Model && (typeof Model === 'object' || typeof Model === 'function') ? parsed.get(Model) : undefined
|
|
129
|
+
if (cached)
|
|
130
|
+
return cached
|
|
131
|
+
|
|
132
|
+
const fields: Record<string, ModelFieldOverride> = {}
|
|
133
|
+
const problems: string[] = []
|
|
134
|
+
const declared = Model?.dashboard?.fields
|
|
135
|
+
const result = { fields, problems }
|
|
136
|
+
if (declared === undefined || declared === null)
|
|
137
|
+
return result
|
|
138
|
+
if (typeof declared !== 'object' || Array.isArray(declared)) {
|
|
139
|
+
problems.push('dashboard.fields is not an object keyed by field name')
|
|
140
|
+
return result
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const relations = belongsToRelations(Model)
|
|
144
|
+
for (const [name, settings] of Object.entries(declared as Record<string, any>)) {
|
|
145
|
+
const called = `'${name}'`
|
|
146
|
+
if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
|
|
147
|
+
problems.push(`${called} is not an object of settings`)
|
|
148
|
+
continue
|
|
149
|
+
}
|
|
150
|
+
const own = snakeCase(name)
|
|
151
|
+
const relation = relations.find(candidate => candidate.column === own || candidate.column === `${own}_id` || snakeCase(candidate.model) === own)
|
|
152
|
+
const override: ModelFieldOverride = { declared: name, ...readFieldAsking(called, settings, problems) }
|
|
153
|
+
|
|
154
|
+
if (settings.format !== undefined) {
|
|
155
|
+
if (MODEL_FIELD_FORMATS.includes(settings.format))
|
|
156
|
+
override.display = { format: settings.format }
|
|
157
|
+
else
|
|
158
|
+
problems.push(`${called} asks for a format the dashboard does not have: '${String(settings.format)}' (it has ${list(MODEL_FIELD_FORMATS)})`)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const display = override.display
|
|
162
|
+
if (settings.currency !== undefined) {
|
|
163
|
+
if (display?.format !== 'money')
|
|
164
|
+
problems.push(`${called} names a currency, which only \`format: 'money'\` reads`)
|
|
165
|
+
else if (typeof settings.currency === 'string' && /^[A-Z]{3}$/i.test(settings.currency.trim()))
|
|
166
|
+
display.currency = settings.currency.trim().toUpperCase()
|
|
167
|
+
else
|
|
168
|
+
problems.push(`${called} names a currency that is not a three-letter code: '${String(settings.currency)}'`)
|
|
169
|
+
}
|
|
170
|
+
if (settings.currencyField !== undefined) {
|
|
171
|
+
if (display?.format !== 'money')
|
|
172
|
+
problems.push(`${called} names a currency field, which only \`format: 'money'\` reads`)
|
|
173
|
+
else if (typeof settings.currencyField === 'string' && /^[A-Z_]\w*$/i.test(settings.currencyField.trim()))
|
|
174
|
+
display.currencyColumn = snakeCase(settings.currencyField.trim())
|
|
175
|
+
else
|
|
176
|
+
problems.push(`${called} names a currency field that is not a field name`)
|
|
177
|
+
}
|
|
178
|
+
if (settings.unit !== undefined) {
|
|
179
|
+
if (display?.format !== 'duration')
|
|
180
|
+
problems.push(`${called} names a unit, which only \`format: 'duration'\` reads`)
|
|
181
|
+
else if (settings.unit === 'ms' || settings.unit === 's')
|
|
182
|
+
display.unit = settings.unit
|
|
183
|
+
else
|
|
184
|
+
problems.push(`${called} names a unit that is not 'ms' or 's': '${String(settings.unit)}'`)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// An uploaded file's address is somewhere to look: shown as the picture
|
|
188
|
+
// it is when only images may be chosen, as a link otherwise.
|
|
189
|
+
if (override.input === 'upload' && !override.display && settings.format === undefined)
|
|
190
|
+
override.display = { format: acceptsOnlyImages(override.accept) ? 'image' : 'link' }
|
|
191
|
+
|
|
192
|
+
fields[relation ? relation.column : own] = override
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (Model && (typeof Model === 'object' || typeof Model === 'function'))
|
|
196
|
+
parsed.set(Model, result)
|
|
197
|
+
return result
|
|
198
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fields a model's form asks for, as the dashboard can actually draw
|
|
3
|
+
* them.
|
|
4
|
+
*
|
|
5
|
+
* A `belongsTo` is asked for by a picker that lists the related model's
|
|
6
|
+
* records. That only works when the dashboard can reach that model: one
|
|
7
|
+
* whose feature is off, or that is kept out of the dashboard, has no list to
|
|
8
|
+
* pick from, and its field stays the plain id it is. A model's own pages and
|
|
9
|
+
* a panel that edits its rows on another record's page both ask through
|
|
10
|
+
* here, so a field is not a picker on one and a number box on the other.
|
|
11
|
+
*/
|
|
12
|
+
import type { ModelRelation } from './model-relations'
|
|
13
|
+
import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
|
|
14
|
+
import { belongsToRelations } from './model-relations'
|
|
15
|
+
import { type ModelCreateField, modelColumnLabel, modelCreateFields } from './model-write'
|
|
16
|
+
|
|
17
|
+
/** The records a model points at that the dashboard can list, and so name and pick. */
|
|
18
|
+
export async function reachableRelations(Model: any): Promise<ModelRelation[]> {
|
|
19
|
+
const reachable: ModelRelation[] = []
|
|
20
|
+
for (const relation of belongsToRelations(Model)) {
|
|
21
|
+
const related = await resolveDashboardModel(relation.model).catch(() => null)
|
|
22
|
+
if (related && typeof related.where === 'function')
|
|
23
|
+
reachable.push(relation)
|
|
24
|
+
}
|
|
25
|
+
return reachable
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The model's form fields, with a relation the dashboard cannot reach asked for as its id. */
|
|
29
|
+
export function modelFormFields(Model: any, reachable: ReadonlySet<string>): ModelCreateField[] {
|
|
30
|
+
return modelCreateFields(Model).map((field) => {
|
|
31
|
+
if (field.type !== 'relation' || reachable.has(field.relation?.model ?? ''))
|
|
32
|
+
return field
|
|
33
|
+
const { relation: _unreachable, ...plain } = field
|
|
34
|
+
return { ...plain, type: 'number', label: modelColumnLabel(Model, field.name) }
|
|
35
|
+
})
|
|
36
|
+
}
|