jmd-format 0.1.2 → 0.2.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.
package/LICENSE CHANGED
@@ -1,21 +1,202 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Andreas Ostermeyer <andreas@ostermeyer.de>
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.
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -127,4 +127,6 @@ parser side, following §22.1 of the specification.
127
127
 
128
128
  ## License
129
129
 
130
- MIT — see [LICENSE](./LICENSE).
130
+ Apache 2.0 — see [LICENSE](./LICENSE).
131
+
132
+ The JMD format specification is licensed separately under [CC BY 4.0](https://github.com/ostermeyer/jmd-spec/blob/main/LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jmd-format",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "description": "JMD (JSON Markdown) — structured data format for LLM-driven infrastructure. JavaScript reference implementation.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -11,7 +11,7 @@
11
11
  "name": "Andreas Ostermeyer",
12
12
  "email": "andreas@ostermeyer.de"
13
13
  },
14
- "license": "MIT",
14
+ "license": "Apache-2.0",
15
15
  "homepage": "https://github.com/ostermeyer/jmd-spec",
16
16
  "repository": {
17
17
  "type": "git",
package/src/index.js CHANGED
@@ -1,7 +1,8 @@
1
+ // SPDX-License-Identifier: Apache-2.0
1
2
  // jmd-format — JavaScript reference implementation.
2
3
  //
3
4
  // Public surface: minimal on purpose. Batch API for the common case,
4
5
  // streaming API for large or incremental workloads.
5
6
 
6
- export { parse, createParser, toLines } from './parser.js'
7
- export { serialize, serializeLines } from './serializer.js'
7
+ export { parse, createParser, toLines, JMDParseError } from './parser.js'
8
+ export { serialize, serializeLines, validateLabel } from './serializer.js'
package/src/parser.js CHANGED
@@ -1,3 +1,4 @@
1
+ // SPDX-License-Identifier: Apache-2.0
1
2
  // JMD parser.
2
3
  //
3
4
  // The parser processes a JMD document line by line, maintaining a scope
@@ -8,11 +9,37 @@
8
9
  //
9
10
  // Both share the same line-processing core. Events follow the sequence
10
11
  // defined in JMD spec §18.2. Parser-tolerant per §22.1.
12
+ //
13
+ // Spec coverage: v0.3.3 — including §7.4 repeated-heading promotion with
14
+ // three structured errors (sigil_conflict, repeated_explicit_array,
15
+ // repeated_scalar_key), §3.5.1 frontmatter `---` marker tolerance, and
16
+ // §5.2 multi-line block scalars (`|` literal, `>` folded).
11
17
 
12
18
  import { parseScalar, parseKey, parseField } from './value.js'
13
19
 
14
20
  const HEADING = /^(#+)([!?-])?(?:\s+(.*))?$/
15
21
 
22
+ // §7.4 — kinds tracked per object scope to detect repeated-heading
23
+ // conflicts and to drive implicit-array promotion.
24
+ const K_OBJECT_HEADING = 1 // `## foo` opened an object scope
25
+ const K_ARRAY_SIGIL = 2 // `## foo[]` opened an explicit array
26
+ const K_ARRAY_PROMOTED = 3 // two `## foo` collapsed into an array
27
+ const K_SCALAR_BARE = 4 // `foo: 1` at column 0
28
+ const K_SCALAR_HEADING = 5 // `## foo: 1`
29
+
30
+ // Structured parse error — `kind` lets callers distinguish the §7.4
31
+ // conditions (and any other tagged failures we add later) from generic
32
+ // malformed-input errors. The line number is appended to the message
33
+ // for legibility but also stored separately on the error.
34
+ export class JMDParseError extends Error {
35
+ constructor(kind, message, line) {
36
+ super(message + ' (line ' + line + ')')
37
+ this.name = 'JMDParseError'
38
+ this.kind = kind
39
+ this.line = line
40
+ }
41
+ }
42
+
16
43
  export function createParser() {
17
44
  let lineNo = 0
18
45
 
@@ -21,19 +48,28 @@ export function createParser() {
21
48
  let label = null
22
49
  const frontmatter = {}
23
50
  let inFrontmatter = true
51
+ let frontmatterStarted = false // §3.5.1: have we seen any frontmatter field?
24
52
  let seenRoot = false
25
53
  let root = null
26
54
 
27
55
  // Scope stack. Each entry:
28
- // { kind: 'object' | 'array', container, depth, currentItem? }
29
- // currentItem lives on array scopes only and holds the object built by
30
- // the most recent `- ` line so indented continuations attach to it.
56
+ // { kind: 'object' | 'array', container, depth,
57
+ // seen: Map<key, K_*>, // object scopes only
58
+ // currentItem?, itemSeen? } // array scopes only
59
+ // currentItem lives on array scopes and holds the object built by the
60
+ // most recent `- ` line so indented continuations attach to it.
61
+ // itemSeen mirrors `seen` for that per-item object.
31
62
  let stack = []
32
63
 
33
64
  // Pending blockquote state.
34
65
  // { container, key, lines }
35
66
  let bq = null
36
67
 
68
+ // Pending block-scalar state (§5.2).
69
+ // { container, key, kind: '|' | '>', lines, baseIndent }
70
+ // baseIndent is null until the first content line establishes it.
71
+ let block = null
72
+
37
73
  // A blank line may or may not terminate the current scope — it depends on
38
74
  // what comes after. We defer the decision: flag the blank, then let the
39
75
  // next real line resolve it. A deeper heading re-enters (no reset); a bare
@@ -58,6 +94,11 @@ export function createParser() {
58
94
  lineNo++
59
95
  const line = rawLine.replace(/\r$/, '')
60
96
 
97
+ if (block !== null) {
98
+ if (processBlockLine(line)) return drain()
99
+ // Block ended; fall through to normal line handling.
100
+ }
101
+
61
102
  if (bq !== null) {
62
103
  if (line === '>' || line.startsWith('> ')) {
63
104
  const content = line === '>' ? '' : line.slice(2)
@@ -114,11 +155,15 @@ export function createParser() {
114
155
 
115
156
  function onThematicBreak() {
116
157
  blankPending = false
117
- // A thematic break is consumed by the innermost enclosing array whose
118
- // most-recent item is a dict containing nested structures this is
119
- // the only context where jmd-format emits the break, and the parser
120
- // mirrors that rule (spec §8.6). Inner scopes are closed; if no array
121
- // on the stack qualifies, the line is tolerated as decoration.
158
+ // A thematic break closes any sub-scope opened by the most-recent
159
+ // item, then signals the next item of the enclosing array (spec §8.6).
160
+ // We search outward for the innermost array whose last item opened a
161
+ // sub-structure and close down to it. If none qualifies, the break is
162
+ // a no-op and that is correct, not lossy: a flat item opens no
163
+ // sub-scope, so the enclosing array is still current and the next
164
+ // `- ` item continues it. This is why a `---` after a flat item in a
165
+ // mixed array (canonical per the v0.3.4 §8.6 clarification) parses
166
+ // without dropping the following item.
122
167
  let targetIdx = -1
123
168
  for (let i = stack.length - 1; i >= 0; i--) {
124
169
  const s = stack[i]
@@ -148,23 +193,118 @@ export function createParser() {
148
193
  bq = null
149
194
  }
150
195
 
196
+ // --- Block scalars (§5.2) ------------------------------------------------
197
+
198
+ function startBlock(container, key, kind) {
199
+ block = { container, key, kind, lines: [], baseIndent: null }
200
+ emit('field_start', { key })
201
+ }
202
+
203
+ // Returns true if the line was consumed by the block scalar, false if it
204
+ // signals the block has ended and the line must be re-dispatched normally.
205
+ function processBlockLine(line) {
206
+ if (line === '') {
207
+ block.lines.push('')
208
+ return true
209
+ }
210
+ const m = /^(\s*)/.exec(line)
211
+ const indent = m[0].length
212
+ if (block.baseIndent === null) {
213
+ if (indent === 0) {
214
+ commitBlock()
215
+ return false
216
+ }
217
+ block.baseIndent = indent
218
+ block.lines.push(line.slice(indent))
219
+ return true
220
+ }
221
+ if (indent < block.baseIndent && /\S/.test(line)) {
222
+ commitBlock()
223
+ return false
224
+ }
225
+ block.lines.push(line.slice(block.baseIndent))
226
+ return true
227
+ }
228
+
229
+ function commitBlock() {
230
+ const lines = block.lines.slice()
231
+ // Drop trailing blank lines for both kinds — spec §5.2 treats the
232
+ // trailing newline as a line-terminator, not part of the value.
233
+ while (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()
234
+ const value = block.kind === '|' ? lines.join('\n') : foldLines(lines)
235
+ block.container[block.key] = value
236
+ emit('field', { key: block.key, value })
237
+ block = null
238
+ }
239
+
240
+ // Folded block scalar fold (§5.2):
241
+ // consecutive non-blank lines → joined with single space
242
+ // one blank between groups → one newline
243
+ // N+1 blank lines → N newlines
244
+ function foldLines(lines) {
245
+ let out = ''
246
+ let group = []
247
+ let blanks = 0
248
+ function flushGroup() {
249
+ if (group.length > 0) {
250
+ out += group.join(' ')
251
+ group = []
252
+ }
253
+ }
254
+ for (const ln of lines) {
255
+ if (ln === '') {
256
+ flushGroup()
257
+ blanks++
258
+ } else {
259
+ if (blanks > 0) {
260
+ out += '\n'.repeat(blanks)
261
+ blanks = 0
262
+ }
263
+ group.push(ln)
264
+ }
265
+ }
266
+ flushGroup()
267
+ return out
268
+ }
269
+
151
270
  // --- Root / frontmatter --------------------------------------------------
152
271
 
153
272
  function onFrontmatter(line) {
273
+ // §3.5.1: tolerate `---` (or more) marker lines bracketing the
274
+ // frontmatter block. A marker before any field opens it; a marker
275
+ // after the last field separates it from the root heading. Both
276
+ // forms are consumed without emitting a frontmatter event.
277
+ if (/^-{3,}$/.test(line)) {
278
+ // Marker is structural-only — no state change beyond ignoring it.
279
+ return
280
+ }
154
281
  const f = parseField(line)
155
282
  if (f) {
156
- const v = f.empty ? true : f.value
157
- frontmatter[f.key] = v
158
- emit('frontmatter', { key: f.key, value: v })
283
+ if (f.empty) {
284
+ // D12: multi-line frontmatter value enters a blockquote that
285
+ // collects subsequent `> ...` lines; commit assigns the joined
286
+ // string to frontmatter[key] (handled by the bq state machine).
287
+ frontmatterStarted = true
288
+ startBlockquote(frontmatter, f.key)
289
+ return
290
+ }
291
+ frontmatter[f.key] = f.value
292
+ frontmatterStarted = true
293
+ emit('frontmatter', { key: f.key, value: f.value })
159
294
  return
160
295
  }
161
296
  const pk = parseKey(line)
162
297
  if (pk && pk.rest === '') {
163
298
  frontmatter[pk.key] = true
299
+ frontmatterStarted = true
164
300
  emit('frontmatter', { key: pk.key, value: true })
165
301
  return
166
302
  }
167
- throw parseError('Unexpected line before root heading')
303
+ throw new JMDParseError(
304
+ 'malformed_frontmatter',
305
+ 'Unexpected line before root heading',
306
+ lineNo,
307
+ )
168
308
  }
169
309
 
170
310
  function openRoot(modeMark, text) {
@@ -179,31 +319,50 @@ export function createParser() {
179
319
  if (text === '[]') {
180
320
  label = '[]'
181
321
  root = []
182
- stack = [{ kind: 'array', container: root, depth: 1, currentItem: null }]
322
+ stack = [arrayScope(root, 1)]
183
323
  } else if (text.endsWith('[]')) {
184
324
  label = text.slice(0, -2)
185
325
  root = []
186
- stack = [{ kind: 'array', container: root, depth: 1, currentItem: null }]
326
+ stack = [arrayScope(root, 1)]
187
327
  } else {
188
328
  label = text
189
329
  root = {}
190
- stack = [{ kind: 'object', container: root, depth: 1 }]
330
+ stack = [objectScope(root, 1)]
191
331
  }
192
332
  emit('document_start', { mode, label })
193
333
  }
194
334
 
335
+ function objectScope(container, depth) {
336
+ return { kind: 'object', container, depth, seen: new Map() }
337
+ }
338
+
339
+ function arrayScope(container, depth) {
340
+ return {
341
+ kind: 'array', container, depth,
342
+ currentItem: null, itemSeen: null,
343
+ }
344
+ }
345
+
195
346
  // --- Headings ------------------------------------------------------------
196
347
 
197
348
  function onHeading(depth, modeMark, text) {
198
349
  if (!seenRoot) {
199
350
  if (depth !== 1) {
200
- throw parseError('Document must begin with a depth-1 heading')
351
+ throw new JMDParseError(
352
+ 'malformed_root',
353
+ 'Document must begin with a depth-1 heading',
354
+ lineNo,
355
+ )
201
356
  }
202
357
  openRoot(modeMark, text)
203
358
  return
204
359
  }
205
360
  if (modeMark) {
206
- throw parseError('Mode markers (!, ?, -) are only valid on the root heading')
361
+ throw new JMDParseError(
362
+ 'malformed_heading',
363
+ 'Mode markers (!, ?, -) are only valid on the root heading',
364
+ lineNo,
365
+ )
207
366
  }
208
367
 
209
368
  // Depth-qualified array item (§8.6a) or depth+1 item (§8.6b):
@@ -231,22 +390,37 @@ export function createParser() {
231
390
  if (text.endsWith('[]')) {
232
391
  const keyText = text.slice(0, -2)
233
392
  const pk = parseKey(keyText)
234
- if (!pk || pk.rest !== '') throw parseError('Malformed array heading key')
393
+ if (!pk || pk.rest !== '') {
394
+ throw new JMDParseError(
395
+ 'malformed_heading',
396
+ 'Malformed array heading key',
397
+ lineNo,
398
+ )
399
+ }
235
400
  openArrayScope(depth, pk.key)
236
401
  return
237
402
  }
238
403
 
239
404
  const field = parseField(text)
240
- if (field && !field.empty) {
241
- const parent = parentObjectAt(depth)
242
- parent[field.key] = field.value
405
+ if (field && field.value !== undefined) {
406
+ const { container, seen } = scalarParentAt(depth)
407
+ checkScalar(seen, field.key, K_SCALAR_HEADING)
408
+ container[field.key] = field.value
243
409
  emit('field', { key: field.key, value: field.value })
244
410
  return
245
411
  }
246
412
 
247
413
  if (field && field.empty) {
248
- const parent = parentObjectAt(depth)
249
- startBlockquote(parent, field.key)
414
+ const { container, seen } = scalarParentAt(depth)
415
+ checkScalar(seen, field.key, K_SCALAR_HEADING)
416
+ startBlockquote(container, field.key)
417
+ return
418
+ }
419
+
420
+ if (field && field.block) {
421
+ const { container, seen } = scalarParentAt(depth)
422
+ checkScalar(seen, field.key, K_SCALAR_HEADING)
423
+ startBlock(container, field.key, field.block)
250
424
  return
251
425
  }
252
426
 
@@ -256,22 +430,90 @@ export function createParser() {
256
430
  return
257
431
  }
258
432
 
259
- throw parseError('Malformed heading')
433
+ throw new JMDParseError(
434
+ 'malformed_heading',
435
+ 'Malformed heading',
436
+ lineNo,
437
+ )
260
438
  }
261
439
 
262
440
  function openObjectScope(depth, key) {
263
- const parent = parentObjectAt(depth)
441
+ const parent = parentScopeAt(depth)
442
+ const { container, seen } = parentContainerAndSeen(parent)
443
+ const prior = seen ? seen.get(key) : undefined
444
+
445
+ if (prior === K_ARRAY_SIGIL) {
446
+ throw new JMDParseError(
447
+ 'sigil_conflict',
448
+ 'Repeated heading "' + key + '" mixes [] sigil with bare form',
449
+ lineNo,
450
+ )
451
+ }
452
+ if (prior === K_SCALAR_BARE || prior === K_SCALAR_HEADING) {
453
+ throw new JMDParseError(
454
+ 'repeated_scalar_key',
455
+ 'Key "' + key + '" first seen as scalar, then as object heading',
456
+ lineNo,
457
+ )
458
+ }
459
+ if (prior === K_ARRAY_PROMOTED) {
460
+ // Third+ occurrence: append a fresh object to the existing array.
461
+ const arr = container[key]
462
+ const obj = {}
463
+ arr.push(obj)
464
+ stack.push(objectScope(obj, depth))
465
+ emit('object_start', { key })
466
+ return
467
+ }
468
+ if (prior === K_OBJECT_HEADING) {
469
+ // §7.4: second occurrence promotes the scalar object to an array.
470
+ const existing = container[key]
471
+ const obj = {}
472
+ const arr = [existing, obj]
473
+ container[key] = arr
474
+ if (seen) seen.set(key, K_ARRAY_PROMOTED)
475
+ stack.push(objectScope(obj, depth))
476
+ emit('object_start', { key })
477
+ return
478
+ }
479
+ // First occurrence — plain object heading.
264
480
  const obj = {}
265
- parent[key] = obj
266
- stack.push({ kind: 'object', container: obj, depth })
481
+ container[key] = obj
482
+ if (seen) seen.set(key, K_OBJECT_HEADING)
483
+ stack.push(objectScope(obj, depth))
267
484
  emit('object_start', { key })
268
485
  }
269
486
 
270
487
  function openArrayScope(depth, key) {
271
- const parent = parentObjectAt(depth)
488
+ const parent = parentScopeAt(depth)
489
+ const { container, seen } = parentContainerAndSeen(parent)
490
+ const prior = seen ? seen.get(key) : undefined
491
+
492
+ if (prior === K_ARRAY_SIGIL) {
493
+ throw new JMDParseError(
494
+ 'repeated_explicit_array',
495
+ 'Repeated explicit-array heading "' + key + '"',
496
+ lineNo,
497
+ )
498
+ }
499
+ if (prior === K_OBJECT_HEADING || prior === K_ARRAY_PROMOTED) {
500
+ throw new JMDParseError(
501
+ 'sigil_conflict',
502
+ 'Heading "' + key + '" first appeared without [], then with []',
503
+ lineNo,
504
+ )
505
+ }
506
+ if (prior === K_SCALAR_BARE || prior === K_SCALAR_HEADING) {
507
+ throw new JMDParseError(
508
+ 'repeated_scalar_key',
509
+ 'Key "' + key + '" first seen as scalar, then as array heading',
510
+ lineNo,
511
+ )
512
+ }
272
513
  const arr = []
273
- parent[key] = arr
274
- stack.push({ kind: 'array', container: arr, depth, currentItem: null })
514
+ container[key] = arr
515
+ if (seen) seen.set(key, K_ARRAY_SIGIL)
516
+ stack.push(arrayScope(arr, depth))
275
517
  emit('array_start', { key })
276
518
  }
277
519
 
@@ -280,25 +522,84 @@ export function createParser() {
280
522
  // enclosing array scope.
281
523
  const top = stack[stack.length - 1]
282
524
  if (!top || top.kind !== 'array') {
283
- throw parseError('Anonymous sub-array outside array scope')
525
+ throw new JMDParseError(
526
+ 'malformed_heading',
527
+ 'Anonymous sub-array outside array scope',
528
+ lineNo,
529
+ )
284
530
  }
285
531
  closeItem(top)
286
532
  const inner = []
287
533
  top.container.push(inner)
288
- stack.push({ kind: 'array', container: inner, depth, currentItem: null })
534
+ stack.push(arrayScope(inner, depth))
289
535
  emit('array_start', {})
290
536
  }
291
537
 
292
- function parentObjectAt(depth) {
538
+ // Find the scope that should receive a scalar field at the given heading
539
+ // depth, returning its container plus the `seen` map for §7.4 tracking.
540
+ function scalarParentAt(depth) {
293
541
  for (let i = stack.length - 1; i >= 0; i--) {
294
542
  const s = stack[i]
295
- if (s.depth < depth) {
296
- if (s.kind === 'object') return s.container
297
- if (s.kind === 'array' && s.currentItem) return s.currentItem
298
- throw parseError('Field has no enclosing object scope')
543
+ if (s.depth >= depth) continue
544
+ if (s.kind === 'object') {
545
+ return { container: s.container, seen: s.seen }
299
546
  }
547
+ if (s.kind === 'array' && s.currentItem) {
548
+ // Per-item object: track its own seen-keys so repeated keys on
549
+ // one item still surface as repeated_scalar_key.
550
+ if (s.itemSeen === null) s.itemSeen = new Map()
551
+ return { container: s.currentItem, seen: s.itemSeen }
552
+ }
553
+ throw new JMDParseError(
554
+ 'malformed_field',
555
+ 'Field has no enclosing object scope',
556
+ lineNo,
557
+ )
558
+ }
559
+ throw new JMDParseError(
560
+ 'malformed_field',
561
+ 'No enclosing scope for depth ' + depth,
562
+ lineNo,
563
+ )
564
+ }
565
+
566
+ function parentScopeAt(depth) {
567
+ for (let i = stack.length - 1; i >= 0; i--) {
568
+ if (stack[i].depth < depth) return stack[i]
569
+ }
570
+ throw new JMDParseError(
571
+ 'malformed_heading',
572
+ 'No enclosing scope for depth ' + depth,
573
+ lineNo,
574
+ )
575
+ }
576
+
577
+ function parentContainerAndSeen(scope) {
578
+ if (scope.kind === 'object') {
579
+ return { container: scope.container, seen: scope.seen }
580
+ }
581
+ if (scope.kind === 'array' && scope.currentItem) {
582
+ if (scope.itemSeen === null) scope.itemSeen = new Map()
583
+ return { container: scope.currentItem, seen: scope.itemSeen }
300
584
  }
301
- throw parseError('No enclosing scope for depth ' + depth)
585
+ throw new JMDParseError(
586
+ 'malformed_heading',
587
+ 'Heading inside an array scope needs an active item',
588
+ lineNo,
589
+ )
590
+ }
591
+
592
+ function checkScalar(seen, key, kind) {
593
+ if (!seen) return
594
+ const prior = seen.get(key)
595
+ if (prior !== undefined) {
596
+ throw new JMDParseError(
597
+ 'repeated_scalar_key',
598
+ 'Key "' + key + '" repeated',
599
+ lineNo,
600
+ )
601
+ }
602
+ seen.set(key, kind)
302
603
  }
303
604
 
304
605
  function popToDepth(targetDepth) {
@@ -321,6 +622,7 @@ export function createParser() {
321
622
  if (arrayScope.currentItem !== null) {
322
623
  emit('item_end')
323
624
  arrayScope.currentItem = null
625
+ arrayScope.itemSeen = null
324
626
  }
325
627
  }
326
628
 
@@ -334,8 +636,18 @@ export function createParser() {
334
636
  const bag = parent.kind === 'array' && parent.currentItem
335
637
  ? parent.currentItem
336
638
  : parent.container
639
+ if (Array.isArray(bag)) {
640
+ // Promoted array: search every parent dict in the bag for the
641
+ // container reference (rare path; small N).
642
+ continue
643
+ }
337
644
  for (const k of Object.keys(bag)) {
338
645
  if (bag[k] === scope.container) return k
646
+ // §7.4 promoted: parent[k] may be an array containing scope.container.
647
+ if (Array.isArray(bag[k])
648
+ && bag[k][bag[k].length - 1] === scope.container) {
649
+ return k
650
+ }
339
651
  }
340
652
  }
341
653
  return undefined
@@ -345,15 +657,39 @@ export function createParser() {
345
657
 
346
658
  function onField(line) {
347
659
  const f = parseField(line)
348
- if (!f) throw parseError('Malformed field line')
660
+ if (!f) {
661
+ throw new JMDParseError(
662
+ 'malformed_field',
663
+ 'Malformed field line',
664
+ lineNo,
665
+ )
666
+ }
349
667
  const top = stack[stack.length - 1]
350
- const target = top.kind === 'object'
351
- ? top.container
352
- : (top.currentItem || throwHere('Bare field inside array scope without an item'))
668
+ let target, seen
669
+ if (top.kind === 'object') {
670
+ target = top.container
671
+ seen = top.seen
672
+ } else {
673
+ if (!top.currentItem) {
674
+ throw new JMDParseError(
675
+ 'malformed_field',
676
+ 'Bare field inside array scope without an item',
677
+ lineNo,
678
+ )
679
+ }
680
+ target = top.currentItem
681
+ if (top.itemSeen === null) top.itemSeen = new Map()
682
+ seen = top.itemSeen
683
+ }
684
+ checkScalar(seen, f.key, K_SCALAR_BARE)
353
685
  if (f.empty) {
354
686
  startBlockquote(target, f.key)
355
687
  return
356
688
  }
689
+ if (f.block) {
690
+ startBlock(target, f.key, f.block)
691
+ return
692
+ }
357
693
  target[f.key] = f.value
358
694
  emit('field', { key: f.key, value: f.value })
359
695
  }
@@ -377,7 +713,11 @@ export function createParser() {
377
713
  }
378
714
  const targetIdx = sameDepthIdx !== -1 ? sameDepthIdx : parentDepthIdx
379
715
  if (targetIdx === -1) {
380
- throw parseError('Depth-qualified item has no matching array scope')
716
+ throw new JMDParseError(
717
+ 'malformed_heading',
718
+ 'Depth-qualified item has no matching array scope',
719
+ lineNo,
720
+ )
381
721
  }
382
722
  // Close any scopes nested inside the target array.
383
723
  while (stack.length - 1 > targetIdx) popScope()
@@ -387,7 +727,13 @@ export function createParser() {
387
727
 
388
728
  function onItem(line) {
389
729
  const top = stack[stack.length - 1]
390
- if (top.kind !== 'array') throw parseError('Array item outside array scope')
730
+ if (top.kind !== 'array') {
731
+ throw new JMDParseError(
732
+ 'malformed_item',
733
+ 'Array item outside array scope',
734
+ lineNo,
735
+ )
736
+ }
391
737
 
392
738
  closeItem(top)
393
739
  const rest = line === '-' ? '' : line.slice(2)
@@ -396,6 +742,7 @@ export function createParser() {
396
742
  const item = {}
397
743
  top.container.push(item)
398
744
  top.currentItem = item
745
+ top.itemSeen = new Map()
399
746
  emit('item_start')
400
747
  return
401
748
  }
@@ -405,9 +752,13 @@ export function createParser() {
405
752
  const item = {}
406
753
  top.container.push(item)
407
754
  top.currentItem = item
755
+ top.itemSeen = new Map()
756
+ top.itemSeen.set(f.key, K_SCALAR_BARE)
408
757
  emit('item_start')
409
758
  if (f.empty) {
410
759
  startBlockquote(item, f.key)
760
+ } else if (f.block) {
761
+ startBlock(item, f.key, f.block)
411
762
  } else {
412
763
  item[f.key] = f.value
413
764
  emit('field', { key: f.key, value: f.value })
@@ -418,6 +769,7 @@ export function createParser() {
418
769
  const value = parseScalar(rest)
419
770
  top.container.push(value)
420
771
  top.currentItem = null
772
+ top.itemSeen = null
421
773
  emit('item_value', { value })
422
774
  }
423
775
 
@@ -425,14 +777,30 @@ export function createParser() {
425
777
  const content = line.replace(/^\s+/, '')
426
778
  const top = stack[stack.length - 1]
427
779
  if (top.kind !== 'array' || !top.currentItem) {
428
- throw parseError('Indented continuation without an active array item')
780
+ throw new JMDParseError(
781
+ 'malformed_field',
782
+ 'Indented continuation without an active array item',
783
+ lineNo,
784
+ )
429
785
  }
430
786
  const f = parseField(content)
431
- if (!f) throw parseError('Malformed indented continuation')
787
+ if (!f) {
788
+ throw new JMDParseError(
789
+ 'malformed_field',
790
+ 'Malformed indented continuation',
791
+ lineNo,
792
+ )
793
+ }
794
+ if (top.itemSeen === null) top.itemSeen = new Map()
795
+ checkScalar(top.itemSeen, f.key, K_SCALAR_BARE)
432
796
  if (f.empty) {
433
797
  startBlockquote(top.currentItem, f.key)
434
798
  return
435
799
  }
800
+ if (f.block) {
801
+ startBlock(top.currentItem, f.key, f.block)
802
+ return
803
+ }
436
804
  top.currentItem[f.key] = f.value
437
805
  emit('field', { key: f.key, value: f.value })
438
806
  }
@@ -440,24 +808,20 @@ export function createParser() {
440
808
  // --- Finalization --------------------------------------------------------
441
809
 
442
810
  function finish() {
811
+ if (block !== null) commitBlock()
443
812
  if (bq !== null) commitBlockquote()
444
813
  if (!seenRoot) {
445
- throw parseError('Document contained no root heading')
814
+ throw new JMDParseError(
815
+ 'malformed_root',
816
+ 'Document contained no root heading',
817
+ lineNo,
818
+ )
446
819
  }
447
820
  while (stack.length > 0) popScope()
448
821
  emit('document_end')
449
822
  return drain()
450
823
  }
451
824
 
452
- // --- Errors --------------------------------------------------------------
453
-
454
- function parseError(msg) {
455
- const err = new Error(msg + ' (line ' + lineNo + ')')
456
- err.line = lineNo
457
- return err
458
- }
459
- function throwHere(msg) { throw parseError(msg) }
460
-
461
825
  // --- Public surface ------------------------------------------------------
462
826
 
463
827
  function parse(text) {
@@ -467,6 +831,8 @@ export function createParser() {
467
831
  if (lines.length && lines[lines.length - 1] === '') lines.pop()
468
832
  for (const line of lines) processLine(line)
469
833
  finish()
834
+ // frontmatterStarted is internal — keep the public shape unchanged.
835
+ void frontmatterStarted
470
836
  return { mode, label, frontmatter, value: root }
471
837
  }
472
838
 
package/src/serializer.js CHANGED
@@ -1,3 +1,4 @@
1
+ // SPDX-License-Identifier: Apache-2.0
1
2
  // JMD serializer.
2
3
  //
3
4
  // Two surfaces over one implementation:
@@ -19,16 +20,39 @@ import { serializeScalar, serializeKey } from './value.js'
19
20
 
20
21
  export function serialize(value, label = 'Document', frontmatter = null) {
21
22
  const lines = []
22
- emitDocument(value, label, frontmatter, lines)
23
+ emitDocument(value, validateLabel(label), frontmatter, lines)
23
24
  return lines.join('\n')
24
25
  }
25
26
 
26
27
  export function* serializeLines(value, label = 'Document', frontmatter = null) {
27
28
  const lines = []
28
- emitDocument(value, label, frontmatter, lines)
29
+ emitDocument(value, validateLabel(label), frontmatter, lines)
29
30
  for (const ln of lines) yield ln + '\n'
30
31
  }
31
32
 
33
+ // D11: validate and normalize a root-heading label. Newline characters
34
+ // would split the heading across lines and corrupt the document, so we
35
+ // reject them outright; surrounding whitespace is silently stripped, but
36
+ // a leading mode prefix (`- `, `? `, `! `) is preserved intact.
37
+ export function validateLabel(label) {
38
+ if (typeof label !== 'string') {
39
+ throw new TypeError('Label must be a string')
40
+ }
41
+ if (label.includes('\n') || label.includes('\r')) {
42
+ throw new RangeError(
43
+ 'JMD root labels must not contain newline characters; got '
44
+ + JSON.stringify(label),
45
+ )
46
+ }
47
+ let s = label.replace(/^\s+/, '')
48
+ if (s.length >= 2
49
+ && (s[0] === '-' || s[0] === '?' || s[0] === '!')
50
+ && s[1] === ' ') {
51
+ return s.slice(0, 2) + s.slice(2).replace(/\s+$/, '')
52
+ }
53
+ return s.replace(/\s+$/, '')
54
+ }
55
+
32
56
  // Mode markers attach directly to `#` in the root heading: `#- Order`,
33
57
  // `#? Order`, `#! Order`. Callers pass the mark as a `- `, `? ` or `! `
34
58
  // prefix on `label`; the serializer attaches it to `#` without a space
@@ -45,8 +69,18 @@ function splitLabel(label) {
45
69
  function emitDocument(value, label, frontmatter, lines) {
46
70
  if (frontmatter && Object.keys(frontmatter).length > 0) {
47
71
  for (const [k, v] of Object.entries(frontmatter)) {
48
- if (v === true) lines.push(serializeKey(k))
49
- else lines.push(serializeKey(k) + ': ' + serializeScalar(v))
72
+ const qk = serializeKey(k)
73
+ if (v === true) {
74
+ lines.push(qk)
75
+ } else if (typeof v === 'string' && v.includes('\n')) {
76
+ // D12: multi-line frontmatter values go in the blockquote form,
77
+ // matching the body serializer's handling of multi-line scalars
78
+ // (§9.1) so the value round-trips through frontmatter parsing.
79
+ lines.push(qk + ':')
80
+ writeMultiline(v, lines)
81
+ } else {
82
+ lines.push(qk + ': ' + serializeScalar(v))
83
+ }
50
84
  }
51
85
  lines.push('')
52
86
  }
@@ -133,24 +167,36 @@ function writeArrayItems(lst, lines, depth) {
133
167
  return
134
168
  }
135
169
 
136
- // Heterogeneous array.
170
+ // Heterogeneous array — items mixing scalars, dicts, sub-arrays.
137
171
  //
138
- // The C-accelerated Python reference does not insert thematic breaks
139
- // inside a heterogeneous array items simply follow one another. We
140
- // match that form byte-for-byte.
172
+ // After any item that opens a sub-scope (a nested list, or a dict
173
+ // with nested fields), the NEXT item needs an explicit depth-qualified
174
+ // heading `## - ...` (§8.6a same-depth form) so the parser pops out
175
+ // of the sub-scope and attaches the item to *this* array. The
176
+ // qualifier uses the array's own scope depth — items[] opened by
177
+ // `## items[]` at depth 2 take a `## - ...` prefix.
178
+ const qualifier = heading(depth)
179
+ let needsQualifier = false
141
180
  for (const item of lst) {
142
181
  if (isPlainObject(item)) {
143
- writeDictItem(item, lines, depth, false)
182
+ const hasNested = Object.values(item).some(isNested)
183
+ writeDictItem(item, lines, depth, false, needsQualifier ? qualifier : '')
184
+ needsQualifier = hasNested
144
185
  } else if (Array.isArray(item)) {
186
+ // Anonymous sub-array still opens at depth+1; only the item-
187
+ // qualifier shrinks to same-depth.
145
188
  lines.push(heading(depth + 1) + '[]')
146
189
  writeArrayItems(item, lines, depth + 1)
190
+ needsQualifier = true
147
191
  } else {
148
- lines.push('- ' + serializeScalar(item))
192
+ const pfx = needsQualifier ? qualifier : ''
193
+ lines.push(pfx + '- ' + serializeScalar(item))
194
+ needsQualifier = false
149
195
  }
150
196
  }
151
197
  }
152
198
 
153
- function writeDictItem(item, lines, depth, separatorNeeded) {
199
+ function writeDictItem(item, lines, depth, separatorNeeded, qualifierPrefix = '') {
154
200
  const scalarFields = []
155
201
  const nestedFields = []
156
202
  for (const [k, v] of Object.entries(item)) {
@@ -167,14 +213,14 @@ function writeDictItem(item, lines, depth, separatorNeeded) {
167
213
  }
168
214
 
169
215
  if (scalarFields.length === 0) {
170
- lines.push('-')
216
+ lines.push(qualifierPrefix + '-')
171
217
  } else {
172
218
  let first = true
173
219
  for (const [k, v] of scalarFields) {
174
220
  const sv = serializeScalar(v)
175
221
  const qk = serializeKey(k)
176
222
  if (first) {
177
- lines.push('- ' + qk + ': ' + sv)
223
+ lines.push(qualifierPrefix + '- ' + qk + ': ' + sv)
178
224
  first = false
179
225
  } else {
180
226
  lines.push(' ' + qk + ': ' + sv)
package/src/value.js CHANGED
@@ -1,3 +1,4 @@
1
+ // SPDX-License-Identifier: Apache-2.0
1
2
  // Scalar values and keys.
2
3
  //
3
4
  // Parsing and serialization of the smallest JMD units: scalar values
@@ -89,8 +90,14 @@ export function serializeKey(key) {
89
90
  return JSON.stringify(key)
90
91
  }
91
92
 
92
- // Parse `key: value` or `key:` (empty value).
93
- // Returns { key, value } or { key, empty: true } or null.
93
+ // Parse `key: value`, `key:` (empty / blockquote-opening), or
94
+ // `key: |` / `key: >` (block-scalar opening, §5.2).
95
+ // Returns one of:
96
+ // { key, value } — scalar field
97
+ // { key, empty: true } — empty value, opens a blockquote field
98
+ // { key, block: '|' } — literal block scalar
99
+ // { key, block: '>' } — folded block scalar
100
+ // or null if the line is not a field.
94
101
  export function parseField(line) {
95
102
  const pk = parseKey(line)
96
103
  if (!pk) return null
@@ -102,5 +109,8 @@ export function parseField(line) {
102
109
  return { key: pk.key, empty: true }
103
110
  }
104
111
  if (after.charCodeAt(0) !== 32 /* space */) return null
105
- return { key: pk.key, value: parseScalar(after.slice(1)) }
112
+ const value = after.slice(1)
113
+ if (value === '|') return { key: pk.key, block: '|' }
114
+ if (value === '>') return { key: pk.key, block: '>' }
115
+ return { key: pk.key, value: parseScalar(value) }
106
116
  }