@beechcms/api 0.5.0 → 0.6.0-preview.2

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 (225) hide show
  1. package/assets/dashboard/BeechLogo.svg +18 -18
  2. package/assets/dashboard/BeechLogoLIght.svg +48 -48
  3. package/assets/dashboard/Searching.svg +1 -0
  4. package/assets/dashboard/assets/chart-BrJFdsGZ.js +39 -0
  5. package/assets/dashboard/assets/index-CIaoMxuB.css +1 -0
  6. package/assets/dashboard/assets/index-wTKgygsg.js +636 -0
  7. package/assets/dashboard/assets/pie-chart-recharts-BEaE1FOE.js +1 -0
  8. package/assets/dashboard/assets/timeseries-chart-recharts-DmWM6imF.js +1 -0
  9. package/assets/dashboard/beechLogoDark.svg +48 -48
  10. package/assets/dashboard/index.html +18 -18
  11. package/assets/dashboard/noResult.svg +43 -0
  12. package/assets/dashboard/sol.svg +3 -3
  13. package/assets/dashboard/undraw_enter_nwx3.svg +36 -36
  14. package/assets/dashboard/working.svg +1 -0
  15. package/migrations/0000_v040_base.sql +265 -238
  16. package/migrations/0029_automations.sql +14 -14
  17. package/migrations/0030_test_seeds.sql +125 -125
  18. package/package.json +13 -9
  19. package/src/auth/{in-memory-hash-provider.ts → __fixtures__/in-memory-hash-provider.ts} +17 -13
  20. package/src/auth/{static-token-service.ts → __fixtures__/static-token-service.ts} +22 -18
  21. package/src/auth/bcrypt-hash-provider.ts +24 -20
  22. package/src/auth/constants.ts +14 -10
  23. package/src/auth/generate-refresh-token.test.ts +23 -19
  24. package/src/auth/hash-provider.test.ts +55 -46
  25. package/src/auth/jose-token-service.ts +62 -55
  26. package/src/auth/jwt-claims-passthrough.test.ts +87 -0
  27. package/src/auth/login.test.ts +100 -92
  28. package/src/auth/login.ts +78 -74
  29. package/src/auth/refresh.ts +11 -5
  30. package/src/auth/token-service.test.ts +90 -82
  31. package/src/factory.ts +370 -347
  32. package/src/features/automations/__tests__/action-executors.test.ts +255 -268
  33. package/src/features/automations/__tests__/automation-runner.test.ts +196 -192
  34. package/src/features/automations/__tests__/automation-runner.utils.test.ts +60 -56
  35. package/src/features/automations/__tests__/automations.handler.test.ts +264 -260
  36. package/src/features/automations/__tests__/automations.repository.test.ts +163 -159
  37. package/src/features/automations/__tests__/automations.schema.test.ts +224 -134
  38. package/src/features/automations/__tests__/context-resolver.test.ts +126 -122
  39. package/src/features/automations/__tests__/cron-runner.test.ts +267 -263
  40. package/src/features/automations/__tests__/cron-runner.utils.test.ts +144 -140
  41. package/src/features/automations/__tests__/set-variable.executor.test.ts +383 -306
  42. package/src/features/automations/__tests__/template-grammar.test.ts +308 -304
  43. package/src/features/automations/__tests__/webhook.executor.test.ts +142 -0
  44. package/src/features/automations/__tests__/when-evaluator.test.ts +274 -270
  45. package/src/features/automations/__tests__/when-pushdown.test.ts +281 -277
  46. package/src/features/automations/action-executors/create-entry.executor.ts +27 -23
  47. package/src/features/automations/action-executors/edit-field.executor.ts +26 -22
  48. package/src/features/automations/action-executors/index.ts +37 -33
  49. package/src/features/automations/action-executors/send-mail.executor.ts +53 -42
  50. package/src/features/automations/action-executors/set-variable.executor.ts +159 -146
  51. package/src/features/automations/action-executors/webhook.executor.ts +67 -25
  52. package/src/features/automations/automation-runner.ts +85 -81
  53. package/src/features/automations/automation-runner.utils.ts +47 -43
  54. package/src/features/automations/automations.handler.ts +197 -193
  55. package/src/features/automations/automations.schema.ts +177 -160
  56. package/src/features/automations/context-resolver.ts +152 -148
  57. package/src/features/automations/cron-runner.ts +140 -136
  58. package/src/features/automations/cron-runner.utils.ts +44 -40
  59. package/src/features/automations/filter-translation.ts +46 -42
  60. package/src/features/automations/index.ts +16 -12
  61. package/src/features/automations/template-grammar.ts +245 -241
  62. package/src/features/automations/var-access-resolver.ts +140 -136
  63. package/src/features/automations/when-evaluator.ts +87 -83
  64. package/src/features/automations/when-pushdown.ts +57 -53
  65. package/src/features/backrefs/__tests__/backrefs.handler.test.ts +359 -0
  66. package/src/features/backrefs/backrefs.handler.ts +168 -0
  67. package/src/features/backrefs/d1-backref.repository.ts +84 -0
  68. package/src/features/backrefs/index.ts +5 -0
  69. package/src/features/content/constants.ts +16 -10
  70. package/src/features/content/handlers/bulk.handler.ts +185 -0
  71. package/src/features/content/handlers/create.ts +129 -165
  72. package/src/features/content/handlers/delete.ts +62 -87
  73. package/src/features/content/handlers/facets.ts +49 -45
  74. package/src/features/content/handlers/get.ts +120 -116
  75. package/src/features/content/handlers/helpers.test.ts +180 -0
  76. package/src/features/content/handlers/helpers.ts +93 -0
  77. package/src/features/content/handlers/list.ts +174 -88
  78. package/src/features/content/handlers/update.ts +174 -219
  79. package/src/features/content/index.ts +26 -20
  80. package/src/features/dashboard-layout/__tests__/dashboard-layout.handler.test.ts +388 -0
  81. package/src/features/dashboard-layout/dashboard-layout.handler.ts +206 -0
  82. package/src/features/dashboard-layout/index.ts +5 -0
  83. package/src/features/draft/draft.handler.ts +195 -170
  84. package/src/features/draft/draft.middleware.ts +66 -62
  85. package/src/features/draft/index.ts +5 -1
  86. package/src/features/email/email.provider.ts +42 -38
  87. package/src/features/email/email.service.ts +98 -93
  88. package/src/features/email/email.types.ts +119 -108
  89. package/src/features/email/index.ts +33 -29
  90. package/src/features/email/providers/resend.ts +67 -63
  91. package/src/features/email/providers/smtp.ts +55 -0
  92. package/src/features/email/templates/automation-mail.ts +19 -15
  93. package/src/features/email/templates/password-changed.ts +63 -59
  94. package/src/features/email/templates/password-reset.ts +68 -64
  95. package/src/features/email/templates/shell.ts +96 -92
  96. package/src/features/notifications/index.ts +5 -1
  97. package/src/features/notifications/notifications.handler.ts +105 -101
  98. package/src/features/password-reset/index.ts +19 -15
  99. package/src/features/password-reset/request.ts +92 -82
  100. package/src/features/password-reset/reset.ts +102 -92
  101. package/src/features/rotate-field/index.ts +5 -1
  102. package/src/features/rotate-field/rotate-field.handler.ts +132 -128
  103. package/src/features/rotate-field/rotate-field.schema.ts +17 -13
  104. package/src/features/schema/schema.handler.ts +131 -16
  105. package/src/features/seeds/index.ts +5 -0
  106. package/src/features/seeds/seeds.handler.test.ts +1199 -0
  107. package/src/features/seeds/seeds.handler.ts +558 -0
  108. package/src/features/settings/__tests__/settings.handler.test.ts +555 -0
  109. package/src/features/settings/settings.handler.ts +392 -302
  110. package/src/features/setup/index.ts +288 -91
  111. package/src/features/stats/index.ts +5 -1
  112. package/src/features/stats/stats.handler.ts +420 -430
  113. package/src/features/webhooks/index.ts +63 -0
  114. package/src/index.ts +65 -56
  115. package/src/media-utils.ts +82 -78
  116. package/src/middleware/auth-providers.middleware.test.ts +85 -0
  117. package/src/middleware/auth-providers.middleware.ts +45 -32
  118. package/src/middleware/observability.middleware.test.ts +93 -0
  119. package/src/middleware/observability.middleware.ts +70 -52
  120. package/src/middleware/rate-limit.middleware.ts +45 -41
  121. package/src/middleware/repository.middleware.ts +117 -91
  122. package/src/middleware/seed-registry.middleware.test.ts +97 -0
  123. package/src/middleware/seed-registry.middleware.ts +21 -0
  124. package/src/middleware/storage.middleware.ts +25 -21
  125. package/src/middleware.ts +45 -47
  126. package/src/public/access-policy.ts +27 -23
  127. package/src/public/api-key-middleware.ts +57 -53
  128. package/src/public/cache-utils.ts +38 -34
  129. package/src/public/entry-projection.ts +46 -42
  130. package/src/public/idempotency.ts +23 -19
  131. package/src/public/index.ts +16 -12
  132. package/src/public/problem-details.ts +124 -53
  133. package/src/public/public-add.ts +114 -110
  134. package/src/public/public-edit.ts +163 -159
  135. package/src/public/public-errors.ts +19 -15
  136. package/src/public/public-read.ts +63 -59
  137. package/src/public/public-routes.ts +88 -84
  138. package/src/public/query-builder.test.ts +224 -220
  139. package/src/public/query-builder.ts +156 -152
  140. package/src/public/rate-limit-middleware.ts +34 -30
  141. package/src/public/read-list.ts +54 -50
  142. package/src/public/read-single.ts +48 -44
  143. package/src/public/response-builder.ts +30 -26
  144. package/src/public/sanitize.ts +69 -65
  145. package/src/public/slug-utils.ts +18 -14
  146. package/src/rate-limit/cloudflare-rate-limiter.test.ts +30 -26
  147. package/src/rate-limit/cloudflare-rate-limiter.ts +15 -11
  148. package/src/rate-limit/in-memory-rate-limiter.test.ts +37 -33
  149. package/src/rate-limit/in-memory-rate-limiter.ts +17 -13
  150. package/src/rate-limit/no-op-rate-limiter.test.ts +22 -18
  151. package/src/rate-limit/no-op-rate-limiter.ts +11 -7
  152. package/src/search-utils.test.ts +211 -207
  153. package/src/search-utils.ts +213 -209
  154. package/src/search.ts +65 -61
  155. package/src/shared/apply-policies.test.ts +81 -77
  156. package/src/shared/apply-policies.ts +67 -63
  157. package/src/shared/automations.repository.d1.ts +150 -146
  158. package/src/shared/background-notification-service.test.ts +62 -58
  159. package/src/shared/background-notification-service.ts +52 -48
  160. package/src/shared/base.repository.d1.ts +32 -28
  161. package/src/shared/content-utils.test.ts +165 -161
  162. package/src/shared/content-utils.ts +86 -82
  163. package/src/shared/content.repository.d1.test.ts +507 -312
  164. package/src/shared/content.repository.d1.ts +851 -382
  165. package/src/shared/d1-activity-log.repository.test.ts +140 -136
  166. package/src/shared/d1-activity-log.repository.ts +105 -101
  167. package/src/shared/d1-activity-logger.test.ts +86 -82
  168. package/src/shared/d1-activity-logger.ts +67 -63
  169. package/src/shared/d1-analytics.repository.test.ts +78 -74
  170. package/src/shared/d1-analytics.repository.ts +85 -81
  171. package/src/shared/d1-content-scan.repository.test.ts +80 -76
  172. package/src/shared/d1-content-scan.repository.ts +37 -29
  173. package/src/shared/d1-notification.repository.test.ts +128 -124
  174. package/src/shared/d1-notification.repository.ts +118 -114
  175. package/src/shared/d1-password-reset-token.repository.test.ts +81 -77
  176. package/src/shared/d1-password-reset-token.repository.ts +56 -52
  177. package/src/shared/d1-search.repository.test.ts +87 -83
  178. package/src/shared/d1-search.repository.ts +88 -84
  179. package/src/shared/d1-session.repository.test.ts +125 -121
  180. package/src/shared/d1-session.repository.ts +102 -98
  181. package/src/shared/d1-setup-checklist.repository.ts +36 -0
  182. package/src/shared/d1-user.repository.test.ts +151 -147
  183. package/src/shared/d1-user.repository.ts +119 -109
  184. package/src/shared/d1-widget.repository.test.ts +267 -217
  185. package/src/shared/d1-widget.repository.ts +385 -337
  186. package/src/shared/dashboard-layout.repository.d1.test.ts +135 -0
  187. package/src/shared/dashboard-layout.repository.d1.ts +58 -0
  188. package/src/shared/demo-data-sql.ts +216 -0
  189. package/src/shared/demo-data.repository.d1.ts +20 -0
  190. package/src/shared/execution-context-scheduler.ts +13 -9
  191. package/src/shared/fixed-clock.ts +25 -21
  192. package/src/shared/fts-sync.ts +8 -4
  193. package/src/shared/idempotency.repository.d1.test.ts +83 -79
  194. package/src/shared/idempotency.repository.d1.ts +60 -56
  195. package/src/shared/in-memory-activity-logger.ts +19 -15
  196. package/src/shared/in-memory-notification-service.ts +19 -15
  197. package/src/shared/in-memory-seed.repository.ts +58 -0
  198. package/src/shared/media.repository.d1.test.ts +107 -103
  199. package/src/shared/media.repository.d1.ts +68 -64
  200. package/src/shared/qstash-notification-service.test.ts +67 -0
  201. package/src/shared/qstash-notification-service.ts +55 -0
  202. package/src/shared/query-utils.ts +141 -137
  203. package/src/shared/request-utils.ts +26 -22
  204. package/src/shared/schema-mutator.d1.test.ts +142 -0
  205. package/src/shared/schema-mutator.d1.ts +64 -0
  206. package/src/shared/seed-layout.repository.d1.test.ts +114 -0
  207. package/src/shared/seed-layout.repository.d1.ts +62 -0
  208. package/src/shared/seed-registry-cache.test.ts +68 -0
  209. package/src/shared/seed-registry-cache.ts +49 -0
  210. package/src/shared/seed.repository.d1.test.ts +143 -0
  211. package/src/shared/seed.repository.d1.ts +98 -0
  212. package/src/shared/sequential-id-generator.ts +33 -22
  213. package/src/shared/site-settings.repository.d1.ts +53 -0
  214. package/src/shared/storage/factory.ts +41 -40
  215. package/src/shared/storage/s3-bucket.ts +195 -163
  216. package/src/shared/storage-utils.ts +40 -36
  217. package/src/shared/system-stats.repository.d1.test.ts +58 -54
  218. package/src/shared/system-stats.repository.d1.ts +48 -44
  219. package/src/types.ts +90 -67
  220. package/src/upload.ts +198 -187
  221. package/src/widget.test.ts +85 -0
  222. package/src/widget.ts +251 -208
  223. package/assets/dashboard/assets/index-B1mUfgiK.css +0 -1
  224. package/assets/dashboard/assets/index-CHxxc_id.js +0 -629
  225. package/src/shared/storage/r2-binding-bucket.ts +0 -81
@@ -1,337 +1,385 @@
1
- /// <reference types="@cloudflare/workers-types" />
2
- import type {
3
- Seed,
4
- IWidgetRepository,
5
- AggregateFormula,
6
- TimeWindow,
7
- LeaderboardEntry,
8
- LeaderboardOptions,
9
- TimeseriesPoint,
10
- WidgetListOptions,
11
- WidgetListResult,
12
- GrowthResult,
13
- } from '@beechcms/core'
14
-
15
- const SYSTEM_COLUMNS: ReadonlySet<string> = new Set([
16
- 'id',
17
- 'slug',
18
- 'status',
19
- 'created_at',
20
- 'updated_at',
21
- ])
22
-
23
- const ALLOWED_FILTER_OPERATORS: ReadonlySet<string> = new Set([
24
- 'eq',
25
- '=',
26
- 'neq',
27
- '!=',
28
- 'like',
29
- 'gt',
30
- '>',
31
- 'lt',
32
- '<',
33
- ])
34
-
35
- const UNSAFE_COLUMN_ERROR = 'UNSAFE_COLUMN'
36
-
37
- /**
38
- * D1-backed implementation of {@link IWidgetRepository}.
39
- *
40
- * All user-supplied values are bound via parameterised statements. Column
41
- * aliases originating from query strings are validated against the seed
42
- * before being composed into the SQL string, preventing column-name
43
- * injection. SQL keywords (aggregate function names, ORDER direction) are
44
- * selected via hardcoded branches.
45
- */
46
- export class D1WidgetRepository implements IWidgetRepository {
47
- constructor(private readonly database: D1Database) {}
48
-
49
- async aggregate(seed: Seed, formula: AggregateFormula, window: TimeWindow): Promise<number> {
50
- const aggregateExpression = this.buildAggregateExpression(seed, formula)
51
- const timeWindowFilter = this.buildTimeWindowFilter(window)
52
- const tableName = `content_${seed.slug}`
53
-
54
- const sql =
55
- `SELECT ${aggregateExpression} as computed_value
56
- FROM ${tableName}
57
- WHERE ${timeWindowFilter}`
58
-
59
- const row = await this.database.prepare(sql).first<{ computed_value: number | null }>()
60
- return row?.computed_value ?? 0
61
- }
62
-
63
- async growth(
64
- seed: Seed,
65
- formula: AggregateFormula,
66
- window: TimeWindow,
67
- ): Promise<GrowthResult> {
68
- const aggregateExpression = this.buildAggregateExpression(seed, formula)
69
- const { currentFilter, previousFilter } = this.buildPreviousWindowFilter(window)
70
- const tableName = `content_${seed.slug}`
71
-
72
- const [currentRow, previousRow] = await Promise.all([
73
- this.database
74
- .prepare(`SELECT ${aggregateExpression} as computed_value FROM ${tableName} WHERE ${currentFilter}`)
75
- .first<{ computed_value: number | null }>(),
76
- this.database
77
- .prepare(`SELECT ${aggregateExpression} as computed_value FROM ${tableName} WHERE ${previousFilter}`)
78
- .first<{ computed_value: number | null }>(),
79
- ])
80
-
81
- return {
82
- currentValue: currentRow?.computed_value ?? 0,
83
- previousValue: previousRow?.computed_value ?? 0,
84
- }
85
- }
86
-
87
- async leaderboard(seed: Seed, options: LeaderboardOptions): Promise<LeaderboardEntry[]> {
88
- const scoreColumn = this.resolveColumnExpression(seed, options.scoreColumn)
89
- const labelColumn = this.resolveColumnExpression(seed, seed.displayNameAlias)
90
- const tableName = `content_${seed.slug}`
91
- const orderClause = options.orderDirection === 'ASC'
92
- ? `ORDER BY CAST(${scoreColumn} AS REAL) ASC`
93
- : `ORDER BY CAST(${scoreColumn} AS REAL) DESC`
94
-
95
- const sql =
96
- `SELECT id, ${labelColumn} as label, ${scoreColumn} as score
97
- FROM ${tableName}
98
- WHERE ${scoreColumn} IS NOT NULL
99
- ${orderClause}
100
- LIMIT ?`
101
-
102
- const rows = await this.database
103
- .prepare(sql)
104
- .bind(options.limit)
105
- .all<{ id: string; label: string | null; score: number | string | null }>()
106
-
107
- return (rows.results ?? []).map(row => ({
108
- id: row.id,
109
- label: row.label ?? row.id,
110
- score: row.score ?? 0,
111
- }))
112
- }
113
-
114
- async list(seed: Seed, options: WidgetListOptions): Promise<WidgetListResult> {
115
- const tableName = `content_${seed.slug}`
116
- const conditions: string[] = []
117
- const bindings: unknown[] = []
118
-
119
- const trimmedSearch = options.search?.trim() ?? ''
120
- if (trimmedSearch.length > 0) {
121
- const displayColumn = this.resolveColumnExpression(seed, seed.displayNameAlias)
122
- conditions.push(`${displayColumn} LIKE ?`)
123
- bindings.push(`%${trimmedSearch}%`)
124
- }
125
-
126
- for (const filter of options.filters ?? []) {
127
- this.appendFilterCondition(seed, filter, conditions, bindings)
128
- }
129
-
130
- const whereSql = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
131
- const orderClause = this.buildListOrderClause(seed, options)
132
- const branchColumns = seed.branches.map(branch => branch.alias).join(', ')
133
- const selectColumns = branchColumns.length > 0
134
- ? `id, slug, status, created_at, updated_at, ${branchColumns}`
135
- : `id, slug, status, created_at, updated_at`
136
-
137
- const dataSql =
138
- `SELECT ${selectColumns}
139
- FROM ${tableName}
140
- ${whereSql}
141
- ${orderClause}
142
- LIMIT ? OFFSET ?`
143
-
144
- const countSql = `SELECT COUNT(*) as total FROM ${tableName} ${whereSql}`
145
-
146
- const [countRow, listRows] = await Promise.all([
147
- this.database.prepare(countSql).bind(...bindings).first<{ total: number }>(),
148
- this.database
149
- .prepare(dataSql)
150
- .bind(...bindings, options.limit, options.offset)
151
- .all<Record<string, unknown>>(),
152
- ])
153
-
154
- return {
155
- entries: listRows.results ?? [],
156
- totalCount: countRow?.total ?? 0,
157
- }
158
- }
159
-
160
- async timeseries(
161
- seed: Seed,
162
- formula: AggregateFormula,
163
- window: TimeWindow,
164
- groupColumn: string,
165
- ): Promise<TimeseriesPoint[]> {
166
- const groupColumnExpression = this.resolveColumnExpression(seed, groupColumn)
167
- const aggregateExpression = this.buildAggregateExpression(seed, formula)
168
- const timeWindowFilter = this.buildTimeWindowFilter(window)
169
- const tableName = `content_${seed.slug}`
170
-
171
- const dateBucketExpression = groupColumnExpression === 'created_at'
172
- ? `strftime('%Y-%m-%d', created_at, 'unixepoch')`
173
- : `strftime('%Y-%m-%d', CAST(${groupColumnExpression} AS INTEGER), 'unixepoch')`
174
-
175
- const sql =
176
- `SELECT ${dateBucketExpression} as bucket_label,
177
- ${aggregateExpression} as bucket_value
178
- FROM ${tableName}
179
- WHERE ${timeWindowFilter}
180
- GROUP BY bucket_label
181
- ORDER BY bucket_label ASC`
182
-
183
- const rows = await this.database
184
- .prepare(sql)
185
- .all<{ bucket_label: string | null; bucket_value: number | null }>()
186
-
187
- return (rows.results ?? []).map(row => ({
188
- label: row.bucket_label ?? '',
189
- value: row.bucket_value ?? 0,
190
- }))
191
- }
192
-
193
- /**
194
- * Throws UNSAFE_COLUMN if the alias is neither a system column nor a
195
- * declared seed branch, preventing SQL injection via column names.
196
- */
197
- private resolveColumnExpression(seed: Seed, alias: string): string {
198
- if (SYSTEM_COLUMNS.has(alias)) return alias
199
- const branch = seed.branches.find(candidate => candidate.alias === alias)
200
- if (!branch) throw new Error(UNSAFE_COLUMN_ERROR)
201
- return branch.alias
202
- }
203
-
204
- private buildAggregateExpression(seed: Seed, formula: AggregateFormula): string {
205
- switch (formula.op) {
206
- case 'count':
207
- return 'COUNT(*)'
208
- case 'sum': {
209
- const column = this.resolveColumnExpression(seed, formula.column)
210
- return `SUM(CAST(${column} AS REAL))`
211
- }
212
- case 'avg': {
213
- const column = this.resolveColumnExpression(seed, formula.column)
214
- return `AVG(CAST(${column} AS REAL))`
215
- }
216
- case 'min': {
217
- const column = this.resolveColumnExpression(seed, formula.column)
218
- return `MIN(CAST(${column} AS REAL))`
219
- }
220
- case 'max': {
221
- const column = this.resolveColumnExpression(seed, formula.column)
222
- return `MAX(CAST(${column} AS REAL))`
223
- }
224
- case 'countWhere':
225
- return this.buildCountWhereExpression(seed, formula.column, formula.value)
226
- case 'percentageOf': {
227
- const numerator = this.resolveColumnExpression(seed, formula.numeratorColumn)
228
- const denominator = this.resolveColumnExpression(seed, formula.denominatorColumn)
229
- return `CASE WHEN SUM(CAST(${denominator} AS REAL)) = 0 THEN 0 ELSE (SUM(CAST(${numerator} AS REAL)) * 100.0 / SUM(CAST(${denominator} AS REAL))) END`
230
- }
231
- }
232
- }
233
-
234
- private buildCountWhereExpression(seed: Seed, alias: string, value: unknown): string {
235
- const column = this.resolveColumnExpression(seed, alias)
236
- if (value === null) return `COUNT(CASE WHEN ${column} IS NULL THEN 1 END)`
237
- if (typeof value === 'boolean') {
238
- const numericValue = value ? 1 : 0
239
- return `COUNT(CASE WHEN ${column} = ${numericValue} THEN 1 END)`
240
- }
241
- if (typeof value === 'number' && Number.isFinite(value)) {
242
- return `COUNT(CASE WHEN CAST(${column} AS REAL) = ${value} THEN 1 END)`
243
- }
244
- const escaped = String(value).replace(/'/g, "''")
245
- return `COUNT(CASE WHEN ${column} = '${escaped}' THEN 1 END)`
246
- }
247
-
248
- private buildTimeWindowFilter(window: TimeWindow): string {
249
- switch (window) {
250
- case 'week': return "created_at > unixepoch('now', '-7 days')"
251
- case 'month': return "created_at > unixepoch('now', '-1 month')"
252
- case 'year': return "created_at > unixepoch('now', '-1 year')"
253
- case 'all': return '1=1'
254
- }
255
- }
256
-
257
- private buildPreviousWindowFilter(
258
- window: TimeWindow,
259
- ): { currentFilter: string; previousFilter: string } {
260
- switch (window) {
261
- case 'week':
262
- return {
263
- currentFilter: "created_at > unixepoch('now', '-7 days')",
264
- previousFilter: "created_at > unixepoch('now', '-14 days') AND created_at <= unixepoch('now', '-7 days')",
265
- }
266
- case 'month':
267
- return {
268
- currentFilter: "created_at > unixepoch('now', '-1 month')",
269
- previousFilter: "created_at > unixepoch('now', '-2 months') AND created_at <= unixepoch('now', '-1 month')",
270
- }
271
- case 'year':
272
- return {
273
- currentFilter: "created_at > unixepoch('now', '-1 year')",
274
- previousFilter: "created_at > unixepoch('now', '-2 years') AND created_at <= unixepoch('now', '-1 year')",
275
- }
276
- case 'all':
277
- return { currentFilter: '1=1', previousFilter: '1=0' }
278
- }
279
- }
280
-
281
- private appendFilterCondition(
282
- seed: Seed,
283
- filter: { column: string; op: string; value: unknown },
284
- conditions: string[],
285
- bindings: unknown[],
286
- ): void {
287
- if (!ALLOWED_FILTER_OPERATORS.has(filter.op)) return
288
-
289
- let column: string
290
- try {
291
- column = this.resolveColumnExpression(seed, filter.column)
292
- } catch {
293
- return
294
- }
295
-
296
- switch (filter.op) {
297
- case 'eq':
298
- case '=':
299
- conditions.push(`${column} = ?`)
300
- bindings.push(filter.value)
301
- return
302
- case 'neq':
303
- case '!=':
304
- conditions.push(`${column} != ?`)
305
- bindings.push(filter.value)
306
- return
307
- case 'like':
308
- conditions.push(`${column} LIKE ?`)
309
- bindings.push(filter.value)
310
- return
311
- case 'gt':
312
- case '>':
313
- conditions.push(`CAST(${column} AS REAL) > ?`)
314
- bindings.push(filter.value)
315
- return
316
- case 'lt':
317
- case '<':
318
- conditions.push(`CAST(${column} AS REAL) < ?`)
319
- bindings.push(filter.value)
320
- return
321
- }
322
- }
323
-
324
- private buildListOrderClause(seed: Seed, options: WidgetListOptions): string {
325
- let orderColumn = 'created_at'
326
- if (options.orderByColumn) {
327
- try {
328
- orderColumn = this.resolveColumnExpression(seed, options.orderByColumn)
329
- } catch {
330
- orderColumn = 'created_at'
331
- }
332
- }
333
- return options.orderDirection === 'DESC'
334
- ? `ORDER BY ${orderColumn} DESC`
335
- : `ORDER BY ${orderColumn} ASC`
336
- }
337
- }
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // Copyright (c) 2024–2026 Flavio De Musso. All rights reserved.
3
+ // See LICENSE in the repository root for license terms.
4
+
5
+ /// <reference types="@cloudflare/workers-types" />
6
+ import {
7
+ isDateRange,
8
+ type Seed,
9
+ type IWidgetRepository,
10
+ type AggregateFormula,
11
+ type WidgetWindow,
12
+ type LeaderboardEntry,
13
+ type LeaderboardOptions,
14
+ type TimeseriesPoint,
15
+ type WidgetListOptions,
16
+ type WidgetListResult,
17
+ type GrowthResult,
18
+ type DistributionSlice,
19
+ } from '@beechcms/core'
20
+
21
+ const SYSTEM_COLUMNS: ReadonlySet<string> = new Set([
22
+ 'id',
23
+ 'slug',
24
+ 'status',
25
+ 'created_at',
26
+ 'updated_at',
27
+ ])
28
+
29
+ const ALLOWED_FILTER_OPERATORS: ReadonlySet<string> = new Set([
30
+ 'eq',
31
+ '=',
32
+ 'neq',
33
+ '!=',
34
+ 'like',
35
+ 'gt',
36
+ '>',
37
+ 'lt',
38
+ '<',
39
+ ])
40
+
41
+ const UNSAFE_COLUMN_ERROR = 'UNSAFE_COLUMN'
42
+
43
+ /**
44
+ * D1-backed implementation of {@link IWidgetRepository}.
45
+ *
46
+ * All user-supplied values are bound via parameterised statements. Column
47
+ * aliases originating from query strings are validated against the seed
48
+ * before being composed into the SQL string, preventing column-name
49
+ * injection. SQL keywords (aggregate function names, ORDER direction) are
50
+ * selected via hardcoded branches.
51
+ */
52
+ export class D1WidgetRepository implements IWidgetRepository {
53
+ constructor(private readonly database: D1Database) {}
54
+
55
+ async aggregate(seed: Seed, formula: AggregateFormula, window: WidgetWindow): Promise<number> {
56
+ const aggregateExpression = this.buildAggregateExpression(seed, formula)
57
+ const { sql: timeWindowFilter, bindings } = this.buildTimeWindowFilter(window)
58
+ const tableName = `content_${seed.slug}`
59
+
60
+ const sql =
61
+ `SELECT ${aggregateExpression} as computed_value
62
+ FROM ${tableName}
63
+ WHERE ${timeWindowFilter}`
64
+
65
+ const row = await this.database.prepare(sql).bind(...bindings).first<{ computed_value: number | null }>()
66
+ return row?.computed_value ?? 0
67
+ }
68
+
69
+ async growth(
70
+ seed: Seed,
71
+ formula: AggregateFormula,
72
+ window: WidgetWindow,
73
+ ): Promise<GrowthResult> {
74
+ const aggregateExpression = this.buildAggregateExpression(seed, formula)
75
+ const { currentFilter, previousFilter } = this.buildPreviousWindowFilter(window)
76
+ const tableName = `content_${seed.slug}`
77
+
78
+ const [currentRow, previousRow] = await Promise.all([
79
+ this.database
80
+ .prepare(`SELECT ${aggregateExpression} as computed_value FROM ${tableName} WHERE ${currentFilter.sql}`)
81
+ .bind(...currentFilter.bindings)
82
+ .first<{ computed_value: number | null }>(),
83
+ this.database
84
+ .prepare(`SELECT ${aggregateExpression} as computed_value FROM ${tableName} WHERE ${previousFilter.sql}`)
85
+ .bind(...previousFilter.bindings)
86
+ .first<{ computed_value: number | null }>(),
87
+ ])
88
+
89
+ return {
90
+ currentValue: currentRow?.computed_value ?? 0,
91
+ previousValue: previousRow?.computed_value ?? 0,
92
+ }
93
+ }
94
+
95
+ async leaderboard(seed: Seed, options: LeaderboardOptions): Promise<LeaderboardEntry[]> {
96
+ const scoreColumn = this.resolveColumnExpression(seed, options.scoreColumn)
97
+ const labelColumn = this.resolveColumnExpression(seed, seed.displayNameAlias)
98
+ const tableName = `content_${seed.slug}`
99
+ const orderClause = options.orderDirection === 'ASC'
100
+ ? `ORDER BY CAST(${scoreColumn} AS REAL) ASC`
101
+ : `ORDER BY CAST(${scoreColumn} AS REAL) DESC`
102
+
103
+ const sql =
104
+ `SELECT id, ${labelColumn} as label, ${scoreColumn} as score
105
+ FROM ${tableName}
106
+ WHERE ${scoreColumn} IS NOT NULL
107
+ ${orderClause}
108
+ LIMIT ?`
109
+
110
+ const rows = await this.database
111
+ .prepare(sql)
112
+ .bind(options.limit)
113
+ .all<{ id: string; label: string | null; score: number | string | null }>()
114
+
115
+ return (rows.results ?? []).map(row => ({
116
+ id: row.id,
117
+ label: row.label ?? row.id,
118
+ score: row.score ?? 0,
119
+ }))
120
+ }
121
+
122
+ async list(seed: Seed, options: WidgetListOptions): Promise<WidgetListResult> {
123
+ const tableName = `content_${seed.slug}`
124
+ const conditions: string[] = []
125
+ const bindings: unknown[] = []
126
+
127
+ const trimmedSearch = options.search?.trim() ?? ''
128
+ if (trimmedSearch.length > 0) {
129
+ const displayColumn = this.resolveColumnExpression(seed, seed.displayNameAlias)
130
+ conditions.push(`${displayColumn} LIKE ?`)
131
+ bindings.push(`%${trimmedSearch}%`)
132
+ }
133
+
134
+ for (const filter of options.filters ?? []) {
135
+ this.appendFilterCondition(seed, filter, conditions, bindings)
136
+ }
137
+
138
+ const whereSql = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
139
+ const orderClause = this.buildListOrderClause(seed, options)
140
+ const branchColumns = seed.branches.map(branch => branch.alias).join(', ')
141
+ const selectColumns = branchColumns.length > 0
142
+ ? `id, slug, status, created_at, updated_at, ${branchColumns}`
143
+ : `id, slug, status, created_at, updated_at`
144
+
145
+ const dataSql =
146
+ `SELECT ${selectColumns}
147
+ FROM ${tableName}
148
+ ${whereSql}
149
+ ${orderClause}
150
+ LIMIT ? OFFSET ?`
151
+
152
+ const countSql = `SELECT COUNT(*) as total FROM ${tableName} ${whereSql}`
153
+
154
+ const [countRow, listRows] = await Promise.all([
155
+ this.database.prepare(countSql).bind(...bindings).first<{ total: number }>(),
156
+ this.database
157
+ .prepare(dataSql)
158
+ .bind(...bindings, options.limit, options.offset)
159
+ .all<Record<string, unknown>>(),
160
+ ])
161
+
162
+ return {
163
+ entries: listRows.results ?? [],
164
+ totalCount: countRow?.total ?? 0,
165
+ }
166
+ }
167
+
168
+ async timeseries(
169
+ seed: Seed,
170
+ formula: AggregateFormula,
171
+ window: WidgetWindow,
172
+ groupColumn: string,
173
+ ): Promise<TimeseriesPoint[]> {
174
+ const groupColumnExpression = this.resolveColumnExpression(seed, groupColumn)
175
+ const aggregateExpression = this.buildAggregateExpression(seed, formula)
176
+ const { sql: timeWindowFilter, bindings } = this.buildTimeWindowFilter(window)
177
+ const tableName = `content_${seed.slug}`
178
+
179
+ const dateBucketExpression = groupColumnExpression === 'created_at'
180
+ ? `strftime('%Y-%m-%d', created_at, 'unixepoch')`
181
+ : `strftime('%Y-%m-%d', CAST(${groupColumnExpression} AS INTEGER), 'unixepoch')`
182
+
183
+ const sql =
184
+ `SELECT ${dateBucketExpression} as bucket_label,
185
+ ${aggregateExpression} as bucket_value
186
+ FROM ${tableName}
187
+ WHERE ${timeWindowFilter}
188
+ GROUP BY bucket_label
189
+ ORDER BY bucket_label ASC`
190
+
191
+ const rows = await this.database
192
+ .prepare(sql)
193
+ .bind(...bindings)
194
+ .all<{ bucket_label: string | null; bucket_value: number | null }>()
195
+
196
+ return (rows.results ?? []).map(row => ({
197
+ label: row.bucket_label ?? '',
198
+ value: row.bucket_value ?? 0,
199
+ }))
200
+ }
201
+
202
+ async distribution(
203
+ seed: Seed,
204
+ column: string,
205
+ window: WidgetWindow,
206
+ limit: number,
207
+ ): Promise<DistributionSlice[]> {
208
+ const columnExpression = this.resolveColumnExpression(seed, column)
209
+ const { sql: timeWindowFilter, bindings } = this.buildTimeWindowFilter(window)
210
+ const tableName = `content_${seed.slug}`
211
+
212
+ const sql =
213
+ `SELECT ${columnExpression} as label, COUNT(*) as value
214
+ FROM ${tableName}
215
+ WHERE ${timeWindowFilter}
216
+ GROUP BY ${columnExpression}
217
+ ORDER BY value DESC
218
+ LIMIT ?`
219
+
220
+ const rows = await this.database
221
+ .prepare(sql)
222
+ .bind(...bindings, limit)
223
+ .all<{ label: string | number | null; value: number | null }>()
224
+
225
+ return (rows.results ?? []).map(row => ({
226
+ label: row.label === null ? '' : String(row.label),
227
+ value: row.value ?? 0,
228
+ }))
229
+ }
230
+
231
+ /**
232
+ * Throws UNSAFE_COLUMN if the alias is neither a system column nor a
233
+ * declared seed branch, preventing SQL injection via column names.
234
+ */
235
+ private resolveColumnExpression(seed: Seed, alias: string): string {
236
+ if (SYSTEM_COLUMNS.has(alias)) return alias
237
+ const branch = seed.branches.find(candidate => candidate.alias === alias)
238
+ if (!branch) throw new Error(UNSAFE_COLUMN_ERROR)
239
+ return branch.alias
240
+ }
241
+
242
+ private buildAggregateExpression(seed: Seed, formula: AggregateFormula): string {
243
+ switch (formula.op) {
244
+ case 'count':
245
+ return 'COUNT(*)'
246
+ case 'sum': {
247
+ const column = this.resolveColumnExpression(seed, formula.column)
248
+ return `SUM(CAST(${column} AS REAL))`
249
+ }
250
+ case 'avg': {
251
+ const column = this.resolveColumnExpression(seed, formula.column)
252
+ return `AVG(CAST(${column} AS REAL))`
253
+ }
254
+ case 'min': {
255
+ const column = this.resolveColumnExpression(seed, formula.column)
256
+ return `MIN(CAST(${column} AS REAL))`
257
+ }
258
+ case 'max': {
259
+ const column = this.resolveColumnExpression(seed, formula.column)
260
+ return `MAX(CAST(${column} AS REAL))`
261
+ }
262
+ case 'countWhere':
263
+ return this.buildCountWhereExpression(seed, formula.column, formula.value)
264
+ case 'percentageOf': {
265
+ const numerator = this.resolveColumnExpression(seed, formula.numeratorColumn)
266
+ const denominator = this.resolveColumnExpression(seed, formula.denominatorColumn)
267
+ return `CASE WHEN SUM(CAST(${denominator} AS REAL)) = 0 THEN 0 ELSE (SUM(CAST(${numerator} AS REAL)) * 100.0 / SUM(CAST(${denominator} AS REAL))) END`
268
+ }
269
+ }
270
+ }
271
+
272
+ private buildCountWhereExpression(seed: Seed, alias: string, value: unknown): string {
273
+ const column = this.resolveColumnExpression(seed, alias)
274
+ if (value === null) return `COUNT(CASE WHEN ${column} IS NULL THEN 1 END)`
275
+ if (typeof value === 'boolean') {
276
+ const numericValue = value ? 1 : 0
277
+ return `COUNT(CASE WHEN ${column} = ${numericValue} THEN 1 END)`
278
+ }
279
+ if (typeof value === 'number' && Number.isFinite(value)) {
280
+ return `COUNT(CASE WHEN CAST(${column} AS REAL) = ${value} THEN 1 END)`
281
+ }
282
+ const escaped = String(value).replace(/'/g, "''")
283
+ return `COUNT(CASE WHEN ${column} = '${escaped}' THEN 1 END)`
284
+ }
285
+
286
+ private buildTimeWindowFilter(window: WidgetWindow): { sql: string; bindings: number[] } {
287
+ if (isDateRange(window)) {
288
+ return { sql: 'created_at BETWEEN ? AND ?', bindings: [window.from, window.to] }
289
+ }
290
+ switch (window) {
291
+ case 'week': return { sql: "created_at > unixepoch('now', '-7 days')", bindings: [] }
292
+ case 'month': return { sql: "created_at > unixepoch('now', '-1 month')", bindings: [] }
293
+ case 'year': return { sql: "created_at > unixepoch('now', '-1 year')", bindings: [] }
294
+ case 'all': return { sql: '1=1', bindings: [] }
295
+ }
296
+ }
297
+
298
+ private buildPreviousWindowFilter(
299
+ window: WidgetWindow,
300
+ ): { currentFilter: { sql: string; bindings: number[] }; previousFilter: { sql: string; bindings: number[] } } {
301
+ if (isDateRange(window)) {
302
+ const span = window.to - window.from
303
+ return {
304
+ currentFilter: { sql: 'created_at BETWEEN ? AND ?', bindings: [window.from, window.to] },
305
+ previousFilter: { sql: 'created_at BETWEEN ? AND ?', bindings: [window.from - span - 1, window.from - 1] },
306
+ }
307
+ }
308
+ switch (window) {
309
+ case 'week':
310
+ return {
311
+ currentFilter: { sql: "created_at > unixepoch('now', '-7 days')", bindings: [] },
312
+ previousFilter: { sql: "created_at > unixepoch('now', '-14 days') AND created_at <= unixepoch('now', '-7 days')", bindings: [] },
313
+ }
314
+ case 'month':
315
+ return {
316
+ currentFilter: { sql: "created_at > unixepoch('now', '-1 month')", bindings: [] },
317
+ previousFilter: { sql: "created_at > unixepoch('now', '-2 months') AND created_at <= unixepoch('now', '-1 month')", bindings: [] },
318
+ }
319
+ case 'year':
320
+ return {
321
+ currentFilter: { sql: "created_at > unixepoch('now', '-1 year')", bindings: [] },
322
+ previousFilter: { sql: "created_at > unixepoch('now', '-2 years') AND created_at <= unixepoch('now', '-1 year')", bindings: [] },
323
+ }
324
+ case 'all':
325
+ return { currentFilter: { sql: '1=1', bindings: [] }, previousFilter: { sql: '1=0', bindings: [] } }
326
+ }
327
+ }
328
+
329
+ private appendFilterCondition(
330
+ seed: Seed,
331
+ filter: { column: string; op: string; value: unknown },
332
+ conditions: string[],
333
+ bindings: unknown[],
334
+ ): void {
335
+ if (!ALLOWED_FILTER_OPERATORS.has(filter.op)) return
336
+
337
+ let column: string
338
+ try {
339
+ column = this.resolveColumnExpression(seed, filter.column)
340
+ } catch {
341
+ return
342
+ }
343
+
344
+ switch (filter.op) {
345
+ case 'eq':
346
+ case '=':
347
+ conditions.push(`${column} = ?`)
348
+ bindings.push(filter.value)
349
+ return
350
+ case 'neq':
351
+ case '!=':
352
+ conditions.push(`${column} != ?`)
353
+ bindings.push(filter.value)
354
+ return
355
+ case 'like':
356
+ conditions.push(`${column} LIKE ?`)
357
+ bindings.push(filter.value)
358
+ return
359
+ case 'gt':
360
+ case '>':
361
+ conditions.push(`CAST(${column} AS REAL) > ?`)
362
+ bindings.push(filter.value)
363
+ return
364
+ case 'lt':
365
+ case '<':
366
+ conditions.push(`CAST(${column} AS REAL) < ?`)
367
+ bindings.push(filter.value)
368
+ return
369
+ }
370
+ }
371
+
372
+ private buildListOrderClause(seed: Seed, options: WidgetListOptions): string {
373
+ let orderColumn = 'created_at'
374
+ if (options.orderByColumn) {
375
+ try {
376
+ orderColumn = this.resolveColumnExpression(seed, options.orderByColumn)
377
+ } catch {
378
+ orderColumn = 'created_at'
379
+ }
380
+ }
381
+ return options.orderDirection === 'DESC'
382
+ ? `ORDER BY ${orderColumn} DESC`
383
+ : `ORDER BY ${orderColumn} ASC`
384
+ }
385
+ }