fs#writeFileSync JavaScript Examples

The following examples show how to use fs#writeFileSync. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: docs.js    From bitECS with Mozilla Public License 2.0 6 votes vote down vote up
async function render (pattern, output) {
  const files = await globby([
    pattern,
    '!**/**/node_modules',
    '!**/**/test',
    '!**/**/examples',
  ])
  const md = await jsdoc2md.render({
    files,
    plugin: 'dmd-readable'
  })
  writeFileSync(output, md)
}
Example #2
Source File: data_manager.js    From cortex-bot with MIT License 6 votes vote down vote up
/**
   * Получает чат из БД
   * @param {number} chat_id ID чата
   */
   static getChat(chat_id) {

    // Поиск чата в БД
    let chat = db.chats.find(chat => chat.id == chat_id)

    // Добавление чата в БД при его отсутствии
    if (!chat) {

      // Добавление
      db.chats.push({id: chat_id, data: []})

      // Запись
      writeFileSync('data.json', JSON.stringify(db, null, '\t'))

      // Обновление значения переменной
      chat = db.chats.find(chat => chat.id == chat_id)
    }

    // Возвращение объекта чата
    return chat
  }
Example #3
Source File: data_manager.js    From cortex-bot with MIT License 6 votes vote down vote up
/**
   * Записывает новые данные для чата
   * @param {number} chat_id ID чата
   * @param {string} data Данные
   */
  static writeChatData(chat_id, data) {

    // Добавление данных в БД
    DataManager.getChat(chat_id).data.push(data)
  
    // Запись БД
    writeFileSync('data.json', JSON.stringify(db, null, '\t'))
  }
Example #4
Source File: post-install.js    From ip-index with GNU General Public License v3.0 5 votes vote down vote up
promises = [
  axios.get('https://github.com/Umkus/asn-ip/releases/download/latest/as.csv', opts).then((res) => writeFileSync(fileAsns, res.data)),
  axios.get('https://github.com/Umkus/asn-ip/releases/download/latest/ranges_ipv4.csv', opts).then((res) => writeFileSync(fileCidrs, res.data)),
  axios.get('https://github.com/Umkus/nordvpn-ips/releases/download/ips/ips.csv', opts).then((res) => writeFileSync(fileNord, res.data)),
]
Example #5
Source File: post-install.js    From ip-index with GNU General Public License v3.0 5 votes vote down vote up
Promise.all(promises)
  .then(() => {
    readFileSync(`${__dirname}/../data/asns_cidrs.csv`).toString().split('\n').slice(0)
      .forEach((row) => {
        const items = row.split(',');
        const asn = +items[0];

        if (asnToCountry[asn] !== undefined || isNaN(asn)) {
          return false;
        }

        const start = +items[2];
        const end = +items[3];
        let country = '';

        const foundCountry = countries.find((country) => start >= country[0] && end <= country[1]);

        if (foundCountry) {
          country = foundCountry[2];
        }

        asnToCountry[asn] = country;
      });

    const asnsWithCountries = readFileSync(`${__dirname}/../data/asns.csv`).toString().split('\n').slice(1)
      .map((row) => {
        if (row.length <= 2) {
          return row;
        }

        const item = row.split(',');
        const country = asnToCountry[+item[0]] || '-';

        row = `${item[0]},${item[1]},${country},${item[2]}`;

        return row;
      })
      .join('\n');

    writeFileSync(`${__dirname}/../data/asns.csv`, asnsWithCountries);
  });
Example #6
Source File: update.js    From ip-index with GNU General Public License v3.0 5 votes vote down vote up
writeFileSync(`${__dirname}/../data/asns_dcs.csv`, [...oldBad].sort().join('\n') + '\n');
Example #7
Source File: store.js    From HinataMd with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param {String} filename 
 * @param {import('pino').Logger} logger
 * @returns 
 */
function useSingleFileAuthState(filename, logger) {
    let creds, keys = {}, saveCount = 0
    // save the authentication state to a file
    const saveState = (forceSave) => {
        logger?.trace('saving auth state')
        saveCount++
        if (forceSave || saveCount > 5) {
            writeFileSync(
                filename,
                // BufferJSON replacer utility saves buffers nicely
                JSON.stringify({ creds, keys }, BufferJSON.replacer, 2)
            )
            saveCount = 0
        }
    }

    if (existsSync(filename)) {
        const result = JSON.parse(
            readFileSync(filename, { encoding: 'utf-8' }),
            BufferJSON.reviver
        )
        creds = result.creds
        keys = result.keys
    } else {
        creds = initAuthCreds()
        keys = {}
    }

    return {
        state: {
            creds,
            keys: {
                get: (type, ids) => {
                    const key = KEY_MAP[type]
                    return ids.reduce(
                        (dict, id) => {
                            let value = keys[key]?.[id]
                            if (value) {
                                if (type === 'app-state-sync-key') {
                                    value = proto.AppStateSyncKeyData.fromObject(value)
                                }

                                dict[id] = value
                            }

                            return dict
                        }, {}
                    )
                },
                set: (data) => {
                    for (const _key in data) {
                        const key = KEY_MAP[_key]
                        keys[key] = keys[key] || {}
                        Object.assign(keys[key], data[_key])
                    }

                    saveState()
                }
            }
        },
        saveState
    }
}
Example #8
Source File: Generator.js    From fes.js with MIT License 5 votes vote down vote up
copyTpl(opts) {
      const tpl = readFileSync(opts.templatePath, 'utf-8');
      const content = Mustache.render(tpl, opts.context);
      mkdirp.sync(dirname(opts.target));
      console.log(`${chalk.green('Write:')} ${relative(this.cwd, opts.target)}`);
      writeFileSync(opts.target, content, 'utf-8');
  }
Example #9
Source File: filesystem.spec.js    From kit with MIT License 5 votes vote down vote up
write = (file, contents) => {
	const filepath = join(source_dir, file);
	mkdirp(dirname(filepath));
	writeFileSync(filepath, contents);
}
Example #10
Source File: genAliases.js    From atomize with MIT License 5 votes vote down vote up
b = () => {
  const result = Object.entries(dict).reduce((acc, [name, { alias = 'none' }]) => {
    acc += genRule(name, alias);
    return acc;
  }, TPL);

  writeFileSync(ALIASES_PATH, result);
}
Example #11
Source File: index.js    From kit with MIT License 5 votes vote down vote up
/** @type {import('.').default} */
export default function (options = {}) {
	return {
		name: '@sveltejs/adapter-cloudflare',
		async adapt(builder) {
			const files = fileURLToPath(new URL('./files', import.meta.url).href);
			const dest = builder.getBuildDirectory('cloudflare');
			const tmp = builder.getBuildDirectory('cloudflare-tmp');

			builder.rimraf(dest);
			builder.rimraf(tmp);
			builder.mkdirp(tmp);

			builder.writeStatic(dest);
			builder.writeClient(dest);
			builder.writePrerendered(dest);

			const relativePath = posix.relative(tmp, builder.getServerDirectory());

			writeFileSync(
				`${tmp}/manifest.js`,
				`export const manifest = ${builder.generateManifest({
					relativePath
				})};\n\nexport const prerendered = new Set(${JSON.stringify(builder.prerendered.paths)});\n`
			);

			builder.copy(`${files}/worker.js`, `${tmp}/_worker.js`, {
				replace: {
					SERVER: `${relativePath}/index.js`,
					MANIFEST: './manifest.js'
				}
			});

			await esbuild.build({
				platform: 'browser',
				sourcemap: 'linked',
				target: 'es2020',
				...options,
				entryPoints: [`${tmp}/_worker.js`],
				outfile: `${dest}/_worker.js`,
				allowOverwrite: true,
				format: 'esm',
				bundle: true
			});
		}
	};
}
Example #12
Source File: index.js    From kit with MIT License 5 votes vote down vote up
/**
 * @typedef {{
 *   main: string;
 *   site: {
 *     bucket: string;
 *   }
 * }} WranglerConfig
 */

/** @type {import('.').default} */
export default function (options = {}) {
	return {
		name: '@sveltejs/adapter-cloudflare-workers',

		async adapt(builder) {
			const { main, site } = validate_config(builder);

			const files = fileURLToPath(new URL('./files', import.meta.url).href);
			const tmp = builder.getBuildDirectory('cloudflare-workers-tmp');

			builder.rimraf(site.bucket);
			builder.rimraf(dirname(main));

			builder.log.info('Installing worker dependencies...');
			builder.copy(`${files}/_package.json`, `${tmp}/package.json`);

			// TODO would be cool if we could make this step unnecessary somehow
			const stdout = execSync('npm install', { cwd: tmp });
			builder.log.info(stdout.toString());

			builder.log.minor('Generating worker...');
			const relativePath = posix.relative(tmp, builder.getServerDirectory());

			builder.copy(`${files}/entry.js`, `${tmp}/entry.js`, {
				replace: {
					SERVER: `${relativePath}/index.js`,
					MANIFEST: './manifest.js'
				}
			});

			writeFileSync(
				`${tmp}/manifest.js`,
				`export const manifest = ${builder.generateManifest({
					relativePath
				})};\n\nexport const prerendered = new Map(${JSON.stringify(
					Array.from(builder.prerendered.pages.entries())
				)});\n`
			);

			await esbuild.build({
				platform: 'browser',
				sourcemap: 'linked',
				target: 'es2020',
				...options,
				entryPoints: [`${tmp}/entry.js`],
				outfile: main,
				bundle: true,
				external: ['__STATIC_CONTENT_MANIFEST', ...(options?.external || [])],
				format: 'esm'
			});

			builder.log.minor('Copying assets...');
			builder.writeClient(site.bucket);
			builder.writeStatic(site.bucket);
			builder.writePrerendered(site.bucket);
		}
	};
}
Example #13
Source File: index.js    From kit with MIT License 5 votes vote down vote up
/**
 * @param { object } params
 * @param {import('@sveltejs/kit').Builder} params.builder
 */
async function generate_edge_functions({ builder }) {
	const tmp = builder.getBuildDirectory('netlify-tmp');
	builder.rimraf(tmp);
	builder.mkdirp(tmp);

	builder.mkdirp('.netlify/edge-functions');

	// Don't match the static directory
	const pattern = '^/.*$';

	// Go doesn't support lookarounds, so we can't do this
	// const pattern = appDir ? `^/(?!${escapeStringRegexp(appDir)}).*$` : '^/.*$';

	/** @type {HandlerManifest} */
	const edge_manifest = {
		functions: [
			{
				function: 'render',
				pattern
			}
		],
		version: 1
	};

	builder.log.minor('Generating Edge Function...');
	const relativePath = posix.relative(tmp, builder.getServerDirectory());

	builder.copy(`${files}/edge.js`, `${tmp}/entry.js`, {
		replace: {
			'0SERVER': `${relativePath}/index.js`,
			MANIFEST: './manifest.js'
		}
	});

	const manifest = builder.generateManifest({
		relativePath
	});

	writeFileSync(
		`${tmp}/manifest.js`,
		`export const manifest = ${manifest};\n\nexport const prerendered = new Set(${JSON.stringify(
			builder.prerendered.paths
		)});\n`
	);

	await esbuild.build({
		entryPoints: [`${tmp}/entry.js`],
		outfile: '.netlify/edge-functions/render.js',
		bundle: true,
		format: 'esm',
		platform: 'browser',
		sourcemap: 'linked',
		target: 'es2020'
	});

	writeFileSync('.netlify/edge-functions/manifest.json', JSON.stringify(edge_manifest));
}
Example #14
Source File: index.js    From kit with MIT License 5 votes vote down vote up
/** @type {import('.').default} */
export default function (opts = {}) {
	// TODO remove for 1.0
	// @ts-expect-error
	if (opts.env) {
		throw new Error(
			'options.env has been removed in favour of options.envPrefix. Consult the adapter-node README: https://github.com/sveltejs/kit/tree/master/packages/adapter-node'
		);
	}

	const { out = 'build', precompress, envPrefix = '' } = opts;

	return {
		name: '@sveltejs/adapter-node',

		async adapt(builder) {
			builder.rimraf(out);

			builder.log.minor('Copying assets');
			builder.writeClient(`${out}/client`);
			builder.writeServer(`${out}/server`);
			builder.writeStatic(`${out}/static`);
			builder.writePrerendered(`${out}/prerendered`);

			writeFileSync(
				`${out}/manifest.js`,
				`export const manifest = ${builder.generateManifest({
					relativePath: './server'
				})};\n`
			);

			builder.copy(files, out, {
				replace: {
					SERVER: './server/index.js',
					MANIFEST: './manifest.js',
					ENV_PREFIX: JSON.stringify(envPrefix)
				}
			});

			if (precompress) {
				builder.log.minor('Compressing assets');
				await compress(`${out}/client`);
				await compress(`${out}/static`);
				await compress(`${out}/prerendered`);
			}
		}
	};
}
Example #15
Source File: prerender.js    From kit with MIT License 4 votes vote down vote up
/**
 * @param {{
 *   config: import('types').ValidatedKitConfig;
 *   entries: string[];
 *   files: Set<string>;
 *   log: Logger;
 * }} opts
 */
export async function prerender({ config, entries, files, log }) {
	/** @type {import('types').Prerendered} */
	const prerendered = {
		pages: new Map(),
		assets: new Map(),
		redirects: new Map(),
		paths: []
	};

	if (!config.prerender.enabled) {
		return prerendered;
	}

	installPolyfills();

	const server_root = join(config.outDir, 'output');

	/** @type {import('types').ServerModule} */
	const { Server, override } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
	const { manifest } = await import(pathToFileURL(`${server_root}/server/manifest.js`).href);

	override({
		paths: config.paths,
		prerendering: true,
		read: (file) => readFileSync(join(config.files.assets, file))
	});

	const server = new Server(manifest);

	const error = normalise_error_handler(log, config.prerender.onError);

	const q = queue(config.prerender.concurrency);

	/**
	 * @param {string} path
	 * @param {boolean} is_html
	 */
	function output_filename(path, is_html) {
		const file = path.slice(config.paths.base.length + 1);

		if (file === '') {
			return 'index.html';
		}

		if (is_html && !file.endsWith('.html')) {
			return file + (file.endsWith('/') ? 'index.html' : '.html');
		}

		return file;
	}

	const seen = new Set();
	const written = new Set();

	/**
	 * @param {string | null} referrer
	 * @param {string} decoded
	 * @param {string} [encoded]
	 */
	function enqueue(referrer, decoded, encoded) {
		if (seen.has(decoded)) return;
		seen.add(decoded);

		const file = decoded.slice(config.paths.base.length + 1);
		if (files.has(file)) return;

		return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer));
	}

	/**
	 * @param {string} decoded
	 * @param {string} encoded
	 * @param {string?} referrer
	 */
	async function visit(decoded, encoded, referrer) {
		if (!decoded.startsWith(config.paths.base)) {
			error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
			return;
		}

		/** @type {Map<string, import('types').PrerenderDependency>} */
		const dependencies = new Map();

		const response = await server.respond(new Request(`http://sveltekit-prerender${encoded}`), {
			getClientAddress,
			prerendering: {
				dependencies
			}
		});

		const text = await response.text();

		save('pages', response, text, decoded, encoded, referrer, 'linked');

		for (const [dependency_path, result] of dependencies) {
			// this seems circuitous, but using new URL allows us to not care
			// whether dependency_path is encoded or not
			const encoded_dependency_path = new URL(dependency_path, 'http://localhost').pathname;
			const decoded_dependency_path = decodeURI(encoded_dependency_path);

			const body = result.body ?? new Uint8Array(await result.response.arrayBuffer());
			save(
				'dependencies',
				result.response,
				body,
				decoded_dependency_path,
				encoded_dependency_path,
				decoded,
				'fetched'
			);
		}

		if (config.prerender.crawl && response.headers.get('content-type') === 'text/html') {
			for (const href of crawl(text)) {
				if (href.startsWith('data:') || href.startsWith('#')) continue;

				const resolved = resolve(encoded, href);
				if (!is_root_relative(resolved)) continue;

				const { pathname, search } = new URL(resolved, 'http://localhost');

				if (search) {
					// TODO warn that query strings have no effect on statically-exported pages
				}

				enqueue(decoded, decodeURI(pathname), pathname);
			}
		}
	}

	/**
	 * @param {'pages' | 'dependencies'} category
	 * @param {Response} response
	 * @param {string | Uint8Array} body
	 * @param {string} decoded
	 * @param {string} encoded
	 * @param {string | null} referrer
	 * @param {'linked' | 'fetched'} referenceType
	 */
	function save(category, response, body, decoded, encoded, referrer, referenceType) {
		const response_type = Math.floor(response.status / 100);
		const type = /** @type {string} */ (response.headers.get('content-type'));
		const is_html = response_type === REDIRECT || type === 'text/html';

		const file = output_filename(decoded, is_html);
		const dest = `${config.outDir}/output/prerendered/${category}/${file}`;

		if (written.has(file)) return;

		if (response_type === REDIRECT) {
			const location = response.headers.get('location');

			if (location) {
				const resolved = resolve(encoded, location);
				if (is_root_relative(resolved)) {
					enqueue(decoded, decodeURI(resolved), resolved);
				}

				if (!response.headers.get('x-sveltekit-normalize')) {
					mkdirp(dirname(dest));

					log.warn(`${response.status} ${decoded} -> ${location}`);

					writeFileSync(
						dest,
						`<meta http-equiv="refresh" content=${escape_html_attr(`0;url=${location}`)}>`
					);

					written.add(file);

					if (!prerendered.redirects.has(decoded)) {
						prerendered.redirects.set(decoded, {
							status: response.status,
							location: resolved
						});

						prerendered.paths.push(normalize_path(decoded, 'never'));
					}
				}
			} else {
				log.warn(`location header missing on redirect received from ${decoded}`);
			}

			return;
		}

		if (response.status === 200) {
			mkdirp(dirname(dest));

			log.info(`${response.status} ${decoded}`);
			writeFileSync(dest, body);
			written.add(file);

			if (is_html) {
				prerendered.pages.set(decoded, {
					file
				});
			} else {
				prerendered.assets.set(decoded, {
					type
				});
			}

			prerendered.paths.push(normalize_path(decoded, 'never'));
		} else if (response_type !== OK) {
			error({ status: response.status, path: decoded, referrer, referenceType });
		}
	}

	if (config.prerender.enabled) {
		for (const entry of config.prerender.entries) {
			if (entry === '*') {
				for (const entry of entries) {
					enqueue(null, config.paths.base + entry); // TODO can we pre-normalize these?
				}
			} else {
				enqueue(null, config.paths.base + entry);
			}
		}

		await q.done();
	}

	const rendered = await server.respond(new Request('http://sveltekit-prerender/[fallback]'), {
		getClientAddress,
		prerendering: {
			fallback: true,
			dependencies: new Map()
		}
	});

	const file = `${config.outDir}/output/prerendered/fallback.html`;
	mkdirp(dirname(file));
	writeFileSync(file, await rendered.text());

	return prerendered;
}
Example #16
Source File: index.js    From kit with MIT License 4 votes vote down vote up
/**
 * @param { object } params
 * @param {import('@sveltejs/kit').Builder} params.builder
 * @param { string } params.publish
 * @param { boolean } params.split
 * @param { boolean } params.esm
 */
async function generate_lambda_functions({ builder, publish, split, esm }) {
	builder.mkdirp('.netlify/functions-internal');

	/** @type {string[]} */
	const redirects = [];
	builder.writeServer('.netlify/server');

	const replace = {
		'0SERVER': './server/index.js' // digit prefix prevents CJS build from using this as a variable name, which would also get replaced
	};
	if (esm) {
		builder.copy(`${files}/esm`, '.netlify', { replace });
	} else {
		glob('**/*.js', { cwd: '.netlify/server' }).forEach((file) => {
			const filepath = `.netlify/server/${file}`;
			const input = readFileSync(filepath, 'utf8');
			const output = esbuild.transformSync(input, { format: 'cjs', target: 'node12' }).code;
			writeFileSync(filepath, output);
		});

		builder.copy(`${files}/cjs`, '.netlify', { replace });
		writeFileSync(join('.netlify', 'package.json'), JSON.stringify({ type: 'commonjs' }));
	}

	if (split) {
		builder.log.minor('Generating serverless functions...');

		await builder.createEntries((route) => {
			const parts = [];
			// Netlify's syntax uses '*' and ':param' as "splats" and "placeholders"
			// https://docs.netlify.com/routing/redirects/redirect-options/#splats
			for (const segment of route.segments) {
				if (segment.rest) {
					parts.push('*');
					break; // Netlify redirects don't allow anything after a *
				} else if (segment.dynamic) {
					parts.push(`:${parts.length}`);
				} else {
					parts.push(segment.content);
				}
			}

			const pattern = `/${parts.join('/')}`;
			const name = parts.join('-').replace(/[:.]/g, '_').replace('*', '__rest') || 'index';

			return {
				id: pattern,
				filter: (other) => matches(route.segments, other.segments),
				complete: (entry) => {
					const manifest = entry.generateManifest({
						relativePath: '../server',
						format: esm ? 'esm' : 'cjs'
					});

					const fn = esm
						? `import { init } from '../serverless.js';\n\nexport const handler = init(${manifest});\n`
						: `const { init } = require('../serverless.js');\n\nexports.handler = init(${manifest});\n`;

					writeFileSync(`.netlify/functions-internal/${name}.js`, fn);

					redirects.push(`${pattern} /.netlify/functions/${name} 200`);
					redirects.push(`${pattern}/__data.json /.netlify/functions/${name} 200`);
				}
			};
		});
	} else {
		builder.log.minor('Generating serverless functions...');

		const manifest = builder.generateManifest({
			relativePath: '../server',
			format: esm ? 'esm' : 'cjs'
		});

		const fn = esm
			? `import { init } from '../serverless.js';\n\nexport const handler = init(${manifest});\n`
			: `const { init } = require('../serverless.js');\n\nexports.handler = init(${manifest});\n`;

		writeFileSync('.netlify/functions-internal/render.js', fn);
		redirects.push('* /.netlify/functions/render 200');
	}

	// this should happen at the end, after builder.writeStatic(...),
	// so that generated redirects are appended to custom redirects
	// rather than replaced by them
	builder.log.minor('Writing redirects...');
	const redirect_file = join(publish, '_redirects');
	if (existsSync('_redirects')) {
		builder.copy('_redirects', redirect_file);
	}
	builder.mkdirp(dirname(redirect_file));
	appendFileSync(redirect_file, `\n\n${redirects.join('\n')}`);
}
Example #17
Source File: module.js    From onesignal-module with MIT License 4 votes vote down vote up
function addOneSignal (oneSignalOptions) {
  const { publicPath } = getRouteParams(this.options)

  // Merge options
  const defaults = {
    OneSignalSDK: undefined,
    cdn: true,
    GcmSenderId: '482941778795',
    importScripts: [
      '/sw.js?' + Date.now()
    ],
    init: {
      allowLocalhostAsSecureOrigin: true,
      welcomeNotification: {
        disable: true
      }
    }
  }

  const options = defu({ ...this.options.oneSignal, ...oneSignalOptions }, defaults)

  if (options.OneSignalSDK === undefined) {
    if (options.cdn) {
      // Use OneSignalSDK.js from CDN
      options.OneSignalSDK = 'https://cdn.onesignal.com/sdks/OneSignalSDK.js'
    } else {
      // Use OneSignalSDK.js from Dist
      const OneSignalSDKJS = readFileSync(path.resolve(__dirname, '../dist/OneSignalSDK.js'))
      const OneSignalSDKHash = hasha(OneSignalSDKJS)
      const OneSignalSDKFile = `ons.${OneSignalSDKHash}.js`

      options.OneSignalSDK = joinUrl(publicPath, OneSignalSDKFile)

      this.options.build.plugins.push({
        apply (compiler) {
          compiler.hooks.emit.tap('nuxt-pwa-onesignal', (compilation) => {
            compilation.assets[OneSignalSDKFile] = {
              source: () => OneSignalSDKJS,
              size: () => OneSignalSDKJS.length
            }
          })
        }
      })
    }
  }

  // Add the oneSignal SDK script to head
  if (!this.options.head.script.find(s => s.hid === 'onesignal')) {
    this.options.head.script.push({
      async: true,
      src: options.OneSignalSDK,
      hid: 'onesignal'
    })
  }

  // Adjust manifest for oneSignal
  if (!this.options.manifest) {
    this.options.manifest = {}
  }
  this.options.manifest.gcm_sender_id = options.GcmSenderId

  // Adjust swURL option of Workbox for oneSignal
  if (!this.options.workbox) {
    this.options.workbox = {}
  }
  this.options.workbox.swURL = 'OneSignalSDKWorker.js'

  // Provide OneSignalSDKWorker.js and OneSignalSDKUpdaterWorker.js
  const makeSW = (name, scripts) => {
    const workerScript = `importScripts(${scripts.map(i => `'${i}'`).join(', ')})\r\n`
    writeFileSync(path.resolve(this.options.srcDir, 'static', name), workerScript, 'utf-8')
  }

  makeSW('OneSignalSDKWorker.js', [].concat(options.importScripts || []).concat(options.OneSignalSDK))
  makeSW('OneSignalSDKUpdaterWorker.js', [options.OneSignalSDK])

  // Add OneSignal plugin
  this.addPlugin({
    src: path.resolve(__dirname, '../templates/plugin.js'),
    ssr: false,
    fileName: 'onesignal.js',
    options
  })
}
Example #18
Source File: registerMethods.js    From fes.js with MIT License 4 votes vote down vote up
export default function (api) {
    [
        'onExit',
        'onGenerateFiles',
        'addPluginExports',
        'addCoreExports',
        'addRuntimePluginKey',
        'addRuntimePlugin',
        'addEntryImportsAhead',
        'addEntryImports',
        'addEntryCodeAhead',
        'addEntryCode',
        'addBeforeMiddlewares',
        'addHTMLHeadScripts',
        'addMiddlewares',
        'modifyRoutes',
        'modifyBundleConfigOpts',
        'modifyBundleConfig',
        'modifyBabelOpts',
        'modifyBabelPresetOpts',
        'chainWebpack',
        'addTmpGenerateWatcherPaths',
        'modifyPublicPathStr'
    ].forEach((name) => {
        api.registerMethod({ name });
    });

    api.registerMethod({
        name: 'writeTmpFile',
        fn({
            path,
            content
        }) {
            assert(
                api.stage >= api.ServiceStage.pluginReady,
                'api.writeTmpFile() should not execute in register stage.'
            );
            const absPath = join(api.paths.absTmpPath, path);
            api.utils.mkdirp.sync(dirname(absPath));
            if (!existsSync(absPath) || readFileSync(absPath, 'utf-8') !== content) {
                writeFileSync(absPath, content, 'utf-8');
            }
        }
    });

    api.registerMethod({
        name: 'copyTmpFiles',
        fn({
            namespace, path, ignore
        }) {
            assert(
                api.stage >= api.ServiceStage.pluginReady,
                'api.copyTmpFiles() should not execute in register stage.'
            );
            assert(
                path,
                'api.copyTmpFiles() should has param path'
            );
            assert(
                namespace,
                'api.copyTmpFiles() should has param namespace'
            );
            const files = api.utils.glob.sync('**/*', {
                cwd: path
            });
            const base = join(api.paths.absTmpPath, namespace);
            files.forEach((file) => {
                const source = join(path, file);
                const target = join(base, file);
                if (!existsSync(dirname(target))) {
                    api.utils.mkdirp.sync(dirname(target));
                }
                if (statSync(source).isDirectory()) {
                    api.utils.mkdirp.sync(target);
                } else if (Array.isArray(ignore)) {
                    if (!ignore.some(pattern => new RegExp(pattern).test(file))) {
                        copyFileSync(source, target);
                    }
                } else {
                    copyFileSync(source, target);
                }
            });
        }
    });
}