@gram-lang/format 1.5.0 → 1.5.1

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 (2) hide show
  1. package/dist/index.js +303 -86
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // src/index.ts
2
+ import { getAST } from "@gram-lang/parser";
2
3
  function hasChanges(changes) {
3
4
  return changes.lowercasedIds > 0 || changes.spacesBeforeBrace > 0 || changes.spacesInsideBraces > 0 || changes.trailingZeros > 0 || changes.quantityOperatorSpacing > 0 || changes.temperatureSpacing > 0 || changes.compositeSeparatorSpacing > 0 || changes.arrowDeclarationSpacing > 0 || changes.headerSpacing > 0 || changes.tabsToSpaces > 0 || changes.consecutiveBlankLines > 0 || changes.trailingWhitespace > 0 || changes.eofNewline;
4
5
  }
@@ -40,27 +41,33 @@ function summarizeChanges(changes) {
40
41
  if (changes.eofNewline) parts.push("EOF newline added");
41
42
  return parts.join(" \xB7 ");
42
43
  }
44
+ var TRAILING_BLANKS = /[ \t]+$/;
45
+ var LEADING_BLANKS = /^[ \t]+/;
46
+ function trimBlanks(text) {
47
+ return text.replace(LEADING_BLANKS, "").replace(TRAILING_BLANKS, "");
48
+ }
49
+ var LINE_BREAK = /\r\n|\r|\n/g;
43
50
  function splitFrontmatter(source) {
44
- const firstLineEnd = source.indexOf("\n");
45
- const firstLine = firstLineEnd === -1 ? source : source.slice(0, firstLineEnd);
46
- if (firstLineEnd === -1 || firstLine.trimEnd() !== "---") {
47
- return { frontmatter: "", body: source };
48
- }
49
- let cursor = firstLineEnd + 1;
50
- while (cursor <= source.length) {
51
- const nextLineEnd = source.indexOf("\n", cursor);
52
- const line = nextLineEnd === -1 ? source.slice(cursor) : source.slice(cursor, nextLineEnd);
53
- if (line.trimEnd() === "---") {
54
- const boundary = nextLineEnd === -1 ? source.length : nextLineEnd + 1;
55
- return {
56
- frontmatter: source.slice(0, boundary),
57
- body: source.slice(boundary)
58
- };
51
+ const none = { frontmatter: "", body: source };
52
+ const lineBreak = new RegExp(LINE_BREAK);
53
+ let start = 0;
54
+ let first = true;
55
+ for (; ; ) {
56
+ const match = lineBreak.exec(source);
57
+ const end = match ? match.index : source.length;
58
+ const next = match ? end + match[0].length : source.length;
59
+ let line = source.slice(start, end).replace(TRAILING_BLANKS, "");
60
+ if (first) line = line.replace(/^\uFEFF/, "");
61
+ const isFence = line === "---";
62
+ if (first) {
63
+ if (!match || !isFence) return none;
64
+ first = false;
65
+ } else if (isFence) {
66
+ return { frontmatter: source.slice(0, next), body: source.slice(next) };
59
67
  }
60
- if (nextLineEnd === -1) break;
61
- cursor = nextLineEnd + 1;
68
+ if (!match) return none;
69
+ start = next;
62
70
  }
63
- return { frontmatter: "", body: source };
64
71
  }
65
72
  var SUM_OPERATOR = / [+-] /;
66
73
  var HAS_TARGET = /.(?:@&|&)/u;
@@ -79,21 +86,226 @@ function trimTrailingZeros(inner) {
79
86
  );
80
87
  return { text: amount + inner.slice(end), count };
81
88
  }
82
- function braceOwner(body, offset) {
83
- if (body[offset - 1] === "=") return "checkpoint";
84
- for (let i = offset - 1; i >= 0; i--) {
85
- const c = body[i];
86
- if (c === "\n" || c === "}" || c === "{") return "other";
87
- if (c === "@" || c === "&") return "ingredient";
88
- if (c === "~") return "timer";
89
- if (c === "^") return "temperature";
90
- if (c === "#") return "cookware";
89
+ var KIND_OF = {
90
+ Ingredient: "ingredient",
91
+ Composite: "ingredient",
92
+ Reference: "ingredient",
93
+ Timer: "timer",
94
+ Temperature: "temperature",
95
+ Cookware: "cookware",
96
+ Checkpoint: "checkpoint"
97
+ };
98
+ var VERBATIM = /* @__PURE__ */ new Set(["Comment", "IntermediateDecl"]);
99
+ function locate(source, text, at, end) {
100
+ if (!text) return null;
101
+ if (source.startsWith(text, at)) return { start: at, end: at + text.length };
102
+ const brace = source.indexOf("{", at);
103
+ if (brace === -1 || brace >= end) return null;
104
+ const start = skipBlanks(source, brace + 1);
105
+ return source.startsWith(text, start) ? { start, end: start + text.length } : null;
106
+ }
107
+ function skipBlanks(source, at) {
108
+ let p = at;
109
+ while (source[p] === " " || source[p] === " ") p++;
110
+ return p;
111
+ }
112
+ function locateAfterSlash(source, text, from) {
113
+ if (!text) return null;
114
+ let p = skipBlanks(source, from);
115
+ if (source[p] !== "/") return null;
116
+ p = skipBlanks(source, p + 1);
117
+ return source.startsWith(text, p) ? { start: p, end: p + text.length } : null;
118
+ }
119
+ function quantityNumbers(q, source) {
120
+ if (!q?.loc) return [];
121
+ const { start, end } = q.loc;
122
+ const found = [];
123
+ switch (q.type) {
124
+ case "Quantity":
125
+ found.push(
126
+ locate(source, q.value?.text, start, end)
127
+ );
128
+ break;
129
+ case "CompoundQuantity":
130
+ for (const term of q.terms) {
131
+ if (term.loc)
132
+ found.push(locate(source, term.value?.text, term.loc.start, end));
133
+ }
134
+ break;
135
+ case "RelativeQuantity":
136
+ found.push(locate(source, q.text, start, end));
137
+ break;
138
+ case "RatioQuantity": {
139
+ const numerator = q.numerator;
140
+ const denominator = q.denominator;
141
+ const duration = q.durationRaw;
142
+ const first = locate(
143
+ source,
144
+ duration ?? numerator.value?.text,
145
+ start,
146
+ end
147
+ );
148
+ found.push(first);
149
+ const unitEnd = first ? source.indexOf("/", first.end) : -1;
150
+ if (unitEnd !== -1 && unitEnd < end) {
151
+ found.push(locateAfterSlash(source, denominator.value?.text, unitEnd));
152
+ }
153
+ break;
154
+ }
155
+ }
156
+ return found.filter((r) => r !== null && r.end <= end);
157
+ }
158
+ function elementNumbers(n, source) {
159
+ if (n.type === "Temperature") {
160
+ const value = n.value;
161
+ if (n.text || !value || !n.loc) return [];
162
+ const at = locate(source, value.text, n.loc.start, n.loc.end);
163
+ return at ? [at] : [];
164
+ }
165
+ return quantityNumbers(n.quantity, source);
166
+ }
167
+ function anchorNumbers(retro, source) {
168
+ if (retro.value === null || retro.value === void 0 || !retro.loc)
169
+ return [];
170
+ const raw = retro.raw;
171
+ const unit = retro.unit;
172
+ const number = trimBlanks(
173
+ unit && raw.endsWith(unit) ? raw.slice(0, raw.length - unit.length) : raw
174
+ );
175
+ const at = locate(source, number, retro.loc.start, retro.loc.end);
176
+ return at ? [at] : [];
177
+ }
178
+ function collectSpans(node, source, spans = []) {
179
+ if (Array.isArray(node)) {
180
+ for (const child of node) collectSpans(child, source, spans);
181
+ return spans;
182
+ }
183
+ if (!node || typeof node !== "object") return spans;
184
+ const n = node;
185
+ const verbatim = (start, end) => spans.push({ start, end, numbers: [], compound: false });
186
+ const kind = n.type ? KIND_OF[n.type] : void 0;
187
+ if (kind && n.loc) {
188
+ const composite = n.composite;
189
+ const end = composite?.loc ? composite.loc.start : n.loc.end;
190
+ const quantity = n.quantity;
191
+ spans.push({
192
+ kind,
193
+ start: n.loc.start,
194
+ end,
195
+ numbers: elementNumbers(n, source).filter((r) => r.end <= end),
196
+ compound: quantity?.type === "CompoundQuantity"
197
+ });
198
+ if (composite) collectSpans(composite, source, spans);
199
+ return spans;
200
+ }
201
+ if (n.type && VERBATIM.has(n.type) && n.loc) {
202
+ verbatim(n.loc.start, n.loc.end);
203
+ return spans;
204
+ }
205
+ if (n.type === "Step" && n.loc && typeof n.action === "string") {
206
+ const open = n.loc.start;
207
+ const at = source[open] === "[" ? source.indexOf(n.action, open + 1) : -1;
208
+ const close = at === -1 ? -1 : source.indexOf("]", at + n.action.length);
209
+ if (close !== -1) verbatim(open, close + 1);
210
+ }
211
+ if (n.type === "Section" && n.loc && typeof n.title === "string" && n.title) {
212
+ const at = source.startsWith("##", n.loc.start) ? source.indexOf(n.title, n.loc.start + 2) : -1;
213
+ if (at !== -1) verbatim(at, at + n.title.length);
214
+ }
215
+ const retro = n.retroPlanning;
216
+ if (n.type === "ImportDecl" && n.loc) {
217
+ const line = source.slice(n.loc.start, n.loc.end);
218
+ const open = line.indexOf('"');
219
+ const quote = line.indexOf('"', open + 1);
220
+ if (open !== -1 && quote !== -1) {
221
+ verbatim(n.loc.start + open, n.loc.start + quote + 1);
222
+ }
223
+ spans.push({
224
+ kind: "bindings",
225
+ start: n.loc.start + quote + 1,
226
+ end: retro?.loc ? retro.loc.start : n.loc.end,
227
+ numbers: [],
228
+ compound: false
229
+ });
230
+ }
231
+ if (retro?.loc) {
232
+ spans.push({
233
+ kind: "timer",
234
+ start: retro.loc.start,
235
+ end: retro.loc.end,
236
+ numbers: anchorNumbers(retro, source),
237
+ compound: false
238
+ });
239
+ }
240
+ for (const [key, value] of Object.entries(n)) {
241
+ if (key !== "retroPlanning" && key !== "loc") {
242
+ collectSpans(value, source, spans);
243
+ }
244
+ }
245
+ return spans;
246
+ }
247
+ function parseSpans(source) {
248
+ try {
249
+ return collectSpans(getAST(source), source).sort(
250
+ (a, b) => a.start - b.start
251
+ );
252
+ } catch {
253
+ return null;
91
254
  }
92
- return "other";
93
255
  }
94
- var isCheckpoint = (body, offset) => braceOwner(body, offset) === "checkpoint";
95
256
  function spaceSumOperators(inner) {
96
- return inner.replace(/(?<=[\p{L}\d%.])\s*\+\s*(?=[\d\p{No}])/gu, " + ").replace(/(?<=[\p{L}%])\s*-\s*(?=[\d\p{No}])/gu, " - ");
257
+ return inner.replace(/(?<=[\p{L}\d%.])[ \t]*\+[ \t]*(?=[\d\p{No}])/gu, " + ").replace(/(?<=[\p{L}%])[ \t]*-[ \t]*(?=[\d\p{No}])/gu, " - ");
258
+ }
259
+ function formatNumbers(span, numbers, changes) {
260
+ let text = span;
261
+ for (const { start, end } of [...numbers].sort((a, b) => b.start - a.start)) {
262
+ const zeros = trimTrailingZeros(text.slice(start, end));
263
+ changes.trailingZeros += zeros.count;
264
+ let after = text.slice(end);
265
+ const gap = /^[ \t]+(?=°)/.exec(after);
266
+ if (gap) {
267
+ changes.temperatureSpacing++;
268
+ after = after.slice(gap[0].length);
269
+ }
270
+ text = text.slice(0, start) + zeros.text + after;
271
+ }
272
+ return text;
273
+ }
274
+ function formatElement(original, kind, numbers, compound, changes) {
275
+ const span = formatNumbers(original, numbers, changes);
276
+ const open = span.search(/[{(]/);
277
+ const hasBraces = open !== -1 && span[open] === "{";
278
+ let head = open === -1 ? span : span.slice(0, open);
279
+ const rest = open === -1 ? "" : span.slice(open);
280
+ if (kind === "ingredient") {
281
+ head = head.replace(/(?<=@)([a-zA-Z][a-zA-Z0-9_-]*)/g, (match) => {
282
+ const lower = match.toLowerCase();
283
+ if (lower !== match) changes.lowercasedIds++;
284
+ return lower;
285
+ });
286
+ if (hasBraces) {
287
+ head = head.replace(/(@[a-zA-Z][a-zA-Z0-9_-]*)[ \t]+$/, (_, id) => {
288
+ changes.spacesBeforeBrace++;
289
+ return id;
290
+ });
291
+ }
292
+ }
293
+ if (!hasBraces) return head + rest;
294
+ const braces = /^\{([^{}\r\n]*)\}/.exec(rest);
295
+ if (!braces) return head + rest;
296
+ return `${head}{${formatBraces(braces[1] ?? "", kind, compound, changes)}}${rest.slice(braces[0].length)}`;
297
+ }
298
+ function formatBraces(original, kind, compound, changes) {
299
+ const inner = trimBlanks(original);
300
+ if (inner !== original) changes.spacesInsideBraces++;
301
+ if (kind === "ingredient" && compound && !HAS_TARGET.test(inner)) {
302
+ const spaced = spaceSumOperators(inner);
303
+ if (SUM_OPERATOR.test(spaced) && spaced !== inner) {
304
+ changes.quantityOperatorSpacing++;
305
+ return spaced;
306
+ }
307
+ }
308
+ return inner;
97
309
  }
98
310
  function formatGram(source) {
99
311
  const changes = {
@@ -113,71 +325,76 @@ function formatGram(source) {
113
325
  };
114
326
  const { frontmatter, body: originalBody } = splitFrontmatter(source);
115
327
  let body = originalBody;
116
- body = body.replace(/(?<=@)([a-zA-Z][a-zA-Z0-9_-]*)/g, (match) => {
117
- const lower = match.toLowerCase();
118
- if (lower !== match) changes.lowercasedIds++;
119
- return lower;
120
- });
121
- body = body.replace(/@([a-zA-Z][a-zA-Z0-9_-]*)\s+\{/g, (_, id) => {
122
- changes.spacesBeforeBrace++;
123
- return `@${id}{`;
124
- });
125
- body = body.replace(/\{([^}]*)\}/g, (_, inner) => {
126
- const trimmed = inner.trim();
127
- if (trimmed !== inner) changes.spacesInsideBraces++;
128
- return `{${trimmed}}`;
129
- });
130
- body = body.replace(/\{([^}]*)\}/g, (match, inner, offset) => {
131
- if (isCheckpoint(body, offset)) return match;
132
- const fixed = inner.replace(/(\d+)\s+°/g, (_m, n) => {
133
- changes.temperatureSpacing++;
134
- return `${n}\xB0`;
135
- });
136
- return `{${fixed}}`;
137
- });
138
- body = body.replace(/\{([^{}\n]*)\}/g, (match, inner, offset) => {
139
- if (isCheckpoint(body, offset)) return match;
140
- const { text, count } = trimTrailingZeros(inner);
141
- if (count === 0) return match;
142
- changes.trailingZeros += count;
143
- return `{${text}}`;
144
- });
145
- body = body.replace(/\{([^{}\n]*)\}/g, (match, inner, offset) => {
146
- if (braceOwner(body, offset) !== "ingredient") return match;
147
- if (HAS_TARGET.test(inner)) return match;
148
- const spaced = spaceSumOperators(inner);
149
- if (!SUM_OPERATOR.test(spaced) || spaced === inner) return match;
150
- changes.quantityOperatorSpacing++;
151
- return `{${spaced}}`;
152
- });
153
- body = body.replace(/ *< *@/g, (match) => {
328
+ body = body.replace(/[ \t]*<[ \t]*@/g, (match) => {
154
329
  if (match !== "<@") changes.compositeSeparatorSpacing++;
155
330
  return "<@";
156
331
  });
157
- body = body.replace(/->&([^{\n]+?)\s+\{\}/g, (_, name) => {
332
+ body = body.replace(/->&([^{\r\n]+?)[ \t]+\{\}/g, (_, name) => {
158
333
  changes.arrowDeclarationSpacing++;
159
334
  return `->&${name}{}`;
160
335
  });
161
336
  body = body.replace(/^(##(?!#))[ \t]*(?=\S)/gm, (match, hashes) => {
162
- const normalized = `${hashes} `;
163
- if (match !== normalized) changes.headerSpacing++;
164
- return normalized;
165
- });
166
- body = body.replace(/\t/g, () => {
167
- changes.tabsToSpaces++;
168
- return " ";
337
+ const normalized2 = `${hashes} `;
338
+ if (match !== normalized2) changes.headerSpacing++;
339
+ return normalized2;
169
340
  });
170
- let content = frontmatter + body;
171
- content = content.split("\n").map((line) => {
172
- const trimmed = line.trimEnd();
173
- if (trimmed !== line) changes.trailingWhitespace++;
174
- return trimmed;
175
- }).join("\n");
176
- content = content.replace(/\n{3,}/g, () => {
177
- changes.consecutiveBlankLines++;
178
- return "\n\n";
341
+ const repaired = frontmatter + body;
342
+ const segments = [
343
+ { text: frontmatter, verbatim: false }
344
+ ];
345
+ let cursor = frontmatter.length;
346
+ for (const span of parseSpans(repaired) ?? []) {
347
+ if (span.start < cursor) continue;
348
+ segments.push({
349
+ text: repaired.slice(cursor, span.start),
350
+ verbatim: false
351
+ });
352
+ const text = repaired.slice(span.start, span.end);
353
+ segments.push({
354
+ text: span.kind ? formatElement(
355
+ text,
356
+ span.kind,
357
+ span.numbers.map(({ start, end }) => ({
358
+ start: start - span.start,
359
+ end: end - span.start
360
+ })),
361
+ span.compound,
362
+ changes
363
+ ) : text,
364
+ verbatim: true
365
+ });
366
+ cursor = span.end;
367
+ }
368
+ segments.push({ text: repaired.slice(cursor), verbatim: false });
369
+ const last = segments.length - 1;
370
+ const normalized = segments.map(({ text, verbatim }, i) => {
371
+ if (verbatim) {
372
+ return text.replace(/\r\n?/g, () => {
373
+ changes.trailingWhitespace++;
374
+ return "\n";
375
+ });
376
+ }
377
+ let out = text;
378
+ if (i > 0) {
379
+ out = out.replace(/\t/g, () => {
380
+ changes.tabsToSpaces++;
381
+ return " ";
382
+ });
383
+ }
384
+ out = out.replace(
385
+ i === last ? /[ \t]*(?:\r\n|\r|\n)|[ \t]+$/g : /[ \t]*(?:\r\n|\r|\n)/g,
386
+ (match) => {
387
+ if (match !== "\n") changes.trailingWhitespace++;
388
+ return /[\r\n]$/.test(match) ? "\n" : "";
389
+ }
390
+ );
391
+ return out.replace(/\n{3,}/g, () => {
392
+ changes.consecutiveBlankLines++;
393
+ return "\n\n";
394
+ });
179
395
  });
180
- const trimmedEnd = content.trimEnd();
396
+ let content = normalized.join("");
397
+ const trimmedEnd = content.replace(/\n+$/, "");
181
398
  const withEof = `${trimmedEnd}
182
399
  `;
183
400
  if (withEof !== content) changes.eofNewline = true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gram-lang/format",
3
- "version": "1.5.0",
3
+ "version": "1.5.1",
4
4
  "description": "Canonical .gram source formatter, shared by the CLI and language server",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -33,8 +33,8 @@
33
33
  "test": "bun test --only-failures",
34
34
  "prepublishOnly": "npm run build"
35
35
  },
36
- "devDependencies": {
37
- "@gram-lang/parser": "1.5.0"
38
- },
39
- "type": "module"
36
+ "type": "module",
37
+ "dependencies": {
38
+ "@gram-lang/parser": "1.5.1"
39
+ }
40
40
  }