@weft-framework/server 0.0.0-stage → 0.0.3

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 (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -2
  3. package/dist/account.d.ts +124 -0
  4. package/dist/account.js +344 -0
  5. package/dist/action.d.ts +43 -0
  6. package/dist/action.js +135 -0
  7. package/dist/admin.d.ts +99 -0
  8. package/dist/admin.js +431 -0
  9. package/dist/api.d.ts +21 -0
  10. package/dist/api.js +72 -0
  11. package/dist/app.d.ts +202 -0
  12. package/dist/app.js +3692 -0
  13. package/dist/assets.d.ts +4 -0
  14. package/dist/assets.js +91 -0
  15. package/dist/auth.d.ts +150 -0
  16. package/dist/auth.js +215 -0
  17. package/dist/backup.d.ts +46 -0
  18. package/dist/backup.js +345 -0
  19. package/dist/build.d.ts +33 -0
  20. package/dist/build.js +274 -0
  21. package/dist/bun.d.ts +30 -0
  22. package/dist/bun.js +53 -0
  23. package/dist/calendar.d.ts +161 -0
  24. package/dist/calendar.js +690 -0
  25. package/dist/compiler.d.ts +13 -0
  26. package/dist/compiler.js +58 -0
  27. package/dist/compress.d.ts +6 -0
  28. package/dist/compress.js +78 -0
  29. package/dist/config.d.ts +26 -0
  30. package/dist/config.js +317 -0
  31. package/dist/context.d.ts +9 -0
  32. package/dist/context.js +1 -0
  33. package/dist/contract.d.ts +18 -0
  34. package/dist/contract.js +171 -0
  35. package/dist/datamap.d.ts +24 -0
  36. package/dist/datamap.js +365 -0
  37. package/dist/db-backup.d.ts +27 -0
  38. package/dist/db-backup.js +115 -0
  39. package/dist/dev-events.d.ts +14 -0
  40. package/dist/dev-events.js +135 -0
  41. package/dist/dev.d.ts +1 -0
  42. package/dist/dev.js +240 -0
  43. package/dist/devtools-client.d.ts +1 -0
  44. package/dist/devtools-client.js +362 -0
  45. package/dist/devtools.d.ts +87 -0
  46. package/dist/devtools.js +68 -0
  47. package/dist/edge.d.ts +3 -0
  48. package/dist/edge.js +7 -0
  49. package/dist/email-signin.d.ts +92 -0
  50. package/dist/email-signin.js +259 -0
  51. package/dist/env.d.ts +1 -0
  52. package/dist/env.js +15 -0
  53. package/dist/explain.d.ts +12 -0
  54. package/dist/explain.js +217 -0
  55. package/dist/files.d.ts +6 -0
  56. package/dist/files.js +170 -0
  57. package/dist/grants.d.ts +69 -0
  58. package/dist/grants.js +206 -0
  59. package/dist/image/bitmap.d.ts +11 -0
  60. package/dist/image/bitmap.js +172 -0
  61. package/dist/image/jpeg.d.ts +10 -0
  62. package/dist/image/jpeg.js +697 -0
  63. package/dist/image/png.d.ts +8 -0
  64. package/dist/image/png.js +282 -0
  65. package/dist/image/transform.d.ts +20 -0
  66. package/dist/image/transform.js +52 -0
  67. package/dist/image/worker.d.ts +1 -0
  68. package/dist/image/worker.js +11 -0
  69. package/dist/images.d.ts +39 -0
  70. package/dist/images.js +283 -0
  71. package/dist/index.d.ts +64 -0
  72. package/dist/index.js +31 -0
  73. package/dist/inspect-hub.d.ts +42 -0
  74. package/dist/inspect-hub.js +14 -0
  75. package/dist/inspector.d.ts +51 -0
  76. package/dist/inspector.js +193 -0
  77. package/dist/job-admin.d.ts +55 -0
  78. package/dist/job-admin.js +89 -0
  79. package/dist/jobs.d.ts +222 -0
  80. package/dist/jobs.js +789 -0
  81. package/dist/live.d.ts +72 -0
  82. package/dist/live.js +481 -0
  83. package/dist/load-config.d.ts +2 -0
  84. package/dist/load-config.js +41 -0
  85. package/dist/log.d.ts +20 -0
  86. package/dist/log.js +143 -0
  87. package/dist/mail.d.ts +189 -0
  88. package/dist/mail.js +999 -0
  89. package/dist/media.d.ts +129 -0
  90. package/dist/media.js +470 -0
  91. package/dist/meta.d.ts +54 -0
  92. package/dist/meta.js +146 -0
  93. package/dist/middleware.d.ts +20 -0
  94. package/dist/middleware.js +101 -0
  95. package/dist/migrate.d.ts +12 -0
  96. package/dist/migrate.js +88 -0
  97. package/dist/node.d.ts +26 -0
  98. package/dist/node.js +96 -0
  99. package/dist/notice.d.ts +21 -0
  100. package/dist/notice.js +48 -0
  101. package/dist/npm.d.ts +16 -0
  102. package/dist/npm.js +347 -0
  103. package/dist/oauth.d.ts +76 -0
  104. package/dist/oauth.js +408 -0
  105. package/dist/otel.d.ts +57 -0
  106. package/dist/otel.js +293 -0
  107. package/dist/passkey.d.ts +99 -0
  108. package/dist/passkey.js +572 -0
  109. package/dist/password.d.ts +8 -0
  110. package/dist/password.js +65 -0
  111. package/dist/pdf.d.ts +46 -0
  112. package/dist/pdf.js +332 -0
  113. package/dist/personal-data.d.ts +22 -0
  114. package/dist/personal-data.js +148 -0
  115. package/dist/pointers.d.ts +9 -0
  116. package/dist/pointers.js +148 -0
  117. package/dist/postcss.d.ts +3 -0
  118. package/dist/postcss.js +89 -0
  119. package/dist/presence.d.ts +27 -0
  120. package/dist/presence.js +161 -0
  121. package/dist/preview.d.ts +25 -0
  122. package/dist/preview.js +353 -0
  123. package/dist/production.d.ts +16 -0
  124. package/dist/production.js +119 -0
  125. package/dist/project.d.ts +23 -0
  126. package/dist/project.js +536 -0
  127. package/dist/regions.d.ts +47 -0
  128. package/dist/regions.js +511 -0
  129. package/dist/replay.d.ts +44 -0
  130. package/dist/replay.js +259 -0
  131. package/dist/router.d.ts +29 -0
  132. package/dist/router.js +146 -0
  133. package/dist/rules-diff.d.ts +18 -0
  134. package/dist/rules-diff.js +165 -0
  135. package/dist/rules-test.d.ts +17 -0
  136. package/dist/rules-test.js +108 -0
  137. package/dist/saml.d.ts +160 -0
  138. package/dist/saml.js +959 -0
  139. package/dist/seal.d.ts +35 -0
  140. package/dist/seal.js +107 -0
  141. package/dist/secret.d.ts +14 -0
  142. package/dist/secret.js +110 -0
  143. package/dist/security.d.ts +53 -0
  144. package/dist/security.js +250 -0
  145. package/dist/seed.d.ts +16 -0
  146. package/dist/seed.js +94 -0
  147. package/dist/seo.d.ts +42 -0
  148. package/dist/seo.js +175 -0
  149. package/dist/settings.d.ts +79 -0
  150. package/dist/settings.js +212 -0
  151. package/dist/shared.d.ts +15 -0
  152. package/dist/shared.js +283 -0
  153. package/dist/shell.d.ts +12 -0
  154. package/dist/shell.js +118 -0
  155. package/dist/storage.d.ts +13 -0
  156. package/dist/storage.js +55 -0
  157. package/dist/support.d.ts +83 -0
  158. package/dist/support.js +236 -0
  159. package/dist/sync.d.ts +35 -0
  160. package/dist/sync.js +167 -0
  161. package/dist/tailwind.d.ts +14 -0
  162. package/dist/tailwind.js +117 -0
  163. package/dist/two-factor.d.ts +103 -0
  164. package/dist/two-factor.js +435 -0
  165. package/dist/uploads.d.ts +185 -0
  166. package/dist/uploads.js +991 -0
  167. package/dist/webhooks.d.ts +169 -0
  168. package/dist/webhooks.js +758 -0
  169. package/dist/webpush.d.ts +97 -0
  170. package/dist/webpush.js +372 -0
  171. package/dist/wizard.d.ts +141 -0
  172. package/dist/wizard.js +410 -0
  173. package/dist/workflows.d.ts +134 -0
  174. package/dist/workflows.js +511 -0
  175. package/package.json +186 -4
@@ -0,0 +1,99 @@
1
+ import type { FieldSpec, Model, TableColumn, TableView } from "@weft-framework/data";
2
+ import { type Action } from "./action.js";
3
+ import type { PageContext } from "./context.js";
4
+ type Row = Record<string, unknown>;
5
+ type AnyModel = Model<any, any>;
6
+ export interface AdminField {
7
+ label?: string;
8
+ help?: string;
9
+ readonly?: boolean;
10
+ hidden?: boolean;
11
+ widget?: "input" | "textarea";
12
+ }
13
+ export interface AdminModel<T = any> {
14
+ model: Model<T, any>;
15
+ label?: string;
16
+ list?: readonly (keyof T & string)[];
17
+ search?: readonly (keyof T & string)[];
18
+ filters?: readonly (keyof T & string)[];
19
+ sort?: readonly [keyof T & string, "asc" | "desc"];
20
+ pageSize?: number;
21
+ fields?: {
22
+ [K in keyof T & string]?: AdminField;
23
+ };
24
+ title?: (row: T) => string;
25
+ create?: boolean;
26
+ edit?: boolean;
27
+ delete?: boolean;
28
+ }
29
+ export interface AdminOptions {
30
+ allow: (ctx: PageContext) => boolean | Promise<boolean>;
31
+ models: readonly (AnyModel | AdminModel)[];
32
+ actor?: (ctx: PageContext) => unknown;
33
+ name?: string;
34
+ }
35
+ export interface AdminFieldInfo {
36
+ name: string;
37
+ label: string;
38
+ help: string | null;
39
+ kind: FieldSpec["kind"];
40
+ type: string;
41
+ nullable: boolean;
42
+ required: boolean;
43
+ options: string[] | null;
44
+ readonly: boolean;
45
+ widget: "input" | "textarea";
46
+ isKey: boolean;
47
+ onCreate: boolean;
48
+ onEdit: boolean;
49
+ listed: boolean;
50
+ searchable: boolean;
51
+ filter: TableColumn["filter"] | null;
52
+ }
53
+ export interface AdminModelInfo {
54
+ name: string;
55
+ label: string;
56
+ key: string;
57
+ fields: AdminFieldInfo[];
58
+ list: string[];
59
+ create: boolean;
60
+ edit: boolean;
61
+ delete: boolean;
62
+ }
63
+ export interface AdminRow {
64
+ key: unknown;
65
+ title: string;
66
+ row: Row;
67
+ text: Record<string, string>;
68
+ writable: boolean;
69
+ }
70
+ export type AdminResult = {
71
+ ok: true;
72
+ key: unknown;
73
+ row: Row;
74
+ } | {
75
+ ok: false;
76
+ reason: "not found" | "disabled" | "forbidden" | "conflict";
77
+ error: string;
78
+ } | {
79
+ ok: false;
80
+ reason: "invalid";
81
+ field: string | null;
82
+ error: string;
83
+ };
84
+ export interface Admin {
85
+ overview(ctx: PageContext): Promise<{
86
+ name: string;
87
+ label: string;
88
+ count: number;
89
+ }[] | null>;
90
+ model(name: string): AdminModelInfo | null;
91
+ list(ctx: PageContext, model: string, query?: URL): Promise<TableView<Row> | null>;
92
+ row(ctx: PageContext, model: string, key: unknown): Promise<AdminRow | null>;
93
+ create(ctx: PageContext, model: string, input: Readonly<Record<string, unknown>>): Promise<AdminResult>;
94
+ update(ctx: PageContext, model: string, key: unknown, input: Readonly<Record<string, unknown>>, shown?: Readonly<Record<string, unknown>> | null): Promise<AdminResult>;
95
+ delete(ctx: PageContext, model: string, key: unknown): Promise<AdminResult>;
96
+ actions: Record<string, Action<never[]>>;
97
+ }
98
+ export declare function defineAdmin(opts: AdminOptions): Admin;
99
+ export {};
package/dist/admin.js ADDED
@@ -0,0 +1,431 @@
1
+ import { defineTable } from "@weft-framework/data";
2
+ import { defineAction } from "./action.js";
3
+ const NAME_RE = /^[a-z][A-Za-z0-9]{0,30}$/;
4
+ const MAX_TEXT = 100_000;
5
+ function literalOptions(type) {
6
+ const parts = type.split("|").map((p) => p.trim()).filter((p) => p !== "null" && p !== "undefined");
7
+ if (parts.length === 0)
8
+ return null;
9
+ const out = [];
10
+ for (const p of parts) {
11
+ const m = /^"([^"\\]*)"$/.exec(p) ?? /^'([^'\\]*)'$/.exec(p);
12
+ if (!m)
13
+ return null;
14
+ out.push(m[1]);
15
+ }
16
+ return out;
17
+ }
18
+ function humanize(name) {
19
+ const s = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").trim();
20
+ return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
21
+ }
22
+ function formText(f, v) {
23
+ if (v === null || v === undefined)
24
+ return "";
25
+ switch (f.spec.kind) {
26
+ case "bool":
27
+ return v === true ? "true" : "false";
28
+ case "date":
29
+ return v instanceof Date && !Number.isNaN(v.getTime()) ? v.toISOString() : "";
30
+ case "json":
31
+ return JSON.stringify(v, null, 2);
32
+ default:
33
+ return String(v);
34
+ }
35
+ }
36
+ function parse(f, input) {
37
+ const bad = (what) => ({ ok: false, error: `${f.label}: ${what}` });
38
+ let raw;
39
+ if (typeof input === "string")
40
+ raw = input;
41
+ else if (f.spec.kind === "json")
42
+ raw = JSON.stringify(input ?? null);
43
+ else if (input === null || input === undefined)
44
+ raw = "";
45
+ else if (f.spec.kind === "date" && !(input instanceof Date))
46
+ return bad("is a date");
47
+ else if (typeof input === "object" && !(input instanceof Date))
48
+ return bad("is not a value of this field");
49
+ else
50
+ raw = formText(f, input);
51
+ if (raw.length > MAX_TEXT)
52
+ return bad("too long");
53
+ const empty = raw.trim() === "";
54
+ if (empty && f.spec.kind !== "text")
55
+ return f.spec.nullable ? { ok: true, value: null } : bad("is required");
56
+ switch (f.spec.kind) {
57
+ case "text":
58
+ if (f.options) {
59
+ if (raw === "" && f.spec.nullable)
60
+ return { ok: true, value: null };
61
+ return f.options.includes(raw) ? { ok: true, value: raw } : bad(`is one of ${f.options.join(", ")}`);
62
+ }
63
+ return { ok: true, value: raw === "" && f.spec.nullable ? null : raw };
64
+ case "real": {
65
+ const n = Number(raw.trim());
66
+ return Number.isFinite(n) ? { ok: true, value: n } : bad("is a number");
67
+ }
68
+ case "integer":
69
+ return /^-?\d{1,30}$/.test(raw.trim()) ? { ok: true, value: BigInt(raw.trim()) } : bad("is a whole number");
70
+ case "bool":
71
+ return raw === "true" ? { ok: true, value: true } : raw === "false" ? { ok: true, value: false } : bad("is yes or no");
72
+ case "date": {
73
+ const t = raw.trim();
74
+ const iso = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?$/.test(t) ? `${t}Z` : t;
75
+ if (!/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2}))?$/.test(iso))
76
+ return bad("is a date like 2026-11-14T09:30Z");
77
+ const [y, mo, da] = iso.slice(0, 10).split("-").map(Number);
78
+ const day = new Date(Date.UTC(y, mo - 1, da));
79
+ const d = new Date(iso);
80
+ if (Number.isNaN(d.getTime()) || day.getUTCMonth() !== mo - 1 || day.getUTCDate() !== da)
81
+ return bad("is not a date");
82
+ return { ok: true, value: d };
83
+ }
84
+ case "json":
85
+ try {
86
+ return { ok: true, value: JSON.parse(raw) };
87
+ }
88
+ catch {
89
+ return bad("is not valid JSON");
90
+ }
91
+ }
92
+ }
93
+ function keyValue(f, input) {
94
+ if (typeof input === "bigint")
95
+ return f.kind === "integer" ? input : undefined;
96
+ if (typeof input === "number")
97
+ return f.kind === "real" && Number.isFinite(input) ? input : f.kind === "integer" && Number.isInteger(input) ? BigInt(input) : undefined;
98
+ if (typeof input !== "string")
99
+ return undefined;
100
+ if (f.kind === "real") {
101
+ const n = Number(input);
102
+ return input !== "" && Number.isFinite(n) ? n : undefined;
103
+ }
104
+ if (f.kind === "integer")
105
+ return /^-?\d{1,30}$/.test(input) ? BigInt(input) : undefined;
106
+ return f.kind === "text" ? input : undefined;
107
+ }
108
+ function filterFor(f, options) {
109
+ if (f.kind === "bool")
110
+ return "boolean";
111
+ if (f.kind === "real" || f.kind === "integer")
112
+ return "number";
113
+ if (f.kind === "date")
114
+ return "date";
115
+ if (f.kind === "text")
116
+ return options ? { options } : "text";
117
+ return undefined;
118
+ }
119
+ export function defineAdmin(opts) {
120
+ if (!opts || typeof opts.allow !== "function")
121
+ throw new Error("defineAdmin: `allow(ctx)` is required");
122
+ const prefix = opts.name ?? "admin";
123
+ if (!NAME_RE.test(prefix))
124
+ throw new Error("defineAdmin: name is a lower-case identifier");
125
+ const actorOf = opts.actor ?? ((ctx) => ctx.user);
126
+ const entries = new Map();
127
+ for (const item of opts.models ?? []) {
128
+ const cfg = typeof item.as === "function" ? { model: item } : item;
129
+ const model = cfg.model;
130
+ if (!model || typeof model.as !== "function")
131
+ throw new Error("defineAdmin: models are defineModel(...) results");
132
+ if (entries.has(model.name))
133
+ throw new Error(`defineAdmin: ${model.name} is listed twice`);
134
+ const fail = (msg) => {
135
+ throw new Error(`defineAdmin: ${model.name}: ${msg}`);
136
+ };
137
+ const specs = new Map(model.fields.map((f) => [f.name, f]));
138
+ for (const name of Object.keys(cfg.fields ?? {}))
139
+ if (!specs.has(name))
140
+ fail(`no field \`${name}\``);
141
+ const fields = model.fields.map((spec) => {
142
+ const c = cfg.fields?.[spec.name] ?? {};
143
+ if (c.widget !== undefined && c.widget !== "input" && c.widget !== "textarea")
144
+ fail(`${spec.name}: widget is "input" or "textarea"`);
145
+ return {
146
+ spec,
147
+ name: spec.name,
148
+ label: c.label ?? humanize(spec.name),
149
+ help: c.help ?? "",
150
+ readonly: c.readonly === true || spec.file || model.lockedFields.includes(spec.name),
151
+ hidden: c.hidden === true,
152
+ widget: c.widget ?? (spec.kind === "json" ? "textarea" : "input"),
153
+ options: spec.kind === "text" ? literalOptions(spec.type) : null,
154
+ };
155
+ });
156
+ if (fields.find((f) => f.name === model.key)?.hidden)
157
+ fail("the key cannot be hidden");
158
+ if (cfg.create !== false) {
159
+ for (const f of fields) {
160
+ const unset = (f.hidden || f.readonly) && f.name !== model.key && !model.lockedFields.includes(f.name) && !f.spec.default && !f.spec.nullable && !f.spec.optional;
161
+ if (unset && f.spec.kind !== "text")
162
+ fail(`${f.name} is not set by the admin and has no default; give it one, or create: false`);
163
+ }
164
+ }
165
+ const byName = new Map(fields.map((f) => [f.name, f]));
166
+ const visible = fields.filter((f) => !f.hidden);
167
+ const list = [...(cfg.list ?? [model.key, ...visible.filter((f) => f.name !== model.key && f.spec.kind !== "json").slice(0, 5).map((f) => f.name)])];
168
+ for (const n of list)
169
+ if (!byName.get(n) || byName.get(n).hidden)
170
+ fail(`list: no visible field \`${n}\``);
171
+ const search = new Set(cfg.search ?? list.filter((n) => byName.get(n).spec.kind === "text" && !byName.get(n).spec.file));
172
+ for (const n of search)
173
+ if (!list.includes(n) || byName.get(n).spec.kind !== "text")
174
+ fail(`search: \`${n}\` is a listed text field`);
175
+ const filters = new Set(cfg.filters ?? []);
176
+ for (const n of filters)
177
+ if (!list.includes(n))
178
+ fail(`filters: \`${n}\` is not listed`);
179
+ const columns = {};
180
+ for (const n of list) {
181
+ const f = byName.get(n);
182
+ const filter = filters.has(n) ? (filterFor(f.spec, f.options) ?? fail(`filters: \`${n}\` cannot be filtered`)) : undefined;
183
+ columns[n] = { sort: f.spec.kind !== "json", ...(search.has(n) ? { search: true } : {}), ...(filter ? { filter } : {}) };
184
+ }
185
+ const firstText = list.find((n) => n !== model.key && byName.get(n).spec.kind === "text");
186
+ const table = defineTable(model, {
187
+ columns: columns,
188
+ sort: (cfg.sort ?? [model.key, "asc"]),
189
+ pageSize: cfg.pageSize ?? 25,
190
+ ...(firstText ? { fields: [firstText] } : {}),
191
+ });
192
+ const title = cfg.title ??
193
+ ((row) => {
194
+ const t = firstText ? row[firstText] : undefined;
195
+ return typeof t === "string" && t.trim() !== "" ? t : String(row[model.key]);
196
+ });
197
+ const onCreate = (f) => !f.hidden && !f.readonly && !(f.name === model.key && f.spec.default);
198
+ const onEdit = (f) => !f.hidden && !f.readonly && f.name !== model.key;
199
+ const info = {
200
+ name: model.name,
201
+ label: cfg.label ?? model.name,
202
+ key: model.key,
203
+ list,
204
+ create: cfg.create !== false,
205
+ edit: cfg.edit !== false,
206
+ delete: cfg.delete !== false,
207
+ fields: visible.map((f) => ({
208
+ name: f.name,
209
+ label: f.label,
210
+ help: f.help || null,
211
+ kind: f.spec.kind,
212
+ type: f.spec.type,
213
+ nullable: f.spec.nullable,
214
+ required: !f.spec.default && !f.spec.nullable && !f.spec.optional && f.spec.kind !== "text",
215
+ options: f.options,
216
+ readonly: f.readonly,
217
+ widget: f.widget,
218
+ isKey: f.name === model.key,
219
+ onCreate: onCreate(f),
220
+ onEdit: onEdit(f),
221
+ listed: list.includes(f.name),
222
+ searchable: search.has(f.name),
223
+ filter: columns[f.name]?.filter ?? null,
224
+ })),
225
+ };
226
+ entries.set(model.name, {
227
+ model,
228
+ label: info.label,
229
+ fields,
230
+ byName,
231
+ list,
232
+ table,
233
+ title: title,
234
+ create: info.create,
235
+ edit: info.edit,
236
+ delete: info.delete,
237
+ info: deepFreeze(info),
238
+ });
239
+ }
240
+ if (entries.size === 0)
241
+ throw new Error("defineAdmin: list at least one model");
242
+ async function gate(ctx) {
243
+ try {
244
+ return (await opts.allow(ctx)) === true;
245
+ }
246
+ catch {
247
+ return false;
248
+ }
249
+ }
250
+ async function admitted(ctx, name) {
251
+ if (typeof name !== "string" || !(await gate(ctx)))
252
+ return null;
253
+ return entries.get(name) ?? null;
254
+ }
255
+ const scoped = (ctx, e) => e.model.as(actorOf(ctx));
256
+ function find(ctx, e, rawKey) {
257
+ const key = keyValue(e.byName.get(e.model.key).spec, rawKey);
258
+ if (key === undefined)
259
+ return null;
260
+ const row = scoped(ctx, e).get(key);
261
+ return row ? { key, row } : null;
262
+ }
263
+ const visibleRow = (e, row) => Object.fromEntries(e.fields.filter((f) => !f.hidden).map((f) => [f.name, row[f.name]]));
264
+ function values(fields, input, before, shown) {
265
+ const out = {};
266
+ for (const f of fields) {
267
+ if (!Object.hasOwn(input, f.name))
268
+ continue;
269
+ const v = parse(f, input[f.name]);
270
+ if (!v.ok)
271
+ return { refused: { ok: false, reason: "invalid", field: f.name, error: v.error } };
272
+ if (before) {
273
+ const now = formText(f, before[f.name]);
274
+ const was = shown && Object.hasOwn(shown, f.name) ? (typeof shown[f.name] === "string" ? shown[f.name] : formText(f, shown[f.name])) : now;
275
+ const next = formText(f, v.value);
276
+ if (next === was || next === now)
277
+ continue;
278
+ }
279
+ out[f.name] = v.value;
280
+ }
281
+ return { values: out };
282
+ }
283
+ function friendly(err, e) {
284
+ const msg = err instanceof Error ? err.message : "";
285
+ const m = /unique field (\w+)|UNIQUE constraint failed: \S+?\.(\w+)/.exec(msg);
286
+ if (m) {
287
+ const f = e.byName.get(m[1] ?? m[2] ?? "");
288
+ return { ok: false, reason: "conflict", error: `${f ? f.label : "A value"} is already used by another row` };
289
+ }
290
+ if (/duplicate key|PRIMARY KEY|already exists/i.test(msg))
291
+ return { ok: false, reason: "conflict", error: "A row with this key exists already" };
292
+ throw err;
293
+ }
294
+ const NOT_FOUND = { ok: false, reason: "not found", error: "Not found" };
295
+ const admin = {
296
+ async overview(ctx) {
297
+ if (!(await gate(ctx)))
298
+ return null;
299
+ return [...entries.values()].map((e) => ({ name: e.model.name, label: e.label, count: scoped(ctx, e).query().count() }));
300
+ },
301
+ model: (name) => entries.get(name)?.info ?? null,
302
+ async list(ctx, model, query) {
303
+ const e = await admitted(ctx, model);
304
+ if (!e)
305
+ return null;
306
+ return e.table.view(scoped(ctx, e), query ?? ctx.url);
307
+ },
308
+ async row(ctx, model, key) {
309
+ const e = await admitted(ctx, model);
310
+ if (!e)
311
+ return null;
312
+ const found = find(ctx, e, key);
313
+ if (!found)
314
+ return null;
315
+ const text = Object.fromEntries(e.fields.filter((f) => !f.hidden).map((f) => [f.name, formText(f, found.row[f.name])]));
316
+ return { key: found.key, title: e.title(found.row), row: visibleRow(e, found.row), text, writable: scoped(ctx, e).writable(found.row) };
317
+ },
318
+ async create(ctx, model, input) {
319
+ const e = await admitted(ctx, model);
320
+ if (!e)
321
+ return NOT_FOUND;
322
+ if (!e.create)
323
+ return { ok: false, reason: "disabled", error: "Rows of this model are not created here" };
324
+ const fields = e.fields.filter((f) => !f.hidden && !f.readonly && !(f.name === e.model.key && f.spec.default));
325
+ const parsed = values(fields, input ?? {}, null, null);
326
+ if ("refused" in parsed)
327
+ return parsed.refused;
328
+ const row = parsed.values;
329
+ for (const f of e.fields) {
330
+ if (row[f.name] !== undefined || f.spec.default || f.spec.nullable || f.spec.optional)
331
+ continue;
332
+ if (f.spec.kind === "text")
333
+ row[f.name] = "";
334
+ else
335
+ return { ok: false, reason: "invalid", field: f.name, error: `${f.label} is required` };
336
+ }
337
+ let made;
338
+ try {
339
+ made = scoped(ctx, e).create(row);
340
+ }
341
+ catch (err) {
342
+ return friendly(err, e);
343
+ }
344
+ if (!made)
345
+ return { ok: false, reason: "forbidden", error: "You may not create this row" };
346
+ return { ok: true, key: made[e.model.key], row: visibleRow(e, made) };
347
+ },
348
+ async update(ctx, model, key, input, shown = null) {
349
+ const e = await admitted(ctx, model);
350
+ if (!e)
351
+ return NOT_FOUND;
352
+ if (!e.edit)
353
+ return { ok: false, reason: "disabled", error: "Rows of this model are not edited here" };
354
+ const found = find(ctx, e, key);
355
+ if (!found)
356
+ return NOT_FOUND;
357
+ const fields = e.fields.filter((f) => !f.hidden && !f.readonly && f.name !== e.model.key);
358
+ const parsed = values(fields, input ?? {}, found.row, shown);
359
+ if ("refused" in parsed)
360
+ return parsed.refused;
361
+ const patch = parsed.values;
362
+ if (Object.keys(patch).length > 0) {
363
+ const k = e.model.key;
364
+ let n = 0;
365
+ try {
366
+ n = scoped(ctx, e).update((r) => r[k] === found.key, patch);
367
+ }
368
+ catch (err) {
369
+ return friendly(err, e);
370
+ }
371
+ if (n === 0)
372
+ return { ok: false, reason: "forbidden", error: "You may not make this change" };
373
+ }
374
+ return { ok: true, key: found.key, row: visibleRow(e, scoped(ctx, e).get(found.key) ?? found.row) };
375
+ },
376
+ async delete(ctx, model, key) {
377
+ const e = await admitted(ctx, model);
378
+ if (!e)
379
+ return NOT_FOUND;
380
+ if (!e.delete)
381
+ return { ok: false, reason: "disabled", error: "Rows of this model are not deleted here" };
382
+ const found = find(ctx, e, key);
383
+ if (!found)
384
+ return NOT_FOUND;
385
+ const k = e.model.key;
386
+ if (scoped(ctx, e).delete((r) => r[k] === found.key) === 0)
387
+ return { ok: false, reason: "forbidden", error: "You may not delete this row" };
388
+ return { ok: true, key: found.key, row: visibleRow(e, found.row) };
389
+ },
390
+ actions: {},
391
+ };
392
+ const names = [...new Set([...entries.values()].flatMap((e) => e.fields.filter((f) => !f.hidden).map((f) => f.name)))].filter((n) => n !== "model" && n !== "key" && n !== "shown");
393
+ const fieldParams = names.map((name) => ({ name, type: "string", optional: true }));
394
+ const inputOf = (args) => {
395
+ const out = {};
396
+ names.forEach((n, i) => {
397
+ if (typeof args[i] === "string")
398
+ out[n] = args[i];
399
+ });
400
+ return out;
401
+ };
402
+ const head = [{ name: "model", type: "string" }];
403
+ const keyed = [...head, { name: "key", type: "string" }];
404
+ admin.actions = {
405
+ [`${prefix}Create`]: defineAction(`${prefix}Create`, [...head, ...fieldParams], (ctx, model, ...args) => admin.create(ctx, model, inputOf(args))),
406
+ [`${prefix}Update`]: defineAction(`${prefix}Update`, [...keyed, ...fieldParams, { name: "shown", type: "string", optional: true }], (ctx, model, key, ...args) => {
407
+ let shown = null;
408
+ const sent = args[names.length];
409
+ if (typeof sent === "string" && sent.length <= MAX_TEXT) {
410
+ try {
411
+ const s = JSON.parse(sent);
412
+ if (s && typeof s === "object" && !Array.isArray(s))
413
+ shown = s;
414
+ }
415
+ catch {
416
+ }
417
+ }
418
+ return admin.update(ctx, model, key, inputOf(args), shown);
419
+ }),
420
+ [`${prefix}Delete`]: defineAction(`${prefix}Delete`, keyed, (ctx, model, key) => admin.delete(ctx, model, key)),
421
+ };
422
+ return admin;
423
+ }
424
+ function deepFreeze(v) {
425
+ if (v && typeof v === "object" && !Object.isFrozen(v)) {
426
+ Object.freeze(v);
427
+ for (const x of Object.values(v))
428
+ deepFreeze(x);
429
+ }
430
+ return v;
431
+ }
package/dist/api.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import type { PageContext } from "./context.js";
2
+ export type ApiMethod = "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS";
3
+ export type ApiHandler = (ctx: PageContext) => Response | Promise<Response>;
4
+ export declare function external(handler: ApiHandler): ApiHandler;
5
+ export declare function isExternal(handler: ApiHandler): boolean;
6
+ export interface ApiHandlers {
7
+ GET?: ApiHandler;
8
+ HEAD?: ApiHandler;
9
+ POST?: ApiHandler;
10
+ PUT?: ApiHandler;
11
+ PATCH?: ApiHandler;
12
+ DELETE?: ApiHandler;
13
+ OPTIONS?: ApiHandler;
14
+ default?: ApiHandler;
15
+ }
16
+ export declare function isUnsafeMethod(method: string): boolean;
17
+ export declare function isApiMethod(method: string): method is ApiMethod;
18
+ export declare function handlerFor(handlers: ApiHandlers, method: string): ApiHandler | undefined;
19
+ export declare function allowHeader(handlers: ApiHandlers): string;
20
+ export declare function safeLocation(location: string, ownOrigin: string): boolean;
21
+ export declare function guardApiResponse(res: Response, ownOrigin: string): Response | null;
package/dist/api.js ADDED
@@ -0,0 +1,72 @@
1
+ import { isSafePath } from "@weft-framework/runtime";
2
+ const EXTERNAL = Symbol.for("weft.api.external");
3
+ export function external(handler) {
4
+ if (typeof handler !== "function")
5
+ throw new Error("external: wraps an API handler function");
6
+ const fn = (ctx) => handler(ctx);
7
+ Object.defineProperty(fn, EXTERNAL, { value: true });
8
+ return fn;
9
+ }
10
+ export function isExternal(handler) {
11
+ return Object.hasOwn(handler, EXTERNAL) && handler[EXTERNAL] === true;
12
+ }
13
+ const UNSAFE = new Set(["POST", "PUT", "PATCH", "DELETE"]);
14
+ const KNOWN = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]);
15
+ export function isUnsafeMethod(method) {
16
+ return UNSAFE.has(method);
17
+ }
18
+ export function isApiMethod(method) {
19
+ return KNOWN.has(method);
20
+ }
21
+ export function handlerFor(handlers, method) {
22
+ const specific = handlers[method];
23
+ if (specific) {
24
+ return specific;
25
+ }
26
+ if (method === "HEAD" && handlers.GET) {
27
+ return handlers.GET;
28
+ }
29
+ return handlers.default;
30
+ }
31
+ export function allowHeader(handlers) {
32
+ const methods = [];
33
+ const has = (method) => handlers[method] !== undefined || handlers.default !== undefined;
34
+ if (has("GET")) {
35
+ methods.push("GET");
36
+ }
37
+ if (handlers.HEAD || has("GET")) {
38
+ methods.push("HEAD");
39
+ }
40
+ for (const method of ["POST", "PUT", "PATCH", "DELETE"]) {
41
+ if (has(method)) {
42
+ methods.push(method);
43
+ }
44
+ }
45
+ methods.push("OPTIONS");
46
+ return methods.join(", ");
47
+ }
48
+ export function safeLocation(location, ownOrigin) {
49
+ if (location.length === 0 || location.length > 2048 || /[\r\n\0]/.test(location) || location.includes("\\")) {
50
+ return false;
51
+ }
52
+ if (isSafePath(location)) {
53
+ return true;
54
+ }
55
+ try {
56
+ const url = new URL(location);
57
+ return ((url.protocol === "http:" || url.protocol === "https:") &&
58
+ url.origin === ownOrigin &&
59
+ url.username === "" &&
60
+ url.password === "");
61
+ }
62
+ catch {
63
+ return false;
64
+ }
65
+ }
66
+ export function guardApiResponse(res, ownOrigin) {
67
+ const location = res.headers.get("location");
68
+ if (location !== null && !safeLocation(location, ownOrigin)) {
69
+ return null;
70
+ }
71
+ return res;
72
+ }