xml2js#parseStringPromise TypeScript Examples

The following examples show how to use xml2js#parseStringPromise. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: annotations.test.ts    From nunit-reporter with MIT License 6 votes vote down vote up
test("parse TestCase", async () => {
  const data = `
                <test-case id="1480" name="ServerUpdate" fullname="Mirror.Tests.NetworkIdentityTests.ServerUpdate" methodname="ServerUpdate" classname="Mirror.Tests.NetworkIdentityTests" runstate="Runnable" seed="1748324986" result="Failed" start-time="2020-03-22 14:13:33Z" end-time="2020-03-22 14:13:33Z" duration="0.052314" asserts="0">
    <properties />
    <failure>
      <message><![CDATA[  Expected: 1
  But was:  0
  ]]></message>
      <stack-trace><![CDATA[at Mirror.Tests.NetworkIdentityTests.ServerUpdate () [0x00194] in /github/workspace/Assets/Mirror/Tests/Editor/NetworkIdentityTests.cs:895
  ]]></stack-trace>
    </failure>
    <output><![CDATA[You are trying to create a MonoBehaviour using the 'new' keyword.  This is not allowed.  MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
  Closing connection: connection(0). Received message Mirror.UpdateVarsMessage that required authentication, but the user has not authenticated yet
  Closing connection: connection(0). Received message Mirror.UpdateVarsMessage that required authentication, but the user has not authenticated yet
  ]]></output>
  </test-case>
  `;
  const testCase: any = await parseStringPromise(data, {
    trim: true,
    mergeAttrs: true,
    explicitArray: false,
  });

  const annotation = testCaseAnnotation(testCase["test-case"]);

  expect(annotation).toBeTruthy();

  expect(annotation.path).toContain(
    "Assets/Mirror/Tests/Editor/NetworkIdentityTests.cs"
  );
  expect(annotation.start_line).toBe(895);
  expect(annotation.end_line).toBe(895);
  expect(annotation.title).toBe(
    "Failed test ServerUpdate in Mirror.Tests.NetworkIdentityTests"
  );
  expect(annotation.message).toBe("Expected: 1\n  But was:  0");
  expect(annotation.annotation_level).toBe("failure");
});
Example #2
Source File: nunit.ts    From nunit-reporter with MIT License 6 votes vote down vote up
export async function parseNunit(nunitReport: string): Promise<TestResult> {
  const nunitResults: any = await parseStringPromise(nunitReport, {
    trim: true,
    mergeAttrs: true,
    explicitArray: false,
  });

  const testRun = nunitResults["test-run"];

  const testCases = getTestCases(testRun);
  const failedCases = testCases.filter((tc) => tc.result === "Failed");

  const annotations = failedCases.map(testCaseAnnotation);

  return new TestResult(
    parseInt(testRun.passed),
    parseInt(testRun.failed),
    annotations
  );
}
Example #3
Source File: transformSvgToComponent.ts    From reskript with MIT License 6 votes vote down vote up
parseSVG = async (source: string) => {
    const startOfStartTag = source.indexOf('<svg');
    const endOfStartTag = source.indexOf('>', startOfStartTag);
    const startOfEndTag = source.lastIndexOf('<');
    const startTag = source.slice(startOfStartTag, endOfStartTag + 1);
    const endTag = source.slice(startOfEndTag);
    const body = source.slice(endOfStartTag + 1, startOfEndTag);
    const parsedWrapper = await parseStringPromise(
        startTag + endTag,
        {
            attrNameProcessors: [
                name => {
                    // React有一些属性要换名字,不过应该只有`class`会用在`<svg>`元素上,其它的不处理了
                    if (name === 'class') {
                        return 'className';
                    }

                    return name.replace(/(?:-|_)([a-z])/g, (match, letter) => letter.toUpperCase());
                },
            ],
        }
    );
    return [removeNamespaceAttributes(parsedWrapper.svg.$), body] as const;
}
Example #4
Source File: FurnitureData.ts    From shroom with GNU Lesser General Public License v3.0 6 votes vote down vote up
private async _prepareData() {
    const furniDataString = await this._getFurniData();
    const parsed = await parseStringPromise(furniDataString);

    const typeToInfo: FurnitureMap = {};
    const floorIdToType: IdToTypeMap = {};
    const wallIdToType: IdToTypeMap = {};

    const register = (data: any[], furnitureType: "floor" | "wall") => {
      data.forEach((element) => {
        const type = element.$.classname;
        const id = element.$.id;

        typeToInfo[type] = formatFurnitureData(element);

        if (furnitureType === "floor") {
          if (floorIdToType[id] != null)
            throw new Error(`Floor furniture with id ${id} already exists`);

          floorIdToType[id] = type;
        } else if (furnitureType === "wall") {
          if (wallIdToType[id] != null)
            throw new Error(`Wall furniture with id ${id} already exists`);

          wallIdToType[id] = type;
        }
      });
    };

    register(parsed.furnidata.roomitemtypes[0].furnitype, "wall");
    register(parsed.furnidata.wallitemtypes[0].furnitype, "floor");

    return { typeToInfo, floorIdToType, wallIdToType };
  }
Example #5
Source File: xml-crawler.ts    From vt-api with GNU Affero General Public License v3.0 5 votes vote down vote up
private async parseXml(): Promise<YoutubeVideoObject[]> {
    const parsedString = await parseStringPromise(this.rawXmlData, this.xmlOptions)
      .catch(() => logger.warn(`Channel ${this.channelId} doesn\'t exist.`));
    if (!parsedString || !parsedString.feed.entry?.map) return;
    return parsedString.feed.entry.map(this.parseEntries.bind(this)).sort(this.videoSorter);
  }
Example #6
Source File: main.ts    From ioBroker.luxtronik2 with Apache License 2.0 4 votes vote down vote up
private async handleWsMessageAsync(msg: string): Promise<void> {
        const message: Message = await parseStringPromise(msg);
        this.log.debug(JSON.stringify(message));

        if ('Navigation' in message) {
            if (this.navigationSections.length > 0) {
                return;
            }
            // Reply to the REFRESH command, gives us the structure but no actual data
            for (let i = 0; i < message.Navigation.item.length && i < 2; i++) {
                // only look at the first two items ("Informationen" and "Einstellungen")
                const item = message.Navigation.item[i];
                await this.extendObjectAsync(this.getItemId(item), {
                    type: 'device',
                    common: {
                        name: item.name[0],
                    },
                    native: item as any,
                });
                this.navigationSections.push(item);
            }

            this.requestAllContent();
        } else if ('Content' in message) {
            if (this.isSaving) {
                // the SAVE command gives us the latest "Content", thus we need to ignore this message
                this.isSaving = false;
                if (!this.handleNextUpdate()) {
                    this.requestAllContent();
                }
                return;
            }

            const navigationItem = this.navigationSections[this.currentNavigationSection];
            const navigationId = this.getItemId(navigationItem);
            const sectionIds: string[] = [];
            let shouldSave = false;
            for (let i = 0; i < message.Content.item.length; i++) {
                const section = message.Content.item[i];
                const sectionHandler = this.createHandler(section, navigationId, sectionIds);
                if (!sectionHandler) {
                    continue;
                }
                if (!this.handlers[sectionHandler.id]) {
                    this.handlers[sectionHandler.id] = sectionHandler;
                    await sectionHandler.extendObjectAsync();
                }

                if (sectionHandler instanceof TimeLogSectionHandler) {
                    // time log sections are actually states
                    await sectionHandler.setStateAsync();
                    continue;
                }

                const itemIds: string[] = [];

                for (let j = 0; j < section.item.length; j++) {
                    const item = section.item[j];
                    try {
                        const itemHandler = this.createHandler(item, sectionHandler.id, itemIds);
                        if (!itemHandler) {
                            continue;
                        }
                        if (!this.handlers[itemHandler.id]) {
                            this.log.silly(`Creating ${itemHandler.id}`);
                            await itemHandler.extendObjectAsync();
                            this.handlers[itemHandler.id] = itemHandler;
                        }

                        if (this.requestedUpdates.length === 0) {
                            this.log.silly(`Setting state of ${itemHandler.id}`);
                            await itemHandler.setStateAsync();
                        } else {
                            const updateIndex = this.requestedUpdates.findIndex((ch) => ch.id === itemHandler.id);
                            if (updateIndex >= 0) {
                                const cmd = itemHandler.createSetCommand(this.requestedUpdates[updateIndex].value);
                                this.log.debug(`Sending ${cmd}`);
                                this.getSentry()?.addBreadcrumb({ type: 'http', category: 'ws', data: { url: cmd } });
                                this.webSocket?.send(cmd);
                                this.requestedUpdates.splice(updateIndex);
                                shouldSave = true;
                            }
                        }
                    } catch (error) {
                        this.log.error(`Couldn't handle '${sectionHandler.id}' -> '${item.name[0]}': ${error}`);
                        this.getSentry()?.captureException(error, { extra: { section: sectionHandler.id, item } });
                    }
                }
            }

            if (shouldSave) {
                this.log.debug('Saving');
                this.getSentry()?.addBreadcrumb({ type: 'http', category: 'ws', data: { url: 'SAVE;1' } });
                this.webSocket?.send('SAVE;1');
                this.isSaving = true;
            } else {
                this.requestNextContent();
            }
        }
    }
Example #7
Source File: samlRequest.spec.ts    From node-saml with MIT License 4 votes vote down vote up
describe("SAML request", function () {
  it("Config with Extensions", async function () {
    const config: SamlConfig = {
      entryPoint: "https://wwwexampleIdp.com/saml",
      cert: FAKE_CERT,
      samlAuthnRequestExtensions: {
        "md:RequestedAttribute": {
          "@isRequired": "true",
          "@Name": "Lastname",
          "@xmlns:md": "urn:oasis:names:tc:SAML:2.0:metadata",
        },
        vetuma: {
          "@xmlns": "urn:vetuma:SAML:2.0:extensions",
          LG: {
            "#text": "sv",
          },
        },
      },
      issuer: "onelogin_saml",
    };

    const result = {
      "samlp:AuthnRequest": {
        $: {
          "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
          Version: "2.0",
          ProtocolBinding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
          AssertionConsumerServiceURL: "http://localhost/saml/consume",
          Destination: "https://wwwexampleIdp.com/saml",
        },
        "saml:Issuer": [
          { _: "onelogin_saml", $: { "xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion" } },
        ],
        "samlp:Extensions": [
          {
            $: {
              "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
            },
            "md:RequestedAttribute": [
              {
                $: {
                  isRequired: "true",
                  Name: "Lastname",
                  "xmlns:md": "urn:oasis:names:tc:SAML:2.0:metadata",
                },
              },
            ],
            vetuma: [
              {
                $: { xmlns: "urn:vetuma:SAML:2.0:extensions" },
                LG: ["sv"],
              },
            ],
          },
        ],
        "samlp:NameIDPolicy": [
          {
            $: {
              "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
              Format: "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress",
              AllowCreate: "true",
            },
          },
        ],
        "samlp:RequestedAuthnContext": [
          {
            $: { "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol", Comparison: "exact" },
            "saml:AuthnContextClassRef": [
              {
                _: "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport",
                $: { "xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion" },
              },
            ],
          },
        ],
      },
    };

    const oSAML = new SAML(config);
    return oSAML
      .getAuthorizeFormAsync("http://localhost/saml/consume")
      .then((formBody) => {
        expect(formBody).to.match(/<!DOCTYPE html>[^]*<input.*name="SAMLRequest"[^]*<\/html>/);
        const samlRequestMatchValues = formBody.match(/<input.*name="SAMLRequest" value="([^"]*)"/);
        assertRequired(samlRequestMatchValues?.[1]);
        const encodedSamlRequest = samlRequestMatchValues?.[1];

        let buffer = Buffer.from(encodedSamlRequest, "base64");
        if (!config.skipRequestCompression) {
          buffer = zlib.inflateRawSync(buffer);
        }

        return parseStringPromise(buffer.toString());
      })
      .then((doc) => {
        delete doc["samlp:AuthnRequest"]["$"]["ID"];
        delete doc["samlp:AuthnRequest"]["$"]["IssueInstant"];
        expect(doc).to.deep.equal(result);
      });
  });

  it("AllowCreate defaults to true", async function () {
    const config: SamlConfig = {
      entryPoint: "https://wwwexampleIdp.com/saml",
      cert: FAKE_CERT,
      issuer: "onelogin_saml",
    };

    const result = {
      "samlp:AuthnRequest": {
        $: {
          "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
          Version: "2.0",
          ProtocolBinding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
          AssertionConsumerServiceURL: "http://localhost/saml/consume",
          Destination: "https://wwwexampleIdp.com/saml",
        },
        "saml:Issuer": [
          { _: "onelogin_saml", $: { "xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion" } },
        ],
        "samlp:NameIDPolicy": [
          {
            $: {
              "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
              Format: "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress",
              AllowCreate: "true",
            },
          },
        ],
        "samlp:RequestedAuthnContext": [
          {
            $: { "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol", Comparison: "exact" },
            "saml:AuthnContextClassRef": [
              {
                _: "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport",
                $: { "xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion" },
              },
            ],
          },
        ],
      },
    };

    const oSAML = new SAML(config);
    return oSAML
      .getAuthorizeFormAsync("http://localhost/saml/consume")
      .then((formBody) => {
        expect(formBody).to.match(/<!DOCTYPE html>[^]*<input.*name="SAMLRequest"[^]*<\/html>/);
        const samlRequestMatchValues = formBody.match(/<input.*name="SAMLRequest" value="([^"]*)"/);
        assertRequired(samlRequestMatchValues?.[1]);
        const encodedSamlRequest = samlRequestMatchValues?.[1];

        let buffer = Buffer.from(encodedSamlRequest, "base64");
        if (!config.skipRequestCompression) {
          buffer = zlib.inflateRawSync(buffer);
        }

        return parseStringPromise(buffer.toString());
      })
      .then((doc) => {
        delete doc["samlp:AuthnRequest"]["$"]["ID"];
        delete doc["samlp:AuthnRequest"]["$"]["IssueInstant"];
        expect(doc).to.deep.equal(result);
      });
  });

  it("Config with NameIDPolicy options", async function () {
    const config: SamlConfig = {
      entryPoint: "https://wwwexampleIdp.com/saml",
      cert: FAKE_CERT,
      issuer: "onelogin_saml",
      identifierFormat: "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent",
      allowCreate: false,
      spNameQualifier: "https://exampleaffiliation.com/saml",
    };

    const result = {
      "samlp:AuthnRequest": {
        $: {
          "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
          Version: "2.0",
          ProtocolBinding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
          AssertionConsumerServiceURL: "http://localhost/saml/consume",
          Destination: "https://wwwexampleIdp.com/saml",
        },
        "saml:Issuer": [
          { _: "onelogin_saml", $: { "xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion" } },
        ],
        "samlp:NameIDPolicy": [
          {
            $: {
              "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
              Format: "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent",
              AllowCreate: "false",
              SPNameQualifier: "https://exampleaffiliation.com/saml",
            },
          },
        ],
        "samlp:RequestedAuthnContext": [
          {
            $: { "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol", Comparison: "exact" },
            "saml:AuthnContextClassRef": [
              {
                _: "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport",
                $: { "xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion" },
              },
            ],
          },
        ],
      },
    };

    const oSAML = new SAML(config);
    return oSAML
      .getAuthorizeFormAsync("http://localhost/saml/consume")
      .then((formBody) => {
        expect(formBody).to.match(/<!DOCTYPE html>[^]*<input.*name="SAMLRequest"[^]*<\/html>/);
        const samlRequestMatchValues = formBody.match(/<input.*name="SAMLRequest" value="([^"]*)"/);
        assertRequired(samlRequestMatchValues?.[1]);
        const encodedSamlRequest = samlRequestMatchValues?.[1];

        let buffer = Buffer.from(encodedSamlRequest, "base64");
        if (!config.skipRequestCompression) {
          buffer = zlib.inflateRawSync(buffer);
        }

        return parseStringPromise(buffer.toString());
      })
      .then((doc) => {
        delete doc["samlp:AuthnRequest"]["$"]["ID"];
        delete doc["samlp:AuthnRequest"]["$"]["IssueInstant"];
        expect(doc).to.deep.equal(result);
      });
  });

  it("Config with forceAuthn and passive", async function () {
    const config: SamlConfig = {
      entryPoint: "https://wwwexampleIdp.com/saml",
      cert: FAKE_CERT,
      issuer: "onelogin_saml",
      forceAuthn: false,
      passive: true,
    };

    const result = {
      "samlp:AuthnRequest": {
        $: {
          "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
          Version: "2.0",
          ProtocolBinding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
          AssertionConsumerServiceURL: "http://localhost/saml/consume",
          Destination: "https://wwwexampleIdp.com/saml",
          IsPassive: "true",
        },
        "saml:Issuer": [
          { _: "onelogin_saml", $: { "xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion" } },
        ],
        "samlp:NameIDPolicy": [
          {
            $: {
              "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
              Format: "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress",
              AllowCreate: "true",
            },
          },
        ],
        "samlp:RequestedAuthnContext": [
          {
            $: { "xmlns:samlp": "urn:oasis:names:tc:SAML:2.0:protocol", Comparison: "exact" },
            "saml:AuthnContextClassRef": [
              {
                _: "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport",
                $: { "xmlns:saml": "urn:oasis:names:tc:SAML:2.0:assertion" },
              },
            ],
          },
        ],
      },
    };

    const oSAML = new SAML(config);
    oSAML
      .getAuthorizeFormAsync("http://localhost/saml/consume")
      .then((formBody) => {
        expect(formBody).to.match(/<!DOCTYPE html>[^]*<input.*name="SAMLRequest"[^]*<\/html>/);
        const samlRequestMatchValues = formBody.match(/<input.*name="SAMLRequest" value="([^"]*)"/);
        assertRequired(samlRequestMatchValues?.[1]);
        const encodedSamlRequest = samlRequestMatchValues?.[1];

        let buffer = Buffer.from(encodedSamlRequest, "base64");
        if (!config.skipRequestCompression) {
          buffer = zlib.inflateRawSync(buffer);
        }

        return parseStringPromise(buffer.toString());
      })
      .then((doc) => {
        delete doc["samlp:AuthnRequest"]["$"]["ID"];
        delete doc["samlp:AuthnRequest"]["$"]["IssueInstant"];
        expect(doc).to.deep.equal(result);
      });
  });

  it("should throw error when samlAuthnRequestExtensions is not a object", async function () {
    const config: SamlConfig = {
      entryPoint: "https://wwwexampleIdp.com/saml",
      cert: FAKE_CERT,
      samlAuthnRequestExtensions: "anyvalue" as unknown as Record<string, unknown>,
      issuer: "onesaml_login",
    };

    const oSAML = new SAML(config);
    await assert.rejects(oSAML.getAuthorizeFormAsync("http://localhost/saml/consume"), {
      message: "samlAuthnRequestExtensions should be Object",
    });
  });
});