How to use ky-universal - 10 common examples

To help you get started, we’ve selected a few ky-universal examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ipfs / js-ipfs / src / core / ipns / routing / dns-datastore.js View on Github external
function dohBinary (key, callback) {
  const cid = new Cid(key.slice(ipns.namespaceLength))
  const buf = dnsPacket.encode({
    type: 'query',
    id: getRandomInt(1, 65534),
    flags: dnsPacket.RECURSION_DESIRED,
    questions: [{
      type: 'TXT',
      name: `${cid.toV1().toString()}.dns.ipns.dev`
    }]
  })
  // https://dns.google.com/experimental
  // https://cloudflare-dns.com/dns-query
  // https://mozilla.cloudflare-dns.com/dns-query
  ky
    .get('https://cloudflare-dns.com/dns-query', {
      searchParams: {
        dns: buf.toString('base64')
      },
      headers: {
        accept: 'application/dns-message'
      }
    })
    .arrayBuffer()
    .then(data => {
      data = dnsPacket.decode(Buffer.from(data))
      console.log('TCL: dohBinary -> data', data)

      if (!data && data.answers.length < 1) {
        throw errcode(new Error('Record not found'), 'ERR_NOT_FOUND')
      }
github tunnckoCore / opensource / web / pkg.tunnckocore.com / api / index.js View on Github external
);

  const rawName = isScoped ? pkgName.replace(/^tunnckocore\//, '') : pkgName;
  let pkgLoc = isScoped ? `@${pkgName}` : `packages/${pkgName}`;

  const loc = /preset|config/.test(pkgName) ? `configs/${rawName}` : pkgLoc;

  pkgLoc = `${loc}${restPath.length > 0 ? `/${restPath.join('/')}` : ''}`;

  const pathname =
    version === 'master' ? `@master/${pkgLoc}` : `@${encodedName}/${pkgLoc}`;

  // try request `src/index.ts`, `src/index.js`, `index.ts`, `index.js`
  if (!/\.(jsx?|tsx?)$/.test(pathname)) {
    if (field) {
      const resp = await ky
        .get(`${JSDELIVR}${pathname}/package.json`)
        .then((x) => x.text())
        .catch(() => {});

      // if `package.json` is found, try getting the source of file given `field`
      // which field by default is the "module" one.
      // Pass `field=main` query param to get the main field.
      if (resp) {
        let srcPath = null;
        try {
          srcPath = JSON.parse(resp)[field];
        } catch (err) {
          res.send('Found `package.json` but failed to parse.', 500);
          return;
        }
github ipfs / js-ipfs / src / core / runtime / preload-browser.js View on Github external
return httpQueue.add(async () => {
    const res = await ky.get(url, { signal: options.signal })
    const reader = res.body.getReader()

    try {
      while (true) {
        const { done } = await reader.read()
        if (done) return
        // Read to completion but do not cache
      }
    } finally {
      reader.releaseLock()
    }
  })
}
github ipfs / js-ipfs / src / core / runtime / preload-nodejs.js View on Github external
module.exports = async function preload (url, options) {
  log(url)
  options = options || {}

  const res = await ky.get(url, { signal: options.signal })

  for await (const _ of res.body) { // eslint-disable-line no-unused-vars
    // Read to completion but do not cache
  }
}
github ipfs / js-ipfs / src / core / ipns / routing / dns-datastore.js View on Github external
function dohJson (key, callback) {
  const cid = new Cid(key.slice(ipns.namespaceLength))

  // https://dns.google.com/resolve
  // https://cloudflare-dns.com/dns-query
  // https://mozilla.cloudflare-dns.com/dns-query
  ky
    .get('https://cloudflare-dns.com/dns-query', {
      searchParams: {
        name: `${cid.toV1().toString()}.dns.ipns.dev`,
        type: 'TXT',
        cd: 1,
        ad: 0,
        ct: 'application/dns-json'
      }
    })
    .json()
    .then(data => {
      if (!data && !data.Answer && data.Answer.length < 1) {
        throw errcode(new Error('Record not found'), 'ERR_NOT_FOUND')
      }
      const record = new Record(key, Buffer.from(data.Answer[0].data, 'base64'))
      setImmediate(() => callback(null, record.value))
github tunnckoCore / opensource / web / ghub.now.sh / api / _utils.js View on Github external
export async function packageJson(packageName, endpoint) {
  const { name, version } = parsePkgName(packageName);
  const tag = version === '' ? 'latest' : version;
  const uri =
    typeof endpoint === 'function'
      ? endpoint(name, tag)
      : `https://cdn.jsdelivr.net/npm/${name}@${tag}/package.json`;

  let pkg = null;
  try {
    pkg = await ky
      .get(uri)
      .then((resp) => resp.text())
      .then(JSON.parse);
  } catch (err) {
    // ! jsDelivr can response with 403 Forbidden, if over 50MB
    if (err.response && err.response.status === 403) {
      try {
        // ! so, try through UNPKG.com
        pkg = await packageJson(
          packageName,
          (x, t) => `https://unpkg.com/${x}@${t}/package.json`,
        );
      } catch (error) {
        throw new ky.HTTPError(
          `Package "${name}" not found, even through UNPKG.com!`,
        );
github tunnckoCore / opensource / web / pkg.tunnckocore.com / api / _utils.js View on Github external
async function packageJson(packageName, endpoint) {
  const { name, version } = parsePkgName(packageName);
  const tag = version === '' ? 'latest' : version;
  const uri =
    typeof endpoint === 'function'
      ? endpoint(name, tag)
      : `https://cdn.jsdelivr.net/npm/${name}@${tag}/package.json`;

  let pkg = null;
  try {
    pkg = await ky
      .get(uri)
      .then((resp) => resp.text())
      .then(JSON.parse);
  } catch (err) {
    // ! jsDelivr can response with 403 Forbidden, if over 50MB
    if (err.response && err.response.status === 403) {
      try {
        // ! so, try through UNPKG.com
        pkg = await packageJson(
          packageName,
          (x, t) => `https://unpkg.com/${x}@${t}/package.json`,
        );
      } catch (error) {
        throw new ky.HTTPError(
          `Package "${name}" not found, even through UNPKG.com!`,
        );
github tunnckoCore / opensource / web / pkg.tunnckocore.com / api / index.js View on Github external
.then((x) => x.text())
        .catch(() => {});

      // if `package.json` is found, try getting the source of file given `field`
      // which field by default is the "module" one.
      // Pass `field=main` query param to get the main field.
      if (resp) {
        let srcPath = null;
        try {
          srcPath = JSON.parse(resp)[field];
        } catch (err) {
          res.send('Found `package.json` but failed to parse.', 500);
          return;
        }

        await ky
          .get(`${JSDELIVR}${pathname}/${srcPath}`)
          .then(() => {
            res.send(`${JSDELIVR}${pathname}/${srcPath}`, 301);
          })
          .catch(() => {
            res.send(
              `Not found source path given in the "${field}" of package.json`,
              404,
            );
          });
        return;
      }
    }

    const result = await pLocate(
      ['src/index.ts', 'src/index.js', 'index.ts', 'index.js'].map((fp) =>
github ipfs / js-ipfs / src / core / ipns / routing / experimental / workers-datastore.js View on Github external
/* eslint-disable no-console */
'use strict'

const ky = require('ky-universal').default
const errcode = require('err-code')
const debug = require('debug')
const { Record } = require('libp2p-record')
const { keyToBase32 } = require('./utils')

const log = debug('ipfs:ipns:workers-datastore')
log.error = debug('ipfs:ipns:workers-datastore:error')

// Workers datastore aims to mimic the same encoding as routing when storing records
// to the local datastore
class WorkersDataStore {
  /**
   * Put a key value pair into the datastore
   * @param {Buffer} key identifier of the value.
   * @param {Buffer} value value to be stored.
   * @returns {Promise}
github ipfs / js-ipfs / src / core / ipns / routing / dns-datastore.js View on Github external
'use strict'

const ipns = require('ipns')
const ky = require('ky-universal').default
const { Record } = require('libp2p-record')
const dnsSocket = require('dns-socket')
const dnsPacket = require('dns-packet')
const Cid = require('cids')

const errcode = require('err-code')
const debug = require('debug')
const log = debug('ipfs:ipns:workers-api-datastore')
log.error = debug('ipfs:ipns:workers-api:error')

// DNS datastore aims to mimic the same encoding as routing when storing records
// to the local datastore
class DNSDataStore {
  constructor (repo) {
    this._repo = repo
  }