json-schema-to-grammar.mjs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. // WARNING: This file was ported from json_schema_to_grammar.py, please fix bugs / add features there first.
  2. const SPACE_RULE = '| " " | "\\n" [ \\t]{0,20}';
  3. function _buildRepetition(itemRule, minItems, maxItems, opts={}) {
  4. if (minItems === 0 && maxItems === 1) {
  5. return `${itemRule}?`;
  6. }
  7. const separatorRule = opts.separatorRule ?? '';
  8. const itemRuleIsLiteral = opts.itemRuleIsLiteral ?? false
  9. if (separatorRule === '') {
  10. if (minItems === 1 && maxItems === undefined) {
  11. return `${itemRule}+`;
  12. } else if (minItems === 0 && maxItems === undefined) {
  13. return `${itemRule}*`;
  14. } else {
  15. return `${itemRule}{${minItems},${maxItems !== undefined ? maxItems : ''}}`;
  16. }
  17. }
  18. const result = itemRule + ' ' + _buildRepetition(`(${separatorRule} ${itemRule})`, minItems > 0 ? minItems - 1 : 0, maxItems !== undefined ? maxItems - 1 : undefined);
  19. return minItems === 0 ? `(${result})?` : result;
  20. }
  21. function _generateMinMaxInt(minValue, maxValue, out, decimalsLeft = 16, topLevel = true) {
  22. const hasMin = minValue !== null;
  23. const hasMax = maxValue !== null;
  24. function digitRange(fromChar, toChar) {
  25. out.push("[");
  26. if (fromChar === toChar) {
  27. out.push(fromChar);
  28. } else {
  29. out.push(fromChar);
  30. out.push("-");
  31. out.push(toChar);
  32. }
  33. out.push("]");
  34. }
  35. function moreDigits(minDigits, maxDigits) {
  36. out.push("[0-9]");
  37. if (minDigits === maxDigits && minDigits === 1) {
  38. return;
  39. }
  40. out.push("{");
  41. out.push(minDigits.toString());
  42. if (maxDigits !== minDigits) {
  43. out.push(",");
  44. if (maxDigits !== Number.MAX_SAFE_INTEGER) {
  45. out.push(maxDigits.toString());
  46. }
  47. }
  48. out.push("}");
  49. }
  50. function uniformRange(fromStr, toStr) {
  51. let i = 0;
  52. while (i < fromStr.length && fromStr[i] === toStr[i]) {
  53. i++;
  54. }
  55. if (i > 0) {
  56. out.push("\"");
  57. out.push(fromStr.slice(0, i));
  58. out.push("\"");
  59. }
  60. if (i < fromStr.length) {
  61. if (i > 0) {
  62. out.push(" ");
  63. }
  64. const subLen = fromStr.length - i - 1;
  65. if (subLen > 0) {
  66. const fromSub = fromStr.slice(i + 1);
  67. const toSub = toStr.slice(i + 1);
  68. const subZeros = "0".repeat(subLen);
  69. const subNines = "9".repeat(subLen);
  70. let toReached = false;
  71. out.push("(");
  72. if (fromSub === subZeros) {
  73. digitRange(fromStr[i], String.fromCharCode(toStr.charCodeAt(i) - 1));
  74. out.push(" ");
  75. moreDigits(subLen, subLen);
  76. } else {
  77. out.push("[");
  78. out.push(fromStr[i]);
  79. out.push("] ");
  80. out.push("(");
  81. uniformRange(fromSub, subNines);
  82. out.push(")");
  83. if (fromStr.charCodeAt(i) < toStr.charCodeAt(i) - 1) {
  84. out.push(" | ");
  85. if (toSub === subNines) {
  86. digitRange(String.fromCharCode(fromStr.charCodeAt(i) + 1), toStr[i]);
  87. toReached = true;
  88. } else {
  89. digitRange(String.fromCharCode(fromStr.charCodeAt(i) + 1), String.fromCharCode(toStr.charCodeAt(i) - 1));
  90. }
  91. out.push(" ");
  92. moreDigits(subLen, subLen);
  93. }
  94. }
  95. if (!toReached) {
  96. out.push(" | ");
  97. digitRange(toStr[i], toStr[i]);
  98. out.push(" ");
  99. uniformRange(subZeros, toSub);
  100. }
  101. out.push(")");
  102. } else {
  103. out.push("[");
  104. out.push(fromStr[i]);
  105. out.push("-");
  106. out.push(toStr[i]);
  107. out.push("]");
  108. }
  109. }
  110. }
  111. if (hasMin && hasMax) {
  112. if (minValue < 0 && maxValue < 0) {
  113. out.push("\"-\" (");
  114. _generateMinMaxInt(-maxValue, -minValue, out, decimalsLeft, true);
  115. out.push(")");
  116. return;
  117. }
  118. if (minValue < 0) {
  119. out.push("\"-\" (");
  120. _generateMinMaxInt(0, -minValue, out, decimalsLeft, true);
  121. out.push(") | ");
  122. minValue = 0;
  123. }
  124. let minS = minValue.toString();
  125. const maxS = maxValue.toString();
  126. const minDigits = minS.length;
  127. const maxDigits = maxS.length;
  128. for (let digits = minDigits; digits < maxDigits; digits++) {
  129. uniformRange(minS, "9".repeat(digits));
  130. minS = "1" + "0".repeat(digits);
  131. out.push(" | ");
  132. }
  133. uniformRange(minS, maxS);
  134. return;
  135. }
  136. const lessDecimals = Math.max(decimalsLeft - 1, 1);
  137. if (hasMin) {
  138. if (minValue < 0) {
  139. out.push("\"-\" (");
  140. _generateMinMaxInt(null, -minValue, out, decimalsLeft, false);
  141. out.push(") | [0] | [1-9] ");
  142. moreDigits(0, decimalsLeft - 1);
  143. } else if (minValue === 0) {
  144. if (topLevel) {
  145. out.push("[0] | [1-9] ");
  146. moreDigits(0, lessDecimals);
  147. } else {
  148. moreDigits(1, decimalsLeft);
  149. }
  150. } else if (minValue <= 9) {
  151. const c = minValue.toString();
  152. const range_start = topLevel ? '1' : '0';
  153. if (c > range_start) {
  154. digitRange(range_start, String.fromCharCode(c.charCodeAt(0) - 1));
  155. out.push(" ");
  156. moreDigits(1, lessDecimals);
  157. out.push(" | ");
  158. }
  159. digitRange(c, "9");
  160. out.push(" ");
  161. moreDigits(0, lessDecimals);
  162. } else {
  163. const minS = minValue.toString();
  164. const length = minS.length;
  165. const c = minS[0];
  166. if (c > "1") {
  167. digitRange(topLevel ? "1" : "0", String.fromCharCode(c.charCodeAt(0) - 1));
  168. out.push(" ");
  169. moreDigits(length, lessDecimals);
  170. out.push(" | ");
  171. }
  172. digitRange(c, c);
  173. out.push(" (");
  174. _generateMinMaxInt(parseInt(minS.slice(1)), null, out, lessDecimals, false);
  175. out.push(")");
  176. if (c < "9") {
  177. out.push(" | ");
  178. digitRange(String.fromCharCode(c.charCodeAt(0) + 1), "9");
  179. out.push(" ");
  180. moreDigits(length - 1, lessDecimals);
  181. }
  182. }
  183. return;
  184. }
  185. if (hasMax) {
  186. if (maxValue >= 0) {
  187. if (topLevel) {
  188. out.push("\"-\" [1-9] ");
  189. moreDigits(0, lessDecimals);
  190. out.push(" | ");
  191. }
  192. _generateMinMaxInt(0, maxValue, out, decimalsLeft, true);
  193. } else {
  194. out.push("\"-\" (");
  195. _generateMinMaxInt(-maxValue, null, out, decimalsLeft, false);
  196. out.push(")");
  197. }
  198. return;
  199. }
  200. throw new Error("At least one of minValue or maxValue must be set");
  201. }
  202. class BuiltinRule {
  203. constructor(content, deps) {
  204. this.content = content;
  205. this.deps = deps || [];
  206. }
  207. }
  208. const PRIMITIVE_RULES = {
  209. boolean : new BuiltinRule('("true" | "false") space', []),
  210. 'decimal-part' : new BuiltinRule('[0-9]{1,16}', []),
  211. 'integral-part': new BuiltinRule('[0] | [1-9] [0-9]{0,15}', []),
  212. number : new BuiltinRule('("-"? integral-part) ("." decimal-part)? ([eE] [-+]? integral-part)? space', ['integral-part', 'decimal-part']),
  213. integer : new BuiltinRule('("-"? integral-part) space', ['integral-part']),
  214. value : new BuiltinRule('object | array | string | number | boolean | null', ['object', 'array', 'string', 'number', 'boolean', 'null']),
  215. object : new BuiltinRule('"{" space ( string ":" space value ("," space string ":" space value)* )? "}" space', ['string', 'value']),
  216. array : new BuiltinRule('"[" space ( value ("," space value)* )? "]" space', ['value']),
  217. uuid : new BuiltinRule('"\\"" [0-9a-fA-F]{8} "-" [0-9a-fA-F]{4} "-" [0-9a-fA-F]{4} "-" [0-9a-fA-F]{4} "-" [0-9a-fA-F]{12} "\\"" space', []),
  218. char : new BuiltinRule(`[^"\\\\\\x7F\\x00-\\x1F] | [\\\\] (["\\\\bfnrt] | "u" [0-9a-fA-F]{4})`, []),
  219. string : new BuiltinRule(`"\\"" char* "\\"" space`, ['char']),
  220. null : new BuiltinRule('"null" space', []),
  221. };
  222. // TODO: support "uri", "email" string formats
  223. const STRING_FORMAT_RULES = {
  224. 'date' : new BuiltinRule('[0-9]{4} "-" ( "0" [1-9] | "1" [0-2] ) "-" ( \"0\" [1-9] | [1-2] [0-9] | "3" [0-1] )', []),
  225. 'time' : new BuiltinRule('([01] [0-9] | "2" [0-3]) ":" [0-5] [0-9] ":" [0-5] [0-9] ( "." [0-9]{3} )? ( "Z" | ( "+" | "-" ) ( [01] [0-9] | "2" [0-3] ) ":" [0-5] [0-9] )', []),
  226. 'date-time' : new BuiltinRule('date "T" time', ['date', 'time']),
  227. 'date-string' : new BuiltinRule('"\\"" date "\\"" space', ['date']),
  228. 'time-string' : new BuiltinRule('"\\"" time "\\"" space', ['time']),
  229. 'date-time-string': new BuiltinRule('"\\"" date-time "\\"" space', ['date-time']),
  230. }
  231. const RESERVED_NAMES = {'root': true, ...PRIMITIVE_RULES, ...STRING_FORMAT_RULES};
  232. const INVALID_RULE_CHARS_RE = /[^\dA-Za-z-]+/g;
  233. const GRAMMAR_LITERAL_ESCAPE_RE = /[\n\r"]/g;
  234. const GRAMMAR_RANGE_LITERAL_ESCAPE_RE = /[\n\r"\]\-\\]/g;
  235. const GRAMMAR_LITERAL_ESCAPES = { '\r': '\\r', '\n': '\\n', '"': '\\"', '-': '\\-', ']': '\\]' };
  236. const NON_LITERAL_SET = new Set('|.()[]{}*+?');
  237. const ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = new Set('[]()|{}*+?');
  238. export class SchemaConverter {
  239. constructor(options) {
  240. this._propOrder = options.prop_order || {};
  241. this._allowFetch = options.allow_fetch || false;
  242. this._dotall = options.dotall || false;
  243. this._rules = {'space': SPACE_RULE};
  244. this._refs = {};
  245. this._refsBeingResolved = new Set();
  246. }
  247. _formatLiteral(literal) {
  248. const escaped = literal.replace(
  249. GRAMMAR_LITERAL_ESCAPE_RE,
  250. m => GRAMMAR_LITERAL_ESCAPES[m]
  251. );
  252. return `"${escaped}"`;
  253. }
  254. _formatRangeChar(literal) {
  255. return JSON.stringify(literal).slice(1, -1).replace(
  256. GRAMMAR_RANGE_LITERAL_ESCAPE_RE,
  257. m => GRAMMAR_LITERAL_ESCAPES[m]
  258. );
  259. }
  260. _addRule(name, rule) {
  261. let escName = name.replace(INVALID_RULE_CHARS_RE, '-');
  262. let key = escName;
  263. if (escName in this._rules) {
  264. if (this._rules[escName] === rule) {
  265. return key;
  266. }
  267. let i = 0;
  268. while ((`${escName}${i}` in this._rules) && (this._rules[`${escName}${i}`] !== rule)) {
  269. i += 1;
  270. }
  271. key = `${escName}${i}`;
  272. }
  273. this._rules[key] = rule;
  274. return key;
  275. }
  276. async resolveRefs(schema, url) {
  277. const visit = async (n) => {
  278. if (Array.isArray(n)) {
  279. return Promise.all(n.map(visit));
  280. } else if (typeof n === 'object' && n !== null) {
  281. let ref = n.$ref;
  282. let target;
  283. if (ref !== undefined && !this._refs[ref]) {
  284. if (ref.startsWith('https://')) {
  285. if (!this._allowFetch) {
  286. throw new Error('Fetching remote schemas is not allowed (use --allow-fetch for force)');
  287. }
  288. const fetch = (await import('node-fetch')).default;
  289. const fragSplit = ref.split('#');
  290. const baseUrl = fragSplit[0];
  291. target = this._refs[baseUrl];
  292. if (!target) {
  293. target = await this.resolveRefs(await fetch(ref).then(res => res.json()), baseUrl);
  294. this._refs[baseUrl] = target;
  295. }
  296. if (fragSplit.length === 1 || fragSplit[fragSplit.length - 1] === '') {
  297. return target;
  298. }
  299. } else if (ref.startsWith('#/')) {
  300. target = schema;
  301. ref = `${url}${ref}`;
  302. n.$ref = ref;
  303. } else {
  304. throw new Error(`Unsupported ref ${ref}`);
  305. }
  306. const selectors = ref.split('#')[1].split('/').slice(1);
  307. for (const sel of selectors) {
  308. if (!target || !(sel in target)) {
  309. throw new Error(`Error resolving ref ${ref}: ${sel} not in ${JSON.stringify(target)}`);
  310. }
  311. target = target[sel];
  312. }
  313. this._refs[ref] = target;
  314. } else {
  315. await Promise.all(Object.values(n).map(visit));
  316. }
  317. }
  318. return n;
  319. };
  320. return visit(schema);
  321. }
  322. _generateUnionRule(name, altSchemas) {
  323. return altSchemas
  324. .map((altSchema, i) => this.visit(altSchema, `${name ?? ''}${name ? '-' : 'alternative-'}${i}`))
  325. .join(' | ');
  326. }
  327. _visitPattern(pattern, name) {
  328. if (!pattern.startsWith('^') || !pattern.endsWith('$')) {
  329. throw new Error('Pattern must start with "^" and end with "$"');
  330. }
  331. pattern = pattern.slice(1, -1);
  332. const subRuleIds = {};
  333. let i = 0;
  334. const length = pattern.length;
  335. const getDot = () => {
  336. let rule;
  337. if (this._dotall) {
  338. rule = '[\\U00000000-\\U0010FFFF]';
  339. } else {
  340. // Accept any character... except \n and \r line break chars (\x0A and \xOD)
  341. rule = '[^\\x0A\\x0D]';
  342. }
  343. return this._addRule('dot', rule);
  344. };
  345. const toRule = ([s, isLiteral]) => isLiteral ? "\"" + s + "\"" : s;
  346. const transform = () => {
  347. const start = i;
  348. // For each component of this sequence, store its string representation and whether it's a literal.
  349. // We only need a flat structure here to apply repetition operators to the last item, and
  350. // to merge literals at the and (we're parsing grouped ( sequences ) recursively and don't treat '|' specially
  351. // (GBNF's syntax is luckily very close to regular expressions!)
  352. const seq = [];
  353. const joinSeq = () => {
  354. const ret = [];
  355. for (const [isLiteral, g] of groupBy(seq, x => x[1])) {
  356. if (isLiteral) {
  357. ret.push([[...g].map(x => x[0]).join(''), true]);
  358. } else {
  359. ret.push(...g);
  360. }
  361. }
  362. if (ret.length === 1) {
  363. return ret[0];
  364. }
  365. return [ret.map(x => toRule(x)).join(' '), false];
  366. };
  367. while (i < length) {
  368. const c = pattern[i];
  369. if (c === '.') {
  370. seq.push([getDot(), false]);
  371. i += 1;
  372. } else if (c === '(') {
  373. i += 1;
  374. if (i < length) {
  375. if (pattern[i] === '?') {
  376. throw new Error(`Unsupported pattern syntax "${pattern[i]}" at index ${i} of /${pattern}/`);
  377. }
  378. }
  379. seq.push([`(${toRule(transform())})`, false]);
  380. } else if (c === ')') {
  381. i += 1;
  382. if (start <= 0 || pattern[start - 1] !== '(') {
  383. throw new Error(`Unbalanced parentheses; start = ${start}, i = ${i}, pattern = ${pattern}`);
  384. }
  385. return joinSeq();
  386. } else if (c === '[') {
  387. let squareBrackets = c;
  388. i += 1;
  389. while (i < length && pattern[i] !== ']') {
  390. if (pattern[i] === '\\') {
  391. squareBrackets += pattern.slice(i, i + 2);
  392. i += 2;
  393. } else {
  394. squareBrackets += pattern[i];
  395. i += 1;
  396. }
  397. }
  398. if (i >= length) {
  399. throw new Error(`Unbalanced square brackets; start = ${start}, i = ${i}, pattern = ${pattern}`);
  400. }
  401. squareBrackets += ']';
  402. i += 1;
  403. seq.push([squareBrackets, false]);
  404. } else if (c === '|') {
  405. seq.push(['|', false]);
  406. i += 1;
  407. } else if (c === '*' || c === '+' || c === '?') {
  408. seq[seq.length - 1] = [toRule(seq[seq.length - 1]) + c, false];
  409. i += 1;
  410. } else if (c === '{') {
  411. let curlyBrackets = c;
  412. i += 1;
  413. while (i < length && pattern[i] !== '}') {
  414. curlyBrackets += pattern[i];
  415. i += 1;
  416. }
  417. if (i >= length) {
  418. throw new Error(`Unbalanced curly brackets; start = ${start}, i = ${i}, pattern = ${pattern}`);
  419. }
  420. curlyBrackets += '}';
  421. i += 1;
  422. const nums = curlyBrackets.slice(1, -1).split(',').map(s => s.trim());
  423. let minTimes, maxTimes;
  424. if (nums.length === 1) {
  425. minTimes = parseInt(nums[0], 10);
  426. maxTimes = minTimes;
  427. } else {
  428. if (nums.length !== 2) {
  429. throw new Error(`Invalid quantifier ${curlyBrackets}`);
  430. }
  431. minTimes = nums[0] ? parseInt(nums[0], 10) : 0;
  432. maxTimes = nums[1] ? parseInt(nums[1], 10) : Infinity;
  433. }
  434. let [sub, subIsLiteral] = seq[seq.length - 1];
  435. if (!subIsLiteral) {
  436. let id = subRuleIds[sub];
  437. if (id === undefined) {
  438. id = this._addRule(`${name}-${Object.keys(subRuleIds).length + 1}`, sub);
  439. subRuleIds[sub] = id;
  440. }
  441. sub = id;
  442. }
  443. seq[seq.length - 1] = [
  444. _buildRepetition(subIsLiteral ? `"${sub}"` : sub, minTimes, maxTimes, {itemRuleIsLiteral: subIsLiteral}),
  445. false
  446. ];
  447. } else {
  448. let literal = '';
  449. while (i < length) {
  450. if (pattern[i] === '\\' && i < length - 1) {
  451. const next = pattern[i + 1];
  452. if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.has(next)) {
  453. i += 1;
  454. literal += pattern[i];
  455. i += 1;
  456. } else {
  457. literal += pattern.slice(i, i + 2);
  458. i += 2;
  459. }
  460. } else if (pattern[i] === '"') {
  461. literal += '\\"';
  462. i += 1;
  463. } else if (!NON_LITERAL_SET.has(pattern[i]) &&
  464. (i === length - 1 || literal === '' || pattern[i + 1] === '.' || !NON_LITERAL_SET.has(pattern[i+1]))) {
  465. literal += pattern[i];
  466. i += 1;
  467. } else {
  468. break;
  469. }
  470. }
  471. if (literal !== '') {
  472. seq.push([literal, true]);
  473. }
  474. }
  475. }
  476. return joinSeq();
  477. };
  478. return this._addRule(name, "\"\\\"\" " + toRule(transform()) + " \"\\\"\" space")
  479. }
  480. _resolveRef(ref) {
  481. let refName = ref.split('/').pop();
  482. if (!(refName in this._rules) && !this._refsBeingResolved.has(ref)) {
  483. this._refsBeingResolved.add(ref);
  484. const resolved = this._refs[ref];
  485. refName = this.visit(resolved, refName);
  486. this._refsBeingResolved.delete(ref);
  487. }
  488. return refName;
  489. }
  490. _generateConstantRule(value) {
  491. return this._formatLiteral(JSON.stringify(value));
  492. }
  493. visit(schema, name) {
  494. const schemaType = schema.type;
  495. const schemaFormat = schema.format;
  496. const ruleName = name in RESERVED_NAMES ? name + '-' : name == '' ? 'root' : name;
  497. const ref = schema.$ref;
  498. if (ref !== undefined) {
  499. return this._addRule(ruleName, this._resolveRef(ref));
  500. } else if (schema.oneOf || schema.anyOf) {
  501. return this._addRule(ruleName, this._generateUnionRule(name, schema.oneOf || schema.anyOf));
  502. } else if (Array.isArray(schemaType)) {
  503. return this._addRule(ruleName, this._generateUnionRule(name, schemaType.map(t => ({ type: t }))));
  504. } else if ('const' in schema) {
  505. return this._addRule(ruleName, this._generateConstantRule(schema.const));
  506. } else if ('enum' in schema) {
  507. const rule = schema.enum.map(v => this._generateConstantRule(v)).join(' | ');
  508. return this._addRule(ruleName, rule);
  509. } else if ((schemaType === undefined || schemaType === 'object') &&
  510. ('properties' in schema ||
  511. ('additionalProperties' in schema && schema.additionalProperties !== true))) {
  512. const required = new Set(schema.required || []);
  513. const properties = Object.entries(schema.properties ?? {});
  514. return this._addRule(ruleName, this._buildObjectRule(properties, required, name, schema.additionalProperties));
  515. } else if ((schemaType === undefined || schemaType === 'object') && 'allOf' in schema) {
  516. const required = new Set();
  517. const properties = [];
  518. const addComponent = (compSchema, isRequired) => {
  519. const ref = compSchema.$ref;
  520. if (ref !== undefined) {
  521. compSchema = this._refs[ref];
  522. }
  523. if ('properties' in compSchema) {
  524. for (const [propName, propSchema] of Object.entries(compSchema.properties)) {
  525. properties.push([propName, propSchema]);
  526. if (isRequired) {
  527. required.add(propName);
  528. }
  529. }
  530. }
  531. };
  532. for (const t of schema.allOf) {
  533. if ('anyOf' in t) {
  534. for (const tt of t.anyOf) {
  535. addComponent(tt, false);
  536. }
  537. } else {
  538. addComponent(t, true);
  539. }
  540. }
  541. return this._addRule(ruleName, this._buildObjectRule(properties, required, name, /* additionalProperties= */ false));
  542. } else if ((schemaType === undefined || schemaType === 'array') && ('items' in schema || 'prefixItems' in schema)) {
  543. const items = schema.items ?? schema.prefixItems;
  544. if (Array.isArray(items)) {
  545. return this._addRule(
  546. ruleName,
  547. '"[" space ' +
  548. items.map((item, i) => this.visit(item, `${name ?? ''}${name ? '-' : ''}tuple-${i}`)).join(' "," space ') +
  549. ' "]" space'
  550. );
  551. } else {
  552. const itemRuleName = this.visit(items, `${name ?? ''}${name ? '-' : ''}item`);
  553. const minItems = schema.minItems || 0;
  554. const maxItems = schema.maxItems;
  555. return this._addRule(ruleName, '"[" space ' + _buildRepetition(itemRuleName, minItems, maxItems, {separatorRule: '"," space'}) + ' "]" space');
  556. }
  557. } else if ((schemaType === undefined || schemaType === 'string') && 'pattern' in schema) {
  558. return this._visitPattern(schema.pattern, ruleName);
  559. } else if ((schemaType === undefined || schemaType === 'string') && /^uuid[1-5]?$/.test(schema.format || '')) {
  560. return this._addPrimitive(
  561. ruleName === 'root' ? 'root' : schemaFormat,
  562. PRIMITIVE_RULES['uuid']
  563. );
  564. } else if ((schemaType === undefined || schemaType === 'string') && `${schema.format}-string` in STRING_FORMAT_RULES) {
  565. const primName = `${schema.format}-string`
  566. return this._addRule(ruleName, this._addPrimitive(primName, STRING_FORMAT_RULES[primName]));
  567. } else if (schemaType === 'string' && ('minLength' in schema || 'maxLength' in schema)) {
  568. const charRuleName = this._addPrimitive('char', PRIMITIVE_RULES['char']);
  569. const minLen = schema.minLength || 0;
  570. const maxLen = schema.maxLength;
  571. return this._addRule(ruleName, '"\\\"" ' + _buildRepetition(charRuleName, minLen, maxLen) + ' "\\\"" space');
  572. } else if (schemaType === 'integer' && ('minimum' in schema || 'exclusiveMinimum' in schema || 'maximum' in schema || 'exclusiveMaximum' in schema)) {
  573. let minValue = null;
  574. let maxValue = null;
  575. if ('minimum' in schema) {
  576. minValue = schema.minimum;
  577. } else if ('exclusiveMinimum' in schema) {
  578. minValue = schema.exclusiveMinimum + 1;
  579. }
  580. if ('maximum' in schema) {
  581. maxValue = schema.maximum;
  582. } else if ('exclusiveMaximum' in schema) {
  583. maxValue = schema.exclusiveMaximum - 1;
  584. }
  585. const out = ["("];
  586. _generateMinMaxInt(minValue, maxValue, out);
  587. out.push(") space");
  588. return this._addRule(ruleName, out.join(''));
  589. } else if ((schemaType === 'object') || (Object.keys(schema).length === 0)) {
  590. return this._addRule(ruleName, this._addPrimitive('object', PRIMITIVE_RULES['object']));
  591. } else {
  592. if (!(schemaType in PRIMITIVE_RULES)) {
  593. throw new Error(`Unrecognized schema: ${JSON.stringify(schema)}`);
  594. }
  595. // TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
  596. return this._addPrimitive(ruleName === 'root' ? 'root' : schemaType, PRIMITIVE_RULES[schemaType]);
  597. }
  598. }
  599. _addPrimitive(name, rule) {
  600. let n = this._addRule(name, rule.content);
  601. for (const dep of rule.deps) {
  602. const depRule = PRIMITIVE_RULES[dep] || STRING_FORMAT_RULES[dep];
  603. if (!depRule) {
  604. throw new Error(`Rule ${dep} not known`);
  605. }
  606. if (!(dep in this._rules)) {
  607. this._addPrimitive(dep, depRule);
  608. }
  609. }
  610. return n;
  611. }
  612. _buildObjectRule(properties, required, name, additionalProperties) {
  613. const propOrder = this._propOrder;
  614. // sort by position in prop_order (if specified) then by original order
  615. const sortedProps = properties.map(([k]) => k).sort((a, b) => {
  616. const orderA = propOrder[a] || Infinity;
  617. const orderB = propOrder[b] || Infinity;
  618. return orderA - orderB || properties.findIndex(([k]) => k === a) - properties.findIndex(([k]) => k === b);
  619. });
  620. const propKvRuleNames = {};
  621. for (const [propName, propSchema] of properties) {
  622. const propRuleName = this.visit(propSchema, `${name ?? ''}${name ? '-' : ''}${propName}`);
  623. propKvRuleNames[propName] = this._addRule(
  624. `${name ?? ''}${name ? '-' : ''}${propName}-kv`,
  625. `${this._formatLiteral(JSON.stringify(propName))} space ":" space ${propRuleName}`
  626. );
  627. }
  628. const requiredProps = sortedProps.filter(k => required.has(k));
  629. const optionalProps = sortedProps.filter(k => !required.has(k));
  630. if (typeof additionalProperties === 'object' || additionalProperties === true) {
  631. const subName = `${name ?? ''}${name ? '-' : ''}additional`;
  632. const valueRule = this.visit(additionalProperties === true ? {} : additionalProperties, `${subName}-value`);
  633. propKvRuleNames['*'] = this._addRule(
  634. `${subName}-kv`,
  635. `${this._addPrimitive('string', PRIMITIVE_RULES['string'])} ":" space ${valueRule}`);
  636. optionalProps.push('*');
  637. }
  638. let rule = '"{" space ';
  639. rule += requiredProps.map(k => propKvRuleNames[k]).join(' "," space ');
  640. if (optionalProps.length > 0) {
  641. rule += ' (';
  642. if (requiredProps.length > 0) {
  643. rule += ' "," space ( ';
  644. }
  645. const getRecursiveRefs = (ks, firstIsOptional) => {
  646. const [k, ...rest] = ks;
  647. const kvRuleName = propKvRuleNames[k];
  648. let res;
  649. if (k === '*') {
  650. res = this._addRule(
  651. `${name ?? ''}${name ? '-' : ''}additional-kvs`,
  652. `${kvRuleName} ( "," space ` + kvRuleName + ` )*`
  653. )
  654. } else if (firstIsOptional) {
  655. res = `( "," space ${kvRuleName} )?`;
  656. } else {
  657. res = kvRuleName;
  658. }
  659. if (rest.length > 0) {
  660. res += ' ' + this._addRule(
  661. `${name ?? ''}${name ? '-' : ''}${k}-rest`,
  662. getRecursiveRefs(rest, true)
  663. );
  664. }
  665. return res;
  666. };
  667. rule += optionalProps.map((_, i) => getRecursiveRefs(optionalProps.slice(i), false)).join(' | ');
  668. if (requiredProps.length > 0) {
  669. rule += ' )';
  670. }
  671. rule += ' )?';
  672. }
  673. rule += ' "}" space';
  674. return rule;
  675. }
  676. formatGrammar() {
  677. let grammar = '';
  678. for (const [name, rule] of Object.entries(this._rules).sort(([a], [b]) => a.localeCompare(b))) {
  679. grammar += `${name} ::= ${rule}\n`;
  680. }
  681. return grammar;
  682. }
  683. }
  684. // Helper function to group elements by a key function
  685. function* groupBy(iterable, keyFn) {
  686. let lastKey = null;
  687. let group = [];
  688. for (const element of iterable) {
  689. const key = keyFn(element);
  690. if (lastKey !== null && key !== lastKey) {
  691. yield [lastKey, group];
  692. group = [];
  693. }
  694. group.push(element);
  695. lastKey = key;
  696. }
  697. if (group.length > 0) {
  698. yield [lastKey, group];
  699. }
  700. }