1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515 |
x10
x10
x10
x10
x10
x10
x1392
x1392
x10
x69
x73
x73
x126
x182
x182
x183
x183
x182
x123
x69
x10
x29
x30
x30
x47
x29
x29
x29
x29
x31
x31
x29
x106
x106
x106
x106
x106
x106
x106
x106
x106
x107
x107
x106
x44
x29
x10
x10
x81
x81
x89
x89
x89
x99
x99
x99
x99
x99
x99
x101
x101
x101
x101
x101
x212
x212
x212
x212
x212
x212
x212
x212
x81
x84
x84
x81
x192
x192
x192
x192
x192
x192
x1047
x1047
x192
x192
x257
x259
x259
x259
x259
x259
x320
x192
x260
x261
x261
x261
x261
x261
x260
x262
x262
x262
x262
x262
x279
x238
x278
x279
x279
x279
x279
x279
x293
x262
x262
x262
x262
x262
x276
x276
x276
x276
x270
x272
x272
x272
x272
x272
x192
x195
x195
x192
x193
x193
x193
x193
x193
x394
x192
x195
x195
x192
x193
x193
x193
x193
x193
x287
x192
x193
x193
x193
x193
x193
x286
x286
x192
x523
x523
x192
x193
x193
x193
x193
x193
x285
x285
x192
x251
x256
x256
x256
x256
x256
x256
x305
x192
x245
x249
x249
x249
x249
x249
x249
x260
x226
x241
x243
x243
x243
x243
x243
x254
x254
x192
x192
x243
x243
x192
x194
x194
x194
x194
x194
x192
x113
x113
x113
x257
x263
x81
x81
x10
x72
x72
x10
x10
x10
x324
x559
x559
x627
x632
x632
x627
x629
x629
x627
x928
x928
x996
x324
x10
x10
x10
x53
x53
x53
x53
x53
x54
x54
x53
x55
x55
x53
x54
x54
x53
x55
x55
x53
x54
x54
x53
x55
x55
x53
x54
x54
x86
x53
x10
x129
x129
x1392
x348
x263
x263
x263
x263
x419
x129
x129 |
I
I
I
I
|
// Copyright 2018-2026 the Deno authors. MIT license.
// This module is browser compatible.
/**
* Internal shared utilities for the XML module.
*
* @module
*/
import type { XmlName } from "./types.ts";
/**
* Line ending normalization pattern per XML 1.0 §2.11.
* Converts \r\n and standalone \r to \n.
*/
export const LINE_ENDING_RE = /\r\n?/g;
/**
* Whitespace-only test per XML 1.0 §2.3.
* Uses explicit [ \t\r\n] instead of \s to match XML spec exactly:
* S ::= (#x20 | #x9 | #xD | #xA)+
*/
export const WHITESPACE_ONLY_RE = /^[ \t\r\n]*$/;
/**
* XML declaration version attribute pattern.
* Matches both single and double quoted values.
*/
export const VERSION_RE = /version\s*=\s*(?:"([^"]+)"|'([^']+)')/;
/**
* XML declaration encoding attribute pattern.
* Matches both single and double quoted values.
*/
export const ENCODING_RE = /encoding\s*=\s*(?:"([^"]+)"|'([^']+)')/;
/**
* XML declaration standalone attribute pattern.
* Matches both single and double quoted values, restricted to "yes" or "no".
*/
export const STANDALONE_RE = /standalone\s*=\s*(?:"(yes|no)"|'(yes|no)')/;
/**
* Result of validating an XML declaration.
*/
export interface XmlDeclarationValidationResult {
valid: true;
version: string;
encoding?: string;
standalone?: "yes" | "no";
}
/**
* Error result of validating an XML declaration.
*/
export interface XmlDeclarationValidationError {
valid: false;
error: string;
}
/**
* XML whitespace characters per §2.3.
*/
function isXmlWhitespace(code: number): boolean {
return code === 0x20 || code === 0x09 || code === 0x0A || code === 0x0D;
}
/**
* Validates a VersionNum per XML 1.0 §2.8.
* VersionNum ::= '1.' [0-9]+
*
* @param version The version string to validate
* @returns true if valid, false otherwise
*/
function isValidVersionNum(version: string): boolean {
// Must be "1." followed by one or more digits
if (version.length < 3 || !version.startsWith("1.")) {
return false;
}
for (let i = 2; i < version.length; i++) {
const code = version.charCodeAt(i);
if (code < 0x30 || code > 0x39) { // 0-9
return false;
}
}
return true;
}
/**
* Validates an EncName per XML 1.0 §4.3.3.
* EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
*
* @param encoding The encoding name to validate
* @returns true if valid, false otherwise
*/
function isValidEncName(encoding: string): boolean {
if (encoding.length === 0) {
return false;
}
// First character must be a letter
const first = encoding.charCodeAt(0);
if (
!(first >= 0x41 && first <= 0x5A) && // A-Z
!(first >= 0x61 && first <= 0x7A) // a-z
) {
return false;
}
// Rest can be letter, digit, '.', '_', '-'
for (let i = 1; i < encoding.length; i++) {
const code = encoding.charCodeAt(i);
if (
!(code >= 0x41 && code <= 0x5A) && // A-Z
!(code >= 0x61 && code <= 0x7A) && // a-z
!(code >= 0x30 && code <= 0x39) && // 0-9
code !== 0x2E && // .
code !== 0x5F && // _
code !== 0x2D // -
) {
return false;
}
}
return true;
}
/**
* Validates and parses an XML declaration content string.
*
* XML 1.0 §2.8 XMLDecl:
* XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
* VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
* EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" )
* SDDecl ::= S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"'))
* Eq ::= S? '=' S?
*
* This function validates:
* - 'version' is required and must be first
* - Attributes must have whitespace before them (after previous value/version)
* - No duplicate attributes
* - No unknown attributes
* - Quote characters must match
* - 'encoding' must come before 'standalone' if both present
*
* @param content The content between <?xml and ?> (whitespace trimmed by caller)
* @returns Validation result with parsed values or error message
*/
export function validateXmlDeclaration(
content: string,
): XmlDeclarationValidationResult | XmlDeclarationValidationError {
// Fast-path: version is required and must be first, quick check before full parse
const trimmed = content.trimStart();
if (!trimmed.startsWith("version")) {
// Check for common errors: case variants
if (
trimmed.startsWith("VERSION") || trimmed.startsWith("Version")
) {
const name = trimmed.slice(0, 7);
return {
valid: false,
error: `'${name}' must be lowercase in XML declaration`,
};
}
return {
valid: false,
error: "Missing required 'version' attribute in XML declaration",
};
}
let pos = 0;
const len = content.length;
let version: string | undefined;
let encoding: string | undefined;
let standalone: "yes" | "no" | undefined;
let foundVersion = false;
let foundEncoding = false;
let foundStandalone = false;
// Skip leading whitespace
while (pos < len && isXmlWhitespace(content.charCodeAt(pos))) {
pos++;
}
// Parse attributes
while (pos < len) {
// Read attribute name
const nameStart = pos;
while (
pos < len &&
!isXmlWhitespace(content.charCodeAt(pos)) &&
content.charCodeAt(pos) !== 0x3D // =
) {
pos++;
}
const name = content.slice(nameStart, pos);
if (name === "") {
// Trailing whitespace only
break;
}
// Check for valid attribute names and order
if (name === "version") {
if (foundVersion) {
return {
valid: false,
error: "Duplicate 'version' attribute in XML declaration",
};
}
foundVersion = true;
} else if (name === "encoding") {
if (!foundVersion) {
return {
valid: false,
error: "'encoding' must come after 'version' in XML declaration",
};
}
if (foundEncoding) {
return {
valid: false,
error: "Duplicate 'encoding' attribute in XML declaration",
};
}
if (foundStandalone) {
return {
valid: false,
error: "'encoding' must come before 'standalone' in XML declaration",
};
}
foundEncoding = true;
} else if (name === "standalone") {
if (!foundVersion) {
return {
valid: false,
error: "'standalone' must come after 'version' in XML declaration",
};
}
if (foundStandalone) {
return {
valid: false,
error: "Duplicate 'standalone' attribute in XML declaration",
};
}
foundStandalone = true;
} else if (
name === "VERSION" || name === "Version" ||
name === "ENCODING" || name === "Encoding" ||
name === "STANDALONE" || name === "Standalone"
) {
// Case-sensitive check - these must be lowercase
return {
valid: false,
error: `'${name}' must be lowercase in XML declaration`,
};
} else {
return {
valid: false,
error: `Unknown attribute '${name}' in XML declaration`,
};
}
// Skip whitespace before =
while (pos < len && isXmlWhitespace(content.charCodeAt(pos))) {
pos++;
}
// Expect =
if (pos >= len || content.charCodeAt(pos) !== 0x3D) {
return {
valid: false,
error: `Expected '=' after '${name}' in XML declaration`,
};
}
pos++; // Skip =
// Skip whitespace after =
while (pos < len && isXmlWhitespace(content.charCodeAt(pos))) {
pos++;
}
// Expect quote
if (pos >= len) {
return {
valid: false,
error: `Expected quoted value for '${name}' in XML declaration`,
};
}
const quote = content.charCodeAt(pos);
if (quote !== 0x22 && quote !== 0x27) { // " or '
return {
valid: false,
error: `Expected quote for '${name}' value in XML declaration`,
};
}
pos++; // Skip opening quote
// Read value until matching quote
const valueStart = pos;
while (pos < len && content.charCodeAt(pos) !== quote) {
pos++;
}
if (pos >= len) {
return {
valid: false,
error: `Unterminated ${name} value in XML declaration`,
};
}
const value = content.slice(valueStart, pos);
pos++; // Skip closing quote
// Validate and store value
if (name === "version") {
if (!isValidVersionNum(value)) {
return {
valid: false,
error:
`Invalid version '${value}', must match '1.' followed by digits`,
};
}
version = value;
} else if (name === "encoding") {
if (!isValidEncName(value)) {
return {
valid: false,
error:
`Invalid encoding name '${value}', must start with letter and contain only letters, digits, '.', '_', '-'`,
};
}
encoding = value;
} else if (name === "standalone") {
if (value !== "yes" && value !== "no") {
return {
valid: false,
error: `Invalid standalone value '${value}', must be 'yes' or 'no'`,
};
}
standalone = value;
}
// Check for required whitespace before next attribute
const hadWhitespace = pos < len && isXmlWhitespace(content.charCodeAt(pos));
// Skip whitespace
while (pos < len && isXmlWhitespace(content.charCodeAt(pos))) {
pos++;
}
// If there's more content, whitespace was required
if (pos < len && !hadWhitespace) {
return {
valid: false,
error: "Missing whitespace between attributes in XML declaration",
};
}
}
// Validate required attributes
if (!foundVersion) {
return {
valid: false,
error: "Missing required 'version' attribute in XML declaration",
};
}
return {
valid: true,
version: version!,
...(encoding !== undefined && { encoding }),
...(standalone !== undefined && { standalone }),
};
}
/**
* Checks if a PI target is a case-variant of "xml" (which is reserved).
*
* XML 1.0 §2.6: "The target names 'XML', 'xml', and so on are reserved for
* standardization in this or future versions of this specification."
*
* @param target The PI target name
* @returns true if the target is reserved (any case variant of "xml")
*/
export function isReservedPiTarget(target: string): boolean {
return target.length === 3 && target.toLowerCase() === "xml";
}
// =============================================================================
// NAMESPACE VALIDATION (XML Namespaces 1.0)
// =============================================================================
/** The reserved XML namespace URI. */
export const XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace";
/** The reserved xmlns namespace URI. */
export const XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/";
/**
* Validates QName syntax per XML Namespaces 1.0.
*
* A QName must be either:
* - An NCName (no colons)
* - A prefix:local pair where both prefix and local are valid NCNames
*
* This validates:
* - No colon at start (:foo is invalid)
* - No colon at end (foo: is invalid)
* - No multiple colons (a:b:c is invalid)
*
* @param name The name to validate
* @param colonIndex The index of the first colon, or -1 if none
* @returns Error message if invalid, null if valid
*/
export function validateQName(name: string, colonIndex: number): string | null {
if (colonIndex === -1) {
return null; // No colon means valid NCName (already validated by name char rules)
}
// Colon at start (:foo) - invalid
if (colonIndex === 0) {
return "QName cannot start with ':'";
}
// Colon at end (foo:) - invalid
if (colonIndex === name.length - 1) {
return "QName cannot end with ':'";
}
// Multiple colons (a:b:c) - invalid
if (name.indexOf(":", colonIndex + 1) !== -1) {
return "QName cannot contain multiple ':'";
}
return null; // Valid QName
}
/**
* Validates a namespace binding (xmlns or xmlns:prefix attribute).
*
* Per XML Namespaces 1.0:
* - xmlns:prefix="" (prefix unbinding) is NOT allowed in NS 1.0
* - xmlns:xmlns is NOT allowed (cannot declare xmlns prefix)
* - xmlns:xml must bind to the correct XML namespace
* - Only xml prefix can bind to the XML namespace
* - Nothing can bind to the xmlns namespace
* - Default namespace cannot be xml or xmlns namespace
*
* @param attrName The attribute name (e.g., "xmlns" or "xmlns:foo")
* @param attrValue The namespace URI value
* @returns Error message if invalid, null if valid
*/
export function validateNamespaceBinding(
attrName: string,
attrValue: string,
): string | null {
const colonIndex = attrName.indexOf(":");
const isDefaultNs = attrName === "xmlns";
const prefix = isDefaultNs ? "" : attrName.slice(colonIndex + 1);
const uri = attrValue;
// xmlns: with empty local part is caught by QName validation
// But check for empty prefix after xmlns:
if (colonIndex !== -1 && prefix === "") {
return "Namespace prefix cannot be empty after 'xmlns:'";
}
// Prefix unbinding not allowed in NS 1.0 (xmlns:foo="")
if (!isDefaultNs && uri === "") {
return "Namespace prefix unbinding (empty URI) is not allowed in Namespaces 1.0";
}
// Cannot declare xmlns prefix at all
if (prefix === "xmlns") {
return "The 'xmlns' prefix must not be declared";
}
// xml prefix must use correct URI
if (prefix === "xml" && uri !== XML_NAMESPACE) {
return `The 'xml' prefix must be bound to '${XML_NAMESPACE}'`;
}
// Only xml prefix can use xml namespace
if (uri === XML_NAMESPACE && prefix !== "xml" && prefix !== "") {
return `Only the 'xml' prefix may be bound to '${XML_NAMESPACE}'`;
}
// Nothing can bind to xmlns namespace (includes default namespace case)
if (uri === XMLNS_NAMESPACE) {
return `The namespace '${XMLNS_NAMESPACE}' must not be bound to any prefix`;
}
// Default namespace cannot be xml namespace
if (isDefaultNs && uri === XML_NAMESPACE) {
return `The XML namespace '${XML_NAMESPACE}' cannot be the default namespace`;
}
return null; // Valid binding
}
/**
* Parses a qualified XML name into its prefix and local parts.
*
* @param name The raw name string (e.g., "ns:element" or "element")
* @param uri Optional resolved namespace URI for prefixed names
* @returns An XmlName object with raw, local, optional prefix, and optional uri
*/
export function parseName(name: string, uri?: string): XmlName {
const colonIndex = name.indexOf(":");
if (colonIndex === -1) {
return { raw: name, local: name };
}
return {
raw: name,
prefix: name.slice(0, colonIndex),
local: name.slice(colonIndex + 1),
...(uri !== undefined && { uri }),
};
}
|