Best JavaScript code snippet using storybook-root
storybook-metadata.test.ts
Source:storybook-metadata.test.ts
1import type { PackageJson, StorybookConfig } from '@storybook/core-common';2import path from 'path';3import { computeStorybookMetadata, metaFrameworks, sanitizeAddonName } from './storybook-metadata';4const packageJsonMock: PackageJson = {5 name: 'some-user-project',6 version: 'x.x.x',7};8const mainJsMock: StorybookConfig = {9 stories: [],10};11jest.mock('./package-versions', () => {12 const getActualPackageVersion = jest.fn((name) =>13 Promise.resolve({14 name,15 version: 'x.x.x',16 })17 );18 const getActualPackageVersions = jest.fn((packages) =>19 Promise.all(Object.keys(packages).map(getActualPackageVersion))20 );21 return {22 getActualPackageVersions,23 getActualPackageVersion,24 };25});26jest.mock('./get-monorepo-type', () => ({27 getMonorepoType: () => 'Nx',28}));29jest.mock('detect-package-manager', () => ({30 detect: () => 'Yarn',31 getNpmVersion: () => '3.1.1',32}));33describe('sanitizeAddonName', () => {34 const originalSep = path.sep;35 beforeEach(() => {36 // @ts-expect-error the property is read only but we can change it for testing purposes37 path.sep = originalSep;38 });39 test('special addon names', () => {40 const addonNames = [41 '@storybook/preset-create-react-app',42 'storybook-addon-deprecated/register',43 'storybook-addon-ends-with-js/register.js',44 '@storybook/addon-knobs/preset',45 '@storybook/addon-ends-with-js/preset.js',46 '@storybook/addon-postcss/dist/index.js',47 '../local-addon/register.js',48 '../../',49 ].map(sanitizeAddonName);50 expect(addonNames).toEqual([51 '@storybook/preset-create-react-app',52 'storybook-addon-deprecated',53 'storybook-addon-ends-with-js',54 '@storybook/addon-knobs',55 '@storybook/addon-ends-with-js',56 '@storybook/addon-postcss',57 '../local-addon',58 '../../',59 ]);60 });61 test('Windows paths', () => {62 // @ts-expect-error the property is read only but we can change it for testing purposes63 path.sep = '\\';64 const cwdMockPath = `C:\\Users\\username\\storybook-app`;65 jest.spyOn(process, `cwd`).mockImplementationOnce(() => cwdMockPath);66 expect(sanitizeAddonName(`${cwdMockPath}\\local-addon\\themes.js`)).toEqual(67 '$SNIP\\local-addon\\themes'68 );69 });70 test('Linux paths', () => {71 // @ts-expect-error the property is read only but we can change it for testing purposes72 path.sep = '/';73 const cwdMockPath = `/Users/username/storybook-app`;74 jest.spyOn(process, `cwd`).mockImplementationOnce(() => cwdMockPath);75 expect(sanitizeAddonName(`${cwdMockPath}/local-addon/themes.js`)).toEqual(76 '$SNIP/local-addon/themes'77 );78 });79});80describe('await computeStorybookMetadata', () => {81 test('should return frameworkOptions from mainjs', async () => {82 const reactResult = await computeStorybookMetadata({83 packageJson: {84 ...packageJsonMock,85 devDependencies: {86 '@storybook/react': 'x.x.x',87 },88 },89 mainConfig: {90 ...mainJsMock,91 reactOptions: {92 fastRefresh: false,93 },94 },95 });96 expect(reactResult.framework).toEqual({ name: 'react', options: { fastRefresh: false } });97 const angularResult = await computeStorybookMetadata({98 packageJson: {99 ...packageJsonMock,100 devDependencies: {101 '@storybook/angular': 'x.x.x',102 },103 },104 mainConfig: {105 ...mainJsMock,106 angularOptions: {107 enableIvy: true,108 },109 },110 });111 expect(angularResult.framework).toEqual({ name: 'angular', options: { enableIvy: true } });112 });113 test('should separate storybook packages and addons', async () => {114 const result = await computeStorybookMetadata({115 packageJson: {116 ...packageJsonMock,117 devDependencies: {118 '@storybook/react': 'x.y.z',119 '@storybook/addon-essentials': 'x.x.x',120 '@storybook/addon-knobs': 'x.x.y',121 'storybook-addon-deprecated': 'x.x.z',122 },123 },124 mainConfig: {125 ...mainJsMock,126 addons: [127 '@storybook/addon-essentials',128 'storybook-addon-deprecated/register',129 '@storybook/addon-knobs/preset',130 ],131 },132 });133 expect(result.addons).toMatchInlineSnapshot(`134 Object {135 "@storybook/addon-essentials": Object {136 "options": undefined,137 "version": "x.x.x",138 },139 "@storybook/addon-knobs": Object {140 "options": undefined,141 "version": "x.x.x",142 },143 "storybook-addon-deprecated": Object {144 "options": undefined,145 "version": "x.x.x",146 },147 }148 `);149 expect(result.storybookPackages).toMatchInlineSnapshot(`150 Object {151 "@storybook/react": Object {152 "version": "x.x.x",153 },154 }155 `);156 });157 test('should return user specified features', async () => {158 const features = {159 interactionsDebugger: true,160 };161 const result = await computeStorybookMetadata({162 packageJson: packageJsonMock,163 mainConfig: {164 ...mainJsMock,165 features,166 },167 });168 expect(result.features).toEqual(features);169 });170 test('should handle different types of builders', async () => {171 const simpleBuilder = 'webpack4';172 const complexBuilder = {173 name: 'webpack5',174 options: {175 lazyCompilation: true,176 },177 };178 expect(179 (180 await computeStorybookMetadata({181 packageJson: packageJsonMock,182 mainConfig: {183 ...mainJsMock,184 core: {185 builder: complexBuilder,186 },187 },188 })189 ).builder190 ).toEqual(complexBuilder);191 expect(192 (193 await computeStorybookMetadata({194 packageJson: packageJsonMock,195 mainConfig: {196 ...mainJsMock,197 core: {198 builder: simpleBuilder,199 },200 },201 })202 ).builder203 ).toEqual({ name: simpleBuilder });204 });205 test('should return the number of refs', async () => {206 const res = await computeStorybookMetadata({207 packageJson: packageJsonMock,208 mainConfig: {209 ...mainJsMock,210 refs: {211 a: { title: '', url: '' },212 b: { title: '', url: '' },213 },214 },215 });216 expect(res.refCount).toEqual(2);217 });218 test.each(Object.entries(metaFrameworks))(219 'should detect the supported metaframework: %s',220 async (metaFramework, name) => {221 const res = await computeStorybookMetadata({222 packageJson: {223 ...packageJsonMock,224 dependencies: {225 [metaFramework]: 'x.x.x',226 },227 },228 mainConfig: mainJsMock,229 });230 expect(res.metaFramework).toEqual({231 name,232 packageName: metaFramework,233 version: 'x.x.x',234 });235 }236 );...
storybook-metadata.ts
Source:storybook-metadata.ts
1import readPkgUp from 'read-pkg-up';2import { detect, getNpmVersion } from 'detect-package-manager';3import {4 loadMainConfig,5 getStorybookInfo,6 getStorybookConfiguration,7 getProjectRoot,8} from '@storybook/core-common';9import type { StorybookConfig, PackageJson } from '@storybook/core-common';10import type { StorybookMetadata, Dependency, StorybookAddon } from './types';11import { getActualPackageVersion, getActualPackageVersions } from './package-versions';12import { getMonorepoType } from './get-monorepo-type';13import { cleanPaths } from './sanitize';14export const metaFrameworks = {15 next: 'Next',16 'react-scripts': 'CRA',17 gatsby: 'Gatsby',18 '@nuxtjs/storybook': 'nuxt',19 '@nrwl/storybook': 'nx',20 '@vue/cli-service': 'vue-cli',21 '@sveltejs/kit': 'svelte-kit',22} as Record<string, string>;23// @TODO: This should be removed in 7.0 as the framework.options field in main.js will replace this24const getFrameworkOptions = (mainConfig: any) => {25 const possibleOptions = [26 'angular',27 'ember',28 'html',29 'preact',30 'react',31 'server',32 'svelte',33 'vue',34 'vue3',35 'webComponents',36 ].map((opt) => `${opt}Options`);37 // eslint-disable-next-line no-restricted-syntax38 for (const opt of possibleOptions) {39 if (opt in mainConfig) {40 return mainConfig[opt] as any;41 }42 }43 return undefined;44};45export const sanitizeAddonName = (name: string) => {46 return cleanPaths(name)47 .replace(/\/dist\/.*/, '')48 .replace(/\.[mc]?[tj]?s[x]?$/, '')49 .replace(/\/register$/, '')50 .replace(/\/manager$/, '')51 .replace(/\/preset$/, '');52};53// Analyze a combination of information from main.js and package.json54// to provide telemetry over a Storybook project55export const computeStorybookMetadata = async ({56 packageJson,57 mainConfig,58}: {59 packageJson: PackageJson;60 mainConfig: StorybookConfig & Record<string, any>;61}): Promise<StorybookMetadata> => {62 const metadata: Partial<StorybookMetadata> = {63 generatedAt: new Date().getTime(),64 builder: { name: 'webpack5' },65 hasCustomBabel: false,66 hasCustomWebpack: false,67 hasStaticDirs: false,68 hasStorybookEslint: false,69 refCount: 0,70 };71 const allDependencies = {72 ...packageJson?.dependencies,73 ...packageJson?.devDependencies,74 ...packageJson?.peerDependencies,75 };76 const metaFramework = Object.keys(allDependencies).find((dep) => !!metaFrameworks[dep]);77 if (metaFramework) {78 const { version } = await getActualPackageVersion(metaFramework);79 metadata.metaFramework = {80 name: metaFrameworks[metaFramework],81 packageName: metaFramework,82 version,83 };84 }85 const monorepoType = getMonorepoType();86 if (monorepoType) {87 metadata.monorepo = monorepoType;88 }89 try {90 const packageManagerType = await detect({ cwd: getProjectRoot() });91 const packageManagerVerson = await getNpmVersion(packageManagerType);92 metadata.packageManager = {93 type: packageManagerType,94 version: packageManagerVerson,95 };96 // Better be safe than sorry, some codebases/paths might end up breaking with something like "spawn pnpm ENOENT"97 // so we just set the package manager if the detection is successful98 // eslint-disable-next-line no-empty99 } catch (err) {}100 metadata.hasCustomBabel = !!mainConfig.babel;101 metadata.hasCustomWebpack = !!mainConfig.webpackFinal;102 metadata.hasStaticDirs = !!mainConfig.staticDirs;103 if (mainConfig.typescript) {104 metadata.typescriptOptions = mainConfig.typescript;105 }106 if (mainConfig.core?.builder) {107 const { builder } = mainConfig.core;108 metadata.builder = {109 name: typeof builder === 'string' ? builder : builder.name,110 options: typeof builder === 'string' ? undefined : builder?.options ?? undefined,111 };112 }113 if (mainConfig.refs) {114 metadata.refCount = Object.keys(mainConfig.refs).length;115 }116 if (mainConfig.features) {117 metadata.features = mainConfig.features;118 }119 const addons: Record<string, StorybookAddon> = {};120 if (mainConfig.addons) {121 mainConfig.addons.forEach((addon) => {122 let addonName;123 let options;124 if (typeof addon === 'string') {125 addonName = sanitizeAddonName(addon);126 } else {127 options = addon.options;128 addonName = sanitizeAddonName(addon.name);129 }130 addons[addonName] = {131 options,132 version: undefined,133 };134 });135 }136 const addonVersions = await getActualPackageVersions(addons);137 addonVersions.forEach(({ name, version }) => {138 addons[name].version = version;139 });140 const addonNames = Object.keys(addons);141 // all Storybook deps minus the addons142 const storybookPackages = Object.keys(allDependencies)143 .filter((dep) => dep.includes('storybook') && !addonNames.includes(dep))144 .reduce((acc, dep) => {145 return {146 ...acc,147 [dep]: { version: undefined },148 };149 }, {}) as Record<string, Dependency>;150 const storybookPackageVersions = await getActualPackageVersions(storybookPackages);151 storybookPackageVersions.forEach(({ name, version }) => {152 storybookPackages[name].version = version;153 });154 const language = allDependencies.typescript ? 'typescript' : 'javascript';155 const hasStorybookEslint = !!allDependencies['eslint-plugin-storybook'];156 // FIXME: resolve framework/renderer split in 7.0157 // OR should be getting this from mainConfig instead?158 const storybookInfo = getStorybookInfo(packageJson);159 const storybookVersion =160 storybookPackages[storybookInfo.frameworkPackage]?.version || storybookInfo.version;161 return {162 ...metadata,163 storybookVersion,164 language,165 storybookPackages,166 framework: {167 name: storybookInfo.framework,168 options: getFrameworkOptions(mainConfig),169 },170 addons,171 hasStorybookEslint,172 };173};174let cachedMetadata: StorybookMetadata;175export const getStorybookMetadata = async (_configDir?: string) => {176 if (cachedMetadata) {177 return cachedMetadata;178 }179 const { packageJson = {} } = readPkgUp.sync({ cwd: process.cwd(), normalize: false }) || {};180 const configDir =181 (_configDir ||182 (getStorybookConfiguration(183 packageJson?.scripts?.storybook || '',184 '-c',185 '--config-dir'186 ) as string)) ??187 '.storybook';188 const mainConfig = loadMainConfig({ configDir });189 cachedMetadata = await computeStorybookMetadata({ mainConfig, packageJson });190 return cachedMetadata;...
hooks.js
Source:hooks.js
1// src/hooks.js2import { parse } from 'cookie';3/**4 * handle is a server middleware that runs every time that we hit a GET request to Sveltekit app5 * @param {*} param object { request, resolve } provided to us by Sveltekit6 * @returns modified request7 * i.e to send cookie data as a session object on server side8 * We store the data from the cookies on the server side so it's faster for the client9 */10/** @type {import('@sveltejs/kit').Handle} */11export async function handle({ event, resolve }) {12 const { request } = event;13 const cookies = parse(request.headers.get('cookie') || '');14 // Since we created cookies using env variable name, we should fetch cookie keys from env variables15 // If client has access token, we modify the request object16 if (cookies[import.meta.env.VITE_ACCESS_TOKEN] && cookies[import.meta.env.VITE_REFRESH_TOKEN]) {17 const access_token = cookies[import.meta.env.VITE_ACCESS_TOKEN];18 const refresh_token = cookies[import.meta.env.VITE_ACCESS_TOKEN];19 if (access_token) {20 event.locals.access_token = access_token;21 event.locals.refresh_token = refresh_token;22 return resolve(event);23 }24 }25 // If client doesn't have access token, we send a null to be checked inside getSession26 event.locals.access_token = null;27 return resolve(event);28}29/**30 * getSession will check for the stored cookies, feed client with object in session31 * @param {*} request from Svelte metaframework32 * @returns session object with/out access token that we have accessible in the client runtime33 */34/** @type {import('@sveltejs/kit').GetSession} */35export function getSession(request) {36 const access_token = request?.locals?.access_token;37 const refresh_token = request?.locals?.refresh_token;38 return access_token && refresh_token ? { access_token, refresh_token } : {};...
Using AI Code Generation
1import { metaFramework } from 'storybook-root';2import { metaFramework } from 'storybook-root';3import { metaFramework } from 'storybook-root';4import { metaFramework } from 'storybook-root';5import { metaFramework } from 'storybook-root';6import { metaFramework } from 'storybook-root';7import { metaFramework } from 'storybook-root';8import { metaFramework } from 'storybook-root';9import { metaFramework } from 'storybook-root';10import { metaFramework } from 'storybook-root';11import { metaFramework } from 'storybook-root';12import { metaFramework } from 'storybook-root';13import { metaFramework } from 'storybook-root';14import { metaFramework } from 'storybook-root';15import { metaFramework } from 'storybook-root';16import { metaFramework } from 'storybook-root';17import { metaFramework } from 'storybook-root';18import { metaFramework } from 'storybook-root';19import { metaFramework } from 'storybook-root';20import { metaFramework } from 'storybook-root';21import { metaFramework } from 'storybook-root';22import { metaFramework } from 'storybook-root';23import { metaFramework } from 'storybook-root';24import { metaFramework } from 'storybook-root';25import { metaFramework } from 'storybook-root';26import { metaFramework } from 'storybook-root';27import { metaFramework } from 'storybook-root';28import { metaFramework } from 'storybook-root';29import { metaFramework } from 'storybook-root';30import { metaFramework } from 'storybook-root';31import { metaFramework } from 'storybook-root';32import { metaFramework } from 'storybook-root
Using AI Code Generation
1import { metaFramework, metaFramework as mf } from 'storybook-root';2import { metaFramework, metaFramework as mf } from 'storybook-root';3import { metaFramework, metaFramework as mf } from 'storybook-root';4import { metaFramework, metaFramework as mf } from 'storybook-root';5import { metaFramework, metaFramework as mf } from 'storybook-root';6import { metaFramework, metaFramework as mf } from 'storybook-root';7import { metaFramework, metaFramework as mf } from 'storybook-root';8import { metaFramework, metaFramework as mf } from 'storybook-root';9import { metaFramework, metaFramework as mf } from 'storybook-root';10import { metaFramework, metaFramework as mf } from 'storybook-root';11import { metaFramework, metaFramework as mf } from 'storybook-root';12import { metaFramework, metaFramework as mf } from 'storybook-root';13import { metaFramework, metaFramework as mf } from 'storybook-root';14import { metaFramework, metaFramework as mf } from 'storybook-root';15import { metaFramework, metaFramework as mf } from 'storybook-root';16import { metaFramework, metaFramework as mf } from 'storybook-root';17import { metaFramework, metaFramework as mf } from 'storybook-root';
Using AI Code Generation
1const metaFramework = require('storybook-root').metaFramework;2const { storiesOf } = metaFramework(require.context('../src', true, /\.stories\.js$/));3const metaFramework = require('storybook-addon-root').metaFramework;4const { storiesOf } = metaFramework(require.context('../src', true, /\.stories\.js$/));5const metaFramework = require('storybook-root').metaFramework;6const { storiesOf } = metaFramework(require.context('../src', true, /\.stories\.js$/));7const metaFramework = require('storybook-addon-root').metaFramework;8const { storiesOf } = metaFramework(require.context('../src', true, /\.stories\.js$/));9const metaFramework = require('storybook-root').metaFramework;10const { storiesOf } = metaFramework(require.context('../src', true, /\.stories\.js$/));11const metaFramework = require('storybook-addon-root').metaFramework;12const { storiesOf } = metaFramework(require.context('../src', true, /\.stories\.js$/));13const metaFramework = require('storybook-root').metaFramework;14const { storiesOf } = metaFramework(require.context('../src', true, /\.stories\.js$/));15const metaFramework = require('storybook-addon-root').metaFramework;16const { storiesOf } = metaFramework(require.context('../src', true, /\.stories\.js$/));17const metaFramework = require('storybook-root').metaFramework;18const { storiesOf } = metaFramework(require.context('../src', true, /\.stories\.js$/));19const metaFramework = require('storybook-addon-root').metaFramework;20const { storiesOf } = metaFramework(require.context('../src', true, /\.stories\.js$/));21const metaFramework = require('storybook-root').metaFramework;22const { storiesOf } = metaFramework(require.context('../src', true,
Using AI Code Generation
1import { metaFramework } from 'storybook-root';2import { storiesOf } from '@storybook/react';3const meta = metaFramework('test');4storiesOf(meta('test'), module).add('test', () => <div>test</div>);5import { metaFramework } from 'storybook-root';6import { storiesOf } from '@storybook/react';7const meta = metaFramework('test2');8storiesOf(meta('test2'), module).add('test2', () => <div>test2</div>);9import { metaFramework } from 'storybook-root';10import { storiesOf } from '@storybook/react';11const meta = metaFramework('test3');12storiesOf(meta('test3'), module).add('test3', () => <div>test3</div>);13import { metaFramework } from 'storybook-root';14import { storiesOf } from '@storybook/react';15const meta = metaFramework('test4');16storiesOf(meta('test4'), module).add('test4', () => <div>test4</div>);17import { metaFramework } from 'storybook-root';18import { storiesOf } from '@storybook/react';19const meta = metaFramework('test5');20storiesOf(meta('test5'), module).add('test5', () => <div>test5</div>);21import { metaFramework } from 'storybook-root';22import { storiesOf } from '@storybook/react';23const meta = metaFramework('test6');24storiesOf(meta('test6'), module).add('test6', () => <div>test6</div>);25import { metaFramework } from 'storybook-root';26import { storiesOf } from '@storybook/react';27const meta = metaFramework('test7');28storiesOf(meta('test7'), module).add('test7', () => <div>test7</div>);
Using AI Code Generation
1import metaFramework from 'storybook-root'2const storybook = {3 storiesOf: jest.fn()4}5const component = {6}7const fixture = {8}9const storybookStory = jest.fn()10const storybookStoryWithMetaFramework = metaFramework({ storybook, component, fixture })(storybookStory)11storybookStoryWithMetaFramework('MyStory', () => 'MyComponent')12expect(storybook.storiesOf).toHaveBeenCalledWith('MyComponent/MyFixture')13expect(storybookStory).toHaveBeenCalledWith('MyStory', expect.any(Function))14MIT © [jameslnewell](
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!!