<commit_before>import standardSqlFormatter from "xr/sqlFormatter/standardSqlFormatter";

describe("standardSqlFormatter", function() {
    it("formats simple SELECT query", function() {
        const result = standardSqlFormatter.format("SELECT count(*),'Column1' FROM `Table1`;");
        expect(result).toBe(
            "SELECT\n" +
            "  count(*),\n" +
            "  'Column1'\n" +
            "FROM\n" +
            "  `Table1`;\n"
        );
    });

    it("formats SELECT query with WHERE, GROUP/ORDER BY and LIMIT words", function() {
        const result = standardSqlFormatter.format(
            "SELECT count(*),'Column1',`Testing`, `Testing Three` FROM `Table1` WHERE Column1 = 'testing' " +
            "AND ( (`Column2` = `Column3` OR Column4 >= NOW()) ) GROUP BY Column1 ORDER BY Column3 DESC LIMIT 5,10;"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  count(*),\n" +
            "  'Column1',\n" +
            "  `Testing`,\n" +
            "  `Testing Three`\n" +
            "FROM\n" +
            "  `Table1`\n" +
            "WHERE\n" +
            "  Column1 = 'testing'\n" +
            "  AND (\n" +
            "    (\n" +
            "      `Column2` = `Column3`\n" +
            "      OR Column4 >= NOW()\n" +
            "    )\n" +
            "  )\n" +
            "GROUP BY\n" +
            "  Column1\n" +
            "ORDER BY\n" +
            "  Column3 DESC\n" +
            "LIMIT\n" +
            "  5, 10;\n"
        );
    });

    it("formats SELECT query with LIMIT and OFFSET", function() {
        const result = standardSqlFormatter.format(
            "SELECT avg(paycheck) FROM `Table1` LIMIT 5,10 OFFSET 20;"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  avg(paycheck)\n" +
            "FROM\n" +
            "  `Table1`\n" +
            "LIMIT\n" +
            "  5, 10 OFFSET 20;\n"
        );
    });

    it("formats SELECT query with SELECT query inside it", function() {
        const result = standardSqlFormatter.format(
            "SELECT *, SUM(*) AS sum FROM (SELECT * FROM `Posts` LIMIT 30) GROUP BY `Category`"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  *,\n" +
            "  SUM(*) AS sum\n" +
            "FROM\n" +
            "  (\n" +
            "    SELECT\n" +
            "      *\n" +
            "    FROM\n" +
            "      `Posts`\n" +
            "    LIMIT\n" +
            "      30\n" +
            "  )\n" +
            "GROUP BY\n" +
            "  `Category`\n"
        );
    });

    it("formats SELECT query with INNER JOIN", function() {
        const result = standardSqlFormatter.format(
            "SELECT customer_id.from, COUNT(order_id) AS total FROM customers " +
            "INNER JOIN orders ON customers.customer_id = orders.customer_id;"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  customer_id.from,\n" +
            "  COUNT(order_id) AS total\n" +
            "FROM\n" +
            "  customers\n" +
            "  INNER JOIN orders ON customers.customer_id = orders.customer_id;\n"
        );
    });

    it("formats SELECT query with different comments", function() {
        const result = standardSqlFormatter.format(
            "SELECT\n" +
            "/* This is a block comment\n" +
            "*/\n" +
            "* FROM\n" +
            "-- This is another comment\n" +
            "MyTable # One final comment\n" +

            "WHERE 1 = 2;"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  /* This is a block comment\n" +
            "  */\n" +
            "  *\n" +
            "FROM\n" +
            "  -- This is another comment\n" +
            "  MyTable # One final comment\n" +
            "WHERE\n" +
            "  1 = 2;\n"
        );
    });

    it("formats SELECT query with different variable types", function() {
        const result = standardSqlFormatter.format(
            "SELECT @variable, @'variable name';"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  @variable,\n" +
            "  @'variable name';\n"
        );
    });

    it("formats simple INSERT query", function() {
        const result = standardSqlFormatter.format(
            "INSERT INTO Customers (ID, MoneyBalance, Address, City) VALUES (12,-123.4, `Skagen 2111`,'Stavanger');"
        );
        expect(result).toBe(
            "INSERT INTO Customers (ID, MoneyBalance, Address, City)\n" +
            "VALUES\n" +
            "  (\n" +
            "    12, -123.4, `Skagen 2111`, 'Stavanger'\n" +
            "  );\n"
        );
    });

    it("formats long INSERT query including SELECT, IF and INNER JOIN parts", function() {
        const result = standardSqlFormatter.format(
            "INSERT INTO `PREFIX_specific_price` (`id_product`, `id_shop`, `id_currency`, `id_country`, `id_group`, `priority`, " +
            "`price`, `from_quantity`, `reduction`,   `reduction_type`, `from`, `to`) (" +
            "SELECT dq.`id_product`, 1, 1,0,1, 0, 0.00, dq.`quantity`, IF(dq.`id_discount_type` = 2, dq.`value`, dq.`value` / 100)," +
            "IF (dq.`id_discount_type` = 2, 'amount', 'percentage'), '0000-00-00 00:00:00', '0000-00-00 00:00:00' " +
            "FROM `PREFIX_discount_quantity` dq INNER JOIN `PREFIX_product` p ON (p.`id_product` = dq.`id_product`));"
        );
        expect(result).toBe(
            "INSERT INTO `PREFIX_specific_price` (\n" +
            "  `id_product`, `id_shop`, `id_currency`,\n" +
            "  `id_country`, `id_group`, `priority`,\n" +
            "  `price`, `from_quantity`, `reduction`,\n" +
            "  `reduction_type`, `from`, `to`\n" +
            ") (\n" +
            "  SELECT\n" +
            "    dq.`id_product`,\n" +
            "    1,\n" +
            "    1,\n" +
            "    0,\n" +
            "    1,\n" +
            "    0,\n" +
            "    0.00,\n" +
            "    dq.`quantity`,\n" +
            "    IF(\n" +
            "      dq.`id_discount_type` = 2, dq.`value`,\n" +
            "      dq.`value` / 100\n" +
            "    ),\n" +
            "    IF (\n" +
            "      dq.`id_discount_type` = 2, 'amount',\n" +
            "      'percentage'\n" +
            "    ),\n" +
            "    '0000-00-00 00:00:00',\n" +
            "    '0000-00-00 00:00:00'\n" +
            "  FROM\n" +
            "    `PREFIX_discount_quantity` dq\n" +
            "    INNER JOIN `PREFIX_product` p ON (p.`id_product` = dq.`id_product`)\n" +
            ");\n"
        );
    });

    it("formats simple UPDATE query", function() {
        const result = standardSqlFormatter.format(
            "uPDATE Customers set ContactName='Alfred Schmidt', City='Hamburg' WHERE CustomerName='Alfreds Futterkiste';"
        );
        expect(result).toBe(
            "uPDATE\n" +
            "  Customers\n" +
            "set\n" +
            "  ContactName = 'Alfred Schmidt',\n" +
            "  City = 'Hamburg'\n" +
            "WHERE\n" +
            "  CustomerName = 'Alfreds Futterkiste';\n"
        );
    });

    it("formats simple DELETE query", function() {
        const result = standardSqlFormatter.format(
            "DELETE FROM Customers WHERE CustomerName='Alfred' AND Phone=5002132;"
        );
        expect(result).toBe(
            "DELETE FROM\n" +
            "  Customers\n" +
            "WHERE\n" +
            "  CustomerName = 'Alfred'\n" +
            "  AND Phone = 5002132;\n"
        );
    });

    it("formats simple DROP query", function() {
        const result = standardSqlFormatter.format(
            "DROP TABLE IF EXISTS `admin_role`;"
        );
        expect(result).toBe(
            "DROP\n" +
            "  TABLE IF EXISTS `admin_role`;\n"
        );
    });

    it("formats uncomplete query", function() {
        const result = standardSqlFormatter.format("SELECT count(");
        expect(result).toBe(
            "SELECT\n" +
            "  count(\n"
        );
    });

    it("formats query that ends with open comment", function() {
        const result = standardSqlFormatter.format("SELECT count(*)\n/*Comment");
        expect(result).toBe(
            "SELECT\n" +
            "  count(*)\n" +
            "  /*Comment\n"
        );
    });

    it("formats UPDATE query with AS part", function() {
        const result = standardSqlFormatter.format(
            "UPDATE customers SET totalorders = ordersummary.total  FROM ( SELECT * FROM bank) As ordersummary"
        );
        expect(result).toBe(
            "UPDATE\n" +
            "  customers\n" +
            "SET\n" +
            "  totalorders = ordersummary.total\n" +
            "FROM\n" +
            "  (\n" +
            "    SELECT\n" +
            "      *\n" +
            "    FROM\n" +
            "      bank\n" +
            "  ) As ordersummary\n"
        );
    });

    it("formats top-level and newline multi-word reserved words with inconsistent spacing", function() {
        const result = standardSqlFormatter.format("SELECT * FROM foo LEFT \t OUTER  \n JOIN bar ORDER \n BY blah");
        expect(result).toBe(
            "SELECT\n" +
            "  *\n" +
            "FROM\n" +
            "  foo\n" +
            "  LEFT OUTER JOIN bar\n" +
            "ORDER BY\n" +
            "  blah\n"
        );
    });

    it("formats single-char operators", function() {
        expect(standardSqlFormatter.format("foo = bar")).toBe("foo = bar\n");
        expect(standardSqlFormatter.format("foo < bar")).toBe("foo < bar\n");
        expect(standardSqlFormatter.format("foo > bar")).toBe("foo > bar\n");
        expect(standardSqlFormatter.format("foo + bar")).toBe("foo + bar\n");
        expect(standardSqlFormatter.format("foo - bar")).toBe("foo - bar\n");
        expect(standardSqlFormatter.format("foo * bar")).toBe("foo * bar\n");
        expect(standardSqlFormatter.format("foo / bar")).toBe("foo / bar\n");
        expect(standardSqlFormatter.format("foo % bar")).toBe("foo % bar\n");
    });

    it("formats multi-char operators", function() {
        expect(standardSqlFormatter.format("foo != bar")).toBe("foo != bar\n");
        expect(standardSqlFormatter.format("foo <> bar")).toBe("foo <> bar\n");
        expect(standardSqlFormatter.format("foo == bar")).toBe("foo == bar\n"); // N1QL
        expect(standardSqlFormatter.format("foo || bar")).toBe("foo || bar\n"); // Oracle, Postgres, N1QL string concat

        expect(standardSqlFormatter.format("foo <= bar")).toBe("foo <= bar\n");
        expect(standardSqlFormatter.format("foo >= bar")).toBe("foo >= bar\n");

        expect(standardSqlFormatter.format("foo !< bar")).toBe("foo !< bar\n");
        expect(standardSqlFormatter.format("foo !> bar")).toBe("foo !> bar\n");
    });

    it("formats logical operators", function() {
        expect(standardSqlFormatter.format("foo ALL bar")).toBe("foo ALL bar\n");
        expect(standardSqlFormatter.format("foo = ANY (1, 2, 3)")).toBe("foo = ANY (1, 2, 3)\n");
        expect(standardSqlFormatter.format("EXISTS bar")).toBe("EXISTS bar\n");
        expect(standardSqlFormatter.format("foo IN (1, 2, 3)")).toBe("foo IN (1, 2, 3)\n");
        expect(standardSqlFormatter.format("foo LIKE 'hello%'")).toBe("foo LIKE 'hello%'\n");
        expect(standardSqlFormatter.format("foo IS NULL")).toBe("foo IS NULL\n");
        expect(standardSqlFormatter.format("UNIQUE foo")).toBe("UNIQUE foo\n");
    });

    it("formats AND/OR operators", function() {
        expect(standardSqlFormatter.format("foo BETWEEN bar AND baz")).toBe("foo BETWEEN bar\nAND baz\n");
        expect(standardSqlFormatter.format("foo AND bar")).toBe("foo\nAND bar\n");
        expect(standardSqlFormatter.format("foo OR bar")).toBe("foo\nOR bar\n");
    });
});
<commit_msg>XR-3710 Add tests for SQL strings<commit_after>import standardSqlFormatter from "xr/sqlFormatter/standardSqlFormatter";

describe("standardSqlFormatter", function() {
    it("formats simple SELECT query", function() {
        const result = standardSqlFormatter.format("SELECT count(*),'Column1' FROM `Table1`;");
        expect(result).toBe(
            "SELECT\n" +
            "  count(*),\n" +
            "  'Column1'\n" +
            "FROM\n" +
            "  `Table1`;\n"
        );
    });

    it("formats SELECT query with WHERE, GROUP/ORDER BY and LIMIT words", function() {
        const result = standardSqlFormatter.format(
            "SELECT count(*),'Column1',`Testing`, `Testing Three` FROM `Table1` WHERE Column1 = 'testing' " +
            "AND ( (`Column2` = `Column3` OR Column4 >= NOW()) ) GROUP BY Column1 ORDER BY Column3 DESC LIMIT 5,10;"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  count(*),\n" +
            "  'Column1',\n" +
            "  `Testing`,\n" +
            "  `Testing Three`\n" +
            "FROM\n" +
            "  `Table1`\n" +
            "WHERE\n" +
            "  Column1 = 'testing'\n" +
            "  AND (\n" +
            "    (\n" +
            "      `Column2` = `Column3`\n" +
            "      OR Column4 >= NOW()\n" +
            "    )\n" +
            "  )\n" +
            "GROUP BY\n" +
            "  Column1\n" +
            "ORDER BY\n" +
            "  Column3 DESC\n" +
            "LIMIT\n" +
            "  5, 10;\n"
        );
    });

    it("formats SELECT query with LIMIT and OFFSET", function() {
        const result = standardSqlFormatter.format(
            "SELECT avg(paycheck) FROM `Table1` LIMIT 5,10 OFFSET 20;"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  avg(paycheck)\n" +
            "FROM\n" +
            "  `Table1`\n" +
            "LIMIT\n" +
            "  5, 10 OFFSET 20;\n"
        );
    });

    it("formats SELECT query with SELECT query inside it", function() {
        const result = standardSqlFormatter.format(
            "SELECT *, SUM(*) AS sum FROM (SELECT * FROM `Posts` LIMIT 30) GROUP BY `Category`"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  *,\n" +
            "  SUM(*) AS sum\n" +
            "FROM\n" +
            "  (\n" +
            "    SELECT\n" +
            "      *\n" +
            "    FROM\n" +
            "      `Posts`\n" +
            "    LIMIT\n" +
            "      30\n" +
            "  )\n" +
            "GROUP BY\n" +
            "  `Category`\n"
        );
    });

    it("formats SELECT query with INNER JOIN", function() {
        const result = standardSqlFormatter.format(
            "SELECT customer_id.from, COUNT(order_id) AS total FROM customers " +
            "INNER JOIN orders ON customers.customer_id = orders.customer_id;"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  customer_id.from,\n" +
            "  COUNT(order_id) AS total\n" +
            "FROM\n" +
            "  customers\n" +
            "  INNER JOIN orders ON customers.customer_id = orders.customer_id;\n"
        );
    });

    it("formats SELECT query with different comments", function() {
        const result = standardSqlFormatter.format(
            "SELECT\n" +
            "/* This is a block comment\n" +
            "*/\n" +
            "* FROM\n" +
            "-- This is another comment\n" +
            "MyTable # One final comment\n" +

            "WHERE 1 = 2;"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  /* This is a block comment\n" +
            "  */\n" +
            "  *\n" +
            "FROM\n" +
            "  -- This is another comment\n" +
            "  MyTable # One final comment\n" +
            "WHERE\n" +
            "  1 = 2;\n"
        );
    });

    it("formats SELECT query with different variable types", function() {
        const result = standardSqlFormatter.format(
            "SELECT @variable, @'variable name';"
        );
        expect(result).toBe(
            "SELECT\n" +
            "  @variable,\n" +
            "  @'variable name';\n"
        );
    });

    it("formats simple INSERT query", function() {
        const result = standardSqlFormatter.format(
            "INSERT INTO Customers (ID, MoneyBalance, Address, City) VALUES (12,-123.4, `Skagen 2111`,'Stavanger');"
        );
        expect(result).toBe(
            "INSERT INTO Customers (ID, MoneyBalance, Address, City)\n" +
            "VALUES\n" +
            "  (\n" +
            "    12, -123.4, `Skagen 2111`, 'Stavanger'\n" +
            "  );\n"
        );
    });

    it("formats long INSERT query including SELECT, IF and INNER JOIN parts", function() {
        const result = standardSqlFormatter.format(
            "INSERT INTO `PREFIX_specific_price` (`id_product`, `id_shop`, `id_currency`, `id_country`, `id_group`, `priority`, " +
            "`price`, `from_quantity`, `reduction`,   `reduction_type`, `from`, `to`) (" +
            "SELECT dq.`id_product`, 1, 1,0,1, 0, 0.00, dq.`quantity`, IF(dq.`id_discount_type` = 2, dq.`value`, dq.`value` / 100)," +
            "IF (dq.`id_discount_type` = 2, 'amount', 'percentage'), '0000-00-00 00:00:00', '0000-00-00 00:00:00' " +
            "FROM `PREFIX_discount_quantity` dq INNER JOIN `PREFIX_product` p ON (p.`id_product` = dq.`id_product`));"
        );
        expect(result).toBe(
            "INSERT INTO `PREFIX_specific_price` (\n" +
            "  `id_product`, `id_shop`, `id_currency`,\n" +
            "  `id_country`, `id_group`, `priority`,\n" +
            "  `price`, `from_quantity`, `reduction`,\n" +
            "  `reduction_type`, `from`, `to`\n" +
            ") (\n" +
            "  SELECT\n" +
            "    dq.`id_product`,\n" +
            "    1,\n" +
            "    1,\n" +
            "    0,\n" +
            "    1,\n" +
            "    0,\n" +
            "    0.00,\n" +
            "    dq.`quantity`,\n" +
            "    IF(\n" +
            "      dq.`id_discount_type` = 2, dq.`value`,\n" +
            "      dq.`value` / 100\n" +
            "    ),\n" +
            "    IF (\n" +
            "      dq.`id_discount_type` = 2, 'amount',\n" +
            "      'percentage'\n" +
            "    ),\n" +
            "    '0000-00-00 00:00:00',\n" +
            "    '0000-00-00 00:00:00'\n" +
            "  FROM\n" +
            "    `PREFIX_discount_quantity` dq\n" +
            "    INNER JOIN `PREFIX_product` p ON (p.`id_product` = dq.`id_product`)\n" +
            ");\n"
        );
    });

    it("formats simple UPDATE query", function() {
        const result = standardSqlFormatter.format(
            "uPDATE Customers set ContactName='Alfred Schmidt', City='Hamburg' WHERE CustomerName='Alfreds Futterkiste';"
        );
        expect(result).toBe(
            "uPDATE\n" +
            "  Customers\n" +
            "set\n" +
            "  ContactName = 'Alfred Schmidt',\n" +
            "  City = 'Hamburg'\n" +
            "WHERE\n" +
            "  CustomerName = 'Alfreds Futterkiste';\n"
        );
    });

    it("formats simple DELETE query", function() {
        const result = standardSqlFormatter.format(
            "DELETE FROM Customers WHERE CustomerName='Alfred' AND Phone=5002132;"
        );
        expect(result).toBe(
            "DELETE FROM\n" +
            "  Customers\n" +
            "WHERE\n" +
            "  CustomerName = 'Alfred'\n" +
            "  AND Phone = 5002132;\n"
        );
    });

    it("formats simple DROP query", function() {
        const result = standardSqlFormatter.format(
            "DROP TABLE IF EXISTS `admin_role`;"
        );
        expect(result).toBe(
            "DROP\n" +
            "  TABLE IF EXISTS `admin_role`;\n"
        );
    });

    it("formats uncomplete query", function() {
        const result = standardSqlFormatter.format("SELECT count(");
        expect(result).toBe(
            "SELECT\n" +
            "  count(\n"
        );
    });

    it("formats query that ends with open comment", function() {
        const result = standardSqlFormatter.format("SELECT count(*)\n/*Comment");
        expect(result).toBe(
            "SELECT\n" +
            "  count(*)\n" +
            "  /*Comment\n"
        );
    });

    it("formats UPDATE query with AS part", function() {
        const result = standardSqlFormatter.format(
            "UPDATE customers SET totalorders = ordersummary.total  FROM ( SELECT * FROM bank) As ordersummary"
        );
        expect(result).toBe(
            "UPDATE\n" +
            "  customers\n" +
            "SET\n" +
            "  totalorders = ordersummary.total\n" +
            "FROM\n" +
            "  (\n" +
            "    SELECT\n" +
            "      *\n" +
            "    FROM\n" +
            "      bank\n" +
            "  ) As ordersummary\n"
        );
    });

    it("formats top-level and newline multi-word reserved words with inconsistent spacing", function() {
        const result = standardSqlFormatter.format("SELECT * FROM foo LEFT \t OUTER  \n JOIN bar ORDER \n BY blah");
        expect(result).toBe(
            "SELECT\n" +
            "  *\n" +
            "FROM\n" +
            "  foo\n" +
            "  LEFT OUTER JOIN bar\n" +
            "ORDER BY\n" +
            "  blah\n"
        );
    });

    it("formats single-char operators", function() {
        expect(standardSqlFormatter.format("foo = bar")).toBe("foo = bar\n");
        expect(standardSqlFormatter.format("foo < bar")).toBe("foo < bar\n");
        expect(standardSqlFormatter.format("foo > bar")).toBe("foo > bar\n");
        expect(standardSqlFormatter.format("foo + bar")).toBe("foo + bar\n");
        expect(standardSqlFormatter.format("foo - bar")).toBe("foo - bar\n");
        expect(standardSqlFormatter.format("foo * bar")).toBe("foo * bar\n");
        expect(standardSqlFormatter.format("foo / bar")).toBe("foo / bar\n");
        expect(standardSqlFormatter.format("foo % bar")).toBe("foo % bar\n");
    });

    it("formats multi-char operators", function() {
        expect(standardSqlFormatter.format("foo != bar")).toBe("foo != bar\n");
        expect(standardSqlFormatter.format("foo <> bar")).toBe("foo <> bar\n");
        expect(standardSqlFormatter.format("foo == bar")).toBe("foo == bar\n"); // N1QL
        expect(standardSqlFormatter.format("foo || bar")).toBe("foo || bar\n"); // Oracle, Postgres, N1QL string concat

        expect(standardSqlFormatter.format("foo <= bar")).toBe("foo <= bar\n");
        expect(standardSqlFormatter.format("foo >= bar")).toBe("foo >= bar\n");

        expect(standardSqlFormatter.format("foo !< bar")).toBe("foo !< bar\n");
        expect(standardSqlFormatter.format("foo !> bar")).toBe("foo !> bar\n");
    });

    it("formats logical operators", function() {
        expect(standardSqlFormatter.format("foo ALL bar")).toBe("foo ALL bar\n");
        expect(standardSqlFormatter.format("foo = ANY (1, 2, 3)")).toBe("foo = ANY (1, 2, 3)\n");
        expect(standardSqlFormatter.format("EXISTS bar")).toBe("EXISTS bar\n");
        expect(standardSqlFormatter.format("foo IN (1, 2, 3)")).toBe("foo IN (1, 2, 3)\n");
        expect(standardSqlFormatter.format("foo LIKE 'hello%'")).toBe("foo LIKE 'hello%'\n");
        expect(standardSqlFormatter.format("foo IS NULL")).toBe("foo IS NULL\n");
        expect(standardSqlFormatter.format("UNIQUE foo")).toBe("UNIQUE foo\n");
    });

    it("formats AND/OR operators", function() {
        expect(standardSqlFormatter.format("foo BETWEEN bar AND baz")).toBe("foo BETWEEN bar\nAND baz\n");
        expect(standardSqlFormatter.format("foo AND bar")).toBe("foo\nAND bar\n");
        expect(standardSqlFormatter.format("foo OR bar")).toBe("foo\nOR bar\n");
    });

    it("recognizes strings", function() {
        expect(standardSqlFormatter.format("\"foo JOIN bar\"")).toBe("\"foo JOIN bar\"\n");
        expect(standardSqlFormatter.format("'foo JOIN bar'")).toBe("'foo JOIN bar'\n");
        expect(standardSqlFormatter.format("`foo JOIN bar`")).toBe("`foo JOIN bar`\n");
        expect(standardSqlFormatter.format("[foo JOIN bar]")).toBe("[foo JOIN bar]\n");
    });

    it("recognizes escaped strings", function() {
        expect(standardSqlFormatter.format("\"foo \\\" JOIN bar\"")).toBe("\"foo \\\" JOIN bar\"\n");
        expect(standardSqlFormatter.format("'foo \\' JOIN bar'")).toBe("'foo \\' JOIN bar'\n");
        expect(standardSqlFormatter.format("`foo `` JOIN bar`")).toBe("`foo `` JOIN bar`\n");
        expect(standardSqlFormatter.format("[foo ]] JOIN bar]")).toBe("[foo ]] JOIN bar]\n");
    });
});
<|endoftext|>


<commit_before>import Player from './components/Player';
import Video from './components/Video';
import BigPlayButton from './components/BigPlayButton';
import LoadingSpinner from './components/LoadingSpinner';
import PosterImage from './components/PosterImage';
import Slider from './components/Slider';
import Bezel from './components/Bezel';
import Shortcut from './components/Shortcut';

import ControlBar from './components/control-bar/ControlBar';
import PlayToggle from './components/control-bar/PlayToggle';
import ForwardControl from './components/control-bar/ForwardControl';
import ReplayControl from './components/control-bar/ReplayControl';
import FullscreenToggle from './components/control-bar/FullscreenToggle';
import ProgressControl from './components/control-bar/ProgressControl';
import SeekBar from './components/control-bar/SeekBar';
import PlayProgressBar from './components/control-bar/PlayProgressBar';
import LoadProgressBar from './components/control-bar/LoadProgressBar';
import MouseTimeDisplay from './components/control-bar/MouseTimeDisplay';
import VolumeMenuButton from './components/control-bar/VolumeMenuButton';
import PlaybackRateMenuButton from './components/control-bar/PlaybackRateMenuButton';
import PlaybackRate from './components/control-bar/PlaybackRate';

import RemainingTimeDisplay from './components/time-controls/RemainingTimeDisplay';
import CurrentTimeDisplay from './components/time-controls/CurrentTimeDisplay';
import DurationDisplay from './components/time-controls/DurationDisplay';
import TimeDivider from './components/time-controls/TimeDivider';
import * as playerActions from './actions/player';
import * as videoActions from './actions/video';
import { playerReducer, operationReducer } from './reducers';

export {
  Player,
  Video,
  BigPlayButton,
  LoadingSpinner,
  PosterImage,
  Bezel,
  Shortcut,
  ControlBar,
  PlayToggle,
  ForwardControl,
  ReplayControl,
  FullscreenToggle,
  ProgressControl,
  SeekBar,
  Slider,
  PlayProgressBar,
  LoadProgressBar,
  MouseTimeDisplay,
  RemainingTimeDisplay,
  CurrentTimeDisplay,
  DurationDisplay,
  TimeDivider,
  VolumeMenuButton,
  PlaybackRateMenuButton,
  PlaybackRate,
  playerActions,
  videoActions,
  playerReducer,
  operationReducer
};
<commit_msg>feat: expose MenuButton<commit_after>import Player from './components/Player';
import Video from './components/Video';
import BigPlayButton from './components/BigPlayButton';
import LoadingSpinner from './components/LoadingSpinner';
import PosterImage from './components/PosterImage';
import Slider from './components/Slider';
import Bezel from './components/Bezel';
import Shortcut from './components/Shortcut';

import ControlBar from './components/control-bar/ControlBar';
import PlayToggle from './components/control-bar/PlayToggle';
import ForwardControl from './components/control-bar/ForwardControl';
import ReplayControl from './components/control-bar/ReplayControl';
import FullscreenToggle from './components/control-bar/FullscreenToggle';
import ProgressControl from './components/control-bar/ProgressControl';
import SeekBar from './components/control-bar/SeekBar';
import PlayProgressBar from './components/control-bar/PlayProgressBar';
import LoadProgressBar from './components/control-bar/LoadProgressBar';
import MouseTimeDisplay from './components/control-bar/MouseTimeDisplay';
import VolumeMenuButton from './components/control-bar/VolumeMenuButton';
import PlaybackRateMenuButton from './components/control-bar/PlaybackRateMenuButton';
import PlaybackRate from './components/control-bar/PlaybackRate';

import RemainingTimeDisplay from './components/time-controls/RemainingTimeDisplay';
import CurrentTimeDisplay from './components/time-controls/CurrentTimeDisplay';
import DurationDisplay from './components/time-controls/DurationDisplay';
import TimeDivider from './components/time-controls/TimeDivider';

import MenuButton from './components/menu/MenuButton';

import * as playerActions from './actions/player';
import * as videoActions from './actions/video';
import { playerReducer, operationReducer } from './reducers';

export {
  Player,
  Video,
  BigPlayButton,
  LoadingSpinner,
  PosterImage,
  Bezel,
  Shortcut,
  ControlBar,
  PlayToggle,
  ForwardControl,
  ReplayControl,
  FullscreenToggle,
  ProgressControl,
  SeekBar,
  Slider,
  PlayProgressBar,
  LoadProgressBar,
  MouseTimeDisplay,
  RemainingTimeDisplay,
  CurrentTimeDisplay,
  DurationDisplay,
  TimeDivider,
  VolumeMenuButton,
  PlaybackRateMenuButton,
  PlaybackRate,
  MenuButton,
  playerActions,
  videoActions,
  playerReducer,
  operationReducer
};
<|endoftext|>


<commit_before>import _ from 'lodash';
import Long from 'long';
import { createMessage } from './utils';

class BaseConstructor {
    static generics = {
        int: 'Int',
        bool: 'Bool',
        long: 'Long',
        uint: 'UInt',
        short: 'Short',
        ulong: 'ULong',
        float: 'Float',
        bytes: 'Bytes',
        string: 'String',
        ushort: 'UShort',
        double: 'Double'
    };

    static validate(header, ids) {
        let found = false;

        header = header.readUInt32LE(0);

        for(let i = 0; i < ids.length; i++) {
            if(ids[i] != header) {
                continue;
            }

            found = true;
            break;
        }

        return found;
    }

    static isGenericType(type) {
        return this.generics.hasOwnProperty(type);
    }

    static isVectorType(type) {
        return type.substring(0, 6) == 'Vector';
    }

    static isTypeReference(name) {
        if(name.indexOf('.') > -1) {
            name = this.skipDots(name);
        }
        return _.upperCase(name.charAt(0)) == name.charAt(0);
    }

    static isConstructorReference(name) {
        if(name.indexOf('.') > -1) {
            name = this.skipDots(name);
        }
        return _.lowerCase(name.charAt(0)) == name.charAt(0);
    }

    static skipDots(name) {
        const dotIndex = name.indexOf('.');

        if(dotIndex > -1) {
            return this.skipDots(name.substring(dotIndex + 1));
        }

        return name;
    }

    static getConstructorName(name) {
        return _.upperFirst(this.skipDots(name));
    }

    static onError(...args) {
        throw new Error(createMessage(...args));
    }

    onError(...args) {
        return BaseConstructor.onError(...args);
    }

    _expect(property, value, type) {
        this.onError(
            'Invalid type for %s "%s". ',
            _.isNumber(property) ? 'vector index' : 'param',
            property,

            'Expected type %s but got %s instead.',
            type,
            typeof value,

            'Check constructor: %s',
            this._name
        );
    }

    _validateGenericProperty(property, value, type) {
        switch(type) {
        case 'int':
        case 'uint':
        case 'float':
        case 'double':
            if(_.isNumber(value)) {
                break;
            }

            this._expect(property, value, 'number');
            break;

        case 'bytes':
            if(Buffer.isBuffer(value)) {
                break;
            }

            this._expect(property, value, 'Buffer');
            break;

        case 'long':
        case 'ulong':
            if(_.isNumber(value) || Long.isLong(value)) {
                break;
            }
            if(_.isString(value)) {
                let padding = value.substring(0, 2);
                const paddingLength = value.length % 2;

                if(padding == '0x' && paddingLength != 0) {
                    padding = value.substring(2);

                    for(let i = 0; i < paddingLength; i++) {
                        padding = '0' + padding;
                    }

                    this.onError(
                        'Invalid value for property "%s". ', property,
                        'Hexadecimal strings must have even length. Given: %s. ', value,
                        'Try adding zero padding: 0x%s', padding
                    );
                    break;
                }
                break;
            }
            this._expect(property, value, 'number or string');
            break;

        case 'bool':
            if(_.isBoolean(value)) {
                break;
            }

            this._expect(property, value, 'boolean');
            break;

        case 'string':
            if(_.isString(value)) {
                break;
            }

            this._expect(property, value, 'string');
            break;

        default:
            this.onError('unhandled type of %s', type);
        }
    }
}

export default BaseConstructor;
<commit_msg>src/BaseConstructor.js: add validation for "short" and "ushort"<commit_after>import _ from 'lodash';
import Long from 'long';
import { createMessage } from './utils';

class BaseConstructor {
    static generics = {
        int: 'Int',
        bool: 'Bool',
        long: 'Long',
        uint: 'UInt',
        short: 'Short',
        ulong: 'ULong',
        float: 'Float',
        bytes: 'Bytes',
        string: 'String',
        ushort: 'UShort',
        double: 'Double'
    };

    static validate(header, ids) {
        let found = false;

        header = header.readUInt32LE(0);

        for(let i = 0; i < ids.length; i++) {
            if(ids[i] != header) {
                continue;
            }

            found = true;
            break;
        }

        return found;
    }

    static isGenericType(type) {
        return this.generics.hasOwnProperty(type);
    }

    static isVectorType(type) {
        return type.substring(0, 6) == 'Vector';
    }

    static isTypeReference(name) {
        if(name.indexOf('.') > -1) {
            name = this.skipDots(name);
        }
        return _.upperCase(name.charAt(0)) == name.charAt(0);
    }

    static isConstructorReference(name) {
        if(name.indexOf('.') > -1) {
            name = this.skipDots(name);
        }
        return _.lowerCase(name.charAt(0)) == name.charAt(0);
    }

    static skipDots(name) {
        const dotIndex = name.indexOf('.');

        if(dotIndex > -1) {
            return this.skipDots(name.substring(dotIndex + 1));
        }

        return name;
    }

    static getConstructorName(name) {
        return _.upperFirst(this.skipDots(name));
    }

    static onError(...args) {
        throw new Error(createMessage(...args));
    }

    onError(...args) {
        return BaseConstructor.onError(...args);
    }

    _expect(property, value, type) {
        this.onError(
            'Invalid type for %s "%s". ',
            _.isNumber(property) ? 'vector index' : 'param',
            property,

            'Expected type %s but got %s instead.',
            type,
            typeof value,

            'Check constructor: %s',
            this._name
        );
    }

    _validateGenericProperty(property, value, type) {
        switch(type) {
        case 'int':
        case 'uint':
        case 'float':
        case 'short':
        case 'ushort':
        case 'double':
            if(_.isNumber(value)) {
                break;
            }

            this._expect(property, value, 'number');
            break;

        case 'bytes':
            if(Buffer.isBuffer(value)) {
                break;
            }

            this._expect(property, value, 'Buffer');
            break;

        case 'long':
        case 'ulong':
            if(_.isNumber(value) || Long.isLong(value)) {
                break;
            }
            if(_.isString(value)) {
                let padding = value.substring(0, 2);
                const paddingLength = value.length % 2;

                if(padding == '0x' && paddingLength != 0) {
                    padding = value.substring(2);

                    for(let i = 0; i < paddingLength; i++) {
                        padding = '0' + padding;
                    }

                    this.onError(
                        'Invalid value for property "%s". ', property,
                        'Hexadecimal strings must have even length. Given: %s. ', value,
                        'Try adding zero padding: 0x%s', padding
                    );
                    break;
                }
                break;
            }
            this._expect(property, value, 'number or string');
            break;

        case 'bool':
            if(_.isBoolean(value)) {
                break;
            }

            this._expect(property, value, 'boolean');
            break;

        case 'string':
            if(_.isString(value)) {
                break;
            }

            this._expect(property, value, 'string');
            break;

        default:
            this.onError('unhandled type of %s', type);
        }
    }
}

export default BaseConstructor;
<|endoftext|>


<commit_before>/*
 * mobile checkboxradio unit tests
 */
(function($){
	module( 'jquery.mobile.forms.checkboxradio.js' );

	test( "widget can be disabled and enabled", function(){
		var input = $( "#checkbox-1" ),
			button = input.parent().find( ".ui-btn" );

		input.checkboxradio( "disable" );
		input.checkboxradio( "enable" );
		ok( !input.attr( "disabled" ), "start input as enabled" );
		ok( !input.parent().hasClass( "ui-disabled" ), "no disabled styles" );
		ok( !input.attr( "checked" ), "not checked before click" );
		button.trigger( "click" );
		ok( input.attr( "checked" ), "checked after click" );
		ok( button.hasClass( "ui-checkbox-on" ), "active styles after click" );
		button.trigger( "click" );

		input.checkboxradio( "disable" );
		ok( input.attr( "disabled" ), "input disabled" );
		ok( input.parent().hasClass( "ui-disabled" ), "disabled styles" );
		ok( !input.attr( "checked" ), "not checked before click" );
		button.trigger( "click" );
		ok( !input.attr( "checked" ), "not checked after click" );
		ok( !button.hasClass( "ui-checkbox-on" ), "no active styles after click" );
	});

	test( "clicking a checkbox within a controlgroup does not affect checkboxes with the same name in the same controlgroup", function(){
		var input1 = $("#checkbox-31");
		var button1 = input1.parent().find(".ui-btn");
		var input2 = $("#checkbox-32");
		var button2 = input2.parent().find(".ui-btn");

		ok(!input1.attr("checked"), "input1 not checked before click");
		ok(!input2.attr("checked"), "input2 not checked before click");

		button1.trigger("click");
		ok(input1.attr("checked"), "input1 checked after click on input1");
		ok(!input2.attr("checked"), "input2 not checked after click on input1");

		button2.trigger("click");
		ok(input1.attr("checked"), "input1 not changed after click on input2");
		ok(input2.attr("checked"), "input2 checked after click on input2");
	});

	asyncTest( "change events fired on checkbox for both check and uncheck", function(){
		var $checkbox = $( "#checkbox-2" ),
			$checkboxLabel = $checkbox.parent().find( ".ui-btn" );

		$checkbox.unbind( "change" );

		expect( 2 );

		$checkbox.change(function(){
			ok( true, "change fired on click to check the box" );
		});

		$checkboxLabel.trigger( "click" );

		//test above will be triggered twice, and the start here once
		$checkbox.change( function(){
			start();
		});

		$checkboxLabel.trigger( "click" );
	});

	asyncTest( "radio button labels should update the active button class to last clicked and clear checked", function(){
		var $radioBtns = $( '#radio-active-btn-test input' ),
			singleActiveAndChecked = function(){
				same( $( "#radio-active-btn-test .ui-radio-on" ).length, 1, "there should be only one active button" );
				same( $( "#radio-active-btn-test :checked" ).length, 1, "there should be only one checked" );
			};

		$.testHelper.sequence([
			function(){
				$radioBtns.last().siblings( 'label' ).click();
			},

			function(){
				ok( $radioBtns.last().attr( 'checked' ) );
				ok( $radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"last input label is an active button" );

				ok( !$radioBtns.first().attr( 'checked' ) );
				ok( !$radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"first input label is not active" );

				singleActiveAndChecked();

				$radioBtns.first().siblings( 'label' ).click();
			},

			function(){
				ok( $radioBtns.first().attr( 'checked' ));
				ok( $radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"first input label is an active button" );

				ok( !$radioBtns.last().attr( 'checked' ));
				ok( !$radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"last input label is not active" );

				singleActiveAndChecked();

				start();
			}
		], 500);

	});

	test( "checkboxradio controls will create when inside a container that receives a 'create' event", function(){
		ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-checkbox").length, "did not have enhancements applied" );
		ok( $("#enhancetest").trigger("create").find(".ui-checkbox").length, "enhancements applied" );
	});

})(jQuery);
<commit_msg>fix for failing checkbox radio test<commit_after>/*
 * mobile checkboxradio unit tests
 */
(function($){
	module( 'jquery.mobile.forms.checkboxradio.js' );

	test( "widget can be disabled and enabled", function(){
		var input = $( "#checkbox-1" ),
			button = input.parent().find( ".ui-btn" );

		input.checkboxradio( "disable" );
		input.checkboxradio( "enable" );
		ok( !input.attr( "disabled" ), "start input as enabled" );
		ok( !input.parent().hasClass( "ui-disabled" ), "no disabled styles" );
		ok( !input.attr( "checked" ), "not checked before click" );
		button.trigger( "click" );
		ok( input.attr( "checked" ), "checked after click" );
		ok( button.hasClass( "ui-checkbox-on" ), "active styles after click" );
		button.trigger( "click" );

		input.checkboxradio( "disable" );
		ok( input.attr( "disabled" ), "input disabled" );
		ok( input.parent().hasClass( "ui-disabled" ), "disabled styles" );
		ok( !input.attr( "checked" ), "not checked before click" );
		button.trigger( "click" );
		ok( !input.attr( "checked" ), "not checked after click" );
		ok( !button.hasClass( "ui-checkbox-on" ), "no active styles after click" );
	});

	test( "clicking a checkbox within a controlgroup does not affect checkboxes with the same name in the same controlgroup", function(){
		var input1 = $("#checkbox-31");
		var button1 = input1.parent().find(".ui-btn");
		var input2 = $("#checkbox-32");
		var button2 = input2.parent().find(".ui-btn");

		ok(!input1.attr("checked"), "input1 not checked before click");
		ok(!input2.attr("checked"), "input2 not checked before click");

		button1.trigger("click");
		ok(input1.attr("checked"), "input1 checked after click on input1");
		ok(!input2.attr("checked"), "input2 not checked after click on input1");

		button2.trigger("click");
		ok(input1.attr("checked"), "input1 not changed after click on input2");
		ok(input2.attr("checked"), "input2 checked after click on input2");
	});

	asyncTest( "change events fired on checkbox for both check and uncheck", function(){
		var $checkbox = $( "#checkbox-2" ),
			$checkboxLabel = $checkbox.parent().find( ".ui-btn" );

		$checkbox.unbind( "change" );

		expect( 2 );

		$checkbox.change(function(){
			ok( true, "change fired on click to check the box" );
		});

		$checkboxLabel.trigger( "click" );

		//test above will be triggered twice, and the start here once
		$checkbox.change( function(){
			start();
		});

		$checkboxLabel.trigger( "click" );
	});

	asyncTest( "radio button labels should update the active button class to last clicked and clear checked", function(){
		var $radioBtns = $( '#radio-active-btn-test input' ),
			singleActiveAndChecked = function(){
				same( $( "#radio-active-btn-test .ui-radio-on" ).length, 1, "there should be only one active button" );
				same( $( "#radio-active-btn-test :checked" ).length, 1, "there should be only one checked" );
			};

		$.testHelper.sequence([
			function(){
				$radioBtns.last().siblings( 'label' ).click();
			},

			function(){
				ok( $radioBtns.last().prop( 'checked' ) );
				ok( $radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"last input label is an active button" );

				ok( !$radioBtns.first().prop( 'checked' ) );
				ok( !$radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"first input label is not active" );

				singleActiveAndChecked();

				$radioBtns.first().siblings( 'label' ).click();
			},

			function(){
				ok( $radioBtns.first().prop( 'checked' ));
				ok( $radioBtns.first().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"first input label is an active button" );

				ok( !$radioBtns.last().prop( 'checked' ));
				ok( !$radioBtns.last().siblings( 'label' ).hasClass( 'ui-radio-on' ),
					"last input label is not active" );

				singleActiveAndChecked();

				start();
			}
		], 500);

	});

	test( "checkboxradio controls will create when inside a container that receives a 'create' event", function(){
		ok( !$("#enhancetest").appendTo(".ui-page-active").find(".ui-checkbox").length, "did not have enhancements applied" );
		ok( $("#enhancetest").trigger("create").find(".ui-checkbox").length, "enhancements applied" );
	});

})(jQuery);
<|endoftext|>


<commit_before>/* global THREE, dat, modifiers */
(function() {
  'use strict';

  var container;

  var scene, camera, renderer;
  var views;

  var baseGeometry;
  var geometry, material, mesh;
  var wireframe;

  var textarea = document.getElementById( 'textarea' );
  var viewports = document.getElementById( 'viewports' );

  var config = {
    widthSegments: 8,
    heightSegments: 8,
    depthSegments: 8
  };

  var transformVertex = function() {};

  function createWireframe() {
    if ( wireframe && wireframe.parent ) {
      wireframe.parent.remove( wireframe );
    }

    wireframe = new THREE.WireframeHelper( mesh );
    scene.add( wireframe );
  }

  function transformGeometry() {
    var _geometry = new THREE.Geometry().copy( baseGeometry );

    // Handle invalid geometry (for example, NaN values).
    try {
      _geometry.vertices.forEach( transformVertex );
      _geometry.computeFaceNormals();
      _geometry.computeVertexNormals();
    } catch ( error ) {
      console.error( error );
      return;
    }

    geometry = _geometry;
    mesh.geometry = geometry;
    mesh.needsUpdate = true;

    createWireframe( mesh );

    render();
  }

  function onInput() {
    var lines = textarea.value.split( '\n' );

    var x = lines[0] || 'x';
    var y = lines[1] || 'y';
    var z = lines[2] || 'z';

    try {
      var fn = new Function(
        [ 'x', 'y', 'z', 'xt', 'yt', 'zt' ],
        'return [' + x + ', ' + y + ', ' + z + '];'
      );

      transformVertex = modifiers.parametric( baseGeometry, function( vector, xt, yt, zt ) {
        vector.fromArray( fn( vector.x, vector.y, vector.z, xt, yt, zt ) );
      });

      transformGeometry();
    } catch ( error ) {
      console.error( error );
    }
  }

  function init() {
    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight );
    camera.position.set( 0, 1, 2 );

    views = [ 'x', 'y', 'z' ].reduce(function( views, axis ) {
      var _renderer = new THREE.WebGLRenderer({ antialias: true });
      _renderer.setPixelRatio( window.devicePixelRatio );
      _renderer.setSize( 128, 128 );
      viewports.appendChild( _renderer.domElement );

      var size = 1;
      var _camera = new THREE.OrthographicCamera( -size, size, size, -size );
      _camera.position[ axis ] = 2;
      _camera.lookAt( new THREE.Vector3() );

      views[ axis ] = {
        renderer: _renderer,
        camera: _camera
      };

      return views;
    }, {} );

    var controls = new THREE.OrbitControls( camera, renderer.domElement );
    controls.addEventListener( 'change', render );

    baseGeometry = new THREE.BoxGeometry(
      1, 1, 1,
      config.widthSegments, config.heightSegments, config.depthSegments
    );

    geometry = baseGeometry;
    material = new THREE.MeshStandardMaterial({ shading: THREE.FlatShading });
    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    createWireframe( mesh );

    var light = new THREE.DirectionalLight();
    light.position.set( 8, 8, 0 );
    scene.add( light );

    scene.add( new THREE.AmbientLight( '#333' ) );

    textarea.addEventListener( 'input', onInput );

    var gui = new dat.GUI();

    [ 'widthSegments', 'heightSegments', 'depthSegments' ].forEach(function( segmentCount ) {
      gui.add( config, segmentCount, 1, 16 )
        .step( 1 )
        .listen()
        .onChange(function( count ) {
          config[ segmentCount ] = count;

          baseGeometry = new THREE.BoxGeometry(
            1, 1, 1,
            config.widthSegments, config.heightSegments, config.depthSegments
          );

          transformGeometry();
        });
    })
  }

  function render() {
    renderer.render( scene, camera );

    Object.keys( views ).forEach(function( key ) {
      var view = views[ key ];
      view.renderer.render( scene, view.camera );
    });
  }

  init();
  render();

  window.addEventListener( 'resize', function() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );
    render();
  });

})();
<commit_msg>lathe[modifiers]: Prevent input from propagating to dat.gui.<commit_after>/* global THREE, dat, modifiers */
(function() {
  'use strict';

  var container;

  var scene, camera, renderer;
  var views;

  var baseGeometry;
  var geometry, material, mesh;
  var wireframe;

  var textarea = document.getElementById( 'textarea' );
  var viewports = document.getElementById( 'viewports' );

  var config = {
    widthSegments: 8,
    heightSegments: 8,
    depthSegments: 8
  };

  var transformVertex = function() {};

  function createWireframe() {
    if ( wireframe && wireframe.parent ) {
      wireframe.parent.remove( wireframe );
    }

    wireframe = new THREE.WireframeHelper( mesh );
    scene.add( wireframe );
  }

  function transformGeometry() {
    var _geometry = new THREE.Geometry().copy( baseGeometry );
    _geometry.vertices.forEach( transformVertex );
    _geometry.computeFaceNormals();
    _geometry.computeVertexNormals();

    geometry = _geometry;
    mesh.geometry = geometry;
    mesh.needsUpdate = true;

    createWireframe( mesh );

    render();
  }

  function onInput() {
    var lines = textarea.value.split( '\n' );

    var x = lines[0] || 'x';
    var y = lines[1] || 'y';
    var z = lines[2] || 'z';

    try {
      var fn = new Function(
        [ 'x', 'y', 'z', 'xt', 'yt', 'zt' ],
        'return [' + x + ', ' + y + ', ' + z + '];'
      );

      transformVertex = modifiers.parametric( baseGeometry, function( vector, xt, yt, zt ) {
        vector.fromArray( fn( vector.x, vector.y, vector.z, xt, yt, zt ) );
      });

      transformGeometry();
    } catch ( error ) {
      console.error( error );
    }
  }

  function init() {
    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight );
    camera.position.set( 0, 1, 2 );

    views = [ 'x', 'y', 'z' ].reduce(function( views, axis ) {
      var _renderer = new THREE.WebGLRenderer({ antialias: true });
      _renderer.setPixelRatio( window.devicePixelRatio );
      _renderer.setSize( 128, 128 );
      viewports.appendChild( _renderer.domElement );

      var size = 1;
      var _camera = new THREE.OrthographicCamera( -size, size, size, -size );
      _camera.position[ axis ] = 2;
      _camera.lookAt( new THREE.Vector3() );

      views[ axis ] = {
        renderer: _renderer,
        camera: _camera
      };

      return views;
    }, {} );

    var controls = new THREE.OrbitControls( camera, renderer.domElement );
    controls.addEventListener( 'change', render );

    baseGeometry = new THREE.BoxGeometry(
      1, 1, 1,
      config.widthSegments, config.heightSegments, config.depthSegments
    );

    geometry = baseGeometry;
    material = new THREE.MeshStandardMaterial({ shading: THREE.FlatShading });
    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    createWireframe( mesh );

    var light = new THREE.DirectionalLight();
    light.position.set( 8, 8, 0 );
    scene.add( light );

    scene.add( new THREE.AmbientLight( '#333' ) );

    textarea.addEventListener( 'input', onInput );

    // Prevent input from toggling dat.gui via hide shortcut ('h').
    textarea.addEventListener( 'keydown', function( event ) {
      event.stopPropagation();
    });

    var gui = new dat.GUI();

    [ 'widthSegments', 'heightSegments', 'depthSegments' ].forEach(function( segmentCount ) {
      gui.add( config, segmentCount, 1, 16 )
        .step( 1 )
        .listen()
        .onChange(function( count ) {
          config[ segmentCount ] = count;

          baseGeometry = new THREE.BoxGeometry(
            1, 1, 1,
            config.widthSegments, config.heightSegments, config.depthSegments
          );

          transformGeometry();
        });
    })
  }

  function render() {
    renderer.render( scene, camera );

    Object.keys( views ).forEach(function( key ) {
      var view = views[ key ];
      view.renderer.render( scene, view.camera );
    });
  }

  init();
  render();

  window.addEventListener( 'resize', function() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );
    render();
  });

})();
<|endoftext|>


<commit_before>enyo.depends(
	"View.js",
	"ViewStack.js",
	"AppStack.js",
);
<commit_msg>Syntax fixes<commit_after>enyo.depends(
	"View.js",
	"ViewStack.js",
	"AppStack.js"
);
<|endoftext|>


<commit_before>var generator = require('../helpers/generator');
var controllers = require('../api/controllers');
var plugins = require('../config.json').plugins;
var pconf = require('../config.json').APIVARS.PLUGINS;
var pluginsDir = __dirname.replace('/helpers', pconf.DIR);

function apiParams (defRoute) {
  var defParams = '';

  if (defRoute.params) {
    for (var param in defRoute.params) {
      if (param) { defParams += '/:'+ param; }
    }
  }
  return defParams;
}

function addPluginsApi (api) {
  for (var idx in plugins) {
    if (plugins.hasOwnProperty(idx)) {
      var name = plugins[idx];
      var prefix = '/' + name;
      var plugin = require(pluginsDir + prefix + pconf.MAIN);
      var _cfg_ = require(pluginsDir + prefix + pconf.CONFIG);

      for (var g in plugin.api.GET) {
        if (plugin.api.GET.hasOwnProperty(g)) {
          var defGET = plugin.api.GET[g];
          api.get(prefix + '/' + defGET.route + apiParams(defGET), defGET.fn);
        }
      }

      for(var p in plugin.api.POST) {
        if (plugin.api.POST.hasOwnProperty(p)) {
          var defPOST = plugin.api.POST[p];
          api.post(prefix + '/' + defPOST.route + apiParams(defPOST), defPOST.fn);
        }
      }

      for (var d in plugin.api.DELETE) {
        if (plugin.api.DELETE.hasOwnProperty(d)) {
          var defDELETE = plugin.api.DELETE[d];
          api.del(prefix + '/' + defDELETE.route + apiParams(defDELETE), defDELETE.fn);
        }
      }

      for (var t in plugin.api.PUT) {
        if (plugin.api.PUT.hasOwnProperty(t)) {
          var defPUT = plugin.api.PUT[t];
          api.delete(prefix + '/' + defPUT.route + apiParams(defPUT), defPUT.fn);
        }
      }

      addResourceRoutes(_cfg_.resources, api);
    }
  }
}

addResourceRoutes (resources, api){
  for (var route in resources) {
    if (resources.hasOwnProperty(route)) {
      if (resources[route].exclude){ continue; }

      generator.addRoutes({
        api: api,
        route: route,
        admin: resources[route].admin,
        controller: controllers[route],
        schema: resources[route].schema,
        clean:  resources[route].clean
      });
    }
  }
}

getViewPath (name) {
  var dirname = __dirname.replace('/helpers', '');
  return dirname + pconf.DIR + '/' + name + pconf.VIEWS;
}

addPluginsWeb (web, express){
  var views = [];
  for (var idx in plugins) {
    if (plugins.hasOwnProperty(idx)) {
      var name = plugins[idx];
      var prefix = '/' + name;
      var plugin = require(pluginsDir + prefix + pconf.CONFIG);

      web.use(express.static(pluginsDir + prefix + '/public'));

      for (var idy in plugin.pages) {
        var page = plugin.pages[idy];
        views.push(getViewPath(page));
        generator.addPage(web, page);
      }

      for (var route in plugin.resources) {
        if (plugin.resources.hasOwnProperty(route)) {
          generator.addView(web, route);
        }
      }
    }
  }

  return views;
}

//module.exports.apiParams = apiParams;
module.exports.addPluginsApi = addPluginsApi;
module.exports.addPluginsWeb = addPluginsWeb;
<commit_msg>Add missing word<commit_after>var generator = require('../helpers/generator');
var controllers = require('../api/controllers');
var plugins = require('../config.json').plugins;
var pconf = require('../config.json').APIVARS.PLUGINS;
var pluginsDir = __dirname.replace('/helpers', pconf.DIR);

function apiParams (defRoute) {
  var defParams = '';

  if (defRoute.params) {
    for (var param in defRoute.params) {
      if (param) { defParams += '/:'+ param; }
    }
  }
  return defParams;
}

function addPluginsApi (api) {
  for (var idx in plugins) {
    if (plugins.hasOwnProperty(idx)) {
      var name = plugins[idx];
      var prefix = '/' + name;
      var plugin = require(pluginsDir + prefix + pconf.MAIN);
      var _cfg_ = require(pluginsDir + prefix + pconf.CONFIG);

      for (var g in plugin.api.GET) {
        if (plugin.api.GET.hasOwnProperty(g)) {
          var defGET = plugin.api.GET[g];
          api.get(prefix + '/' + defGET.route + apiParams(defGET), defGET.fn);
        }
      }

      for(var p in plugin.api.POST) {
        if (plugin.api.POST.hasOwnProperty(p)) {
          var defPOST = plugin.api.POST[p];
          api.post(prefix + '/' + defPOST.route + apiParams(defPOST), defPOST.fn);
        }
      }

      for (var d in plugin.api.DELETE) {
        if (plugin.api.DELETE.hasOwnProperty(d)) {
          var defDELETE = plugin.api.DELETE[d];
          api.del(prefix + '/' + defDELETE.route + apiParams(defDELETE), defDELETE.fn);
        }
      }

      for (var t in plugin.api.PUT) {
        if (plugin.api.PUT.hasOwnProperty(t)) {
          var defPUT = plugin.api.PUT[t];
          api.delete(prefix + '/' + defPUT.route + apiParams(defPUT), defPUT.fn);
        }
      }

      addResourceRoutes(_cfg_.resources, api);
    }
  }
}

function addResourceRoutes (resources, api){
  for (var route in resources) {
    if (resources.hasOwnProperty(route)) {
      if (resources[route].exclude){ continue; }

      generator.addRoutes({
        api: api,
        route: route,
        admin: resources[route].admin,
        controller: controllers[route],
        schema: resources[route].schema,
        clean:  resources[route].clean
      });
    }
  }
}

function getViewPath (name) {
  var dirname = __dirname.replace('/helpers', '');
  return dirname + pconf.DIR + '/' + name + pconf.VIEWS;
}

function addPluginsWeb (web, express){
  var views = [];
  for (var idx in plugins) {
    if (plugins.hasOwnProperty(idx)) {
      var name = plugins[idx];
      var prefix = '/' + name;
      var plugin = require(pluginsDir + prefix + pconf.CONFIG);

      web.use(express.static(pluginsDir + prefix + '/public'));

      for (var idy in plugin.pages) {
        var page = plugin.pages[idy];
        views.push(getViewPath(page));
        generator.addPage(web, page);
      }

      for (var route in plugin.resources) {
        if (plugin.resources.hasOwnProperty(route)) {
          generator.addView(web, route);
        }
      }
    }
  }

  return views;
}

//module.exports.apiParams = apiParams;
module.exports.addPluginsApi = addPluginsApi;
module.exports.addPluginsWeb = addPluginsWeb;
<|endoftext|>


<commit_before>'use strict';

var request = require('request');
var version = require('../package.json').version;

var tap = function (func) {
  return function (value) {
    func.apply(null, arguments);
    return value;
  };
};

var cronofy = function (config) {
  if (!this || this.constructor !== cronofy) {
    throw new Error('Cronofy must be called as a constructor');
  }

  this.config = config;

  this.urls = {
    api: 'https://api' + (config.dataCenter ? '-' + config.dataCenter : '') + '.cronofy.com'
  };
};

var omit = function (obj, props) {
  var keys = Object.keys(obj);
  var res = {};

  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var val = obj[key];

    if (!props || props.indexOf(key) === -1) {
      res[key] = val;
    }
  }
  return res;
};

cronofy.prototype._httpCall = function (method, path, options, callback, optionsToOmit) {
  var settings = {
    method: method,
    url: path,
    gzip: true,
    json: true,
    headers: {
      Authorization: 'Bearer ' + (options.access_token || options.bearer_token),
      'Content-Type': 'application/json',
      'User-Agent': 'Cronofy Node - ' + version
    },
    qsStringifyOptions: { arrayFormat: 'brackets' }
  };

  if (method === 'GET') {
    settings['qs'] = omit(options, optionsToOmit || ['access_token']);
  } else {
    settings['body'] = omit(options, optionsToOmit || ['access_token']);
  }

  return new Promise(function (resolve, reject) {
    request(settings, function (error, result, body) {
      if (error || result.statusCode >= 400) {
        var err = new Error(JSON.stringify(body));

        if (result && result.statusCode) {
          err.statusCode = result.statusCode;
        }

        err.error = {
          url: path,
          entity: body
        };

        if (callback) {
          callback(err);
        } else {
          reject(err);
        }
      } else {
        if (callback) {
          callback(null, body);
        } else {
          resolve(body);
        }
      }
    });
  });
};

cronofy.prototype._parseArguments = function (args, configDefaults) {
  var parsed = { options: {}, callback: null };

  if (args.length === 2) {
    parsed.options = args[0];
    parsed.callback = args[1];
  } else {
    switch (typeof args[0]) {
      case 'object':
        parsed.options = args[0];
        break;
      case 'function':
        parsed.callback = args[0];
        break;
    }
  }

  for (var i = 0; i < configDefaults.length; i++) {
    var key = configDefaults[i];

    parsed.options[key] = parsed.options[key] || this.config[key];
  }

  return parsed;
};

cronofy.prototype._httpGet = function (path, options, callback, optionsToOmit) {
  return this._httpCall('GET', this.urls.api + path, options, callback, optionsToOmit);
};

cronofy.prototype._httpPost = function (path, options, callback, optionsToOmit) {
  return this._httpCall('POST', this.urls.api + path, options, callback, optionsToOmit);
};

cronofy.prototype._httpDelete = function (path, options, callback, optionsToOmit) {
  return this._httpCall('DELETE', this.urls.api + path, options, callback, optionsToOmit);
};

cronofy.prototype.accountInformation = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/account', details.options, details.callback);
};

cronofy.prototype.addToCalendar = function () {
  var details = this._parseArguments(arguments, ['client_id', 'client_secret']);

  return this._httpPost('/v1/add_to_calendar', details.options, details.callback);
};

cronofy.prototype.realTimeScheduling = function () {
  var details = this._parseArguments(arguments, ['client_id', 'client_secret']);

  return this._httpPost('/v1/real_time_scheduling', details.options, details.callback);
};

cronofy.prototype.realTimeSequencing = function () {
  var details = this._parseArguments(arguments, ['client_id', 'client_secret']);

  return this._httpPost('/v1/real_time_sequencing', details.options, details.callback);
};

cronofy.prototype.authorizeWithServiceAccount = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/service_account_authorizations', details.options, details.callback);
};

cronofy.prototype.availability = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/availability', details.options, details.callback);
};

cronofy.prototype.sequencedAvailability = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/sequenced_availability', details.options, details.callback);
};

cronofy.prototype.listAvailabilityRules = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/availability_rules', details.options, details.callback);
};

cronofy.prototype.upsertAvailabilityRule = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/availability_rules', details.options, details.callback);
};

cronofy.prototype.readAvailabilityRule = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/availability_rules/' + details.options.availability_rule_id, details.options, details.callback);
};

cronofy.prototype.deleteAvailabilityRule = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpDelete('/v1/availability_rules/' + details.options.availability_rule_id, details.options, details.callback);
};

cronofy.prototype.createEvent = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/calendars/' + details.options.calendar_id + '/events', details.options, details.callback, ['access_token', 'calendar_id']);
};

cronofy.prototype.createNotificationChannel = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/channels', details.options, details.callback);
};

cronofy.prototype.deleteEvent = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpDelete('/v1/calendars/' + details.options.calendar_id + '/events', details.options, details.callback, ['access_token', 'calendar_id']);
};

cronofy.prototype.bulkDeleteEvents = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpDelete('/v1/events', details.options, details.callback, ['access_token']);
};

cronofy.prototype.deleteExternalEvent = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpDelete('/v1/calendars/' + details.options.calendar_id + '/events', details.options, details.callback, ['access_token', 'calendar_id']);
};

cronofy.prototype.deleteNotificationChannel = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpDelete('/v1/channels/' + details.options.channel_id, details.options, details.callback, ['access_token', 'channel_id']);
};

cronofy.prototype.elevatedPermissions = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/permissions', details.options, details.callback);
};

cronofy.prototype.freeBusy = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  if (details.options.next_page) {
    return this._httpCall('GET', details.options.next_page, details.options, details.callback, ['access_token', 'next_page']);
  }

  return this._httpGet('/v1/free_busy', details.options, details.callback);
};

cronofy.prototype.listCalendars = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/calendars', details.options, details.callback);
};

cronofy.prototype.createCalendar = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/calendars', details.options, details.callback);
};

cronofy.prototype.listNotificationChannels = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/channels', details.options, details.callback);
};

cronofy.prototype.profileInformation = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/profiles', details.options, details.callback);
};

cronofy.prototype.readEvents = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  if (details.options.next_page) {
    return this._httpCall('GET', details.options.next_page, details.options, details.callback, ['access_token', 'next_page']);
  }

  return this._httpGet('/v1/events', details.options, details.callback);
};

cronofy.prototype.applicationCalendar = function () {
  var that = this;
  var details = this._parseArguments(arguments, ['client_id', 'client_secret', 'application_calendar_id']);

  return this._httpPost('/v1/application_calendars', details.options).then(tap(function (response) {
    that.config.access_token = response.access_token;
    that.config.refresh_token = response.refresh_token;

    if (details.callback) {
      details.callback(null, response);
    }
  }), details.callback);
};

cronofy.prototype.revokeProfileAuthorization = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/profiles/' + details.options.profile_id + '/revoke', details.options, details.callback);
};

cronofy.prototype.refreshAccessToken = function () {
  var that = this;
  var details = this._parseArguments(arguments, ['client_id', 'client_secret', 'refresh_token']);

  details.options.grant_type = 'refresh_token';

  return this._httpPost('/oauth/token', details.options).then(tap(function (token) {
    that.config.access_token = token.access_token;
    that.config.refresh_token = token.refresh_token;

    if (details.callback) {
      details.callback(null, token);
    }
  }), details.callback);
};

cronofy.prototype.requestAccessToken = function () {
  var that = this;
  var details = this._parseArguments(arguments, ['client_id', 'client_secret', 'refresh_token']);

  details.options.grant_type = 'authorization_code';

  return this._httpPost('/oauth/token', details.options).then(tap(function (token) {
    that.config.access_token = token.access_token;
    that.config.refresh_token = token.refresh_token;

    if (details.callback) {
      details.callback(null, token);
    }
  }), details.callback);
};

cronofy.prototype.revokeAuthorization = function () {
  var that = this;
  var details = this._parseArguments(arguments, ['client_id', 'client_secret', 'refresh_token']);

  return this._httpPost('/oauth/token/revoke', details.options).then(tap(function () {
    delete that.config.access_token;
    delete that.config.refresh_token;

    if (details.callback) {
      details.callback();
    }
  }), details.callback);
};

cronofy.prototype.getSmartInvite = function () {
  var details = this._parseArguments(arguments, ['smart_invite_id', 'recipient_email', 'client_secret']);

  details.options.bearer_token = details.options.client_secret;

  return this._httpGet('/v1/smart_invites', details.options, details.callback, ['client_secret', 'access_token', 'bearer_token']);
};

cronofy.prototype.createSmartInvite = function () {
  var details = this._parseArguments(arguments, ['client_secret']);

  details.options.bearer_token = details.options.client_secret;

  return this._httpPost('/v1/smart_invites', details.options, details.callback, ['access_token', 'client_secret', 'bearer_token']);
};

cronofy.prototype.cancelSmartInvite = function () {
  var details = this._parseArguments(arguments, ['client_secret']);

  details.options.bearer_token = details.options.client_secret;
  details.options.method = 'cancel';

  return this._httpPost('/v1/smart_invites', details.options, details.callback, ['access_token', 'client_secret', 'bearer_token']);
};

cronofy.prototype.userInfo = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/userinfo', details.options, details.callback);
};

cronofy.prototype.requestElementToken = function () {
  var details = this._parseArguments(arguments, ['client_secret']);

  details.options.bearer_token = details.options.client_secret;

  return this._httpPost(
    '/v1/element_tokens',
    details.options,
    details.callback,
    ['access_token', 'client_secret', 'bearer_token']
  );
};

module.exports = cronofy;
<commit_msg>adding version to element token defaults<commit_after>'use strict';

var request = require('request');
var version = require('../package.json').version;

var tap = function (func) {
  return function (value) {
    func.apply(null, arguments);
    return value;
  };
};

var cronofy = function (config) {
  if (!this || this.constructor !== cronofy) {
    throw new Error('Cronofy must be called as a constructor');
  }

  this.config = config;

  this.urls = {
    api: 'https://api' + (config.dataCenter ? '-' + config.dataCenter : '') + '.cronofy.com'
  };
};

var omit = function (obj, props) {
  var keys = Object.keys(obj);
  var res = {};

  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var val = obj[key];

    if (!props || props.indexOf(key) === -1) {
      res[key] = val;
    }
  }
  return res;
};

cronofy.prototype._httpCall = function (method, path, options, callback, optionsToOmit) {
  var settings = {
    method: method,
    url: path,
    gzip: true,
    json: true,
    headers: {
      Authorization: 'Bearer ' + (options.access_token || options.bearer_token),
      'Content-Type': 'application/json',
      'User-Agent': 'Cronofy Node - ' + version
    },
    qsStringifyOptions: { arrayFormat: 'brackets' }
  };

  if (method === 'GET') {
    settings['qs'] = omit(options, optionsToOmit || ['access_token']);
  } else {
    settings['body'] = omit(options, optionsToOmit || ['access_token']);
  }

  return new Promise(function (resolve, reject) {
    request(settings, function (error, result, body) {
      if (error || result.statusCode >= 400) {
        var err = new Error(JSON.stringify(body));

        if (result && result.statusCode) {
          err.statusCode = result.statusCode;
        }

        err.error = {
          url: path,
          entity: body
        };

        if (callback) {
          callback(err);
        } else {
          reject(err);
        }
      } else {
        if (callback) {
          callback(null, body);
        } else {
          resolve(body);
        }
      }
    });
  });
};

cronofy.prototype._parseArguments = function (args, configDefaults) {
  var parsed = { options: {}, callback: null };

  if (args.length === 2) {
    parsed.options = args[0];
    parsed.callback = args[1];
  } else {
    switch (typeof args[0]) {
      case 'object':
        parsed.options = args[0];
        break;
      case 'function':
        parsed.callback = args[0];
        break;
    }
  }

  for (var i = 0; i < configDefaults.length; i++) {
    var key = configDefaults[i];

    parsed.options[key] = parsed.options[key] || this.config[key];
  }

  return parsed;
};

cronofy.prototype._httpGet = function (path, options, callback, optionsToOmit) {
  return this._httpCall('GET', this.urls.api + path, options, callback, optionsToOmit);
};

cronofy.prototype._httpPost = function (path, options, callback, optionsToOmit) {
  return this._httpCall('POST', this.urls.api + path, options, callback, optionsToOmit);
};

cronofy.prototype._httpDelete = function (path, options, callback, optionsToOmit) {
  return this._httpCall('DELETE', this.urls.api + path, options, callback, optionsToOmit);
};

cronofy.prototype.accountInformation = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/account', details.options, details.callback);
};

cronofy.prototype.addToCalendar = function () {
  var details = this._parseArguments(arguments, ['client_id', 'client_secret']);

  return this._httpPost('/v1/add_to_calendar', details.options, details.callback);
};

cronofy.prototype.realTimeScheduling = function () {
  var details = this._parseArguments(arguments, ['client_id', 'client_secret']);

  return this._httpPost('/v1/real_time_scheduling', details.options, details.callback);
};

cronofy.prototype.realTimeSequencing = function () {
  var details = this._parseArguments(arguments, ['client_id', 'client_secret']);

  return this._httpPost('/v1/real_time_sequencing', details.options, details.callback);
};

cronofy.prototype.authorizeWithServiceAccount = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/service_account_authorizations', details.options, details.callback);
};

cronofy.prototype.availability = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/availability', details.options, details.callback);
};

cronofy.prototype.sequencedAvailability = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/sequenced_availability', details.options, details.callback);
};

cronofy.prototype.listAvailabilityRules = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/availability_rules', details.options, details.callback);
};

cronofy.prototype.upsertAvailabilityRule = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/availability_rules', details.options, details.callback);
};

cronofy.prototype.readAvailabilityRule = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/availability_rules/' + details.options.availability_rule_id, details.options, details.callback);
};

cronofy.prototype.deleteAvailabilityRule = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpDelete('/v1/availability_rules/' + details.options.availability_rule_id, details.options, details.callback);
};

cronofy.prototype.createEvent = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/calendars/' + details.options.calendar_id + '/events', details.options, details.callback, ['access_token', 'calendar_id']);
};

cronofy.prototype.createNotificationChannel = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/channels', details.options, details.callback);
};

cronofy.prototype.deleteEvent = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpDelete('/v1/calendars/' + details.options.calendar_id + '/events', details.options, details.callback, ['access_token', 'calendar_id']);
};

cronofy.prototype.bulkDeleteEvents = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpDelete('/v1/events', details.options, details.callback, ['access_token']);
};

cronofy.prototype.deleteExternalEvent = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpDelete('/v1/calendars/' + details.options.calendar_id + '/events', details.options, details.callback, ['access_token', 'calendar_id']);
};

cronofy.prototype.deleteNotificationChannel = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpDelete('/v1/channels/' + details.options.channel_id, details.options, details.callback, ['access_token', 'channel_id']);
};

cronofy.prototype.elevatedPermissions = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/permissions', details.options, details.callback);
};

cronofy.prototype.freeBusy = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  if (details.options.next_page) {
    return this._httpCall('GET', details.options.next_page, details.options, details.callback, ['access_token', 'next_page']);
  }

  return this._httpGet('/v1/free_busy', details.options, details.callback);
};

cronofy.prototype.listCalendars = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/calendars', details.options, details.callback);
};

cronofy.prototype.createCalendar = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/calendars', details.options, details.callback);
};

cronofy.prototype.listNotificationChannels = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/channels', details.options, details.callback);
};

cronofy.prototype.profileInformation = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/profiles', details.options, details.callback);
};

cronofy.prototype.readEvents = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  if (details.options.next_page) {
    return this._httpCall('GET', details.options.next_page, details.options, details.callback, ['access_token', 'next_page']);
  }

  return this._httpGet('/v1/events', details.options, details.callback);
};

cronofy.prototype.applicationCalendar = function () {
  var that = this;
  var details = this._parseArguments(arguments, ['client_id', 'client_secret', 'application_calendar_id']);

  return this._httpPost('/v1/application_calendars', details.options).then(tap(function (response) {
    that.config.access_token = response.access_token;
    that.config.refresh_token = response.refresh_token;

    if (details.callback) {
      details.callback(null, response);
    }
  }), details.callback);
};

cronofy.prototype.revokeProfileAuthorization = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpPost('/v1/profiles/' + details.options.profile_id + '/revoke', details.options, details.callback);
};

cronofy.prototype.refreshAccessToken = function () {
  var that = this;
  var details = this._parseArguments(arguments, ['client_id', 'client_secret', 'refresh_token']);

  details.options.grant_type = 'refresh_token';

  return this._httpPost('/oauth/token', details.options).then(tap(function (token) {
    that.config.access_token = token.access_token;
    that.config.refresh_token = token.refresh_token;

    if (details.callback) {
      details.callback(null, token);
    }
  }), details.callback);
};

cronofy.prototype.requestAccessToken = function () {
  var that = this;
  var details = this._parseArguments(arguments, ['client_id', 'client_secret', 'refresh_token']);

  details.options.grant_type = 'authorization_code';

  return this._httpPost('/oauth/token', details.options).then(tap(function (token) {
    that.config.access_token = token.access_token;
    that.config.refresh_token = token.refresh_token;

    if (details.callback) {
      details.callback(null, token);
    }
  }), details.callback);
};

cronofy.prototype.revokeAuthorization = function () {
  var that = this;
  var details = this._parseArguments(arguments, ['client_id', 'client_secret', 'refresh_token']);

  return this._httpPost('/oauth/token/revoke', details.options).then(tap(function () {
    delete that.config.access_token;
    delete that.config.refresh_token;

    if (details.callback) {
      details.callback();
    }
  }), details.callback);
};

cronofy.prototype.getSmartInvite = function () {
  var details = this._parseArguments(arguments, ['smart_invite_id', 'recipient_email', 'client_secret']);

  details.options.bearer_token = details.options.client_secret;

  return this._httpGet('/v1/smart_invites', details.options, details.callback, ['client_secret', 'access_token', 'bearer_token']);
};

cronofy.prototype.createSmartInvite = function () {
  var details = this._parseArguments(arguments, ['client_secret']);

  details.options.bearer_token = details.options.client_secret;

  return this._httpPost('/v1/smart_invites', details.options, details.callback, ['access_token', 'client_secret', 'bearer_token']);
};

cronofy.prototype.cancelSmartInvite = function () {
  var details = this._parseArguments(arguments, ['client_secret']);

  details.options.bearer_token = details.options.client_secret;
  details.options.method = 'cancel';

  return this._httpPost('/v1/smart_invites', details.options, details.callback, ['access_token', 'client_secret', 'bearer_token']);
};

cronofy.prototype.userInfo = function () {
  var details = this._parseArguments(arguments, ['access_token']);

  return this._httpGet('/v1/userinfo', details.options, details.callback);
};

cronofy.prototype.requestElementToken = function () {
  var details = this._parseArguments(arguments, ['client_secret']);

  details.options.bearer_token = details.options.client_secret;

  details.options.version = "1";

  return this._httpPost('/v1/element_tokens', details.options, details.callback, ['access_token', 'client_secret', 'bearer_token']);
};

module.exports = cronofy;
<|endoftext|>


<commit_before>"use strict";

// change it to target hostname when develop
const DEFAULT_HOSTNAME = "demo-1.semiot.ru";
const hostname = location.hostname;

const TSDB_BASE_URL = `http://${hostname}:4242/api/query`;

export default {
    COOKIE_NAME: "ru.semiot",
    VERSION: `@VERSION`,
    URLS: {
        messageBus: "ws://" + hostname + ":8080/ws",
        tripleStore: "http://" + hostname + ":3030/ds/query",
        tsdb: {
            // archiveQuantity: `${TSDB_BASE_URL}?start={0}&end={1}&m=sum:{2}`,
            archiveQuantity: `${TSDB_BASE_URL}?start={0}&end={1}&m=sum:{2}{property={3}}`,
            archiveEnum: `${TSDB_BASE_URL}?start={0}&end={1}&m=sum:{2}{enum_value=*}`,
            last: `${TSDB_BASE_URL}/last/{0}`
        },
        analyze: {
            query: "http://" + hostname + ":8085/api/query",
            events: "http://" + hostname + ":8085/api/query/{0}/events"
        }
    },
    TOPICS: {
        "device_registered": 'ru.semiot.devices.newandobserving',
        "device_turned_off": 'ru.semiot.devices.turnoff',
        "device_remove": 'ru.semiot.devices.remove'
    },
    SPARQL: {
        prefixes: {
            rdfs: 'http://www.w3.org/2000/01/rdf-schema#',
            ssn: 'http://purl.oclc.org/NET/ssnx/ssn#',
            rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
            ssncom: 'http://purl.org/NET/ssnext/communication#',
            saref: 'http://ontology.tno.nl/saref#',
            mcht: 'http://purl.org/NET/ssnext/machinetools#',
            qudt: 'http://qudt.org/schema/qudt#',
            "qudt-quantity": 'http://qudt.org/vocab/quantity#',
            "qudt-unit": "http://qudt.org/vocab/unit#",
            om: 'http://purl.org/ifgi/om#',
            ext: 'http://w3id.org/qudt/vocab/quantity/ext#'
        },
        types: {
            heatSystem: "http://purl.org/NET/ssnext/heatmeters#HeatMeter",
            electricSystem: "http://purl.org/NET/ssnext/electricmeters#ElectricMeter",
            temperature: "http://purl.org/NET/ssnext/heatmeters#Temperature",
            heat: "http://purl.org/NET/ssnext/heatmeters#Heat",
            observationResult: "http://purl.org/NET/ssnext/meters/core#hasQuantityValue"
        },
        queries: {
            getAllSystems: [
                "SELECT DISTINCT ?label ?uri",
                "WHERE {",
                "   ?uri a ssn:System ;",
                "       rdfs:label ?label .",
                "}"
            ].join('\n'),
            getSystemSensors: `
                SELECT ?subsystem ?type ?observationType ?propLabel ?valueUnitLabel {
                  <{0}> ssn:hasSubSystem ?subsystem .
                  ?subsystem ssn:observes ?type .
                  ?subsystem ssn:hasMeasurementCapability ?mc .
                  ?mc ssn:forProperty ?prop .
                  ?prop rdfs:label ?propLabel .
                  ?mc ssn:hasMeasurementProperty ?mp .
                  ?mp ssn:hasValue ?v .
                  ?v a ?observationType .
                  ?v ssn:hasValue ?valueUnit .
                  ?valueUnit rdfs:label ?valueUnitLabel .
                }
            `,
            getSystemName: [
                "SELECT ?label {",
                "   <{0}> rdfs:label ?label, .",
                "}"
            ].join('\n'),
            getSystemDetail: `
                SELECT ?label ?topic {
                    <{0}> rdfs:label ?label ;
                        ssncom:hasCommunicationEndpoint ?endpoint .
                    ?endpoint ssncom:protocol "WAMP" ;
                        ssncom:topic ?topic .
                }
            `,
            getMachineToolStates: `
                SELECT ?stateURI ?stateLabel ?stateDescription
                WHERE {
                    ?stateURI rdf:type mcht:MachineToolWorkingStateValue ;
                        rdfs:label ?stateLabel ;
                        rdfs:comment ?stateDescription .
                }
            `
        }
    },
    TIMEZONE_OFFSET: -1 * new Date().getTimezoneOffset() * 60 * 1000 // in ms
};
<commit_msg>Update config.js<commit_after>"use strict";

// change it to target hostname when develop
const DEFAULT_HOSTNAME = "demo-1.semiot.ru";
const hostname = location.hostname;

const TSDB_BASE_URL = `http://${hostname}:4242/api/query`;

export default {
    COOKIE_NAME: "ru.semiot",
    VERSION: `@VERSION`,
    URLS: {
        messageBus: "ws://" + hostname + ":8080/ws",
        tripleStore: "http://" + hostname + ":3030/ds/query",
        tsdb: {
            // archiveQuantity: `${TSDB_BASE_URL}?start={0}&end={1}&m=sum:{2}`,
            archiveQuantity: `${TSDB_BASE_URL}?start={0}&end={1}&m=sum:{2}{property={3}}`,
            archiveEnum: `${TSDB_BASE_URL}?start={0}&end={1}&m=sum:{2}{enum_value=*}`,
            last: `${TSDB_BASE_URL}/last/{0}`
        },
        analyze: {
            query: "http://" + hostname + ":8085/api/query",
            events: "http://" + hostname + ":8085/api/query/{0}/events"
        }
    },
    TOPICS: {
        "device_registered": 'ru.semiot.devices.newandobserving',
        "device_turned_off": 'ru.semiot.devices.turnoff',
        "device_remove": 'ru.semiot.devices.remove'
    },
    SPARQL: {
        prefixes: {
            rdfs: 'http://www.w3.org/2000/01/rdf-schema#',
            ssn: 'http://purl.oclc.org/NET/ssnx/ssn#',
            rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
            ssncom: 'http://purl.org/NET/ssnext/communication#',
            saref: 'http://ontology.tno.nl/saref#',
            mcht: 'http://purl.org/NET/ssnext/machinetools#',
            qudt: 'http://qudt.org/schema/qudt#',
            "qudt-quantity": 'http://qudt.org/vocab/quantity#',
            "qudt-unit": "http://qudt.org/vocab/unit#",
            proto: "http://w3id.org/semiot/ontologies/proto#",
            om: 'http://purl.org/ifgi/om#',
            ext: 'http://w3id.org/qudt/vocab/quantity/ext#'
        },
        types: {
            heatSystem: "http://purl.org/NET/ssnext/heatmeters#HeatMeter",
            electricSystem: "http://purl.org/NET/ssnext/electricmeters#ElectricMeter",
            temperature: "http://purl.org/NET/ssnext/heatmeters#Temperature",
            heat: "http://purl.org/NET/ssnext/heatmeters#Heat",
            observationResult: "http://purl.org/NET/ssnext/meters/core#hasQuantityValue"
        },
        queries: {
            getAllSystems: [
                "SELECT DISTINCT ?label ?uri",
                "WHERE {",
                "   ?uri a ssn:System ;",
                "       proto:hasPrototype/rdfs:label ?label .",
                "}"
            ].join('\n'),
            getSystemSensors: `
                SELECT ?subsystem ?type ?observationType ?propLabel ?valueUnitLabel {
                  <{0}> ssn:hasSubSystem ?subsystem .
                  ?subsystem ssn:observes ?type .
                  ?subsystem ssn:hasMeasurementCapability ?mc .
                  ?mc ssn:forProperty ?prop .
                  ?prop rdfs:label ?propLabel .
                  ?mc ssn:hasMeasurementProperty ?mp .
                  ?mp ssn:hasValue ?v .
                  ?v a ?observationType .
                  ?v ssn:hasValue ?valueUnit .
                  ?valueUnit rdfs:label ?valueUnitLabel .
                }
            `,
            getSystemName: [
                "SELECT ?label {",
                "   <{0}> rdfs:label ?label, .",
                "}"
            ].join('\n'),
            getSystemDetail: `
                SELECT ?label ?topic {
                    <{0}> rdfs:label ?label ;
                        ssncom:hasCommunicationEndpoint ?endpoint .
                    ?endpoint ssncom:protocol "WAMP" ;
                        ssncom:topic ?topic .
                }
            `,
            getMachineToolStates: `
                SELECT ?stateURI ?stateLabel ?stateDescription
                WHERE {
                    ?stateURI rdf:type mcht:MachineToolWorkingStateValue ;
                        rdfs:label ?stateLabel ;
                        rdfs:comment ?stateDescription .
                }
            `
        }
    },
    TIMEZONE_OFFSET: -1 * new Date().getTimezoneOffset() * 60 * 1000 // in ms
};
<|endoftext|>