dataset_reader.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.DatasetReader = void 0;
  27. var _util = require("../shared/util.js");
  28. var _core_utils = require("./core_utils.js");
  29. var _xml_parser = require("./xml_parser.js");
  30. function decodeString(str) {
  31. try {
  32. return (0, _util.stringToUTF8String)(str);
  33. } catch (ex) {
  34. (0, _util.warn)(`UTF-8 decoding failed: "${ex}".`);
  35. return str;
  36. }
  37. }
  38. class DatasetXMLParser extends _xml_parser.SimpleXMLParser {
  39. constructor(options) {
  40. super(options);
  41. this.node = null;
  42. }
  43. onEndElement(name) {
  44. const node = super.onEndElement(name);
  45. if (node && name === "xfa:datasets") {
  46. this.node = node;
  47. throw new Error("Aborting DatasetXMLParser.");
  48. }
  49. }
  50. }
  51. class DatasetReader {
  52. constructor(data) {
  53. if (data.datasets) {
  54. this.node = new _xml_parser.SimpleXMLParser({
  55. hasAttributes: true
  56. }).parseFromString(data.datasets).documentElement;
  57. } else {
  58. const parser = new DatasetXMLParser({
  59. hasAttributes: true
  60. });
  61. try {
  62. parser.parseFromString(data["xdp:xdp"]);
  63. } catch (_) {}
  64. this.node = parser.node;
  65. }
  66. }
  67. getValue(path) {
  68. if (!this.node || !path) {
  69. return "";
  70. }
  71. const node = this.node.searchNode((0, _core_utils.parseXFAPath)(path), 0);
  72. if (!node) {
  73. return "";
  74. }
  75. const first = node.firstChild;
  76. if (first && first.nodeName === "value") {
  77. return node.children.map(child => decodeString(child.textContent));
  78. }
  79. return decodeString(node.textContent);
  80. }
  81. }
  82. exports.DatasetReader = DatasetReader;