@stacksjs/defaults 0.75.613 → 0.75.615

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.
@@ -0,0 +1,188 @@
1
+ /**
2
+ * One row created, edited or deleted from the dashboard, as an outcome
3
+ * rather than a response.
4
+ *
5
+ * The create, edit and delete endpoints each answer for one row. Saving a
6
+ * record and its related rows together runs the same steps several times
7
+ * inside one transaction, and has to stop at the first refusal and say where
8
+ * it was. So the steps live here, each returning what happened, and every
9
+ * endpoint turns that into its answer the same way (`rowRefusalResponse`).
10
+ * Every rule a single save has applies to each row of a combined one.
11
+ */
12
+ import type { ResponseStatus } from '@stacksjs/bun-router'
13
+ import type { RequestInstance } from '@stacksjs/types'
14
+ import { eraseSubject, GDPR_SUBJECT_MODEL, isUniqueViolation, ModelValidationError, toSnakeCaseKeys } from '@stacksjs/orm'
15
+ import { response } from '@stacksjs/router'
16
+ import { dashboardOperationalError } from '../dashboard-response'
17
+ import { destroyModelRecord } from './model-destroy'
18
+ import { missingRelationErrors } from './model-relations'
19
+ import { planSwitches, requestedSwitches, storedSwitches } from './model-switches'
20
+ import type { ResolvedModel } from './model-write'
21
+ import { duplicateFieldErrors, humanizeIdentifier, isAccountModel, prepareModelFields } from './model-write'
22
+
23
+ /** Why a row was not written: what the visitor is told, and for a failure, what went wrong. */
24
+ export interface RowRefusal {
25
+ ok: false
26
+ status: ResponseStatus
27
+ message: string
28
+ /** The model's own words, field by field. */
29
+ errors?: Record<string, string[]>
30
+ /** A failure of the server rather than of the input: logged, and answered as one. */
31
+ cause?: unknown
32
+ /** Where it failed, for the log line. Set on a failure, never on a refusal. */
33
+ where?: string
34
+ }
35
+
36
+ export type RowWrite<T> = ({ ok: true } & T) | RowRefusal
37
+
38
+ function refused(status: ResponseStatus, message: string, errors?: Record<string, string[]>): RowRefusal {
39
+ return { ok: false, status, message, ...(errors ? { errors } : {}) }
40
+ }
41
+
42
+ function failed(cause: unknown, message: string, where: string): RowRefusal {
43
+ return { ok: false, status: 500, message, cause, where }
44
+ }
45
+
46
+ /** The refusals a person can act on, read out of an error a write threw. */
47
+ function fieldRefusal(resolved: ResolvedModel, error: unknown, columns: string[], unique: boolean): RowRefusal | null {
48
+ // The model's own rules rejected the row: the caller's mistake, named
49
+ // field by field, not a server failure (stacksjs/stacks#3007).
50
+ if (error instanceof ModelValidationError)
51
+ return refused(422, 'Validation failed.', error.errors)
52
+ // A value another row already holds, on a field the model marks unique
53
+ // (a user's email). The person can fix that, so it is named on the field
54
+ // like any other rule, not reported as a failed save.
55
+ if (unique && isUniqueViolation(error)) {
56
+ const errors = duplicateFieldErrors(resolved.Model, columns)
57
+ if (Object.keys(errors).length > 0)
58
+ return refused(422, 'Validation failed.', errors)
59
+ }
60
+ // A record this one points at was deleted while the form was open. The
61
+ // person can pick another, so it is said on that field.
62
+ const missing = missingRelationErrors(resolved.Model, error, columns, humanizeIdentifier)
63
+ if (Object.keys(missing).length > 0)
64
+ return refused(422, 'Validation failed.', missing)
65
+ return null
66
+ }
67
+
68
+ /**
69
+ * The fields a form sent. Edits arrive nested under `fields`: the router's
70
+ * input bag merges the body with route params and query, so a flat payload
71
+ * would pick up the `slug` and `id` from the URL and try to write them as
72
+ * columns, and `slug` is a real column on plenty of models.
73
+ */
74
+ export function formFields(raw: unknown): Record<string, unknown> {
75
+ return (raw && typeof raw === 'object' && !Array.isArray(raw)) ? raw as Record<string, unknown> : {}
76
+ }
77
+
78
+ /** Create one row. `fixed` are columns set by where it is created, not by the form: a related row's link back. */
79
+ export async function storeModelRow(resolved: ResolvedModel, body: Record<string, unknown>, fixed: Record<string, unknown> = {}): Promise<RowWrite<{ id: unknown }>> {
80
+ const { data, errors } = prepareModelFields(resolved.Model, body)
81
+ if (Object.keys(errors).length > 0)
82
+ return refused(422, 'Validation failed.', errors)
83
+ if (Object.keys(data).length === 0)
84
+ return refused(422, 'No fillable fields in the request body.')
85
+
86
+ const values = { ...toSnakeCaseKeys(data), ...fixed }
87
+ try {
88
+ const row = await resolved.Model.create(values)
89
+ return { ok: true, id: row?.id ?? row?.attributes?.id ?? null }
90
+ }
91
+ catch (error) {
92
+ return fieldRefusal(resolved, error, Object.keys(values), false)
93
+ ?? failed(error, 'The model record could not be created.', 'ModelStoreAction')
94
+ }
95
+ }
96
+
97
+ /** Edit one row with the fields that changed, and the switches a trait keeps for itself. */
98
+ export async function updateModelRow(resolved: ResolvedModel, id: number, body: Record<string, unknown>): Promise<RowWrite<{ id: number, changed: string[] }>> {
99
+ const prepared = prepareModelFields(resolved.Model, body, true)
100
+ if (Object.keys(prepared.errors).length > 0)
101
+ return refused(422, 'Validation failed.', prepared.errors)
102
+ const changes = toSnakeCaseKeys(prepared.data)
103
+ // What a trait keeps for itself (a confirmed email, two-factor) is asked
104
+ // for as a switch and changed by the trait's own function.
105
+ const { asked, errors: unreadable } = requestedSwitches(resolved.Model, body)
106
+ if (Object.keys(unreadable).length > 0)
107
+ return refused(422, 'Validation failed.', unreadable)
108
+ if (Object.keys(changes).length === 0 && asked.length === 0)
109
+ return refused(422, 'No writable fields in the request body.')
110
+
111
+ try {
112
+ const row = await resolved.Model.find(id)
113
+ if (!row)
114
+ return refused(404, `${resolved.modelName} ${id} not found.`)
115
+ // Refused before anything is written: a switch that cannot be turned
116
+ // that way refuses the whole save, like any other field's rule.
117
+ const { turning, errors } = planSwitches(resolved.Model, asked, asked.length > 0 ? await storedSwitches(resolved.Model, id) : {})
118
+ if (Object.keys(errors).length > 0)
119
+ return refused(422, 'Validation failed.', errors)
120
+ if (Object.keys(changes).length > 0)
121
+ await resolved.Model.update(id, changes)
122
+ for (const request of turning)
123
+ await request.switch.set(id, request.on)
124
+ return { ok: true, id, changed: [...Object.keys(changes), ...turning.map(request => request.switch.column)] }
125
+ }
126
+ catch (error) {
127
+ return fieldRefusal(resolved, error, Object.keys(changes), true)
128
+ ?? failed(error, 'The model record could not be updated.', 'ModelUpdateAction')
129
+ }
130
+ }
131
+
132
+ /** The id of the account making this request, when there is one. */
133
+ export async function requestAccountId(request: RequestInstance): Promise<number | null> {
134
+ try {
135
+ const id = Number((await request.user())?.id)
136
+ return Number.isSafeInteger(id) && id > 0 ? id : null
137
+ }
138
+ catch {
139
+ // The local dashboard runs without a session, and then there is no
140
+ // account to protect.
141
+ return null
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Delete one row through the model, so soft deletes, observers and cascades
147
+ * apply. A user other records still point at is anonymized instead: see
148
+ * `./model-destroy`. `viewer` is the account making the request, which is
149
+ * not deleted from here.
150
+ */
151
+ export async function destroyModelRow(resolved: ResolvedModel, id: number, viewer: number | null): Promise<RowWrite<{ id: number, anonymized: boolean }>> {
152
+ // Deleting the account you are signed in with ends your own access in the
153
+ // middle of using it, and for the last admin there is no way back in.
154
+ if (isAccountModel(resolved.Model) && viewer === id)
155
+ return refused(409, 'You are signed in with this account, so it cannot be deleted from here. Ask another admin to remove it.')
156
+
157
+ const result = await destroyModelRecord(id, {
158
+ Model: resolved.Model,
159
+ actor: viewer === null ? 'dashboard' : `dashboard:user:${viewer}`,
160
+ erase: async (subject, actor) => {
161
+ const erased = await eraseSubject(subject, { actor })
162
+ const own = erased.changes.find(change => change.model === GDPR_SUBJECT_MODEL)
163
+ return { action: (own?.action ?? 'keep') as 'anonymize' | 'delete' | 'keep' }
164
+ },
165
+ })
166
+
167
+ if (result.ok)
168
+ return { ok: true, id, anonymized: result.outcome === 'anonymized' }
169
+ if (result.reason === 'missing')
170
+ return refused(404, `${resolved.modelName} ${id} not found.`)
171
+ // The database kept the row because others still point at it. Nothing
172
+ // failed: the answer is to deal with those records first, and saying
173
+ // "could not be deleted" sent people to the server logs for it.
174
+ if (result.reason === 'referenced')
175
+ return refused(409, `This ${resolved.modelName.toLowerCase()} cannot be deleted while other records still refer to it. Remove or reassign those records first.`)
176
+ // Erasure is one transaction and repeating it changes nothing it already
177
+ // changed, so "try again" is a real answer here.
178
+ if (result.reason === 'erasure-failed')
179
+ return failed(result.cause, 'Other records still refer to this user, and anonymizing the account did not finish. Try again: repeating it is safe.', 'ModelDestroyAction.erase')
180
+ return failed(result.cause, 'The model record could not be deleted.', 'ModelDestroyAction')
181
+ }
182
+
183
+ /** A refusal as an endpoint answers it: the visitor's words, or a logged failure of the server. */
184
+ export function rowRefusalResponse(refusal: RowRefusal): Response {
185
+ if (refusal.where)
186
+ return dashboardOperationalError(refusal.cause, refusal.message, refusal.where, refusal.status)
187
+ return response.json({ message: refusal.message, ...(refusal.errors ? { errors: refusal.errors } : {}) }, refusal.status)
188
+ }
@@ -28,12 +28,18 @@ export interface ApiRequestOptions {
28
28
  export class DashboardApiError extends Error {
29
29
  readonly status: number
30
30
  readonly fields?: Record<string, string>
31
+ /**
32
+ * The answer's body as it came, for a caller that needs more of it than the
33
+ * message and the fields: where a combined save was refused, say.
34
+ */
35
+ readonly body?: unknown
31
36
 
32
- constructor(message: string, status: number, fields?: Record<string, string>) {
37
+ constructor(message: string, status: number, fields?: Record<string, string>, body?: unknown) {
33
38
  super(message)
34
39
  this.name = 'DashboardApiError'
35
40
  this.status = status
36
41
  this.fields = fields
42
+ this.body = body
37
43
  }
38
44
  }
39
45
 
@@ -78,7 +84,7 @@ async function dashboardResponseError(res: Response): Promise<DashboardApiError>
78
84
  const failure = describeResponseError(res.status, payload)
79
85
  if (failure.unexpected)
80
86
  console.error('[dashboard-api] Unexpected request failure:', failure.cause)
81
- return new DashboardApiError(failure.message, res.status, failure.fields)
87
+ return new DashboardApiError(failure.message, res.status, failure.fields, payload)
82
88
  }
83
89
 
84
90
  /**
@@ -104,7 +110,7 @@ export async function dashboardApi<T = unknown>(path: string, options: ApiReques
104
110
  const failure = describeResponseError(res.status, payload as ApiErrorBody | null)
105
111
  if (failure.unexpected)
106
112
  console.error('[dashboard-api] Unexpected request failure:', failure.cause)
107
- throw new DashboardApiError(failure.message, res.status, failure.fields)
113
+ throw new DashboardApiError(failure.message, res.status, failure.fields, payload)
108
114
  }
109
115
 
110
116
  return payload as T
@@ -5,9 +5,9 @@
5
5
  * A selection is acted on one record at a time, each through the endpoint a
6
6
  * single row uses, so every guard a single press has applies to each record
7
7
  * and nothing about an action changes for it. It is not all or nothing and
8
- * does not claim to be (a write through a model takes no part in a
9
- * transaction, stacksjs/stacks#3269): what is reported is what happened, how
10
- * many were done and, for the rest, which and why.
8
+ * does not claim to be: one record refused does not take back the others.
9
+ * What is reported is what happened, how many were done and, for the rest,
10
+ * which and why.
11
11
  */
12
12
  import { DashboardApiError } from './dashboard-api'
13
13
  import type { ModelActionResult, ModelCustomAction, ModelDeleteOutcome } from './dashboard-model-record'
@@ -0,0 +1,122 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+ import type { ModelDrafts } from './dashboard-model-drafts'
3
+ import { modelDraftChangeCount, modelDraftKey, modelDraftListRows, modelDraftPut, modelDraftRemove, modelDraftRestore, modelDraftRowLabel, modelDraftValues, modelRelatedSaveChanges, saveModelRecordWithRelated } from './dashboard-model-drafts'
4
+ import type { ModelRelatedPanel } from './dashboard-model-record'
5
+
6
+ // An order's lines: the panel a record's edit page shows, as the API sends it.
7
+ const lines: ModelRelatedPanel = {
8
+ kind: 'many',
9
+ model: 'OrderLine',
10
+ slug: 'order-line',
11
+ title: 'Order Lines',
12
+ label: 'Order Line',
13
+ foreignKey: 'order_id',
14
+ field: 'orderId',
15
+ total: 2,
16
+ columns: [{ key: 'sku', label: 'SKU', type: 'text' }, { key: 'unit_price', label: 'Unit Price', type: 'text' }],
17
+ rows: [{ id: 10, sku: 'A-1', unit_price: 5 }, { id: 11, sku: 'B-2', unit_price: 9 }],
18
+ canCreate: true,
19
+ canUpdate: true,
20
+ canDestroy: true,
21
+ fields: [
22
+ { name: 'sku', label: 'SKU', type: 'text', required: true },
23
+ { name: 'unitPrice', label: 'Unit Price', type: 'number', required: false },
24
+ ] as never,
25
+ values: { 10: { sku: 'A-1', unit_price: 5 }, 11: { sku: 'B-2', unit_price: 9 } },
26
+ }
27
+
28
+ describe('a record\'s related rows, changed on its edit page', () => {
29
+ it('sends nothing for rows that were only looked at, or edited back to what they were', () => {
30
+ let drafts: ModelDrafts = {}
31
+ expect(modelRelatedSaveChanges([lines], drafts)).toEqual([])
32
+ drafts = modelDraftPut(drafts, lines, '10', { ...modelDraftValues(lines, drafts, '10') })
33
+ expect(modelRelatedSaveChanges([lines], drafts)).toEqual([])
34
+ expect(modelDraftChangeCount([lines], drafts)).toBe(0)
35
+ expect(modelDraftListRows(lines, drafts).map(row => row.state)).toEqual(['kept', 'kept'])
36
+ })
37
+
38
+ it('sends only the fields an edit changed', () => {
39
+ const start = modelDraftValues(lines, {}, '10')
40
+ const drafts = modelDraftPut({}, lines, '10', { ...start, unitPrice: '7' })
41
+ // As the form sends any field: text, which the server reads as its column's type.
42
+ expect(modelRelatedSaveChanges([lines], drafts)).toEqual([{ slug: 'order-line', create: [], update: [{ id: 10, fields: { unitPrice: '7' } }], destroy: [] }])
43
+ const listed = modelDraftListRows(lines, drafts)
44
+ expect(listed[0]).toMatchObject({ key: '10', state: 'edited' })
45
+ // Shown with the value it will be saved with, under the panel's column.
46
+ expect(listed[0]!.values.unit_price).toBe('7')
47
+ })
48
+
49
+ it('adds rows under their own keys, and an added row edited again is one row', () => {
50
+ let drafts: ModelDrafts = {}
51
+ const first = modelDraftKey(drafts, 'order-line')
52
+ drafts = modelDraftPut(drafts, lines, first, { sku: 'C-3', unitPrice: '2' })
53
+ const second = modelDraftKey(drafts, 'order-line')
54
+ expect(second).not.toBe(first)
55
+ drafts = modelDraftPut(drafts, lines, second, { sku: 'D-4', unitPrice: '' })
56
+ drafts = modelDraftPut(drafts, lines, first, { sku: 'C-3b', unitPrice: '2' })
57
+ expect(modelRelatedSaveChanges([lines], drafts)[0]!.create).toEqual([
58
+ { key: first, fields: { sku: 'C-3b', unitPrice: '2' } },
59
+ { key: second, fields: { sku: 'D-4', unitPrice: null } },
60
+ ])
61
+ expect(modelDraftListRows(lines, drafts).map(row => [row.key, row.state])).toEqual([['10', 'kept'], ['11', 'kept'], [first, 'added'], [second, 'added']])
62
+ })
63
+
64
+ it('deletes a listed row and forgets its edit; a row added here is just dropped', () => {
65
+ let drafts = modelDraftPut({}, lines, '11', { sku: 'B-2', unitPrice: '1' })
66
+ drafts = modelDraftRemove(drafts, lines, '11')
67
+ const added = modelDraftKey(drafts, 'order-line')
68
+ drafts = modelDraftPut(drafts, lines, added, { sku: 'E-5', unitPrice: '3' })
69
+ drafts = modelDraftRemove(drafts, lines, added)
70
+ expect(modelRelatedSaveChanges([lines], drafts)).toEqual([{ slug: 'order-line', create: [], update: [], destroy: [11] }])
71
+ expect(modelDraftListRows(lines, drafts).map(row => row.state)).toEqual(['kept', 'removed'])
72
+ drafts = modelDraftRestore(drafts, lines, '11')
73
+ expect(modelRelatedSaveChanges([lines], drafts)).toEqual([])
74
+ })
75
+
76
+ it('names a row by its summary values, or by what it is', () => {
77
+ const [first] = modelDraftListRows(lines, {})
78
+ expect(modelDraftRowLabel(lines, first!)).toBe('A-1 · 5')
79
+ expect(modelDraftRowLabel(lines, { key: 'new-1', state: 'added', values: {} })).toBe('New order line')
80
+ expect(modelDraftRowLabel(lines, { key: '12', state: 'kept', values: {} })).toBe('Order Line #12')
81
+ })
82
+ })
83
+
84
+ describe('saving them with the record', () => {
85
+ async function withFetch<T>(answer: Response, run: (asked: Request[]) => Promise<T>): Promise<T> {
86
+ const original = globalThis.fetch
87
+ const asked: Request[] = []
88
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
89
+ asked.push(new Request(new URL(String(input), 'http://dashboard.test'), init))
90
+ return answer
91
+ }) as typeof fetch
92
+ try {
93
+ return await run(asked)
94
+ }
95
+ finally {
96
+ globalThis.fetch = original
97
+ }
98
+ }
99
+
100
+ it('sends the record\'s fields and the panels\' changes in one request', async () => {
101
+ const related = [{ slug: 'order-line', create: [], update: [], destroy: [11] }]
102
+ const result = await withFetch(Response.json({ ok: true }), async (asked) => {
103
+ const saved = await saveModelRecordWithRelated('order', 3, { status: 'paid' }, related)
104
+ expect(asked).toHaveLength(1)
105
+ expect(asked[0]!.method).toBe('PATCH')
106
+ expect(new URL(asked[0]!.url).pathname).toBe('/api/dashboard/models/order/3/save')
107
+ expect(await asked[0]!.json()).toEqual({ fields: { status: 'paid' }, related })
108
+ return saved
109
+ })
110
+ expect(result).toEqual({ ok: true })
111
+ })
112
+
113
+ it('says where a refusal was, so the page can point at the row', async () => {
114
+ const refusal = Response.json({ message: 'Validation failed.', errors: { unitPrice: ['Unit Price must be at least 1.'] }, at: { operation: 'create', panel: 'order-line', row: 'new-2' } }, { status: 422 })
115
+ const result = await withFetch(refusal, () => saveModelRecordWithRelated('order', 3, {}, [{ slug: 'order-line', create: [{ key: 'new-2', fields: { unitPrice: 0 } }], update: [], destroy: [] }]))
116
+ expect(result.ok).toBe(false)
117
+ if (result.ok)
118
+ return
119
+ expect(result.at).toEqual({ operation: 'create', panel: 'order-line', row: 'new-2' })
120
+ expect(result.errors).toEqual({ unitPrice: ['Unit Price must be at least 1.'] })
121
+ })
122
+ })
@@ -0,0 +1,228 @@
1
+ /**
2
+ * A record's related rows, changed on its edit page and saved with it, all or
3
+ * nothing (stacksjs/stacks#3315).
4
+ *
5
+ * On the edit page a related panel's rows are not written one at a time. Each
6
+ * add, edit and delete is kept as a draft until "Save changes", which sends
7
+ * the record's fields and every panel's drafts in one request
8
+ * (`PATCH /models/{slug}/{id}/save`). The server writes them all in one
9
+ * transaction, or none of them, and says where a refusal was.
10
+ *
11
+ * Everything here is plain data in and out, so the page holds the drafts in
12
+ * one state and each change makes a new one.
13
+ */
14
+ import { DashboardApiError, dashboardApi } from './dashboard-api'
15
+ import type { ModelFormValues, ModelRelatedPanel, ModelWriteFailure } from './dashboard-model-record'
16
+ import { modelFieldColumn, modelFormPayload, modelFormValues, modelPath, modelWriteFailure } from './dashboard-model-record'
17
+
18
+ /** A row added on this page and not saved yet. `key` names it until it has an id. */
19
+ export interface ModelDraftRow {
20
+ key: string
21
+ values: ModelFormValues
22
+ }
23
+
24
+ /** One panel's unsaved changes. */
25
+ export interface ModelPanelDraft {
26
+ added: ModelDraftRow[]
27
+ /** A listed row's values as edited here, by row id. */
28
+ edited: Record<string, ModelFormValues>
29
+ /** The listed rows to delete, by id. */
30
+ removed: string[]
31
+ }
32
+
33
+ /** Every panel's unsaved changes, by panel slug. */
34
+ export type ModelDrafts = Record<string, ModelPanelDraft>
35
+
36
+ /** What one panel asks the save to change, as the endpoint reads it. */
37
+ export interface ModelRelatedChanges {
38
+ slug: string
39
+ create: Array<{ key: string, fields: Record<string, unknown> }>
40
+ update: Array<{ id: number | string, fields: Record<string, unknown> }>
41
+ destroy: Array<number | string>
42
+ }
43
+
44
+ /** Where a combined save was refused: the record's fields, or one row of one panel. */
45
+ export interface ModelSaveLocation {
46
+ operation: 'update' | 'create' | 'destroy'
47
+ panel?: string
48
+ /** A listed row's id, or the key of one added here. */
49
+ row?: string
50
+ }
51
+
52
+ export type ModelSaveFailure = ModelWriteFailure & { at?: ModelSaveLocation }
53
+
54
+ /** How a row of a panel stands on this page. */
55
+ export type ModelDraftState = 'kept' | 'added' | 'edited' | 'removed'
56
+
57
+ /** A row as the edit page lists it: its summary values, how it stands, and what names it. */
58
+ export interface ModelDraftListRow {
59
+ /** The listed row's id, or the key of one added here. */
60
+ key: string
61
+ state: ModelDraftState
62
+ values: Record<string, unknown>
63
+ }
64
+
65
+ const NEW_ROW = 'new-'
66
+
67
+ function panelDraft(drafts: ModelDrafts, slug: string): ModelPanelDraft {
68
+ return drafts[slug] ?? { added: [], edited: {}, removed: [] }
69
+ }
70
+
71
+ function withPanel(drafts: ModelDrafts, slug: string, next: ModelPanelDraft): ModelDrafts {
72
+ return { ...drafts, [slug]: next }
73
+ }
74
+
75
+ /** Whether `key` names a row added here rather than one that is stored. */
76
+ export function modelDraftIsNew(key: string): boolean {
77
+ return key.startsWith(NEW_ROW)
78
+ }
79
+
80
+ /** A key for the next row added to a panel, unique among the ones there. */
81
+ export function modelDraftKey(drafts: ModelDrafts, slug: string): string {
82
+ const taken = new Set(panelDraft(drafts, slug).added.map(row => row.key))
83
+ let index = taken.size + 1
84
+ while (taken.has(`${NEW_ROW}${index}`))
85
+ index++
86
+ return `${NEW_ROW}${index}`
87
+ }
88
+
89
+ /** What a row's form starts from: the values added or edited here, else the row's stored ones. */
90
+ export function modelDraftValues(panel: ModelRelatedPanel, drafts: ModelDrafts, key: string): ModelFormValues {
91
+ const draft = panelDraft(drafts, panel.slug)
92
+ if (modelDraftIsNew(key))
93
+ return { ...(draft.added.find(row => row.key === key)?.values ?? modelFormValues(panel.fields ?? [])) }
94
+ return { ...(draft.edited[key] ?? modelDraftStored(panel, key)) }
95
+ }
96
+
97
+ /** A listed row's values as they are stored, in the form's shape. */
98
+ export function modelDraftStored(panel: ModelRelatedPanel, key: string): ModelFormValues {
99
+ return modelFormValues(panel.fields ?? [], panel.values?.[key] ?? {})
100
+ }
101
+
102
+ /** Keep a row's form: a new row added, or a row's values changed, whether it was listed or added here. */
103
+ export function modelDraftPut(drafts: ModelDrafts, panel: ModelRelatedPanel, key: string, values: ModelFormValues): ModelDrafts {
104
+ const draft = panelDraft(drafts, panel.slug)
105
+ if (modelDraftIsNew(key)) {
106
+ const added = draft.added.some(row => row.key === key)
107
+ ? draft.added.map(row => row.key === key ? { key, values } : row)
108
+ : [...draft.added, { key, values }]
109
+ return withPanel(drafts, panel.slug, { ...draft, added })
110
+ }
111
+ return withPanel(drafts, panel.slug, { ...draft, edited: { ...draft.edited, [key]: values } })
112
+ }
113
+
114
+ /** Mark a row to be deleted. A row added here is simply dropped, and an edit to a deleted row goes with it. */
115
+ export function modelDraftRemove(drafts: ModelDrafts, panel: ModelRelatedPanel, key: string): ModelDrafts {
116
+ const draft = panelDraft(drafts, panel.slug)
117
+ if (modelDraftIsNew(key))
118
+ return withPanel(drafts, panel.slug, { ...draft, added: draft.added.filter(row => row.key !== key) })
119
+ const edited = { ...draft.edited }
120
+ delete edited[key]
121
+ return withPanel(drafts, panel.slug, { ...draft, edited, removed: draft.removed.includes(key) ? draft.removed : [...draft.removed, key] })
122
+ }
123
+
124
+ /** Keep a row marked for deletion after all. */
125
+ export function modelDraftRestore(drafts: ModelDrafts, panel: ModelRelatedPanel, key: string): ModelDrafts {
126
+ const draft = panelDraft(drafts, panel.slug)
127
+ return withPanel(drafts, panel.slug, { ...draft, removed: draft.removed.filter(id => id !== key) })
128
+ }
129
+
130
+ /** The fields an edit to a listed row changed, against what is stored. */
131
+ function editedFields(panel: ModelRelatedPanel, key: string, values: ModelFormValues): Record<string, unknown> {
132
+ return modelFormPayload(panel.fields ?? [], values, modelDraftStored(panel, key))
133
+ }
134
+
135
+ /**
136
+ * What the save sends for the related rows: per panel, the new rows, the
137
+ * edits that changed something, and the rows to delete. A panel with none of
138
+ * them is left out, so a page whose rows were only looked at sends nothing.
139
+ */
140
+ export function modelRelatedSaveChanges(panels: ModelRelatedPanel[], drafts: ModelDrafts): ModelRelatedChanges[] {
141
+ const changes: ModelRelatedChanges[] = []
142
+ for (const panel of panels) {
143
+ const draft = drafts[panel.slug]
144
+ if (!draft)
145
+ continue
146
+ const create = draft.added.map(row => ({ key: row.key, fields: modelFormPayload(panel.fields ?? [], row.values) }))
147
+ const update = Object.entries(draft.edited)
148
+ .filter(([key]) => !draft.removed.includes(key))
149
+ .map(([key, values]) => ({ id: rowId(key), fields: editedFields(panel, key, values) }))
150
+ .filter(row => Object.keys(row.fields).length > 0)
151
+ const destroy = draft.removed.map(rowId)
152
+ if (create.length + update.length + destroy.length > 0)
153
+ changes.push({ slug: panel.slug, create, update, destroy })
154
+ }
155
+ return changes
156
+ }
157
+
158
+ /** How many related rows a save would add, change or delete. */
159
+ export function modelDraftChangeCount(panels: ModelRelatedPanel[], drafts: ModelDrafts): number {
160
+ return modelRelatedSaveChanges(panels, drafts).reduce((count, panel) => count + panel.create.length + panel.update.length + panel.destroy.length, 0)
161
+ }
162
+
163
+ function rowId(key: string): number | string {
164
+ const id = Number(key)
165
+ return Number.isSafeInteger(id) && id > 0 ? id : key
166
+ }
167
+
168
+ /**
169
+ * A panel's rows as the edit page lists them: the stored ones, marked edited
170
+ * or to be deleted, then the ones added here. An added or edited row shows
171
+ * the values it will be saved with.
172
+ */
173
+ export function modelDraftListRows(panel: ModelRelatedPanel, drafts: ModelDrafts): ModelDraftListRow[] {
174
+ const draft = panelDraft(drafts, panel.slug)
175
+ const shown = (values: ModelFormValues, base: Record<string, unknown>): Record<string, unknown> => {
176
+ const out = { ...base }
177
+ for (const [name, value] of Object.entries(values))
178
+ out[modelFieldColumn(name)] = value
179
+ return out
180
+ }
181
+ const listed = panel.rows.map((row): ModelDraftListRow => {
182
+ const key = String(row.id)
183
+ if (draft.removed.includes(key))
184
+ return { key, state: 'removed', values: row }
185
+ const edited = draft.edited[key]
186
+ if (edited && Object.keys(editedFields(panel, key, edited)).length > 0)
187
+ return { key, state: 'edited', values: shown(edited, row) }
188
+ return { key, state: 'kept', values: row }
189
+ })
190
+ const added = draft.added.map((row): ModelDraftListRow => ({ key: row.key, state: 'added', values: shown(row.values, {}) }))
191
+ return [...listed, ...added]
192
+ }
193
+
194
+ /** The words for a row on the list: its first few summary values, else its id. */
195
+ export function modelDraftRowLabel(panel: ModelRelatedPanel, row: ModelDraftListRow): string {
196
+ const words = panel.columns
197
+ .map(column => row.values[column.key])
198
+ .filter(value => value !== null && value !== undefined && String(value).trim() !== '')
199
+ .slice(0, 3)
200
+ .map(String)
201
+ if (words.length > 0)
202
+ return words.join(' · ')
203
+ return modelDraftIsNew(row.key) ? `New ${panel.label.toLowerCase()}` : `${panel.label} #${row.key}`
204
+ }
205
+
206
+ /**
207
+ * Save the record's changed fields and its panels' changes in one request,
208
+ * all or nothing. A refusal comes back with where it was (`at`), so the page
209
+ * can point at the record's field or at the row.
210
+ */
211
+ export async function saveModelRecordWithRelated(
212
+ slug: string,
213
+ id: string | number,
214
+ fields: Record<string, unknown>,
215
+ related: ModelRelatedChanges[],
216
+ ): Promise<{ ok: true } | ModelSaveFailure> {
217
+ try {
218
+ await dashboardApi(`${modelPath(slug)}/${encodeURIComponent(String(id))}/save`, { method: 'PATCH', body: { fields, related } })
219
+ return { ok: true }
220
+ }
221
+ catch (reason) {
222
+ const failure: ModelSaveFailure = modelWriteFailure(reason)
223
+ const at = reason instanceof DashboardApiError ? (reason.body as { at?: unknown } | null)?.at : undefined
224
+ if (at && typeof at === 'object' && typeof (at as ModelSaveLocation).operation === 'string')
225
+ failure.at = at as ModelSaveLocation
226
+ return failure
227
+ }
228
+ }
@@ -164,7 +164,7 @@ export interface ModelCreateForm {
164
164
  /** What a model offers before its capabilities are known, or when it has none. */
165
165
  export const NO_WRITES: ModelWriteCapabilities = { create: false, update: false, destroy: false, invite: false, anonymize: false }
166
166
 
167
- function modelPath(slug: string): string {
167
+ export function modelPath(slug: string): string {
168
168
  return `/api/dashboard/models/${encodeURIComponent(slug)}`
169
169
  }
170
170
 
@@ -2,7 +2,7 @@
2
2
  "publisher": "Stacks",
3
3
  "name": "vscode-stacks",
4
4
  "displayName": "Stacks",
5
- "version": "0.75.613",
5
+ "version": "0.75.615",
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.613",
5
+ "version": "0.75.615",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/stacksjs/stacks.git",
@@ -45,14 +45,14 @@
45
45
  "dependencies": {
46
46
  "@iconify-json/f7": "^1.2.2",
47
47
  "@iconify-json/hugeicons": "^1.2.35",
48
- "@stacksjs/mobile": "0.75.613",
48
+ "@stacksjs/mobile": "0.75.615",
49
49
  "@stacksjs/sanitizer": "^0.2.889",
50
50
  "@stacksjs/stx": "^0.2.889",
51
- "@stacksjs/strings": "0.75.613",
51
+ "@stacksjs/strings": "0.75.615",
52
52
  "@xterm/addon-fit": "^0.11.0",
53
53
  "@xterm/xterm": "^6.0.0",
54
54
  "ts-qr-codes": "^0.1.8",
55
- "@stacksjs/support": "0.75.613",
56
- "@stacksjs/browser": "0.75.613"
55
+ "@stacksjs/support": "0.75.615",
56
+ "@stacksjs/browser": "0.75.615"
57
57
  }
58
58
  }