readingPosts.forEach(({ node }, index) => {
   const next = index === 0 ? null : readingPosts[index - 1].node
   const prev =
     index === readingPosts.length - 1
       ? null
       : readingPosts[index + 1].node
   createPage({
     path: node.fields.slug,
     component: path.resolve(`./src/templates/reading-post.js`),
     context: {
       slug: node.fields.slug,
       prev,
       next
     }
   })
 })
Example #2
0
 pluginOptions.plugins.map(plugin => {
   const requiredPlugin = require(plugin.resolve)
   if (_.isFunction(requiredPlugin.mutateSource)) {
     console.log(`running plugin to mutate markdown source`)
     return requiredPlugin.mutateSource(
       {
         markdownNode,
         files,
         getNode,
       },
       plugin.pluginOptions
     )
   } else {
     return Promise.resolve()
   }
 })
Example #3
0
exports.run = function(args) {
	var cmd = 'help';
	
	if(args.length > 0) {
		cmd = args[0];
	}
	
	process.stdin.resume();
	
	fs.readFile(path.resolve(__dirname, command.resolve(cmd).join('/') + '.txt'), function(er, helpTxt) {
		if(er) process.exit(1);
		
		console.log(helpTxt + '');
		process.exit(0);
	});
}
Example #4
0
function findPkgPath(pkgPath) {
  if (pkgPath.endsWith(`package.json`)) {
    return pkgPath;
  }

  try {
    const filePath = `${pkgPath}.json`;
    fs.statSync(filePath);
    return filePath;
  }
  catch (err) {
    const dirPath = path.resolve(pkgPath, `package.json`);
    fs.statSync(dirPath);
    return dirPath;
  }
}
Example #5
0
  return new Promise((resolve) => {
    const serverPath = path.resolve(process.cwd(), `packages/node_modules/@ciscospark/test-helper-server`);
    child = spawn(process.argv[0], [serverPath], {
      env: process.env,
      stdio: [`ignore`, `pipe`, process.stderr]
    });

    child.stdout.on(`data`, (data) => {
      const message = `${data}`;
      const pattern = /.+/gi;
      if (message.match(pattern)) {
        resolve();
      }
    });

    process.on(`exit`, stop);
  });
Example #6
0
 pluginOptions.plugins.map(plugin => {
   const requiredPlugin = require(plugin.resolve)
   if (_.isFunction(requiredPlugin)) {
     return requiredPlugin(
       {
         markdownAST,
         markdownNode,
         getNode,
         files,
         pathPrefix,
       },
       plugin.pluginOptions
     )
   } else {
     return Promise.resolve()
   }
 })
  QueryInterface.prototype.dropAllEnums = function(options) {
    if (this.sequelize.getDialect() !== 'postgres') {
      return Promise.resolve();
    }

    options = options || {};

    var self = this
      , sql = this.QueryGenerator.pgListEnums();

    return this.sequelize.query(sql, { plain: false, raw: true, type: QueryTypes.SELECT, logging: options.logging }).map(function(result) {
      return self.sequelize.query(
        self.QueryGenerator.pgEnumDrop(null, null, self.QueryGenerator.pgEscapeAndQuote(result.enum_name)),
        {logging: options.logging, raw: true}
      );
    });
  };
Example #8
0
 resolve: (image, fieldArgs, context) => {
   const file = getNodeAndSavePathDependency(image.parent, context.path)
   const args = { ...fieldArgs, pathPrefix }
   return Promise.resolve(
     fluid({
       file,
       args,
       reporter,
     })
   ).then(o =>
     Object.assign({}, o, {
       fieldArgs: args,
       image,
       file,
     })
   )
 },
Example #9
0
  QueryInterface.prototype.setIsolationLevel = function(transaction, value, options) {
    if (!transaction || !(transaction instanceof Transaction)) {
      throw new Error('Unable to set isolation level for a transaction without transaction object!');
    }

    options = Utils._.extend({
      parent: options.transaction
    }, options || {});

    var sql = this.QueryGenerator.setIsolationLevelQuery(value, options);

    if (sql) {
      return this.sequelize.query(sql, null, { transaction: transaction });
    } else {
      return Promise.resolve();
    }
  };
Example #10
0
  const nodesPromise = () => {
    const nodesCacheKey = JSON.stringify({
      // typeName + count being the same is a pretty good
      // indication that the nodes are the same.
      typeName,
      nodesLength: nodes.length,
      ...fieldsToSift,
    })
    if (
      process.env.NODE_ENV === `production` &&
      resolvedNodesCache.has(nodesCacheKey)
    ) {
      return Promise.resolve(resolvedNodesCache.get(nodesCacheKey))
    } else {
      return Promise.all(
        nodes.map(node => {
          const cacheKey = enhancedNodeCacheId({
            node,
            args: fieldsToSift,
          })
          if (cacheKey && enhancedNodeCache.has(cacheKey)) {
            return Promise.resolve(enhancedNodeCache.get(cacheKey))
          } else if (cacheKey && enhancedNodePromiseCache.has(cacheKey)) {
            return enhancedNodePromiseCache.get(cacheKey)
          }

          const enhancedNodeGenerationPromise = new Promise(resolve => {
            resolveRecursive(node, fieldsToSift, type.getFields()).then(
              resolvedNode => {
                trackInlineObjectsInRootNode(resolvedNode)
                if (cacheKey) {
                  enhancedNodeCache.set(cacheKey, resolvedNode)
                }
                resolve(resolvedNode)
              }
            )
          })
          enhancedNodePromiseCache.set(cacheKey, enhancedNodeGenerationPromise)
          return enhancedNodeGenerationPromise
        })
      ).then(resolvedNodes => {
        resolvedNodesCache.set(nodesCacheKey, resolvedNodes)
        return resolvedNodes
      })
    }
  }
).then(result => {
  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    switch(node.fields.type) {
      case 'talks': {
        createPage({
          path: node.fields.slug,
          component: path.resolve(`./src/templates/talk.js`),
          context: {
            slug: node.fields.slug,
          },
        })
        break
      }

      case 'posts': {
        createPage({
          path: node.fields.slug,
          component: path.resolve(`./src/templates/article.js`),
          context: {
            slug: node.fields.slug,
          },
        })
        break
      }

    }

    // Collect all tags into a set.
    if (node.frontmatter.tags) {
      node.frontmatter.tags.forEach(tag => topics.add(tag))
    }
  })

  // Create topic pages for each tag
  for (topic of topics) {
    createPage({
      path: `/topic/${topic}/`,
      component: path.resolve(`./src/templates/topic.js`),
      context: {
        topic: topic
      },
    })
  }

})
  await verificationReminders.keys.reduce(async (promise, key) => {
    await promise;

    const method = `verificationReminder${key[0].toUpperCase()}${key.substr(1)}Email`;
    const reminders = allReminders[key];

    console.log(`Processing ${reminders.length} ${key} reminders...`);

    const failedReminders = await reminders.reduce(async (promise, { timestamp, uid }) => {
      const failed = await promise;

      try {
        if (sent[uid]) {
          // Don't send e.g. first and second reminders to the same email from a single batch
          console.log(`  * skipping ${uid}`);
          failed.push({ timestamp, uid });
          return failed;
        }

        const account = await db.account(uid);
        await mailer[method]({
          acceptLanguage: account.locale,
          code: account.emailCode,
          email: account.email,
          uid,
        });
        sent[uid] = true;
      } catch (err) {
        if (err.errno === error.ERRNO.ACCOUNT_UNKNOWN) {
          console.log(`  * ignoring deleted account ${uid}`);
        } else {
          console.log(`  * failed ${uid}`);
          console.error(err.stack);
          failed.push({ timestamp, uid });
        }
      }

      return failed;
    }, Promise.resolve([]));

    if (failedReminders.length > 0) {
      console.log(`Reinstating ${reminders.length} failed or skipped ${key} reminders...`);
      return verificationReminders.reinstate(key, failedReminders);
    }
  }, Promise.resolve());
Example #13
0
  QueryInterface.prototype.commitTransaction = function(transaction, options) {
    if (!transaction || !(transaction instanceof Transaction)) {
      throw new Error('Unable to commit a transaction without transaction object!');
    }

    options = Utils._.extend({
      transaction: transaction,
      parent: options.transaction
    }, options || {});

    var sql = this.QueryGenerator.commitTransactionQuery(options);

    if (sql) {
      return this.sequelize.query(sql, null, options);
    } else {
      return Promise.resolve();
    }
  };
  it(`should create Error element`, (done) => {
    let response = {
      statusCode: 400,
      body: `body`,
    }
    spyOn(RequestAsync, `request`).and.returnValue(Promise.resolve(response))

    restClient.post(`/testUrl`, {data: '1'})
      .error((e) => {
        expect(e.isOperational).toEqual(true)
        expect(e.request.url).toEqual('URL/testUrl')
        expect(e.request.method).toEqual("post")
        expect(e.request.body).toEqual({data: '1'})
        expect(e.body).toEqual(response.body)
        expect(e).toEqual(jasmine.any(Error))
        done()
      })
  })
Example #15
0
    files.forEach(file => {
      if (extname(file) === `.js` || extname(file) === `.jsx`) {
        const slug = file
          .substring(0, file.length - extname(file).length)
          .replace(new RegExp(`^${directory}`), `redirect-to-codepen/`)
        const code = fs.readFileSync(file, `utf8`)

        let css
        if (includeMatchingCSS === true) {
          try {
            css = fs.readFileSync(file.replace(extname(file), `.css`), `utf8`)
          } catch (err) {
            // If the file doesn't exist, we gracefully ignore the error
            if (err.code !== `ENOENT`) {
              throw err
            }
          }
        }

        // Codepen configuration.
        // https://blog.codepen.io/documentation/api/prefill/
        const action = `https://codepen.io/pen/define`
        const payload = JSON.stringify({
          editors: `0010`,
          html,
          js: code,
          js_external: externals.join(`;`),
          js_pre_processor: `babel`,
          layout: `left`,
          css,
        })

        createPage({
          path: slug,
          // Normalize the path so tests pass on Linux + Windows
          component: normalizePath(resolve(redirectTemplate)),
          context: {
            action,
            payload,
          },
        })
      }
    })
Example #16
0
 await Promise.each(pluginOptions.plugins, plugin => {
   const requiredPlugin = require(plugin.resolve)
   if (_.isFunction(requiredPlugin.mutateSource)) {
     return requiredPlugin.mutateSource(
       {
         markdownNode,
         files: fileNodes,
         getNode,
         reporter,
         cache: getCache(plugin.name),
         getCache,
         ...rest,
       },
       plugin.pluginOptions
     )
   } else {
     return Promise.resolve()
   }
 })
Example #17
0
const server = http.createServer((request, response) =>
  handler(request, response, {
    public: path.resolve(`assets`),
    headers: [
      {
        source: `**/*`,
        headers: [
          {
            key: `Access-Control-Allow-Origin`,
            value: `http://localhost:9000`,
          },
          {
            key: `Access-Control-Allow-Credentials`,
            value: true,
          },
        ],
      },
    ],
  })
Example #18
0
  // check the cache, the user's project, and finally the theme files
  resolveComponentPath({ matchingTheme: theme, themes: ogThemes, component }) {
    // don't include matching theme in possible shadowing paths
    const themes = ogThemes.filter(({ themeName }) => themeName !== theme)
    if (!this.cache[`${theme}-${component}`]) {
      this.cache[`${theme}-${component}`] = [
        path.join(path.resolve(`.`), `src`, theme),
      ]
        .concat(
          Array.from(themes)
            .reverse()
            .map(({ themeDir }) => path.join(themeDir, `src`, theme))
        )
        .map(dir => path.join(dir, component))
        .find(possibleComponentPath => {
          debug(`possibleComponentPath`, possibleComponentPath)
          let dir
          try {
            // we use fs/path instead of require.resolve to work with
            // TypeScript and alternate syntaxes
            dir = fs.readdirSync(path.dirname(possibleComponentPath))
          } catch (e) {
            return false
          }
          const exists = dir
            .map(filepath => {
              const ext = path.extname(filepath)
              const filenameWithoutExtension = path.basename(filepath, ext)
              return filenameWithoutExtension
            })
            .includes(
              path.basename(
                possibleComponentPath,
                path.extname(possibleComponentPath)
              )
            )
          return exists
        })
    }

    return this.cache[`${theme}-${component}`]
  }
Example #19
0
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  // The “graphql” function allows us to run arbitrary
  // queries against the mongoDB graphql schema.

  // Mongodb{dbName}{collection} is a data node type created from mongoDB is a
  // "connection" (a GraphQL convention for accessing a list of nodes) gives
  // us an easy way to query all documents in the mongoDB collection.

  const { data } = await graphql(`
    {
      allMongodbCloudDocuments(limit: 1000) {
        edges {
          node {
            id
          }
        }
      }
    }
  `)
  // Create pages.
  const pageTemplate = path.resolve(`./src/templates/item.js`)
  // We want to create a detailed page for each
  // document in our mongoDB collection
  for (const { node } of data.allMongodbCloudDocuments.edges) {
    // Gatsby uses Redux to manage its internal state.
    // Plugins and sites can use functions like "createPage"
    // to interact with Gatsby.
    createPage({
      // Each page is required to have a `path` as well
      // as a template component. The `context` is
      // optional but is often necessary so the template
      // can query data specific to each page.
      path: `/item/${node.id}/`,
      component: pageTemplate,
      context: {
        id: node.id,
      },
    })
  }
}
Example #20
0
exports.listVersions = async function listVersions(packageName, options) {
  const deps = await exports.list(packageName, options);
  // eslint-disable-next-line global-require
  const pkg = require(path.resolve(process.cwd(), `package.json`));

  return deps.reduce((acc, dep) => {
    acc[dep] = pkg.dependencies[dep] || pkg.devDependencies[dep] || pkg.optionalDependencies[dep];
    if (!acc[dep]) {
      try {
        // eslint-disable-next-line global-require
        acc[dep] = require(path.resolve(process.cwd(), `./packages/node_modules/${dep}/package.json`)).version;
      }
      catch (err) {
        // eslint-disable-next-line no-console
        debug(err);
        throw new Error(`Failed to determine version for ${dep}, Is it missing from package.json?`);
      }
    }
    return acc;
  }, {});
};
 result.data.allMarkdownRemark.edges.map(({ node }) => {
   console.log('Node.field.type', JSON.stringify(node));
   let templatePath = './src/templates/page.js';
   switch (node.fields.slug) {
     case '/':
       templatePath = './src/templates/home-page.js';
       break;
     case '/zoeken/':
       templatePath = './src/templates/search-page.js';
       break;
   }
   console.log('#DH# Pages', node.fields.slug, templatePath);
   createPage({
     path: node.fields.slug,
     component: path.resolve(templatePath),
     context: {
       // Data passed to context is available in page queries as GraphQL variables.
       slug: node.fields.slug,
     },
   });
 });
Example #22
0
      const findLinkedFileNode = relativePath => {
        // Use the parent File node to create the absolute path to
        // the linked file.
        const fileLinkPath = normalize(
          systemPath.resolve(parentFileNode.dir, relativePath)
        )

        // Use that path to find the linked File node.
        const linkedFileNode = _.find(
          getNodes(),
          n => n.internal.type === `File` && n.absolutePath === fileLinkPath
        )
        if (linkedFileNode) {
          createPageDependency({
            path,
            nodeId: linkedFileNode.id,
          })
          return linkedFileNode
        } else {
          return null
        }
      }
Example #23
0
 _.keys(siftFieldsObj).map(k =>
   Promise.resolve(awaitSiftField(gqFields, node, k))
     .then(v => {
       const innerSift = siftFieldsObj[k]
       const innerGqConfig = gqFields[k]
       if (
         _.isObject(innerSift) &&
         v != null &&
         innerGqConfig &&
         innerGqConfig.type &&
         _.isFunction(innerGqConfig.type.getFields)
       ) {
         return resolveRecursive(
           v,
           innerSift,
           innerGqConfig.type.getFields()
         )
       } else {
         return v
       }
     })
     .then(v => [k, v])
Example #24
0
exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  const blogPostTemplate = path.resolve(`src/templates/template-blog-post.js`)
  return graphql(
    `
      {
        allMarkdownRemark(
          limit: 1000
          filter: { frontmatter: { draft: { ne: true } } }
        ) {
          edges {
            node {
              fields {
                slug
              }
            }
          }
        }
      }
    `
  ).then(result => {
    if (result.errors) {
      throw result.errors
    }

    // Create blog posts pages.
    result.data.allMarkdownRemark.edges.forEach(edge => {
      createPage({
        path: edge.node.fields.slug, // required
        component: slash(blogPostTemplate),
        context: {
          slug: edge.node.fields.slug,
        },
      })
    })
  })
}
Example #25
0
exports.loadNodeContent = node => {
  if (node.internal.content) {
    return Promise.resolve(node.internal.content)
  } else {
    return new Promise(resolve => {
      // Load plugin's loader function
      const plugin = store
        .getState()
        .flattenedPlugins.find(plug => plug.name === node.internal.owner)
      const { loadNodeContent } = require(plugin.resolve)
      if (!loadNodeContent) {
        throw new Error(
          `Could not find function loadNodeContent for plugin ${plugin.name}`
        )
      }

      return loadNodeContent(node).then(content => {
        // TODO update node's content field here.
        resolve(content)
      })
    })
  }
}
Example #26
0
module.exports = relativePath => {
  debugTheme(`resolving`, relativePath)
  let pathResolvedPath = path.resolve(relativePath)
  let finalPath = pathResolvedPath

  try {
    debugTheme(`checking`, pathResolvedPath)
    // check if the user's site has the file
    require.resolve(pathResolvedPath)
    finalPath = pathResolvedPath
  } catch (e) {
    try {
      // if the user hasn't implemented the file,
      finalPath = require.resolve(relativePath)
    } catch (e) {
      console.log(e)
      return relativePath
    }
  }

  debugTheme(`using`, finalPath)
  return finalPath
}
Example #27
0
exports.createPages = ({ actions, graphql }) => {
  const { createPage } = actions

  const recipeTemplate = path.resolve(`src/templates/recipe.js`)
  // Query for recipe nodes to use in creating pages.
  return graphql(
    `
      {
        allRecipes {
          edges {
            node {
              internalId
              fields {
                slug
              }
            }
          }
        }
      }
    `
  ).then(result => {
    if (result.errors) {
      throw result.errors
    }

    // Create pages for each recipe.
    result.data.allRecipes.edges.forEach(({ node }) => {
      createPage({
        path: node.fields.slug,
        component: recipeTemplate,
        context: {
          slug: node.fields.slug,
        },
      })
    })
  })
}
Example #28
0
    Module.prototype.require = function (moduleName) {

        let contextPath = path.resolve(webpackBaseConfiguration.context);
        let resolvedPath = Module._resolveFilename(moduleName, this, false);

        if (Module._cache[resolvedPath])
            return Module._cache[resolvedPath].exports;

        if (!resolvedPath.startsWith(`${contextPath}${path.sep}`))
            return originalRequire.call(this, moduleName);

        let ext = path.extname(resolvedPath);

        if (ignoreExtensions && !ext || ignoreExtensions.includes(ext))
            return originalRequire.call(this, moduleName);

        let newModule = Module._cache[resolvedPath] = new Module(resolvedPath, this);

        newModule.exports = loadModuleFromWebpack(moduleName);
        newModule.loaded = true;

        return newModule.exports;

    };
Example #29
0
    it(`Links to file node`, async () => {
      const nodes = [
        {
          id: `1`,
          file: `./file_1.jpg`,
          parent: `parent`,
          internal: { type: `Test` },
        },
      ].concat(getFileNodes())

      let result = await getQueryResult(
        nodes,
        `
          file {
            absolutePath
          }
        `
      )

      expect(result.errors).not.toBeDefined()
      expect(result.data.allTest.edges[0].node.file.absolutePath).toEqual(
        slash(path.resolve(dir, `file_1.jpg`))
      )
    })
Example #30
0
module.exports.modifyWebpackConfig = ({ config }, { compilerOptions }) => {
  // CommonJS to keep Webpack happy.
  const copts = Object.assign({}, compilerDefaults, compilerOptions, {
    module: `commonjs`,
  })

  // React-land is rather undertyped; nontrivial TS projects will most likely
  // error (i.e., not build) at something or other.
  const opts = { compilerOptions: copts, transpileOnly: true }

  // Load gatsby babel plugin to extract graphql query
  const extractQueryPlugin = path.resolve(
    __dirname,
    `../gatsby/dist/utils/babel-plugin-extract-graphql.js`
  )

  config.loader(`typescript`, {
    test,
    loaders: [
      `babel?${JSON.stringify({ plugins: [extractQueryPlugin] })}`,
      `ts-loader?${JSON.stringify(opts)}`,
    ],
  })
}