<commit_before>"use strict";

describe("compatibility/promise", function () {

    function generateTests (PromiseClass) {

        describe("simple usage", function () {

            it("waits for synchronous fulfilment", function (done) {
                new PromiseClass(function (resolve/*, reject*/) {
                    assert("function" === typeof resolve);
                    resolve("ok");
                })
                    .then(function (value) {
                        assert("ok" === value);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("waits for asynchronous fulfilment", function (done) {
                new PromiseClass(function (resolve/*, reject*/) {
                    assert("function" === typeof resolve);
                    setTimeout(function () {
                        resolve("ok");
                    }, 0);
                })
                    .then(function (value) {
                        assert("ok" === value);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("waits for synchronous rejection (rejection handler)", function (done) {
                var fulfilled = false;
                new PromiseClass(function (resolve, reject) {
                    assert("function" === typeof resolve);
                    assert("function" === typeof reject);
                    reject("ko");
                })
                    .then(function () {
                        fulfilled = true;
                    }, function (reason) {
                        assert(false === fulfilled);
                        assert("ko" === reason);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("waits for asynchronous rejection (rejection handler)", function (done) {
                var fulfilled = false;
                new PromiseClass(function (resolve, reject) {
                    assert("function" === typeof resolve);
                    assert("function" === typeof reject);
                    setTimeout(function () {
                        reject("ko");
                    }, 0);
                })
                    .then(function () {
                        fulfilled = true;
                    }, function (reason) {
                        assert(false === fulfilled);
                        assert("ko" === reason);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("waits for synchronous rejection (catch handler)", function (done) {
                new PromiseClass(function (resolve, reject) {
                    assert("function" === typeof resolve);
                    assert("function" === typeof reject);
                    reject("ko");
                })
                    .then(function () {
                        assert(false);
                    })["catch"](function (reason) {
                        try {
                            assert("ko" === reason);
                            done();
                        } catch (e) {
                            done(e);
                        }
                    });
            });

            it("waits for asynchronous rejection (catch handler)", function (done) {
                new PromiseClass(function (resolve, reject) {
                    assert("function" === typeof resolve);
                    assert("function" === typeof reject);
                    setTimeout(function () {
                        reject("ko");
                    }, 0);
                })
                    .then(function () {
                        assert(false);
                    })["catch"](function (reason) {
                        try {
                            assert("ko" === reason);
                            done();
                        } catch (e) {
                            done(e);
                        }
                    });
            });

            it("rejects automatically on exception", function (done) {
                new PromiseClass(function (resolve, reject) {
                    assert("function" === typeof resolve);
                    assert("function" === typeof reject);
                    throw new Error("ko");
                })
                    .then(function () {
                        assert(false);
                    }, function (reason) {
                        assert(reason instanceof Error);
                        assert("ko" === reason.message);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("catches exception from the fulfilment handler", function (done) {
                new PromiseClass(function (resolve, reject) {
                    assert("function" === typeof resolve);
                    assert("function" === typeof reject);
                    setTimeout(function () {
                        resolve("ok");
                    }, 0);
                })
                    .then(function (value) {
                        assert("ok" === value);
                        throw new Error("ko");
                    })["catch"](function (reason) {
                        try {
                            assert(reason instanceof Error);
                            assert("ko" === reason.message);
                            done();
                        } catch (e) {
                            done(e);
                        }
                    });
            });

            it("catches exception from the rejection handler", function (done) {
                new PromiseClass(function (resolve, reject) {
                    assert("function" === typeof resolve);
                    assert("function" === typeof reject);
                    setTimeout(function () {
                        reject("ko");
                    }, 0);
                })
                    .then(function () {
                        assert(false);
                    }, function (reason) {
                        assert("ko" === reason);
                        throw new Error("ko");
                    })["catch"](function (reason) {
                        try {
                            assert(reason instanceof Error);
                            assert("ko" === reason.message);
                            done();
                        } catch (e) {
                            done(e);
                        }
                    });
            });

        });

        describe("shortcuts", function () {

            it("offers Promise.resolve", function (done) {
                PromiseClass.resolve("ok")
                    .then(function (value) {
                        assert("ok" === value);
                        done();
                    }, function (/*reason*/) {
                        assert(false);
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("offers Promise.reject", function (done) {
                PromiseClass.reject("ko")
                    .then(function (/*value*/) {
                        assert(false);
                    }, function (reason) {
                        assert("ko" === reason);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

        });

        describe("chaining", function () {

            it("chains by passing results from one handler to the other", function (done) {
                new PromiseClass(function (resolve/*, reject*/) {
                    resolve("ok 1");
                })
                    .then(function (value) {
                        assert("ok 1" === value);
                        return "ok 2";
                    })
                    .then(undefined, function (reason) {
                        done(reason);
                    })
                    .then(function (value) {
                        assert("ok 2" === value);
                        return "ok 3";
                    })
                    .then(function (value) {
                        assert("ok 3" === value);
                        return "ok 4";
                    })
                    .then(function (value) {
                        assert("ok 4" === value);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("chains by returning a promise in the fulfilment handler", function (done) {
                new PromiseClass(function (resolve/*, reject*/) {
                    resolve("ok 1");
                })
                    .then(function (value) {
                        assert("ok 1" === value);
                        return PromiseClass.resolve("ok 2");
                    })
                    .then(function (value) {
                        assert("ok 2" === value);
                        return new PromiseClass(function (resolve/*, reject*/) {
                            setTimeout(function () {
                                resolve("ok 3");
                            }, 0);
                        });
                    })
                    .then(function (value) {
                        assert("ok 3" === value);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("stops on first error", function (done) {

                new PromiseClass(function (resolve/*, reject*/) {
                    resolve("ok 1");
                })
                    .then(function (value) {
                        assert("ok 1" === value);
                        return "ok 2";
                    })
                    .then(function (value) {
                        assert("ok 2" === value);
                        throw new Error("ko");
                    })
                    .then(function (/*value*/) {
                        assert(false);
                    })["catch"](function (reason) {
                        try {
                            assert(reason instanceof Error);
                            assert("ko" === reason.message);
                            done();
                        } catch (e) {
                            done(e);
                        }
                    });

            });

        });

        describe("synchronisation", function () {

            describe("Promise.all", function () {

                it("succeeds with an empty array", function (done) {
                    PromiseClass.all([])
                        .then(function (values) {
                            assert(0 === values.length);
                            done();
                        })["catch"](function (reason) {
                            done(reason);
                        });
                });

                it("works with one promise", function (done) {
                    PromiseClass.all([PromiseClass.resolve("ok")])
                        .then(function (values) {
                            assert(1 === values.length);
                            assert("ok" === values[0]);
                            done();
                        })["catch"](function (reason) {
                            done(reason);
                        });
                });

                it("waits for all promises to be resolved", function (done) {
                    var promises = [],
                        index;
                    for (index = 0; index < 10; ++index) {
                        promises.push(PromiseClass.resolve(index));
                    }
                    PromiseClass.all(promises)
                        .then(function (values) {
                            assert(45 === values.reduce(function (previousValue, currentValue) {
                                return previousValue + currentValue;
                            }));
                            done();
                        })["catch"](function (reason) {
                            done(reason);
                        });
                });

                it("fails on the first error", function (done) {
                    var promises = [],
                        index;
                    function resolveOrReject (value) {
                        if (0 === value % 2) {
                            return PromiseClass.reject(value);
                        }
                        return PromiseClass.resolve(value);
                    }
                    for (index = 0; index < 10; ++index) {
                        promises.push(resolveOrReject(index));
                    }
                    PromiseClass.all(promises)
                        .then(function (/*values*/) {
                            assert(false);
                        })["catch"](function (reason) {
                            try {
                                assert("number" === typeof reason);
                                assert(reason < 10);
                                done();
                            } catch (e) {
                                done(e);
                            }
                        });
                });

            });

            describe("Promise.race", function () {

                it("waits for the first promise that is resolved", function (done) {
                    var promises = [],
                        index;
                    function resolveAfter (value) {
                        return new PromiseClass(function (resolve/*, reject*/) {
                            setTimeout(function () {
                                resolve(value);
                            }, (10 - value) * 20); // Last should be the first to be executed
                        });
                    }
                    for (index = 0; index < 10; ++index) {
                        promises.push(resolveAfter(index));
                    }
                    PromiseClass.race(promises)
                        .then(function (value) {
                            assert(value === 9);
                            done();
                        })["catch"](function (reason) {
                            done(reason);
                        });
                });

                it("waits for the first promise that is resolved or rejected", function (done) {
                    var promises = [],
                        index;
                    function resolveOrRejectAfter (value) {
                        return new PromiseClass(function (resolve, reject) {
                            if (5 === value) {
                                setTimeout(function () {
                                    reject(value);
                                }, 20);
                            } else {
                                setTimeout(function () {
                                    resolve(value);
                                }, 50);
                            }
                        });
                    }
                    for (index = 0; index < 10; ++index) {
                        promises.push(resolveOrRejectAfter(index));
                    }
                    PromiseClass.race(promises)
                        .then(function (/*values*/) {
                            assert(false);
                        })["catch"](function (reason) {
                            try {
                                assert("number" === typeof reason);
                                assert(5 === reason);
                                done();
                            } catch (e) {
                                done(e);
                            }
                        });
                });

            });

        });

        describe("branching", function () {

            it("supports different branches", function (done) {
                var deferred = {};
                deferred.promise = new PromiseClass(function (resolve, reject) {
                    deferred.resolve = resolve;
                    deferred.reject = reject;
                });
                // branch 1
                var branch1 = deferred.promise
                    .then(function (value) {
                        return value + 1;
                    })
                    .then(function (value) {
                        return value + 2;
                    })
                    .then(function (value) {
                        return value + 3;
                    });
                // branch 2
                var branch2 = deferred.promise
                    .then(function (value) {
                        return 2 * value;
                    })
                    .then(function (value) {
                        return 3 * value;
                    });
                PromiseClass.all([branch1, branch2])
                    .then(function (values) {
                        assert(7 === values[0]);
                        assert(6 === values[1]);
                        done();
                    })["catch"](function (e) {
                        done(e);
                    });
                deferred.resolve(1);
            });

        });

    }

    describe("Promise", function () {

        generateTests(Promise);

    });

    if (gpf.internals && Promise !== gpf.internals._GpfPromise) {

        describe("(internal) _GpfPromise", function () {

            generateTests(gpf.internals._GpfPromise);

        });

    }

});
<commit_msg>Remove the use of setTimeout (#186)<commit_after>"use strict";

describe("compatibility/promise", function () {

    function generateTests (PromiseClass) {

        describe("simple usage", function () {

            it("waits for synchronous fulfilment", function (done) {
                new PromiseClass(function (resolve/*, reject*/) {
                    assert("function" === typeof resolve);
                    resolve("ok");
                })
                    .then(function (value) {
                        assert("ok" === value);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("waits for asynchronous fulfilment", function (done) {
                var callback;
                new PromiseClass(function (resolve/*, reject*/) {
                    callback = resolve;
                })
                    .then(function (value) {
                        assert("ok" === value);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
                callback("ok");
            });

            it("waits for synchronous rejection (rejection handler)", function (done) {
                var fulfilled = false;
                new PromiseClass(function (resolve, reject) {
                    assert("function" === typeof reject);
                    reject("ko");
                })
                    .then(function () {
                        fulfilled = true;
                    }, function (reason) {
                        assert(false === fulfilled);
                        assert("ko" === reason);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("waits for asynchronous rejection (rejection handler)", function (done) {
                var fulfilled = false,
                    callback;
                new PromiseClass(function (resolve, reject) {
                    callback = reject;
                })
                    .then(function () {
                        fulfilled = true;
                    }, function (reason) {
                        assert(false === fulfilled);
                        assert("ko" === reason);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
                callback("ko");
            });

            it("waits for synchronous rejection (catch handler)", function (done) {
                new PromiseClass(function (resolve, reject) {
                    reject("ko");
                })
                    .then(function () {
                        assert(false);
                    })["catch"](function (reason) {
                        try {
                            assert("ko" === reason);
                            done();
                        } catch (e) {
                            done(e);
                        }
                    });
            });

            it("waits for asynchronous rejection (catch handler)", function (done) {
                var callback;
                new PromiseClass(function (resolve, reject) {
                    callback = reject;
                })
                    .then(function () {
                        assert(false);
                    })["catch"](function (reason) {
                        try {
                            assert("ko" === reason);
                            done();
                        } catch (e) {
                            done(e);
                        }
                    });
                callback("ko");
            });

            it("rejects automatically on exception", function (done) {
                new PromiseClass(function (/*resolve, reject*/) {
                    throw new Error("ko");
                })
                    .then(function () {
                        assert(false);
                    }, function (reason) {
                        assert(reason instanceof Error);
                        assert("ko" === reason.message);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("catches exception from the fulfilment handler", function (done) {
                new PromiseClass(function (resolve/*, reject*/) {
                    resolve("ok");
                })
                    .then(function (value) {
                        assert("ok" === value);
                        throw new Error("ko");
                    })["catch"](function (reason) {
                        try {
                            assert(reason instanceof Error);
                            assert("ko" === reason.message);
                            done();
                        } catch (e) {
                            done(e);
                        }
                    });
            });

            it("catches exception from the rejection handler", function (done) {
                new PromiseClass(function (resolve, reject) {
                    reject("ko");
                })
                    .then(function () {
                        assert(false);
                    }, function (reason) {
                        assert("ko" === reason);
                        throw new Error("ko");
                    })["catch"](function (reason) {
                        try {
                            assert(reason instanceof Error);
                            assert("ko" === reason.message);
                            done();
                        } catch (e) {
                            done(e);
                        }
                    });
            });

        });

        describe("shortcuts", function () {

            it("offers Promise.resolve", function (done) {
                PromiseClass.resolve("ok")
                    .then(function (value) {
                        assert("ok" === value);
                        done();
                    }, function (/*reason*/) {
                        assert(false);
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("offers Promise.reject", function (done) {
                PromiseClass.reject("ko")
                    .then(function (/*value*/) {
                        assert(false);
                    }, function (reason) {
                        assert("ko" === reason);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

        });

        describe("chaining", function () {

            it("chains by passing results from one handler to the other", function (done) {
                new PromiseClass(function (resolve/*, reject*/) {
                    resolve("ok 1");
                })
                    .then(function (value) {
                        assert("ok 1" === value);
                        return "ok 2";
                    })
                    .then(undefined, function (reason) {
                        done(reason);
                    })
                    .then(function (value) {
                        assert("ok 2" === value);
                        return "ok 3";
                    })
                    .then(function (value) {
                        assert("ok 3" === value);
                        return "ok 4";
                    })
                    .then(function (value) {
                        assert("ok 4" === value);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("chains by returning a promise in the fulfilment handler", function (done) {
                new PromiseClass(function (resolve/*, reject*/) {
                    resolve("ok 1");
                })
                    .then(function (value) {
                        assert("ok 1" === value);
                        return PromiseClass.resolve("ok 2");
                    })
                    .then(function (value) {
                        assert("ok 2" === value);
                        return new PromiseClass(function (resolve/*, reject*/) {
                            resolve("ok 3");
                        });
                    })
                    .then(function (value) {
                        assert("ok 3" === value);
                        done();
                    })["catch"](function (reason) {
                        done(reason);
                    });
            });

            it("stops on first error", function (done) {

                new PromiseClass(function (resolve/*, reject*/) {
                    resolve("ok 1");
                })
                    .then(function (value) {
                        assert("ok 1" === value);
                        return "ok 2";
                    })
                    .then(function (value) {
                        assert("ok 2" === value);
                        throw new Error("ko");
                    })
                    .then(function (/*value*/) {
                        assert(false);
                    })["catch"](function (reason) {
                        try {
                            assert(reason instanceof Error);
                            assert("ko" === reason.message);
                            done();
                        } catch (e) {
                            done(e);
                        }
                    });

            });

        });

        describe("synchronisation", function () {

            describe("Promise.all", function () {

                it("succeeds with an empty array", function (done) {
                    PromiseClass.all([])
                        .then(function (values) {
                            assert(0 === values.length);
                            done();
                        })["catch"](function (reason) {
                            done(reason);
                        });
                });

                it("works with one promise", function (done) {
                    PromiseClass.all([PromiseClass.resolve("ok")])
                        .then(function (values) {
                            assert(1 === values.length);
                            assert("ok" === values[0]);
                            done();
                        })["catch"](function (reason) {
                            done(reason);
                        });
                });

                it("waits for all promises to be resolved", function (done) {
                    var promises = [],
                        index;
                    for (index = 0; index < 10; ++index) {
                        promises.push(PromiseClass.resolve(index));
                    }
                    PromiseClass.all(promises)
                        .then(function (values) {
                            assert(45 === values.reduce(function (previousValue, currentValue) {
                                return previousValue + currentValue;
                            }));
                            done();
                        })["catch"](function (reason) {
                            done(reason);
                        });
                });

                it("fails on the first error", function (done) {
                    var promises = [],
                        index;
                    function resolveOrReject (value) {
                        if (0 === value % 2) {
                            return PromiseClass.reject(value);
                        }
                        return PromiseClass.resolve(value);
                    }
                    for (index = 0; index < 10; ++index) {
                        promises.push(resolveOrReject(index));
                    }
                    PromiseClass.all(promises)
                        .then(function (/*values*/) {
                            assert(false);
                        })["catch"](function (reason) {
                            try {
                                assert("number" === typeof reason);
                                assert(reason < 10);
                                done();
                            } catch (e) {
                                done(e);
                            }
                        });
                });

            });

            describe("Promise.race", function () {

                it("waits for the first promise that is resolved", function (done) {
                    var promises = [],
                        index,
                        callbacks = [];
                    function resolveAfter (value) {
                        return new PromiseClass(function (resolve/*, reject*/) {
                            callbacks.unshift(resolve.bind(null, value)); // reverse order
                        });
                    }
                    for (index = 0; index < 10; ++index) {
                        promises.push(resolveAfter(index));
                    }
                    PromiseClass.race(promises)
                        .then(function (value) {
                            assert(value === 9);
                            callbacks[9](); // Ignored
                            done();
                        })["catch"](function (reason) {
                            done(reason);
                        });
                    callbacks[0](); // Only this one should win Promise.race
                    callbacks[1]();
                    callbacks[2]();
                });

                it("waits for the first promise that is resolved or rejected", function (done) {
                    var promises = [],
                        index,
                        callbacks = [];
                    function resolveOrRejectAfter (value) {
                        return new PromiseClass(function (resolve, reject) {
                            if (5 === value) {
                                callbacks.push(reject.bind(null, value));
                            } else {
                                callbacks.push(resolve.bind(null, value));
                            }
                        });
                    }
                    for (index = 0; index < 10; ++index) {
                        promises.push(resolveOrRejectAfter(index));
                    }
                    PromiseClass.race(promises)
                        .then(function (/*values*/) {
                            assert(false);
                        })["catch"](function (reason) {
                            try {
                                assert("number" === typeof reason);
                                assert(5 === reason);
                                callbacks[9](); // Ignored
                                done();
                            } catch (e) {
                                done(e);
                            }
                        });
                    callbacks[5]();  // Only this one should win Promise.race
                    callbacks[0]();
                    callbacks[1]();
                });

            });

        });

        describe("branching", function () {

            it("supports different branches", function (done) {
                var deferred = {};
                deferred.promise = new PromiseClass(function (resolve, reject) {
                    deferred.resolve = resolve;
                    deferred.reject = reject;
                });
                // branch 1
                var branch1 = deferred.promise
                    .then(function (value) {
                        return value + 1;
                    })
                    .then(function (value) {
                        return value + 2;
                    })
                    .then(function (value) {
                        return value + 3;
                    });
                // branch 2
                var branch2 = deferred.promise
                    .then(function (value) {
                        return 2 * value;
                    })
                    .then(function (value) {
                        return 3 * value;
                    });
                PromiseClass.all([branch1, branch2])
                    .then(function (values) {
                        assert(7 === values[0]);
                        assert(6 === values[1]);
                        done();
                    })["catch"](function (e) {
                        done(e);
                    });
                deferred.resolve(1);
            });

        });

    }

    describe("Promise", function () {

        generateTests(Promise);

    });

    if (gpf.internals && Promise !== gpf.internals._GpfPromise) {

        describe("(internal) _GpfPromise", function () {

            generateTests(gpf.internals._GpfPromise);

        });

    }

});
<|endoftext|>


<commit_before>const {
  GraphQLObjectType,
  GraphQLList,
  GraphQLString,
  GraphQLInt,
  GraphQLEnumType,
  GraphQLJSON
} = require("gatsby/graphql");
const _ = require("lodash");
const remark = require("remark");
const retext = require("retext");
const visit = require("unist-util-visit");
const remove = require("unist-util-remove");
const toString = require("mdast-util-to-string");
const generateTOC = require("mdast-util-toc");
const stripMarkdown = require("strip-markdown");
const prune = require("underscore.string/prune");

const debug = require("debug")("gatsby-mdx:extend-node-type");
const renderHTML = require("../utils/render-html");
const getTableOfContents = require("../utils/get-table-of-content");
const defaultOptions = require("../utils/default-options");
const genMDX = require("../utils/gen-mdx");

module.exports = (
  { type, store, pathPrefix, getNode, getNodes, cache, reporter },
  pluginOptions
) => {
  if (type.name !== `Mdx`) {
    return {};
  }

  const options = defaultOptions(pluginOptions);

  for (let plugin of options.gatsbyRemarkPlugins) {
    if (!plugin.resolve) {
      throw new Error(
        'gatsby-remark plugins must be configured in the form {resolve: "plugin", options: {}}'
      );
    }
    debug("requiring", plugin.resolve);
    const requiredPlugin = require(plugin.resolve);
    debug("required", plugin);
    if (_.isFunction(requiredPlugin.setParserPlugins)) {
      for (let parserPlugin of requiredPlugin.setParserPlugins(
        plugin.pluginOptions
      )) {
        if (_.isArray(parserPlugin)) {
          const [parser, parserPluginOptions] = parserPlugin;
          debug("adding mdPlugin with options", plugin, parserPluginOptions);
          options.mdPlugins.push([parser, parserPluginOptions]);
        } else {
          debug("adding mdPlugin", plugin);
          options.mdPlugins.push(parserPlugin);
        }
      }
    }
  }

  const processMDX = ({ node }) =>
    genMDX({ node, getNode, getNodes, reporter, cache, pathPrefix, options });
  return new Promise((resolve /*, reject*/) => {
    async function getText(mdxNode) {
      const { mdast } = await processMDX({ node: mdxNode });

      // convert the mdxast to back to mdast
      remove(mdast, "import");
      remove(mdast, "export");
      visit(mdast, "jsx", node => {
        node.type = "html";
      });

      const textAst = await remark()
        .use(stripMarkdown)
        .run(mdast);

      return remark().stringify(textAst);
    }

    const HeadingType = new GraphQLObjectType({
      name: `MdxHeadingMdx`,
      fields: {
        value: {
          type: GraphQLString,
          resolve(heading) {
            return heading.value;
          }
        },
        depth: {
          type: GraphQLInt,
          resolve(heading) {
            return heading.depth;
          }
        }
      }
    });
    const Headings = new GraphQLEnumType({
      name: `HeadingsMdx`,
      values: {
        h1: { value: 1 },
        h2: { value: 2 },
        h3: { value: 3 },
        h4: { value: 4 },
        h5: { value: 5 },
        h6: { value: 6 }
      }
    });

    return resolve({
      code: {
        resolve(mdxNode) {
          return mdxNode;
        },
        type: new GraphQLObjectType({
          name: `MDXCodeMdx`,
          fields: {
            body: {
              type: GraphQLString,
              async resolve(mdxNode) {
                const { body } = await processMDX({ node: mdxNode });
                return body;
              }
            },
            scope: {
              type: GraphQLString,
              async resolve() {
                return "";
              }
            }
          }
        })
      },
      excerpt: {
        type: GraphQLString,
        args: {
          pruneLength: {
            type: GraphQLInt,
            defaultValue: 140
          }
        },
        async resolve(mdxNode, { pruneLength }) {
          if (mdxNode.excerpt) {
            return Promise.resolve(mdxNode.excerpt);
          }
          const { mdast } = await processMDX({ node: mdxNode });

          const excerptNodes = [];
          visit(mdast, node => {
            if (node.type === "text" || node.type === "inlineCode") {
              excerptNodes.push(node.value);
            }
            return;
          });

          return prune(excerptNodes.join(" "), pruneLength, "…");
        }
      },
      headings: {
        type: new GraphQLList(HeadingType),
        args: {
          depth: {
            type: Headings
          }
        },
        async resolve(mdxNode, { depth }) {
          // TODO: change this to operate on html instead of mdast
          const { mdast } = await processMDX({ node: mdxNode });
          let headings = [];
          visit(mdast, "heading", heading => {
            headings.push({
              value: toString(heading),
              depth: heading.depth
            });
          });
          if (typeof depth === `number`) {
            headings = headings.filter(heading => heading.depth === depth);
          }
          return headings;
        }
      },
      html: {
        type: GraphQLString,
        async resolve(mdxNode) {
          if (mdxNode.html) {
            return Promise.resolve(mdxNode.html);
          }
          const { body } = await processMDX({ node: mdxNode });
          const withMDX = renderHTML(body);
          return withMDX(store.getState().webpack);
        }
      },
      tableOfContents: {
        type: GraphQLJSON,
        args: {
          maxDepth: {
            type: GraphQLInt,
            default: 6
          }
        },
        async resolve(mdxNode, { maxDepth }) {
          const { mdast } = await processMDX({ node: mdxNode });
          const toc = generateTOC(mdast, maxDepth);

          return getTableOfContents(toc.map, {});
        }
      },
      timeToRead: {
        type: GraphQLInt,
        async resolve(mdxNode) {
          const text = await getText(mdxNode);
          let timeToRead = 0;
          const avgWPM = 265;
          const wordCount = _.words(text).length;
          timeToRead = Math.round(wordCount / avgWPM);
          if (timeToRead === 0) {
            timeToRead = 1;
          }
          return timeToRead;
        }
      },
      wordCount: {
        type: new GraphQLObjectType({
          name: `wordCountsMdx`,
          fields: {
            paragraphs: {
              type: GraphQLInt
            },
            sentences: {
              type: GraphQLInt
            },
            words: {
              type: GraphQLInt
            }
          }
        }),
        async resolve(mdxNode) {
          let counts = {};

          const text = await getText(mdxNode);

          await retext()
            .use(count)
            .process(text);

          return {
            paragraphs: counts.ParagraphNode,
            sentences: counts.SentenceNode,
            words: counts.WordNode
          };

          function count() {
            return counter;
            function counter(tree) {
              visit(tree, visitor);
              function visitor(node) {
                counts[node.type] = (counts[node.type] || 0) + 1;
              }
            }
          }
        }
      }
    });
  });
};
<commit_msg>adding more helpful error when html query fails (fixes #250) (#298)<commit_after>const {
  GraphQLObjectType,
  GraphQLList,
  GraphQLString,
  GraphQLInt,
  GraphQLEnumType,
  GraphQLJSON
} = require("gatsby/graphql");
const _ = require("lodash");
const remark = require("remark");
const retext = require("retext");
const visit = require("unist-util-visit");
const remove = require("unist-util-remove");
const toString = require("mdast-util-to-string");
const generateTOC = require("mdast-util-toc");
const stripMarkdown = require("strip-markdown");
const prune = require("underscore.string/prune");

const debug = require("debug")("gatsby-mdx:extend-node-type");
const renderHTML = require("../utils/render-html");
const getTableOfContents = require("../utils/get-table-of-content");
const defaultOptions = require("../utils/default-options");
const genMDX = require("../utils/gen-mdx");

module.exports = (
  { type, store, pathPrefix, getNode, getNodes, cache, reporter },
  pluginOptions
) => {
  if (type.name !== `Mdx`) {
    return {};
  }

  const options = defaultOptions(pluginOptions);

  for (let plugin of options.gatsbyRemarkPlugins) {
    if (!plugin.resolve) {
      throw new Error(
        'gatsby-remark plugins must be configured in the form {resolve: "plugin", options: {}}'
      );
    }
    debug("requiring", plugin.resolve);
    const requiredPlugin = require(plugin.resolve);
    debug("required", plugin);
    if (_.isFunction(requiredPlugin.setParserPlugins)) {
      for (let parserPlugin of requiredPlugin.setParserPlugins(
        plugin.pluginOptions
      )) {
        if (_.isArray(parserPlugin)) {
          const [parser, parserPluginOptions] = parserPlugin;
          debug("adding mdPlugin with options", plugin, parserPluginOptions);
          options.mdPlugins.push([parser, parserPluginOptions]);
        } else {
          debug("adding mdPlugin", plugin);
          options.mdPlugins.push(parserPlugin);
        }
      }
    }
  }

  const processMDX = ({ node }) =>
    genMDX({ node, getNode, getNodes, reporter, cache, pathPrefix, options });
  return new Promise((resolve /*, reject*/) => {
    async function getText(mdxNode) {
      const { mdast } = await processMDX({ node: mdxNode });

      // convert the mdxast to back to mdast
      remove(mdast, "import");
      remove(mdast, "export");
      visit(mdast, "jsx", node => {
        node.type = "html";
      });

      const textAst = await remark()
        .use(stripMarkdown)
        .run(mdast);

      return remark().stringify(textAst);
    }

    const HeadingType = new GraphQLObjectType({
      name: `MdxHeadingMdx`,
      fields: {
        value: {
          type: GraphQLString,
          resolve(heading) {
            return heading.value;
          }
        },
        depth: {
          type: GraphQLInt,
          resolve(heading) {
            return heading.depth;
          }
        }
      }
    });
    const Headings = new GraphQLEnumType({
      name: `HeadingsMdx`,
      values: {
        h1: { value: 1 },
        h2: { value: 2 },
        h3: { value: 3 },
        h4: { value: 4 },
        h5: { value: 5 },
        h6: { value: 6 }
      }
    });

    return resolve({
      code: {
        resolve(mdxNode) {
          return mdxNode;
        },
        type: new GraphQLObjectType({
          name: `MDXCodeMdx`,
          fields: {
            body: {
              type: GraphQLString,
              async resolve(mdxNode) {
                const { body } = await processMDX({ node: mdxNode });
                return body;
              }
            },
            scope: {
              type: GraphQLString,
              async resolve() {
                return "";
              }
            }
          }
        })
      },
      excerpt: {
        type: GraphQLString,
        args: {
          pruneLength: {
            type: GraphQLInt,
            defaultValue: 140
          }
        },
        async resolve(mdxNode, { pruneLength }) {
          if (mdxNode.excerpt) {
            return Promise.resolve(mdxNode.excerpt);
          }
          const { mdast } = await processMDX({ node: mdxNode });

          const excerptNodes = [];
          visit(mdast, node => {
            if (node.type === "text" || node.type === "inlineCode") {
              excerptNodes.push(node.value);
            }
            return;
          });

          return prune(excerptNodes.join(" "), pruneLength, "…");
        }
      },
      headings: {
        type: new GraphQLList(HeadingType),
        args: {
          depth: {
            type: Headings
          }
        },
        async resolve(mdxNode, { depth }) {
          // TODO: change this to operate on html instead of mdast
          const { mdast } = await processMDX({ node: mdxNode });
          let headings = [];
          visit(mdast, "heading", heading => {
            headings.push({
              value: toString(heading),
              depth: heading.depth
            });
          });
          if (typeof depth === `number`) {
            headings = headings.filter(heading => heading.depth === depth);
          }
          return headings;
        }
      },
      html: {
        type: GraphQLString,
        async resolve(mdxNode) {
          if (mdxNode.html) {
            return Promise.resolve(mdxNode.html);
          }
          const { body } = await processMDX({ node: mdxNode });
          try {
            const withMDX = renderHTML(body);
            return withMDX(store.getState().webpack);
          } catch (e) {
            throw new Error(
              "Error querying the `html` field. This field is inded for use with RSS feed generation.\n" +
                "If you're trying to use it in application-level code, try querying for code.body instead.\n" +
                "Original error: " +
                e
            );
          }
        }
      },
      tableOfContents: {
        type: GraphQLJSON,
        args: {
          maxDepth: {
            type: GraphQLInt,
            default: 6
          }
        },
        async resolve(mdxNode, { maxDepth }) {
          const { mdast } = await processMDX({ node: mdxNode });
          const toc = generateTOC(mdast, maxDepth);

          return getTableOfContents(toc.map, {});
        }
      },
      timeToRead: {
        type: GraphQLInt,
        async resolve(mdxNode) {
          const text = await getText(mdxNode);
          let timeToRead = 0;
          const avgWPM = 265;
          const wordCount = _.words(text).length;
          timeToRead = Math.round(wordCount / avgWPM);
          if (timeToRead === 0) {
            timeToRead = 1;
          }
          return timeToRead;
        }
      },
      wordCount: {
        type: new GraphQLObjectType({
          name: `wordCountsMdx`,
          fields: {
            paragraphs: {
              type: GraphQLInt
            },
            sentences: {
              type: GraphQLInt
            },
            words: {
              type: GraphQLInt
            }
          }
        }),
        async resolve(mdxNode) {
          let counts = {};

          const text = await getText(mdxNode);

          await retext()
            .use(count)
            .process(text);

          return {
            paragraphs: counts.ParagraphNode,
            sentences: counts.SentenceNode,
            words: counts.WordNode
          };

          function count() {
            return counter;
            function counter(tree) {
              visit(tree, visitor);
              function visitor(node) {
                counts[node.type] = (counts[node.type] || 0) + 1;
              }
            }
          }
        }
      }
    });
  });
};
<|endoftext|>


<commit_before>var _ = require('lodash');
var async = require('async');
var Message = require('../models/Message');
var Thread = require('../models/Thread');
var mongoose = require('mongoose');

function toObjectId(str) {
    var ObjectId = (require('mongoose').Types.ObjectId);
    return new ObjectId(str);
};

function getThreadMessages (thread, callback, current_user_id) {
  return Message.find({'_thread': toObjectId(thread._id)})
    .populate('_sender')
    .exec(function (err, messages) {
        if (err) {
            callback(err, null);
        } else {
            var other_participants = thread._participants.filter(function (user) {
                return user._id != current_user_id;
            });
            callback(null, {
                participants: other_participants,
                messages: messages,
                _id: thread._id,
            });
        }
    });
}

/**
 * GET /messages
 * Show a user's messages.
 */
exports.showMessages = function(req, res) {
  Thread.find({'_participants': toObjectId(req.user.id)})
    .populate('_participants')
    .exec(function (err, threads) {
        var func = function (thread, callback) {
            getThreadMessages(thread, callback, req.user.id);
        }
        async.map(threads, func, function (err, threads_with_messages) {
            res.render('messages/showMessages', {
                threads: threads_with_messages
            });
        });
  })
};

exports.getMessages = function(req, res) {
    var thread_id = req.params.id;
    Message.find({'_thread': toObjectId(thread_id)})
    .populate('_sender')
    .exec(function (err, messages) {
        res.json(messages.map(function (message) {
            return {
                message: message.message,
                timeSent: message.timeSent,
                author: {
                    name: message._sender.profile.name,
                    pic: message._sender.profile.picture,
                    id: message._sender._id,
                    isMe: (message._sender._id == req.user.id),
                },
            };
        }));
    });
};
<commit_msg>Sort threads before loading them in messages page<commit_after>var _ = require('lodash');
var async = require('async');
var Message = require('../models/Message');
var Thread = require('../models/Thread');
var mongoose = require('mongoose');

function toObjectId(str) {
    var ObjectId = (require('mongoose').Types.ObjectId);
    return new ObjectId(str);
};

function getThreadMessages (thread, callback, current_user_id) {
  return Message.find({'_thread': toObjectId(thread._id)})
    .populate('_sender')
    .exec(function (err, messages) {
        if (err) {
            callback(err, null);
        } else {
            var other_participants = thread._participants.filter(function (user) {
                return user._id != current_user_id;
            });
            callback(null, {
                participants: other_participants,
                messages: messages,
                _id: thread._id,
            });
        }
    });
}

/**
 * GET /messages
 * Show a user's messages.
 */
exports.showMessages = function(req, res) {
  Thread.find({'_participants': toObjectId(req.user.id)})
    .populate('_participants')
    .exec(function (err, threads) {
        var func = function (thread, callback) {
            getThreadMessages(thread, callback, req.user.id);
        }
        async.map(threads, func, function (err, threads_with_messages) {
            var sorted_threads = threads_with_messages.sort(function (a, b) {
                                    return b.messages.slice(-1)[0].timeSent - a.messages.slice(-1)[0].timeSent;
                                 });
            res.render('messages/showMessages', {
                threads: sorted_threads,
            });
        });
  })
};

exports.getMessages = function(req, res) {
    var thread_id = req.params.id;
    Message.find({'_thread': toObjectId(thread_id)})
    .populate('_sender')
    .exec(function (err, messages) {
        res.json(messages.map(function (message) {
            return {
                message: message.message,
                timeSent: message.timeSent,
                author: {
                    name: message._sender.profile.name,
                    pic: message._sender.profile.picture,
                    id: message._sender._id,
                    isMe: (message._sender._id == req.user.id),
                },
            };
        }));
    });
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
var configParser = require('./config_parser');

describe('config_parse.js', function () {
    'use strict';
    describe('should have defined:', function () {
        it('getTagsFormat', function () {
            expect(configParser.getTagsFormat);
        });
        it('getCommitConfBy', function () {
            expect(configParser.getCommitConfBy);
        });
    });
    describe('getTagsFormat:', function () {
        it('should return an array with elements', function () {
            expect(configParser.getTagsFormat().length).toBeGreaterThan(0);
        });
    });
    describe('getCommitConfBy:', function () {
        it('should return an empty array without arguments', function () {
            expect(configParser.getCommitConfBy().length).toBe(0);
        });
        it('should return results with a correct parameter type', function () {
            expect(configParser.getCommitConfBy('tag').length).toBeGreaterThan(0);
        });
    });
});
<commit_msg>[FIX] unit test: config parser path<commit_after>#!/usr/bin/env node
var configParser = require('./config-parser');

describe('config_parse.js', function () {
    'use strict';
    describe('should have defined:', function () {
        it('getTagsFormat', function () {
            expect(configParser.getTagsFormat);
        });
        it('getCommitConfBy', function () {
            expect(configParser.getCommitConfBy);
        });
    });
    describe('getTagsFormat:', function () {
        it('should return an array with elements', function () {
            expect(configParser.getTagsFormat().length).toBeGreaterThan(0);
        });
    });
    describe('getCommitConfBy:', function () {
        it('should return an empty array without arguments', function () {
            expect(configParser.getCommitConfBy().length).toBe(0);
        });
        it('should return results with a correct parameter type', function () {
            expect(configParser.getCommitConfBy('tag').length).toBeGreaterThan(0);
        });
    });
});
<|endoftext|>


<commit_before>define(["Test", "Tone/core/IntervalTimeline", "helper/Basic"], function (Test, IntervalTimeline, Basic) {

	describe("IntervalTimeline", function(){

		Basic(IntervalTimeline);

		context("inserting/deleting events", function(){

			it ("accepts events into the timeline", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"state" : "A",
					"duration" : 0.2,
					"time"  : 0
				});
				sched.add({
					"state" : "B",
					"duration" : 0.4,
					"time"  : 1
				});
				sched.add({
					"state" : "C",
					"duration" : 12,
					"time"  : 2
				});
				sched.dispose();
			});

			it ("computes the lenght of the timeline correctly after adding events", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"state" : "A",
					"duration" : 0.2,
					"time"  : 0
				});
				sched.add({
					"state" : "B",
					"duration" : 0.4,
					"time"  : 1
				});
				sched.add({
					"state" : "C",
					"duration" : 12,
					"time"  : 2
				});
				expect(sched.length).to.equal(3);
				sched.dispose();
			});

			it ("can remove events from the timeline", function(){
				var sched = new IntervalTimeline();

				var ev0 = {
					"duration" : 0.2,
					"time"  : 0
				};
				var ev1 = {
					"duration" : 0.2,
					"time"  : 0.2
				};
				var ev2 = {
					"duration" : 0.2,
					"time"  : 0.1
				};
				sched.add(ev0);
				sched.add(ev1);
				sched.add(ev2);
				expect(sched.length).to.equal(3);
				sched.remove(ev0);
				sched.remove(ev1);
				expect(sched.length).to.equal(1);
				sched.remove(ev2);
				expect(sched.length).to.equal(0);
				sched.dispose();
			});

			it ("can add and remove and add again events from the timeline", function(){
				var sched = new IntervalTimeline();

				var ev0 = {
					"duration" : 0.2,
					"time"  : 0
				};
				var ev1 = {
					"duration" : 0.2,
					"time"  : 0.2
				};
				var ev2 = {
					"duration" : 0.2,
					"time"  : 0.1
				};
				sched.add(ev0);
				sched.add(ev1);
				sched.add(ev2);
				expect(sched.length).to.equal(3);
				sched.remove(ev0);
				sched.remove(ev1);
				expect(sched.length).to.equal(1);
				sched.add(ev0);
				sched.add(ev1);
				expect(sched.length).to.equal(3);
				sched.dispose();
			});

			it ("throws an error if events do not have both time and duration attributes", function(){
				var sched = new IntervalTimeline();
				expect(function(){
					sched.add({
						"time" : 0
					});
				}).to.throw(Error);
				expect(function(){
					sched.add({
						"duration" : 0
					});
				}).to.throw(Error);
				sched.dispose();
			});

		});

		context("getting events", function(){

			it ("returns null when no events are in the timeline", function(){
				var sched = new IntervalTimeline();
				expect(sched.get(3)).to.equal(null);
				sched.dispose();
			});

			it ("returns the event which overlaps the given time", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"state" : "A",
					"duration" : Infinity,
					"time"  : 0
				});
				sched.add({
					"state" : "B",
					"duration" : 0.4,
					"time"  : 1
				});
				sched.add({
					"state" : "C",
					"duration" : 12,
					"time"  : 2
				});
				expect(sched.get(0.2).state).to.equal("A");
				sched.dispose();
			});

			it ("returns events exclusive of the end time", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"state" : "A",
					"duration" : 1,
					"time"  : 0
				});
				expect(sched.get(0.99).state).to.equal("A");
				expect(sched.get(1)).to.equal(null);
				sched.dispose();
			});

			it ("factors in start position and duration when checking for overlaps", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"duration" : 0.4,
					"time"  : 0
				});
				expect(sched.get(0.5)).to.be.null;
				expect(sched.get(-1)).to.be.null;
				expect(sched.get(0)).to.not.be.null;
				expect(sched.get(0.39)).to.not.be.null;
				sched.dispose();
			});

			it ("returns the event whose start is closest to the given time", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"state" : "A",
					"duration" : Infinity,
					"time"  : 0
				});
				sched.add({
					"state" : "B",
					"duration" : 0.4,
					"time"  : 0.2
				});
				sched.add({
					"state" : "C",
					"duration" : 12,
					"time"  : 2
				});
				expect(sched.get(0.2).state).to.equal("B");
				sched.dispose();
			});

			it ("returns the events correctly after some events are removed", function(){
				var sched = new IntervalTimeline();
				var ev0 = {
					"state" : "A",
					"duration" : 0.2,
					"time"  : 0.1
				};
				var ev1 = {
					"state" : "B",
					"duration" : 0.3,
					"time"  : 0.2
				};
				var ev2 = {
					"state" : "C",
					"duration" : Infinity,
					"time"  : 0
				};
				sched.add(ev0);
				sched.add(ev1);
				sched.add(ev2);
				sched.remove(ev0);
				sched.remove(ev1);
				expect(sched.get(0.2)).to.not.be.null;
				expect(sched.get(0.2).state).to.equal("C");
				sched.dispose();
			});

			it ("can handle many items", function(){
				var sched = new IntervalTimeline();
				var len = 5000;
				var events = [];
				var duration = 1;
				var time = 0;
				for (var i = 0; i < len; i++){
					var event = {
						"time" : time,
						"duration" : duration
					};
					time = (time + 3.1) % 109;
					duration = (duration + 5.7) % 19;
					sched.add(event);
					events.push(event);
				}
				for (var j = 0; j < events.length; j++){
					var event = events[j];
					expect(sched.get(event.time).time).to.equal(event.time);
				}

				for (var k = 0; k < events.length; k++){
					sched.remove(events[k]);
					expect(sched.length).to.equal(events.length - k - 1);
				}
				sched.dispose();
			});

		});

		context("cancelling", function(){

			it ("can cancel items after the given time", function(){
				var sched = new IntervalTimeline();
				for (var i = 5; i < 100; i++){
					sched.add({
						"time" : i,
						"duration" : 10
					});
				}
				sched.cancel(10);
				expect(sched.length).to.equal(5);
				sched.cancel(0);
				expect(sched.length).to.equal(0);
				sched.dispose();
			});
		});

		context("Iterators", function(){

			it("iterates over all items and returns and item", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0, "duration" : 5});
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEach(function(event){
					expect(event).to.be.an.object;
					count++;
				});
				expect(count).to.equal(5);
				sched.dispose();
			});

			it("iterates over all items overlapping the given time", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0, "duration" : 5});
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEachAtTime(0.3, function(event){
					expect(event).to.be.an.object;
					expect(event.time).to.be.at.most(0.3);
					count++;
				});
				expect(count).to.equal(4);
				sched.dispose();
			});

			it("handles time ranges before the available objects", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEachAtTime(0, function(){
					count++;
				});
				expect(count).to.equal(0);
				sched.dispose();
			});

			it("handles time ranges after the available objects", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEachAtTime(5.5, function(){
					count++;
				});
				expect(count).to.equal(0);
				sched.dispose();
			});

			it("iterates over all items after the given time", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEachAfter(0.2, function(event){
					expect(event).to.be.an.object;
					expect(event.time).to.be.gte(0.2);
					count++;
				});
				expect(count).to.equal(3);
				count = 0;
				sched.forEachAfter(0.35, function(event){
					expect(event.time).to.be.gte(0.35);
					count++;
				});
				expect(count).to.equal(1);
				sched.dispose();
			});

			it("handles time ranges after the available objects", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEachAfter(0.5, function(){
					count++;
				});
				expect(count).to.equal(0);
				sched.dispose();
			});

			it("iterates over all items", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEach(function(){
					count++;
				});
				expect(count).to.equal(4);
				sched.dispose();
			});

			it("can remove items during forEach iterations", function(){
				var sched = new IntervalTimeline();
				for (var i = 0; i < 1000; i++){
					sched.add({"time" : i, "duration" : 0.01});
				}
				sched.forEach(function(event){
					sched.cancel(event.time);
				});
				expect(sched.length).to.equal(0);
				sched.dispose();
			});

			it("can remove items during forEachAtTime iterations", function(){
				var sched = new IntervalTimeline();
				for (var i = 0; i < 1000; i++){
					sched.add({"time" : i, "duration" : Infinity});
				}
				sched.forEachAtTime(1000, function(event){
					sched.cancel(event.time);
				});
				expect(sched.length).to.equal(0);
				sched.dispose();
			});

			it("can remove items during forEachAfter iterations", function(){
				var sched = new IntervalTimeline();
				for (var i = 0; i < 1000; i++){
					sched.add({"time" : i, "duration" : Infinity});
				}
				sched.forEachAfter(0, function(event){
					sched.remove(event);
				});
				expect(sched.length).to.equal(0);
				sched.dispose();
			});
		});
	});
});<commit_msg>testing null sets<commit_after>define(["Test", "Tone/core/IntervalTimeline", "helper/Basic"], function (Test, IntervalTimeline, Basic) {

	describe("IntervalTimeline", function(){

		Basic(IntervalTimeline);

		context("inserting/deleting events", function(){

			it ("accepts events into the timeline", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"state" : "A",
					"duration" : 0.2,
					"time"  : 0
				});
				sched.add({
					"state" : "B",
					"duration" : 0.4,
					"time"  : 1
				});
				sched.add({
					"state" : "C",
					"duration" : 12,
					"time"  : 2
				});
				sched.dispose();
			});

			it ("computes the lenght of the timeline correctly after adding events", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"state" : "A",
					"duration" : 0.2,
					"time"  : 0
				});
				sched.add({
					"state" : "B",
					"duration" : 0.4,
					"time"  : 1
				});
				sched.add({
					"state" : "C",
					"duration" : 12,
					"time"  : 2
				});
				expect(sched.length).to.equal(3);
				sched.dispose();
			});

			it ("can remove events from the timeline", function(){
				var sched = new IntervalTimeline();

				var ev0 = {
					"duration" : 0.2,
					"time"  : 0
				};
				var ev1 = {
					"duration" : 0.2,
					"time"  : 0.2
				};
				var ev2 = {
					"duration" : 0.2,
					"time"  : 0.1
				};
				sched.add(ev0);
				sched.add(ev1);
				sched.add(ev2);
				expect(sched.length).to.equal(3);
				sched.remove(ev0);
				sched.remove(ev1);
				expect(sched.length).to.equal(1);
				sched.remove(ev2);
				expect(sched.length).to.equal(0);
				sched.dispose();
			});

			it ("removing on a null set does nothing", function(){
				var sched = new IntervalTimeline();
				expect(sched.length).to.equal(0);
				sched.remove({});
				expect(sched.length).to.equal(0);
				sched.dispose();
			});

			it ("can add and remove and add again events from the timeline", function(){
				var sched = new IntervalTimeline();

				var ev0 = {
					"duration" : 0.2,
					"time"  : 0
				};
				var ev1 = {
					"duration" : 0.2,
					"time"  : 0.2
				};
				var ev2 = {
					"duration" : 0.2,
					"time"  : 0.1
				};
				sched.add(ev0);
				sched.add(ev1);
				sched.add(ev2);
				expect(sched.length).to.equal(3);
				sched.remove(ev0);
				sched.remove(ev1);
				expect(sched.length).to.equal(1);
				sched.add(ev0);
				sched.add(ev1);
				expect(sched.length).to.equal(3);
				sched.dispose();
			});

			it ("throws an error if events do not have both time and duration attributes", function(){
				var sched = new IntervalTimeline();
				expect(function(){
					sched.add({
						"time" : 0
					});
				}).to.throw(Error);
				expect(function(){
					sched.add({
						"duration" : 0
					});
				}).to.throw(Error);
				sched.dispose();
			});

		});

		context("getting events", function(){

			it ("returns null when no events are in the timeline", function(){
				var sched = new IntervalTimeline();
				expect(sched.get(3)).to.equal(null);
				sched.dispose();
			});

			it ("returns the event which overlaps the given time", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"state" : "A",
					"duration" : Infinity,
					"time"  : 0
				});
				sched.add({
					"state" : "B",
					"duration" : 0.4,
					"time"  : 1
				});
				sched.add({
					"state" : "C",
					"duration" : 12,
					"time"  : 2
				});
				expect(sched.get(0.2).state).to.equal("A");
				sched.dispose();
			});

			it ("returns events exclusive of the end time", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"state" : "A",
					"duration" : 1,
					"time"  : 0
				});
				expect(sched.get(0.99).state).to.equal("A");
				expect(sched.get(1)).to.equal(null);
				sched.dispose();
			});

			it ("factors in start position and duration when checking for overlaps", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"duration" : 0.4,
					"time"  : 0
				});
				expect(sched.get(0.5)).to.be.null;
				expect(sched.get(-1)).to.be.null;
				expect(sched.get(0)).to.not.be.null;
				expect(sched.get(0.39)).to.not.be.null;
				sched.dispose();
			});

			it ("returns the event whose start is closest to the given time", function(){
				var sched = new IntervalTimeline();
				sched.add({
					"state" : "A",
					"duration" : Infinity,
					"time"  : 0
				});
				sched.add({
					"state" : "B",
					"duration" : 0.4,
					"time"  : 0.2
				});
				sched.add({
					"state" : "C",
					"duration" : 12,
					"time"  : 2
				});
				expect(sched.get(0.2).state).to.equal("B");
				sched.dispose();
			});

			it ("returns the events correctly after some events are removed", function(){
				var sched = new IntervalTimeline();
				var ev0 = {
					"state" : "A",
					"duration" : 0.2,
					"time"  : 0.1
				};
				var ev1 = {
					"state" : "B",
					"duration" : 0.3,
					"time"  : 0.2
				};
				var ev2 = {
					"state" : "C",
					"duration" : Infinity,
					"time"  : 0
				};
				sched.add(ev0);
				sched.add(ev1);
				sched.add(ev2);
				sched.remove(ev0);
				sched.remove(ev1);
				expect(sched.get(0.2)).to.not.be.null;
				expect(sched.get(0.2).state).to.equal("C");
				sched.dispose();
			});

			it ("can handle many items", function(){
				var sched = new IntervalTimeline();
				var len = 5000;
				var events = [];
				var duration = 1;
				var time = 0;
				for (var i = 0; i < len; i++){
					var event = {
						"time" : time,
						"duration" : duration
					};
					time = (time + 3.1) % 109;
					duration = (duration + 5.7) % 19;
					sched.add(event);
					events.push(event);
				}
				for (var j = 0; j < events.length; j++){
					var event = events[j];
					expect(sched.get(event.time).time).to.equal(event.time);
				}

				for (var k = 0; k < events.length; k++){
					sched.remove(events[k]);
					expect(sched.length).to.equal(events.length - k - 1);
				}
				sched.dispose();
			});

		});

		context("cancelling", function(){

			it ("can cancel items after the given time", function(){
				var sched = new IntervalTimeline();
				for (var i = 5; i < 100; i++){
					sched.add({
						"time" : i,
						"duration" : 10
					});
				}
				sched.cancel(10);
				expect(sched.length).to.equal(5);
				sched.cancel(0);
				expect(sched.length).to.equal(0);
				sched.dispose();
			});
		});

		context("Iterators", function(){

			it("iterates over all items and returns and item", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0, "duration" : 5});
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEach(function(event){
					expect(event).to.be.an.object;
					count++;
				});
				expect(count).to.equal(5);
				sched.dispose();
			});

			it("iterate over null set", function(){
				var sched = new IntervalTimeline();
				var count = 0;
				sched.forEach(function(){
					count++;
				});
				expect(count).to.equal(0);
				sched.dispose();
			});

			it("iterates over all items overlapping the given time", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0, "duration" : 5});
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEachAtTime(0.3, function(event){
					expect(event).to.be.an.object;
					expect(event.time).to.be.at.most(0.3);
					count++;
				});
				expect(count).to.equal(4);
				sched.dispose();
			});

			it("handles time ranges before the available objects", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEachAtTime(0, function(){
					count++;
				});
				expect(count).to.equal(0);
				sched.dispose();
			});

			it("handles time ranges after the available objects", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEachAtTime(5.5, function(){
					count++;
				});
				expect(count).to.equal(0);
				sched.dispose();
			});

			it("iterates over all items after the given time", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEachAfter(0.2, function(event){
					expect(event).to.be.an.object;
					expect(event.time).to.be.gte(0.2);
					count++;
				});
				expect(count).to.equal(3);
				count = 0;
				sched.forEachAfter(0.35, function(event){
					expect(event.time).to.be.gte(0.35);
					count++;
				});
				expect(count).to.equal(1);
				sched.dispose();
			});

			it("handles time ranges after the available objects", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEachAfter(0.5, function(){
					count++;
				});
				expect(count).to.equal(0);
				sched.dispose();
			});

			it("iterates over all items", function(){
				var sched = new IntervalTimeline();
				sched.add({"time" : 0.1, "duration" : 5});
				sched.add({"time" : 0.2, "duration" : 5});
				sched.add({"time" : 0.3, "duration" : 5});
				sched.add({"time" : 0.4, "duration" : 5});
				var count = 0;
				sched.forEach(function(){
					count++;
				});
				expect(count).to.equal(4);
				sched.dispose();
			});

			it("can remove items during forEach iterations", function(){
				var sched = new IntervalTimeline();
				for (var i = 0; i < 1000; i++){
					sched.add({"time" : i, "duration" : 0.01});
				}
				sched.forEach(function(event){
					sched.cancel(event.time);
				});
				expect(sched.length).to.equal(0);
				sched.dispose();
			});

			it("can remove items during forEachAtTime iterations", function(){
				var sched = new IntervalTimeline();
				for (var i = 0; i < 1000; i++){
					sched.add({"time" : i, "duration" : Infinity});
				}
				sched.forEachAtTime(1000, function(event){
					sched.cancel(event.time);
				});
				expect(sched.length).to.equal(0);
				sched.dispose();
			});

			it("can remove items during forEachAfter iterations", function(){
				var sched = new IntervalTimeline();
				for (var i = 0; i < 1000; i++){
					sched.add({"time" : i, "duration" : Infinity});
				}
				sched.forEachAfter(0, function(event){
					sched.remove(event);
				});
				expect(sched.length).to.equal(0);
				sched.dispose();
			});
		});
	});
});<|endoftext|>


<commit_before>var global = (typeof window !== 'undefined') ? window : {},
    Ember = global.Ember;

/**
  SimpleAuth's configuration object.

  @class Configuration
  @namespace SimpleAuth
  @module simple-auth/configuration
*/
export default {
  /**
    The route to transition to for authentication; should be set through
    [SimpleAuth.setup](#Ember-SimpleAuth-setup).

    @property authenticationRoute
    @readOnly
    @static
    @type String
    @default 'login'
  */
  authenticationRoute: 'login',

  /**
    The route to transition to after successful authentication; should be set
    through [SimpleAuth.setup](#Ember-SimpleAuth-setup).

    @property routeAfterAuthentication
    @readOnly
    @static
    @type String
    @default 'index'
  */
  routeAfterAuthentication: 'index',

  /**
    The name of the property that the session is injected with into routes and
    controllers; should be set through
    [SimpleAuth.setup](#Ember-SimpleAuth-setup).

    @property sessionPropertyName
    @readOnly
    @static
    @type String
    @default 'session'
  */
  sessionPropertyName: 'session',

  /**
    The authorizer factory to use as it is registered with Ember's container,
    see
    [Ember's API docs](http://emberjs.com/api/classes/Ember.Application.html#method_register);
    when the application does not interact with a server that requires
    authorized requests, no auzthorizer is needed.

    @property sessionPropertyName
    @readOnly
    @static
    @type String
    @default null
  */
  authorizerFactory: null,

  /**
    The store factory to use as it is registered with Ember's container, see
    [Ember's API docs](http://emberjs.com/api/classes/Ember.Application.html#method_register).

    @property storeFactory
    @readOnly
    @static
    @type String
    @default simple-auth-session-store:local-storage
  */
  storeFactory: 'simple-auth-session-store:local-storage',

  /**
    SimpleAuth will never authorize requests going to a different origin
    than the one the Ember.js application was loaded from; to explicitely
    enable authorization for additional origins, whitelist those origins with
    this setting. _Beware that origins consist of protocol, host and port (port
    can be left out when it is 80 for HTTP or 443 for HTTPS)_

    @property crossOriginWhitelist
    @readOnly
    @static
    @type Array
    @default []
  */
  crossOriginWhitelist: [],

  /**
    @property applicationRootUrl
    @private
  */
  applicationRootUrl: null,

  /**
    @method load
    @private
  */
  load: function(container) {
    var globalConfig = (global.ENV || {})['simple-auth'] || {};
    this.authenticationRoute      = globalConfig.authenticationRoute || this.authenticationRoute;
    this.routeAfterAuthentication = globalConfig.routeAfterAuthentication || this.routeAfterAuthentication;
    this.sessionPropertyName      = globalConfig.sessionPropertyName || this.sessionPropertyName;
    this.authorizerFactory        = globalConfig.authorizerFactory || this.authorizerFactory;
    this.storeFactory             = globalConfig.storeFactory || this.storeFactory;
    this.applicationRootUrl       = container.lookup('router:main').get('rootURL') || '/';
  }
};
<commit_msg>fixed docs for configuration class<commit_after>var global = (typeof window !== 'undefined') ? window : {},
    Ember = global.Ember;

/**
  Ember Simple Auth's configuration object.

  To change any of these values, define a global configuration object for Ember
  Simple Auth and define the values there:

  ```javascript
  window.ENV = window.ENV || {};
  window.ENV['simple-auth'] = {
    authenticationRoute: 'sign-in'
  };
  ```

  @class Configuration
  @namespace SimpleAuth
  @module simple-auth/configuration
*/
export default {
  /**
    The route to transition to for authentication.

    @property authenticationRoute
    @readOnly
    @static
    @type String
    @default 'login'
  */
  authenticationRoute: 'login',

  /**
    The route to transition to after successful authentication.

    @property routeAfterAuthentication
    @readOnly
    @static
    @type String
    @default 'index'
  */
  routeAfterAuthentication: 'index',

  /**
    The name of the property that the session is injected with into routes and
    controllers.

    @property sessionPropertyName
    @readOnly
    @static
    @type String
    @default 'session'
  */
  sessionPropertyName: 'session',

  /**
    The authorizer factory to use as it is registered with Ember's container,
    see
    [Ember's API docs](http://emberjs.com/api/classes/Ember.Application.html#method_register);
    when the application does not interact with a server that requires
    authorized requests, no auzthorizer is needed.

    @property sessionPropertyName
    @readOnly
    @static
    @type String
    @default null
  */
  authorizerFactory: null,

  /**
    The store factory to use as it is registered with Ember's container, see
    [Ember's API docs](http://emberjs.com/api/classes/Ember.Application.html#method_register).

    @property storeFactory
    @readOnly
    @static
    @type String
    @default simple-auth-session-store:local-storage
  */
  storeFactory: 'simple-auth-session-store:local-storage',

  /**
    Ember Simple Auth will never authorize requests going to a different origin
    than the one the Ember.js application was loaded from; to explicitely
    enable authorization for additional origins, whitelist those origins with
    this setting. _Beware that origins consist of protocol, host and port (port
    can be left out when it is 80 for HTTP or 443 for HTTPS)_

    @property crossOriginWhitelist
    @readOnly
    @static
    @type Array
    @default []
  */
  crossOriginWhitelist: [],

  /**
    @property applicationRootUrl
    @private
  */
  applicationRootUrl: null,

  /**
    @method load
    @private
  */
  load: function(container) {
    var globalConfig = (global.ENV || {})['simple-auth'] || {};
    this.authenticationRoute      = globalConfig.authenticationRoute || this.authenticationRoute;
    this.routeAfterAuthentication = globalConfig.routeAfterAuthentication || this.routeAfterAuthentication;
    this.sessionPropertyName      = globalConfig.sessionPropertyName || this.sessionPropertyName;
    this.authorizerFactory        = globalConfig.authorizerFactory || this.authorizerFactory;
    this.storeFactory             = globalConfig.storeFactory || this.storeFactory;
    this.applicationRootUrl       = container.lookup('router:main').get('rootURL') || '/';
  }
};
<|endoftext|>


<commit_before>var helpers = require('../helpers.js');
var Link = require('../../models/link.js');

// List links
exports.list = function (req, res) {
	var limit = Number(req.query.limit) || 10;
	var offset = Number(req.query.offset) || 0;
	var sortBy = req.query.sortBy || 'created';
	var sortOrder = Number(req.query.sortOrder) || -1;

	// Restrict limit range
	limit = Math.min(limit, 100);
	limit = Math.max(limit, 0);

    console.log(limit);

	// Format and validate sort
	var sort = {};
	sort[sortBy] = sortOrder;
	// Only accept -1, 1
	if (!(sort[sortBy] in [-1, 1])) {
		sort[sortBy] = -1;
	}

	query = Link.find().sort(sort).skip(offset).limit(limit);
	query.exec(function (err, docs) {
		if (err) { console.log(err); }
		res.send(docs);
	});
};

// Get link by id
exports.details = function (req, res) {
	var id = req.params.linkId;

	Link.findById(id, function (err, doc) {
		if (err) { console.log(err); }
		res.send(doc);
	});
};

exports.create = function (req, res) {

	var tag = helpers.generateBase62(5);
	var destination = req.body.destination;

    console.log(req.body);

    var link = new Link({
        destination: destination,
        domain: 'wrapulous.com', // Eventually we use cool mini domains
        tag: tag
    });

    link.save(function (err, link) {
        if (err) { console.log(err); }
        res.send(link);
    });
};

<commit_msg>forgot logger<commit_after>var helpers = require('../helpers.js');
var Link = require('../../models/link.js');

// List links
exports.list = function (req, res) {
	var limit = Number(req.query.limit) || 10;
	var offset = Number(req.query.offset) || 0;
	var sortBy = req.query.sortBy || 'created';
	var sortOrder = Number(req.query.sortOrder) || -1;

	// Restrict limit range
	limit = Math.min(limit, 100);
	limit = Math.max(limit, 0);

	// Format and validate sort
	var sort = {};
	sort[sortBy] = sortOrder;
	// Only accept -1, 1
	if (!(sort[sortBy] in [-1, 1])) {
		sort[sortBy] = -1;
	}

	query = Link.find().sort(sort).skip(offset).limit(limit);
	query.exec(function (err, docs) {
		if (err) { console.log(err); }
		res.send(docs);
	});
};

// Get link by id
exports.details = function (req, res) {
	var id = req.params.linkId;

	Link.findById(id, function (err, doc) {
		if (err) { console.log(err); }
		res.send(doc);
	});
};

exports.create = function (req, res) {

	var tag = helpers.generateBase62(5);
	var destination = req.body.destination;

    console.log(req.body);

    var link = new Link({
        destination: destination,
        domain: 'wrapulous.com', // Eventually we use cool mini domains
        tag: tag
    });

    link.save(function (err, link) {
        if (err) { console.log(err); }
        res.send(link);
    });
};

<|endoftext|>


<commit_before>//
// Copyright (C) 2013 - present Instructure, Inc.
//
// This file is part of Canvas.
//
// Canvas is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License as published by the Free
// Software Foundation, version 3 of the License.
//
// Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
// A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
// details.
//
// You should have received a copy of the GNU Affero General Public License along
// with this program. If not, see <http://www.gnu.org/licenses/>.

import {Model} from '@canvas/backbone'
import { useScope as useI18nScope } from '@canvas/i18n';

const I18n = useI18nScope('publishableModuleItem');

// A slightly terrible class that branches the urls and json data for the
// different module types
export default class PublishableModuleItem extends Model {
  static initClass() {
    this.prototype.defaults = {
      module_type: null,
      course_id: null,
      module_id: null,
      published: true,
      publishable: true,
      unpublishable: true,
      module_item_name: null
    }

    this.prototype.urls = {
      generic() {
        return `${this.baseUrl()}/modules/${this.get('module_id')}/items/${this.get(
          'module_item_id'
        )}`
      },
      module() {
        return `${this.baseUrl()}/modules/${this.get('id')}`
      }
    }

    this.prototype.toJSONs = {
      generic() {
        return {module_item: {published: this.get('published')}}
      },
      module() {
        return {module: {published: this.get('published')}}
      }
    }

    this.prototype.disabledMessages = {
      generic() {
        if (this.get('module_item_name')) {
          return I18n.t('Publishing %{item_name} is disabled', {
            item_name: this.get('module_item_name')
          })
        } else {
          return I18n.t('Publishing is disabled for this item')
        }
      },

      assignment() {
        if (this.get('module_item_name')) {
          return I18n.t("Can't unpublish %{item_name} if there are student submissions", {
            item_name: this.get('module_item_name')
          })
        } else {
          return I18n.t("Can't unpublish if there are student submissions")
        }
      },

      quiz() {
        if (this.get('module_item_name')) {
          return I18n.t("Can't unpublish %{item_name} if there are student submissions", {
            item_name: this.get('module_item_name')
          })
        } else {
          return I18n.t("Can't unpublish if there are student submissions")
        }
      },
      discussion_topic() {
        if (this.get('module_item_name')) {
          return I18n.t("Can't unpublish %{item_name} if there are student submissions", {
            item_name: this.get('module_item_name')
          })
        } else {
          return I18n.t("Can't unpublish if there are student submissions")
        }
      }
    }
  }

  branch(key) {
    return (this[key][this.get('module_type')] || this[key].generic).call(this)
  }

  url() {
    return this.branch('urls')
  }

  toJSON() {
    return this.branch('toJSONs')
  }

  disabledMessage() {
    return this.branch('disabledMessages')
  }

  baseUrl() {
    return `/api/v1/courses/${this.get('course_id')}`
  }

  publish() {
    return this.save('published', true)
  }

  unpublish() {
    return this.save('published', false)
  }
}

PublishableModuleItem.initClass()
<commit_msg>Fix messaging on nq module item publish button<commit_after>//
// Copyright (C) 2013 - present Instructure, Inc.
//
// This file is part of Canvas.
//
// Canvas is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License as published by the Free
// Software Foundation, version 3 of the License.
//
// Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
// A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
// details.
//
// You should have received a copy of the GNU Affero General Public License along
// with this program. If not, see <http://www.gnu.org/licenses/>.

import {Model} from '@canvas/backbone'
import { useScope as useI18nScope } from '@canvas/i18n';

const I18n = useI18nScope('publishableModuleItem');

// A slightly terrible class that branches the urls and json data for the
// different module types
export default class PublishableModuleItem extends Model {
  static initClass() {
    this.prototype.defaults = {
      module_type: null,
      course_id: null,
      module_id: null,
      published: true,
      publishable: true,
      unpublishable: true,
      module_item_name: null
    }

    this.prototype.urls = {
      generic() {
        return `${this.baseUrl()}/modules/${this.get('module_id')}/items/${this.get(
          'module_item_id'
        )}`
      },
      module() {
        return `${this.baseUrl()}/modules/${this.get('id')}`
      }
    }

    this.prototype.toJSONs = {
      generic() {
        return {module_item: {published: this.get('published')}}
      },
      module() {
        return {module: {published: this.get('published')}}
      }
    }

    this.prototype.disabledMessages = {
      generic() {
        if (this.get('module_item_name')) {
          return I18n.t('Publishing %{item_name} is disabled', {
            item_name: this.get('module_item_name')
          })
        } else {
          return I18n.t('Publishing is disabled for this item')
        }
      },

      assignment() {
        if (this.get('module_item_name')) {
          return I18n.t("Can't unpublish %{item_name} if there are student submissions", {
            item_name: this.get('module_item_name')
          })
        } else {
          return I18n.t("Can't unpublish if there are student submissions")
        }
      },

      quiz() {
        if (this.get('module_item_name')) {
          return I18n.t("Can't unpublish %{item_name} if there are student submissions", {
            item_name: this.get('module_item_name')
          })
        } else {
          return I18n.t("Can't unpublish if there are student submissions")
        }
      },
      discussion_topic() {
        if (this.get('module_item_name')) {
          return I18n.t("Can't unpublish %{item_name} if there are student submissions", {
            item_name: this.get('module_item_name')
          })
        } else {
          return I18n.t("Can't unpublish if there are student submissions")
        }
      }
    }
  }

  branch(key) {
    const moduleType = this.get('module_type') === 'lti-quiz' ? 'quiz' : this.get('module_type')
    return (this[key][moduleType] || this[key].generic).call(this)
  }

  url() {
    return this.branch('urls')
  }

  toJSON() {
    return this.branch('toJSONs')
  }

  disabledMessage() {
    return this.branch('disabledMessages')
  }

  baseUrl() {
    return `/api/v1/courses/${this.get('course_id')}`
  }

  publish() {
    return this.save('published', true)
  }

  unpublish() {
    return this.save('published', false)
  }
}

PublishableModuleItem.initClass()
<|endoftext|>