@20baht/definitions 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nattapong Promthong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,98 @@
1
- # Temporary Holding Version
1
+ # @20baht/definitions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Form and workflow definitions kept in storage instead of in code. Fields, columns and approval steps
4
+ change more often than the app is deployed, so the definition lives in a database and the copy in
5
+ code is only a seed.
6
+
7
+ A name (`contact`, `it-request`) moves **draft → publish → activate**:
8
+
9
+ - **draft**: the edit in progress, saved as the builder holds it, valid or not;
10
+ - **publish**: checks the draft with `parseSchema` (the server's gate, with your registry) and
11
+ freezes it as the next version (1, 2, 3…), never changed after;
12
+ - **activate**: one version is the one new submissions use. A rollback is activating an older one.
13
+
14
+ A version stored years ago is read in today's wire spelling (camelCase keys from before 0.3.0,
15
+ an `assignment` from before 0.2.0). The row itself is never rewritten.
16
+
17
+ ```bash
18
+ bun add @20baht/definitions drizzle-orm
19
+ ```
20
+
21
+ ## Tables
22
+
23
+ Add them to your drizzle schema, so your own migrations (`drizzle-kit generate`) create them:
24
+
25
+ ```ts
26
+ // schema.ts
27
+ import { definitionTables } from '@20baht/definitions/pg';
28
+
29
+ export const { heads, versions } = definitionTables(); // baht_definitions, baht_definition_versions
30
+ // definitionTables({ prefix: 'app_' }) names them app_…
31
+ ```
32
+
33
+ ## The service
34
+
35
+ ```ts
36
+ import { createDefinitions, seed } from '@20baht/definitions';
37
+ import { pgStorage } from '@20baht/definitions/pg';
38
+ import { readDefinitionFiles } from '@20baht/definitions/files';
39
+ import { heads, versions } from './schema';
40
+
41
+ export const definitions = createDefinitions({
42
+ storage: pgStorage({ db, tables: { heads, versions } }), // any drizzle Postgres database
43
+ registry, // the one the forms render with: its `fieldTypes` are valid at publish
44
+ // upgrade: (json) => json, // your own spelling changes, after the library's (idempotent)
45
+ });
46
+
47
+ // on start: what storage lacks is published as version 1 and activated; the rest is left alone,
48
+ // so an edit published from the builder is never overwritten by the copy in code
49
+ await seed(definitions, await readDefinitionFiles('src/workflows'));
50
+ ```
51
+
52
+ | Call | What it does |
53
+ | --- | --- |
54
+ | `active(name)` / `active<typeof form>(name)` | The version new submissions use (`undefined` when none) |
55
+ | `version(name, n)` | One published version, as it was published |
56
+ | `versions(name)` | Every version without its content, newest first, with `active` |
57
+ | `list()` | Every name: kind, `active`, `latest`, whether it has a draft |
58
+ | `draft(name)` / `saveDraft(name, json, { by })` / `discardDraft(name)` | The edit in progress. `saveDraft` answers `issue`: the first thing wrong, or `null` |
59
+ | `check(json)` | `parseSchema` with your registry, storing nothing |
60
+ | `publish(name, { by, activate?, definition? })` | Freezes the draft (or `definition`) as the next version |
61
+ | `activate(name, n)` | Makes version `n` the active one |
62
+
63
+ A refusal is `{ ok: false, reason, message }`: `bad-name` (a name is one path segment: letters,
64
+ digits, `.`, `_`, `-`), `no-draft`, `invalid` (what `parseSchema` said), `kind-changed` (a name keeps
65
+ the kind it was first published with: form or workflow), `unchanged` (the latest version is this
66
+ content already) and `not-found`.
67
+
68
+ `memoryStorage()` keeps everything in memory, for tests and dev servers. Another store (D1, S3)
69
+ is an object with the methods of `DefinitionStorage`; each is one atomic step.
70
+
71
+ ## Routes
72
+
73
+ ```ts
74
+ import { definitionRoutes } from '@20baht/definitions/elysia';
75
+
76
+ new Elysia()
77
+ .use(cors({ origin: 'https://builder.example.com' })) // the builder is a site of its own
78
+ .use(
79
+ definitionRoutes(definitions, {
80
+ // who is asking, or nothing for a 403; action is read | edit | publish | activate
81
+ authorize: ({ request, action, name }) => callerOf(request, action),
82
+ }),
83
+ );
84
+ ```
85
+
86
+ | Route | |
87
+ | --- | --- |
88
+ | `GET /definitions/` | `list()` |
89
+ | `GET /definitions/:name` | the active version, 404 when none |
90
+ | `GET /definitions/:name/versions`, `GET /definitions/:name/versions/:version` | versions |
91
+ | `GET`, `PUT { definition }`, `DELETE /definitions/:name/draft` | the draft |
92
+ | `POST /definitions/check { definition }` | `check`: `{ kind }` or 422 |
93
+ | `POST /definitions/:name/publish { activate? }` | publish the draft |
94
+ | `POST /definitions/:name/activate { version }` | activate |
95
+
96
+ A refusal answers `{ reason, message }` with 400 (`bad-name`), 403 (`denied`), 404 (`no-draft`,
97
+ `not-found`), 409 (`kind-changed`, `unchanged`) or 422 (`invalid`). Every route is in the OpenAPI
98
+ document, so `@20baht/elysia-openapi-mcp` gives them to agents as tools.
@@ -0,0 +1,363 @@
1
+ import { Elysia } from 'elysia';
2
+ import type { Definitions } from './types.js';
3
+ /** What a route does, as `authorize` is asked about it. */
4
+ export type DefinitionAction = 'read' | 'edit' | 'publish' | 'activate';
5
+ export interface DefinitionRoutesOptions {
6
+ /** Where the routes sit. Default `/definitions`. */
7
+ prefix?: string;
8
+ /**
9
+ * Who is asking, or nothing when they may not: the route answers 403. `name` is the
10
+ * definition the route is about (`null` for the list and `check`).
11
+ */
12
+ authorize: (input: {
13
+ request: Request;
14
+ action: DefinitionAction;
15
+ name: string | null;
16
+ }) => {
17
+ by: string;
18
+ } | null | undefined | Promise<{
19
+ by: string;
20
+ } | null | undefined>;
21
+ }
22
+ /** The routes of one app's definitions, under `prefix`. */
23
+ export declare function definitionRoutes(definitions: Definitions, options: DefinitionRoutesOptions): Elysia<string, {
24
+ decorator: {};
25
+ store: {};
26
+ derive: {};
27
+ resolve: {};
28
+ }, {
29
+ typebox: {};
30
+ error: {};
31
+ }, {
32
+ schema: {};
33
+ standaloneSchema: {};
34
+ macro: {};
35
+ macroFn: {};
36
+ parser: {};
37
+ response: {};
38
+ }, {
39
+ [x: string]: {
40
+ get: {
41
+ body: unknown;
42
+ params: {};
43
+ query: unknown;
44
+ headers: unknown;
45
+ response: {
46
+ 200: import("./types.js").DefinitionSummary[];
47
+ };
48
+ };
49
+ };
50
+ } & {
51
+ [x: string]: {
52
+ check: {
53
+ post: {
54
+ body: {
55
+ definition: unknown;
56
+ };
57
+ params: {};
58
+ query: unknown;
59
+ headers: unknown;
60
+ response: {
61
+ 422: {
62
+ readonly reason: "invalid";
63
+ readonly message: string;
64
+ } | {
65
+ type: "validation";
66
+ on: string;
67
+ summary?: string;
68
+ message?: string;
69
+ found?: unknown;
70
+ property?: string;
71
+ expected?: string;
72
+ };
73
+ 200: {
74
+ kind: import("./types.js").DefinitionKind;
75
+ };
76
+ };
77
+ };
78
+ };
79
+ };
80
+ } & {
81
+ [x: string]: {
82
+ ":name": {
83
+ get: {
84
+ body: unknown;
85
+ params: {
86
+ name: string;
87
+ };
88
+ query: unknown;
89
+ headers: unknown;
90
+ response: {
91
+ 404: {
92
+ readonly reason: "not-found";
93
+ readonly message: string;
94
+ };
95
+ 422: {
96
+ type: "validation";
97
+ on: string;
98
+ summary?: string;
99
+ message?: string;
100
+ found?: unknown;
101
+ property?: string;
102
+ expected?: string;
103
+ };
104
+ 200: import("./types.js").DefinitionVersion<import("./types.js").Definition>;
105
+ };
106
+ };
107
+ };
108
+ };
109
+ } & {
110
+ [x: string]: {
111
+ ":name": {
112
+ versions: {
113
+ get: {
114
+ body: unknown;
115
+ params: {
116
+ name: string;
117
+ };
118
+ query: unknown;
119
+ headers: unknown;
120
+ response: {
121
+ 422: {
122
+ type: "validation";
123
+ on: string;
124
+ summary?: string;
125
+ message?: string;
126
+ found?: unknown;
127
+ property?: string;
128
+ expected?: string;
129
+ };
130
+ 200: import("./types.js").VersionInfo[];
131
+ };
132
+ };
133
+ };
134
+ };
135
+ };
136
+ } & {
137
+ [x: string]: {
138
+ ":name": {
139
+ versions: {
140
+ ":version": {
141
+ get: {
142
+ body: unknown;
143
+ params: {
144
+ name: string;
145
+ version: number;
146
+ };
147
+ query: unknown;
148
+ headers: unknown;
149
+ response: {
150
+ 404: {
151
+ readonly reason: "not-found";
152
+ readonly message: string;
153
+ };
154
+ 422: {
155
+ type: "validation";
156
+ on: string;
157
+ summary?: string;
158
+ message?: string;
159
+ found?: unknown;
160
+ property?: string;
161
+ expected?: string;
162
+ };
163
+ 200: import("./types.js").DefinitionVersion<import("./types.js").Definition>;
164
+ };
165
+ };
166
+ };
167
+ };
168
+ };
169
+ };
170
+ } & {
171
+ [x: string]: {
172
+ ":name": {
173
+ draft: {
174
+ get: {
175
+ body: unknown;
176
+ params: {
177
+ name: string;
178
+ };
179
+ query: unknown;
180
+ headers: unknown;
181
+ response: {
182
+ 404: {
183
+ readonly reason: "not-found";
184
+ readonly message: string;
185
+ };
186
+ 422: {
187
+ type: "validation";
188
+ on: string;
189
+ summary?: string;
190
+ message?: string;
191
+ found?: unknown;
192
+ property?: string;
193
+ expected?: string;
194
+ };
195
+ 200: import("./types.js").Draft;
196
+ };
197
+ };
198
+ };
199
+ };
200
+ };
201
+ } & {
202
+ [x: string]: {
203
+ ":name": {
204
+ draft: {
205
+ put: {
206
+ body: {
207
+ definition: unknown;
208
+ };
209
+ params: {
210
+ name: string;
211
+ };
212
+ query: unknown;
213
+ headers: unknown;
214
+ response: {
215
+ 400: {
216
+ readonly reason: "kind-changed" | "bad-name";
217
+ readonly message: string;
218
+ };
219
+ 409: {
220
+ readonly reason: "kind-changed" | "bad-name";
221
+ readonly message: string;
222
+ };
223
+ 422: {
224
+ type: "validation";
225
+ on: string;
226
+ summary?: string;
227
+ message?: string;
228
+ found?: unknown;
229
+ property?: string;
230
+ expected?: string;
231
+ };
232
+ 200: {
233
+ draft: import("./types.js").Draft;
234
+ issue: string | null;
235
+ };
236
+ };
237
+ };
238
+ };
239
+ };
240
+ };
241
+ } & {
242
+ [x: string]: {
243
+ ":name": {
244
+ draft: {
245
+ delete: {
246
+ body: unknown;
247
+ params: {
248
+ name: string;
249
+ };
250
+ query: unknown;
251
+ headers: unknown;
252
+ response: {
253
+ 404: {
254
+ readonly reason: "not-found";
255
+ readonly message: string;
256
+ };
257
+ 422: {
258
+ type: "validation";
259
+ on: string;
260
+ summary?: string;
261
+ message?: string;
262
+ found?: unknown;
263
+ property?: string;
264
+ expected?: string;
265
+ };
266
+ 200: {
267
+ discarded: boolean;
268
+ };
269
+ };
270
+ };
271
+ };
272
+ };
273
+ };
274
+ } & {
275
+ [x: string]: {
276
+ ":name": {
277
+ publish: {
278
+ post: {
279
+ body: Partial<{
280
+ activate?: boolean;
281
+ }> | null;
282
+ params: {
283
+ name: string;
284
+ };
285
+ query: unknown;
286
+ headers: unknown;
287
+ response: {
288
+ 400: {
289
+ readonly reason: "invalid" | "kind-changed" | "bad-name" | "no-draft" | "unchanged";
290
+ readonly message: string;
291
+ };
292
+ 404: {
293
+ readonly reason: "invalid" | "kind-changed" | "bad-name" | "no-draft" | "unchanged";
294
+ readonly message: string;
295
+ };
296
+ 409: {
297
+ readonly reason: "invalid" | "kind-changed" | "bad-name" | "no-draft" | "unchanged";
298
+ readonly message: string;
299
+ };
300
+ 422: {
301
+ readonly reason: "invalid" | "kind-changed" | "bad-name" | "no-draft" | "unchanged";
302
+ readonly message: string;
303
+ } | {
304
+ type: "validation";
305
+ on: string;
306
+ summary?: string;
307
+ message?: string;
308
+ found?: unknown;
309
+ property?: string;
310
+ expected?: string;
311
+ };
312
+ 200: import("./types.js").DefinitionVersion<import("./types.js").Definition>;
313
+ };
314
+ };
315
+ };
316
+ };
317
+ };
318
+ } & {
319
+ [x: string]: {
320
+ ":name": {
321
+ activate: {
322
+ post: {
323
+ body: {
324
+ version: number;
325
+ };
326
+ params: {
327
+ name: string;
328
+ };
329
+ query: unknown;
330
+ headers: unknown;
331
+ response: {
332
+ 404: {
333
+ readonly reason: "not-found";
334
+ readonly message: string;
335
+ };
336
+ 422: {
337
+ type: "validation";
338
+ on: string;
339
+ summary?: string;
340
+ message?: string;
341
+ found?: unknown;
342
+ property?: string;
343
+ expected?: string;
344
+ };
345
+ 200: import("./types.js").DefinitionVersion<import("./types.js").Definition>;
346
+ };
347
+ };
348
+ };
349
+ };
350
+ };
351
+ }, {
352
+ derive: {};
353
+ resolve: {};
354
+ schema: {};
355
+ standaloneSchema: {};
356
+ response: {};
357
+ }, {
358
+ derive: {};
359
+ resolve: {};
360
+ schema: {};
361
+ standaloneSchema: {};
362
+ response: {};
363
+ }>;
package/dist/elysia.js ADDED
@@ -0,0 +1,101 @@
1
+ import { Elysia, status, t } from 'elysia';
2
+ const STATUS = {
3
+ 'bad-name': 400,
4
+ 'no-draft': 404,
5
+ 'not-found': 404,
6
+ 'kind-changed': 409,
7
+ unchanged: 409,
8
+ invalid: 422,
9
+ };
10
+ const answer = (refusal) => status(STATUS[refusal.reason], { reason: refusal.reason, message: refusal.message });
11
+ const notFound = (message) => status(404, { reason: 'not-found', message });
12
+ const name = t.Object({ name: t.String() });
13
+ const tags = ['definitions'];
14
+ export function definitionRoutes(definitions, options) {
15
+ const ask = async (request, action, of) => {
16
+ const who = await options.authorize({ request, action, name: of });
17
+ if (!who) {
18
+ throw status(403, { reason: 'denied', message: `not allowed to ${action} definitions` });
19
+ }
20
+ return who;
21
+ };
22
+ return new Elysia({ prefix: options.prefix ?? '/definitions' })
23
+ .get('/', async ({ request }) => {
24
+ await ask(request, 'read', null);
25
+ return definitions.list();
26
+ }, { detail: { tags, summary: 'List the definitions: kind, active and latest version, draft' } })
27
+ .post('/check', async ({ request, body }) => {
28
+ await ask(request, 'edit', null);
29
+ const checked = definitions.check(body.definition);
30
+ return checked.ok ? { kind: checked.kind } : answer(checked);
31
+ }, {
32
+ body: t.Object({ definition: t.Unknown() }),
33
+ detail: { tags, summary: 'Check a definition with parseSchema, storing nothing' },
34
+ })
35
+ .get('/:name', async ({ request, params }) => {
36
+ await ask(request, 'read', params.name);
37
+ return ((await definitions.active(params.name)) ??
38
+ notFound(`${params.name} has no active version`));
39
+ }, { params: name, detail: { tags, summary: 'The active version of a definition' } })
40
+ .get('/:name/versions', async ({ request, params }) => {
41
+ await ask(request, 'read', params.name);
42
+ return definitions.versions(params.name);
43
+ }, { params: name, detail: { tags, summary: "A definition's versions, newest first" } })
44
+ .get('/:name/versions/:version', async ({ request, params }) => {
45
+ await ask(request, 'read', params.name);
46
+ return ((await definitions.version(params.name, params.version)) ??
47
+ notFound(`${params.name} has no version ${params.version}`));
48
+ }, {
49
+ params: t.Object({ name: t.String(), version: t.Integer({ minimum: 1 }) }),
50
+ detail: { tags, summary: 'One published version of a definition' },
51
+ })
52
+ .get('/:name/draft', async ({ request, params }) => {
53
+ await ask(request, 'edit', params.name);
54
+ return (await definitions.draft(params.name)) ?? notFound(`${params.name} has no draft`);
55
+ }, { params: name, detail: { tags, summary: 'The draft of a definition' } })
56
+ .put('/:name/draft', async ({ request, params, body }) => {
57
+ const { by } = await ask(request, 'edit', params.name);
58
+ const saved = await definitions.saveDraft(params.name, body.definition, { by });
59
+ return saved.ok ? { draft: saved.draft, issue: saved.issue } : answer(saved);
60
+ }, {
61
+ params: name,
62
+ body: t.Object({ definition: t.Unknown() }),
63
+ detail: {
64
+ tags,
65
+ summary: 'Save the draft of a definition, valid or not; `issue` is the first thing wrong',
66
+ },
67
+ })
68
+ .delete('/:name/draft', async ({ request, params }) => {
69
+ await ask(request, 'edit', params.name);
70
+ return (await definitions.discardDraft(params.name))
71
+ ? { discarded: true }
72
+ : notFound(`${params.name} has no draft`);
73
+ }, { params: name, detail: { tags, summary: 'Discard the draft of a definition' } })
74
+ .post('/:name/publish', async ({ request, params, body }) => {
75
+ const { by } = await ask(request, 'publish', params.name);
76
+ const published = await definitions.publish(params.name, {
77
+ by,
78
+ activate: body?.activate ?? false,
79
+ });
80
+ return published.ok ? published.version : answer(published);
81
+ }, {
82
+ params: name,
83
+ body: t.Optional(t.Object({ activate: t.Optional(t.Boolean()) })),
84
+ detail: {
85
+ tags,
86
+ summary: 'Publish the draft as the next version; `activate` makes it the active one',
87
+ },
88
+ })
89
+ .post('/:name/activate', async ({ request, params, body }) => {
90
+ await ask(request, 'activate', params.name);
91
+ const activated = await definitions.activate(params.name, body.version);
92
+ return activated.ok ? activated.version : answer(activated);
93
+ }, {
94
+ params: name,
95
+ body: t.Object({ version: t.Integer({ minimum: 1 }) }),
96
+ detail: {
97
+ tags,
98
+ summary: 'Make a published version the active one (a rollback is an older version)',
99
+ },
100
+ });
101
+ }
@@ -0,0 +1,4 @@
1
+ import type { SeedEntry } from './seed.js';
2
+ /** Every `*.json` file directly in `dir`, in name order, as seed entries. */
3
+ export declare function readDefinitionFiles(dir: string): Promise<SeedEntry[]>;
4
+ export type { SeedEntry } from './seed.js';
package/dist/files.js ADDED
@@ -0,0 +1,9 @@
1
+ import { readdir, readFile } from 'node:fs/promises';
2
+ import { basename, join } from 'node:path';
3
+ export async function readDefinitionFiles(dir) {
4
+ const names = (await readdir(dir)).filter((file) => file.endsWith('.json')).sort();
5
+ return Promise.all(names.map(async (file) => ({
6
+ name: basename(file, '.json'),
7
+ definition: JSON.parse(await readFile(join(dir, file), 'utf8')),
8
+ })));
9
+ }
package/dist/hash.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** The SHA-256 of a definition's content, keys in order: equal content, equal hash. */
2
+ export declare function contentHash(definition: unknown): Promise<string>;
package/dist/hash.js ADDED
@@ -0,0 +1,17 @@
1
+ function canonical(value) {
2
+ if (Array.isArray(value))
3
+ return `[${value.map(canonical).join(',')}]`;
4
+ if (typeof value !== 'object' || value === null)
5
+ return JSON.stringify(value);
6
+ const record = value;
7
+ const entries = Object.keys(record)
8
+ .sort()
9
+ .filter((key) => record[key] !== undefined)
10
+ .map((key) => `${JSON.stringify(key)}:${canonical(record[key])}`);
11
+ return `{${entries.join(',')}}`;
12
+ }
13
+ export async function contentHash(definition) {
14
+ const bytes = new TextEncoder().encode(canonical(definition));
15
+ const digest = await crypto.subtle.digest('SHA-256', bytes);
16
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
17
+ }
@@ -0,0 +1,6 @@
1
+ export { createDefinitions } from './service.js';
2
+ export { memoryStorage } from './memory.js';
3
+ export { seed, type SeedEntry, type SeedReport } from './seed.js';
4
+ export { upgradeDefinition } from './upgrade.js';
5
+ export { contentHash } from './hash.js';
6
+ export type * from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { createDefinitions } from './service.js';
2
+ export { memoryStorage } from './memory.js';
3
+ export { seed } from './seed.js';
4
+ export { upgradeDefinition } from './upgrade.js';
5
+ export { contentHash } from './hash.js';
@@ -0,0 +1,3 @@
1
+ import type { DefinitionStorage } from './types.js';
2
+ /** A `DefinitionStorage` in a `Map`. Nothing outlives the process. */
3
+ export declare function memoryStorage(): DefinitionStorage;