text: "use strict";
  
  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  exports.createResolvers = exports.createSchemaCustomization = exports.createPages = void 0;
  
  var _lunr = _interopRequireDefault(require("lunr"));
  
  var _flexsearch = _interopRequireDefault(require("flexsearch"));
  
  var _lodash = _interopRequireDefault(require("lodash.lowerfirst"));
  
  var _lodash2 = _interopRequireDefault(require("lodash.pick"));
  
  var _pascalcase = _interopRequireDefault(require("pascalcase"));
  
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  
  function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
  
  function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
  
  const TYPE_PREFIX = 'LocalSearch';
  const TYPE_INDEX = 'Index';
  const TYPE_STORE = 'Store'; // Returns an exported FlexSearch index using the provided documents, fields,
  // and ref.
  
  const createFlexSearchIndexExport = ({
    documents,
    fields,
    ref,
    engineOptions
  }) => {
    const index = _flexsearch.default.create.apply(null, Array.isArray(engineOptions) ? engineOptions : [engineOptions]);
  
    documents.forEach(doc => index.add(doc[ref], JSON.stringify((0, _lodash2.default)(doc, fields))));
    return index.export();
  }; // Returns an exported Lunr index using the provided documents, fields, and
  // ref.
  
  
  const createLunrIndexExport = ({
    documents,
    fields,
    ref
  }) => {
    const index = (0, _lunr.default)(function () {
      this.ref(ref);
      fields.forEach(field => this.field(field));
      documents.forEach(doc => this.add(doc));
    });
    return JSON.stringify(index);
  }; // Returns an exported index using the provided engine, documents, fields, and
  // ref. Throws if the provided engine is invalid.
  
  
  const createIndexExport = (_ref) => {
    let reporter = _ref.reporter,
        name = _ref.name,
        engine = _ref.engine,
        args = _objectWithoutProperties(_ref, ["reporter", "name", "engine"]);
  
    switch (engine) {
      case 'flexsearch':
        return createFlexSearchIndexExport(args);
  
      case 'lunr':
        return createLunrIndexExport(args);
  
      default:
        reporter.error(`The gatsby-plugin-local-search engine option for index "${name}" is invalid. Must be one of: flexsearch, lunr. The index will be null.`);
        return null;
    }
  }; // Create index and store during createPages and save to cache. The cached
  // values will be used in createResolvers.
  
  
  const createPages =
  /*#__PURE__*/
  function () {
    var _ref2 = _asyncToGenerator(function* (gatsbyContext, pluginOptions) {
      const graphql = gatsbyContext.graphql,
            cache = gatsbyContext.cache,
            reporter = gatsbyContext.reporter,
            createNodeId = gatsbyContext.createNodeId;
      const name = pluginOptions.name,
            _pluginOptions$ref = pluginOptions.ref,
            ref = _pluginOptions$ref === void 0 ? 'id' : _pluginOptions$ref,
            indexFields = pluginOptions.index,
            storeFields = pluginOptions.store,
            query = pluginOptions.query,
            normalizer = pluginOptions.normalizer,
            engine = pluginOptions.engine,
            engineOptions = pluginOptions.engineOptions;
      const result = yield graphql(query);
      if (result.errors) throw result.errors[0];
      const documents = yield Promise.resolve(normalizer(result));
      if (documents.length < 1) reporter.warn(`The gatsby-plugin-local-search query for index "${name}" returned no nodes. The index and store will be empty.`); // Default set of fields to index.
  
      const normalizerFields = documents.length > 0 ? Object.keys(documents[0]) : [];
      const index = createIndexExport({
        reporter,
        name,
        engine,
        engineOptions,
        documents,
        fields: indexFields !== null && indexFields !== void 0 ? indexFields : normalizerFields,
        ref
      });
      const store = documents.reduce((acc, doc) => {
        acc[doc[ref]] = storeFields ? (0, _lodash2.default)(doc, storeFields) : doc;
        return acc;
      }, {}); // Save to cache to use later in GraphQL resolver.
  
      yield cache.set(createNodeId(`${TYPE_INDEX} ${name}`), index);
      yield cache.set(createNodeId(`${TYPE_STORE} ${name}`), store);
      return;
    });
  
    return function createPages(_x, _x2) {
      return _ref2.apply(this, arguments);
    };
  }(); // Set the GraphQL type for LocalSearchIndex.
  
  
  exports.createPages = createPages;
  
  const createSchemaCustomization = (gatsbyContext, pluginOptions) => {
    const actions = gatsbyContext.actions,
          schema = gatsbyContext.schema;
    const createTypes = actions.createTypes;
    const name = pluginOptions.name;
    createTypes([schema.buildObjectType({
      name: (0, _pascalcase.default)(`${TYPE_PREFIX} ${TYPE_INDEX} ${name}`),
      fields: {
        id: 'ID',
        engine: 'String',
        index: 'String',
        store: 'String'
      }
    })]);
  };
  
  exports.createSchemaCustomization = createSchemaCustomization;
  
  const createResolvers =
  /*#__PURE__*/
  function () {
    var _ref3 = _asyncToGenerator(function* (gatsbyContext, pluginOptions) {
      const createResolvers = gatsbyContext.createResolvers,
            cache = gatsbyContext.cache,
            createNodeId = gatsbyContext.createNodeId;
      const name = pluginOptions.name,
            engine = pluginOptions.engine;
      createResolvers({
        Query: {
          [(0, _lodash.default)((0, _pascalcase.default)(`${TYPE_PREFIX} ${name}`))]: {
            type: (0, _pascalcase.default)(`${TYPE_PREFIX} ${TYPE_INDEX} ${name}`),
            resolve: function () {
              var _resolve = _asyncToGenerator(function* () {
                const index = yield cache.get(createNodeId(`${TYPE_INDEX} ${name}`));
                const store = yield cache.get(createNodeId(`${TYPE_STORE} ${name}`));
                return {
                  id: name,
                  engine,
                  index,
                  store: JSON.stringify(store)
                };
              });
  
              function resolve() {
                return _resolve.apply(this, arguments);
              }
  
              return resolve;
            }()
          }
        }
      });
      return;
    });
  
    return function createResolvers(_x3, _x4) {
      return _ref3.apply(this, arguments);
    };
  }();
  
  exports.createResolvers = createResolvers;