schema.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { Scalar } from '../../nodes/Scalar.js';
  2. import { map } from '../common/map.js';
  3. import { seq } from '../common/seq.js';
  4. function intIdentify(value) {
  5. return typeof value === 'bigint' || Number.isInteger(value);
  6. }
  7. const stringifyJSON = ({ value }) => JSON.stringify(value);
  8. const jsonScalars = [
  9. {
  10. identify: value => typeof value === 'string',
  11. default: true,
  12. tag: 'tag:yaml.org,2002:str',
  13. resolve: str => str,
  14. stringify: stringifyJSON
  15. },
  16. {
  17. identify: value => value == null,
  18. createNode: () => new Scalar(null),
  19. default: true,
  20. tag: 'tag:yaml.org,2002:null',
  21. test: /^null$/,
  22. resolve: () => null,
  23. stringify: stringifyJSON
  24. },
  25. {
  26. identify: value => typeof value === 'boolean',
  27. default: true,
  28. tag: 'tag:yaml.org,2002:bool',
  29. test: /^true|false$/,
  30. resolve: str => str === 'true',
  31. stringify: stringifyJSON
  32. },
  33. {
  34. identify: intIdentify,
  35. default: true,
  36. tag: 'tag:yaml.org,2002:int',
  37. test: /^-?(?:0|[1-9][0-9]*)$/,
  38. resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
  39. stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
  40. },
  41. {
  42. identify: value => typeof value === 'number',
  43. default: true,
  44. tag: 'tag:yaml.org,2002:float',
  45. test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
  46. resolve: str => parseFloat(str),
  47. stringify: stringifyJSON
  48. }
  49. ];
  50. const jsonError = {
  51. default: true,
  52. tag: '',
  53. test: /^/,
  54. resolve(str, onError) {
  55. onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
  56. return str;
  57. }
  58. };
  59. const schema = [map, seq].concat(jsonScalars, jsonError);
  60. export { schema };