Best JavaScript code snippet using storybook-root
watcher.js
Source:watcher.js
1const path = require("path");2const fs = require("fs-extra");3const chokidar = require("chokidar");4const find_ = require("lodash/find");5const reject_ = require("lodash/reject");6const logger = require("corvid-local-logger");7const { isUnderPath, isSamePath } = require("./utils/fileUtils");8const { isPathRelatedToSite } = require("./sitePaths");9const { getMessage } = require("./messages");10const ensureWriteFile = async (path, content) => {11 await fs.ensureFile(path);12 await fs.writeFile(path, content);13};14const toPosixPath = winPath => winPath.replace(/\\/g, "/");15const watch = async givenPath => {16 let ignoreBefore = 0;17 let ignoreAll = false;18 logger.verbose(getMessage("Watcher_Start_Log", { path: givenPath }));19 const rootPath = fs.realpathSync(givenPath);20 if (rootPath !== givenPath) {21 logger.debug(getMessage("Watcher_Path_Resolved_Log", { path: rootPath }));22 }23 const fullPath = relativePath => path.join(rootPath, relativePath);24 const isUnderRoot = pathToCheck =>25 isUnderPath(rootPath, fullPath(pathToCheck));26 const shouldIgnoreFile = watchPath => {27 const isInterestingPath =28 isSamePath(rootPath, watchPath) ||29 (isUnderRoot(watchPath) && isPathRelatedToSite(rootPath, watchPath));30 return !isInterestingPath;31 };32 const assertUnderRoot = pathToCheck => {33 if (!isUnderRoot(pathToCheck)) {34 throw new Error(getMessage("Watcher_Not_Under_Root_Error"));35 }36 };37 const watcher = chokidar.watch(rootPath, {38 ignored: shouldIgnoreFile,39 persistent: true,40 ignoreInitial: true,41 cwd: rootPath,42 awaitWriteFinish: {43 stabilityThreshold: 50044 },45 followSymlinks: false,46 disableGlobbing: true,47 alwaysStat: true48 });49 await new Promise((resolve, reject) => {50 watcher.on("ready", () => resolve());51 watcher.on("error", () => reject());52 });53 let actionsToIgnore = [];54 const ignoreAction = (type, path) => {55 actionsToIgnore.push({ type, path });56 };57 const removeFromIgnoredActions = (type, path) => {58 actionsToIgnore = reject_(actionsToIgnore, { type, path });59 };60 const isIgnoredAction = (type, path, mtimeMs = Date.now()) =>61 ignoreAll ||62 mtimeMs < ignoreBefore ||63 !!find_(actionsToIgnore, { type, path });64 return {65 close: () => watcher.close(),66 onAdd: callback => {67 watcher.on("add", async (relativePath, stats) => {68 const posixRelativePath = toPosixPath(relativePath);69 if (!isIgnoredAction("write", posixRelativePath, stats.mtimeMs)) {70 logger.debug(71 getMessage("Watcher_Add_Reporting_Log", { path: posixRelativePath })72 );73 callback(74 posixRelativePath,75 await fs.readFile(fullPath(posixRelativePath), "utf8")76 );77 } else {78 logger.debug(79 getMessage("Watcher_Add_Ignoring_Log", { path: posixRelativePath })80 );81 removeFromIgnoredActions("write", posixRelativePath);82 }83 });84 },85 onChange: callback => {86 watcher.on("change", async (relativePath, stats) => {87 const posixRelativePath = toPosixPath(relativePath);88 if (!isIgnoredAction("write", posixRelativePath, stats.mtimeMs)) {89 logger.debug(90 getMessage("Watcher_Change_Reporting_Log", {91 path: posixRelativePath92 })93 );94 callback(95 posixRelativePath,96 await fs.readFile(fullPath(posixRelativePath), "utf8")97 );98 } else {99 logger.debug(100 getMessage("Watcher_Change_Ignoring_Log", {101 path: posixRelativePath102 })103 );104 removeFromIgnoredActions("write", posixRelativePath);105 }106 });107 },108 onDelete: callback => {109 watcher.on("unlink", async relativePath => {110 const posixRelativePath = toPosixPath(relativePath);111 if (!isIgnoredAction("delete", posixRelativePath)) {112 logger.debug(113 getMessage("Watcher_Delete_Reporting_Log", {114 path: posixRelativePath115 })116 );117 callback(posixRelativePath);118 } else {119 logger.debug(120 getMessage("Watcher_Delete_Ignoring_Log", {121 path: posixRelativePath122 })123 );124 removeFromIgnoredActions("delete", posixRelativePath);125 }126 });127 },128 ignoredWriteFile: async (relativePath, content) => {129 logger.silly(130 getMessage("Watcher_Ignored_Write_Log", { path: relativePath })131 );132 try {133 ignoreAction("write", relativePath);134 assertUnderRoot(relativePath);135 await ensureWriteFile(fullPath(relativePath), content);136 } catch (err) {137 logger.info(138 `Failed writing file to [${relativePath}] failed - ${err.message}`139 );140 logger.error(err);141 removeFromIgnoredActions("write", relativePath);142 throw err;143 }144 },145 ignoredEnsureFile: async relativePath => {146 logger.silly(147 getMessage("Watcher_Ignored_Ensure_Log", { path: relativePath })148 );149 const fullPathFile = fullPath(relativePath);150 if (await fs.exists(fullPathFile)) return;151 try {152 ignoreAction("write", relativePath);153 assertUnderRoot(relativePath);154 await fs.ensureFile(fullPathFile);155 } catch (err) {156 logger.info(157 `Failed ensuring file at [${relativePath}] failed - ${err.message}`158 );159 logger.error(err);160 removeFromIgnoredActions("write", relativePath);161 throw err;162 }163 },164 ignoredDeleteFile: async relativePath => {165 logger.silly(166 getMessage("Watcher_Ignored_Delete_Log", { path: relativePath })167 );168 try {169 ignoreAction("delete", relativePath);170 assertUnderRoot(relativePath);171 await fs.remove(fullPath(relativePath));172 } catch (err) {173 logger.info(174 `Failed deleting file at [${relativePath}] failed - ${err.message}`175 );176 logger.error(err);177 removeFromIgnoredActions("delete", relativePath);178 throw err;179 }180 },181 ignoredCopyFile: async (relativeSourcePath, relativeTargetPath) => {182 logger.silly(183 getMessage("Watcher_Ignored_Copy_Log", {184 sourcePath: relativeSourcePath,185 targetPath: relativeTargetPath186 })187 );188 try {189 ignoreAction("write", relativeTargetPath);190 assertUnderRoot(relativeSourcePath);191 assertUnderRoot(relativeTargetPath);192 await fs.copy(193 fullPath(relativeSourcePath),194 fullPath(relativeTargetPath)195 );196 } catch (err) {197 logger.info(198 `Failed copying file from [${relativeSourcePath}] to [${relativeTargetPath}] failed - ${199 err.message200 }`201 );202 logger.error(err);203 removeFromIgnoredActions("write", relativeTargetPath);204 throw err;205 }206 },207 ignoredMoveFile: async (relativeSourcePath, relativeTargetPath) => {208 logger.silly(209 getMessage("Watcher_Ignored_Move_Log", {210 sourcePath: relativeSourcePath,211 targetPath: relativeTargetPath212 })213 );214 try {215 ignoreAction("delete", relativeSourcePath);216 ignoreAction("write", relativeTargetPath);217 await fs.move(218 fullPath(relativeSourcePath),219 fullPath(relativeTargetPath)220 );221 } catch (err) {222 logger.info(223 `Failed moving file from [${relativeSourcePath}] to [${relativeTargetPath}] failed - ${224 err.message225 }`226 );227 logger.error(err);228 removeFromIgnoredActions("delete", relativeSourcePath);229 removeFromIgnoredActions("write", relativeTargetPath);230 throw err;231 }232 },233 pause: () => {234 ignoreAll = true;235 },236 resume: () => {237 ignoreAll = false;238 ignoreBefore = Date.now();239 }240 };241};...
firebaser.js
Source:firebaser.js
1import firebase from 'firebase'2import { typeReducer } from './index'3import { isArray, isString } from 'lodash'4import { firebase as firebaseConfig } from '../config'5/**6 * @description Initialize firebase application7 */8export const init = (config) => {9 const fbConfig = config ? firebaseConfig[config.env] : firebaseConfig.prod10 try {11 firebase.initializeApp(fbConfig)12 } catch (err) {13 console.warn('You only need to initialize Firebase once', JSON.stringify(err))14 }15 return firebase16}17export const storage = () => firebase.storage()18/**19 * @description Handles abnormal characters within paths20 * @param {Array|String} relativePath - Releative path on firebase21 * @return {String} realtive url string for Firebase22 */23export const createFirebaseUrl = (relativePath) => () => {24 if (!isArray(relativePath)) relativePath = [relativePath]25 // TODO: Check for path not being string26 return relativePath.map((loc) => (loc && isString(loc))27 ? loc.replace(/[.]/g, ':')28 .replace(/[#$[\]]/g, '_-_')29 : loc30 ).join('/')31}32/**33 * @description Handles abnormal characters within paths34 * @param {Array|String} relativePath - Releative path35 * @return {Promise}36 */37export const createFirebaseRef = (relativePath) => () =>38 firebase.database().ref(createFirebaseUrl(relativePath)()) // eslint-disable-line new-cap39/**40 * @description Get a location on Firebase41 * @param {Array|String} relativePath - Releative42 * @return {Promise}43 */44export const get = (relativePath) => () =>45 createFirebaseRef(relativePath)()46 .once('value')47 .then((data) => data.val())48/**49 * @description Set data to a Firebase location based on array or string path50 * @param {Array|String} relativePath - Releative51 * @return {Promise}52 */53export const set = (relativePath) => (object, priority) => {54 return createFirebaseRef(relativePath)()[priority ? 'setWithPriority' : 'set'](object)55 .then((data) => data ? data.val() : object)56}57/**58 * @description Set data to a Firebase location based on array or string path59 * @param {Array|String} relativePath - Releative60 * @return {Promise}61 */62export const setWithPriority = (relativePath) => (object, priority) =>63 createFirebaseRef(relativePath)()64 .setWithPriority(object)65 .then((data) => data ? data.val() : object)66/**67 * @description Push data to a Firebase location based on array or string path68 * @param {Array|String} relativePath - Releative69 * @return {Promise}70 */71export const push = (relativePath) => (object, priority) => {72 const pushRef = createFirebaseRef(relativePath)().push()73 return pushRef[priority ? 'setWithPriority' : 'set'](object)74 .then((data) => data75 ? Object.assign({}, { key: pushRef.key }, data)76 : Object.assign(object, { key: pushRef.key })77 )78}79export const add = push80/**81 * @description Update data at a Firebase location based on array or string path82 * @param {Array|String} relativePath - Releative83 * @return {Promise}84 */85export const update = (relativePath) => (object) =>86 createFirebaseRef(relativePath)()87 .update(object)88 .then((data) => data ? data.val() : object)89/**90 * @description Remove data a Firebase location based on array or string path91 * @param {Array|String} relativePath - Releative92 * @return {Promise}93 */94export const remove = (relativePath) => () =>95 createFirebaseRef(relativePath)()96 .remove()97 .then((data) => null)98/**99 * @description Set data to a Firebase location based on array or string path100 * @param {Array|String} relativePath - Path from Firebase root101 * @return {Promise}102 */103 // TODO: Allow passing of type of sync like 'child_added'104export const sync = (relativePath) => (callback) =>105 createFirebaseRef(relativePath)()106 .on('value', (data) =>107 callback(Object.assign(data.val(), { ref: data.ref }))108 )109/**110 * @description Set data to a Firebase location based on array or string path111 * @param {Array|String} relativePath - Path from Firebase root112 * @return {Promise}113 */114export const unsync = (relativePath) => (callback) => {115 createFirebaseRef(relativePath)()116 .off('value', callback, callback)117}118/**119 * @description Search firebase router120 * @param {Array|String} relativePath - Path from Firebase root121 * @return {Promise}122 */123export const search = (relativePath) => (param, q) =>124 createFirebaseRef(relativePath)()125 .orderByChild(param)126 .startAt(q)127 .once('value')128 .then((data) => data.val())129/**130 * @description Resolve the JSON value a Firebase location's child131 * @param {Array|String} relativePath - Path from Firebase root132 * @return {Promise}133 */134export const getChild = (relativePath) => (child) =>135 createFirebaseRef(relativePath)()136 .child(child)137 .once('value')138 .then((data) => data.val())139export default (url, types) => {140 let methods = {141 get,142 getChild,143 set,144 add,145 sync,146 update,147 remove,148 createFirebaseUrl,149 createFirebaseRef150 }151 return typeReducer(url, types, methods, 'firebaser')...
cache.js
Source:cache.js
1var assert = require("assert");2var Q = require("q");3var fs = require("fs");4var path = require("path");5var util = require("./util");6var EventEmitter = require("events").EventEmitter;7var hasOwn = Object.prototype.hasOwnProperty;8/**9 * ReadFileCache is an EventEmitter subclass that caches file contents in10 * memory so that subsequent calls to readFileP return the same contents,11 * regardless of any changes in the underlying file.12 */13function ReadFileCache(sourceDir, charset) {14 assert.ok(this instanceof ReadFileCache);15 assert.strictEqual(typeof sourceDir, "string");16 this.charset = charset;17 EventEmitter.call(this);18 Object.defineProperties(this, {19 sourceDir: { value: sourceDir },20 sourceCache: { value: {} }21 });22}23util.inherits(ReadFileCache, EventEmitter);24var RFCp = ReadFileCache.prototype;25/**26 * Read a file from the cache if possible, else from disk.27 */28RFCp.readFileP = function(relativePath) {29 var cache = this.sourceCache;30 relativePath = path.normalize(relativePath);31 return hasOwn.call(cache, relativePath)32 ? cache[relativePath]33 : this.noCacheReadFileP(relativePath);34};35/**36 * Read (or re-read) a file without using the cache.37 *38 * The new contents are stored in the cache for any future calls to39 * readFileP.40 */41RFCp.noCacheReadFileP = function(relativePath) {42 relativePath = path.normalize(relativePath);43 var added = !hasOwn.call(this.sourceCache, relativePath);44 var promise = this.sourceCache[relativePath] = util.readFileP(45 path.join(this.sourceDir, relativePath), this.charset);46 if (added) {47 this.emit("added", relativePath);48 }49 return promise;50};51/**52 * If you have reason to believe the contents of a file have changed, call53 * this method to re-read the file and compare the new contents to the54 * cached contents. If the new contents differ from the contents of the55 * cache, the "changed" event will be emitted.56 */57RFCp.reportPossiblyChanged = function(relativePath) {58 var self = this;59 var cached = self.readFileP(relativePath);60 var fresh = self.noCacheReadFileP(relativePath);61 Q.spread([62 cached.catch(orNull),63 fresh.catch(orNull)64 ], function(oldData, newData) {65 if (oldData !== newData) {66 self.emit("changed", relativePath);67 }68 }).done();69};70/**71 * Invoke the given callback for all files currently known to the72 * ReadFileCache, and invoke it in the future when any new files become73 * known to the cache.74 */75RFCp.subscribe = function(callback, context) {76 for (var relativePath in this.sourceCache) {77 if (hasOwn.call(this.sourceCache, relativePath)) {78 callback.call(context || null, relativePath);79 }80 }81 this.on("added", function(relativePath) {82 callback.call(context || null, relativePath);83 });84};85/**86 * Avoid memory leaks by removing listeners and emptying the cache.87 */88RFCp.clear = function() {89 this.removeAllListeners();90 for (var relativePath in this.sourceCache) {91 delete this.sourceCache[relativePath];92 }93};94function orNull(err) {95 return null;96}...
Using AI Code Generation
1const rootRequire = require('storybook-root-require');2const path = rootRequire.relativePath('./src');3const rootRequire = require('storybook-root-require');4const path = rootRequire.relativePath('./src');5const path = require('path');6const rootRequire = require('storybook-root-require');7const path = rootRequire.relativePath('./src');8const path = require('path');9const rootRequire = require('storybook-root-require');10const path = rootRequire.relativePath('./src');11const path = require('path');12const rootRequire = require('storybook-root-require');13const path = rootRequire.relativePath('./src');14const path = require('path');15const rootRequire = require('storybook-root-require');16const path = rootRequire.relativePath('./src');17const path = require('path');18const rootRequire = require('storybook-root-require');19const path = rootRequire.relativePath('./src');20const path = require('path');21const rootRequire = require('storybook-root-require');22const path = rootRequire.relativePath('./src');23const path = require('path');24const rootRequire = require('storybook-root-require');25const path = rootRequire.relativePath('./src');26const path = require('path');27const rootRequire = require('storybook-root-require');28const path = rootRequire.relativePath('./src');29const path = require('path');30const rootRequire = require('storybook-root-require');31const path = rootRequire.relativePath('./src');32const path = require('path');33const rootRequire = require('storybook-root-require');34const path = rootRequire.relativePath('./src');35const path = require('path');36const rootRequire = require('storybook-root-require');37const path = rootRequire.relativePath('./src');38const path = require('path');39const rootRequire = require('storybook-root-require');40const path = rootRequire.relativePath('./src');41const path = require('path');
Using AI Code Generation
1var path = require('storybook-root-require').relativePath;2module.exports = {3 webpackFinal: async config => {4 config.module.rules.push({5 include: path('../'),6 });7 return config;8 },9};
Using AI Code Generation
1import { relativePath } from 'storybook-root';2const path = relativePath('src', 'test.js');3import { relativePath } from 'storybook-root';4const path = relativePath('src', 'test.js');5import { relativePath } from 'storybook-root';6const path = relativePath('src', 'test.js');7import { relativePath } from 'storybook-root';8const path = relativePath('src', 'test.js');9import { relativePath } from 'storybook-root';10const path = relativePath('src', 'test.js');11import { relativePath } from 'storybook-root';12const path = relativePath('src', 'test.js');13import { relativePath } from 'storybook-root';14const path = relativePath('src', 'test.js');15import { relativePath } from 'storybook-root';16const path = relativePath('src', 'test.js');17import { relativePath } from 'storybook-root';18const path = relativePath('src', 'test.js');19import { relativePath } from 'storybook-root';20const path = relativePath('src', 'test.js');
Using AI Code Generation
1const path = require('path');2const root = require('storybook-root');3const relativePath = root.relativePath;4const myPath = relativePath(__dirname, './test.js');5const path = require('path');6const root = require('storybook-root');7const relativePath = root.relativePath;8const myPath = relativePath(__dirname, './test.js');9const path = require('path');10const root = require('storybook-root');11const relativePath = root.relativePath;12const myPath = relativePath(__dirname, './test.js');13const path = require('path');14const root = require('storybook-root');15const relativePath = root.relativePath;16const myPath = relativePath(__dirname, './test.js');17const path = require('path');18const root = require('storybook-root');19const relativePath = root.relativePath;20const myPath = relativePath(__dirname, './test.js');21const path = require('path');22const root = require('storybook-root');23const relativePath = root.relativePath;24const myPath = relativePath(__dirname, './test.js');25const path = require('path');26const root = require('storybook-root');27const relativePath = root.relativePath;28const myPath = relativePath(__dirname, './test.js');29const path = require('path');30const root = require('storybook-root');31const relativePath = root.relativePath;32const myPath = relativePath(__dirname, './test.js');
Using AI Code Generation
1const path = require('path');2const root = require('storybook-root');3const relativePath = root.relativePath;4const absolutePath = path.join(__dirname, 'src');5console.log(relativePath(absolutePath));6const path = require('path');7const root = require('storybook-root');8const relativePath = root.relativePath;9const absolutePath = path.join(__dirname, '../src');10console.log(relativePath(absolutePath));11const path = require('path');12const root = require('storybook-root');13const relativePath = root.relativePath;14const absolutePath = path.join(__dirname, 'src');15console.log(relativePath(absolutePath));16const path = require('path');17const root = require('storybook-root');18const relativePath = root.relativePath;19const absolutePath = path.join(__dirname, 'src');20console.log(relativePath(absolutePath));21const path = require('path');22const root = require('storybook-root');23const relativePath = root.relativePath;24const absolutePath = path.join(__dirname, 'src');25console.log(relativePath(absolutePath));26const path = require('path');27const root = require('storybook-root');28const relativePath = root.relativePath;29const absolutePath = path.join(__dirname, 'src');30console.log(relativePath(absolutePath));31const path = require('path');32const root = require('storybook-root');33const relativePath = root.relativePath;34const absolutePath = path.join(__dirname, 'src');35console.log(relativePath(absolutePath));
Using AI Code Generation
1const relativePath = require('storybook-root-require');2const path = require('path');3const absolutePath = relativePath('./src');4console.log(absolutePath);5console.log(path.resolve('./src'));6If you are using babel-plugin-root-import , you can use the same config in storybook-root-require . For example, if you have the following config in your .babelrc file:7{8 ["babel-plugin-root-import", {9 }]10}11import { configure } from '@storybook/react';12import { setRootRequire } from 'storybook-root-require';13setRootRequire({14});15configure(() => {16 require('./stories');17}, module);18Now, you can use the following syntax to import your components in your stories:19import Button from 'components/Button';
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!