@pubid/pubid 0.1.69 → 0.1.71

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 (56) hide show
  1. package/README.md +123 -1
  2. package/dist/flavors/bsi/index.d.ts +3 -2
  3. package/dist/flavors/bsi/index.js +43 -42
  4. package/dist/flavors/bsi/worker.d.ts +3 -0
  5. package/dist/flavors/bsi/worker.js +18 -0
  6. package/dist/flavors/cen_cenelec/index.d.ts +3 -2
  7. package/dist/flavors/cen_cenelec/index.js +14 -8
  8. package/dist/flavors/cen_cenelec/worker.d.ts +3 -0
  9. package/dist/flavors/cen_cenelec/worker.js +17 -0
  10. package/dist/flavors/csa/index.d.ts +2 -1
  11. package/dist/flavors/csa/index.js +27 -28
  12. package/dist/flavors/csa/worker.d.ts +3 -0
  13. package/dist/flavors/csa/worker.js +17 -0
  14. package/dist/flavors/evs/index.d.ts +2 -1
  15. package/dist/flavors/evs/index.js +4 -4
  16. package/dist/flavors/evs/worker.d.ts +3 -0
  17. package/dist/flavors/evs/worker.js +18 -0
  18. package/dist/flavors/foreign-resolver.d.ts +6 -0
  19. package/dist/flavors/foreign-resolver.js +9 -0
  20. package/dist/flavors/gost/index.d.ts +2 -1
  21. package/dist/flavors/gost/index.js +19 -20
  22. package/dist/flavors/gost/worker.d.ts +3 -0
  23. package/dist/flavors/gost/worker.js +21 -0
  24. package/dist/flavors/ieee/artifact_tree.js +1 -1
  25. package/dist/flavors/ieee/implementation.d.ts +16 -0
  26. package/dist/flavors/ieee/implementation.js +2195 -0
  27. package/dist/flavors/ieee/index.js +18 -2181
  28. package/dist/flavors/ieee/worker.d.ts +7 -0
  29. package/dist/flavors/ieee/worker.js +31 -0
  30. package/dist/flavors/index.js +6 -6
  31. package/dist/flavors/nist/implementation.d.ts +5 -0
  32. package/dist/flavors/nist/implementation.js +1326 -0
  33. package/dist/flavors/nist/index.js +14 -1330
  34. package/dist/flavors/nist/worker.d.ts +3 -0
  35. package/dist/flavors/nist/worker.js +24 -0
  36. package/dist/flavors/oiml/implementation.d.ts +2 -1
  37. package/dist/flavors/oiml/implementation.js +2 -3
  38. package/dist/flavors/oiml/index.d.ts +2 -0
  39. package/dist/flavors/oiml/index.js +10 -0
  40. package/dist/flavors/oiml/worker.d.ts +2 -0
  41. package/dist/flavors/oiml/worker.js +14 -0
  42. package/dist/flavors/worker-registry.d.ts +13 -0
  43. package/dist/flavors/worker-registry.js +120 -0
  44. package/dist/parg/artifacts/ieee.d.ts +2 -0
  45. package/dist/parg/artifacts/ieee.js +5 -0
  46. package/dist/parg/artifacts/nist.d.ts +2 -0
  47. package/dist/parg/artifacts/nist.js +5 -0
  48. package/dist/parg/runtime.d.ts +1 -13
  49. package/dist/parg/runtime.js +4 -36
  50. package/dist/parg/shape.d.ts +13 -0
  51. package/dist/parg/shape.js +39 -0
  52. package/dist/parg/worker.d.ts +9 -0
  53. package/dist/parg/worker.js +32 -0
  54. package/dist/register-types.d.ts +7 -1
  55. package/dist/register-types.js +7 -1
  56. package/package.json +7 -2
@@ -0,0 +1,2195 @@
1
+ import { ParseFailed, parseGrammar } from "../../grammar/engine.js";
2
+ import { artifactToBuilderTree } from "./artifact_tree.js";
3
+ import { ieeeGrammar } from "./grammar.js";
4
+ import { preParse, preprocessIeee } from "./preprocessor.js";
5
+ import { applyUpdateCodes } from "./update_codes.js";
6
+ import { AdoptedStandardClass, AieeClass, AmendmentClass, ConformanceClass, CorrigendumClass, CsaDualPublishedClass, DualPublishedClass, IecIeeeCopublishedClass, IeeeCode, IeeeDraft, IeeeRelationship, IeeeTypedStage, InterpretationClass, IreClass, JointDevelopmentClass, MultiNumberedClass, NescDraftClass, NescEditionClass, NescHandbookClass, NescPreprintClass, NescRedlineClass, NescStandardClass, DRAFT_MONTH_NAMES, ProjectDraftIdentifierClass, SiStandardClass, StandardClass, locateStage, } from "./model.js";
7
+ /**
8
+ * Port of lib/pubid/ieee/{builder}.rb + Identifier.parse orchestration
9
+ * (pre-parser dispatch, adopted/dual constructors, sub-builders).
10
+ */
11
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
12
+ const extractValue = (value) => {
13
+ if (value === undefined || value === null)
14
+ return undefined;
15
+ if (Array.isArray(value)) {
16
+ if (value.length === 0)
17
+ return undefined;
18
+ const joined = value.join("");
19
+ return joined.length > 0 ? joined : undefined;
20
+ }
21
+ const strValue = String(value).trim();
22
+ return strValue.length > 0 ? strValue : undefined;
23
+ };
24
+ function mergeParsedArray(parsedArray) {
25
+ return Object.assign({}, ...parsedArray);
26
+ }
27
+ const asHash = (v) => (Array.isArray(v) ? mergeParsedArray(v) : v);
28
+ const SI_STAGES = [
29
+ { abbr: ["SI"], stage_code: "published", type_code: "SI" },
30
+ { abbr: ["PSI"], stage_code: "draft", type_code: "SI" },
31
+ ];
32
+ // --- Builder -----------------------------------------------------------------
33
+ class IeeeBuilder {
34
+ env;
35
+ originalInput = "";
36
+ // The injected parse environment (the artifact runtime + the
37
+ // co-publisher routing): the builder's supplement and relationship
38
+ // builders re-parse base identifiers through it.
39
+ constructor(env) {
40
+ this.env = env;
41
+ }
42
+ build(parsed) {
43
+ const d = Array.isArray(parsed) ? mergeParsedArray(parsed) : parsed;
44
+ if (d["ieee_portion"] !== undefined && d["csa_portion"] !== undefined) {
45
+ return this.buildCsaDualPublished(d);
46
+ }
47
+ if (d["s_number"] !== undefined)
48
+ return this.buildSDesignation(d);
49
+ if (d["first_aiee"] !== undefined && d["second_aiee"] !== undefined) {
50
+ return this.buildCombinedAiee(d);
51
+ }
52
+ if (d["content"] !== undefined)
53
+ return this.buildIecIeeCopublished(d);
54
+ if (d["nesc"] !== undefined)
55
+ return this.buildNesc(asHash(d["nesc"]));
56
+ if (d["aiee"] !== undefined)
57
+ return this.buildAiee(asHash(d["aiee"]));
58
+ if (d["ire"] !== undefined)
59
+ return this.buildIre(asHash(d["ire"]));
60
+ if (d["si_type"] !== undefined)
61
+ return this.buildSiPsi(d);
62
+ return this.buildSingleIdentifier(d, false);
63
+ }
64
+ // --- single identifier -----------------------------------------------------
65
+ // Deep-first collection of every :subpart node under a raw
66
+ // part_subpart_year wrapper (hash or array, any nesting).
67
+ collectSubparts(node, out = []) {
68
+ if (isObj(node)) {
69
+ for (const [key, value] of Object.entries(node)) {
70
+ if (key === "subpart")
71
+ out.push(value);
72
+ else
73
+ this.collectSubparts(value, out);
74
+ }
75
+ }
76
+ else if (Array.isArray(node)) {
77
+ for (const item of node)
78
+ this.collectSubparts(item, out);
79
+ }
80
+ return out;
81
+ }
82
+ // The part/subpart/year captures ride the raw part_subpart_year wrapper
83
+ // (parsanol-ruby#399: the repeated-subpart flat spread clobbers to the
84
+ // last value, so the run does not bind top-level). Hoist the wrapper's
85
+ // part/year and deep-collect its interior subparts, so every consumer —
86
+ // and every raw subtree built through here (the CSA dual's
87
+ // ieee_portion, the multi-numbered primary, the supplement bases) —
88
+ // sees the flat keys it has always read (the reference's
89
+ // unwrap_part_subpart_year).
90
+ unwrapPartSubpartYear(node) {
91
+ const run = node["part_subpart_year"];
92
+ if (run === undefined)
93
+ return;
94
+ const nodes = Array.isArray(run) ? run : [run];
95
+ const flat = {};
96
+ for (const item of nodes) {
97
+ if (isObj(item))
98
+ Object.assign(flat, item);
99
+ }
100
+ if (flat["part"] !== undefined)
101
+ node["part"] = flat["part"];
102
+ if (flat["year"] !== undefined)
103
+ node["year"] = flat["year"];
104
+ if (node["subpart"] === undefined) {
105
+ const collected = this.collectSubparts(run);
106
+ if (collected.length > 0)
107
+ node["subpart"] = collected;
108
+ }
109
+ }
110
+ // The edition-2 wasm tree → the native engine's flat shape — the
111
+ // normalization prelude the reference's build_single_identifier runs
112
+ // before every dispatch (builder.rb: the scalar surfacing, the
113
+ // composite rename, the wrapper unwrap, the draft-array repairs and
114
+ // the dash-date hoist).
115
+ normalizeParsedHash(parsedHash) {
116
+ // The wasm bound map captures the optional rev_sep for every printed
117
+ // boundary; the reference's native engine binds it on the bare-REV
118
+ // ("-REV/D1.7" keeps "-") and lettered-revision branches
119
+ // ("-REVmc" keeps "-") and declines it on every numeric revision
120
+ // spelling (".Rev 3", "/rev43", "-rev1", "_Rev2", " Rev 8" — the
121
+ // rev_numbered route, parsanol-ruby#394 family), so the render glues
122
+ // the numeric lettered revisions on those rows.
123
+ if (parsedHash["rev_sep"] !== undefined) {
124
+ const revision = extractValue(parsedHash["revision"]) ?? "";
125
+ if (/^[0-9]+$/.test(revision)) {
126
+ delete parsedHash["rev_sep"];
127
+ }
128
+ }
129
+ // The grammar binds the bare top-level draft clause as
130
+ // draft_version_scalar (string) — surface it under the key the rest
131
+ // of the builder has always read.
132
+ if (parsedHash["draft_version"] === undefined && parsedHash["draft_version_scalar"] !== undefined) {
133
+ parsedHash["draft_version"] = parsedHash["draft_version_scalar"];
134
+ delete parsedHash["draft_version_scalar"];
135
+ }
136
+ // The composite draft rule binds draft_version_composite (raw)
137
+ // inside the draft elements; rename it under the interior key the
138
+ // draft-element walks read.
139
+ const draftElems0 = Array.isArray(parsedHash["draft"])
140
+ ? parsedHash["draft"]
141
+ : [parsedHash["draft"]];
142
+ for (const e of draftElems0) {
143
+ if (isObj(e) && e["draft_version"] === undefined && e["draft_version_composite"] !== undefined) {
144
+ e["draft_version"] = e["draft_version_composite"];
145
+ delete e["draft_version_composite"];
146
+ }
147
+ }
148
+ this.unwrapPartSubpartYear(parsedHash);
149
+ // A revision element INSIDE the draft array is the draft rule's own
150
+ // split artifact (the version's trailing ".1" segment) — the spine
151
+ // captured the same value; drop it.
152
+ if (Array.isArray(parsedHash["draft"]) && parsedHash["revision"] !== undefined) {
153
+ const artifact = parsedHash["draft"].some((e) => isObj(e) && e["revision"] !== undefined &&
154
+ String(extractValue(e["revision"]) ?? "") === String(extractValue(parsedHash["revision"]) ?? ""));
155
+ if (artifact)
156
+ delete parsedHash["revision"];
157
+ }
158
+ // The edition-2 tree materializes a multi-segment draft version
159
+ // ("D2.1.1") as per-token nodes carrying no draft_version key (the
160
+ // v1 tree degraded such a clause to a whole-clause LEAF string when
161
+ // no draft date follows, and to a date-only hash when it does).
162
+ // Normalize to the v1 shape before the stage derivation and draft
163
+ // handling read it.
164
+ if (Array.isArray(parsedHash["draft"])) {
165
+ const elems = parsedHash["draft"].filter(isObj);
166
+ if (elems.length > 0 && elems.every((e) => e["draft_version"] === undefined)) {
167
+ const hasDate = elems.some((e) => e["draft_date_month"] !== undefined || e["draft_date_year"] !== undefined);
168
+ if (hasDate) {
169
+ const dateElems = elems.filter((e) => e["draft_date_month"] !== undefined || e["draft_date_year"] !== undefined || e["draft_date_day"] !== undefined);
170
+ parsedHash["draft"] = Object.assign({}, ...dateElems);
171
+ }
172
+ else {
173
+ parsedHash["draft"] = elems
174
+ .flatMap((e) => Object.values(e))
175
+ .map((v) => String(extractValue(v) ?? ""))
176
+ .join("");
177
+ }
178
+ }
179
+ }
180
+ const drafts = Array.isArray(parsedHash["draft"])
181
+ ? parsedHash["draft"]
182
+ : [parsedHash["draft"]].filter((v) => v !== undefined);
183
+ // The edition-2 grammar renames the nested draft-version dash
184
+ // captures (draft_version_dash_year/month); hoist them to the
185
+ // element level the dash walk reads, and drop the wrapper key.
186
+ for (const d of drafts) {
187
+ if (!isObj(d) || !isObj(d["draft_version"]))
188
+ continue;
189
+ const dv = d["draft_version"];
190
+ if (dv["draft_version_dash_year"] !== undefined || dv["dash_year"] !== undefined) {
191
+ d["dash_year"] = dv["draft_version_dash_year"] ?? dv["dash_year"];
192
+ }
193
+ if (dv["draft_version_dash_month"] !== undefined || dv["dash_month"] !== undefined) {
194
+ d["dash_month"] = dv["draft_version_dash_month"] ?? dv["dash_month"];
195
+ }
196
+ delete d["draft_version"];
197
+ }
198
+ // The dash host: the top-level spine, else a draft element carrying
199
+ // its own dash date (draft_date_dash_year/month on the edition-2
200
+ // grammar, dash_year/month on v1 — read both spellings).
201
+ let dash = parsedHash["dash_year"] !== undefined ? parsedHash : undefined;
202
+ if (dash === undefined) {
203
+ for (const d of drafts) {
204
+ if (isObj(d) && (d["draft_date_dash_year"] !== undefined || d["dash_year"] !== undefined)) {
205
+ dash = d;
206
+ break;
207
+ }
208
+ }
209
+ }
210
+ // A numeric month trailing a draft is the draft's own date: it
211
+ // embeds in the designator ("D09, 04 2011" -> "D09-2011-04") rather
212
+ // than printing the long-format comma face — pubid ruling
213
+ // 2026-10-13.
214
+ if (dash === undefined && parsedHash["draft"] !== undefined) {
215
+ const mVal = extractValue((parsedHash["month"] ?? parsedHash["trailing_month"]));
216
+ const yVal = extractValue((parsedHash["year"] ?? parsedHash["trailing_year"]));
217
+ if (mVal !== undefined && /^\d{1,2}$/.test(mVal) && yVal !== undefined) {
218
+ const host = drafts.find((d) => isObj(d) && d["draft_version"] !== undefined);
219
+ if (host !== undefined && isObj(host)) {
220
+ const hv = host["draft_version"];
221
+ const joined = Array.isArray(hv)
222
+ ? hv.map((v) => extractValue(v) ?? "").join("")
223
+ : String(extractValue(hv) ?? "");
224
+ host["draft_version"] = [joined, yVal, mVal].filter((s) => s !== "").join("-");
225
+ delete parsedHash["month"];
226
+ delete parsedHash["year"];
227
+ delete parsedHash["trailing_month"];
228
+ delete parsedHash["trailing_year"];
229
+ }
230
+ }
231
+ }
232
+ if (dash === undefined)
233
+ return;
234
+ // The draft's own dash date embeds onto the draft even when a base
235
+ // identity year is present ("…-2011/D4-2015-07"); only the root-year
236
+ // assignment waits for an unoccupied year slot.
237
+ const objs = drafts.filter(isObj);
238
+ const joined = objs
239
+ .map((e) => e["draft_version"])
240
+ .filter((v) => v !== undefined)
241
+ .map((v) => (Array.isArray(v) ? v.map((x) => extractValue(x) ?? "").join("") : String(extractValue(v) ?? "")))
242
+ .join("");
243
+ const dashY = extractValue((dash["dash_year"] ?? dash["draft_date_dash_year"]));
244
+ const dashM = extractValue((dash["dash_month"] ?? dash["draft_date_dash_month"]));
245
+ const clearDash = () => {
246
+ delete dash["dash_year"];
247
+ delete dash["dash_month"];
248
+ delete dash["draft_date_dash_year"];
249
+ delete dash["draft_date_dash_month"];
250
+ };
251
+ const embed = () => {
252
+ const host = drafts.find((d) => isObj(d) && d["draft_version"] !== undefined);
253
+ if (host === undefined || !isObj(host))
254
+ return undefined;
255
+ const hv = host["draft_version"];
256
+ const vJoined = Array.isArray(hv)
257
+ ? hv.map((v) => extractValue(v) ?? "").join("")
258
+ : String(extractValue(hv) ?? "");
259
+ host["draft_version"] = [vJoined, dashY, dashM]
260
+ .filter((s) => s !== undefined)
261
+ .join("-");
262
+ return host;
263
+ };
264
+ const bareJointDraft = parsedHash["joint_publishers"] !== undefined &&
265
+ parsedHash["part"] === undefined && parsedHash["iso_stage"] === undefined &&
266
+ objs.some((e) => e["draft_version"] !== undefined);
267
+ const dashLed = joined.startsWith("-");
268
+ if (bareJointDraft && dashLed) {
269
+ parsedHash["part"] = { value: dashY };
270
+ }
271
+ else if (dashM !== undefined && embed() !== undefined) {
272
+ clearDash();
273
+ }
274
+ else if ((dashM !== undefined || dashLed) && parsedHash["year"] === undefined) {
275
+ parsedHash["year"] = dashY;
276
+ parsedHash["month"] = dashM;
277
+ }
278
+ else if (embed() !== undefined) {
279
+ clearDash();
280
+ // the hyphenated "/D-2-2007" spelling's year the spine captured at
281
+ // top level is the draft's own — vacate it
282
+ if (extractValue(parsedHash["year"]) === dashY)
283
+ delete parsedHash["year"];
284
+ }
285
+ else {
286
+ parsedHash["year"] = dashY;
287
+ parsedHash["month"] = dashM;
288
+ }
289
+ }
290
+ buildSingleIdentifier(parsed, buildingSecondary) {
291
+ const parsedHash = asHash(parsed);
292
+ // The edition-2 wasm tree → the native engine's flat shape, before
293
+ // every dispatch reads it (the reference's prelude).
294
+ this.normalizeParsedHash(parsedHash);
295
+ if (!buildingSecondary && parsedHash["primary_identifier"] !== undefined &&
296
+ (parsedHash["secondary_crossref"] !== undefined || parsedHash["secondary_joint"] !== undefined)) {
297
+ return this.buildMultiNumbered(parsedHash);
298
+ }
299
+ if (parsedHash["base"] !== undefined && parsedHash["cor_number"] !== undefined) {
300
+ return this.buildCorrigendumSupplement(parsedHash);
301
+ }
302
+ // A corrigendum capture that is a bare STRING matched the marker
303
+ // without its ordinal - never a valid complete parse (the reference
304
+ // rejects "…Corrigendum/D1").
305
+ if (typeof parsedHash["corrigendum"] === "string") {
306
+ throw new ParseFailed("corrigendum marker without ordinal", 0);
307
+ }
308
+ if (isObj(parsedHash["corrigendum"]) && parsedHash["base"] === undefined) {
309
+ // A corrigendum marker without its ordinal is not a marker - the
310
+ // reference never completes such a parse ("…Corrigendum/D1").
311
+ const cor = asHash(parsedHash["corrigendum"]);
312
+ if (cor["cor_number"] === undefined && cor["cor_year"] === undefined) {
313
+ throw new ParseFailed("corrigendum marker without ordinal", 0);
314
+ }
315
+ return this.buildFlatCorrigendum(parsedHash);
316
+ }
317
+ if (parsedHash["base"] !== undefined && parsedHash["amd_number"] !== undefined) {
318
+ return this.buildAmendmentSupplement(parsedHash);
319
+ }
320
+ if (isObj(parsedHash["amendment"]) && parsedHash["base"] === undefined) {
321
+ return this.buildFlatAmendment(parsedHash);
322
+ }
323
+ if (parsedHash["base"] !== undefined &&
324
+ (parsedHash["int_year"] !== undefined || parsedHash["interpretation"] !== undefined)) {
325
+ return this.buildInterpretationSupplement(parsedHash);
326
+ }
327
+ if (parsedHash["interpretation"] !== undefined && parsedHash["base"] === undefined) {
328
+ return this.buildFlatInterpretation(parsedHash);
329
+ }
330
+ if (parsedHash["base"] !== undefined && parsedHash["conf_number"] !== undefined) {
331
+ return this.buildConformanceSupplement(parsedHash);
332
+ }
333
+ if (parsedHash["joint_publishers"] !== undefined || parsedHash["iso_stage"] !== undefined) {
334
+ return this.buildJointDevelopment(parsedHash);
335
+ }
336
+ // The ORDINAL-LESS D= designator on a multi-publisher row is the
337
+ // joint compound form ("ISO/IEC/IEEE P16326:2017/D=WD.4a"); the
338
+ // ordinal compound ("D8=DIS.3") is a project draft whatever the
339
+ // publishers — the D-ordinal is the draft, the stage the target.
340
+ if (parsedHash["draft_iso_stage"] !== undefined) {
341
+ const draftHash = parsedHash["draft"] !== undefined
342
+ ? asHash(parsedHash["draft"])
343
+ : undefined;
344
+ const hasOrdinal = extractValue(parsedHash["draft_version"]) !== undefined ||
345
+ extractValue(draftHash?.["draft_version"]) !== undefined;
346
+ if (!hasOrdinal) {
347
+ const pubData = parsedHash["publishers"] !== undefined
348
+ ? asHash(parsedHash["publishers"])
349
+ : undefined;
350
+ const copubs = pubData?.["copublishers"] !== undefined
351
+ ? (Array.isArray(pubData["copublishers"]) ? pubData["copublishers"] : [pubData["copublishers"]])
352
+ : [];
353
+ if (copubs.length > 0)
354
+ return this.buildJointDevelopment(parsedHash);
355
+ }
356
+ }
357
+ const attributes = this.extractAttributes(parsedHash);
358
+ if (parsedHash["relationship_type"] !== undefined || parsedHash["relationship_clause"] !== undefined) {
359
+ attributes["relationships"] = this.buildRelationships(parsedHash);
360
+ }
361
+ const klass = this.determineIdentifierClass(attributes);
362
+ // ProjectDraftIdentifier#initialize strips the leading P off the code
363
+ // string (the project marker lives in the stage, not the columns).
364
+ if (klass === ProjectDraftIdentifierClass) {
365
+ // The strip happens on the CODE STRING before Code.parse (Ruby
366
+ // ProjectDraftIdentifier#initialize), so "PIEEP62" -> prefix I.
367
+ const codeStr = attributes["__code"];
368
+ if (codeStr !== undefined && codeStr.startsWith("P")) {
369
+ const codeObj = IeeeCode.parse(codeStr.slice(1));
370
+ delete attributes["prefix"];
371
+ delete attributes["parts"];
372
+ delete attributes["separator"];
373
+ attributes["number"] = codeObj?.number;
374
+ if (codeObj?.prefix !== undefined)
375
+ attributes["prefix"] = codeObj.prefix;
376
+ if (codeObj !== undefined && codeObj.parts.length > 0)
377
+ attributes["parts"] = codeObj.parts;
378
+ if (codeObj?.originalSeparator !== undefined)
379
+ attributes["separator"] = codeObj.originalSeparator;
380
+ if (codeObj !== undefined)
381
+ attributes["__code_obj"] = codeObj;
382
+ // P = project (the document is a draft): the marker is
383
+ // identity-bearing, so stripping the letter must not strip the
384
+ // fact (docs/IEEE-DRAFT-STAGES.md §1.1).
385
+ attributes["project_marker"] = true;
386
+ }
387
+ }
388
+ delete attributes["__code"];
389
+ this.renameSupplementKeys(attributes);
390
+ // The parse path carries the freshly parsed Code (per-part
391
+ // separators — the reference's `code:` string → Components::Code.parse
392
+ // in base #initialize); the column-only rebuild stays the from_hash
393
+ // face.
394
+ const built = new klass(attributes);
395
+ if (attributes["__code_obj"] instanceof IeeeCode) {
396
+ built["__code_obj"] = attributes["__code_obj"];
397
+ }
398
+ return built;
399
+ }
400
+ renameSupplementKeys(attributes) {
401
+ const ordinal = attributes["cor_number"] ?? attributes["amd_number"] ?? attributes["conf_number"];
402
+ delete attributes["cor_number"];
403
+ delete attributes["amd_number"];
404
+ delete attributes["conf_number"];
405
+ if (ordinal !== undefined)
406
+ attributes["number"] = ordinal;
407
+ const year = attributes["cor_year"] ?? attributes["amd_year"] ?? attributes["conf_year"] ?? attributes["int_year"];
408
+ delete attributes["cor_year"];
409
+ delete attributes["amd_year"];
410
+ delete attributes["conf_year"];
411
+ delete attributes["int_year"];
412
+ if (year !== undefined)
413
+ attributes["year"] = year;
414
+ }
415
+ determineIdentifierClass(attributes) {
416
+ if (attributes["publisher"] === "AIEE")
417
+ return AieeClass;
418
+ // A stage-bearing row is a joint development whatever its type
419
+ // code: the stage is the printed identity ("IEEE P15026.2/FDIS",
420
+ // pubid#203) and only the joint model carries iso_stage and the D=
421
+ // designator (the reference's chooser).
422
+ if (attributes["iso_stage"] !== undefined ||
423
+ (attributes["ieee_draft"] ?? "").startsWith("D=")) {
424
+ return JointDevelopmentClass;
425
+ }
426
+ const typeCode = attributes["type"];
427
+ if (typeCode === "P")
428
+ return ProjectDraftIdentifierClass;
429
+ if (typeCode === "SI" || typeCode === "PSI")
430
+ return SiStandardClass;
431
+ if (attributes["interpretation"] === true || attributes["int_year"] !== undefined) {
432
+ return InterpretationClass;
433
+ }
434
+ if (attributes["conf_number"] !== undefined)
435
+ return ConformanceClass;
436
+ if (attributes["cor_number"] !== undefined)
437
+ return CorrigendumClass;
438
+ if (attributes["amd_number"] !== undefined)
439
+ return AmendmentClass;
440
+ if (attributes["adoption"] !== undefined)
441
+ return AdoptedStandardClass;
442
+ return StandardClass;
443
+ }
444
+ // --- extract_attributes ----------------------------------------------------
445
+ extractAttributes(parsed) {
446
+ const attributes = {};
447
+ if (parsed["publishers"] !== undefined) {
448
+ const pubData = asHash(parsed["publishers"]);
449
+ attributes["publisher"] = extractValue(pubData["publisher"]);
450
+ if (pubData["copublishers"] !== undefined) {
451
+ const copubs = Array.isArray(pubData["copublishers"])
452
+ ? pubData["copublishers"]
453
+ : [pubData["copublishers"]];
454
+ // A capture may carry its own separators ("/IEC/ISO" — a joint
455
+ // token glued to the leading slash); the collection renders
456
+ // join("/"), so entries hold bare orgs.
457
+ attributes["copublisher"] = copubs
458
+ .map((cp) => extractValue(asHash(cp)["copublisher"]))
459
+ .filter((cp) => cp !== undefined)
460
+ .flatMap((c) => c.replace(/^\//, "").split("/"))
461
+ .filter((c) => c !== "");
462
+ }
463
+ }
464
+ else if (parsed["publisher"] !== undefined) {
465
+ attributes["publisher"] = extractValue(parsed["publisher"]);
466
+ }
467
+ const codeParts = [];
468
+ if (parsed["part"] !== undefined)
469
+ codeParts.push(extractValue(parsed["part"]) ?? "");
470
+ if (parsed["subpart"] !== undefined) {
471
+ const subparts = Array.isArray(parsed["subpart"]) ? parsed["subpart"] : [parsed["subpart"]];
472
+ for (const sp of subparts) {
473
+ const v = extractValue(sp);
474
+ if (v !== undefined)
475
+ codeParts.push(v);
476
+ }
477
+ }
478
+ let codeStr = extractValue(parsed["number"]);
479
+ let typeValue = extractValue(parsed["type"]);
480
+ const draftStatusValue = extractValue(parsed["draft_status"]);
481
+ if (typeValue === undefined && this.originalInput !== "" && /IEEE\s+P/.test(this.originalInput)) {
482
+ typeValue = "P";
483
+ }
484
+ if (typeValue === undefined && this.originalInput !== "" && /ANSI\s+P/.test(this.originalInput)) {
485
+ typeValue = "P";
486
+ // The P is identity on a non-IEEE-led publisher too (the C1
487
+ // ruling): record the marker so the render prepends it —
488
+ // "ANSI PN42.34/D9a, 2015" round-trips.
489
+ attributes["project_marker"] = true;
490
+ }
491
+ if (codeStr !== undefined && codeStr.startsWith("P") && this.originalInput.includes("/CSA")) {
492
+ const pubData = parsed["publishers"] !== undefined ? asHash(parsed["publishers"]) : undefined;
493
+ const hasCsaCopub = pubData?.["copublishers"] !== undefined
494
+ ? (Array.isArray(pubData["copublishers"]) ? pubData["copublishers"] : [pubData["copublishers"]])
495
+ .some((cp) => (extractValue(asHash(cp)["copublisher"]) ?? "").includes("CSA"))
496
+ : this.originalInput.includes("/CSA");
497
+ if (hasCsaCopub)
498
+ codeStr = codeStr.replace(/^P/, "");
499
+ }
500
+ if (codeStr !== undefined && codeParts.length > 0) {
501
+ // Captures carry their own separator when present (the artifact's
502
+ // part/subpart bind ".18" / "-10"); join verbatim like the
503
+ // reference's extract_attributes — a dashed "62271-37-082" stays
504
+ // dashed.
505
+ codeStr += codeParts.join("");
506
+ }
507
+ if (codeStr !== undefined && parsed["year"] === undefined && codeParts.length === 0) {
508
+ const m = /^(.+)-(\d{4})$/.exec(codeStr);
509
+ if (m !== null) {
510
+ const potentialYear = Number.parseInt(m[2], 10);
511
+ if (potentialYear >= 1884 && potentialYear <= 2099) {
512
+ codeStr = m[1];
513
+ parsed["year"] = m[2];
514
+ }
515
+ }
516
+ }
517
+ const codeObj = codeStr !== undefined ? IeeeCode.parse(codeStr) : undefined;
518
+ if (codeStr !== undefined)
519
+ attributes["__code"] = codeStr;
520
+ if (codeObj !== undefined) {
521
+ attributes["__code_obj"] = codeObj;
522
+ attributes["number"] = codeObj.number;
523
+ if (codeObj.prefix !== undefined)
524
+ attributes["prefix"] = codeObj.prefix;
525
+ if (codeObj.parts.length > 0)
526
+ attributes["parts"] = codeObj.parts;
527
+ if (codeObj.originalSeparator !== undefined)
528
+ attributes["separator"] = codeObj.originalSeparator;
529
+ }
530
+ if (parsed["year"] !== undefined) {
531
+ attributes["year"] = extractValue(parsed["year"]);
532
+ }
533
+ else if (parsed["edition_year"] !== undefined) {
534
+ attributes["year"] = extractValue(parsed["edition_year"]);
535
+ }
536
+ else if (parsed["trailing_year"] !== undefined) {
537
+ attributes["year"] = extractValue(parsed["trailing_year"]);
538
+ if (parsed["trailing_month"] !== undefined) {
539
+ attributes["month"] = extractValue(parsed["trailing_month"]);
540
+ }
541
+ }
542
+ if (parsed["edition_month"] !== undefined) {
543
+ attributes["edition_month"] = extractValue(parsed["edition_month"]);
544
+ }
545
+ // The historical "No"-prefixed spellings ("IEEE No148, April 1959")
546
+ // are plain standards - No normalizes to Std so the render prints
547
+ // "IEEE Std 148" and the stage lookup resolves. AIEE keeps its No.
548
+ if (typeValue !== undefined && /^No\.?$/.test(typeValue) &&
549
+ /^IEEE\s/.test(this.originalInput)) {
550
+ typeValue = "Std";
551
+ }
552
+ // The canonical type word is the short form (C2 ruling):
553
+ // "IEEE Standard 495-2007" and "IEEE Std 495-2007" are the same
554
+ // identifier. A DRAFT type word never reaches the wire (the
555
+ // draft-ness rides draft_status + the draft component; "Draft Std"
556
+ // is banned from canonical output) - it still feeds
557
+ // determineStageAbbr below (the version-less D1 fabrication).
558
+ if (typeValue === "Standard")
559
+ typeValue = "Std";
560
+ if (typeValue !== undefined && !/^Draft/.test(typeValue))
561
+ attributes["type"] = typeValue;
562
+ const typedStageAbbr = this.determineStageAbbr(typeValue, parsed);
563
+ if (typedStageAbbr !== undefined) {
564
+ const record = locateStage(typedStageAbbr);
565
+ if (record !== undefined)
566
+ attributes["typed_stage"] = new IeeeTypedStage(record);
567
+ }
568
+ attributes["draft_status"] = draftStatusValue;
569
+ for (const key of ["edition", "revision", "rev_sep"]) {
570
+ const value = extractValue(parsed[key]);
571
+ if (value !== undefined)
572
+ attributes[key] = value;
573
+ }
574
+ if (parsed["rev_bare"] !== undefined)
575
+ attributes["rev_bare"] = true;
576
+ if (attributes["edition_month"] === undefined) {
577
+ const month = extractValue(parsed["month"]);
578
+ if (month !== undefined)
579
+ attributes["month"] = month;
580
+ }
581
+ const day = extractValue(parsed["day"]);
582
+ if (day !== undefined)
583
+ attributes["day"] = day;
584
+ this.handleDraft(parsed, attributes);
585
+ this.foldDraftDateTail(attributes);
586
+ // The bare-IEEE fdraft clause (pubid#203): a slash-led stage word
587
+ // after the code ("IEEE P15026.2/FDIS, August 2010") rides the D=
588
+ // designator with the IEEE date convention ("D=FDIS-201008"); the
589
+ // ISO face is not elected (the reference's fdraft rule).
590
+ const fdraft = parsed["fdraft"];
591
+ if (fdraft !== undefined && typeof fdraft === "object" && !Array.isArray(fdraft)) {
592
+ const fdStage = extractValue(fdraft["fdraft_stage"]);
593
+ if (fdStage !== undefined) {
594
+ // fdraft's month/year rename with the fdraft_ prefix on the
595
+ // edition-2 grammar (nested-only); the v1 spellings stay as the
596
+ // fallback.
597
+ const fdYear = extractValue((fdraft["fdraft_year"] ?? fdraft["year"]));
598
+ const fdMonth = extractValue((fdraft["fdraft_month"] ?? fdraft["month"]));
599
+ let date = "";
600
+ if (fdYear !== undefined) {
601
+ date = `-${fdYear}`;
602
+ const monthNum = fdMonth !== undefined
603
+ ? DRAFT_MONTH_NAMES[String(fdMonth).replace(/\.$/, "")]
604
+ : undefined;
605
+ if (monthNum !== undefined)
606
+ date += monthNum.padStart(2, "0");
607
+ }
608
+ attributes["publishers"] ??= [attributes["publisher"] ?? "IEEE"];
609
+ attributes["ieee_draft"] = `D=${fdStage}${date}`;
610
+ const fdRecord = locateStage(fdStage);
611
+ if (fdRecord !== undefined)
612
+ attributes["typed_stage"] = new IeeeTypedStage(fdRecord);
613
+ }
614
+ }
615
+ this.applyDefaultDraftVersion(attributes, typeValue);
616
+ this.handleKeyedHash(parsed, "corrigendum", attributes, "cor_number", "cor_year");
617
+ this.handleKeyedHash(parsed, "amendment", attributes, "amd_number", "amd_year");
618
+ this.handleKeyedHash(parsed, "conformance", attributes, "conf_number", "conf_year");
619
+ this.handleAshraeCopub(parsed, attributes);
620
+ this.handleIeeeCrossref(parsed, attributes);
621
+ this.handleReaffirmed(parsed, attributes);
622
+ this.handleParameters(parsed, attributes);
623
+ if (parsed["nickname"] !== undefined) {
624
+ attributes["nickname"] = extractValue(parsed["nickname"]);
625
+ }
626
+ if (parsed["interpretation"] !== undefined)
627
+ attributes["interpretation"] = true;
628
+ if (parsed["redline"] !== undefined)
629
+ attributes["redline"] = true;
630
+ // Glued identity year-month provenance (gem#520): the input tail is
631
+ // the glued "-YYYY-MM" on a draft-free, revision-free identity.
632
+ if (attributes["month"] !== undefined && attributes["year"] !== undefined &&
633
+ attributes["draft"] === undefined && attributes["revision"] === undefined &&
634
+ /-\d{4}-\d{2}$/.test(this.originalInput ?? "")) {
635
+ attributes["month_glued"] = true;
636
+ }
637
+ return attributes;
638
+ }
639
+ determineStageAbbr(typeValue, parsed) {
640
+ // An explicit joint stage on the draft ("=DFDIS.3") IS the stage —
641
+ // it outranks the ordinal ladder, which classifies IEEE-internal
642
+ // drafts only (docs/IEEE-DRAFT-STAGES.md §1.3).
643
+ let draftVersionPresent = false;
644
+ if (parsed["draft"] !== undefined) {
645
+ let draftData = parsed["draft"];
646
+ if (Array.isArray(draftData)) {
647
+ draftData = mergeParsedArray(draftData);
648
+ }
649
+ // A verbatim draft designator string is a version in itself.
650
+ if (!isObj(draftData))
651
+ draftVersionPresent = true;
652
+ if (isObj(draftData) && draftData["draft_iso_stage"] !== undefined) {
653
+ const stage = extractValue(draftData["draft_iso_stage"]) ?? "";
654
+ // The doubled-D alias ("DFDIS") carries its own draft marker;
655
+ // the stage is what remains.
656
+ const rest = stage.slice(1);
657
+ return stage.startsWith("D") && ["PWI", "NP", "WD", "CD", "CDV", "DIS", "FDIS"].includes(rest)
658
+ ? rest
659
+ : stage;
660
+ }
661
+ if (isObj(draftData) && draftData["draft_version"] !== undefined) {
662
+ draftVersionPresent = true;
663
+ const dv = draftData["draft_version"];
664
+ const version = Array.isArray(dv) ? dv.map((v) => extractValue(v) ?? "").join("") : extractValue(dv);
665
+ if (version !== undefined) {
666
+ // A draft version that IS an ISO stage token ("/DCD1" and
667
+ // "/CD1" both capture "CD1") takes that stage on a plain IEEE
668
+ // document (docs/IEEE-DRAFT-STAGES.md §1.3, "DDIS" = DIS); a
669
+ // joint ISO-led stage-word draft keeps its generic project
670
+ // stage.
671
+ const pubs = parsed["publishers"];
672
+ const copubs = isObj(pubs) ? pubs["copublishers"] : undefined;
673
+ const joint = copubs !== undefined && (Array.isArray(copubs) ? copubs.length > 0 : true);
674
+ const stageMatch = /^(FDIS|FCD|CDV|DIS|CD|WD|PWI|NP)\d*$/.exec(version);
675
+ if (!joint && stageMatch !== null)
676
+ return stageMatch[1];
677
+ // relaton's hyphenated "/D-2" spelling captures the dash inside
678
+ // draft_version; the stage registry keys on "D2". A date-embedded
679
+ // version ("3-2017-07") keys on its leading ordinal.
680
+ const draftAbbr = `D${version.replace(/^-/, "").replace(/-\d{4}(-\d{2})?$/, "")}`;
681
+ const stage = locateStage(draftAbbr);
682
+ if (stage !== undefined && stage.abbr.includes(draftAbbr))
683
+ return draftAbbr;
684
+ }
685
+ }
686
+ }
687
+ if (typeValue !== undefined) {
688
+ if (typeValue.startsWith("P"))
689
+ return "P";
690
+ if (typeValue === "Std")
691
+ return "Std";
692
+ if (typeValue === "Draft Std" && !draftVersionPresent && parsed["digit_draft"] === undefined) {
693
+ return "D1";
694
+ }
695
+ if (/^No\.?$/.test(typeValue))
696
+ return typeValue;
697
+ }
698
+ return "Std";
699
+ }
700
+ handleDraft(parsed, attributes) {
701
+ let draftData = parsed["draft"] ?? parsed["digit_draft"];
702
+ if (draftData === undefined)
703
+ return;
704
+ if (Array.isArray(draftData)) {
705
+ const hashes = draftData.filter((e) => isObj(e));
706
+ const versions = hashes
707
+ .map((e) => e["draft_version"])
708
+ .filter((v) => v !== undefined);
709
+ const merged = Object.assign({}, ...hashes);
710
+ if (versions.length > 0)
711
+ merged["draft_version"] = versions;
712
+ draftData = merged;
713
+ }
714
+ let version;
715
+ let revision;
716
+ let isoStage;
717
+ let isoIteration;
718
+ let month;
719
+ let year;
720
+ let day;
721
+ let commaBeforeMonth = false;
722
+ if (isObj(draftData)) {
723
+ if (draftData["draft_version"] !== undefined) {
724
+ const dv = draftData["draft_version"];
725
+ version = Array.isArray(dv) ? dv.map((v) => extractValue(v) ?? "").join("") : extractValue(dv);
726
+ // The reference's designator normalization (gem#552): a leading
727
+ // hyphen drops, and a three-digit-plus zero-padded designator
728
+ // sheds its zero ("/013.0" -> "13.0" — the 2026-10-19 ruling;
729
+ // the strip is scoped to the dotted designator class — "D043"/
730
+ // "D09"/"D0.16" keep their conventional widths).
731
+ if (version !== undefined)
732
+ version = version.replace(/^-/, "").replace(/^0(?=\d+\.\d)/, "");
733
+ }
734
+ // The dotted ordinal stays part of the designator (the #601
735
+ // convergence): a split field would make the parse and from_hash
736
+ // paths build different Draft objects on wire-identical rows.
737
+ // #to_s renders version + revision identically, so the whole tail
738
+ // rides the version on every route.
739
+ if (draftData["revision"] !== undefined && version !== undefined) {
740
+ const tail = extractValue(draftData["revision"])?.replace(/^\./, "");
741
+ if (tail !== undefined && tail !== "")
742
+ version = `${version}.${tail}`;
743
+ }
744
+ isoStage = extractValue(draftData["draft_iso_stage"]);
745
+ isoIteration = extractValue(draftData["draft_iso_iteration"]);
746
+ // FDIS/CDV/… are ISO/IEC stage tokens, not draft ordinals (C1
747
+ // ruling, testsuite#2). "/DDIS" and "/DFCD" are hallucinated
748
+ // concatenations — the designator D does not merge onto a stage
749
+ // word. The draft of a stage rides the iso_stage slot, which
750
+ // Draft#to_s renders as the D= designator face ("…/D=DIS-2020").
751
+ // The glued month-name date ("-June2010", the 2026-10-19 FCD
752
+ // ruling) rides the designator's date slot with the month numeric.
753
+ // The edition-2 grammar renames draft_date's nested month/year/day
754
+ // captures with the draft_date_ prefix (kept off the identity
755
+ // keys); the v1 spellings stay as the fallback.
756
+ const monthSlice = draftData["draft_date_month"] ?? draftData["month"];
757
+ month = extractValue(monthSlice);
758
+ const yearSlice = draftData["draft_date_year"] ?? draftData["year"];
759
+ year = yearSlice !== undefined ? extractValue(yearSlice) : undefined;
760
+ const daySlice = draftData["draft_date_day"] ?? draftData["day"];
761
+ day = daySlice !== undefined ? extractValue(daySlice) : undefined;
762
+ if (version !== undefined) {
763
+ // The stage iteration rides glued onto the word ("DIS2" — the
764
+ // lossless face, pubid#477; the 2026-10-19 DIS2 ruling).
765
+ const stageDate = /^(FDIS|FCD|CDV|DIS|CD|WD|PWI|NP)(\d+)?(?:-([A-Za-z]+)(\d{4}))?$/.exec(version);
766
+ if (stageDate !== null) {
767
+ isoStage = stageDate[1] + (stageDate[2] ?? "");
768
+ if (stageDate[3] !== undefined) {
769
+ month = DRAFT_MONTH_NAMES[stageDate[3]] !== undefined ? stageDate[3] : month;
770
+ year = stageDate[4];
771
+ }
772
+ version = undefined;
773
+ }
774
+ }
775
+ // The apostrophe-year catalogue convention ("P1484.20.1/D7,
776
+ // May 07"): the 2-digit year expands with the <30 pivot so the
777
+ // hash carries an unambiguous year (the reference's builder).
778
+ if (year !== undefined && /^\d{2}$/.test(year)) {
779
+ year = `${Number(year) < 30 ? 20 : 19}${year}`;
780
+ }
781
+ if (this.originalInput !== "" && month !== undefined) {
782
+ commaBeforeMonth = new RegExp(`,\\s+${month.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "i")
783
+ .test(this.originalInput);
784
+ }
785
+ if (version !== undefined && this.originalInput !== "" &&
786
+ new RegExp(`\\s+/D${version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "i").test(this.originalInput)) {
787
+ attributes["space_before_draft"] = true;
788
+ }
789
+ }
790
+ else {
791
+ // A degraded wire leaf carries the whole draft clause verbatim
792
+ // ("/D2.1.1" — the three-segment designator the engine cannot
793
+ // structure): IeeeDraft.parse is the inverse of render, so it
794
+ // strips the prefix instead of double-appending it.
795
+ const reparsed = IeeeDraft.parse(extractValue(draftData) ?? "");
796
+ if (reparsed !== undefined) {
797
+ attributes["draft"] = reparsed.render();
798
+ return;
799
+ }
800
+ }
801
+ // A REV-carrying draft embeds its print date into the designator
802
+ // with the month canonicalized numeric (pubid ruling 2026-10-14):
803
+ // "P802.11-REVmc/D8.0, Aug 2016" renders ".../D8.0-2016-08".
804
+ // Drafts without a REV keep the comma face.
805
+ if ((attributes["revision"] !== undefined || attributes["rev_bare"] === true ||
806
+ attributes["cor_number"] !== undefined || attributes["cor_year"] !== undefined) &&
807
+ month !== undefined && year !== undefined && version !== undefined) {
808
+ const monthNumber = DRAFT_MONTH_NAMES[String(month).replace(/\.$/, "")];
809
+ if (monthNumber !== undefined) {
810
+ // The canonical face zero-pads ("D8.0-2016-08"), matching the
811
+ // reference's REV_MONTH_NUMBERS.
812
+ version = `${version}-${year}-${monthNumber.padStart(2, "0")}`;
813
+ month = year = day = undefined;
814
+ }
815
+ }
816
+ if (version !== undefined || isoStage !== undefined ||
817
+ (isObj(draftData) && draftData["draft_iso_stage"] !== undefined)) {
818
+ const draftObj = new IeeeDraft({
819
+ version,
820
+ revision,
821
+ iso_stage: isoStage,
822
+ iso_iteration: isoIteration,
823
+ month,
824
+ year,
825
+ day,
826
+ comma_before_month: commaBeforeMonth,
827
+ });
828
+ attributes["draft"] = draftObj.render();
829
+ }
830
+ }
831
+ // A draft-date that routed to the identity slots (the grammar's
832
+ // month/year captures beside a bare draft ordinal) folds onto the
833
+ // draft designator: a REV-carrier embeds it numerically
834
+ // ("P1310Rev3/D2, February 2011" renders "D2-2011-02" — the
835
+ // reference's builder), a plain draft keeps the printed face routed
836
+ // through the draft's own parse so the month canonicalizes to the
837
+ // crawl abbreviation ("D08, September 2018" renders "D08, Sept,
838
+ // 2018"; a space-faced input stays space-faced).
839
+ foldDraftDateTail(attributes) {
840
+ const month = attributes["month"];
841
+ const year = attributes["year"];
842
+ const draft = attributes["draft"];
843
+ if (typeof month !== "string" || typeof year !== "string" ||
844
+ typeof draft !== "string" || !/^\/D[^ =,]+$/.test(draft)) {
845
+ return;
846
+ }
847
+ const draftNum = draft.slice(2);
848
+ if (attributes["revision"] !== undefined || attributes["rev_bare"] === true) {
849
+ const monthNum = DRAFT_MONTH_NAMES[String(month).replace(/\.$/, "")];
850
+ if (monthNum === undefined)
851
+ return;
852
+ attributes["draft"] =
853
+ new IeeeDraft({ version: `${draftNum}-${year}-${monthNum.padStart(2, "0")}` }).render();
854
+ }
855
+ else {
856
+ const escaped = month.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
857
+ const commaFace = this.originalInput !== "" &&
858
+ new RegExp(`,\\s+${escaped}`, "i").test(this.originalInput);
859
+ const reparsed = IeeeDraft.parse(`${draftNum}${commaFace ? ", " : " "}${month} ${year}`);
860
+ if (reparsed === undefined)
861
+ return;
862
+ attributes["draft"] = reparsed.render();
863
+ }
864
+ delete attributes["month"];
865
+ delete attributes["year"];
866
+ }
867
+ applyDefaultDraftVersion(attributes, typeValue) {
868
+ if (attributes["draft"] !== undefined)
869
+ return;
870
+ if (typeValue !== "Draft Std")
871
+ return;
872
+ // The reference stores the fabricated designator comma-joined with the
873
+ // identity year ("D1, 2012" — the gem's Draft#to_s), not space-joined.
874
+ attributes["draft"] = attributes["year"] === undefined
875
+ ? "D1"
876
+ : `D1, ${attributes["year"]}`;
877
+ }
878
+ handleKeyedHash(parsed, key, attributes, numberKey, yearKey) {
879
+ if (isObj(parsed[key])) {
880
+ const data = parsed[key];
881
+ attributes[numberKey] = extractValue(data[numberKey]);
882
+ if (data[yearKey] !== undefined)
883
+ attributes[yearKey] = extractValue(data[yearKey]);
884
+ }
885
+ }
886
+ handleAshraeCopub(parsed, attributes) {
887
+ if (isObj(parsed["ashrae_copub"])) {
888
+ const data = parsed["ashrae_copub"];
889
+ attributes["ashrae_number"] = extractValue(data["ashrae_number"]);
890
+ if (data["ashrae_year"] !== undefined) {
891
+ attributes["ashrae_year"] = extractValue(data["ashrae_year"]);
892
+ }
893
+ }
894
+ }
895
+ handleIeeeCrossref(parsed, attributes) {
896
+ if (parsed["ieee_crossref"] !== undefined) {
897
+ const raw = extractValue(parsed["ieee_crossref"]) ?? "";
898
+ attributes["crossref"] = `/C${raw.replace(/^\//, "")}`;
899
+ }
900
+ }
901
+ handleReaffirmed(parsed, attributes) {
902
+ if (isObj(parsed["reaffirmed"])) {
903
+ // The edition-2 grammar renames the nested year capture
904
+ // (reaffirmed_year) so the reaffirmation year cannot leak onto the
905
+ // identity year key; the v1 spelling stays as the fallback.
906
+ const reaf = parsed["reaffirmed"];
907
+ const value = reaf["reaffirmed_year"] ?? reaf["year"];
908
+ if (value !== undefined)
909
+ attributes["reaffirmed"] = extractValue(value);
910
+ }
911
+ else if (parsed["reaffirmed"] !== undefined) {
912
+ attributes["reaffirmed"] = extractValue(parsed["reaffirmed"]);
913
+ }
914
+ }
915
+ handleParameters(parsed, attributes) {
916
+ if (!isObj(parsed["parameters"]))
917
+ return;
918
+ const paramData = parsed["parameters"];
919
+ for (const key of ["parenthetical_content", "revision_of", "amendment_to", "adoption", "note"]) {
920
+ const value = extractValue(paramData[key]);
921
+ if (value !== undefined)
922
+ attributes[key] = value;
923
+ }
924
+ }
925
+ parseIdentifierList(listData) {
926
+ if (listData === undefined || listData === null)
927
+ return [];
928
+ const entries = Array.isArray(listData) ? listData : [listData];
929
+ const idStrings = [];
930
+ for (const entry of entries) {
931
+ if (isObj(entry) && entry["id"] !== undefined) {
932
+ idStrings.push(String(entry["id"]).trim());
933
+ }
934
+ }
935
+ return idStrings.map((idStr) => {
936
+ try {
937
+ return ieeeParseImpl(this.env, idStr);
938
+ }
939
+ catch {
940
+ return new StandardClass({ parenthetical_content: idStr });
941
+ }
942
+ });
943
+ }
944
+ relationshipFrom(relData) {
945
+ if (!isObj(relData["relationship_type"]))
946
+ return undefined;
947
+ const firstKey = Object.keys(relData["relationship_type"])[0];
948
+ if (firstKey === undefined)
949
+ return undefined;
950
+ let amendments = [];
951
+ if (relData["amendments"] !== undefined && !isObj(relData["amendments"])) {
952
+ amendments = this.parseIdentifierList(relData["amendments"]);
953
+ }
954
+ return new IeeeRelationship(firstKey, this.parseIdentifierList(relData["related_ids"]), amendments, isObj(relData["amendments"]) && relData["amendments"]["approved_amendments"] !== undefined);
955
+ }
956
+ buildRelationships(parsedHash) {
957
+ const relationships = [];
958
+ if (parsedHash["relationship_type"] !== undefined || parsedHash["relationship_clause"] !== undefined) {
959
+ const rel = this.relationshipFrom(parsedHash);
960
+ if (rel !== undefined)
961
+ relationships.push(rel);
962
+ }
963
+ if (parsedHash["additional_rels"] !== undefined) {
964
+ const additional = Array.isArray(parsedHash["additional_rels"])
965
+ ? parsedHash["additional_rels"]
966
+ : [parsedHash["additional_rels"]];
967
+ for (const relData of additional) {
968
+ if (isObj(relData)) {
969
+ const rel = this.relationshipFrom(relData);
970
+ if (rel !== undefined)
971
+ relationships.push(rel);
972
+ }
973
+ }
974
+ }
975
+ return relationships;
976
+ }
977
+ // --- supplements and wrappers ----------------------------------------------
978
+ reconstructBaseString(baseData) {
979
+ // The part/subpart/year captures sit one level down, inside the raw
980
+ // part_subpart_year wrapper — hoist them before the flat reads.
981
+ this.unwrapPartSubpartYear(baseData);
982
+ const baseParts = [];
983
+ if (baseData["publishers"] !== undefined) {
984
+ const pubData = asHash(baseData["publishers"]);
985
+ let publisherStr = extractValue(pubData["publisher"]) ?? "";
986
+ if (pubData["copublishers"] !== undefined && pubData["copublishers"] !== "") {
987
+ const copubs = Array.isArray(pubData["copublishers"])
988
+ ? pubData["copublishers"]
989
+ : [pubData["copublishers"]];
990
+ const copubStrs = copubs
991
+ .map((cp) => extractValue(asHash(cp)["copublisher"]))
992
+ .filter((cp) => cp !== undefined);
993
+ if (copubStrs.length > 0)
994
+ publisherStr += `/${copubStrs.join("/")}`;
995
+ }
996
+ baseParts.push(publisherStr);
997
+ }
998
+ if (baseData["type"] !== undefined) {
999
+ baseParts.push(extractValue(baseData["type"]) ?? "");
1000
+ }
1001
+ let numberStr = extractValue(baseData["number"]) ?? "";
1002
+ const baseSep = extractValue(baseData["part_sep"]) ?? ".";
1003
+ if (baseData["part"] !== undefined) {
1004
+ const pv = extractValue(baseData["part"]) ?? "";
1005
+ numberStr += /^[._-]/.test(pv) ? pv : `${baseSep}${pv}`;
1006
+ }
1007
+ if (baseData["subpart"] !== undefined) {
1008
+ const subparts = Array.isArray(baseData["subpart"]) ? baseData["subpart"] : [baseData["subpart"]];
1009
+ for (const sp of subparts) {
1010
+ const v = extractValue(sp);
1011
+ if (v !== undefined)
1012
+ numberStr += /^[._-]/.test(v) ? v : `${baseSep}${v}`;
1013
+ }
1014
+ }
1015
+ if (baseData["year"] !== undefined) {
1016
+ numberStr += `-${extractValue(baseData["year"]) ?? ""}`;
1017
+ }
1018
+ baseParts.push(numberStr);
1019
+ return baseParts.join(" ");
1020
+ }
1021
+ buildCorrigendumSupplement(parsedHash) {
1022
+ const base = ieeeParseSingle(this.env, this.reconstructBaseString(asHash(parsedHash["base"])));
1023
+ const corNumber = extractValue(parsedHash["cor_number"]);
1024
+ const corYear = extractValue(parsedHash["cor_year"]);
1025
+ return new CorrigendumClass({
1026
+ base, number: corNumber, year: corYear,
1027
+ });
1028
+ }
1029
+ buildFlatCorrigendum(parsedHash) {
1030
+ const corData = parsedHash["corrigendum"];
1031
+ const corNumber = extractValue(corData["cor_number"]);
1032
+ const corYear = corData["cor_year"] !== undefined ? extractValue(corData["cor_year"]) : undefined;
1033
+ const baseHash = { ...parsedHash };
1034
+ delete baseHash["corrigendum"];
1035
+ const base = this.buildSingleIdentifier(baseHash, false);
1036
+ return new CorrigendumClass({
1037
+ base, number: corNumber, year: corYear,
1038
+ });
1039
+ }
1040
+ buildFlatAmendment(parsedHash) {
1041
+ const amdData = parsedHash["amendment"];
1042
+ const amdNumber = extractValue(amdData["amd_number"]);
1043
+ const amdYear = amdData["amd_year"] !== undefined ? extractValue(amdData["amd_year"]) : undefined;
1044
+ const baseHash = { ...parsedHash };
1045
+ delete baseHash["amendment"];
1046
+ const base = this.buildSingleIdentifier(baseHash, false);
1047
+ return new AmendmentClass({
1048
+ base, number: amdNumber, year: amdYear,
1049
+ });
1050
+ }
1051
+ buildFlatInterpretation(parsedHash) {
1052
+ const intYear = parsedHash["trailing_year"] !== undefined
1053
+ ? extractValue(parsedHash["trailing_year"])
1054
+ : undefined;
1055
+ const baseHash = { ...parsedHash };
1056
+ delete baseHash["interpretation"];
1057
+ delete baseHash["trailing_month"];
1058
+ delete baseHash["trailing_year"];
1059
+ const base = this.buildSingleIdentifier(baseHash, false);
1060
+ return new InterpretationClass({
1061
+ base, year: intYear,
1062
+ });
1063
+ }
1064
+ buildInterpretationSupplement(parsedHash) {
1065
+ const base = ieeeParseSingle(this.env, this.reconstructBaseString(asHash(parsedHash["base"])));
1066
+ const intYear = extractValue(parsedHash["int_year"]);
1067
+ return new InterpretationClass({
1068
+ base, year: intYear,
1069
+ });
1070
+ }
1071
+ buildAmendmentSupplement(parsedHash) {
1072
+ const base = ieeeParseSingle(this.env, this.reconstructBaseString(asHash(parsedHash["base"])));
1073
+ return new AmendmentClass({
1074
+ base,
1075
+ number: extractValue(parsedHash["amd_number"]),
1076
+ year: extractValue(parsedHash["amd_year"]),
1077
+ });
1078
+ }
1079
+ buildConformanceSupplement(parsedHash) {
1080
+ const base = ieeeParseSingle(this.env, this.reconstructBaseString(asHash(parsedHash["base"])));
1081
+ return new ConformanceClass({
1082
+ base,
1083
+ number: extractValue(parsedHash["conf_number"]),
1084
+ year: extractValue(parsedHash["conf_year"]),
1085
+ });
1086
+ }
1087
+ buildJointDevelopment(parsed) {
1088
+ const attributes = {};
1089
+ if (parsed["joint_publishers"] !== undefined) {
1090
+ const jointPubStr = extractValue(parsed["joint_publishers"]) ?? "";
1091
+ const pubs = jointPubStr.split("/");
1092
+ attributes["publishers"] = pubs;
1093
+ attributes["publisher"] = pubs[0];
1094
+ attributes["copublisher"] = pubs.slice(1);
1095
+ }
1096
+ else if (parsed["publishers"] !== undefined) {
1097
+ // Stage-bearing rows the artifact routes without a
1098
+ // joint_publishers capture ("ISO/IEC/IEEE P26511/D8=DDIS.3"):
1099
+ // the publishers hash carries the same information.
1100
+ const pubData = asHash(parsed["publishers"]);
1101
+ const lead = extractValue(pubData["publisher"]) ?? "";
1102
+ const copubs = pubData["copublishers"] !== undefined
1103
+ ? (Array.isArray(pubData["copublishers"])
1104
+ ? pubData["copublishers"]
1105
+ : [pubData["copublishers"]])
1106
+ .map((cp) => extractValue(asHash(cp)["copublisher"]))
1107
+ .filter((cp) => cp !== undefined)
1108
+ : [];
1109
+ attributes["publishers"] = [lead, ...copubs];
1110
+ attributes["publisher"] = lead;
1111
+ attributes["copublisher"] = copubs;
1112
+ }
1113
+ const codeParts = [];
1114
+ if (parsed["part"] !== undefined)
1115
+ codeParts.push(extractValue(parsed["part"]) ?? "");
1116
+ // The part/subpart captures carry their printed separator
1117
+ // (separator-in-capture); the subpart rides after the part
1118
+ // ("P65700.19.03", "60079-30-2" — the reference's joint code
1119
+ // assembly).
1120
+ if (parsed["subpart"] !== undefined) {
1121
+ const subs = Array.isArray(parsed["subpart"]) ? parsed["subpart"] : [parsed["subpart"]];
1122
+ for (const sp of subs)
1123
+ codeParts.push(extractValue(sp) ?? "");
1124
+ }
1125
+ let codeStr = extractValue(parsed["number"]);
1126
+ if (codeStr !== undefined && codeParts.length > 0) {
1127
+ // The ISO/IEC label's part may be dash-joined ("8802-9") - keep the
1128
+ // printed separator. Separator-carrying captures (the artifact's
1129
+ // part binds ".2") join verbatim.
1130
+ const sep = parsed["iec_label_dash"] !== undefined ? "-" : ".";
1131
+ codeStr += codeParts.map((cp) => /^[._-]/.test(cp) ? cp : `${sep}${cp}`).join("");
1132
+ }
1133
+ // P = project (a draft): identity-bearing, preserved as spelled.
1134
+ if (parsed["project_marker"] !== undefined && codeStr !== undefined) {
1135
+ codeStr = `P${codeStr}`;
1136
+ }
1137
+ if (codeStr !== undefined) {
1138
+ const codeObj = IeeeCode.parse(codeStr);
1139
+ if (codeObj !== undefined) {
1140
+ attributes["__code_obj"] = codeObj;
1141
+ attributes["number"] = codeObj.number;
1142
+ if (codeObj.prefix !== undefined)
1143
+ attributes["prefix"] = codeObj.prefix;
1144
+ if (codeObj.parts.length > 0)
1145
+ attributes["parts"] = codeObj.parts;
1146
+ if (codeObj.originalSeparator !== undefined)
1147
+ attributes["separator"] = codeObj.originalSeparator;
1148
+ }
1149
+ }
1150
+ if (parsed["year"] !== undefined) {
1151
+ attributes["year"] = extractValue(parsed["year"]);
1152
+ }
1153
+ else if (parsed["edition_year"] !== undefined) {
1154
+ attributes["year"] = extractValue(parsed["edition_year"]);
1155
+ }
1156
+ if (parsed["month"] !== undefined)
1157
+ attributes["month"] = extractValue(parsed["month"]);
1158
+ if (parsed["draft_year"] !== undefined) {
1159
+ if (attributes["year"] === undefined)
1160
+ attributes["year"] = extractValue(parsed["draft_year"]);
1161
+ if (attributes["month"] === undefined)
1162
+ attributes["month"] = extractValue(parsed["draft_month"]);
1163
+ }
1164
+ // A status word ("Unapproved") marks the draft (pubid#318).
1165
+ const jointDraftStatus = extractValue(parsed["draft_status"]);
1166
+ if (jointDraftStatus !== undefined)
1167
+ attributes["draft_status"] = jointDraftStatus;
1168
+ // A dash_year tail ("/D-3-2007") is the identity year when the
1169
+ // slots are otherwise empty — the ISO face prints it colon-joined
1170
+ // ("ISO/IEC/IEEE FDIS P15288:2007", the reference's 9258 flow).
1171
+ if (attributes["year"] === undefined && parsed["dash_year"] !== undefined) {
1172
+ const dashYear = (extractValue(parsed["dash_year"]) ?? "").replace(/^[-:]/, "");
1173
+ if (/^\d{4}$/.test(dashYear))
1174
+ attributes["year"] = dashYear;
1175
+ }
1176
+ // The IEEE-led tail word-stage ("IEEE/ISO/IEC P15026-3/CD,
1177
+ // December 2021") composes the D= designator with the glued
1178
+ // 6-digit date — the identity its D= twin spelling parses to (the
1179
+ // corpus canonical: joint-development, lead IEEE, stage P). The
1180
+ // ISO-led lists converge to the published-Std identity (the issue
1181
+ // #216 semantics). The zero-width printed_month_year capture
1182
+ // carries "" — truthy in the reference (nil-check), falsy in JS:
1183
+ // test presence, not truth.
1184
+ if (parsed["tail_iso_stage"] !== undefined &&
1185
+ parsed["printed_month_year"] !== undefined &&
1186
+ parsed["part"] !== undefined) {
1187
+ const stage = extractValue(parsed["tail_iso_stage"]);
1188
+ const year = extractValue(parsed["year"]) ?? "";
1189
+ const monthName = (extractValue(parsed["month"]) ?? "").replace(/\.$/, "");
1190
+ const monthNum = DRAFT_MONTH_NAMES[monthName];
1191
+ if (stage !== undefined && monthNum !== undefined) {
1192
+ attributes["ieee_draft"] = `D=${stage}-${year}${monthNum.padStart(2, "0")}`;
1193
+ parsed["year"] = undefined;
1194
+ parsed["month"] = undefined;
1195
+ parsed["printed_month_year"] = undefined;
1196
+ delete attributes["year"];
1197
+ delete attributes["month"];
1198
+ // The ISO-led lists converge to the published-Std identity; the
1199
+ // IEEE-led lists stay the live project draft (stage P).
1200
+ if (attributes["publisher"] !== "IEEE") {
1201
+ parsed["iso_published"] = { value: "" };
1202
+ const stdRecord = locateStage("Std");
1203
+ if (stdRecord !== undefined) {
1204
+ attributes["typed_stage"] = new IeeeTypedStage(stdRecord);
1205
+ }
1206
+ }
1207
+ }
1208
+ }
1209
+ if (parsed["edition"] !== undefined)
1210
+ attributes["edition"] = extractValue(parsed["edition"]);
1211
+ if (parsed["edition_month"] !== undefined) {
1212
+ attributes["edition_month"] = extractValue(parsed["edition_month"]);
1213
+ }
1214
+ if (parsed["draft_version"] !== undefined) {
1215
+ const draftVer = (extractValue(parsed["draft_version"]) ?? "").replace(/^D/, "");
1216
+ // FCD is an ISO stage (the 2026-10-19 ruling): a glued month-name
1217
+ // date rides the designator's date slot with the month numeric —
1218
+ // the D= designator face, never the "DFCD" glue.
1219
+ const stageDate = /^(FDIS|FCD|CDV|DIS|CD|WD|PWI|NP)(\d+)?(?:-([A-Za-z]+)(\d{4}))?$/.exec(draftVer);
1220
+ if (stageDate !== null) {
1221
+ const monthNum = stageDate[3] !== undefined ? DRAFT_MONTH_NAMES[stageDate[3]] : undefined;
1222
+ const stageWord = stageDate[1] + (stageDate[2] ?? "");
1223
+ attributes["ieee_draft"] =
1224
+ stageDate[3] !== undefined && monthNum !== undefined
1225
+ ? `D=${stageWord}-${stageDate[4]}${monthNum.padStart(2, "0")}`
1226
+ : `D=${stageWord}`;
1227
+ delete attributes["draft"];
1228
+ delete attributes["year"];
1229
+ delete attributes["month"];
1230
+ }
1231
+ else if (draftVer !== "") {
1232
+ // A date trailing the draft (", June 2010") belongs to the draft
1233
+ // component (canonical month, comma form); the identity
1234
+ // year/month the promotion filled from the same captures are
1235
+ // vacated. Stage-first ISO rows are exempt: their canonical is
1236
+ // the ISO face, which prints the date from the identity slots
1237
+ // (", March 2017", pubid#216).
1238
+ if (parsed["draft_month"] !== undefined && parsed["iso_stage"] === undefined) {
1239
+ const dm = extractValue(parsed["draft_month"]) ?? "";
1240
+ const dy = extractValue(parsed["draft_year"]) ?? "";
1241
+ const monthNum = DRAFT_MONTH_NAMES[dm.replace(/\.$/, "")];
1242
+ if (JSON.stringify(attributes["publishers"]) === JSON.stringify(["IEEE", "CSA"]) &&
1243
+ monthNum !== undefined && dy !== "") {
1244
+ // The joint IEEE/CSA drafts glue their date into the
1245
+ // designator with the month numeric (pubid ruling
1246
+ // 2026-10-14: no comma dates on these rows).
1247
+ const glued = new IeeeDraft({
1248
+ version: `${draftVer}-${dy}-${monthNum.padStart(2, "0")}`,
1249
+ });
1250
+ attributes["draft"] = glued.render();
1251
+ }
1252
+ else {
1253
+ const draftObj = new IeeeDraft({
1254
+ version: draftVer,
1255
+ month: dm === "" ? undefined : dm,
1256
+ year: dy === "" ? undefined : dy,
1257
+ comma_before_month: true,
1258
+ });
1259
+ attributes["draft"] = draftObj.render();
1260
+ }
1261
+ if (parsed["year"] === undefined)
1262
+ delete attributes["year"];
1263
+ if (parsed["month"] === undefined)
1264
+ delete attributes["month"];
1265
+ }
1266
+ else if (parsed["draft_year"] !== undefined && parsed["iso_stage"] === undefined) {
1267
+ // The comma-year tail captures its separator (", 2013") —
1268
+ // strip it (the #471 separator-in-capture rule). The stored
1269
+ // form keeps the comma so it re-parses through the same tail.
1270
+ const draftYear = (extractValue(parsed["draft_year"]) ?? "").replace(/^[, ]+/, "");
1271
+ // Compose through the render so a designator-word version
1272
+ // ("ED1") keeps its word instead of concatenating D ("DED1").
1273
+ attributes["draft"] =
1274
+ new IeeeDraft({ version: draftVer, year: draftYear }).render();
1275
+ if (parsed["year"] === undefined)
1276
+ delete attributes["year"];
1277
+ }
1278
+ else if (JSON.stringify(attributes["publishers"]) === JSON.stringify(["IEEE", "CSA"]) &&
1279
+ parsed["iso_stage"] === undefined &&
1280
+ /^(19|20)\d\d$/.test(extractValue(parsed["year"]) ?? "") &&
1281
+ /^\d{1,2}$/.test(extractValue(parsed["month"]) ?? "")) {
1282
+ // The glued face re-parses with the date in the identity
1283
+ // slots ("D2-2016-09" -> year/month + a bare D2): it
1284
+ // normalizes back onto the draft-embedded date so the
1285
+ // round trip closes on the CSA canonical.
1286
+ const glued = new IeeeDraft({
1287
+ version: `${draftVer}-${extractValue(parsed["year"])}-${extractValue(parsed["month"])}`,
1288
+ });
1289
+ attributes["draft"] = glued.render();
1290
+ delete attributes["year"];
1291
+ delete attributes["month"];
1292
+ }
1293
+ else {
1294
+ attributes["ieee_draft"] = `D${draftVer}`;
1295
+ }
1296
+ }
1297
+ }
1298
+ // The "(E)" edition marker of an ISO/IEC label rides on the joint
1299
+ // reference as parenthetical_content - either from the trailing
1300
+ // parenthetical slot (the double-label form) or the mid-rule slot
1301
+ // before an amendment tail.
1302
+ const parenthetical = parsed["parameters"];
1303
+ if (parenthetical !== undefined && typeof parenthetical === "object" && !Array.isArray(parenthetical)) {
1304
+ const content = parenthetical["parenthetical_content"];
1305
+ if (content !== undefined)
1306
+ attributes["parenthetical_content"] = extractValue(content);
1307
+ }
1308
+ if (attributes["parenthetical_content"] === undefined && parsed["edition_marker"] !== undefined) {
1309
+ attributes["parenthetical_content"] = extractValue(parsed["edition_marker"]);
1310
+ }
1311
+ // A joint ISO-print redline is a distinct document of the same standard
1312
+ // (pubid#215) - same flag semantics as the generic path.
1313
+ if (parsed["redline"] !== undefined)
1314
+ attributes["redline"] = true;
1315
+ // The joint stage-draft clause (docs/IEEE-DRAFT-STAGES.md §1.3):
1316
+ // variant 1's compound tail composes onto the IEEE ordinal
1317
+ // ("D5=DIS.3"); variant 1b is the ordinal-less stage draft whose
1318
+ // date rides inside the designator ("D=CDV:2020"). The doubled-D
1319
+ // alias spelling echoes as spelled.
1320
+ if (parsed["draft_iso_stage"] !== undefined) {
1321
+ // The doubled-D alias ("=DDIS") is notation: the designator carries
1322
+ // its own D-ordinal, the stage is the bare ISO/IEC token.
1323
+ const rawStage = `${extractValue(parsed["draft_stage_d"]) ?? ""}${extractValue(parsed["draft_iso_stage"]) ?? ""}`;
1324
+ const stageText = rawStage.startsWith("D") &&
1325
+ ["PWI", "NP", "WD", "CD", "CDV", "DIS", "FDIS"].includes(rawStage.slice(1))
1326
+ ? rawStage.slice(1)
1327
+ : rawStage;
1328
+ const jointVersion = extractValue(parsed["draft_version"]) ??
1329
+ (parsed["draft"] !== undefined
1330
+ ? extractValue(asHash(parsed["draft"])["draft_version"])
1331
+ : undefined);
1332
+ let jointDraft = jointVersion !== undefined
1333
+ ? `D${jointVersion.replace(/^D/, "")}=${stageText}`
1334
+ : `D=${stageText}`;
1335
+ if (parsed["draft_iso_iteration"] !== undefined) {
1336
+ jointDraft += `.${extractValue(parsed["draft_iso_iteration"])}`;
1337
+ }
1338
+ if (parsed["draft_stage_year"] !== undefined) {
1339
+ // The capture carries its separator verbatim (":2020" /
1340
+ // "-201112" - the #471 separator-in-capture rule): the ruby
1341
+ // builder appends it raw, so the face keeps the printed form.
1342
+ jointDraft += extractValue(parsed["draft_stage_year"]) ?? "";
1343
+ }
1344
+ attributes["ieee_draft"] = jointDraft;
1345
+ }
1346
+ // The catalogue-PRINTED joint form (dash-year / ", Month YYYY" /
1347
+ // date-trailing-the-draft / date-less parenthetical): a Standard
1348
+ // carrying publisher/copublisher renders it as printed; the colon-year
1349
+ // spelling stays the ISO-style JointDevelopment. Stage-WORD drafts
1350
+ // (letters, not a D-number) stay joint - their canonical renders drop
1351
+ // the P and keep the joint spelling.
1352
+ const numericDraft = parsed["draft_version"] !== undefined &&
1353
+ /^\d/.test(extractValue(parsed["draft_version"]) ?? "");
1354
+ // P + a /D designator (any draft capture) is a DRAFT, never a
1355
+ // printed Std (the owner's 2026-10-24 ruling) -- the joint/
1356
+ // project-draft family owns the row whatever date trails the
1357
+ // designator. The ruling extends to the P-less joint rows
1358
+ // (pubid#597): a numeric /D designator alone is project status
1359
+ // too -- the row is a draft AND takes the P, so the marker is set
1360
+ // below when the source spelling lacked it.
1361
+ const pWithDraft = (parsed["project_marker"] !== undefined || numericDraft) &&
1362
+ (parsed["draft_version"] !== undefined || parsed["draft_iso_stage"] !== undefined ||
1363
+ parsed["draft_month"] !== undefined || parsed["draft_year"] !== undefined);
1364
+ if (pWithDraft && parsed["project_marker"] === undefined) {
1365
+ attributes["project_marker"] = true;
1366
+ parsed["project_marker"] = "P";
1367
+ }
1368
+ if (
1369
+ // The bound tree spreads the raw iso_published interior flat, so a
1370
+ // stage-first joint row carries a top-level iso_stage — the stage
1371
+ // word keeps the joint ISO face (the reference's iso_stage.nil? gate).
1372
+ parsed["iso_published"] !== undefined && parsed["iso_stage"] === undefined && !pWithDraft &&
1373
+ (parsed["printed_dash_year"] !== undefined || parsed["printed_month_year"] !== undefined ||
1374
+ (numericDraft && parsed["draft_month"] !== undefined) ||
1375
+ (parsed["year"] === undefined && parsed["parameters"] !== undefined &&
1376
+ typeof parsed["parameters"] === "object" && !Array.isArray(parsed["parameters"]) &&
1377
+ parsed["parameters"]["parenthetical_content"] !== undefined))) {
1378
+ const sep = parsed["part_dash"] !== undefined ? "-" : ".";
1379
+ // The part capture carries its own separator (C1
1380
+ // separator-in-capture); join verbatim, synthesizing one only
1381
+ // for a bare capture — the reference's printed_joint rule.
1382
+ const partVal = extractValue(parsed["part"]);
1383
+ let printedCode = extractValue(parsed["number"]) ?? "";
1384
+ if (partVal !== undefined) {
1385
+ printedCode += /^[._-]/.test(partVal) ? partVal : `${sep}${partVal}`;
1386
+ }
1387
+ // the subpart carries its separator too (C1 separator-in-capture);
1388
+ // the two-party rows split "-57-1202"-class parts into both
1389
+ const subVal = parsed["subpart"] !== undefined ? extractValue(parsed["subpart"]) : undefined;
1390
+ if (subVal !== undefined && subVal !== "")
1391
+ printedCode += subVal;
1392
+ // P = project: the marker is identity, preserved as spelled.
1393
+ if (parsed["project_marker"] !== undefined)
1394
+ printedCode = `P${printedCode}`;
1395
+ const printedAttrs = {
1396
+ publisher: attributes["publisher"],
1397
+ copublisher: attributes["copublisher"],
1398
+ typed_stage: locateStage("Std") !== undefined ? new IeeeTypedStage(locateStage("Std")) : undefined,
1399
+ };
1400
+ let printedDraft = attributes["ieee_draft"];
1401
+ let finalCode = printedCode;
1402
+ if (parsed["printed_dash_year"] !== undefined && parsed["month"] !== undefined) {
1403
+ // A dash-year-month date glues onto the printed code before any
1404
+ // draft - the render's month slot would lose the printed form.
1405
+ finalCode = `${printedCode}-${attributes["year"]}-${attributes["month"]}`;
1406
+ }
1407
+ else if (parsed["printed_dash_year"] !== undefined) {
1408
+ // A bare dash-year is the identity year - an attribute.
1409
+ printedAttrs["year"] = attributes["year"];
1410
+ }
1411
+ else if (parsed["printed_month_year"] !== undefined) {
1412
+ printedAttrs["year"] = attributes["year"];
1413
+ printedAttrs["month"] = attributes["month"];
1414
+ }
1415
+ else if (parsed["draft_month"] !== undefined) {
1416
+ // The date trails the draft itself ("D31, Aug 2010"): the
1417
+ // normalization ledger strips the ordinal draft on the printed
1418
+ // joint face and surfaces the date as the printed date.
1419
+ printedAttrs["year"] = extractValue(parsed["draft_year"]);
1420
+ printedAttrs["month"] = extractValue(parsed["draft_month"]);
1421
+ }
1422
+ const codeObj = IeeeCode.parse(finalCode);
1423
+ if (codeObj !== undefined) {
1424
+ printedAttrs["__code_obj"] = codeObj;
1425
+ printedAttrs["number"] = codeObj.number;
1426
+ if (codeObj.prefix !== undefined)
1427
+ printedAttrs["prefix"] = codeObj.prefix;
1428
+ if (codeObj.parts.length > 0)
1429
+ printedAttrs["parts"] = codeObj.parts;
1430
+ if (codeObj.originalSeparator !== undefined)
1431
+ printedAttrs["separator"] = codeObj.originalSeparator;
1432
+ }
1433
+ if (printedDraft !== undefined)
1434
+ printedAttrs["draft"] = printedDraft;
1435
+ if (attributes["edition"] !== undefined)
1436
+ printedAttrs["edition"] = attributes["edition"];
1437
+ if (attributes["edition_month"] !== undefined)
1438
+ printedAttrs["edition_month"] = attributes["edition_month"];
1439
+ const params = parsed["parameters"];
1440
+ if (params !== undefined && typeof params === "object" && !Array.isArray(params) &&
1441
+ params["parenthetical_content"] !== undefined) {
1442
+ printedAttrs["parenthetical_content"] = extractValue(params["parenthetical_content"]);
1443
+ }
1444
+ for (const k of Object.keys(printedAttrs)) {
1445
+ if (printedAttrs[k] === undefined)
1446
+ delete printedAttrs[k];
1447
+ }
1448
+ const printed = new StandardClass(printedAttrs);
1449
+ if (printedAttrs["__code_obj"] instanceof IeeeCode) {
1450
+ printed["__code_obj"] = printedAttrs["__code_obj"];
1451
+ }
1452
+ return printed;
1453
+ }
1454
+ // A stage word with a glued year tail ("/D=CD2-201802") rides the
1455
+ // D= designator with the IEEE lead (the reference's builder, the
1456
+ // pubid#203 class) — the tail's capture carries its separator. The
1457
+ // date-less form ("/D=CD1") elects the same face only when the input
1458
+ // spells the designator (the reference's original_input gate) — the
1459
+ // stage-first rows keep their ISO rendering.
1460
+ // The designation route ("IEEE P24748-4/D=FDIS") has no
1461
+ // publishers group; IEEE is the sole publisher of the D=
1462
+ // designator face, and the elections below read the builder-local
1463
+ // slots.
1464
+ if (attributes["publisher"] === undefined)
1465
+ attributes["publisher"] = "IEEE";
1466
+ if (attributes["copublisher"] === undefined)
1467
+ attributes["copublisher"] = [];
1468
+ // The model rebuilds publishers from publisher+copublisher when
1469
+ // the publishers group is absent (the reference initialize).
1470
+ if (attributes["publishers"] === undefined) {
1471
+ attributes["publishers"] = [attributes["publisher"],
1472
+ ...(attributes["copublisher"] ?? [])];
1473
+ }
1474
+ const dEqInput = this.originalInput.includes("/D=");
1475
+ const stageWordForGate = extractValue(parsed["iso_stage"]) ?? "";
1476
+ if (parsed["iso_stage"] !== undefined &&
1477
+ (parsed["draft_stage_year"] !== undefined ||
1478
+ (dEqInput && /\d$/.test(stageWordForGate)))) {
1479
+ const stageWord = stageWordForGate;
1480
+ const pubs = (attributes["publishers"] ?? []);
1481
+ if (pubs.length === 0) {
1482
+ attributes["publishers"] = ["IEEE"];
1483
+ attributes["publisher"] = "IEEE";
1484
+ attributes["copublisher"] = [];
1485
+ }
1486
+ attributes["ieee_draft"] = `D=${stageWord}${extractValue(parsed["draft_stage_year"]) ?? ""}`;
1487
+ const stageRecord = locateStage(stageWord);
1488
+ if (stageRecord !== undefined) {
1489
+ attributes["typed_stage"] = new IeeeTypedStage(stageRecord);
1490
+ }
1491
+ attributes["lead_party"] = "IEEE";
1492
+ delete attributes["year"];
1493
+ delete attributes["month"];
1494
+ }
1495
+ if (parsed["iso_stage"] !== undefined) {
1496
+ // A bare-IEEE project carrying a stage never elects the ISO lead
1497
+ // (the reference's bare_ieee_project gate): the lead stays IEEE.
1498
+ const bareIeeeProject = parsed["project_marker"] !== undefined &&
1499
+ attributes["publisher"] === "IEEE" &&
1500
+ (attributes["copublisher"] ?? []).length === 0;
1501
+ if (!bareIeeeProject)
1502
+ attributes["lead_party"] = "ISO";
1503
+ let stageAbbr = extractValue(parsed["iso_stage"]);
1504
+ // The bare-IEEE project row carries the stage on the D=
1505
+ // designator with the IEEE date convention ("D=FDIS-201008",
1506
+ // pubid#203); the ISO stage-word face is not elected.
1507
+ if (bareIeeeProject && parsed["draft_stage_year"] === undefined) {
1508
+ let date = "";
1509
+ const y = attributes["year"];
1510
+ const m = String(attributes["month"] ?? "");
1511
+ if (y !== undefined) {
1512
+ date = `-${y}`;
1513
+ if (m !== "") {
1514
+ const monthNum = /^\d+$/.test(m) ? Number(m) : DRAFT_MONTH_NAMES[String(m).replace(/\.$/, "")];
1515
+ if (monthNum !== undefined)
1516
+ date += String(monthNum).padStart(2, "0");
1517
+ }
1518
+ }
1519
+ attributes["ieee_draft"] = `D=${stageAbbr}${date}`;
1520
+ const record = stageAbbr !== undefined ? locateStage(stageAbbr) : undefined;
1521
+ if (record !== undefined)
1522
+ attributes["typed_stage"] = new IeeeTypedStage(record);
1523
+ attributes["lead_party"] = "IEEE";
1524
+ delete attributes["year"];
1525
+ delete attributes["month"];
1526
+ }
1527
+ // The IEC "/V<version>" iteration rides glued onto the stage word
1528
+ // ("_CDV/V3" -> "CDV3") — the family's lossless spelling (the
1529
+ // reference's builder, pubid#477).
1530
+ const stageIteration = extractValue(parsed["iso_stage_iteration"]);
1531
+ if (stageAbbr !== undefined && stageIteration !== undefined) {
1532
+ stageAbbr += stageIteration;
1533
+ }
1534
+ if (!bareIeeeProject)
1535
+ attributes["iso_stage"] = stageAbbr;
1536
+ if (stageAbbr !== undefined && !bareIeeeProject) {
1537
+ const record = locateStage(stageAbbr);
1538
+ if (record !== undefined)
1539
+ attributes["typed_stage"] = new IeeeTypedStage(record);
1540
+ }
1541
+ }
1542
+ else if (parsed["iso_published"] !== undefined) {
1543
+ attributes["lead_party"] = "ISO";
1544
+ }
1545
+ else {
1546
+ attributes["lead_party"] = "IEEE";
1547
+ attributes["type"] = "P";
1548
+ if ((parsed["draft_iso_stage"] !== undefined ||
1549
+ parsed["tail_iso_stage"] !== undefined) &&
1550
+ attributes["publisher"] === "ISO") {
1551
+ // The ISO-led D= designator (the issue #216 convergence) is
1552
+ // the stage-tracked draft of a published standard - the typed
1553
+ // stage reads Std/published.
1554
+ const stdRecord = locateStage("Std");
1555
+ if (stdRecord !== undefined) {
1556
+ attributes["typed_stage"] = new IeeeTypedStage(stdRecord);
1557
+ }
1558
+ }
1559
+ else {
1560
+ const record = locateStage("P");
1561
+ if (record !== undefined)
1562
+ attributes["typed_stage"] = new IeeeTypedStage(record);
1563
+ }
1564
+ }
1565
+ // A plain IEEE-designator draft on joint publishers ("/D8, June
1566
+ // 2010") carries no ISO stage machinery: it builds as the project
1567
+ // draft its bare-IEEE twin and the D= designator rows already pin
1568
+ // (pubid#430) rather than the joint-development model.
1569
+ if (attributes["draft"] !== undefined &&
1570
+ parsed["iso_stage"] === undefined &&
1571
+ parsed["iec_stage"] === undefined &&
1572
+ parsed["amd_number"] === undefined) {
1573
+ const pubs = (attributes["publishers"] ?? []);
1574
+ const projectAttrs = {
1575
+ draft: attributes["draft"],
1576
+ };
1577
+ // The comma-year tail rides the draft verbatim ("D4, 2019" — the
1578
+ // reference keeps the comma face on the joint project drafts; the
1579
+ // year never promotes to the identity slots).
1580
+ // The code columns (number/parts/separator/prefix) are the
1581
+ // ProjectDraft render/hash face; the spelled P is the project
1582
+ // marker (identity), whatever the lead publisher.
1583
+ for (const k of ["number", "prefix", "parts", "separator"]) {
1584
+ // A "P" prefix is the project marker itself (the generic path
1585
+ // deletes it on the strip) - it must not ride the code columns.
1586
+ if (attributes[k] !== undefined && !(k === "prefix" && attributes[k] === "P")) {
1587
+ projectAttrs[k] = attributes[k];
1588
+ }
1589
+ }
1590
+ // The ruling (pubid#597): a joint row with a numeric /D designator
1591
+ // is a draft AND takes the P project marker, whatever the source
1592
+ // spelling printed -- the marker rides the identifier even when
1593
+ // the row reached it without one.
1594
+ projectAttrs["project_marker"] = true;
1595
+ if (pubs.length > 0) {
1596
+ projectAttrs["publisher"] = pubs[0];
1597
+ if (pubs.length > 1)
1598
+ projectAttrs["copublisher"] = pubs.slice(1);
1599
+ }
1600
+ if (attributes["draft_status"] !== undefined) {
1601
+ projectAttrs["draft_status"] = attributes["draft_status"];
1602
+ }
1603
+ // Ruby's draft_attrs[:code] = "P" + code re-strips in
1604
+ // ProjectDraftIdentifier#initialize and parses the stripped string —
1605
+ // rebuild the runtime code obj from the P-less columns the same way.
1606
+ const strippedCode = new IeeeCode({
1607
+ number: projectAttrs["number"],
1608
+ prefix: projectAttrs["prefix"],
1609
+ parts: projectAttrs["parts"],
1610
+ original_separator: projectAttrs["separator"],
1611
+ }).render();
1612
+ const strippedObj = IeeeCode.parse(strippedCode);
1613
+ if (strippedObj !== undefined)
1614
+ projectAttrs["__code_obj"] = strippedObj;
1615
+ const projectBuilt = new ProjectDraftIdentifierClass(projectAttrs);
1616
+ projectBuilt["__code_obj"] = strippedObj;
1617
+ return projectBuilt;
1618
+ }
1619
+ // The iso_published joint rows normalize the publisher order to
1620
+ // ISO-first (the reference: "IEEE/ISO/IEC 8802-3:2021/Amd 4-2021"
1621
+ // builds the base [ISO, IEC, IEEE], lead ISO); the CD-stage rows and
1622
+ // the IEEE-led project rows preserve the printed order (P90003 stays
1623
+ // IEEE/ISO/IEC).
1624
+ // The reorder is the PUBLISHED stage-less doctrine (pubid#317)
1625
+ // only: the project rows (the P marker) and every draft-bearing
1626
+ // row keep the printed publisher order (the 2026-10-24 corpus
1627
+ // faces, pubid#595).
1628
+ const draftBearing = parsed["project_marker"] !== undefined ||
1629
+ parsed["draft_version"] !== undefined ||
1630
+ parsed["draft"] !== undefined ||
1631
+ parsed["draft_iso_stage"] !== undefined ||
1632
+ parsed["draft_stage_year"] !== undefined;
1633
+ if (parsed["iso_published"] !== undefined && parsed["iso_stage"] === undefined &&
1634
+ !draftBearing && Array.isArray(attributes["publishers"])) {
1635
+ const pubs = attributes["publishers"];
1636
+ attributes["publishers"] = [...pubs.filter((p) => p !== "IEEE"), ...pubs.filter((p) => p === "IEEE")];
1637
+ attributes["publisher"] = attributes["publishers"][0];
1638
+ attributes["copublisher"] = attributes["publishers"].slice(1);
1639
+ }
1640
+ const joint = new JointDevelopmentClass(attributes);
1641
+ if (attributes["__code_obj"] instanceof IeeeCode) {
1642
+ joint["__code_obj"] = attributes["__code_obj"];
1643
+ }
1644
+ const jointIdentifier = joint;
1645
+ if (parsed["amd_number"] === undefined)
1646
+ return jointIdentifier;
1647
+ const amdYear = parsed["amd_year"] !== undefined ? extractValue(parsed["amd_year"]) : undefined;
1648
+ return new AmendmentClass({
1649
+ base: jointIdentifier,
1650
+ number: extractValue(parsed["amd_number"]),
1651
+ year: amdYear,
1652
+ });
1653
+ }
1654
+ buildSiPsi(parsed) {
1655
+ const attributes = {};
1656
+ const siType = extractValue(parsed["si_type"]);
1657
+ // The bare top-level draft clause binds as draft_version_scalar
1658
+ // (string) — surface it under the key this builder reads (the
1659
+ // reference's build_si_psi_identifier).
1660
+ if (parsed["draft_version"] === undefined && parsed["draft_version_scalar"] !== undefined) {
1661
+ parsed["draft_version"] = parsed["draft_version_scalar"];
1662
+ delete parsed["draft_version_scalar"];
1663
+ }
1664
+ // Extract publishers (should be "IEEE/ASTM") — the SI rule's bare
1665
+ // publishers clause binds as publishers_scalar (string); the
1666
+ // composite joint rows deliver publishers (raw).
1667
+ const pubSrc = parsed["publishers"] ?? parsed["publishers_scalar"];
1668
+ if (pubSrc !== undefined) {
1669
+ const publishersStr = extractValue(pubSrc) ?? "";
1670
+ const pubs = publishersStr.split("/");
1671
+ attributes["publisher"] = pubs[0];
1672
+ if (pubs.length > 1)
1673
+ attributes["copublisher"] = pubs.slice(1);
1674
+ }
1675
+ const codeStr = extractValue(parsed["number"]);
1676
+ if (codeStr !== undefined) {
1677
+ const codeObj = IeeeCode.parse(codeStr);
1678
+ if (codeObj !== undefined) {
1679
+ attributes["__code_obj"] = codeObj;
1680
+ attributes["number"] = codeObj.number;
1681
+ if (codeObj.prefix !== undefined)
1682
+ attributes["prefix"] = codeObj.prefix;
1683
+ if (codeObj.parts.length > 0)
1684
+ attributes["parts"] = codeObj.parts;
1685
+ if (codeObj.originalSeparator !== undefined)
1686
+ attributes["separator"] = codeObj.originalSeparator;
1687
+ }
1688
+ }
1689
+ const stageRecord = SI_STAGES.find((ts) => siType !== undefined && ts.abbr.includes(siType));
1690
+ if (stageRecord !== undefined)
1691
+ attributes["typed_stage"] = new IeeeTypedStage(stageRecord);
1692
+ if (siType === "PSI" && parsed["draft_version"] !== undefined) {
1693
+ attributes["draft"] = new IeeeDraft({ version: extractValue(parsed["draft_version"]) ?? "" }).render();
1694
+ }
1695
+ if (parsed["year"] !== undefined)
1696
+ attributes["year"] = extractValue(parsed["year"]);
1697
+ if (parsed["month"] !== undefined)
1698
+ attributes["month"] = extractValue(parsed["month"]);
1699
+ if (parsed["relationship_type"] !== undefined || parsed["relationship_clause"] !== undefined) {
1700
+ attributes["relationships"] = this.buildRelationships(parsed);
1701
+ }
1702
+ this.handleParameters(parsed, attributes);
1703
+ const siBuilt = new SiStandardClass(attributes);
1704
+ if (attributes["__code_obj"] instanceof IeeeCode) {
1705
+ siBuilt["__code_obj"] = attributes["__code_obj"];
1706
+ }
1707
+ return siBuilt;
1708
+ }
1709
+ buildMultiNumbered(parsed) {
1710
+ const primaryId = this.buildSingleIdentifier(asHash(parsed["primary_identifier"]), false);
1711
+ let secondaryId;
1712
+ if (parsed["secondary_crossref"] !== undefined) {
1713
+ const crossref = extractValue(parsed["secondary_crossref"]) ?? "";
1714
+ secondaryId = new StandardClass({
1715
+ publisher: "IEEE",
1716
+ number: crossref.replace(/^\//, ""),
1717
+ });
1718
+ }
1719
+ else if (parsed["secondary_joint"] !== undefined) {
1720
+ secondaryId = this.buildSingleIdentifier(asHash(parsed["secondary_joint"]), true);
1721
+ }
1722
+ return new MultiNumberedClass({
1723
+ primary_identifier: primaryId,
1724
+ secondary_identifier: secondaryId,
1725
+ });
1726
+ }
1727
+ buildCsaDualPublished(parsed) {
1728
+ const ieeeId = this.buildSingleIdentifier(asHash(parsed["ieee_portion"]), false);
1729
+ // The CSA portion normalizes "No." to the catalogue's "NO." spelling
1730
+ // (the Ruby CSA component uppercases it) so every alias renders the
1731
+ // same canonical form.
1732
+ const csaString = (extractValue(parsed["csa_portion"]) ?? "").replace(/\bNo\./, "NO.");
1733
+ return new CsaDualPublishedClass({
1734
+ ieee_identifier: ieeeId,
1735
+ csa_string: csaString,
1736
+ year: ieeeId.year,
1737
+ typed_stage: ieeeId.typed_stage,
1738
+ });
1739
+ }
1740
+ buildSDesignation(parsed) {
1741
+ const attributes = {
1742
+ number: extractValue(parsed["s_number"]),
1743
+ publisher: extractValue(parsed["publisher"]) ?? "IEEE",
1744
+ type: "Std",
1745
+ };
1746
+ const stdRecord = locateStage("Std");
1747
+ if (stdRecord !== undefined)
1748
+ attributes["typed_stage"] = new IeeeTypedStage(stdRecord);
1749
+ if (parsed["ipcea_copub"] !== undefined) {
1750
+ attributes["crossref"] = extractValue(parsed["ipcea_copub"]);
1751
+ }
1752
+ this.handleParameters(parsed, attributes);
1753
+ return new StandardClass(attributes);
1754
+ }
1755
+ buildCombinedAiee(parsed) {
1756
+ const firstId = this.buildAiee(asHash(parsed["first_aiee"]));
1757
+ const secondId = this.buildAiee(asHash(parsed["second_aiee"]));
1758
+ return new DualPublishedClass({
1759
+ first_identifier: firstId,
1760
+ second_identifier: secondId,
1761
+ });
1762
+ }
1763
+ buildIecIeeCopublished(parsed) {
1764
+ const contentRaw = extractValue(parsed["content"]);
1765
+ let copublishedNumber;
1766
+ let draftInfo;
1767
+ let iecYear;
1768
+ let dateInfo;
1769
+ let relationships;
1770
+ if (contentRaw !== undefined) {
1771
+ // A bare (unparenthesised) revision narrative printed after the code
1772
+ // is the same relationship prose as the parenthetical form (C3
1773
+ // ruling) — rewrite it into the parenthetical shape so both
1774
+ // spellings collapse onto one canonical.
1775
+ let content = contentRaw;
1776
+ const bare = content.match(/^(.+?) (Revis(?:ion|on) (?:of|to) IEEE Std .+)$/);
1777
+ if (bare !== null)
1778
+ content = `${bare[1]} (${bare[2]})`;
1779
+ if (content.includes("IEC:")) {
1780
+ copublishedNumber = content.split(" IEC:")[0]?.trim();
1781
+ }
1782
+ else if (content.includes(", ")) {
1783
+ copublishedNumber = content.split(", ")[0]?.trim();
1784
+ }
1785
+ else if (content.includes(" (")) {
1786
+ copublishedNumber = content.split(" (")[0]?.trim();
1787
+ }
1788
+ else {
1789
+ copublishedNumber = content.trim();
1790
+ }
1791
+ if (copublishedNumber !== undefined && copublishedNumber.includes("/D")) {
1792
+ const parts = copublishedNumber.split("/D");
1793
+ copublishedNumber = parts[0];
1794
+ draftInfo = `/D${parts[1] ?? ""}`;
1795
+ }
1796
+ if (content.includes("IEC:")) {
1797
+ const iecPart = content.split("IEC:")[1];
1798
+ if (iecPart !== undefined)
1799
+ iecYear = iecPart.split(" ")[0];
1800
+ }
1801
+ // The parenthetical tail is classified, not swallowed (C3 ruling):
1802
+ // a "(Revision of IEEE Std ...)" narrative is a relationship, not
1803
+ // identity — it lands in `relationships` so the URN carries it as
1804
+ // the rel. segment and the canonical human drops it; an "(MM/DD)"
1805
+ // print date is non-identity and dropped; anything else keeps the
1806
+ // historical date_info rendering.
1807
+ if (content.includes(" (")) {
1808
+ const datePart = content.split(" (")[1];
1809
+ if (datePart !== undefined && datePart.includes(")")) {
1810
+ const tail = datePart.split(")")[0];
1811
+ const revision = tail !== undefined
1812
+ ? tail.match(/^Revis(?:ion|on) (?:of|to) IEEE Std (.+)$/)
1813
+ : null;
1814
+ if (tail !== undefined && revision !== null) {
1815
+ let related;
1816
+ try {
1817
+ related = ieeeParseSingle(this.env, revision[1]);
1818
+ }
1819
+ catch {
1820
+ related = { toHuman: () => revision[1] };
1821
+ }
1822
+ relationships = [new IeeeRelationship("revision_of", [related], [])];
1823
+ }
1824
+ else if (tail !== undefined && /^\d{2}\/\d{2}$/.test(tail)) {
1825
+ // print date — non-identity, dropped
1826
+ }
1827
+ else if (tail !== undefined) {
1828
+ dateInfo = tail;
1829
+ }
1830
+ }
1831
+ }
1832
+ }
1833
+ const attrs = {};
1834
+ if (draftInfo !== undefined)
1835
+ attrs["draft_info"] = draftInfo;
1836
+ if (iecYear !== undefined)
1837
+ attrs["iec_year"] = iecYear;
1838
+ if (dateInfo !== undefined)
1839
+ attrs["date_info"] = dateInfo;
1840
+ if (relationships !== undefined)
1841
+ attrs["relationships"] = relationships;
1842
+ Object.assign(attrs, copublishedStructured(copublishedNumber));
1843
+ return new IecIeeeCopublishedClass(attrs);
1844
+ }
1845
+ // --- AIEE / IRE / NESC builders ---------------------------------------------
1846
+ buildAiee(parsed) {
1847
+ const attributes = { publisher: "AIEE" };
1848
+ const typeStr = extractValue(parsed["type"]);
1849
+ attributes["type"] = typeStr !== undefined && typeStr.startsWith("Standard") ? "No" : typeStr;
1850
+ const numberValue = parsed["number"];
1851
+ let codeStr;
1852
+ if (isObj(numberValue)) {
1853
+ const main = extractValue(numberValue["main_number"]);
1854
+ const paren = numberValue["parenthetical"];
1855
+ const alt = isObj(paren) ? extractValue(paren["alt_number"]) : undefined;
1856
+ codeStr = alt !== undefined && main !== undefined ? `${main} (${alt})` : main;
1857
+ }
1858
+ else {
1859
+ codeStr = extractValue(numberValue);
1860
+ }
1861
+ if (codeStr !== undefined) {
1862
+ const codeObj = IeeeCode.parse(codeStr);
1863
+ if (codeObj !== undefined) {
1864
+ attributes["__code_obj"] = codeObj;
1865
+ attributes["number"] = codeObj.number;
1866
+ if (codeObj.prefix !== undefined)
1867
+ attributes["prefix"] = codeObj.prefix;
1868
+ if (codeObj.parts.length > 0)
1869
+ attributes["parts"] = codeObj.parts;
1870
+ if (codeObj.originalSeparator !== undefined)
1871
+ attributes["separator"] = codeObj.originalSeparator;
1872
+ }
1873
+ }
1874
+ attributes["year"] = extractValue(parsed["year"]);
1875
+ const monthStr = extractValue(parsed["month"]);
1876
+ if (monthStr !== undefined)
1877
+ attributes["month"] = monthStr;
1878
+ const separatorStr = extractValue(parsed["separator"]);
1879
+ if (separatorStr !== undefined)
1880
+ attributes["date_separator"] = separatorStr;
1881
+ attributes["original_format"] = separatorStr !== undefined || monthStr !== undefined ? "long" : "short";
1882
+ const aieeBuilt = new AieeClass(attributes);
1883
+ if (attributes["__code_obj"] instanceof IeeeCode) {
1884
+ aieeBuilt["__code_obj"] = attributes["__code_obj"];
1885
+ }
1886
+ return aieeBuilt;
1887
+ }
1888
+ buildIre(parsed) {
1889
+ const attributes = {};
1890
+ attributes["publisher"] = extractValue(parsed["publisher"]);
1891
+ attributes["type"] = extractValue(parsed["type"]);
1892
+ const numberStr = extractValue(parsed["number"]);
1893
+ if (numberStr !== undefined) {
1894
+ const codeObj = IeeeCode.parse(numberStr);
1895
+ if (codeObj !== undefined) {
1896
+ attributes["number"] = codeObj.number;
1897
+ if (codeObj.prefix !== undefined)
1898
+ attributes["prefix"] = codeObj.prefix;
1899
+ if (codeObj.parts.length > 0)
1900
+ attributes["parts"] = codeObj.parts;
1901
+ if (codeObj.originalSeparator !== undefined)
1902
+ attributes["separator"] = codeObj.originalSeparator;
1903
+ }
1904
+ }
1905
+ const yearStr = extractValue(parsed["year"]);
1906
+ if (yearStr !== undefined) {
1907
+ const yearInt = Number.parseInt(yearStr, 10);
1908
+ attributes["year"] = String(yearInt >= 12 && yearInt <= 63 ? yearInt + 1900 : yearInt);
1909
+ }
1910
+ const fullYearStr = extractValue(parsed["full_year"]);
1911
+ if (fullYearStr !== undefined)
1912
+ attributes["year"] = String(Number.parseInt(fullYearStr, 10));
1913
+ return new IreClass(attributes);
1914
+ }
1915
+ buildNesc(parsedHash) {
1916
+ // Ruby falls through the variant case on a non-matching value (the
1917
+ // nested name_first variant captures as a hash) and reaches Standard
1918
+ // via the code check; Edition is only the no-code fallback.
1919
+ let klass = NescEditionClass;
1920
+ if (parsedHash["preprint"] !== undefined) {
1921
+ // Preprint is a draft STAGE of the C2 code — checked before the
1922
+ // Standard route: the c2-preprint tree carries :code "C2" too.
1923
+ klass = NescPreprintClass;
1924
+ }
1925
+ else if (parsedHash["draft"] !== undefined) {
1926
+ klass = NescDraftClass;
1927
+ }
1928
+ else if (typeof parsedHash["variant"] === "string") {
1929
+ const variant = parsedHash["variant"];
1930
+ if (variant === "Handbook")
1931
+ klass = NescHandbookClass;
1932
+ else if (variant === "Redline")
1933
+ klass = NescRedlineClass;
1934
+ }
1935
+ if (klass === NescEditionClass && parsedHash["code"] !== undefined) {
1936
+ klass = NescStandardClass;
1937
+ }
1938
+ const attrs = { code: parsedHash["code"] ?? "C2" };
1939
+ const codeObj = IeeeCode.parse(String(attrs["code"]));
1940
+ if (codeObj !== undefined) {
1941
+ attrs["number"] = codeObj.number;
1942
+ if (codeObj.prefix !== undefined)
1943
+ attrs["prefix"] = codeObj.prefix;
1944
+ if (codeObj.parts.length > 0)
1945
+ attrs["parts"] = codeObj.parts;
1946
+ }
1947
+ if (parsedHash["year"] !== undefined)
1948
+ attrs["year"] = String(parsedHash["year"]);
1949
+ if (parsedHash["variant"] !== undefined)
1950
+ attrs["variant"] = String(parsedHash["variant"]);
1951
+ if (parsedHash["edition"] !== undefined)
1952
+ attrs["edition"] = String(parsedHash["edition"]);
1953
+ if (parsedHash["month"] !== undefined)
1954
+ attrs["month"] = String(parsedHash["month"]);
1955
+ if (parsedHash["name_registered"] !== undefined || parsedHash["abbr_registered"] !== undefined) {
1956
+ attrs["registered"] = true;
1957
+ }
1958
+ if (parsedHash["paren_abbr"] !== undefined) {
1959
+ attrs["abbr_suffix"] = true;
1960
+ if (parsedHash["paren_registered"] !== undefined)
1961
+ attrs["abbr_suffix_registered"] = true;
1962
+ }
1963
+ return new klass(attrs);
1964
+ }
1965
+ }
1966
+ function copublishedStructured(copublishedNumber) {
1967
+ if (copublishedNumber === undefined || copublishedNumber === "")
1968
+ return {};
1969
+ const attrs = {};
1970
+ let remainder = copublishedNumber;
1971
+ let year;
1972
+ let yearSep;
1973
+ const yearMatch = /([-:])((?:19|20)\d\d)$/.exec(copublishedNumber);
1974
+ if (yearMatch !== null) {
1975
+ yearSep = yearMatch[1];
1976
+ year = yearMatch[2];
1977
+ remainder = copublishedNumber.slice(0, copublishedNumber.length - yearSep.length - year.length);
1978
+ }
1979
+ const all = remainder.match(/^[^.\-]+|[.\-][^.\-]+/g) ?? [];
1980
+ const parts = [];
1981
+ const separators = [];
1982
+ for (const token of all.slice(1)) {
1983
+ parts.push(token.slice(1));
1984
+ separators.push(token[0] ?? "");
1985
+ }
1986
+ attrs["number"] = all[0];
1987
+ if (parts.length > 0) {
1988
+ attrs["parts"] = parts;
1989
+ attrs["separators"] = separators;
1990
+ }
1991
+ if (year !== undefined) {
1992
+ attrs["year"] = year;
1993
+ if (yearSep !== "-")
1994
+ attrs["year_sep"] = yearSep;
1995
+ }
1996
+ return attrs;
1997
+ }
1998
+ export function makeIeeeParseEngine(deps) {
1999
+ return {
2000
+ parseSource(input) {
2001
+ try {
2002
+ // The edition-2 artifact's bindings block produces the
2003
+ // builder-ready hash at the engine (typed scalars + raw
2004
+ // wrappers) — the same bound tree the reference's
2005
+ // Pubid::Parg::Model.bound hands its builder.
2006
+ const bound = deps.parseAndBind(input);
2007
+ // A rejected input binds to null (the parseShape contract
2008
+ // threw) — keep the throw so the reference's ParseFailed-keyed
2009
+ // fallbacks fire.
2010
+ if (bound === null || bound === undefined)
2011
+ throw new ParseFailed("no match", 0);
2012
+ return artifactToBuilderTree(bound);
2013
+ }
2014
+ catch (e) {
2015
+ // The engine throws its own error class; the reference's
2016
+ // fallback logic keys on Parslet::ParseFailed, so normalize
2017
+ // (the messageless wasm throws included).
2018
+ throw new ParseFailed(e instanceof Error && e.message !== "" ? e.message : String(e), 0);
2019
+ }
2020
+ },
2021
+ coPublished: deps.coPublished,
2022
+ };
2023
+ }
2024
+ function ieeeParseSingle(env, input) {
2025
+ const normalized = applyUpdateCodes(input);
2026
+ // UpdateCodes may introduce the "; " double-label separator (the
2027
+ // ISO/IEC and IEEE labels of one document), but the dispatch ran on
2028
+ // the raw input - re-dispatch so the dual construction sees it.
2029
+ if (normalized !== input && normalized.includes("; ")) {
2030
+ const re = preParse(normalized);
2031
+ if (re.dispatch === "dual_semicolon")
2032
+ return buildDual(env, re.parts);
2033
+ }
2034
+ const cleaned = preprocessIeee(normalized);
2035
+ const tree = env.parseSource(cleaned);
2036
+ const builder = new IeeeBuilder(env);
2037
+ builder.originalInput = input;
2038
+ return builder.build(tree);
2039
+ }
2040
+ // The aiee_simple fallback parses WITHOUT the legacy update-codes table -
2041
+ // the Ruby reference routes "AIEE …" to the AIEE sub-parser only, so an
2042
+ // update-codes rewrite (e.g. "AIEE Nos 72 and 73 - 1932") must not make
2043
+ // a line parse that the reference rejects.
2044
+ function ieeeParseSingleNoCodes(env, input) {
2045
+ const tree = env.parseSource(preprocessIeee(input));
2046
+ const builder = new IeeeBuilder(env);
2047
+ builder.originalInput = input;
2048
+ return builder.build(tree);
2049
+ }
2050
+ // The aiee_simple fallback parses WITHOUT the legacy update-codes table -
2051
+ // the Ruby reference routes "AIEE …" to the AIEE sub-parser only, so an
2052
+ // update-codes rewrite (e.g. "AIEE Nos 72 and 73 - 1932") must not make
2053
+ // a line parse that the reference rejects.
2054
+ function parseAieeDirect(env, input) {
2055
+ const builder = new IeeeBuilder(env);
2056
+ builder.originalInput = input;
2057
+ const tree = parseGrammar({ rules: ieeeGrammar.rules, root: "aiee_identifier" }, input);
2058
+ return builder.buildAiee(asHash(tree));
2059
+ }
2060
+ function normalizeIecAdoption(part) {
2061
+ return part
2062
+ .replace(/\s+Edition\s+([0-9.]+)\s+([0-9-]+)/, ":$2 ED$1")
2063
+ .replace(/\s+Edition\s+([0-9.]+)\s*$/, " ED$1");
2064
+ }
2065
+ function buildDual(env, parts) {
2066
+ const first = ieeeParseSingle(env, parts[0]);
2067
+ const second = ieeeParseSingle(env, parts[1]);
2068
+ return new DualPublishedClass({
2069
+ first_identifier: first,
2070
+ second_identifier: second,
2071
+ });
2072
+ }
2073
+ function buildReaffirmed(env, input, reaffirmed) {
2074
+ const parsed = ieeeParseSingle(env, input);
2075
+ parsed["reaffirmed"] = reaffirmed;
2076
+ return parsed;
2077
+ }
2078
+ function buildDualWithReaffirmed(env, parts, reaffirmed) {
2079
+ const ieeeId = ieeeParseSingle(env, parts[0]);
2080
+ ieeeId["reaffirmed"] = reaffirmed;
2081
+ const ireId = ieeeParseSingle(env, parts[1]);
2082
+ return new DualPublishedClass({
2083
+ first_identifier: ieeeId,
2084
+ second_identifier: ireId,
2085
+ });
2086
+ }
2087
+ function parseAdoptedPart(env, part) {
2088
+ if (part.startsWith("IEC")) {
2089
+ const impl = env.coPublished("iec");
2090
+ if (impl === undefined)
2091
+ throw new ParseFailed("IEC implementation unavailable", 0);
2092
+ return impl.parse(normalizeIecAdoption(part));
2093
+ }
2094
+ if (part.startsWith("ANSI")) {
2095
+ const impl = env.coPublished("ansi");
2096
+ if (impl === undefined)
2097
+ throw new ParseFailed("ANSI implementation unavailable", 0);
2098
+ return impl.parse(part);
2099
+ }
2100
+ return ieeeParseSingle(env, part);
2101
+ }
2102
+ function buildAdopted(env, parts) {
2103
+ const ieeeId = ieeeParseSingle(env, parts[0]);
2104
+ const adoptedParts = parts[1].split(",").map((p) => p.trim());
2105
+ const adoptedIds = adoptedParts.map((part) => parseAdoptedPart(env, part));
2106
+ const AdoptedClass = AdoptedStandardClass;
2107
+ return new AdoptedClass({
2108
+ ieee_identifier: ieeeId,
2109
+ adopted_identifiers: adoptedIds,
2110
+ });
2111
+ }
2112
+ // A sentinel for "the reference rejects this line outright" - distinct from
2113
+ // ParseFailed so ieeeParse's blanket retry (load-bearing for other forms)
2114
+ // does not resurrect it.
2115
+ class RejectedOutright extends Error {
2116
+ }
2117
+ export function ieeeParseImpl(env, input) {
2118
+ try {
2119
+ return ieeeParseDispatched(env, input);
2120
+ }
2121
+ catch (e) {
2122
+ if (e instanceof ParseFailed && !(e instanceof RejectedOutright))
2123
+ return ieeeParseSingle(env, input);
2124
+ if (e instanceof RejectedOutright)
2125
+ throw new ParseFailed(e.message, 0);
2126
+ throw e;
2127
+ }
2128
+ }
2129
+ function ieeeParseDispatched(env, input) {
2130
+ const result = preParse(input);
2131
+ switch (result.dispatch) {
2132
+ case "aiee_simple":
2133
+ // Ruby: Aiee::Identifier.parse, with the WHOLE parse falling back to
2134
+ // parse_single on ParseFailed (forms the AIEE sub-grammar rejects,
2135
+ // e.g. "AIEE 15-May 1928", parse through the generic bucket).
2136
+ try {
2137
+ return parseAieeDirect(env, result.input);
2138
+ }
2139
+ catch {
2140
+ // Ruby: Aiee::Identifier.parse with no retry - an update-codes
2141
+ // rewrite must not make an AIEE-form line parse that the
2142
+ // reference rejects ("AIEE Nos 72 and 73 - 1932").
2143
+ try {
2144
+ return ieeeParseSingleNoCodes(env, input);
2145
+ }
2146
+ catch {
2147
+ throw new RejectedOutright(input);
2148
+ }
2149
+ }
2150
+ case "iec_ieee_copublished":
2151
+ case "dual_semicolon":
2152
+ case "dual_space_separated":
2153
+ if (result.dispatch === "dual_semicolon" || result.dispatch === "dual_space_separated") {
2154
+ return buildDual(env, result.parts);
2155
+ }
2156
+ try {
2157
+ return ieeeParseSingle(env, result.input);
2158
+ }
2159
+ catch {
2160
+ return ieeeParseSingle(env, input);
2161
+ }
2162
+ case "dual_reaffirmed":
2163
+ return buildReaffirmed(env, result.input, result.metadata["reaffirmed"] ?? "");
2164
+ case "dual_ire":
2165
+ return buildDualWithReaffirmed(env, result.parts, result.metadata["reaffirmed"] ?? "");
2166
+ case "dual_and":
2167
+ case "dual_ampersand":
2168
+ return buildDual(env, result.parts);
2169
+ case "aiee_asa_adoption": {
2170
+ const aieeId = ieeeParseSingle(env, result.parts[0]);
2171
+ const asaId = ieeeParseSingle(env, result.parts[1]);
2172
+ const AdoptedClass = AdoptedStandardClass;
2173
+ return new AdoptedClass({
2174
+ ieee_identifier: aieeId,
2175
+ adopted_identifiers: [asaId],
2176
+ });
2177
+ }
2178
+ case "adopted":
2179
+ return buildAdopted(env, result.parts);
2180
+ default:
2181
+ try {
2182
+ return ieeeParseSingle(env, result.input);
2183
+ }
2184
+ catch {
2185
+ return ieeeParseSingle(env, input);
2186
+ }
2187
+ }
2188
+ }
2189
+ export function makeIeeeGrammarImplementation(env) {
2190
+ return {
2191
+ parse(input) {
2192
+ return ieeeParseImpl(env, input);
2193
+ },
2194
+ };
2195
+ }