@pubid/pubid 0.1.66 → 0.1.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,122 @@
1
+ import type { FlavorImplementation } from "../../conformance/implementation.js";
2
+ import { BaseIdentifier } from "../../model/identifier.js";
3
+ import type { IdentifierStatic } from "../../model/identifier.js";
4
+ import { type FieldMapping } from "../../model/attribute.js";
5
+ import { PubidDate, Publisher } from "../../model/component.js";
6
+ import { BaseUrnGenerator } from "../../model/urn-generator.js";
7
+ import { type BsiTypedStage } from "../bsi/model.js";
8
+ /**
9
+ * The compiled flavor's identifier base: the shared render machinery and
10
+ * the FLAVOR-LOCAL type dispatch. The concrete classes carry the
11
+ * scheme's canonical wire tags (pubid:bsi:…), which deliberately stay
12
+ * OUT of the global type map — one scheme, one `_type`, one global
13
+ * resolution (the coded class); {@linkcode fromHash} routes the tags
14
+ * back here flavor-locally first (mirroring Ruby's flavor-base
15
+ * polymorphic_type_map order), then falls through to the global registry
16
+ * for the cross-flavor nested identifiers (the adopted CEN/ISO/IEC
17
+ * document), exactly the TypeResolver order.
18
+ */
19
+ export declare abstract class BsiPfsIdentifier extends BaseIdentifier {
20
+ /** The wire tags the compiled classes answer, resolved flavor-locally. */
21
+ static localTypeMap: Map<string, new (attrs?: Record<string, unknown>) => BsiPfsIdentifier>;
22
+ readonly publisher: Publisher | undefined;
23
+ readonly number: string | undefined;
24
+ readonly part: string | undefined;
25
+ readonly date: PubidDate | undefined;
26
+ readonly edition: string | undefined;
27
+ readonly type: string | undefined;
28
+ readonly typedStage: BsiTypedStage | undefined;
29
+ readonly base: BaseIdentifier | undefined;
30
+ /** The alias's own from_hash: the scheme tags route HERE, the
31
+ * cross-flavor tags (a nested adopted document) fall through to the
32
+ * global registry, while nothing reaches the coded classes by way of
33
+ * the compiled alias (coexistence, not cutover). */
34
+ static fromHash(hash: Record<string, unknown>): BaseIdentifier;
35
+ /** The root-through walk the official URN and the identity reads use:
36
+ * the adoption wrapper carries no identity of its own, so its
37
+ * identity attributes read the ROOT document's. */
38
+ root(): BsiPfsIdentifier;
39
+ /** An identity attribute of this identifier, or of the document it
40
+ * wraps (the declared root-through): #root is +self+ for a
41
+ * non-wrapper, so an ordinary identifier reads its own value and
42
+ * nothing changes. */
43
+ identity(attr: string): unknown;
44
+ /** The definition's canonical face: `<publisher> <adopted>[ ED<n>]` or
45
+ * `<publisher> <number>[-<part>][:<year>]`, then the supplement run
46
+ * (the standalone slash chain / the consolidated plus run) — every
47
+ * optional renders only what the input carried, and a designation
48
+ * token prints where the face names the publisher. */
49
+ render(): string;
50
+ }
51
+ /**
52
+ * The official URN: urn:bsi[:<publisher>][:<number>][:‑<part>][:-<subpart>]
53
+ * [:<year>][:v<edition>][:<type abbr unless BS>][:stage.<code>]. A
54
+ * wrapper reads through to its subject for the identity columns (the
55
+ * publisher and the edition stay the wrapper's own), a supplement
56
+ * wrapper prepends its declared chain (:amd:/:cor:), and the
57
+ * marker-less bundle appends each member's chain directly (the
58
+ * coded-BSI shape).
59
+ */
60
+ declare class BsiPfsUrnGenerator extends BaseUrnGenerator<BsiPfsIdentifier> {
61
+ generate(): string;
62
+ }
63
+ /** The default class (the token-free face) and the four designation
64
+ * tokens' classes (feature 1): the token selects the class, the
65
+ * designation IS the publisher, and the class default publisher is BS
66
+ * for every family. */
67
+ export declare const BsiPfsBritishStandard: (new (attrs?: Record<string, unknown>) => BsiPfsIdentifier) & IdentifierStatic;
68
+ export declare const BsiPfsPubliclyAvailableSpecification: (new (attrs?: Record<string, unknown>) => BsiPfsIdentifier) & IdentifierStatic;
69
+ export declare const BsiPfsPublishedDocument: (new (attrs?: Record<string, unknown>) => BsiPfsIdentifier) & IdentifierStatic;
70
+ export declare const BsiPfsDraftDocument: (new (attrs?: Record<string, unknown>) => BsiPfsIdentifier) & IdentifierStatic;
71
+ export declare const BsiPfsTechnicalSpecification: (new (attrs?: Record<string, unknown>) => BsiPfsIdentifier) & IdentifierStatic;
72
+ export declare const BsiPfsAdoptedEuropeanNorm: (new (attrs?: Record<string, unknown>) => BsiPfsIdentifier) & IdentifierStatic;
73
+ export declare const BsiPfsAdoptedInternationalStandard: (new (attrs?: Record<string, unknown>) => BsiPfsIdentifier) & IdentifierStatic;
74
+ /** The supplement wrapper base: the wrapper owns its ordinal and the
75
+ * base identifier; every rendered face reads through. */
76
+ declare abstract class BsiPfsSupplement extends BsiPfsIdentifier {
77
+ static get attributes(): import("../../model/attribute.js").AttributeTable;
78
+ static get mappings(): FieldMapping[];
79
+ static urnGenerator: typeof BsiPfsUrnGenerator;
80
+ readonly base: BsiPfsIdentifier | undefined;
81
+ readonly year: string | undefined;
82
+ /** The printed notation: the kind face, the ordinal (absent for an
83
+ * unnumbered corrigendum) and the declared date tail. The bare
84
+ * notation; the render's walkers add the standalone slash and the
85
+ * consolidated plus themselves. */
86
+ supplementNotation(): string;
87
+ }
88
+ export declare class BsiPfsAmendment extends BsiPfsSupplement {
89
+ /** The kind face "A" is the run's dispatch token and the notation
90
+ * face. */
91
+ static get polymorphicName(): string;
92
+ static FACE: string;
93
+ }
94
+ export declare class BsiPfsCorrigendum extends BsiPfsSupplement {
95
+ /** The kind face "C" is the run's dispatch token and the notation
96
+ * face. */
97
+ static get polymorphicName(): string;
98
+ static FACE: string;
99
+ }
100
+ /** The consolidated (plus-run) bundle: the base document is the first
101
+ * member; each member amends it, so the members carry it as their base
102
+ * (the coded builder's shape). The wrapper reads the base document's
103
+ * identity and drops the member suffixes. */
104
+ export declare class BsiPfsConsolidatedIdentifier extends BsiPfsIdentifier {
105
+ static get polymorphicName(): string;
106
+ static get attributes(): import("../../model/attribute.js").AttributeTable;
107
+ static get mappings(): FieldMapping[];
108
+ /** The declared marker-less bundle (the coded-BSI compact-hash rule):
109
+ * the delegated publisher leaves the wrapper's own wire entry, and
110
+ * the wrapper reads the base document's designation — the first
111
+ * member's typed trio supplies the bundle-level type block (the
112
+ * stage/typed_stage blocks stay the members'). */
113
+ static compactHash: (model: BaseIdentifier, hash: Record<string, unknown>) => void;
114
+ static urnGenerator: typeof BsiPfsUrnGenerator;
115
+ readonly identifiers: BsiPfsIdentifier[];
116
+ /** The origin document: members live in `identifiers`, so the walk
117
+ * starts at the first member. */
118
+ root(): BsiPfsIdentifier;
119
+ }
120
+ export declare function buildBsiPfsIdentifier(flat: Record<string, unknown>): BsiPfsIdentifier;
121
+ export declare function bsiPfsGrammarImplementation(): FlavorImplementation;
122
+ export {};
@@ -0,0 +1,697 @@
1
+ import { ParseFailed } from "../../grammar/engine.js";
2
+ import { PubidRuntime } from "../../parg/runtime.js";
3
+ import { BaseIdentifier } from "../../model/identifier.js";
4
+ import { resolveType } from "../../model/identifier.js";
5
+ import { extendAttributes, keyValue } from "../../model/attribute.js";
6
+ import { PubidDate, Publisher } from "../../model/component.js";
7
+ import { BaseUrnGenerator } from "../../model/urn-generator.js";
8
+ import { grammarImplementation } from "../index.js";
9
+ import { TYPED_STAGES_REGISTRY } from "../bsi/model.js";
10
+ /**
11
+ * The PFS-compiled bsi flavor (pubid/pubid#706 §4; the module-composition
12
+ * proof flavor, ported here per pubid-ts#227) — one definition file, both
13
+ * engines: the grammar runtime is the SAME baked artifact the Ruby flavor
14
+ * runs (pubid-grammar artifacts/bsi_pfs.json, compiled from
15
+ * definitions/bsi.pfs by the compiler with the bsi-absorption features),
16
+ * loaded through the artifact runtime, so grammar changes land once and
17
+ * this side cannot drift. The composition is the module library
18
+ * (national.prefix + en.overlay over the iso/iec inners): the plain BS
19
+ * face, the adoption wrappers with the uniform `base` slot (the adopted
20
+ * string parses with the OWNING flavor — EN/CEN/CLC/HD/ENV/ES/CR/CWA
21
+ * leads through the coded cen_cenelec implementation, ISO through iso,
22
+ * IEC/CISPR through iec; an unknown lead or a rejected run is a
23
+ * REJECTION, never a silently empty wrapper), the glued adopted edition
24
+ * face lifted before the delegation, the typed trio
25
+ * (PAS/PD/DD/TS designations: type/stage/typed_stage from the declared
26
+ * registry rows, the ":stage.published" URN segment included), and the
27
+ * marker-less consolidated bundle (each member amends THE bundle's base).
28
+ * Nothing is hand-rolled serialization: the model is declared attributes
29
+ * on the unified model, the trio rides the compactHash hook exactly as
30
+ * the coded {@linkcode import("../bsi/model.js").BsiIdentifier} emits it,
31
+ * and the render body is the definition's canonical template.
32
+ *
33
+ * THE LEDGER IS THE CONTRACT: the bsi corpus rows outside this
34
+ * composition surface (657 of 1,500 — aerospace, Flex, committee
35
+ * documents, index/method/section/test suffixes, addenda/supplements,
36
+ * national annexes, Expert commentary, bundles, sets, standalone AMD,
37
+ * value-added wrappers, DISC escalation prefix, plus four declared
38
+ * shapes) stay REJECTED with a parse failure, never a wrong class —
39
+ * fail-closed exactly as the gem's spec/pubid/bsi_pfs/parity_spec.rb
40
+ * pins them. The parity gate (test/bsi-pfs-parity.test.ts) pins
41
+ * byte-identity with the coded BSI flavor over the absorbed 843-row
42
+ * inventory and the same rejection over every unabsorbed row.
43
+ */
44
+ /** Ruby truthiness for a captured face: an absent capture is absent. */
45
+ function present(value) {
46
+ return value !== undefined && value !== null && value !== "";
47
+ }
48
+ function strOf(value) {
49
+ if (!present(value))
50
+ return undefined;
51
+ return String(value);
52
+ }
53
+ /** A raw capture leaf ({value, line, …}) yields its value; a bound scalar
54
+ * passes through (the run's internal captures bind only through the item
55
+ * row, so unbound ones arrive as raw leaves). */
56
+ function unwrap(capture) {
57
+ if (typeof capture === "object" && capture !== null && "value" in capture) {
58
+ return capture["value"];
59
+ }
60
+ return capture;
61
+ }
62
+ /** The builder's present_string: a capture the grammar bound as an
63
+ * empty string stores as nil (to_hash drops the empty string, so
64
+ * from_hash would give nil and the two identifiers would not be ==). */
65
+ function presentString(value) {
66
+ const s = strOf(value);
67
+ return s === undefined || s === "" ? undefined : s;
68
+ }
69
+ function isRecord(value) {
70
+ return typeof value === "object" && value !== null && !Array.isArray(value);
71
+ }
72
+ /** The deep terminal of the parent chain (the codec's root-first walk):
73
+ * a consolidated bundle roots at its first member, a wrapper at its
74
+ * base — and the nested coded identifiers carry their own parent
75
+ * columns (the CEN adoption wrapper holds the foreign document under
76
+ * `adopted`), so the walk follows both keys. */
77
+ function deepRoot(node, seen = 0) {
78
+ if (seen > 6 || !isRecord(node))
79
+ return node;
80
+ const members = node["identifiers"];
81
+ if (Array.isArray(members) && members.length > 0 && isRecord(members[0])) {
82
+ return deepRoot(members[0], seen + 1);
83
+ }
84
+ for (const key of ["base", "adopted"]) {
85
+ const next = node[key];
86
+ if (isRecord(next))
87
+ return deepRoot(next, seen + 1);
88
+ }
89
+ return node;
90
+ }
91
+ /**
92
+ * The compiled flavor's identifier base: the shared render machinery and
93
+ * the FLAVOR-LOCAL type dispatch. The concrete classes carry the
94
+ * scheme's canonical wire tags (pubid:bsi:…), which deliberately stay
95
+ * OUT of the global type map — one scheme, one `_type`, one global
96
+ * resolution (the coded class); {@linkcode fromHash} routes the tags
97
+ * back here flavor-locally first (mirroring Ruby's flavor-base
98
+ * polymorphic_type_map order), then falls through to the global registry
99
+ * for the cross-flavor nested identifiers (the adopted CEN/ISO/IEC
100
+ * document), exactly the TypeResolver order.
101
+ */
102
+ export class BsiPfsIdentifier extends BaseIdentifier {
103
+ /** The wire tags the compiled classes answer, resolved flavor-locally. */
104
+ static localTypeMap = new Map();
105
+ /** The alias's own from_hash: the scheme tags route HERE, the
106
+ * cross-flavor tags (a nested adopted document) fall through to the
107
+ * global registry, while nothing reaches the coded classes by way of
108
+ * the compiled alias (coexistence, not cutover). */
109
+ static fromHash(hash) {
110
+ const tag = typeof hash["_type"] === "string" ? hash["_type"] : undefined;
111
+ const klass = tag !== undefined ? this.localTypeMap.get(tag) : undefined;
112
+ if (klass === undefined && tag !== undefined) {
113
+ const global = resolveType(tag);
114
+ if (global !== undefined)
115
+ return global.fromHash(hash);
116
+ }
117
+ const target = (klass ?? this);
118
+ return new target(target.applyMappings(target.inflateScalarComponents(hash)));
119
+ }
120
+ /** The root-through walk the official URN and the identity reads use:
121
+ * the adoption wrapper carries no identity of its own, so its
122
+ * identity attributes read the ROOT document's. */
123
+ root() {
124
+ const terminal = deepRoot(this);
125
+ return isRecord(terminal) && terminal instanceof BsiPfsIdentifier
126
+ ? terminal
127
+ : this;
128
+ }
129
+ /** An identity attribute of this identifier, or of the document it
130
+ * wraps (the declared root-through): #root is +self+ for a
131
+ * non-wrapper, so an ordinary identifier reads its own value and
132
+ * nothing changes. */
133
+ identity(attr) {
134
+ const own = this[attr];
135
+ if (own !== undefined && own !== null)
136
+ return own;
137
+ const root = deepRoot(this);
138
+ return root === this ? undefined : root[attr];
139
+ }
140
+ /** The definition's canonical face: `<publisher> <adopted>[ ED<n>]` or
141
+ * `<publisher> <number>[-<part>][:<year>]`, then the supplement run
142
+ * (the standalone slash chain / the consolidated plus run) — every
143
+ * optional renders only what the input carried, and a designation
144
+ * token prints where the face names the publisher. */
145
+ render() {
146
+ let root = this;
147
+ let run = "";
148
+ let members;
149
+ if (root instanceof BsiPfsConsolidatedIdentifier) {
150
+ const [base, ...consolidated] = root.identifiers;
151
+ members = consolidated;
152
+ root = base ?? root;
153
+ }
154
+ while (root instanceof BsiPfsSupplement) {
155
+ run = `/${root.supplementNotation()}${run}`;
156
+ root = root.base ?? root;
157
+ }
158
+ if (members !== undefined) {
159
+ for (const member of members) {
160
+ run += `+${member.supplementNotation()}`;
161
+ }
162
+ }
163
+ const designation = root.type !== undefined && DESIGNATION_FACES.has(root.type);
164
+ const publisher = designation
165
+ ? root.type
166
+ : root.publisher !== undefined
167
+ ? root.publisher.body
168
+ : undefined;
169
+ const adopted = adoptedView(root);
170
+ const year = root.date?.year;
171
+ let head = "";
172
+ if (publisher !== undefined && adopted !== undefined) {
173
+ head = `${publisher} ${adopted}`;
174
+ }
175
+ else if (publisher !== undefined && present(root.number)) {
176
+ head =
177
+ `${publisher} ${root.number}` +
178
+ `${present(root.part) ? `-${root.part}` : ""}` +
179
+ `${present(year) ? `:${year}` : ""}`;
180
+ }
181
+ return head + run;
182
+ }
183
+ }
184
+ /** The adoption face: the adopted document, with the wrapper's own
185
+ * edition face after it (the declared glued ED form — the hook lifts
186
+ * the ordinal onto the wrapper). */
187
+ function adoptedView(root) {
188
+ const adopted = root["base"];
189
+ if (!(adopted instanceof BaseIdentifier))
190
+ return undefined;
191
+ const edition = root["edition"];
192
+ const adoptedStr = adopted.toString();
193
+ return present(edition) ? `${adoptedStr} ED${edition}` : adoptedStr;
194
+ }
195
+ /** The designation faces (the typed trio): the token that selected the
196
+ * class prints where the face names the publisher. */
197
+ const DESIGNATION_FACES = new Set(["PAS", "PD", "DD", "TS"]);
198
+ /** The typed trio the designation rows carry (the wire keys the coded
199
+ * flavor serializes): type {name, abbr, type_code}, stage {name,
200
+ * stage_code, harmonized_stages, abbr}, typed_stage {name, code,
201
+ * type_code, stage_code, abbr, harmonized_stages} — the same nested
202
+ * blocks the coded {@linkcode BsiIdentifier} compactHash emits. */
203
+ function emitTypedTrio(model, hash) {
204
+ const ts = model.typedStage;
205
+ if (ts === undefined)
206
+ return;
207
+ hash["type"] = { name: ts.name, abbr: ts.abbr[0], type_code: ts.typeCode };
208
+ hash["stage"] = {
209
+ name: ts.name,
210
+ stage_code: ts.stageCode,
211
+ harmonized_stages: ts.harmonizedStages,
212
+ abbr: ts.abbr[0],
213
+ };
214
+ hash["typed_stage"] = {
215
+ name: ts.name,
216
+ code: ts.code,
217
+ type_code: ts.typeCode,
218
+ stage_code: ts.stageCode,
219
+ abbr: ts.abbr,
220
+ harmonized_stages: ts.harmonizedStages,
221
+ };
222
+ }
223
+ /**
224
+ * The official URN: urn:bsi[:<publisher>][:<number>][:‑<part>][:-<subpart>]
225
+ * [:<year>][:v<edition>][:<type abbr unless BS>][:stage.<code>]. A
226
+ * wrapper reads through to its subject for the identity columns (the
227
+ * publisher and the edition stay the wrapper's own), a supplement
228
+ * wrapper prepends its declared chain (:amd:/:cor:), and the
229
+ * marker-less bundle appends each member's chain directly (the
230
+ * coded-BSI shape).
231
+ */
232
+ class BsiPfsUrnGenerator extends BaseUrnGenerator {
233
+ generate() {
234
+ let id = this.identifier;
235
+ const wrapper = [];
236
+ let members;
237
+ if (id instanceof BsiPfsConsolidatedIdentifier) {
238
+ const [base, ...consolidated] = id.identifiers;
239
+ members = consolidated;
240
+ id = base ?? id;
241
+ }
242
+ while (id instanceof BsiPfsSupplement) {
243
+ wrapper.unshift(...wrapperSegments(id));
244
+ id = id.base ?? id;
245
+ }
246
+ const parts = ["urn", "bsi", ...officialSegments(id), ...wrapper];
247
+ if (members !== undefined) {
248
+ for (const member of members) {
249
+ parts.push(...wrapperSegments(member));
250
+ }
251
+ }
252
+ return parts.join(":");
253
+ }
254
+ }
255
+ /** The fused official segments: the wrapper's own publisher, the
256
+ * root-through identity columns, the wrapper's own glued edition face,
257
+ * the designation type abbr (the BS token never fires), and the typed
258
+ * trio's own stage segment (it fires for published rows too — the
259
+ * coded generator's own comparison: a stage_code String is never the
260
+ * :published Symbol, so a set typed stage always segments). */
261
+ function officialSegments(id) {
262
+ const segments = [];
263
+ if (id.publisher !== undefined)
264
+ segments.push(id.publisher.render("urn"));
265
+ const number = id.identity("number");
266
+ if (present(number))
267
+ segments.push(String(number));
268
+ const part = id.identity("part");
269
+ if (present(part))
270
+ segments.push(`-${part}`);
271
+ const subpart = id.identity("subpart");
272
+ if (present(subpart))
273
+ segments.push(`-${subpart}`);
274
+ const year = id.identity("date")?.year;
275
+ if (present(year))
276
+ segments.push(String(year));
277
+ if (present(id.edition))
278
+ segments.push(`v${id.edition}`);
279
+ if (id.type !== undefined && id.type !== "BS") {
280
+ segments.push(id.type.toLowerCase());
281
+ }
282
+ const code = id.typedStage?.stageCode;
283
+ if (code !== undefined)
284
+ segments.push(`stage.${code}`);
285
+ return segments;
286
+ }
287
+ /** One wrapper's declared URN chain: the kind word, then the wrapper's
288
+ * columns (the ordinal, the year). */
289
+ function wrapperSegments(id) {
290
+ let segments;
291
+ if (id instanceof BsiPfsAmendment) {
292
+ segments = ["amd", id.number, id.year];
293
+ }
294
+ else if (id instanceof BsiPfsCorrigendum) {
295
+ segments = ["cor", id.number, id.year];
296
+ }
297
+ else {
298
+ segments = [];
299
+ }
300
+ return segments.map((s) => String(s ?? "")).filter((s) => s !== "");
301
+ }
302
+ /** A declared document family: the columns the compiled builder casts,
303
+ * the class defaults, and the whitelist that keeps the wire flat (the
304
+ * `type`/`typedStage` slots never serialize raw — the trio rides the
305
+ * compactHash hook, exactly the coded flavor's wire). */
306
+ function documentClass(spec) {
307
+ class BsiPfsDocument extends BsiPfsIdentifier {
308
+ static get polymorphicName() {
309
+ return spec.tag;
310
+ }
311
+ static get attributes() {
312
+ return extendAttributes(BaseIdentifier, {
313
+ publisher: { type: Publisher, default: new Publisher({ body: "BS" }) },
314
+ number: { type: "string" },
315
+ part: { type: "string" },
316
+ date: { type: PubidDate },
317
+ ...(spec.adopted
318
+ ? {
319
+ edition: { type: "string" },
320
+ // The nested foreign document: a complete cross-flavor
321
+ // instance passes through untouched; a wire hash rebuilds
322
+ // through the alias's TypeResolver order (flavor map,
323
+ // then the global registry).
324
+ base: { type: BsiPfsIdentifier },
325
+ }
326
+ : {}),
327
+ type: { type: "string" },
328
+ typedStage: { type: "string" },
329
+ });
330
+ }
331
+ static get mappings() {
332
+ return keyValue({ wire: "publisher", to: "publisher" }, { wire: "number", to: "number" }, { wire: "part", to: "part" }, { wire: "date", to: "date" }, ...(spec.adopted
333
+ ? [
334
+ { wire: "edition", to: "edition" },
335
+ { wire: "base", to: "base" },
336
+ ]
337
+ : []), {
338
+ // The typed trio's wire keys ride compactHash (the coded
339
+ // flavor's hook); from the wire they rebuild the registry row.
340
+ wire: "typed_stage",
341
+ to: "typedStage",
342
+ fromWire: (h) => {
343
+ const trio = h["typed_stage"];
344
+ if (trio === undefined || trio === null || typeof trio !== "object")
345
+ return undefined;
346
+ const code = trio["code"];
347
+ return TYPED_STAGES_REGISTRY.find((t) => t.code === code);
348
+ },
349
+ toWire: () => undefined,
350
+ }, {
351
+ wire: "type",
352
+ to: "type",
353
+ fromWire: (h) => {
354
+ const trio = h["type"];
355
+ if (trio === undefined || trio === null || typeof trio !== "object")
356
+ return undefined;
357
+ const typeCode = trio["type_code"];
358
+ return TYPED_STAGES_REGISTRY.find((t) => t.typeCode === typeCode)?.abbr[0];
359
+ },
360
+ toWire: () => undefined,
361
+ });
362
+ }
363
+ static compactHash = (model, hash) => {
364
+ emitTypedTrio(model, hash);
365
+ };
366
+ static urnGenerator = BsiPfsUrnGenerator;
367
+ constructor(attrs = {}) {
368
+ super(attrs);
369
+ const self = this;
370
+ if (self["publisher"] === undefined)
371
+ self["publisher"] = new Publisher({ body: "BS" });
372
+ }
373
+ }
374
+ return BsiPfsDocument;
375
+ }
376
+ /** The default class (the token-free face) and the four designation
377
+ * tokens' classes (feature 1): the token selects the class, the
378
+ * designation IS the publisher, and the class default publisher is BS
379
+ * for every family. */
380
+ export const BsiPfsBritishStandard = documentClass({ tag: "pubid:bsi:british-standard" });
381
+ export const BsiPfsPubliclyAvailableSpecification = documentClass({
382
+ tag: "pubid:bsi:publicly-available-specification",
383
+ });
384
+ export const BsiPfsPublishedDocument = documentClass({ tag: "pubid:bsi:published-document" });
385
+ export const BsiPfsDraftDocument = documentClass({ tag: "pubid:bsi:draft-document" });
386
+ export const BsiPfsTechnicalSpecification = documentClass({ tag: "pubid:bsi:technical-specification" });
387
+ export const BsiPfsAdoptedEuropeanNorm = documentClass({
388
+ tag: "pubid:bsi:adopted-european-norm",
389
+ adopted: true,
390
+ });
391
+ export const BsiPfsAdoptedInternationalStandard = documentClass({
392
+ tag: "pubid:bsi:adopted-international-standard",
393
+ adopted: true,
394
+ });
395
+ /** The supplement wrapper base: the wrapper owns its ordinal and the
396
+ * base identifier; every rendered face reads through. */
397
+ class BsiPfsSupplement extends BsiPfsIdentifier {
398
+ static get attributes() {
399
+ return extendAttributes(BaseIdentifier, {
400
+ base: { type: BsiPfsIdentifier },
401
+ number: { type: "string" },
402
+ year: { type: "string" },
403
+ });
404
+ }
405
+ static get mappings() {
406
+ return keyValue({ wire: "base", to: "base" }, { wire: "number", to: "number" }, { wire: "year", to: "year" });
407
+ }
408
+ static urnGenerator = BsiPfsUrnGenerator;
409
+ /** The printed notation: the kind face, the ordinal (absent for an
410
+ * unnumbered corrigendum) and the declared date tail. The bare
411
+ * notation; the render's walkers add the standalone slash and the
412
+ * consolidated plus themselves. */
413
+ supplementNotation() {
414
+ return (this.constructor.FACE +
415
+ (this.number ?? "") +
416
+ (present(this.year) ? `:${this.year}` : ""));
417
+ }
418
+ }
419
+ export class BsiPfsAmendment extends BsiPfsSupplement {
420
+ /** The kind face "A" is the run's dispatch token and the notation
421
+ * face. */
422
+ static get polymorphicName() {
423
+ return "pubid:bsi:amendment";
424
+ }
425
+ static FACE = "A";
426
+ }
427
+ export class BsiPfsCorrigendum extends BsiPfsSupplement {
428
+ /** The kind face "C" is the run's dispatch token and the notation
429
+ * face. */
430
+ static get polymorphicName() {
431
+ return "pubid:bsi:corrigendum";
432
+ }
433
+ static FACE = "C";
434
+ }
435
+ /** The consolidated (plus-run) bundle: the base document is the first
436
+ * member; each member amends it, so the members carry it as their base
437
+ * (the coded builder's shape). The wrapper reads the base document's
438
+ * identity and drops the member suffixes. */
439
+ export class BsiPfsConsolidatedIdentifier extends BsiPfsIdentifier {
440
+ static get polymorphicName() {
441
+ return "pubid:bsi:consolidated-identifier";
442
+ }
443
+ static get attributes() {
444
+ return extendAttributes(BaseIdentifier, {
445
+ identifiers: {
446
+ type: BsiPfsIdentifier,
447
+ collection: true,
448
+ },
449
+ });
450
+ }
451
+ static get mappings() {
452
+ return keyValue({ wire: "identifiers", to: "identifiers" });
453
+ }
454
+ /** The declared marker-less bundle (the coded-BSI compact-hash rule):
455
+ * the delegated publisher leaves the wrapper's own wire entry, and
456
+ * the wrapper reads the base document's designation — the first
457
+ * member's typed trio supplies the bundle-level type block (the
458
+ * stage/typed_stage blocks stay the members'). */
459
+ static compactHash = (model, hash) => {
460
+ delete hash["publisher"];
461
+ const first = model.identifiers?.[0];
462
+ const ts = first?.typedStage;
463
+ if (ts !== undefined) {
464
+ hash["type"] = { name: ts.name, abbr: ts.abbr[0], type_code: ts.typeCode };
465
+ }
466
+ };
467
+ static urnGenerator = BsiPfsUrnGenerator;
468
+ /** The origin document: members live in `identifiers`, so the walk
469
+ * starts at the first member. */
470
+ root() {
471
+ const first = this.identifiers[0];
472
+ return first !== undefined ? first.root() : this;
473
+ }
474
+ }
475
+ for (const klass of [
476
+ BsiPfsBritishStandard,
477
+ BsiPfsPubliclyAvailableSpecification,
478
+ BsiPfsPublishedDocument,
479
+ BsiPfsDraftDocument,
480
+ BsiPfsTechnicalSpecification,
481
+ BsiPfsAdoptedEuropeanNorm,
482
+ BsiPfsAdoptedInternationalStandard,
483
+ BsiPfsAmendment,
484
+ BsiPfsCorrigendum,
485
+ BsiPfsConsolidatedIdentifier,
486
+ ]) {
487
+ BsiPfsIdentifier.localTypeMap.set(klass.polymorphicName, klass);
488
+ }
489
+ // --- the builder (the generated builder's shape) -------------------------------
490
+ /** The designation registry rows by their token (the builder's
491
+ * DESIGNATION_STAGES): the token that selected the class is the
492
+ * designation face, not a publisher — the identifier carries the
493
+ * stage entry's type/typed stage (the coded builder's cast). */
494
+ const DESIGNATION_STAGES = new Map([
495
+ ["PAS", "pas"],
496
+ ["PD", "pd"],
497
+ ["DD", "dd"],
498
+ ["TS", "ts"],
499
+ ]
500
+ .map(([token, typeCode]) => [token, TYPED_STAGES_REGISTRY.find((t) => t.typeCode === typeCode)])
501
+ .filter(([, row]) => row !== undefined));
502
+ /** The type each declared token selects (feature 1); the token-free
503
+ * type is the default class. */
504
+ const TYPE_TOKENS = {
505
+ PAS: BsiPfsPubliclyAvailableSpecification,
506
+ PD: BsiPfsPublishedDocument,
507
+ DD: BsiPfsDraftDocument,
508
+ TS: BsiPfsTechnicalSpecification,
509
+ };
510
+ /** The columns, as the compiled builder's cast writes them: the date
511
+ * carries the captured year, a designation token selects the class and
512
+ * carries the trio row but is not a publisher. */
513
+ function assignAttributes(flat) {
514
+ const attrs = {};
515
+ const year = strOf(unwrap(flat["year"]));
516
+ if (year !== undefined)
517
+ attrs["date"] = new PubidDate({ year });
518
+ const number = strOf(unwrap(flat["number"]));
519
+ if (number !== undefined)
520
+ attrs["number"] = number;
521
+ const part = strOf(unwrap(flat["part"]));
522
+ if (part !== undefined)
523
+ attrs["part"] = part;
524
+ const publisher = strOf(unwrap(flat["publisher"]));
525
+ if (publisher !== undefined && !DESIGNATION_STAGES.has(publisher)) {
526
+ attrs["publisher"] = new Publisher({ body: publisher });
527
+ }
528
+ const row = publisher !== undefined ? DESIGNATION_STAGES.get(publisher) : undefined;
529
+ if (row !== undefined) {
530
+ attrs["typedStage"] = row;
531
+ attrs["type"] = row.abbr[0];
532
+ }
533
+ return attrs;
534
+ }
535
+ /** The class each reference selects: the publisher-position token (the
536
+ * designation faces), else the token-free default class. The bsi
537
+ * grammar declares no guide/type position, so the token scan is the
538
+ * publisher column only. */
539
+ function locateIdentifierKlass(flat) {
540
+ const publisher = strOf(unwrap(flat["publisher"]));
541
+ const selected = publisher !== undefined ? TYPE_TOKENS[publisher] : undefined;
542
+ return selected ?? BsiPfsBritishStandard;
543
+ }
544
+ /** The en.overlay routing: the lead token names the owning flavor — EN,
545
+ * CEN, CLC, HD, ENV, ES, CR and CWA leads through the coded cen_cenelec
546
+ * implementation (the cen inner), ISO through iso (iso.inner), IEC and
547
+ * CISPR through iec (iec.inner). An unknown lead is a rejection citing
548
+ * the run; a run the owning flavor rejects propagates THAT flavor's
549
+ * parse failure (the honest attribution). */
550
+ function parseAdopted(adoptedStr) {
551
+ const lead = adoptedStr.split(/\s|\//, 2)[0] ?? "";
552
+ const flavor = CEN_LEADS.has(lead)
553
+ ? "cen_cenelec"
554
+ : lead === "ISO"
555
+ ? "iso"
556
+ : IEC_LEADS.has(lead)
557
+ ? "iec"
558
+ : undefined;
559
+ if (flavor === undefined) {
560
+ throw new ParseFailed(`bsi_pfs: no owning flavor parses the run ${JSON.stringify(adoptedStr)}`, 0);
561
+ }
562
+ const impl = grammarImplementation(flavor);
563
+ if (impl === undefined) {
564
+ throw new ParseFailed(`bsi_pfs: the ${flavor} implementation is unavailable`, 0);
565
+ }
566
+ return impl.parse(adoptedStr);
567
+ }
568
+ const CEN_LEADS = new Set(["EN", "CEN", "CLC", "HD", "ENV", "ES", "CR", "CWA"]);
569
+ const IEC_LEADS = new Set(["IEC", "CISPR"]);
570
+ const ADOPTED_EDITION_FACE = "ED";
571
+ /** The declared glued edition face, lifted from the run's tail ("BS HD
572
+ * IEC 60364-8-81 ED1" — the ordinal glues to the face, there is no
573
+ * edition space): the owning flavor drops it, the wrapper column
574
+ * carries it. Returns the cleaned run and the ordinal; a run with no
575
+ * face passes through untouched. */
576
+ function extractEdition(adoptedStr) {
577
+ const match = /\s+ED(\d+)\s*$/.exec(adoptedStr);
578
+ if (match === null)
579
+ return [adoptedStr, undefined];
580
+ return [adoptedStr.replace(/\s+ED(\d+)\s*$/, ""), match[1]];
581
+ }
582
+ /** The wrapper class by what the owning flavor came back with: a CEN
583
+ * identifier (including a CEN adoption of an ISO/IEC document) is the
584
+ * adopted European norm; an ISO/IEC identifier is the adopted
585
+ * international standard. */
586
+ function wrapperClassOf(adoptedId) {
587
+ const tag = adoptedId.constructor.polymorphicName;
588
+ return typeof tag === "string" && tag.startsWith("pubid:cencenelec:") ? "aen" : "ais";
589
+ }
590
+ /** The adopted-base dispatch (the §4 coded escape hatch): the wrapper's
591
+ * attributes are the adopted document under the uniform `base` slot,
592
+ * the captured head token as the publisher, and the lifted edition
593
+ * face when the run carried one. BSI carries no implicit adoption
594
+ * probe — the coded builder's adoptions are all printed. */
595
+ function adoptedBuild(flat) {
596
+ const adoptedStr = strOf(unwrap(flat["adopted"]))?.trim();
597
+ if (adoptedStr === undefined || adoptedStr === "") {
598
+ throw new ParseFailed("bsi_pfs: an adopted run captured no document", 0);
599
+ }
600
+ const [run, edition] = extractEdition(adoptedStr);
601
+ const adoptedId = parseAdopted(run);
602
+ const attrs = { base: adoptedId };
603
+ const publisher = strOf(unwrap(flat["publisher"]));
604
+ if (publisher !== undefined)
605
+ attrs["publisher"] = new Publisher({ body: publisher });
606
+ if (edition !== undefined)
607
+ attrs["edition"] = edition;
608
+ return wrapperClassOf(adoptedId) === "aen"
609
+ ? new BsiPfsAdoptedEuropeanNorm(attrs)
610
+ : new BsiPfsAdoptedInternationalStandard(attrs);
611
+ }
612
+ function buildBaseDocument(flat) {
613
+ if (present(flat["adopted"]))
614
+ return adoptedBuild(flat);
615
+ return new (locateIdentifierKlass(flat))(assignAttributes(flat));
616
+ }
617
+ /** The run's internal captures bind only through the item row, so the
618
+ * raw supplement item arrives as the capture map itself (or, on a
619
+ * doubly-nested row, as the inner map's first value — the compiled
620
+ * builder's own unwrap). */
621
+ function supplementItemOf(row) {
622
+ const inner = isRecord(row) ? row["supplement"] : undefined;
623
+ if (!isRecord(inner))
624
+ return {};
625
+ const values = Object.values(inner);
626
+ // A row of capture leaves ({value, …}) IS the item; a row whose every
627
+ // value is a nested group descends into its first group (the compiled
628
+ // builder's own unwrap — the Slice/Hash discrimination on the Ruby
629
+ // side, where a leaf capture never arrives as a plain group hash).
630
+ if (values.length > 0 && values.every((v) => isRecord(v) && !("value" in v))) {
631
+ return values[0];
632
+ }
633
+ return inner;
634
+ }
635
+ /** The wrapper classes by kind face: the run's dispatch. */
636
+ function supplementFrom(item, base) {
637
+ const kind = strOf(unwrap(item["supplement_kind"])) ?? "";
638
+ const Wrapper = kind === BsiPfsAmendment.FACE
639
+ ? BsiPfsAmendment
640
+ : kind === BsiPfsCorrigendum.FACE
641
+ ? BsiPfsCorrigendum
642
+ : undefined;
643
+ if (Wrapper === undefined) {
644
+ throw new ParseFailed(`BSI: unknown supplement kind ${kind}`, 0);
645
+ }
646
+ const attrs = {};
647
+ if (base !== undefined)
648
+ attrs["base"] = base;
649
+ const number = presentString(unwrap(item["supplement_number"]));
650
+ if (number !== undefined)
651
+ attrs["number"] = number;
652
+ const year = presentString(unwrap(item["supplements_year"]));
653
+ if (year !== undefined)
654
+ attrs["year"] = year;
655
+ return new Wrapper(attrs);
656
+ }
657
+ /** The declared wrapper shapes: the slash run folds into the standalone
658
+ * wrapper chain, the plus run into the marker-less consolidated bundle
659
+ * whose members each carry the bundle's base document. */
660
+ function wrapSupplements(base, flat) {
661
+ const rows = Array.isArray(flat["supplements"])
662
+ ? flat["supplements"]
663
+ : present(flat["supplements"])
664
+ ? [flat["supplements"]]
665
+ : [];
666
+ if (rows.length === 0)
667
+ return base;
668
+ const items = rows.map(supplementItemOf);
669
+ if (items.some((item) => present(item["supplements_plus"]))) {
670
+ const members = items.map((item) => supplementFrom(item, base));
671
+ return new BsiPfsConsolidatedIdentifier({ identifiers: [base, ...members] });
672
+ }
673
+ return supplementFrom(items[0], base);
674
+ }
675
+ export function buildBsiPfsIdentifier(flat) {
676
+ return wrapSupplements(buildBaseDocument(flat), flat);
677
+ }
678
+ /**
679
+ * The artifact's declared bindings carry the parsed faces: the flat
680
+ * columns land on the model fields, the adopted run dispatches through
681
+ * the hook (the same fold the Ruby builder performs), and the
682
+ * supplement run folds into the synthesized wrapper chain (standalone)
683
+ * or the consolidated bundle (plus).
684
+ */
685
+ let cachedRuntime;
686
+ export function bsiPfsGrammarImplementation() {
687
+ return {
688
+ parse(input) {
689
+ cachedRuntime ??= PubidRuntime.load("bsi_pfs");
690
+ const bound = cachedRuntime.parseAndBind(input);
691
+ if (bound === null || typeof bound !== "object") {
692
+ throw new ParseFailed("bsi_pfs: the artifact rejected the input", 0);
693
+ }
694
+ return buildBsiPfsIdentifier(bound);
695
+ },
696
+ };
697
+ }
@@ -38,6 +38,7 @@ import { gostGrammarImplementation } from "./gost/index.js";
38
38
  import { evsGrammarImplementation } from "./evs/index.js";
39
39
  import { ashraeGrammarImplementation } from "./ashrae/index.js";
40
40
  import { bsiGrammarImplementation } from "./bsi/index.js";
41
+ import { bsiPfsGrammarImplementation } from "./bsi_pfs/index.js";
41
42
  import { csaGrammarImplementation } from "./csa/index.js";
42
43
  import { asmeGrammarImplementation } from "./asme/index.js";
43
44
  import { amcaGrammarImplementation } from "./amca/index.js";
@@ -161,6 +162,8 @@ function grammarImplementationSwitch(flavor) {
161
162
  return ashraeGrammarImplementation();
162
163
  case "bsi":
163
164
  return bsiGrammarImplementation();
165
+ case "bsi_pfs":
166
+ return bsiPfsGrammarImplementation();
164
167
  case "csa":
165
168
  return csaGrammarImplementation();
166
169
  case "asme":
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The pubid-scheme URN schema of BSI_PFS — the transcription
3
+ * of lib/pubid/<flavor>/pubid_urn_schema.rb (pubid#656, completed by
4
+ * #670; design in docs/URN-SCHEMES.adoc). GENERATED by
5
+ * scripts/port-urn-schemas.rb from the ruby declaration: edit the ruby
6
+ * schema and regenerate, never this table by hand.
7
+ */
8
+ export declare const bsiPfsSchema: import("../schema.js").FlavorSchema;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The pubid-scheme URN schema of BSI_PFS — the transcription
3
+ * of lib/pubid/<flavor>/pubid_urn_schema.rb (pubid#656, completed by
4
+ * #670; design in docs/URN-SCHEMES.adoc). GENERATED by
5
+ * scripts/port-urn-schemas.rb from the ruby declaration: edit the ruby
6
+ * schema and regenerate, never this table by hand.
7
+ */
8
+ import { define } from "../index.js";
9
+ export const bsiPfsSchema = define("bsi_pfs", (s) => {
10
+ s.atom("publisher.body", "pubbody");
11
+ s.atom("part", "part");
12
+ s.atom("year", "year");
13
+ s.atom("edition", "ed");
14
+ s.atom("type.abbr", "typeabbr");
15
+ s.atom("type.name", "typename");
16
+ s.atom("type.type_code", "typetypecode");
17
+ s.atom("stage.abbr", "stageabbr");
18
+ s.atom("stage.name", "stagename");
19
+ s.atom("stage.stage_code", "stagecode");
20
+ s.atom("stage.harmonized_stages", "stagehs", "list");
21
+ s.atom("typed_stage.abbr", "tsabbr", "list");
22
+ s.atom("typed_stage.name", "tsname");
23
+ s.atom("typed_stage.code", "tscode");
24
+ s.atom("typed_stage.stage_code", "tsstagecode");
25
+ s.atom("typed_stage.type_code", "tstypecode");
26
+ s.atom("typed_stage.harmonized_stages", "tshs", "list");
27
+ s.atom("identifiers", "ids", "ids");
28
+ s.type("pubid:bsi:adopted-european-norm", "aen", { core: [] });
29
+ s.type("pubid:bsi:adopted-international-standard", "ais", { core: [] });
30
+ s.type("pubid:bsi:amendment", "amd", { core: ["number"] });
31
+ s.type("pubid:bsi:british-standard", "bs", { core: ["number"] });
32
+ s.type("pubid:bsi:consolidated-identifier", "consol", { core: [] });
33
+ s.type("pubid:bsi:corrigendum", "cor", { core: ["number"] });
34
+ s.type("pubid:bsi:draft-document", "dd", { core: ["number"] });
35
+ s.type("pubid:bsi:published-document", "pd", { core: ["number"] });
36
+ s.type("pubid:bsi:publicly-available-specification", "pas", { core: ["number"] });
37
+ s.type("pubid:bsi:technical-specification", "ts", { core: ["number"] });
38
+ });
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The registry of all 47 flavor pubid-urn schema tables — the TS mirror
2
+ * The registry of all 48 flavor pubid-urn schema tables — the TS mirror
3
3
  * of lib/pubid.rb's autoloaded Pubid::<Flavor>::PubidUrnSchema chain.
4
4
  * Declared tables only: importing this module has no side effects; the
5
5
  * pubid-urn module builds its flavor lookup lazily from this array.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The registry of all 47 flavor pubid-urn schema tables — the TS mirror
2
+ * The registry of all 48 flavor pubid-urn schema tables — the TS mirror
3
3
  * of lib/pubid.rb's autoloaded Pubid::<Flavor>::PubidUrnSchema chain.
4
4
  * Declared tables only: importing this module has no side effects; the
5
5
  * pubid-urn module builds its flavor lookup lazily from this array.
@@ -14,6 +14,7 @@ import { asmeSchema } from "./asme.js";
14
14
  import { astmSchema } from "./astm.js";
15
15
  import { bipmSchema } from "./bipm.js";
16
16
  import { bsiSchema } from "./bsi.js";
17
+ import { bsiPfsSchema } from "./bsi_pfs.js";
17
18
  import { calconnectSchema } from "./calconnect.js";
18
19
  import { calconnectPfsSchema } from "./calconnect_pfs.js";
19
20
  import { ccsdsSchema } from "./ccsds.js";
@@ -67,6 +68,7 @@ export const PUBID_URN_SCHEMAS = [
67
68
  astmSchema,
68
69
  bipmSchema,
69
70
  bsiSchema,
71
+ bsiPfsSchema,
70
72
  calconnectSchema,
71
73
  calconnectPfsSchema,
72
74
  ccsdsSchema,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pubid/pubid",
3
- "version": "0.1.66",
3
+ "version": "0.1.67",
4
4
  "description": "TypeScript PubID identifiers: resolution, normalization and canonical hashes for every identifier in the pubid-testsuite corpus (41 standards bodies), with a conformance runner mirroring the Ruby reference",
5
5
  "type": "module",
6
6
  "license": "MIT",