@dudko.dev/baton-format 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.
@@ -0,0 +1,334 @@
1
+ import { DEFAULT_SETTINGS, } from "./types.js";
2
+ // MARK: - Scalar formatting
3
+ //
4
+ // Canonical rules (invariant 3): plain style wherever YAML allows it
5
+ // unambiguously; double quotes otherwise; literal block scalars for
6
+ // code-like fields. The Dart writer must match this byte for byte —
7
+ // the conformance fixtures in spec/ are the contract.
8
+ const RESERVED = /^(true|false|null|~|yes|no|on|off)$/i;
9
+ const INDICATOR_START = /^[-?:,[\]{}#&*!|>'"%@` ]/;
10
+ const NUMBER_TOKEN_START = /^[+-]?\d\S*\s/;
11
+ /**
12
+ * Anything a YAML reader would take as a number rather than a string.
13
+ *
14
+ * This used to be `Number.isFinite(Number(s))` here and a regex "mirroring
15
+ * what JavaScript's Number() accepts" in Dart. The two did not agree, and the
16
+ * JS side was wrong on its own terms: `Number("1e400")` is Infinity, so
17
+ * `isFinite` said no quotes needed — but YAML 1.2 reads `1e400` as a float,
18
+ * so the TypeScript writer produced a file the TypeScript parser rejected.
19
+ * `Infinity`, `+0x10`, `+0b101` and `+0o17` each came out quoted on one side
20
+ * and bare on the other: two byte-different files for one model, and a git
21
+ * conflict out of nothing.
22
+ *
23
+ * A purely syntactic rule, identical in both languages, has neither problem.
24
+ * The special floats matter too — `.inf` and `.nan` were quoted by neither
25
+ * writer and came back as numbers.
26
+ */
27
+ const NUMBERISH = /^[+-]?((\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?|0[xX][0-9a-fA-F]+|0[oO][0-7]+|0[bB][01]+|Infinity|\.(inf|Inf|INF|nan|NaN|NAN))$/;
28
+ function needsQuote(s) {
29
+ if (s === "")
30
+ return true;
31
+ if (/^\s|\s$/.test(s))
32
+ return true;
33
+ if (/[\u0000-\u001F\u007F]/.test(s))
34
+ return true;
35
+ if (INDICATOR_START.test(s))
36
+ return true;
37
+ if (s.includes(": ") || s.endsWith(":"))
38
+ return true;
39
+ if (s.includes(" #"))
40
+ return true;
41
+ if (RESERVED.test(s))
42
+ return true;
43
+ if (NUMBERISH.test(s))
44
+ return true;
45
+ if (NUMBER_TOKEN_START.test(s))
46
+ return true;
47
+ return false;
48
+ }
49
+ function scalar(value) {
50
+ if (typeof value === "number" || typeof value === "boolean")
51
+ return String(value);
52
+ return needsQuote(value) ? JSON.stringify(value) : value;
53
+ }
54
+ /** Flow context adds its own delimiters to the set that must be quoted. */
55
+ function needsQuoteInFlow(s) {
56
+ return needsQuote(s) || /[,[\]{}]/.test(s);
57
+ }
58
+ function flowList(items) {
59
+ // `scalar` alone was wrong here: it only knows block context, so a tag
60
+ // written as `a, b` was emitted bare inside `[…]` and read back as two
61
+ // tags, and one containing `]` or `}` produced YAML that would not parse.
62
+ return `[${items
63
+ .map((item) => (needsQuoteInFlow(item) ? JSON.stringify(item) : item))
64
+ .join(", ")}]`;
65
+ }
66
+ class Out {
67
+ lines = [];
68
+ line(indent, text) {
69
+ this.lines.push(text === "" ? "" : " ".repeat(indent) + text);
70
+ }
71
+ /** `key: value` with canonical scalar style. */
72
+ kv(indent, key, value) {
73
+ this.line(indent, `${key}: ${scalar(value)}`);
74
+ }
75
+ /**
76
+ * `key: |2` literal block scalar; used for code-like fields regardless of
77
+ * line count.
78
+ *
79
+ * The explicit indentation indicator is load-bearing. Without it YAML infers
80
+ * the block's indentation from its first non-empty line, so a body whose
81
+ * first line is indented — anything pasted out of a nested snippet — had
82
+ * that indentation swallowed into the block header on read-back, and a body
83
+ * whose first line was *more* indented than the rest produced a file the
84
+ * parser rejected outright ("Expected a key while parsing a block mapping").
85
+ * Both implementations did this, so no conformance fixture could catch it.
86
+ *
87
+ * Two shapes cannot be written as a literal block at all and fall back to a
88
+ * quoted scalar: text containing a carriage return, because YAML normalizes
89
+ * line breaks and `\r\n` would silently become `\n`; and text that is empty
90
+ * or nothing but newlines, which reads back as the empty string.
91
+ */
92
+ block(indent, key, text) {
93
+ if (text.includes("\r") || text.replace(/\n+$/, "") === "") {
94
+ this.line(indent, `${key}: ${JSON.stringify(text)}`);
95
+ return;
96
+ }
97
+ const trailing = text.length - text.replace(/\n+$/, "").length;
98
+ const content = trailing === 1 ? text.slice(0, -1) : text.replace(/\n+$/, (m) => m.slice(0, -1));
99
+ // The indicator only where it changes the reading, so files that were
100
+ // already correct keep their bytes and do not all churn on the next save.
101
+ // YAML infers the block's indentation from the first non-empty line, so
102
+ // that is the only line whose leading space is at risk.
103
+ const first = content.split("\n").find((row) => row !== "") ?? "";
104
+ const indicator = first.startsWith(" ") ? "2" : "";
105
+ const suffix = trailing === 1 ? "" : trailing === 0 ? "-" : "+";
106
+ this.line(indent, `${key}: |${indicator}${suffix}`);
107
+ for (const row of content.split("\n")) {
108
+ this.line(row === "" ? 0 : indent + 2, row);
109
+ }
110
+ }
111
+ /** Block list of scalars. */
112
+ list(indent, key, items) {
113
+ this.line(indent, `${key}:`);
114
+ for (const item of items) {
115
+ this.line(indent + 2, `- ${scalar(item)}`);
116
+ }
117
+ }
118
+ toString() {
119
+ return this.lines.join("\n") + "\n";
120
+ }
121
+ }
122
+ // MARK: - Shared shapes
123
+ function emitKvRows(out, indent, key, rows) {
124
+ if (rows.length === 0)
125
+ return;
126
+ out.line(indent, `${key}:`);
127
+ for (const row of rows) {
128
+ out.line(indent + 2, `- name: ${scalar(row.name)}`);
129
+ out.kv(indent + 4, "value", row.value);
130
+ if (!row.enabled)
131
+ out.kv(indent + 4, "enabled", false);
132
+ }
133
+ }
134
+ function emitVariables(out, indent, key, rows) {
135
+ if (rows.length === 0)
136
+ return;
137
+ out.line(indent, `${key}:`);
138
+ for (const row of rows) {
139
+ out.line(indent + 2, `- name: ${scalar(row.name)}`);
140
+ out.kv(indent + 4, "value", row.value);
141
+ }
142
+ }
143
+ function emitAuth(out, indent, auth) {
144
+ if (auth.type === "inherit")
145
+ return;
146
+ out.line(indent, "auth:");
147
+ out.kv(indent + 2, "type", auth.type);
148
+ switch (auth.type) {
149
+ case "none":
150
+ break;
151
+ case "basic":
152
+ out.line(indent + 2, "basic:");
153
+ out.kv(indent + 4, "username", auth.basic.username);
154
+ out.kv(indent + 4, "password", auth.basic.password);
155
+ break;
156
+ case "bearer":
157
+ out.line(indent + 2, "bearer:");
158
+ out.kv(indent + 4, "token", auth.bearer.token);
159
+ break;
160
+ case "apiKey":
161
+ out.line(indent + 2, "apiKey:");
162
+ out.kv(indent + 4, "name", auth.apiKey.name);
163
+ out.kv(indent + 4, "value", auth.apiKey.value);
164
+ out.kv(indent + 4, "in", auth.apiKey.in);
165
+ break;
166
+ case "oauth2": {
167
+ const cfg = auth.oauth2;
168
+ out.line(indent + 2, "oauth2:");
169
+ out.kv(indent + 4, "grant", cfg.grant);
170
+ if (cfg.authUrl !== undefined)
171
+ out.kv(indent + 4, "authUrl", cfg.authUrl);
172
+ out.kv(indent + 4, "tokenUrl", cfg.tokenUrl);
173
+ out.kv(indent + 4, "clientId", cfg.clientId);
174
+ if (cfg.clientSecret !== undefined)
175
+ out.kv(indent + 4, "clientSecret", cfg.clientSecret);
176
+ if (cfg.scopes.length > 0)
177
+ out.line(indent + 4, `scopes: ${flowList(cfg.scopes)}`);
178
+ const pkceDefault = cfg.grant === "authorizationCode";
179
+ if (cfg.usePkce !== pkceDefault)
180
+ out.kv(indent + 4, "usePkce", cfg.usePkce);
181
+ break;
182
+ }
183
+ }
184
+ }
185
+ function emitBody(out, indent, body) {
186
+ if (body.type === "none")
187
+ return;
188
+ out.line(indent, "body:");
189
+ out.kv(indent + 2, "type", body.type);
190
+ switch (body.type) {
191
+ case "json":
192
+ out.block(indent + 2, "json", body.json);
193
+ break;
194
+ case "text":
195
+ out.block(indent + 2, "text", body.text);
196
+ break;
197
+ case "form":
198
+ emitKvRows(out, indent + 2, "form", body.form);
199
+ break;
200
+ case "multipart":
201
+ out.line(indent + 2, "multipart:");
202
+ for (const part of body.multipart) {
203
+ out.line(indent + 4, `- name: ${scalar(part.name)}`);
204
+ if (part.value !== undefined)
205
+ out.kv(indent + 6, "value", part.value);
206
+ if (part.filePath !== undefined)
207
+ out.kv(indent + 6, "filePath", part.filePath);
208
+ if (!part.enabled)
209
+ out.kv(indent + 6, "enabled", false);
210
+ }
211
+ break;
212
+ case "binary":
213
+ out.line(indent + 2, "binary:");
214
+ out.kv(indent + 4, "path", body.binary.path);
215
+ break;
216
+ case "graphql":
217
+ out.line(indent + 2, "graphql:");
218
+ out.block(indent + 4, "query", body.graphql.query);
219
+ if (body.graphql.variables !== undefined) {
220
+ out.block(indent + 4, "variables", body.graphql.variables);
221
+ }
222
+ break;
223
+ }
224
+ }
225
+ // MARK: - File serializers
226
+ /** Serialize a normalized request to canonical `*.req.yaml` bytes. */
227
+ export function serializeRequestFile(req) {
228
+ const out = new Out();
229
+ out.kv(0, "format", req.format);
230
+ out.kv(0, "id", req.id);
231
+ out.kv(0, "name", req.name);
232
+ out.kv(0, "method", req.method);
233
+ out.kv(0, "url", req.url);
234
+ emitKvRows(out, 0, "query", req.query);
235
+ emitKvRows(out, 0, "headers", req.headers);
236
+ emitAuth(out, 0, req.auth);
237
+ emitBody(out, 0, req.body);
238
+ if (req.scripts.preRequest !== undefined || req.scripts.tests !== undefined) {
239
+ out.line(0, "scripts:");
240
+ if (req.scripts.preRequest !== undefined)
241
+ out.kv(2, "preRequest", req.scripts.preRequest);
242
+ if (req.scripts.tests !== undefined)
243
+ out.kv(2, "tests", req.scripts.tests);
244
+ }
245
+ if (req.presets.length > 0) {
246
+ out.line(0, "presets:");
247
+ for (const preset of req.presets) {
248
+ out.line(2, `- name: ${scalar(preset.name)}`);
249
+ out.block(4, "payload", preset.payload);
250
+ }
251
+ }
252
+ if (req.meta.description !== undefined || req.meta.tags.length > 0) {
253
+ out.line(0, "meta:");
254
+ if (req.meta.description !== undefined)
255
+ out.kv(2, "description", req.meta.description);
256
+ if (req.meta.tags.length > 0)
257
+ out.line(2, `tags: ${flowList(req.meta.tags)}`);
258
+ }
259
+ return out.toString();
260
+ }
261
+ /** Serialize a normalized collection/folder to canonical bytes. */
262
+ export function serializeCollectionFile(col) {
263
+ const out = new Out();
264
+ out.kv(0, "format", col.format);
265
+ out.kv(0, "id", col.id);
266
+ out.kv(0, "name", col.name);
267
+ emitAuth(out, 0, col.auth);
268
+ emitVariables(out, 0, "variables", col.variables);
269
+ if (col.order.length > 0)
270
+ out.list(0, "order", col.order);
271
+ return out.toString();
272
+ }
273
+ /** Serialize a normalized environment to canonical bytes. */
274
+ export function serializeEnvironmentFile(env) {
275
+ const out = new Out();
276
+ out.kv(0, "format", env.format);
277
+ out.kv(0, "name", env.name);
278
+ emitVariables(out, 0, "variables", env.variables);
279
+ if (env.secrets.length > 0)
280
+ out.list(0, "secrets", env.secrets);
281
+ return out.toString();
282
+ }
283
+ /** Serialize a normalized workspace manifest to canonical bytes. */
284
+ export function serializeWorkspaceManifest(ws) {
285
+ const out = new Out();
286
+ out.kv(0, "format", ws.format);
287
+ out.kv(0, "name", ws.name);
288
+ if (ws.description !== undefined)
289
+ out.kv(0, "description", ws.description);
290
+ const s = ws.settings;
291
+ const nonDefault = [];
292
+ if (s.followRedirects !== DEFAULT_SETTINGS.followRedirects) {
293
+ nonDefault.push(["followRedirects", s.followRedirects]);
294
+ }
295
+ if (s.timeoutMs !== DEFAULT_SETTINGS.timeoutMs)
296
+ nonDefault.push(["timeoutMs", s.timeoutMs]);
297
+ if (s.validateTls !== DEFAULT_SETTINGS.validateTls)
298
+ nonDefault.push(["validateTls", s.validateTls]);
299
+ if (nonDefault.length > 0) {
300
+ out.line(0, "settings:");
301
+ for (const [key, value] of nonDefault)
302
+ out.kv(2, key, value);
303
+ }
304
+ return out.toString();
305
+ }
306
+ /** Serialize normalized schedules to canonical bytes. */
307
+ export function serializeSchedulesFile(file) {
308
+ const out = new Out();
309
+ out.kv(0, "format", file.format);
310
+ if (file.schedules.length > 0) {
311
+ out.line(0, "schedules:");
312
+ for (const sched of file.schedules) {
313
+ out.line(2, `- id: ${scalar(sched.id)}`);
314
+ out.kv(4, "cron", sched.cron);
315
+ if (sched.timezone !== "UTC")
316
+ out.kv(4, "timezone", sched.timezone);
317
+ if (!sched.enabled)
318
+ out.kv(4, "enabled", false);
319
+ out.line(4, "run:");
320
+ if (sched.run.collection !== undefined)
321
+ out.kv(6, "collection", sched.run.collection);
322
+ if (sched.run.request !== undefined)
323
+ out.kv(6, "request", sched.run.request);
324
+ out.kv(6, "environment", sched.run.environment);
325
+ if (sched.notify?.onFailure !== undefined) {
326
+ out.line(4, "notify:");
327
+ out.line(6, "onFailure:");
328
+ out.kv(8, "webhookUrl", sched.notify.onFailure.webhookUrl);
329
+ }
330
+ }
331
+ }
332
+ return out.toString();
333
+ }
334
+ //# sourceMappingURL=serialize.js.map
@@ -0,0 +1,164 @@
1
+ /** Current workspace file format version. Readers reject newer majors. */
2
+ export declare const FORMAT_VERSION = 1;
3
+ /** A name/value row in query, headers, or form bodies. */
4
+ export interface KeyValueRow {
5
+ name: string;
6
+ value: string;
7
+ /** Disabled rows stay in the file but are not sent. Default: true. */
8
+ enabled: boolean;
9
+ }
10
+ /** A plain name/value pair (collection and environment variables). */
11
+ export interface Variable {
12
+ name: string;
13
+ value: string;
14
+ }
15
+ export interface OAuth2Config {
16
+ grant: "authorizationCode" | "clientCredentials";
17
+ authUrl?: string;
18
+ tokenUrl: string;
19
+ clientId: string;
20
+ clientSecret?: string;
21
+ scopes: string[];
22
+ usePkce: boolean;
23
+ }
24
+ export type AuthConfig = {
25
+ type: "inherit";
26
+ } | {
27
+ type: "none";
28
+ } | {
29
+ type: "basic";
30
+ basic: {
31
+ username: string;
32
+ password: string;
33
+ };
34
+ } | {
35
+ type: "bearer";
36
+ bearer: {
37
+ token: string;
38
+ };
39
+ } | {
40
+ type: "apiKey";
41
+ apiKey: {
42
+ name: string;
43
+ value: string;
44
+ in: "header" | "query";
45
+ };
46
+ } | {
47
+ type: "oauth2";
48
+ oauth2: OAuth2Config;
49
+ };
50
+ export type Body = {
51
+ type: "none";
52
+ } | {
53
+ type: "json";
54
+ json: string;
55
+ } | {
56
+ type: "text";
57
+ text: string;
58
+ } | {
59
+ type: "form";
60
+ form: KeyValueRow[];
61
+ } | {
62
+ type: "multipart";
63
+ multipart: MultipartPart[];
64
+ } | {
65
+ type: "binary";
66
+ binary: {
67
+ path: string;
68
+ };
69
+ } | {
70
+ type: "graphql";
71
+ graphql: {
72
+ query: string;
73
+ variables?: string;
74
+ };
75
+ };
76
+ export interface MultipartPart {
77
+ name: string;
78
+ /** Literal value or a workspace-relative file reference — exactly one is set. */
79
+ value?: string;
80
+ filePath?: string;
81
+ enabled: boolean;
82
+ }
83
+ export declare const METHODS: readonly ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "WS"];
84
+ export type Method = (typeof METHODS)[number];
85
+ export interface Scripts {
86
+ preRequest?: string;
87
+ tests?: string;
88
+ }
89
+ export interface WsPreset {
90
+ name: string;
91
+ payload: string;
92
+ }
93
+ export interface RequestMeta {
94
+ description?: string;
95
+ tags: string[];
96
+ }
97
+ /** One `*.req.yaml` file, normalized: defaults are materialized. */
98
+ export interface RequestFile {
99
+ format: number;
100
+ id: string;
101
+ name: string;
102
+ method: Method;
103
+ url: string;
104
+ query: KeyValueRow[];
105
+ headers: KeyValueRow[];
106
+ auth: AuthConfig;
107
+ body: Body;
108
+ scripts: Scripts;
109
+ presets: WsPreset[];
110
+ meta: RequestMeta;
111
+ }
112
+ /** `collection.yaml` / `folder.yaml`. */
113
+ export interface CollectionFile {
114
+ format: number;
115
+ id: string;
116
+ name: string;
117
+ auth: AuthConfig;
118
+ variables: Variable[];
119
+ order: string[];
120
+ }
121
+ /** `*.env.yaml`. */
122
+ export interface EnvironmentFile {
123
+ format: number;
124
+ name: string;
125
+ variables: Variable[];
126
+ /** Secret names only — values never live in the workspace. */
127
+ secrets: string[];
128
+ }
129
+ export interface WorkspaceSettings {
130
+ followRedirects: boolean;
131
+ timeoutMs: number;
132
+ validateTls: boolean;
133
+ }
134
+ export declare const DEFAULT_SETTINGS: WorkspaceSettings;
135
+ /** `baton.yaml` — the workspace manifest. */
136
+ export interface WorkspaceManifest {
137
+ format: number;
138
+ name: string;
139
+ description?: string;
140
+ settings: WorkspaceSettings;
141
+ }
142
+ export interface ScheduleNotify {
143
+ onFailure?: {
144
+ webhookUrl: string;
145
+ };
146
+ }
147
+ export interface Schedule {
148
+ id: string;
149
+ cron: string;
150
+ /** IANA zone name. Default: UTC. */
151
+ timezone: string;
152
+ enabled: boolean;
153
+ run: {
154
+ collection?: string;
155
+ request?: string;
156
+ environment: string;
157
+ };
158
+ notify?: ScheduleNotify;
159
+ }
160
+ /** `schedules.yaml`. */
161
+ export interface SchedulesFile {
162
+ format: number;
163
+ schedules: Schedule[];
164
+ }
@@ -0,0 +1,9 @@
1
+ /** Current workspace file format version. Readers reject newer majors. */
2
+ export const FORMAT_VERSION = 1;
3
+ export const METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "WS"];
4
+ export const DEFAULT_SETTINGS = {
5
+ followRedirects: true,
6
+ timeoutMs: 30000,
7
+ validateTls: true,
8
+ };
9
+ //# sourceMappingURL=types.js.map
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@dudko.dev/baton-format",
3
+ "version": "0.1.0",
4
+ "description": "Baton workspace file format: parsing, validation, and deterministic serialization.",
5
+ "keywords": ["baton", "api-client", "yaml", "workspace", "format"],
6
+ "homepage": "https://baton.dudko.dev",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/dudko-dev/baton.git",
10
+ "directory": "js/format"
11
+ },
12
+ "bugs": "https://baton.dudko.dev",
13
+ "author": "Siarhei Dudko <siarhei@dudko.dev>",
14
+ "license": "SEE LICENSE IN LICENSE",
15
+ "type": "module",
16
+ "main": "dist/src/index.js",
17
+ "types": "dist/src/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/src/index.d.ts",
21
+ "default": "./dist/src/index.js"
22
+ }
23
+ },
24
+ "engines": {
25
+ "node": ">=24"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public",
29
+ "registry": "https://registry.npmjs.org/"
30
+ },
31
+ "files": ["dist/src/**/*.js", "dist/src/**/*.d.ts"],
32
+ "scripts": {
33
+ "build": "tsc",
34
+ "test": "tsc && node --test \"dist/test/*.test.js\"",
35
+ "prepublishOnly": "tsc"
36
+ },
37
+ "dependencies": {
38
+ "yaml": "^2.5.0"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^24.0.0",
42
+ "typescript": "^5.5.0"
43
+ }
44
+ }