level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
323
0
petrpan-code/vercel/swr
petrpan-code/vercel/swr/test/use-swr-preload.test.tsx
import { act, fireEvent, screen } from '@testing-library/react' import { Suspense, useEffect, useState, Profiler } from 'react' import useSWR, { preload, useSWRConfig } from 'swr' import { createKey, createResponse, renderWithConfig, sleep } from './utils' describe('useSWR - preload', () => { it('preload the fetcher function', async () => { const key = createKey() const fetcher = jest.fn(() => createResponse('foo')) function Page() { const { data } = useSWR(key, fetcher) return <div>data:{data}</div> } preload(key, fetcher) expect(fetcher).toBeCalledTimes(1) renderWithConfig(<Page />) await screen.findByText('data:foo') expect(fetcher).toBeCalledTimes(1) }) it('should avoid preloading the resource multiple times', async () => { const key = createKey() const fetcher = jest.fn(() => createResponse('foo')) function Page() { const { data } = useSWR(key, fetcher) return <div>data:{data}</div> } preload(key, fetcher) preload(key, fetcher) preload(key, fetcher) expect(fetcher).toBeCalledTimes(1) renderWithConfig(<Page />) await screen.findByText('data:foo') expect(fetcher).toBeCalledTimes(1) }) it('should be able to prealod resources in effects', async () => { const key = createKey() const fetcher = jest.fn(() => createResponse('foo')) function Comp() { const { data } = useSWR(key, fetcher) return <div>data:{data}</div> } function Page() { const [show, setShow] = useState(false) useEffect(() => { preload(key, fetcher) }, []) return show ? ( <Comp /> ) : ( <button onClick={() => setShow(true)}>click</button> ) } renderWithConfig(<Page />) expect(fetcher).toBeCalledTimes(1) fireEvent.click(screen.getByText('click')) await screen.findByText('data:foo') expect(fetcher).toBeCalledTimes(1) }) it('preload the fetcher function with the suspense mode', async () => { const key = createKey() const fetcher = jest.fn(() => createResponse('foo')) const onRender = jest.fn() function Page() { const { data } = useSWR(key, fetcher, { suspense: true }) return <div>data:{data}</div> } preload(key, fetcher) expect(fetcher).toBeCalledTimes(1) renderWithConfig( <Suspense fallback={ <Profiler id={key} onRender={onRender}> loading </Profiler> } > <Page /> </Suspense> ) await screen.findByText('data:foo') expect(onRender).toBeCalledTimes(1) expect(fetcher).toBeCalledTimes(1) }) it('avoid suspense waterfall by prefetching the resources', async () => { const key1 = createKey() const key2 = createKey() const response1 = createResponse('foo', { delay: 50 }) const response2 = createResponse('bar', { delay: 50 }) const fetcher1 = () => response1 const fetcher2 = () => response2 function Page() { const { data: data1 } = useSWR(key1, fetcher1, { suspense: true }) const { data: data2 } = useSWR(key2, fetcher2, { suspense: true }) return ( <div> data:{data1}:{data2} </div> ) } preload(key1, fetcher1) preload(key2, fetcher2) renderWithConfig( <Suspense fallback="loading"> <Page /> </Suspense> ) screen.getByText('loading') // Should avoid waterfall(50ms + 50ms) await act(() => sleep(80)) screen.getByText('data:foo:bar') }) it('reset the preload result when the preload function gets an error', async () => { const key = createKey() let count = 0 const fetcher = () => { ++count const res = count === 1 ? new Error('err') : 'foo' return createResponse(res) } let mutate function Page() { mutate = useSWRConfig().mutate const { data, error } = useSWR<any>(key, fetcher) if (error) { return <div>error:{error.message}</div> } return <div>data:{data}</div> } try { // error await preload(key, fetcher) } catch (e) { // noop } renderWithConfig(<Page />) screen.getByText('data:') // use the preloaded result await screen.findByText('error:err') expect(count).toBe(1) // revalidate await act(() => mutate(key)) // should not use the preload data await screen.findByText('data:foo') }) it('dedupe requests during preloading', async () => { const key = createKey() const fetcher = jest.fn(() => createResponse('foo', { delay: 50 }) ) const onRender = jest.fn() function Page() { const { data } = useSWR(key, fetcher, { dedupingInterval: 0 }) return ( <Profiler id={key} onRender={onRender}> data:{data} </Profiler> ) } preload(key, fetcher) expect(fetcher).toBeCalledTimes(1) const { rerender } = renderWithConfig(<Page />) expect(onRender).toBeCalledTimes(1) // rerender when the preloading is in-flight, and the deduping interval is over await act(() => sleep(10)) rerender(<Page />) expect(onRender).toBeCalledTimes(2) await screen.findByText('data:foo') expect(fetcher).toBeCalledTimes(1) expect(onRender).toBeCalledTimes(3) }) it('should pass serialize key to fetcher', async () => { const key = createKey() let calledWith: string const fetcher = (args: string) => { calledWith = args } preload(() => key, fetcher) expect(calledWith).toBe(key) }) })
324
0
petrpan-code/vercel/swr
petrpan-code/vercel/swr/test/use-swr-reconnect.test.tsx
import { screen, fireEvent, createEvent } from '@testing-library/react' import useSWR from 'swr' import { nextTick as waitForNextTick, renderWithConfig, createKey, mockVisibilityHidden } from './utils' describe('useSWR - reconnect', () => { it('should revalidate on reconnect by default', async () => { let value = 0 const key = createKey() function Page() { const { data } = useSWR(key, () => value++, { dedupingInterval: 0 }) return <div>data: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('data:') // mount await screen.findByText('data: 0') await waitForNextTick() // trigger reconnect fireEvent(window, createEvent('offline', window)) fireEvent(window, createEvent('online', window)) await screen.findByText('data: 1') }) it("shouldn't revalidate on reconnect when revalidateOnReconnect is false", async () => { let value = 0 const key = createKey() function Page() { const { data } = useSWR(key, () => value++, { dedupingInterval: 0, revalidateOnReconnect: false }) return <div>data: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('data:') // mount await screen.findByText('data: 0') await waitForNextTick() // trigger reconnect fireEvent(window, createEvent('offline', window)) fireEvent(window, createEvent('online', window)) // should not be revalidated screen.getByText('data: 0') }) it("shouldn't revalidate on reconnect when isOnline is returning false", async () => { let value = 0 const key = createKey() function Page() { const { data } = useSWR(key, () => value++, { dedupingInterval: 0, isOnline: () => false }) return <div>data: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('data:') // mount await screen.findByText('data: 0') await waitForNextTick() // trigger reconnect fireEvent(window, createEvent('offline', window)) fireEvent(window, createEvent('online', window)) // should not be revalidated screen.getByText('data: 0') }) it("shouldn't revalidate on reconnect if invisible", async () => { let value = 0 const key = createKey() function Page() { const { data } = useSWR(key, () => value++, { dedupingInterval: 0, isOnline: () => false }) return <div>data: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('data:') // mount await screen.findByText('data: 0') await waitForNextTick() const resetVisibility = mockVisibilityHidden() // trigger reconnect fireEvent(window, createEvent('offline', window)) fireEvent(window, createEvent('online', window)) // should not be revalidated screen.getByText('data: 0') resetVisibility() }) })
325
0
petrpan-code/vercel/swr
petrpan-code/vercel/swr/test/use-swr-refresh.test.tsx
import { act, fireEvent, screen } from '@testing-library/react' import React, { useState } from 'react' import useSWR, { SWRConfig, useSWRConfig } from 'swr' import { createKey, renderWithConfig, sleep } from './utils' // This has to be an async function to wait for a microtask to flush updates const advanceTimers = async (ms: number) => jest.advanceTimersByTime(ms) as any // This test heavily depends on setInterval/setTimeout timers, which makes tests slower and flaky. // So we use Jest's fake timers describe('useSWR - refresh', () => { beforeAll(() => { jest.useFakeTimers() }) afterAll(() => { jest.useRealTimers() }) it('should rerender automatically on interval', async () => { let count = 0 const key = createKey() function Page() { const { data } = useSWR(key, () => count++, { refreshInterval: 200, dedupingInterval: 100 }) return <div>count: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('count:') // mount await screen.findByText('count: 0') await act(() => advanceTimers(200)) // update screen.getByText('count: 1') await act(() => advanceTimers(50)) // no update screen.getByText('count: 1') await act(() => advanceTimers(150)) // update screen.getByText('count: 2') }) it('should dedupe requests combined with intervals', async () => { let count = 0 const key = createKey() function Page() { const { data } = useSWR(key, () => count++, { refreshInterval: 100, dedupingInterval: 500 }) return <div>count: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('count:') // mount await screen.findByText('count: 0') await act(() => advanceTimers(100)) // no update (deduped) screen.getByText('count: 0') await act(() => advanceTimers(400)) // reach dudupingInterval await act(() => advanceTimers(100)) // update screen.getByText('count: 1') await act(() => advanceTimers(100)) // no update (deduped) screen.getByText('count: 1') await act(() => advanceTimers(400)) // reach dudupingInterval await act(() => advanceTimers(100)) // update screen.getByText('count: 2') }) it('should update data upon interval changes', async () => { let count = 0 const key = createKey() function Page() { const [int, setInt] = React.useState(100) const { data } = useSWR(key, () => count++, { refreshInterval: int, dedupingInterval: 50 }) return ( <div onClick={() => setInt(num => (num < 200 ? num + 50 : 0))}> count: {data} </div> ) } renderWithConfig(<Page />) screen.getByText('count:') // mount await screen.findByText('count: 0') await act(() => advanceTimers(100)) screen.getByText('count: 1') await act(() => advanceTimers(50)) screen.getByText('count: 1') await act(() => advanceTimers(50)) screen.getByText('count: 2') fireEvent.click(screen.getByText('count: 2')) await act(() => advanceTimers(100)) screen.getByText('count: 2') await act(() => advanceTimers(50)) screen.getByText('count: 3') await act(() => advanceTimers(150)) screen.getByText('count: 4') fireEvent.click(screen.getByText('count: 4')) await act(() => { // it will clear the 150ms timer and set up a new 200ms timer return advanceTimers(150) }) screen.getByText('count: 4') await act(() => advanceTimers(50)) screen.getByText('count: 5') fireEvent.click(screen.getByText('count: 5')) await act(() => { // it will clear the 200ms timer and stop return advanceTimers(50) }) screen.getByText('count: 5') await act(() => advanceTimers(50)) screen.getByText('count: 5') }) it('should update data upon interval changes -- changes happened during revalidate', async () => { let count = 0 const STOP_POLLING_THRESHOLD = 2 const key = createKey() function Page() { const [flag, setFlag] = useState(0) const shouldPoll = flag < STOP_POLLING_THRESHOLD const { data } = useSWR(key, () => count++, { refreshInterval: shouldPoll ? 100 : 0, dedupingInterval: 50, onSuccess() { setFlag(value => value + 1) } }) return ( <div onClick={() => setFlag(0)}> count: {data} {flag} </div> ) } renderWithConfig(<Page />) screen.getByText('count: 0') await screen.findByText('count: 0 1') await act(() => advanceTimers(100)) screen.getByText('count: 1 2') await act(() => advanceTimers(100)) screen.getByText('count: 1 2') await act(() => advanceTimers(100)) screen.getByText('count: 1 2') await act(() => advanceTimers(100)) screen.getByText('count: 1 2') fireEvent.click(screen.getByText('count: 1 2')) await act(() => { // it will set up a new 100ms timer return advanceTimers(50) }) screen.getByText('count: 1 0') await act(() => advanceTimers(50)) screen.getByText('count: 2 1') await act(() => advanceTimers(100)) screen.getByText('count: 3 2') await act(() => advanceTimers(100)) screen.getByText('count: 3 2') await act(() => advanceTimers(100)) screen.getByText('count: 3 2') }) it('should allow use custom compare method', async () => { let count = 0 const key = createKey() const fetcher = jest.fn(() => ({ timestamp: ++count, version: '1.0' })) function Page() { const { data, mutate: change } = useSWR(key, fetcher, { compare: function compare(a, b) { if (a === b) { return true } if (!a || !b) { return false } return a.version === b.version } }) if (!data) { return <div>loading</div> } return <button onClick={() => change()}>{data.timestamp}</button> } let customCache function App() { return ( <SWRConfig value={{ provider: () => { return (customCache = new Map()) } }} > <Page /> </SWRConfig> ) } renderWithConfig(<App />) screen.getByText('loading') await screen.findByText('1') expect(fetcher).toBeCalledTimes(1) expect(fetcher).toReturnWith({ timestamp: 1, version: '1.0' }) fireEvent.click(screen.getByText('1')) await act(() => advanceTimers(1)) expect(fetcher).toBeCalledTimes(2) expect(fetcher).toReturnWith({ timestamp: 2, version: '1.0' }) const cachedData = customCache.get(key)?.data expect(cachedData.timestamp.toString()).toEqual('1') screen.getByText('1') }) it('custom compare should only be used for comparing data', async () => { let count = 0 const key = createKey() const compareParams = [] const fetcher = jest.fn(() => ({ timestamp: ++count, version: '1.0' })) function Page() { const config = useSWRConfig() const { data, mutate: change } = useSWR(key, fetcher, { compare: function (a, b) { compareParams.push([a, b]) return config.compare(a, b) }, dedupingInterval: 0 }) if (!data) { return <div>loading</div> } return ( <> <button onClick={() => change()}>change</button> <div>{data.timestamp}</div> </> ) } renderWithConfig(<Page />) await screen.findByText('1') expect(compareParams).toMatchInlineSnapshot(` [ [ undefined, undefined, ], [ undefined, { "timestamp": 1, "version": "1.0", }, ], [ undefined, { "timestamp": 1, "version": "1.0", }, ], [ undefined, { "timestamp": 1, "version": "1.0", }, ], [ { "timestamp": 1, "version": "1.0", }, undefined, ], [ { "timestamp": 1, "version": "1.0", }, { "timestamp": 1, "version": "1.0", }, ], [ { "timestamp": 1, "version": "1.0", }, { "timestamp": 1, "version": "1.0", }, ], [ { "timestamp": 1, "version": "1.0", }, { "timestamp": 1, "version": "1.0", }, ], ] `) fireEvent.click(screen.getByText('change')) await screen.findByText('2') expect(compareParams).toMatchInlineSnapshot(` [ [ undefined, undefined, ], [ undefined, { "timestamp": 1, "version": "1.0", }, ], [ undefined, { "timestamp": 1, "version": "1.0", }, ], [ undefined, { "timestamp": 1, "version": "1.0", }, ], [ { "timestamp": 1, "version": "1.0", }, undefined, ], [ { "timestamp": 1, "version": "1.0", }, { "timestamp": 1, "version": "1.0", }, ], [ { "timestamp": 1, "version": "1.0", }, { "timestamp": 1, "version": "1.0", }, ], [ { "timestamp": 1, "version": "1.0", }, { "timestamp": 1, "version": "1.0", }, ], [ { "timestamp": 1, "version": "1.0", }, { "timestamp": 1, "version": "1.0", }, ], [ { "timestamp": 1, "version": "1.0", }, { "timestamp": 2, "version": "1.0", }, ], [ { "timestamp": 1, "version": "1.0", }, { "timestamp": 2, "version": "1.0", }, ], [ { "timestamp": 2, "version": "1.0", }, { "timestamp": 1, "version": "1.0", }, ], [ { "timestamp": 2, "version": "1.0", }, { "timestamp": 2, "version": "1.0", }, ], [ { "timestamp": 2, "version": "1.0", }, { "timestamp": 2, "version": "1.0", }, ], [ { "timestamp": 2, "version": "1.0", }, { "timestamp": 2, "version": "1.0", }, ], ] `) }) it('should not let the previous interval timer to set new timer if key changes too fast', async () => { const key = createKey() const fetcherWithToken = jest.fn(async token => { await sleep(200) return token }) function Page() { const [count, setCount] = useState(0) const { data } = useSWR(`${key}-${count}`, fetcherWithToken, { refreshInterval: 100, dedupingInterval: 50 }) return ( <button onClick={() => setCount(count + 1)} >{`click me ${data}`}</button> ) } renderWithConfig(<Page />) // initial revalidate await act(() => advanceTimers(200)) expect(fetcherWithToken).toBeCalledTimes(1) // first refresh await act(() => advanceTimers(100)) expect(fetcherWithToken).toBeCalledTimes(2) expect(fetcherWithToken).toHaveBeenLastCalledWith(`${key}-0`) await act(() => advanceTimers(200)) // second refresh start await act(() => advanceTimers(100)) expect(fetcherWithToken).toBeCalledTimes(3) expect(fetcherWithToken).toHaveBeenLastCalledWith(`${key}-0`) // change the key during revalidation // The second refresh will not start a new timer fireEvent.click(screen.getByText(`click me ${key}-0`)) // first, refresh with new key 1 await act(() => advanceTimers(100)) expect(fetcherWithToken).toBeCalledTimes(4) expect(fetcherWithToken).toHaveBeenLastCalledWith(`${key}-1`) await act(() => advanceTimers(200)) // second refresh with new key 1 await act(() => advanceTimers(100)) expect(fetcherWithToken).toBeCalledTimes(5) expect(fetcherWithToken).toHaveBeenLastCalledWith(`${key}-1`) }) it('should not call onSuccess from the previous interval if key has changed', async () => { const fetcherWithToken = jest.fn(async token => { await sleep(100) return token }) const onSuccess = jest.fn((data, key) => { return `${data} ${key}` }) const key = createKey() function Page() { const [count, setCount] = useState(0) const { data } = useSWR(`${count.toString()}-${key}`, fetcherWithToken, { refreshInterval: 50, dedupingInterval: 25, onSuccess }) return ( <button onClick={() => setCount(count + 1)} >{`click me ${data}`}</button> ) } renderWithConfig(<Page />) // initial revalidate await act(() => advanceTimers(100)) expect(fetcherWithToken).toBeCalledTimes(1) expect(onSuccess).toBeCalledTimes(1) expect(onSuccess).toHaveLastReturnedWith(`0-${key} 0-${key}`) // first refresh await act(() => advanceTimers(50)) expect(fetcherWithToken).toBeCalledTimes(2) expect(fetcherWithToken).toHaveBeenLastCalledWith(`0-${key}`) await act(() => advanceTimers(100)) expect(onSuccess).toBeCalledTimes(2) expect(onSuccess).toHaveLastReturnedWith(`0-${key} 0-${key}`) // second refresh start await act(() => advanceTimers(50)) expect(fetcherWithToken).toBeCalledTimes(3) expect(fetcherWithToken).toHaveBeenLastCalledWith(`0-${key}`) // change the key during revalidation // The second refresh will not start a new timer fireEvent.click(screen.getByText(`click me 0-${key}`)) // first, refresh with new key 1 await act(() => advanceTimers(50)) expect(fetcherWithToken).toBeCalledTimes(4) expect(fetcherWithToken).toHaveBeenLastCalledWith(`1-${key}`) await act(() => advanceTimers(100)) expect(onSuccess).toBeCalledTimes(3) expect(onSuccess).toHaveLastReturnedWith(`1-${key} 1-${key}`) // second refresh with new key 1 await act(() => advanceTimers(50)) expect(fetcherWithToken).toBeCalledTimes(5) expect(fetcherWithToken).toHaveBeenLastCalledWith(`1-${key}`) }) it('should allow using function as an interval', async () => { let count = 0 const key = createKey() function Page() { const { data } = useSWR(key, () => count++, { refreshInterval: () => 200, dedupingInterval: 100 }) return <div>count: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('count:') // mount await screen.findByText('count: 0') await act(() => advanceTimers(200)) // update screen.getByText('count: 1') await act(() => advanceTimers(50)) // no update screen.getByText('count: 1') await act(() => advanceTimers(150)) // update screen.getByText('count: 2') }) it('should pass updated data to refreshInterval', async () => { let count = 1 const key = createKey() function Page() { const { data } = useSWR(key, () => count++, { refreshInterval: updatedCount => updatedCount * 1000, dedupingInterval: 100 }) return <div>count: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('count:') // mount await screen.findByText('count: 1') await act(() => advanceTimers(1000)) // updated after 1s screen.getByText('count: 2') await act(() => advanceTimers(1000)) // no update screen.getByText('count: 2') await act(() => advanceTimers(1000)) // updated after 2s screen.getByText('count: 3') await act(() => advanceTimers(2000)) // no update screen.getByText('count: 3') await act(() => advanceTimers(1000)) // updated after 3s screen.getByText('count: 4') }) it('should pass updated data to refreshInterval, when refreshInterval is constant function', async () => { let count = 1 // constant function const refreshInterval = jest.fn(updatedCount => { return updatedCount > 5 ? 0 : 1000 }) const key = createKey() function Page() { // constant function // const refreshInterval = useCallback((updatedCount) => { // return updatedCount > 5 ? 0 : 1000 // }, []) const { data } = useSWR(key, () => count++, { refreshInterval, dedupingInterval: 100 }) return <div>count: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('count:') // mount await screen.findByText('count: 1') await act(() => advanceTimers(1000)) screen.getByText('count: 2') expect(refreshInterval).toHaveBeenLastCalledWith(2) await act(() => advanceTimers(1000)) screen.getByText('count: 3') expect(refreshInterval).toHaveBeenLastCalledWith(3) await act(() => advanceTimers(1000)) screen.getByText('count: 4') expect(refreshInterval).toHaveBeenLastCalledWith(4) }) it('should disable refresh if function returns 0', async () => { let count = 1 const key = createKey() function Page() { const { data } = useSWR(key, () => count++, { refreshInterval: () => 0, dedupingInterval: 100 }) return <div>count: {data}</div> } renderWithConfig(<Page />) // hydration screen.getByText('count:') // mount await screen.findByText('count: 1') await act(() => advanceTimers(9999)) // no update screen.getByText('count: 1') }) })
326
0
petrpan-code/vercel/swr
petrpan-code/vercel/swr/test/use-swr-remote-mutation.test.tsx
import { act, fireEvent, render, screen } from '@testing-library/react' import React, { useState } from 'react' import useSWR from 'swr' import useSWRMutation from 'swr/mutation' import { createKey, sleep, nextTick } from './utils' const waitForNextTick = () => act(() => sleep(1)) describe('useSWR - remote mutation', () => { it('should return data after triggering', async () => { const key = createKey() function Page() { const { data, trigger } = useSWRMutation(key, () => 'data') return <button onClick={() => trigger()}>{data || 'pending'}</button> } render(<Page />) // mount await screen.findByText('pending') fireEvent.click(screen.getByText('pending')) await waitForNextTick() screen.getByText('data') }) it('should return data from `trigger`', async () => { const key = createKey() function Page() { const [data, setData] = React.useState(null) const { trigger } = useSWRMutation(key, () => 'data') return ( <button onClick={async () => { setData(await trigger()) }} > {data || 'pending'} </button> ) } render(<Page />) // mount await screen.findByText('pending') fireEvent.click(screen.getByText('pending')) await waitForNextTick() screen.getByText('data') }) it('should trigger request with the correct argument signature', async () => { const key = createKey() const fetcher = jest.fn((_, __: { arg: string }) => 'data') function Page() { const { data, trigger } = useSWRMutation([key, 'arg0'], fetcher) return ( <button onClick={() => trigger('arg1')}>{data || 'pending'}</button> ) } render(<Page />) // mount await screen.findByText('pending') expect(fetcher).not.toHaveBeenCalled() fireEvent.click(screen.getByText('pending')) await waitForNextTick() screen.getByText('data') expect(fetcher).toHaveBeenCalled() expect(fetcher.mock.calls.length).toBe(1) expect(fetcher.mock.calls[0]).toEqual([[key, 'arg0'], { arg: 'arg1' }]) }) it('should call `onSuccess` event', async () => { const key = createKey() const onSuccess = jest.fn() function Page() { const { data, trigger } = useSWRMutation(key, () => 'data', { onSuccess }) return <button onClick={() => trigger()}>{data || 'pending'}</button> } render(<Page />) // mount await screen.findByText('pending') fireEvent.click(screen.getByText('pending')) await waitForNextTick() screen.getByText('data') expect(onSuccess).toHaveBeenCalled() }) it('should support configuring `onSuccess` with trigger', async () => { const key = createKey() const onSuccess = jest.fn() function Page() { const { data, trigger } = useSWRMutation(key, () => 'data') return ( <button onClick={() => trigger(null, { onSuccess })}> {data || 'pending'} </button> ) } render(<Page />) // mount await screen.findByText('pending') fireEvent.click(screen.getByText('pending')) await waitForNextTick() screen.getByText('data') expect(onSuccess).toHaveBeenCalled() }) it('should call `onError` event and throw', async () => { const key = createKey() const onError = jest.fn() const onInplaceError = jest.fn() function Page() { const { data, error, trigger } = useSWRMutation( key, async () => { await sleep(10) throw new Error('error!') }, { onError } ) return ( <button onClick={() => trigger().catch(onInplaceError)}> {data || (error ? error.message : 'pending')} </button> ) } render(<Page />) // mount await screen.findByText('pending') fireEvent.click(screen.getByText('pending')) await screen.findByText('error!') expect(onError).toHaveBeenCalled() expect(onInplaceError).toHaveBeenCalled() }) it('should call `onError` event and skip throwing the error when `throwOnError` is disabled', async () => { const key = createKey() const onError = jest.fn() const onInplaceError = jest.fn() function Page() { const { data, error, trigger } = useSWRMutation( key, async () => { await sleep(10) throw new Error('error!') }, { onError, throwOnError: false } ) return ( <button onClick={() => trigger().catch(onInplaceError)}> {data || (error ? error.message : 'pending')} </button> ) } render(<Page />) // mount await screen.findByText('pending') fireEvent.click(screen.getByText('pending')) await screen.findByText('error!') expect(onError).toHaveBeenCalled() expect(onInplaceError).not.toHaveBeenCalled() }) it('should return `isMutating` state correctly', async () => { const key = createKey() function Page() { const { data, trigger, isMutating } = useSWRMutation(key, async () => { await sleep(10) return 'data' }) return ( <button onClick={trigger}> state:{(isMutating ? 'pending' : data) || ''} </button> ) } render(<Page />) // mount await screen.findByText('state:') fireEvent.click(screen.getByText('state:')) await screen.findByText('state:pending') await screen.findByText('state:data') }) it('should send `onError` and `onSuccess` events', async () => { const key = createKey() const onSuccess = jest.fn() const onError = jest.fn() let arg = false function Page() { const { data, error, trigger } = useSWRMutation( key, async (_, { arg: shouldReturnValue }: { arg: boolean }) => { await sleep(10) if (shouldReturnValue) return 'data' throw new Error('error') }, { onSuccess, onError } ) return ( <button onClick={() => trigger(arg).catch(() => {})}> {data || (error ? error.message : 'pending')} </button> ) } render(<Page />) // mount await screen.findByText('pending') fireEvent.click(screen.getByText('pending')) await screen.findByText('error') expect(onError).toHaveBeenCalled() expect(onSuccess).not.toHaveBeenCalled() arg = true fireEvent.click(screen.getByText('error')) await screen.findByText('data') expect(onSuccess).toHaveBeenCalled() }) it('should not dedupe trigger requests', async () => { const key = createKey() const fn = jest.fn() function Page() { const { trigger } = useSWRMutation(key, async () => { fn() await sleep(10) return 'data' }) return <button onClick={trigger}>trigger</button> } render(<Page />) // mount await screen.findByText('trigger') expect(fn).not.toHaveBeenCalled() fireEvent.click(screen.getByText('trigger')) expect(fn).toHaveBeenCalledTimes(1) fireEvent.click(screen.getByText('trigger')) fireEvent.click(screen.getByText('trigger')) fireEvent.click(screen.getByText('trigger')) expect(fn).toHaveBeenCalledTimes(4) }) it('should share the cache with `useSWR` when `populateCache` is enabled', async () => { const key = createKey() function Page() { const { data } = useSWR(key) const { trigger } = useSWRMutation(key, async () => { await sleep(10) return 'data' }) return ( <div> <button onClick={() => trigger(undefined, { populateCache: true })}> trigger </button> <div>data:{data || 'none'}</div> </div> ) } render(<Page />) // mount await screen.findByText('data:none') fireEvent.click(screen.getByText('trigger')) await screen.findByText('data:data') }) it('should not read the cache from `useSWR`', async () => { const key = createKey() function Page() { useSWR(key, () => 'data') const { data } = useSWRMutation(key, () => 'wrong!') return <div>data:{data || 'none'}</div> } render(<Page />) // mount await screen.findByText('data:none') }) it('should be able to populate the cache for `useSWR`', async () => { const key = createKey() function Page() { const { data } = useSWR(key, () => 'data') const { trigger } = useSWRMutation( key, (_, { arg }: { arg: string }) => arg ) return ( <div onClick={() => trigger('updated!', { populateCache: true })}> data:{data || 'none'} </div> ) } render(<Page />) await screen.findByText('data:none') // mount await screen.findByText('data:data') // mutate fireEvent.click(screen.getByText('data:data')) await screen.findByText('data:updated!') }) it('should be able to populate the cache with a transformer', async () => { const key = createKey() function Page() { const { data } = useSWR(key, () => 'data') const { trigger } = useSWRMutation( key, (_, { arg }: { arg: string }) => arg ) return ( <div onClick={() => trigger('updated!', { populateCache: (v, current) => v + ':' + current }) } > data:{data || 'none'} </div> ) } render(<Page />) await screen.findByText('data:none') // mount await screen.findByText('data:data') // mutate fireEvent.click(screen.getByText('data:data')) await screen.findByText('data:updated!:data') }) it('should not trigger request when mutating from shared hooks', async () => { const key = createKey() const fn = jest.fn(() => 'data') function Page() { useSWRMutation(key, fn) const { mutate } = useSWR(key) return ( <div> <button onClick={() => mutate()}>mutate</button> </div> ) } render(<Page />) // mount await screen.findByText('mutate') fireEvent.click(screen.getByText('mutate')) await act(() => sleep(50)) expect(fn).not.toHaveBeenCalled() }) it('should not trigger request when key changes', async () => { const key = createKey() const fn = jest.fn(() => 'data') function Page() { const [k, setK] = React.useState(key) useSWRMutation(k, fn) return ( <div> <button onClick={() => setK(key + '_new')}>update key</button> </div> ) } render(<Page />) // mount await screen.findByText('update key') fireEvent.click(screen.getByText('update key')) await act(() => sleep(50)) expect(fn).not.toHaveBeenCalled() }) it('should prevent race conditions with `useSWR`', async () => { const key = createKey() const logger = jest.fn() function Page() { const { data } = useSWR(key, async () => { await sleep(10) return 'foo' }) const { trigger } = useSWRMutation(key, async () => { await sleep(20) return 'bar' }) logger(data) return ( <div> <button onClick={() => trigger(undefined, { revalidate: false, populateCache: true }) } > trigger </button> <div>data:{data || 'none'}</div> </div> ) } render(<Page />) // mount await screen.findByText('data:none') fireEvent.click(screen.getByText('trigger')) await act(() => sleep(50)) await screen.findByText('data:bar') // It should never render `foo`. expect(logger).not.toHaveBeenCalledWith('foo') }) it('should revalidate after mutating by default', async () => { const key = createKey() const logger = jest.fn() function Page() { const { data } = useSWR( key, async () => { await sleep(10) return 'foo' }, { revalidateOnMount: false } ) const { trigger } = useSWRMutation(key, async () => { await sleep(20) return 'bar' }) logger(data) return ( <div> <button onClick={() => trigger(undefined)}>trigger</button> <div>data:{data || 'none'}</div> </div> ) } render(<Page />) // mount await screen.findByText('data:none') fireEvent.click(screen.getByText('trigger')) await act(() => sleep(50)) // It triggers revalidation await screen.findByText('data:foo') // It should never render `bar` since we never populate the cache. expect(logger).not.toHaveBeenCalledWith('bar') }) it('should revalidate the SWR request that starts during the mutation', async () => { const key = createKey() function Page() { const [triggered, setTriggered] = React.useState(false) const { data } = useSWR( triggered ? key : null, async () => { await sleep(10) return 'foo' }, { revalidateOnMount: false } ) const { trigger } = useSWRMutation(key, async () => { await sleep(20) return 'bar' }) return ( <div> <button onClick={() => { trigger(undefined) setTriggered(true) }} > trigger </button> <div>data:{data || 'none'}</div> </div> ) } render(<Page />) // mount await screen.findByText('data:none') fireEvent.click(screen.getByText('trigger')) await act(() => sleep(50)) // The SWR request that starts during the mutation should be revalidated. await screen.findByText('data:foo') }) it('should revalidate after populating the cache', async () => { const key = createKey() const logger = jest.fn() function Page() { const { data } = useSWR( key, async () => { await sleep(20) return 'foo' }, { revalidateOnMount: false } ) const { trigger } = useSWRMutation(key, async () => { await sleep(20) return 'bar' }) logger(data) return ( <div> <button onClick={() => trigger(undefined, { populateCache: true })}> trigger </button> <div>data:{data || 'none'}</div> </div> ) } render(<Page />) // mount await screen.findByText('data:none') fireEvent.click(screen.getByText('trigger')) // Cache is updated await screen.findByText('data:bar') // A revalidation is triggered await screen.findByText('data:foo') }) it('should be able to turn off auto revalidation', async () => { const key = createKey() const logger = jest.fn() function Page() { const { data } = useSWR( key, async () => { await sleep(10) return 'foo' }, { revalidateOnMount: false } ) const { trigger } = useSWRMutation( key, async () => { await sleep(20) return 'bar' }, { revalidate: false, populateCache: true } ) logger(data) return ( <div> <button onClick={() => trigger(undefined)}>trigger</button> <div>data:{data || 'none'}</div> </div> ) } render(<Page />) // mount await screen.findByText('data:none') fireEvent.click(screen.getByText('trigger')) await act(() => sleep(50)) // It should not trigger revalidation await screen.findByText('data:bar') // It should never render `foo`. expect(logger).not.toHaveBeenCalledWith('foo') }) it('should be able to configure auto revalidation from trigger', async () => { const key = createKey() const logger = jest.fn() function Page() { const { data } = useSWR( key, async () => { await sleep(10) return 'foo' }, { revalidateOnMount: false } ) const { trigger } = useSWRMutation( key, async () => { await sleep(20) return 'bar' }, { populateCache: true } ) logger(data) return ( <div> <button onClick={() => trigger(undefined, { revalidate: false })}> trigger1 </button> <button onClick={() => trigger(undefined, { revalidate: true })}> trigger2 </button> <div>data:{data || 'none'}</div> </div> ) } render(<Page />) // mount await screen.findByText('data:none') fireEvent.click(screen.getByText('trigger1')) await act(() => sleep(50)) // It should not trigger revalidation await screen.findByText('data:bar') // It should never render `foo`. expect(logger).not.toHaveBeenCalledWith('foo') fireEvent.click(screen.getByText('trigger2')) await act(() => sleep(50)) // It should trigger revalidation await screen.findByText('data:foo') }) it('should be able to reset the state', async () => { const key = createKey() function Page() { const { data, trigger, reset } = useSWRMutation(key, async () => { return 'data' }) return ( <div> <button onClick={trigger}>trigger</button> <button onClick={reset}>reset</button> <div>data:{data || 'none'}</div> </div> ) } render(<Page />) // mount await screen.findByText('data:none') fireEvent.click(screen.getByText('trigger')) // Cache is updated await screen.findByText('data:data') // reset fireEvent.click(screen.getByText('reset')) await screen.findByText('data:none') }) it('should prevent race condition if reset the state', async () => { const key = createKey() const onSuccess = jest.fn() function Page() { const { data, trigger, reset } = useSWRMutation(key, async () => { await sleep(10) return 'data' }) return ( <div> <button onClick={() => trigger(undefined, { onSuccess })}> trigger </button> <button onClick={reset}>reset</button> <div>data:{data || 'none'}</div> </div> ) } render(<Page />) // mount await screen.findByText('data:none') // start mutation fireEvent.click(screen.getByText('trigger')) // reset, before it ends fireEvent.click(screen.getByText('reset')) await act(() => sleep(30)) await screen.findByText('data:none') }) it('should prevent race condition if triggered multiple times', async () => { const key = createKey() const logger = [] let id = 0 function Page() { const { data, trigger } = useSWRMutation(key, async () => { await sleep(10) return id++ }) logger.push(data) return <button onClick={trigger}>trigger</button> } render(<Page />) // Mount await screen.findByText('trigger') // Start mutation multiple times, to break the previous one fireEvent.click(screen.getByText('trigger')) // 0 await act(() => sleep(5)) fireEvent.click(screen.getByText('trigger')) // 1 await act(() => sleep(5)) fireEvent.click(screen.getByText('trigger')) // 2 await act(() => sleep(20)) // Shouldn't have intermediate states expect(logger).toEqual([undefined, 2]) }) it('should error if no mutator is given', async () => { const key = createKey() const catchError = jest.fn() function Page() { const { trigger } = useSWRMutation(key, null) return ( <div> <button onClick={() => trigger().catch(catchError)}>trigger</button> </div> ) } render(<Page />) fireEvent.click(screen.getByText('trigger')) await nextTick() expect(catchError).toBeCalled() }) it('should support optimistic updates', async () => { const key = createKey() function Page() { const { data } = useSWR(key, async () => { await sleep(10) return ['foo'] }) const { trigger } = useSWRMutation( key, async (_, { arg }: { arg: string }) => { await sleep(20) return arg.toUpperCase() } ) return ( <div> <button onClick={() => trigger<typeof data>('bar', { optimisticData: current => [...current, 'bar'], populateCache: (added, current) => [...current, added], revalidate: false }) } > trigger </button> <div>data:{JSON.stringify(data)}</div> </div> ) } render(<Page />) // mount await screen.findByText('data:["foo"]') // optimistic update fireEvent.click(screen.getByText('trigger')) await screen.findByText('data:["foo","bar"]') await act(() => sleep(50)) await screen.findByText('data:["foo","BAR"]') // 2nd check fireEvent.click(screen.getByText('trigger')) await screen.findByText('data:["foo","BAR","bar"]') await act(() => sleep(50)) await screen.findByText('data:["foo","BAR","BAR"]') }) it('should clear error after successful trigger', async () => { const key = createKey() let arg = false function Page() { const { error, trigger } = useSWRMutation( key, async (_, { arg: shouldReturnValue }: { arg: boolean }) => { await sleep(10) if (shouldReturnValue) return ['foo'] throw new Error('error') } ) return ( <div> <button onClick={() => trigger(arg).catch(() => {})}>trigger</button> <div>Error: {error ? error.message : 'none'}</div> </div> ) } render(<Page />) fireEvent.click(screen.getByText('trigger')) await screen.findByText('Error: error') arg = true fireEvent.click(screen.getByText('trigger')) await screen.findByText('Error: none') }) it('should always use the latest fetcher', async () => { const key = createKey() function Page() { const [count, setCount] = useState(0) const { data, trigger } = useSWRMutation(key, () => count) return ( <div> <button onClick={() => { setCount(c => c + 1) }} > ++ </button> <button onClick={() => { trigger() }} > trigger </button> <div> data:{data},count:{count} </div> </div> ) } render(<Page />) await screen.findByText('data:,count:0') fireEvent.click(screen.getByText('trigger')) await screen.findByText('data:0,count:0') fireEvent.click(screen.getByText('++')) await screen.findByText('data:0,count:1') fireEvent.click(screen.getByText('trigger')) await screen.findByText('data:1,count:1') }) it('should always use the latest config', async () => { const key = createKey() const logs = [] function Page() { const [count, setCount] = useState(0) const { data, trigger } = useSWRMutation(key, async () => count, { onSuccess() { logs.push(count) } }) return ( <div> <button onClick={() => { setCount(c => c + 1) }} > ++ </button> <button onClick={() => { trigger() }} > trigger </button> <div> data:{data},count:{count} </div> </div> ) } render(<Page />) await screen.findByText('data:,count:0') expect(logs).toEqual([]) fireEvent.click(screen.getByText('trigger')) await screen.findByText('data:0,count:0') expect(logs).toEqual([0]) fireEvent.click(screen.getByText('++')) await screen.findByText('data:0,count:1') expect(logs).toEqual([0]) fireEvent.click(screen.getByText('trigger')) await screen.findByText('data:1,count:1') expect(logs).toEqual([0, 1]) }) })
327
0
petrpan-code/vercel/swr
petrpan-code/vercel/swr/test/use-swr-revalidate.test.tsx
import { act, fireEvent, screen } from '@testing-library/react' import { useState } from 'react' import useSWR, { useSWRConfig } from 'swr' import { createResponse, sleep, nextTick as waitForNextTick, createKey, renderWithConfig, nextTick } from './utils' describe('useSWR - revalidate', () => { it('should rerender after triggering revalidation', async () => { let value = 0 const key = createKey() function Page() { const { data, mutate } = useSWR(key, () => value++) return <button onClick={() => mutate()}>data: {data}</button> } renderWithConfig(<Page />) // hydration screen.getByText('data:') // mount await screen.findByText('data: 0') fireEvent.click(screen.getByText('data: 0')) await waitForNextTick() screen.getByText('data: 1') }) it('should revalidate all the hooks with the same key', async () => { let value = 0 const key = createKey() function Page() { const { data: v1, mutate } = useSWR(key, () => value++) const { data: v2 } = useSWR(key, () => value++) return ( <button onClick={() => mutate()}> {v1}, {v2} </button> ) } renderWithConfig(<Page />) // hydration screen.getByText(',') // mount await screen.findByText('0, 0') fireEvent.click(screen.getByText('0, 0')) await waitForNextTick() screen.getByText('1, 1') }) it('should respect sequences of revalidation calls (cope with race condition)', async () => { let faster = false const key = createKey() function Page() { const { data, mutate } = useSWR(key, () => createResponse(faster ? 1 : 0, { delay: faster ? 50 : 100 }) ) return <button onClick={() => mutate()}>data: {data}</button> } renderWithConfig(<Page />) // hydration screen.getByText('data:') // trigger the slower revalidation faster = false fireEvent.click(screen.getByText('data:')) await waitForNextTick() // trigger the faster revalidation faster = true fireEvent.click(screen.getByText('data:')) await act(() => sleep(150)) screen.getByText('data: 1') }) it('should keep isValidating be true when there are two concurrent requests', async () => { const key = createKey() function Page() { const { isValidating, mutate } = useSWR( key, () => createResponse(null, { delay: 100 }), { revalidateOnMount: false } ) return ( <button onClick={() => mutate()}> {isValidating ? 'true' : 'false'} </button> ) } renderWithConfig(<Page />) screen.getByText('false') // trigger the first revalidation fireEvent.click(screen.getByText('false')) await act(() => sleep(50)) screen.getByText('true') fireEvent.click(screen.getByText('true')) await act(() => sleep(70)) // the first revalidation is over, the second revalidation is still in progress screen.getByText('true') await act(() => sleep(70)) screen.getByText('false') }) it('should respect sequences of revalidation calls although in dedupingInterval', async () => { let count = 0 const key = createKey() function Page() { const { data, mutate } = useSWR( key, () => { const currCount = ++count return createResponse(currCount, { delay: currCount === 1 ? 50 : 0 }) }, { dedupingInterval: 30 } ) return <div onClick={() => mutate()}>count: {data}</div> } renderWithConfig(<Page />) await waitForNextTick() fireEvent.click(screen.getByText('count:')) await act(() => sleep(70)) screen.getByText('count: 2') }) it('should set initial isValidating be false when config.isPaused returns true', async () => { function Page() { const { isValidating } = useSWR( 'set isValidating for config.isPaused', () => '123', { isPaused: () => true } ) return <div>{isValidating ? 'true' : 'false'}</div> } renderWithConfig(<Page />) screen.getByText('false') }) it('should mark the key as invalidated and clear deduping with `mutate`, even if there is no mounted hook', async () => { const key = createKey() let cnt = 0 function Foo() { const { data } = useSWR(key, () => 'data: ' + cnt++, { dedupingInterval: 1000 }) return <>{data}</> } function Page() { const [showFoo, setShowFoo] = useState(true) const { mutate } = useSWRConfig() return ( <> {showFoo ? <Foo /> : null} <button onClick={() => setShowFoo(!showFoo)}>toggle</button> <button onClick={() => mutate(key)}>mutate</button> </> ) } renderWithConfig(<Page />) await nextTick() screen.getByText('data: 0') fireEvent.click(screen.getByText('toggle')) await nextTick() fireEvent.click(screen.getByText('mutate')) await nextTick() fireEvent.click(screen.getByText('toggle')) await act(() => sleep(20)) screen.getByText('data: 1') }) })
328
0
petrpan-code/vercel/swr
petrpan-code/vercel/swr/test/use-swr-streaming-ssr.test.tsx
import { act } from '@testing-library/react' import { Suspense } from 'react' import useSWR from 'swr' import { createKey, createResponse, renderWithConfig, hydrateWithConfig, mockConsoleForHydrationErrors, sleep } from './utils' describe('useSWR - streaming', () => { afterEach(() => { jest.clearAllMocks() jest.restoreAllMocks() }) it('should match ssr result when hydrating', async () => { const ensureAndUnmock = mockConsoleForHydrationErrors() const key = createKey() // A block fetches the data and updates the cache. function Block() { const { data } = useSWR(key, () => createResponse('SWR', { delay: 10 })) return <div>{data || 'undefined'}</div> } const container = document.createElement('div') container.innerHTML = '<div>undefined</div>' await hydrateWithConfig(<Block />, container) ensureAndUnmock() }) // NOTE: this test is failing because it's not possible to test this behavior // in JSDOM. We need to test this in a real browser. it.failing( 'should match the ssr result when streaming and partially hydrating', async () => { const key = createKey() const dataDuringHydration = {} // A block fetches the data and updates the cache. function Block({ suspense, delay, id }) { const { data } = useSWR(key, () => createResponse('SWR', { delay }), { suspense }) // The first render is always hydration in our case. if (!dataDuringHydration[id]) { dataDuringHydration[id] = data || 'undefined' } return <div>{data || 'undefined'}</div> } // In this example, a will be hydrated first and b will still be streamed. // When a is hydrated, it will update the client cache to SWR, and when // b is being hydrated, it should NOT read that cache. renderWithConfig( <> <Block id="a" suspense={false} delay={10} /> <Suspense fallback={null}> <Block id="b" suspense={true} delay={20} /> </Suspense> </> ) // The SSR result will always be 2 undefined values because data fetching won't // happen on the server: // <div>undefined</div> // <div>undefined</div> // Wait for streaming to finish. await act(() => sleep(50)) expect(dataDuringHydration).toEqual({ a: 'undefined', b: 'undefined' }) } ) })
329
0
petrpan-code/vercel/swr
petrpan-code/vercel/swr/test/use-swr-subscription.test.tsx
import { act, fireEvent, screen } from '@testing-library/react' import { sleep, renderWithConfig, createKey } from './utils' import useSWRSubscription from 'swr/subscription' import useSWR from 'swr' import { useEffect, useState } from 'react' describe('useSWRSubscription', () => { it('should update the state', async () => { const swrKey = createKey() let intervalId let res = 0 function subscribe(key, { next }) { intervalId = setInterval(() => { if (res === 3) { const err = new Error(key) next(err) } else { next(undefined, key + res) } res++ }, 100) return () => {} } function Page() { const { data, error } = useSWRSubscription(swrKey, subscribe, { fallbackData: 'fallback' }) return ( <> <div data-testid="data">{'data:' + data}</div> <div data-testid="error"> {'error:' + (error ? error.message : '')} </div> </> ) } renderWithConfig(<Page />) await act(() => sleep(10)) screen.getByText(`data:fallback`) screen.getByText('error:') await act(() => sleep(100)) screen.getByText(`data:${swrKey}0`) screen.getByText('error:') await act(() => sleep(100)) screen.getByText(`data:${swrKey}1`) screen.getByText('error:') await act(() => sleep(100)) screen.getByText(`data:${swrKey}2`) screen.getByText('error:') await act(() => sleep(100)) // error occurred, error arrives instead of data 3 screen.getByText(`data:${swrKey}2`) screen.getByText(`error:${swrKey}`) await act(() => sleep(100)) screen.getByText(`data:${swrKey}4`) screen.getByText('error:') clearInterval(intervalId) await sleep(100) screen.getByText(`error:`) }) it('should pass the origin keys', async () => { const swrKey = createKey() let intervalId let res = 0 function subscribe(key, { next }) { intervalId = setInterval(() => { if (res === 3) { const err = new Error(key) next(err) } else { next(undefined, key[0] + res) } res++ }, 100) return () => {} } function Page() { const { data, error } = useSWRSubscription(() => [swrKey], subscribe, { fallbackData: 'fallback' }) return ( <> <div data-testid="data">{'data:' + data}</div> <div data-testid="error"> {'error:' + (error ? error.message : '')} </div> </> ) } renderWithConfig(<Page />) await act(() => sleep(10)) screen.getByText(`data:fallback`) screen.getByText('error:') await act(() => sleep(100)) screen.getByText(`data:${swrKey}0`) screen.getByText('error:') await act(() => sleep(100)) screen.getByText(`data:${swrKey}1`) screen.getByText('error:') await act(() => sleep(100)) screen.getByText(`data:${swrKey}2`) screen.getByText('error:') await act(() => sleep(100)) // error occurred, error arrives instead of data 3 screen.getByText(`data:${swrKey}2`) screen.getByText(`error:${swrKey}`) await act(() => sleep(100)) screen.getByText(`data:${swrKey}4`) screen.getByText('error:') clearInterval(intervalId) await sleep(100) screen.getByText(`error:`) }) it('should deduplicate subscriptions', async () => { const swrKey = createKey() let subscriptionCount = 0 function subscribe(key, { next }) { ++subscriptionCount let res = 0 const intervalId = setInterval(() => { if (res === 3) { const err = new Error(key + 'error') next(err) } else { next(undefined, key + res) } res++ }, 100) return () => { clearInterval(intervalId) } } function Page() { const { data, error } = useSWRSubscription(swrKey, subscribe, { fallbackData: 'fallback' }) useSWRSubscription(swrKey, subscribe) useSWRSubscription(swrKey, subscribe) return <div>{error ? error.message : data}</div> } renderWithConfig(<Page />) await act(() => sleep(10)) screen.getByText(`fallback`) await act(() => sleep(100)) screen.getByText(`${swrKey}0`) await act(() => sleep(100)) screen.getByText(`${swrKey}1`) await act(() => sleep(100)) screen.getByText(`${swrKey}2`) expect(subscriptionCount).toBe(1) }) it('should not conflict with useSWR state', async () => { const swrKey = createKey() function subscribe(key, { next }) { let res = 0 const intervalId = setInterval(() => { if (res === 3) { const err = new Error(key + 'error') next(err) } else { next(undefined, key + res) } res++ }, 100) return () => { clearInterval(intervalId) } } function Page() { const { data, error } = useSWRSubscription(swrKey, subscribe, { fallbackData: 'fallback' }) const { data: swrData } = useSWR(swrKey, () => 'swr') return ( <div> {swrData}:{error ? error.message : data} </div> ) } renderWithConfig(<Page />) await act(() => sleep(10)) screen.getByText(`swr:fallback`) await act(() => sleep(100)) screen.getByText(`swr:${swrKey}0`) await act(() => sleep(100)) screen.getByText(`swr:${swrKey}1`) await act(() => sleep(100)) screen.getByText(`swr:${swrKey}2`) }) it('should support singleton subscription', async () => { const placeholderFn: (data: number) => void = () => {} let callback: (data: number) => void = placeholderFn const sub = (fn: (data: number) => void) => { callback = fn return () => { callback = placeholderFn } } const emit = (data: number) => { callback(data) } const useSubData = (key: number) => useSWRSubscription(key.toString(), (_, { next }) => sub(data => next(null, data + key)) ) const App = () => { const [key, setKey] = useState(0) const { data } = useSubData(key) useEffect(() => { callback(1) }, []) return ( <div className="App"> <p>key: {key}</p> <p className="read-the-docs">data: {data}</p> <button onClick={() => { setKey(value => value + 1) setTimeout(() => { emit(2) }, 100) }} > add </button> </div> ) } renderWithConfig(<App />) await screen.findByText(`key: 0`) await screen.findByText(`data: 1`) fireEvent.click(screen.getByText('add')) await act(() => sleep(100)) await screen.findByText(`key: 1`) await screen.findByText(`data: 3`) }) })
330
0
petrpan-code/vercel/swr
petrpan-code/vercel/swr/test/use-swr-suspense.test.tsx
import { act, fireEvent, screen } from '@testing-library/react' import { Profiler } from 'react' import { Suspense, useReducer, useState } from 'react' import useSWR, { mutate } from 'swr' import { createKey, createResponse, renderWithConfig, renderWithGlobalCache, sleep } from './utils' import { ErrorBoundary } from 'react-error-boundary' describe('useSWR - suspense', () => { afterEach(() => { jest.clearAllMocks() jest.restoreAllMocks() }) it('should render fallback', async () => { const key = createKey() function Section() { const { data } = useSWR(key, () => createResponse('SWR'), { suspense: true }) return <div>{data}</div> } renderWithConfig( <Suspense fallback={<div>fallback</div>}> <Section /> </Suspense> ) // hydration screen.getByText('fallback') await screen.findByText('SWR') }) it('should render multiple SWR fallbacks', async () => { const key = createKey() function Section() { const { data: v1 } = useSWR<number>( key, () => createResponse(1, { delay: 50 }), { suspense: true } ) const { data: v2 } = useSWR<number>( 'suspense-3', () => createResponse(2, { delay: 50 }), { suspense: true } ) return <div>{v1 + v2}</div> } renderWithConfig( <Suspense fallback={<div>fallback</div>}> <Section /> </Suspense> ) // hydration screen.getByText('fallback') await act(() => sleep(70)) screen.getByText('fallback') await act(() => sleep(70)) screen.getByText('3') }) it('should work for non-promises', async () => { const key = createKey() function Section() { const { data } = useSWR(key, () => 'hello', { suspense: true }) return <div>{data}</div> } renderWithConfig( <Suspense fallback={<div>fallback</div>}> <Section /> </Suspense> ) await screen.findByText('hello') }) it('should throw errors', async () => { // eslint-disable-next-line @typescript-eslint/no-empty-function jest.spyOn(console, 'error').mockImplementation(() => {}) const key = createKey() function Section() { const { data } = useSWR<any>( key, () => createResponse(new Error('error')), { suspense: true } ) return <div>{data}</div> } // https://reactjs.org/docs/concurrent-mode-suspense.html#handling-errors renderWithConfig( <ErrorBoundary fallback={<div>error boundary</div>}> <Suspense fallback={<div>fallback</div>}> <Section /> </Suspense> </ErrorBoundary> ) // hydration screen.getByText('fallback') await screen.findByText('error boundary') // 1 for js-dom 1 for react-error-boundary expect(console.error).toHaveBeenCalledTimes(3) }) it('should render cached data with error', async () => { const key = createKey() mutate(key, 'hello') function Section() { const { data, error } = useSWR( // this value is cached key, () => createResponse(new Error('error')), { suspense: true } ) return ( <div> {data}, {error ? error.message : null} </div> ) } renderWithGlobalCache( <Suspense fallback={<div>fallback</div>}> <Section /> </Suspense> ) screen.getByText('hello,') // directly from cache await screen.findByText('hello, error') // get the error with cache }) it('should not fetch when cached data is present and `revalidateIfStale` is false', async () => { const key = createKey() mutate(key, 'cached') let fetchCount = 0 function Section() { const { data } = useSWR(key, () => createResponse(++fetchCount), { suspense: true, revalidateIfStale: false }) return <div>{data}</div> } renderWithGlobalCache( <Suspense fallback={<div>fallback</div>}> <Section /> </Suspense> ) screen.getByText('cached') await act(() => sleep(50)) // Wait to confirm fetch is not triggered expect(fetchCount).toBe(0) }) it('should pause when key changes', async () => { // fixes https://github.com/vercel/swr/issues/57 // initialKey' -> undefined -> updatedKey const initialKey = createKey() const updatedKey = createKey() const onRender = jest.fn() function Section() { const [key, setKey] = useState(initialKey) const { data } = useSWR(key, k => createResponse(k), { suspense: true }) return ( <> <div>data: {data}</div> <button onClick={() => setKey(updatedKey)}>change</button> </> ) } renderWithConfig( <Suspense fallback={ <Profiler id={initialKey} onRender={onRender}> <div>fallback</div> </Profiler> } > <Section /> </Suspense> ) await screen.findByText('fallback') await screen.findByText(`data: ${initialKey}`) fireEvent.click(screen.getByText('change')) await screen.findByText('fallback') await screen.findByText(`data: ${updatedKey}`) expect(onRender).toHaveBeenCalledTimes(2) }) it('should render correctly when key changes (but with same response data)', async () => { // https://github.com/vercel/swr/issues/1056 const renderedResults = [] const baseKey = createKey() function Section() { const [key, setKey] = useState(1) const { data } = useSWR( `${baseKey}-${key}`, () => createResponse('123'), { suspense: true } ) if (`${data},${key}` !== renderedResults[renderedResults.length - 1]) { renderedResults.push(`${data},${key}`) } return <div onClick={() => setKey(v => v + 1)}>{`${data},${key}`}</div> } renderWithConfig( <Suspense fallback={<div>fallback</div>}> <Section /> </Suspense> ) await screen.findByText('123,1') fireEvent.click(screen.getByText('123,1')) await screen.findByText('123,2') expect(renderedResults).toEqual(['123,1', '123,2']) }) it('should render correctly when key changes (from null to valid key)', async () => { // https://github.com/vercel/swr/issues/1836 const renderedResults = [] const baseKey = createKey() let setData: any = () => {} const Result = ({ query }: { query: string }) => { const { data } = useSWR( query ? `${baseKey}-${query}` : null, key => createResponse(key, { delay: 200 }), { suspense: true } ) if (`${data}` !== renderedResults[renderedResults.length - 1]) { if (data === undefined) { renderedResults.push(`${baseKey}-nodata`) } else { renderedResults.push(`${data}`) } } return <div>{data ? data : `${baseKey}-nodata`}</div> } const App = () => { const [query, setQuery] = useState('123') if (setData !== setQuery) { setData = setQuery } return ( <> <br /> <br /> <Suspense fallback={null}> <Result query={query}></Result> </Suspense> </> ) } renderWithConfig(<App />) await screen.findByText(`${baseKey}-123`) act(() => setData('')) await screen.findByText(`${baseKey}-nodata`) act(() => setData('456')) await screen.findByText(`${baseKey}-456`) expect(renderedResults).toEqual([ `${baseKey}-123`, `${baseKey}-nodata`, `${baseKey}-456` ]) }) it('should render initial data if set', async () => { const fetcher = jest.fn(() => 'SWR') const key = createKey() function Page() { const { data } = useSWR(key, fetcher, { fallbackData: 'Initial', suspense: true }) return <div>hello, {data}</div> } renderWithConfig( <Suspense fallback={<div>fallback</div>}> <Page /> </Suspense> ) expect(fetcher).not.toBeCalled() screen.getByText('hello, Initial') }) it('should avoid unnecessary re-renders', async () => { let renderCount = 0 let startRenderCount = 0 const key = createKey() function Section() { ++startRenderCount const { data } = useSWR(key, () => createResponse('SWR'), { suspense: true }) ++renderCount return <div>{data}</div> } renderWithConfig( <Suspense fallback={<div>fallback</div>}> <Section /> </Suspense> ) // hydration screen.getByText('fallback') await screen.findByText('SWR') await act(() => sleep(50)) // wait a moment to observe unnecessary renders expect(startRenderCount).toBe(2) // fallback + data expect(renderCount).toBe(1) // data }) it('should return `undefined` data for falsy key', async () => { const key = createKey() const Section = ({ trigger }: { trigger: boolean }) => { const { data } = useSWR( trigger ? key : null, () => createResponse('SWR'), { suspense: true } ) return <div>{data || 'empty'}</div> } const App = () => { const [trigger, toggle] = useReducer(x => !x, false) return ( <div> <button onClick={toggle}>toggle</button> <Suspense fallback={<div>fallback</div>}> <Section trigger={trigger} /> </Suspense> </div> ) } renderWithConfig(<App />) await screen.findByText('empty') fireEvent.click(screen.getByRole('button')) screen.getByText('fallback') await screen.findByText('SWR') }) it('should only render fallback once when `keepPreviousData` is set to true', async () => { const originKey = createKey() const newKey = createKey() const onRender = jest.fn() const Result = ({ query }: { query: string }) => { const { data } = useSWR(query, q => createResponse(q, { delay: 200 }), { suspense: true, keepPreviousData: true }) return <div>data: {data}</div> } const App = () => { const [query, setQuery] = useState(originKey) return ( <> <button onClick={() => setQuery(newKey)}>change</button> <br /> <Suspense fallback={ <Profiler id={originKey} onRender={onRender}> <div>loading</div> </Profiler> } > <Result query={query}></Result> </Suspense> </> ) } renderWithConfig(<App />) await act(() => sleep(200)) await screen.findByText(`data: ${originKey}`) fireEvent.click(screen.getByText('change')) await act(() => sleep(200)) await screen.findByText(`data: ${newKey}`) expect(onRender).toHaveBeenCalledTimes(1) }) })
345
0
petrpan-code/vercel/swr/test
petrpan-code/vercel/swr/test/unit/serialize.test.ts
import { unstable_serialize } from 'swr' import { stableHash } from 'swr/_internal' describe('SWR - unstable_serialize', () => { it('should serialize arguments correctly', async () => { expect(unstable_serialize([])).toBe('') expect(unstable_serialize(null)).toBe('') expect(unstable_serialize('key')).toBe('key') expect(unstable_serialize([1, { foo: 2, bar: 1 }, ['a', 'b', 'c']])).toBe( stableHash([1, { foo: 2, bar: 1 }, ['a', 'b', 'c']]) ) }) })
346
0
petrpan-code/vercel/swr/test
petrpan-code/vercel/swr/test/unit/utils.test.tsx
import { stableHash as hash, serialize, normalize, mergeConfigs } from 'swr/_internal' describe('Utils', () => { it('should normalize arguments correctly', async () => { const fetcher = () => {} const opts = { revalidateOnFocus: false } // Only the `key` argument is passed expect(normalize(['key'])).toEqual(['key', null, {}]) // `key` and `null` as fetcher (no fetcher) expect(normalize(['key', null])).toEqual(['key', null, {}]) // `key` and `fetcher` expect(normalize(['key', fetcher])).toEqual(['key', fetcher, {}]) // `key` and `options` expect(normalize(['key', opts])).toEqual(['key', null, opts]) // `key`, `null` as fetcher, and `options` expect(normalize(['key', null, opts])).toEqual(['key', null, opts]) // `key`, `fetcher`, and `options` expect(normalize(['key', fetcher, opts])).toEqual(['key', fetcher, opts]) }) it('should hash arguments correctly', async () => { // Empty expect(serialize([])[0]).toEqual('') // Primitives expect(hash(['key'])).toEqual('@"key",') expect(hash([1])).toEqual('@1,') expect(hash(['false'])).toEqual('@"false",') expect(hash([false])).toEqual('@false,') expect(hash([true])).toEqual('@true,') expect(hash([null])).toEqual('@null,') expect(hash(['null'])).toEqual('@"null",') expect(hash([undefined])).toEqual('@undefined,') expect(hash([NaN])).toEqual('@NaN,') expect(hash([Infinity])).toEqual('@Infinity,') expect(hash([''])).toEqual('@"",') // Encodes `"` expect(hash(['","', 1])).not.toEqual(hash(['', '', 1])) // BigInt expect(hash([BigInt(1)])).toEqual('@1,') // Date const date = new Date() expect(hash([date])).toEqual(`@${date.toJSON()},`) expect(hash([new Date(1234)])).toEqual(hash([new Date(1234)])) // Regex expect(hash([/regex/])).toEqual('@/regex/,') // Symbol expect(hash([Symbol('key')])).toMatch('@Symbol(key),') const symbol = Symbol('foo') expect(hash([symbol])).toMatch(hash([symbol])) // Due to serialization, those three are equivalent expect(hash([Symbol.for('key')])).toMatch(hash([Symbol.for('key')])) expect(hash([Symbol('key')])).toMatch(hash([Symbol('key')])) expect(hash([Symbol('key')])).toMatch(hash([Symbol.for('key')])) // Set, Map, Buffer... const set = new Set() expect(hash([set])).not.toMatch(hash([new Set()])) expect(hash([set])).toMatch(hash([set])) const map = new Map() expect(hash([map])).not.toMatch(hash([new Map()])) expect(hash([map])).toMatch(hash([map])) const buffer = new ArrayBuffer(0) expect(hash([buffer])).not.toMatch(hash([new ArrayBuffer(0)])) expect(hash([buffer])).toMatch(hash([buffer])) // Serializable objects expect(hash([{ x: 1 }])).toEqual('@#x:1,,') expect(hash([{ '': 1 }])).toEqual('@#:1,,') expect(hash([{ x: { y: 2 } }])).toEqual('@#x:#y:2,,,') expect(hash([[]])).toEqual('@@,') expect(hash([[[]]])).not.toMatch(hash([[], []])) // Circular const o: any = {} o.o = o expect(hash([o])).toEqual(hash([o])) expect(hash([o])).not.toEqual(hash([{}])) const a: any = [] a.push(a) expect(hash([a])).toEqual(hash([a])) expect(hash([a])).not.toEqual(hash([[]])) const o2: any = {} const a2: any = [o2] o2.a = a2 expect(hash([o2])).toEqual(hash([o2])) // Unserializable objects expect(hash([() => {}])).toMatch(/@\d+~,/) expect(hash([class {}])).toMatch(/@\d+~,/) }) it('should always generate the same and stable hash', async () => { // Multiple arguments expect(hash([() => {}, 1, 'key', null, { x: 1 }])).toMatch( /@\d+~,1,"key",null,#x:1,,/ ) // Stable hash expect(hash([{ x: 1, y: 2, z: undefined }])).toMatch( hash([{ z: undefined, y: 2, x: 1 }]) ) expect(hash([{ x: 1, y: { a: 1, b: 2 }, z: undefined }])).toMatch( hash([{ y: { b: 2, a: 1 }, x: 1 }]) ) // Same hash of the same reference const f = () => {} expect(hash([f])).toEqual(hash([f])) expect(hash([() => {}])).not.toEqual(hash([() => {}])) }) it('should correctly merge configs', async () => { const a: any = { a: 1 }, b: any = { b: 1 } // Should merge middleware expect(mergeConfigs({ use: [a] }, { use: [b] })).toEqual({ use: [a, b] }) // Should merge fallback expect(mergeConfigs({ fallback: a }, { fallback: b })).toEqual({ fallback: { a: 1, b: 1 } }) }) })
347
0
petrpan-code/vercel/swr/test
petrpan-code/vercel/swr/test/unit/web-preset.test.ts
import { EventEmitter } from 'events' const FOCUS_EVENT = 'focus' const VISIBILITYCHANGE_EVENT = 'visibilitychange' function createEventTarget() { EventEmitter.prototype['addEventListener'] = EventEmitter.prototype.on EventEmitter.prototype['removeEventListener'] = EventEmitter.prototype.off const target = new EventEmitter() return target } function runTests(propertyName) { let initFocus const eventName = propertyName === 'window' ? FOCUS_EVENT : VISIBILITYCHANGE_EVENT describe(`Web Preset ${propertyName}`, () => { const globalSpy = { window: undefined, document: undefined } beforeEach(() => { globalSpy.window = jest.spyOn(global, 'window', 'get') globalSpy.document = jest.spyOn(global, 'document', 'get') jest.resetModules() }) afterEach(() => { globalSpy.window.mockClear() globalSpy.document.mockClear() }) it(`should trigger listener when ${propertyName} has browser APIs`, async () => { const target = createEventTarget() if (propertyName === 'window') { globalSpy.window.mockImplementation(() => target) globalSpy.document.mockImplementation(() => undefined) } else if (propertyName === 'document') { globalSpy.window.mockImplementation(() => undefined) globalSpy.document.mockImplementation(() => target) } initFocus = require('swr/_internal').defaultConfigOptions.initFocus const fn = jest.fn() const release = initFocus(fn) as () => void target.emit(eventName) expect(fn).toBeCalledTimes(1) release() target.emit(eventName) expect(fn).toBeCalledTimes(1) }) it(`should not trigger listener when ${propertyName} is falsy`, async () => { if (propertyName === 'window') { // window exists but without event APIs globalSpy.window.mockImplementation(() => ({ emit: createEventTarget().emit })) globalSpy.document.mockImplementation(() => undefined) } else if (propertyName === 'document') { globalSpy.window.mockImplementation(() => undefined) globalSpy.document.mockImplementation(() => undefined) } initFocus = require('swr/_internal').defaultConfigOptions.initFocus const fn = jest.fn() const release = initFocus(fn) as () => void const target = global[propertyName] target?.emit?.(eventName) expect(fn).toBeCalledTimes(0) release() if (target && target.emit) { target.emit(eventName) } expect(fn).toBeCalledTimes(0) }) }) } runTests('window') runTests('document')
651
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/prompts/huggingface.test.ts
import { experimental_buildOpenAssistantPrompt, experimental_buildStarChatBetaPrompt, experimental_buildLlama2Prompt, } from './huggingface'; import type { Message } from '../shared/types'; describe('buildStarChatBetaPrompt', () => { it('should return a string with user, assistant, and system messages', () => { const messages: Pick<Message, 'content' | 'role'>[] = [ { content: 'You are a chat bot.', role: 'system' }, { content: 'Hello!', role: 'user' }, { content: 'Hi there!', role: 'assistant' }, ]; const expectedPrompt = `<|system|>\nYou are a chat bot.<|end|>\n<|user|>\nHello!<|end|>\n<|assistant|>\nHi there!<|end|>\n<|assistant|>`; const prompt = experimental_buildStarChatBetaPrompt(messages); expect(prompt).toEqual(expectedPrompt); }); it('should throw an error if a function message is included', () => { const messages: Pick<Message, 'content' | 'role'>[] = [ { content: 'someFunction()', role: 'function' }, ]; expect(() => experimental_buildStarChatBetaPrompt(messages)).toThrow(); }); }); describe('buildOpenAssistantPrompt', () => { it('should return a string with user and assistant messages', () => { const messages: Pick<Message, 'content' | 'role'>[] = [ { content: 'Hello!', role: 'user' }, { content: 'Hi there!', role: 'assistant' }, ]; const expectedPrompt = '<|prompter|>Hello!<|endoftext|><|assistant|>Hi there!<|endoftext|><|assistant|>'; const prompt = experimental_buildOpenAssistantPrompt(messages); expect(prompt).toEqual(expectedPrompt); }); it('should throw an error if a function message is included', () => { const messages: Pick<Message, 'content' | 'role'>[] = [ { content: 'someFunction()', role: 'function' }, ]; expect(() => experimental_buildOpenAssistantPrompt(messages)).toThrow(); }); }); describe('buildLlamaPrompt', () => { it('should return a string with user instruction', () => { const messages: Pick<Message, 'content' | 'role'>[] = [ { content: 'Hello, how are you?', role: 'user' }, ]; const expectedPrompt = '<s>[INST] Hello, how are you? [/INST]'; const prompt = experimental_buildLlama2Prompt(messages); expect(prompt).toEqual(expectedPrompt); }); it('should return a string with system, user and assistant messages', () => { const messages: Pick<Message, 'content' | 'role'>[] = [ { content: 'You are helpful assistant, but you are drunk, hick', role: 'system', }, { content: 'Hi there!', role: 'user' }, { content: 'Sup, partner!', role: 'assistant' }, { content: 'What are you doing?', role: 'user' }, ]; const expectedPrompt = '<s>[INST] <<SYS>>\nYou are helpful assistant, but you are drunk, hick\n<</SYS>>\n\nHi there! [/INST] Sup, partner!</s><s>[INST] What are you doing? [/INST]'; const prompt = experimental_buildLlama2Prompt(messages); expect(prompt).toEqual(expectedPrompt); }); it('should throw an error if a function message is included', () => { const messages: Pick<Message, 'content' | 'role'>[] = [ { content: 'someFunction()', role: 'function' }, ]; expect(() => experimental_buildLlama2Prompt(messages)).toThrow(); }); });
661
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/react/use-chat.ui.test.tsx
import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { mockFetchDataStream, mockFetchError } from '../tests/utils/mock-fetch'; import { useChat } from './use-chat'; // mock nanoid import jest.mock('nanoid', () => ({ nanoid: () => Math.random().toString(36).slice(2, 9), })); const TestComponent = () => { const { messages, append, error, data } = useChat(); return ( <div> {error && <div data-testid="error">{error.toString()}</div>} {data && <div data-testid="data">{JSON.stringify(data)}</div>} {messages.map((m, idx) => ( <div data-testid={`message-${idx}`} key={m.id}> {m.role === 'user' ? 'User: ' : 'AI: '} {m.content} </div> ))} <button data-testid="button" onClick={() => { append({ role: 'user', content: 'hi' }); }} /> </div> ); }; describe('useChat', () => { afterEach(() => { jest.restoreAllMocks(); }); test('Shows streamed complex text response', async () => { render(<TestComponent />); mockFetchDataStream(['0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n']); await userEvent.click(screen.getByTestId('button')); await screen.findByTestId('message-0'); expect(screen.getByTestId('message-0')).toHaveTextContent('User: hi'); await screen.findByTestId('message-1'); expect(screen.getByTestId('message-1')).toHaveTextContent( 'AI: Hello, world.', ); }); test('Shows streamed complex text response with data', async () => { render(<TestComponent />); mockFetchDataStream(['2:[{"t1":"v1"}]\n', '0:"Hello"\n']); await userEvent.click(screen.getByTestId('button')); await screen.findByTestId('data'); expect(screen.getByTestId('data')).toHaveTextContent('[{"t1":"v1"}]'); await screen.findByTestId('message-1'); expect(screen.getByTestId('message-1')).toHaveTextContent('AI: Hello'); }); test('Shows error response', async () => { render(<TestComponent />); mockFetchError({ statusCode: 404, errorMessage: 'Not found' }); await userEvent.click(screen.getByTestId('button')); // TODO bug? the user message does not show up // await screen.findByTestId('message-0'); // expect(screen.getByTestId('message-0')).toHaveTextContent('User: hi'); await screen.findByTestId('error'); expect(screen.getByTestId('error')).toHaveTextContent('Error: Not found'); }); });
664
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/shared/parse-complex-response.test.ts
import { parseComplexResponse } from './parse-complex-response'; describe('parseComplexResponse function', () => { function createTestReader(chunks: string[]) { const readableStream = new ReadableStream<Uint8Array>({ async start(controller) { for (const chunk of chunks) { controller.enqueue(Buffer.from(chunk, 'utf-8')); } controller.close(); }, }); return readableStream.getReader(); } function assistantTextMessage(text: string) { return { id: expect.any(String), role: 'assistant', content: text, createdAt: expect.any(Date), }; } it('should parse a single text message', async () => { const mockUpdate = jest.fn(); const result = await parseComplexResponse({ reader: createTestReader(['0:"Hello"\n']), abortControllerRef: { current: new AbortController() }, update: mockUpdate, generateId: () => 'test-id', getCurrentDate: () => new Date(0), }); const expectedMessage = assistantTextMessage('Hello'); // check the mockUpdate call: expect(mockUpdate).toHaveBeenCalledTimes(1); expect(mockUpdate.mock.calls[0][0]).toEqual([expectedMessage]); // check the result expect(result).toEqual({ messages: [ { content: 'Hello', createdAt: new Date(0), id: 'test-id', role: 'assistant', }, ], data: [], }); }); it('should parse a sequence of text messages', async () => { const mockUpdate = jest.fn(); const result = await parseComplexResponse({ reader: createTestReader([ '0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', ]), abortControllerRef: { current: new AbortController() }, update: mockUpdate, generateId: () => 'test-id', getCurrentDate: () => new Date(0), }); // check the mockUpdate call: expect(mockUpdate).toHaveBeenCalledTimes(4); expect(mockUpdate.mock.calls[0][0]).toEqual([ assistantTextMessage('Hello'), ]); expect(mockUpdate.mock.calls[1][0]).toEqual([ assistantTextMessage('Hello,'), ]); expect(mockUpdate.mock.calls[2][0]).toEqual([ assistantTextMessage('Hello, world'), ]); expect(mockUpdate.mock.calls[3][0]).toEqual([ assistantTextMessage('Hello, world.'), ]); // check the result expect(result).toEqual({ messages: [ { content: 'Hello, world.', createdAt: new Date(0), id: 'test-id', role: 'assistant', }, ], data: [], }); }); it('should parse a function call', async () => { const mockUpdate = jest.fn(); const result = await parseComplexResponse({ reader: createTestReader([ '1:{"function_call":{"name":"get_current_weather","arguments":"{\\n\\"location\\": \\"Charlottesville, Virginia\\",\\n\\"format\\": \\"celsius\\"\\n}"}}\n', ]), abortControllerRef: { current: new AbortController() }, update: mockUpdate, generateId: () => 'test-id', getCurrentDate: () => new Date(0), }); // check the mockUpdate call: expect(mockUpdate).toHaveBeenCalledTimes(1); expect(mockUpdate.mock.calls[0][0]).toEqual([ { id: expect.any(String), role: 'assistant', content: '', name: 'get_current_weather', function_call: { name: 'get_current_weather', arguments: '{\n"location": "Charlottesville, Virginia",\n"format": "celsius"\n}', }, createdAt: expect.any(Date), }, ]); // check the result expect(result).toEqual({ messages: [ { content: '', createdAt: new Date(0), id: 'test-id', role: 'assistant', function_call: { name: 'get_current_weather', arguments: '{\n"location": "Charlottesville, Virginia",\n"format": "celsius"\n}', }, name: 'get_current_weather', }, ], data: [], }); }); it('should parse a combination of a data and a text message', async () => { const mockUpdate = jest.fn(); // Execute the parser function const result = await parseComplexResponse({ reader: createTestReader([ '2:[{"t1":"v1"}]\n', '0:"Sample text message."\n', ]), abortControllerRef: { current: new AbortController() }, update: mockUpdate, generateId: () => 'test-id', getCurrentDate: () => new Date(0), }); // check the mockUpdate call: expect(mockUpdate).toHaveBeenCalledTimes(2); expect(mockUpdate.mock.calls[0][0]).toEqual([]); expect(mockUpdate.mock.calls[0][1]).toEqual([{ t1: 'v1' }]); expect(mockUpdate.mock.calls[1][0]).toEqual([ assistantTextMessage('Sample text message.'), ]); expect(mockUpdate.mock.calls[1][1]).toEqual([{ t1: 'v1' }]); // check the result expect(result).toEqual({ messages: [ { content: 'Sample text message.', createdAt: new Date(0), id: 'test-id', role: 'assistant', }, ], data: [{ t1: 'v1' }], }); }); it('should parse multiple data messages incl. primitive values', async () => { const mockUpdate = jest.fn(); // Execute the parser function const result = await parseComplexResponse({ reader: createTestReader([ '2:[{"t1":"v1"}, 3]\n', '2:[null,false,"text"]\n', ]), abortControllerRef: { current: new AbortController() }, update: mockUpdate, generateId: () => 'test-id', getCurrentDate: () => new Date(0), }); // check the mockUpdate call: expect(mockUpdate).toHaveBeenCalledTimes(2); expect(mockUpdate.mock.calls[0][0]).toEqual([]); expect(mockUpdate.mock.calls[0][1]).toEqual([{ t1: 'v1' }, 3]); expect(mockUpdate.mock.calls[1][0]).toEqual([]); expect(mockUpdate.mock.calls[1][1]).toEqual([ { t1: 'v1' }, 3, null, false, 'text', ]); // check the result expect(result).toEqual({ messages: [], data: [{ t1: 'v1' }, 3, null, false, 'text'], }); }); });
668
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/shared/stream-parts.test.ts
import { formatStreamPart, parseStreamPart } from './stream-parts'; describe('stream-parts', () => { describe('formatStreamPart', () => { it('should escape newlines in text', () => { expect(formatStreamPart('text', 'value\nvalue')).toEqual( '0:"value\\nvalue"\n', ); }); it('should escape newlines in data objects', () => { expect(formatStreamPart('data', [{ test: 'value\nvalue' }])).toEqual( '2:[{"test":"value\\nvalue"}]\n', ); }); }); describe('parseStreamPart', () => { it('should parse a text line', () => { const input = '0:"Hello, world!"'; expect(parseStreamPart(input)).toEqual({ type: 'text', value: 'Hello, world!', }); }); it('should parse a function call line', () => { const input = '1:{"function_call": {"name":"get_current_weather","arguments":"{\\"location\\": \\"Charlottesville, Virginia\\",\\"format\\": \\"celsius\\"}"}}'; expect(parseStreamPart(input)).toEqual({ type: 'function_call', value: { function_call: { name: 'get_current_weather', arguments: '{"location": "Charlottesville, Virginia","format": "celsius"}', }, }, }); }); it('should parse a data line', () => { const input = '2:[{"test":"value"}]'; const expectedOutput = { type: 'data', value: [{ test: 'value' }] }; expect(parseStreamPart(input)).toEqual(expectedOutput); }); it('should throw an error if the input does not contain a colon separator', () => { const input = 'invalid stream string'; expect(() => parseStreamPart(input)).toThrow(); }); it('should throw an error if the input contains an invalid type', () => { const input = '55:test'; expect(() => parseStreamPart(input)).toThrow(); }); it("should throw error if the input's JSON is invalid", () => { const input = '0:{"test":"value"'; expect(() => parseStreamPart(input)).toThrow(); }); }); });
671
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/shared/utils.test.ts
import { formatStreamPart } from './stream-parts'; import { createChunkDecoder } from './utils'; describe('utils', () => { describe('createChunkDecoder', () => { it('should correctly decode text chunk in complex mode', () => { const decoder = createChunkDecoder(true); const encoder = new TextEncoder(); const chunk = encoder.encode(formatStreamPart('text', 'Hello, world!')); const values = decoder(chunk); expect(values).toStrictEqual([{ type: 'text', value: 'Hello, world!' }]); }); it('should correctly decode function chunk in complex mode', () => { const functionCall = { name: 'get_current_weather', arguments: '{\n"location": "Charlottesville, Virginia",\n"format": "celsius"\n}', }; const decoder = createChunkDecoder(true); const encoder = new TextEncoder(); const chunk = encoder.encode( formatStreamPart('function_call', { function_call: functionCall, }), ); const values = decoder(chunk); expect(values).toStrictEqual([ { type: 'function_call', value: { function_call: functionCall, }, }, ]); }); it('should correctly decode data chunk in complex mode', () => { const data = [{ test: 'value' }]; const decoder = createChunkDecoder(true); const encoder = new TextEncoder(); const chunk = encoder.encode(formatStreamPart('data', data)); const values = decoder(chunk); expect(values).toStrictEqual([{ type: 'data', value: data }]); }); it('should correctly decode streamed utf8 chunks in complex mode', () => { const normalDecode = createChunkDecoder(); const complexDecode = createChunkDecoder(true); const encoder = new TextEncoder(); // Original data chunks const chunk1 = new Uint8Array([226, 153]); const chunk2 = new Uint8Array([165]); const enqueuedChunks = []; enqueuedChunks.push( encoder.encode(formatStreamPart('text', normalDecode(chunk1))), ); enqueuedChunks.push( encoder.encode(formatStreamPart('text', normalDecode(chunk2))), ); let fullDecodedString = ''; for (const chunk of enqueuedChunks) { const lines = complexDecode(chunk); for (const line of lines) { if (line.type !== 'text') { throw new Error('Expected line to be text'); } fullDecodedString += line.value; } } expect(fullDecodedString).toBe('♥'); }); it('should correctly decode streamed utf8 chunks in simple mode', () => { const decoder = createChunkDecoder(false); const chunk1 = new Uint8Array([226, 153]); const chunk2 = new Uint8Array([165]); const values = decoder(chunk1); const secondValues = decoder(chunk2); if (typeof values !== 'string' || typeof secondValues !== 'string') { throw new Error('Expected values to be strings, not objects'); } expect(values + secondValues).toBe('♥'); }); }); });
678
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/streams/anthropic-stream.test.ts
import { AnthropicStream, StreamingTextResponse, experimental_StreamData, } from '.'; import { readAllChunks } from '../tests/utils/mock-client'; import { setup } from '../tests/utils/mock-service'; import Anthropic from '@anthropic-ai/sdk'; describe('AnthropicStream', () => { let server: ReturnType<typeof setup>; beforeAll(() => { server = setup(3035); }); afterAll(async () => server.teardown()); it('should be able to parse SSE and receive the streamed response', async () => { const anthropic = new Anthropic({ fetch: () => fetch(server.api, { headers: { 'x-mock-service': 'anthropic', 'x-mock-type': 'chat', }, }), apiKey: 'sk-doesnt-matter', }); const anthropicResponse = await anthropic.completions.create({ prompt: '', model: 'claude-2', stream: true, max_tokens_to_sample: 300, }); const stream = AnthropicStream(anthropicResponse); const response = new StreamingTextResponse(stream); expect(await readAllChunks(response)).toEqual([ ' Hello', ',', ' world', '.', ]); }); describe('StreamData protocol', () => { it('should send text', async () => { const anthropic = new Anthropic({ fetch: () => fetch(server.api, { headers: { 'x-mock-service': 'anthropic', 'x-mock-type': 'chat', }, }), apiKey: 'sk-doesnt-matter', }); const data = new experimental_StreamData(); const anthropicResponse = await anthropic.completions.create({ prompt: '', model: 'claude-2', stream: true, max_tokens_to_sample: 300, }); const stream = AnthropicStream(anthropicResponse, { onFinal() { data.close(); }, experimental_streamData: true, }); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '0:" Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', ]); }); it('should send text and data', async () => { const anthropic = new Anthropic({ fetch: () => fetch(server.api, { headers: { 'x-mock-service': 'anthropic', 'x-mock-type': 'chat', }, }), apiKey: 'sk-doesnt-matter', }); const data = new experimental_StreamData(); data.append({ t1: 'v1' }); const anthropicResponse = await anthropic.completions.create({ prompt: '', model: 'claude-2', stream: true, max_tokens_to_sample: 300, }); const stream = AnthropicStream(anthropicResponse, { onFinal() { data.close(); }, experimental_streamData: true, }); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '2:[{"t1":"v1"}]\n', '0:" Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', ]); }); }); });
681
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/streams/aws-bedrock-stream.test.ts
import { StreamingTextResponse, experimental_StreamData } from '.'; import { bedrockAnthropicChunks, bedrockCohereChunks, bedrockLlama2Chunks, } from '../tests/snapshots/aws-bedrock'; import { readAllChunks } from '../tests/utils/mock-client'; import { AWSBedrockAnthropicStream, AWSBedrockCohereStream, AWSBedrockLlama2Stream, } from './aws-bedrock-stream'; function simulateBedrockResponse(chunks: any[]) { chunks = chunks.slice(); // make a copy return { body: { [Symbol.asyncIterator]() { return { next() { const chunk = chunks.shift(); if (chunk) { const bytes = new TextEncoder().encode(JSON.stringify(chunk)); return Promise.resolve({ value: { chunk: { bytes } }, done: false, }); } else { return Promise.resolve({ done: true }); } }, }; }, } as AsyncIterable<{ chunk?: { bytes?: Uint8Array } }>, }; } describe('AWS Bedrock', () => { describe('Anthropic', () => { it('should be able to parse SSE and receive the streamed response', async () => { const bedrockResponse = simulateBedrockResponse(bedrockAnthropicChunks); const stream = AWSBedrockAnthropicStream(bedrockResponse); const response = new StreamingTextResponse(stream); expect(await readAllChunks(response)).toEqual([ ' Hello', ',', ' world', '.', ]); }); describe('StreamData protocol', () => { it('should send text', async () => { const data = new experimental_StreamData(); const bedrockResponse = simulateBedrockResponse(bedrockAnthropicChunks); const stream = AWSBedrockAnthropicStream(bedrockResponse, { onFinal() { data.close(); }, experimental_streamData: true, }); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '0:" Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', ]); }); it('should send text and data', async () => { const data = new experimental_StreamData(); data.append({ t1: 'v1' }); const bedrockResponse = simulateBedrockResponse(bedrockAnthropicChunks); const stream = AWSBedrockAnthropicStream(bedrockResponse, { onFinal() { data.close(); }, experimental_streamData: true, }); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '2:[{"t1":"v1"}]\n', '0:" Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', ]); }); }); }); describe('Cohere', () => { it('should be able to parse SSE and receive the streamed response', async () => { const bedrockResponse = simulateBedrockResponse(bedrockCohereChunks); const stream = AWSBedrockCohereStream(bedrockResponse); const response = new StreamingTextResponse(stream); expect(await readAllChunks(response)).toEqual([ ' Hi! How can I help you today?', ]); }); describe('StreamData protocol', () => { it('should send text', async () => { const data = new experimental_StreamData(); const bedrockResponse = simulateBedrockResponse(bedrockCohereChunks); const stream = AWSBedrockCohereStream(bedrockResponse, { onFinal() { data.close(); }, experimental_streamData: true, }); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '0:" Hi! How can I help you today?"\n', ]); }); it('should send text and data', async () => { const data = new experimental_StreamData(); data.append({ t1: 'v1' }); const bedrockResponse = simulateBedrockResponse(bedrockCohereChunks); const stream = AWSBedrockCohereStream(bedrockResponse, { onFinal() { data.close(); }, experimental_streamData: true, }); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '2:[{"t1":"v1"}]\n', '0:" Hi! How can I help you today?"\n', ]); }); }); }); describe('Llama2', () => { it('should be able to parse SSE and receive the streamed response', async () => { const bedrockResponse = simulateBedrockResponse(bedrockLlama2Chunks); const stream = AWSBedrockLlama2Stream(bedrockResponse); const response = new StreamingTextResponse(stream); expect(await readAllChunks(response)).toEqual([ '', ' Hello', ',', ' world', '.', '', ]); }); describe('StreamData protocol', () => { it('should send text', async () => { const data = new experimental_StreamData(); const bedrockResponse = simulateBedrockResponse(bedrockLlama2Chunks); const stream = AWSBedrockLlama2Stream(bedrockResponse, { onFinal() { data.close(); }, experimental_streamData: true, }); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '0:""\n', '0:" Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', '0:""\n', ]); }); it('should send text and data', async () => { const data = new experimental_StreamData(); data.append({ t1: 'v1' }); const bedrockResponse = simulateBedrockResponse(bedrockLlama2Chunks); const stream = AWSBedrockLlama2Stream(bedrockResponse, { onFinal() { data.close(); }, experimental_streamData: true, }); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '2:[{"t1":"v1"}]\n', '0:""\n', '0:" Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', '0:""\n', ]); }); }); }); });
683
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/streams/cohere-stream.test.ts
import { CohereStream, StreamingTextResponse, experimental_StreamData, } from '.'; import { readAllChunks } from '../tests/utils/mock-client'; import { setup } from '../tests/utils/mock-service'; describe('CohereStream', () => { let server: ReturnType<typeof setup>; beforeAll(() => { server = setup(3032); }); afterAll(async () => server.teardown()); it('should be able to parse SSE and receive the streamed response', async () => { const stream = CohereStream( await fetch(server.api, { headers: { 'x-mock-service': 'cohere', 'x-mock-type': 'chat', }, }), ); const response = new StreamingTextResponse(stream); expect(await readAllChunks(response)).toEqual([ ' Hello', ',', ' world', '.', ' ', ]); }); describe('StreamData protocol', () => { it('should send text', async () => { const data = new experimental_StreamData(); const stream = CohereStream( await fetch(server.api, { headers: { 'x-mock-service': 'cohere', 'x-mock-type': 'chat', }, }), { onFinal() { data.close(); }, experimental_streamData: true, }, ); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '0:" Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', '0:" "\n', ]); }); it('should send text and data', async () => { const data = new experimental_StreamData(); data.append({ t1: 'v1' }); const stream = CohereStream( await fetch(server.api, { headers: { 'x-mock-service': 'cohere', 'x-mock-type': 'chat', }, }), { onFinal() { data.close(); }, experimental_streamData: true, }, ); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '2:[{"t1":"v1"}]\n', '0:" Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', '0:" "\n', ]); }); }); });
685
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/streams/huggingface-stream.test.ts
import { HfInference } from '@huggingface/inference'; import { HuggingFaceStream, StreamingTextResponse, experimental_StreamData, } from '.'; import { createClient } from '../tests/utils/mock-client'; import { setup } from '../tests/utils/mock-service'; describe('HuggingFace stream', () => { const Hf = new HfInference(); let server: ReturnType<typeof setup>; beforeAll(() => { server = setup(3033); }); afterAll(async () => server.teardown()); function readAllChunks(response: Response) { return createClient(response).readAll(); } it('should be able to parse HuggingFace response and receive the streamed response', async () => { const stream = HuggingFaceStream( Hf.textGenerationStream( { model: 'model', inputs: '' }, { fetch() { return fetch(server.api, { headers: { 'x-mock-service': 'huggingface', 'x-mock-type': 'chat', }, }); }, }, ), ); const response = new StreamingTextResponse(stream); expect(await readAllChunks(response)).toEqual([ 'Hello', ',', ' world', '.', ]); }); describe('StreamData prototcol', () => { it('should send text', async () => { const data = new experimental_StreamData(); const stream = HuggingFaceStream( Hf.textGenerationStream( { model: 'model', inputs: '' }, { fetch() { return fetch(server.api, { headers: { 'x-mock-service': 'huggingface', 'x-mock-type': 'chat', }, }); }, }, ), { onFinal() { data.close(); }, experimental_streamData: true, }, ); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', ]); }); it('should send text and data', async () => { const data = new experimental_StreamData(); data.append({ t1: 'v1' }); const stream = HuggingFaceStream( Hf.textGenerationStream( { model: 'model', inputs: '' }, { fetch() { return fetch(server.api, { headers: { 'x-mock-service': 'huggingface', 'x-mock-type': 'chat', }, }); }, }, ), { onFinal() { data.close(); }, experimental_streamData: true, }, ); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '2:[{"t1":"v1"}]\n', '0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', ]); }); }); });
688
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/streams/langchain-stream.test.ts
import { LangChainStream, StreamingTextResponse, createStreamDataTransformer, experimental_StreamData, } from '.'; import { createClient } from '../tests/utils/mock-client'; import { setup } from '../tests/utils/mock-service'; // need to mock uuid before importing LangChain jest.mock('uuid', () => { let count = 0; return { v4: () => `uuid-${count++}`, }; }); import { ChatOpenAI } from 'langchain/chat_models/openai'; import { BytesOutputParser } from 'langchain/schema/output_parser'; import { HumanMessage } from 'langchain/schema'; import { PromptTemplate } from 'langchain/prompts'; describe('LangchainStream', () => { let server: ReturnType<typeof setup>; beforeAll(() => { server = setup(3031); }); afterAll(async () => server.teardown()); function readAllChunks(response: Response) { return createClient(response).readAll(); } describe('LangChain Expression Language call', () => { it('should be able to parse SSE and receive the streamed response', async () => { const model = new ChatOpenAI({ streaming: true, openAIApiKey: 'fake', configuration: { baseURL: server.api, defaultHeaders: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }, }); const stream = await PromptTemplate.fromTemplate('{input}') .pipe(model) .pipe(new BytesOutputParser()) .stream({ input: 'Hello' }); const response = new StreamingTextResponse(stream); expect(await readAllChunks(response)).toEqual([ '', 'Hello', ',', ' world', '.', '', ]); }); describe('StreamData prototcol', () => { it('should send text', async () => { const data = new experimental_StreamData(); const model = new ChatOpenAI({ streaming: true, openAIApiKey: 'fake', configuration: { baseURL: server.api, defaultHeaders: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }, }); const stream = await PromptTemplate.fromTemplate('{input}') .pipe(model) .pipe(new BytesOutputParser()) .stream( { input: 'Hello' }, { callbacks: [ { handleChainEnd(outputs, runId, parentRunId) { // check that main chain (without parent) is finished: if (parentRunId == null) { data.close(); } }, }, ], }, ); const response = new StreamingTextResponse( stream.pipeThrough(createStreamDataTransformer(true)), {}, data, ); expect(await readAllChunks(response)).toEqual([ '0:""\n', '0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', '0:""\n', ]); }); it('should send text and data', async () => { const data = new experimental_StreamData(); data.append({ t1: 'v1' }); const model = new ChatOpenAI({ streaming: true, openAIApiKey: 'fake', configuration: { baseURL: server.api, defaultHeaders: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }, }); const stream = await PromptTemplate.fromTemplate('{input}') .pipe(model) .pipe(new BytesOutputParser()) .stream( { input: 'Hello' }, { callbacks: [ { handleChainEnd(outputs, runId, parentRunId) { // check that main chain (without parent) is finished: if (parentRunId == null) { data.close(); } }, }, ], }, ); const response = new StreamingTextResponse( stream.pipeThrough(createStreamDataTransformer(true)), {}, data, ); expect(await readAllChunks(response)).toEqual([ '2:[{"t1":"v1"}]\n', '0:""\n', '0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', '0:""\n', ]); }); }); }); describe('LangChain LLM call', () => { it('should be able to parse SSE and receive the streamed response', async () => { const { stream, handlers } = LangChainStream(); const llm = new ChatOpenAI({ streaming: true, openAIApiKey: 'fake', configuration: { baseURL: server.api, defaultHeaders: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }, }); llm .call([new HumanMessage('hello')], {}, [handlers]) .catch(console.error); const response = new StreamingTextResponse(stream); expect(await readAllChunks(response)).toEqual([ '', 'Hello', ',', ' world', '.', '', ]); }); describe('StreamData prototcol', () => { it('should send text', async () => { const data = new experimental_StreamData(); const { stream, handlers } = LangChainStream({ onFinal() { data.close(); }, experimental_streamData: true, }); const llm = new ChatOpenAI({ streaming: true, openAIApiKey: 'fake', configuration: { baseURL: server.api, defaultHeaders: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }, }); llm .call([new HumanMessage('hello')], {}, [handlers]) .catch(console.error); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '0:""\n', '0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', '0:""\n', ]); }); it('should send text and data', async () => { const data = new experimental_StreamData(); data.append({ t1: 'v1' }); const { stream, handlers } = LangChainStream({ onFinal() { data.close(); }, experimental_streamData: true, }); const llm = new ChatOpenAI({ streaming: true, openAIApiKey: 'fake', configuration: { baseURL: server.api, defaultHeaders: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }, }); llm .call([new HumanMessage('hello')], {}, [handlers]) .catch(console.error); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '2:[{"t1":"v1"}]\n', '0:""\n', '0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', '0:""\n', ]); }); }); }); });
690
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/streams/openai-stream.test.tsx
import React from 'react'; import { OpenAIStream, ReactResponseRow, StreamingTextResponse, experimental_StreamData, experimental_StreamingReactResponse, } from '.'; import OpenAI from 'openai'; import { createClient } from '../tests/utils/mock-client'; import { setup } from '../tests/utils/mock-service'; import ReactDOMServer from 'react-dom/server'; describe('OpenAIStream', () => { let server: ReturnType<typeof setup>; beforeAll(() => { server = setup(); }); afterAll(async () => server.teardown()); // deactivated to only test types xit('should not throw type errors', async () => { const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); const response = await openai.chat.completions.create({ model: 'gpt-3.5-turbo-16k', stream: true, temperature: 0.0, messages: [ { role: 'system', content: 'You are a helpful yada yada' }, { role: 'user', content: '' }, ], }); const stream = OpenAIStream(response); }); it('should be able to parse SSE and receive the streamed response', async () => { const stream = OpenAIStream( await fetch(server.api, { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }), ); const response = new StreamingTextResponse(stream); const client = createClient(response); const chunks = await client.readAll(); expect(JSON.stringify(chunks)).toMatchInlineSnapshot( `"["Hello",","," world","."]"`, ); expect(JSON.stringify(server.getRecentFlushed())).toMatchInlineSnapshot( `"[{"id":"chatcmpl-7RyNSW2BXkOQQh7NlBc65j5kX8AjC","object":"chat.completion.chunk","created":1686901302,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"role":"assistant"},"index":0,"finish_reason":null}]},{"id":"chatcmpl-7RyNSW2BXkOQQh7NlBc65j5kX8AjC","object":"chat.completion.chunk","created":1686901302,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"content":"Hello"},"index":0,"finish_reason":null}]},{"id":"chatcmpl-7RyNSW2BXkOQQh7NlBc65j5kX8AjC","object":"chat.completion.chunk","created":1686901302,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"content":","},"index":0,"finish_reason":null}]},{"id":"chatcmpl-7RyNSW2BXkOQQh7NlBc65j5kX8AjC","object":"chat.completion.chunk","created":1686901302,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"content":" world"},"index":0,"finish_reason":null}]},{"id":"chatcmpl-7RyNSW2BXkOQQh7NlBc65j5kX8AjC","object":"chat.completion.chunk","created":1686901302,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"content":"."},"index":0,"finish_reason":null}]},{"id":"chatcmpl-7RyNSW2BXkOQQh7NlBc65j5kX8AjC","object":"chat.completion.chunk","created":1686901302,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{},"index":0,"finish_reason":"stop"}]}]"`, ); }); it('should correctly parse and escape function call JSON chunks', async () => { const { OpenAIStream, StreamingTextResponse } = require('.') as typeof import('.'); const stream = OpenAIStream( await fetch(server.api + '/mock-func-call', { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'func_call', }, }), ); const response = new StreamingTextResponse(stream); const client = createClient(response); const chunks = await client.readAll(); const expectedChunks = [ '{"function_call": {"name": "get_current_weather", "arguments": "', '{\\n', '\\"', 'location', '\\":', ' \\"', 'Char', 'l', 'ottesville', ',', ' Virginia', '\\",\\n', '\\"', 'format', '\\":', ' \\"', 'c', 'elsius', '\\"\\n', '}', '"}}', ]; expect(chunks).toEqual(expectedChunks); expect(chunks.join('')).toEqual( `{"function_call": {"name": "get_current_weather", "arguments": "{\\n\\"location\\": \\"Charlottesville, Virginia\\",\\n\\"format\\": \\"celsius\\"\\n}"}}`, ); }); it('should handle backpressure on the server', async () => { const controller = new AbortController(); const stream = OpenAIStream( await fetch(server.api, { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, signal: controller.signal, }), ); const response = new StreamingTextResponse(stream); const client = createClient(response); const chunks = await client.readAndAbort(controller); expect(JSON.stringify(chunks)).toMatchInlineSnapshot(`"["Hello"]"`); expect(JSON.stringify(server.getRecentFlushed())).toMatchInlineSnapshot( `"[{"id":"chatcmpl-7RyNSW2BXkOQQh7NlBc65j5kX8AjC","object":"chat.completion.chunk","created":1686901302,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"role":"assistant"},"index":0,"finish_reason":null}]},{"id":"chatcmpl-7RyNSW2BXkOQQh7NlBc65j5kX8AjC","object":"chat.completion.chunk","created":1686901302,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"content":"Hello"},"index":0,"finish_reason":null}]}]"`, ); }); describe('StreamData prototcol', () => { it('should send text', async () => { const data = new experimental_StreamData(); const stream = OpenAIStream( await fetch(server.api, { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }), { onFinal() { data.close(); }, experimental_streamData: true, }, ); const response = new StreamingTextResponse(stream, {}, data); const client = createClient(response); const chunks = await client.readAll(); expect(chunks).toEqual([ '0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', ]); }); it('should send function response as text stream when onFunctionCall is not defined', async () => { const data = new experimental_StreamData(); const stream = OpenAIStream( await fetch(server.api + '/mock-func-call', { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'func_call', }, }), { onFinal() { data.close(); }, experimental_streamData: true, }, ); const response = new StreamingTextResponse(stream, {}, data); const client = createClient(response); const chunks = await client.readAll(); expect(chunks).toEqual([ '0:"{\\"function_call\\": {\\"name\\": \\"get_current_weather\\", \\"arguments\\": \\""\n', '0:"{\\\\n"\n', '0:"\\\\\\""\n', '0:"location"\n', '0:"\\\\\\":"\n', '0:" \\\\\\""\n', '0:"Char"\n', '0:"l"\n', '0:"ottesville"\n', '0:","\n', '0:" Virginia"\n', '0:"\\\\\\",\\\\n"\n', '0:"\\\\\\""\n', '0:"format"\n', '0:"\\\\\\":"\n', '0:" \\\\\\""\n', '0:"c"\n', '0:"elsius"\n', '0:"\\\\\\"\\\\n"\n', '0:"}"\n', '0:"\\"}}"\n', ]); }); it('should send function response when onFunctionCall is defined and returns undefined', async () => { const data = new experimental_StreamData(); const stream = OpenAIStream( await fetch(server.api + '/mock-func-call', { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'func_call', }, }), { onFinal() { data.close(); }, async experimental_onFunctionCall({ name }) { // no response }, experimental_streamData: true, }, ); const response = new StreamingTextResponse(stream, {}, data); const client = createClient(response); const chunks = await client.readAll(); expect(chunks).toEqual([ '1:{"function_call":{"name":"get_current_weather","arguments":"{\\n\\"location\\": \\"Charlottesville, Virginia\\",\\n\\"format\\": \\"celsius\\"\\n}"}}\n', ]); }); it('should send function response and data when onFunctionCall is defined, returns undefined, and data is added', async () => { const data = new experimental_StreamData(); const stream = OpenAIStream( await fetch(server.api + '/mock-func-call', { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'func_call', }, }), { onFinal() { data.close(); }, async experimental_onFunctionCall({ name }) { data.append({ fn: name }); // no response }, experimental_streamData: true, }, ); const response = new StreamingTextResponse(stream, {}, data); const client = createClient(response); const chunks = await client.readAll(); expect(chunks).toEqual([ '2:[{"fn":"get_current_weather"}]\n', '1:{"function_call":{"name":"get_current_weather","arguments":"{\\n\\"location\\": \\"Charlottesville, Virginia\\",\\n\\"format\\": \\"celsius\\"\\n}"}}\n', ]); }); it('should send return value when onFunctionCall is defined and returns value', async () => { const data = new experimental_StreamData(); const stream = OpenAIStream( await fetch(server.api + '/mock-func-call', { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'func_call', }, }), { onFinal() { data.close(); }, async experimental_onFunctionCall({ name }) { return 'experimental_onFunctionCall-return-value'; }, experimental_streamData: true, }, ); const response = new StreamingTextResponse(stream, {}, data); const client = createClient(response); const chunks = await client.readAll(); expect(chunks).toEqual([ '0:"experimental_onFunctionCall-return-value"\n', ]); }); it('should send return value and data when onFunctionCall is defined, returns value and data is added', async () => { const data = new experimental_StreamData(); const stream = OpenAIStream( await fetch(server.api + '/mock-func-call', { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'func_call', }, }), { onFinal() { data.close(); }, async experimental_onFunctionCall({ name }) { data.append({ fn: name }); return 'experimental_onFunctionCall-return-value'; }, experimental_streamData: true, }, ); const response = new StreamingTextResponse(stream, {}, data); const client = createClient(response); const chunks = await client.readAll(); expect(chunks).toEqual([ '2:[{"fn":"get_current_weather"}]\n', '0:"experimental_onFunctionCall-return-value"\n', ]); }); it('should send text and data', async () => { const data = new experimental_StreamData(); data.append({ t1: 'v1' }); const stream = OpenAIStream( await fetch(server.api, { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }), { onFinal() { data.close(); }, experimental_streamData: true, }, ); const response = new StreamingTextResponse(stream, {}, data); const client = createClient(response); const chunks = await client.readAll(); expect(chunks).toEqual([ '2:[{"t1":"v1"}]\n', '0:"Hello"\n', '0:","\n', '0:" world"\n', '0:"."\n', ]); }); }); describe('React Streaming', () => { async function extractReactRowContents( response: Promise<ReactResponseRow>, ) { let current: ReactResponseRow | null = await response; const rows: { ui: string | JSX.Element | JSX.Element[] | null | undefined; content: string; }[] = []; while (current != null) { let ui = await current.ui; if (ui != null && typeof ui !== 'string' && !Array.isArray(ui)) { ui = ReactDOMServer.renderToStaticMarkup(ui); } rows.push({ ui: ui, content: current.content, }); current = await current.next; } return rows; } it('should stream text response as React rows', async () => { const stream = OpenAIStream( await fetch(server.api, { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }), ); const response = new experimental_StreamingReactResponse( stream, {}, ) as Promise<ReactResponseRow>; const rows = await extractReactRowContents(response); expect(rows).toEqual([ { ui: 'Hello', content: 'Hello' }, { ui: 'Hello,', content: 'Hello,' }, { ui: 'Hello, world', content: 'Hello, world' }, { ui: 'Hello, world.', content: 'Hello, world.' }, { ui: 'Hello, world.', content: 'Hello, world.' }, ]); }); it('should stream React response as React rows', async () => { const stream = OpenAIStream( await fetch(server.api, { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }), ); const response = new experimental_StreamingReactResponse(stream, { ui: ({ content }) => <span>{content}</span>, }) as Promise<ReactResponseRow>; const rows = await extractReactRowContents(response); expect(rows).toEqual([ { ui: '<span>Hello</span>', content: 'Hello' }, { ui: '<span>Hello,</span>', content: 'Hello,' }, { ui: '<span>Hello, world</span>', content: 'Hello, world' }, { ui: '<span>Hello, world.</span>', content: 'Hello, world.' }, { ui: '<span>Hello, world.</span>', content: 'Hello, world.' }, ]); }); it('should stream text response as React rows from data stream', async () => { const data = new experimental_StreamData(); const stream = OpenAIStream( await fetch(server.api, { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }), { onFinal() { data.close(); }, experimental_streamData: true, }, ); const response = new experimental_StreamingReactResponse(stream, { data, }) as Promise<ReactResponseRow>; const rows = await extractReactRowContents(response); expect(rows).toEqual([ { ui: 'Hello', content: 'Hello' }, { ui: 'Hello,', content: 'Hello,' }, { ui: 'Hello, world', content: 'Hello, world' }, { ui: 'Hello, world.', content: 'Hello, world.' }, { ui: 'Hello, world.', content: 'Hello, world.' }, ]); }); it('should stream React response as React rows from data stream', async () => { const data = new experimental_StreamData(); const stream = OpenAIStream( await fetch(server.api, { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'chat', }, }), { onFinal() { data.close(); }, experimental_streamData: true, }, ); const response = new experimental_StreamingReactResponse(stream, { data, ui: ({ content }) => <span>{content}</span>, }) as Promise<ReactResponseRow>; const rows = await extractReactRowContents(response); expect(rows).toEqual([ { ui: '<span>Hello</span>', content: 'Hello' }, { ui: '<span>Hello,</span>', content: 'Hello,' }, { ui: '<span>Hello, world</span>', content: 'Hello, world' }, { ui: '<span>Hello, world.</span>', content: 'Hello, world.' }, { ui: '<span>Hello, world.</span>', content: 'Hello, world.' }, ]); }); it('should stream React response as React rows from data stream when data is appended', async () => { const data = new experimental_StreamData(); const stream = OpenAIStream( await fetch(server.api + '/mock-func-call', { headers: { 'x-mock-service': 'openai', 'x-mock-type': 'func_call', }, }), { onFinal() { data.close(); }, async experimental_onFunctionCall({ name }) { data.append({ fn: name }); return undefined; }, experimental_streamData: true, }, ); const response = new experimental_StreamingReactResponse(stream, { data, ui: ({ content, data }) => { if (data != null) { return <pre>{JSON.stringify(data)}</pre>; } return <span>{content}</span>; }, }) as Promise<ReactResponseRow>; const rows = await extractReactRowContents(response); expect(rows).toStrictEqual([ { ui: '<pre>[{&quot;fn&quot;:&quot;get_current_weather&quot;}]</pre>', content: '', }, { ui: '<pre>[{&quot;fn&quot;:&quot;get_current_weather&quot;}]</pre>', content: '', }, { ui: '<pre>[{&quot;fn&quot;:&quot;get_current_weather&quot;}]</pre>', content: '', }, ]); }); }); });
692
0
petrpan-code/vercel/ai/packages/core
petrpan-code/vercel/ai/packages/core/streams/replicate-stream.test.ts
import { ReplicateStream, StreamingTextResponse, experimental_StreamData, } from '.'; import { createClient } from '../tests/utils/mock-client'; import { setup } from '../tests/utils/mock-service'; describe('ReplicateStream', () => { let server: ReturnType<typeof setup>; beforeAll(() => { server = setup(3034); }); afterAll(async () => server.teardown()); function readAllChunks(response: Response) { return createClient(response).readAll(); } it('should be able to parse SSE and receive the streamed response', async () => { // Note: this only tests the streaming response from Replicate, not the framework invocation. const stream = await ReplicateStream( { id: 'fake', status: 'processing', version: 'fake', input: {}, source: 'api', created_at: 'fake', urls: { get: '', cancel: '', stream: server.api }, }, undefined, { headers: { 'x-mock-service': 'replicate', 'x-mock-type': 'chat' }, }, ); const response = new StreamingTextResponse(stream); expect(await readAllChunks(response)).toEqual([' Hello,', ' world', '.']); }); describe('StreamData protocol', () => { it('should send text', async () => { const data = new experimental_StreamData(); const stream = await ReplicateStream( { id: 'fake', status: 'processing', version: 'fake', input: {}, source: 'api', created_at: 'fake', urls: { get: '', cancel: '', stream: server.api }, }, { onFinal() { data.close(); }, experimental_streamData: true, }, { headers: { 'x-mock-service': 'replicate', 'x-mock-type': 'chat' }, }, ); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '0:" Hello,"\n', '0:" world"\n', '0:"."\n', ]); }); it('should send text and data', async () => { const data = new experimental_StreamData(); data.append({ t1: 'v1' }); const stream = await ReplicateStream( { id: 'fake', status: 'processing', version: 'fake', input: {}, source: 'api', created_at: 'fake', urls: { get: '', cancel: '', stream: server.api }, }, { onFinal() { data.close(); }, experimental_streamData: true, }, { headers: { 'x-mock-service': 'replicate', 'x-mock-type': 'chat' }, }, ); const response = new StreamingTextResponse(stream, {}, data); expect(await readAllChunks(response)).toEqual([ '2:[{"t1":"v1"}]\n', '0:" Hello,"\n', '0:" world"\n', '0:"."\n', ]); }); }); });
748
0
petrpan-code/facebook/docusaurus
petrpan-code/facebook/docusaurus/__tests__/validate-package-json.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import fs from 'fs-extra'; import {Globby} from '@docusaurus/utils'; type PackageJsonFile = { file: string; content: { name?: string; private?: boolean; version?: string; repository?: { type?: string; url?: string; directory?: string; }; publishConfig?: { access?: string; }; }; }; async function getPackagesJsonFiles(): Promise<PackageJsonFile[]> { const files = await Globby('packages/*/package.json'); return Promise.all( files.map((file) => fs .readJSON(file) .then((content: PackageJsonFile['content']) => ({file, content})), ), ); } describe('packages', () => { it('are found', async () => { const packageJsonFiles = await getPackagesJsonFiles(); expect(packageJsonFiles.length).toBeGreaterThan(0); }); it('contain repository and directory', async () => { const packageJsonFiles = await getPackagesJsonFiles(); packageJsonFiles .filter((packageJsonFile) => !packageJsonFile.content.private) .forEach((packageJsonFile) => { expect(packageJsonFile.content.repository).toEqual({ type: 'git', url: 'https://github.com/facebook/docusaurus.git', directory: packageJsonFile.file.replace(/\/package\.json$/, ''), }); }); }); /* If a package starts with @, if won't be published to public npm registry without an additional publishConfig.access: "public" config This will make you publish an incomplete list of Docusaurus packages when trying to release with lerna-publish */ it('have publishConfig.access: "public" when name starts with @', async () => { const packageJsonFiles = await getPackagesJsonFiles(); packageJsonFiles .filter((packageJsonFile) => packageJsonFile.content.name?.startsWith('@'), ) .forEach((packageJsonFile) => { // Unfortunately jest custom message do not exist in loops, // so using an exception instead to show failing package file // (see https://github.com/facebook/jest/issues/3293) // expect(packageJsonFile.content.publishConfig?.access) // .toEqual('public'); if (packageJsonFile.content.publishConfig?.access !== 'public') { throw new Error( `Package ${packageJsonFile.file} does not have publishConfig.access: 'public'`, ); } }); }); });
749
0
petrpan-code/facebook/docusaurus
petrpan-code/facebook/docusaurus/__tests__/validate-tsconfig.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import fs from 'fs-extra'; import {Globby} from '@docusaurus/utils'; import {Joi} from '@docusaurus/utils-validation'; type TsconfigFile = { file: string; content: { extends?: string; compilerOptions: { [key: string]: unknown; }; }; }; async function getTsconfigFiles(): Promise<TsconfigFile[]> { const files = await Globby('packages/*/tsconfig.*'); return Promise.all( files.map((file) => fs .readJSON(file) .then((content: TsconfigFile['content']) => ({file, content})), ), ); } const tsconfigSchema = Joi.object({ extends: '../../tsconfig.json', compilerOptions: Joi.alternatives().conditional( Joi.object({noEmit: true}).unknown(), { then: Joi.object({ noEmit: Joi.valid(true).required(), incremental: Joi.forbidden(), tsBuildInfoFile: Joi.forbidden(), outDir: Joi.forbidden(), }).unknown(), otherwise: Joi.object({ noEmit: Joi.valid(false).required(), incremental: Joi.valid(true).required(), rootDir: Joi.valid('src').required(), outDir: Joi.valid('lib').required(), }).unknown(), }, ), }).unknown(); describe('tsconfig files', () => { it('contain all required fields', async () => { const tsconfigFiles = await getTsconfigFiles(); tsconfigFiles.forEach((file) => { try { Joi.attempt(file.content, tsconfigSchema); } catch (e) { ( e as Error ).message += `\n${file.file} does not match the required schema.`; throw e; } }); }); });
915
0
petrpan-code/facebook/docusaurus/packages/docusaurus-cssnano-preset/src/remove-overridden-custom-properties
petrpan-code/facebook/docusaurus/packages/docusaurus-cssnano-preset/src/remove-overridden-custom-properties/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import vfile from 'to-vfile'; import postcss from 'postcss'; import postCssRemoveOverriddenCustomProperties from '../index'; const processFixture = async (name: string) => { const input = await vfile.read( path.join(__dirname, '__fixtures__', `${name}.css`), 'utf8', ); const output = postcss([postCssRemoveOverriddenCustomProperties]).process( input, ); return output.css; }; describe('remove-overridden-custom-properties', () => { it('overridden custom properties should be removed', async () => { await expect(processFixture('normal')).resolves.toMatchSnapshot(); }); it('overridden custom properties with `!important` rule should not be removed', async () => { await expect(processFixture('important_rule')).resolves.toMatchSnapshot(); }); });
918
0
petrpan-code/facebook/docusaurus/packages/docusaurus-cssnano-preset/src/remove-overridden-custom-properties/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-cssnano-preset/src/remove-overridden-custom-properties/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`remove-overridden-custom-properties overridden custom properties should be removed 1`] = ` "/* stylelint-disable docusaurus/copyright-header, declaration-block-no-duplicate-custom-properties */ :root { --color-secondary: green; --color-primary: blue; --color-header: gray; } .non-root { --color-primary: red; --color-primary: red; } " `; exports[`remove-overridden-custom-properties overridden custom properties with \`!important\` rule should not be removed 1`] = ` "/* stylelint-disable docusaurus/copyright-header, declaration-block-no-duplicate-custom-properties */ :root { --color-primary: blue; --color-header: gray !important; --color-secondary: yellow !important; } " `;
925
0
petrpan-code/facebook/docusaurus/packages/docusaurus-logger/src
petrpan-code/facebook/docusaurus/packages/docusaurus-logger/src/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import logger from '../index'; describe('formatters', () => { it('path', () => { expect(logger.path('keepAnsi')).toMatchInlineSnapshot( `"<cyan><underline>"keepAnsi"</underline></color>"`, ); }); it('url', () => { expect(logger.url('https://docusaurus.io/keepAnsi')).toMatchInlineSnapshot( `"<cyan><underline>https://docusaurus.io/keepAnsi</underline></color>"`, ); }); it('id', () => { expect(logger.name('keepAnsi')).toMatchInlineSnapshot( `"<blue><bold>keepAnsi</intensity></color>"`, ); }); it('code', () => { expect(logger.code('keepAnsi')).toMatchInlineSnapshot( `"<cyan>\`keepAnsi\`</color>"`, ); }); it('subdue', () => { expect(logger.subdue('keepAnsi')).toMatchInlineSnapshot( `"<gray>keepAnsi</color>"`, ); }); }); describe('interpolate', () => { it('formats text with variables & arrays', () => { const name = 'Josh'; const items = [1, 'hi', 'Hmmm']; expect( logger.interpolate`(keepAnsi) Hello ${name}! Here are your goodies:${items}`, ).toMatchInlineSnapshot(` "(keepAnsi) Hello Josh! Here are your goodies: - 1 - hi - Hmmm" `); }); it('recognizes valid flags', () => { expect( logger.interpolate`(keepAnsi) The package at path=${'packages/docusaurus'} has number=${10} files. name=${'Babel'} is exported here subdue=${'(as a preset)'} that you can with code=${"require.resolve('@docusaurus/core/lib/babel/preset')"}`, ).toMatchInlineSnapshot( `"(keepAnsi) The package at <cyan><underline>"packages/docusaurus"</underline></color> has <yellow>10</color> files. <blue><bold>Babel</intensity></color> is exported here <gray>(as a preset)</color> that you can with <cyan>\`require.resolve('@docusaurus/core/lib/babel/preset')\`</color>"`, ); }); it('interpolates arrays with flags', () => { expect( logger.interpolate`(keepAnsi) The following commands are available:code=${[ 'docusaurus start', 'docusaurus build', 'docusaurus deploy', ]}`, ).toMatchInlineSnapshot(` "(keepAnsi) The following commands are available: - <cyan>\`docusaurus start\`</color> - <cyan>\`docusaurus build\`</color> - <cyan>\`docusaurus deploy\`</color>" `); }); it('prints detached flags as-is', () => { expect( logger.interpolate`(keepAnsi) You can use placeholders like code= ${'and it will'} be replaced with the succeeding arguments`, ).toMatchInlineSnapshot( `"(keepAnsi) You can use placeholders like code= and it will be replaced with the succeeding arguments"`, ); }); it('throws with bad flags', () => { expect( () => logger.interpolate`(keepAnsi) I mistyped this: cde=${'this code'} and I will be damned`, ).toThrowErrorMatchingInlineSnapshot( `"Bad Docusaurus logging message. This is likely an internal bug, please report it."`, ); }); }); describe('info', () => { const consoleMock = jest.spyOn(console, 'info').mockImplementation(() => {}); it('prints objects', () => { logger.info({a: 1}); logger.info(undefined); logger.info([1, 2, 3]); logger.info(new Date(2021, 10, 13)); expect(consoleMock.mock.calls).toMatchSnapshot(); }); }); describe('warn', () => { const consoleMock = jest.spyOn(console, 'warn').mockImplementation(() => {}); it('prints objects', () => { logger.warn({a: 1}); logger.warn(undefined); logger.warn([1, 2, 3]); logger.warn(new Date(2021, 10, 13)); expect(consoleMock.mock.calls).toMatchSnapshot(); }); }); describe('error', () => { const consoleMock = jest.spyOn(console, 'error').mockImplementation(() => {}); it('prints objects', () => { logger.error({a: 1}); logger.error(undefined); logger.error([1, 2, 3]); logger.error(new Date(2021, 10, 13)); expect(consoleMock.mock.calls).toMatchSnapshot(); }); }); describe('success', () => { const consoleMock = jest.spyOn(console, 'log').mockImplementation(() => {}); it('prints objects', () => { logger.success({a: 1}); logger.success(undefined); logger.success([1, 2, 3]); logger.success(new Date(2021, 10, 13)); expect(consoleMock.mock.calls).toMatchSnapshot(); }); }); describe('report', () => { beforeAll(() => jest.clearAllMocks()); it('works with all severities', () => { const consoleLog = jest.spyOn(console, 'info').mockImplementation(() => {}); const consoleWarn = jest .spyOn(console, 'warn') .mockImplementation(() => {}); logger.report('ignore')('hey'); logger.report('log')('hey'); logger.report('warn')('hey'); expect(() => logger.report('throw')('hey'), ).toThrowErrorMatchingInlineSnapshot(`"hey"`); expect(() => // @ts-expect-error: for test logger.report('foo')('hey'), ).toThrowErrorMatchingInlineSnapshot( `"Unexpected "reportingSeverity" value: foo."`, ); expect(consoleLog).toHaveBeenCalledTimes(1); expect(consoleLog).toHaveBeenCalledWith( expect.stringMatching(/.*\[INFO\].* hey/), ); expect(consoleWarn).toHaveBeenCalledTimes(1); expect(consoleWarn).toHaveBeenCalledWith( expect.stringMatching(/.*\[WARNING\].* hey/), ); }); });
926
0
petrpan-code/facebook/docusaurus/packages/docusaurus-logger/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-logger/src/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`error prints objects 1`] = ` [ [ "[ERROR] {"a":1}", ], [ "[ERROR] undefined", ], [ "[ERROR] 1,2,3", ], [ "[ERROR] Sat, 13 Nov 2021 00:00:00 GMT", ], ] `; exports[`info prints objects 1`] = ` [ [ "[INFO] {"a":1}", ], [ "[INFO] undefined", ], [ "[INFO] 1,2,3", ], [ "[INFO] Sat, 13 Nov 2021 00:00:00 GMT", ], ] `; exports[`success prints objects 1`] = ` [ [ "[SUCCESS] {"a":1}", ], [ "[SUCCESS] undefined", ], [ "[SUCCESS] 1,2,3", ], [ "[SUCCESS] Sat, 13 Nov 2021 00:00:00 GMT", ], ] `; exports[`warn prints objects 1`] = ` [ [ "[WARNING] {"a":1}", ], [ "[WARNING] undefined", ], [ "[WARNING] 1,2,3", ], [ "[WARNING] Sat, 13 Nov 2021 00:00:00 GMT", ], ] `;
938
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/__tests__/format.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {getFormat} from '../format'; describe('getFormat', () => { it('uses frontMatter format over anything else', () => { expect( getFormat({ frontMatterFormat: 'md', filePath: 'xyz.md', markdownConfigFormat: 'mdx', }), ).toBe('md'); expect( getFormat({ frontMatterFormat: 'md', filePath: 'xyz.mdx', markdownConfigFormat: 'mdx', }), ).toBe('md'); expect( getFormat({ frontMatterFormat: 'mdx', filePath: 'xyz.md', markdownConfigFormat: 'md', }), ).toBe('mdx'); expect( getFormat({ frontMatterFormat: 'mdx', filePath: 'xyz.mdx', markdownConfigFormat: 'md', }), ).toBe('mdx'); }); it('supports "detects" for front matter', () => { expect( getFormat({ frontMatterFormat: 'detect', filePath: 'xyz.md', markdownConfigFormat: 'mdx', }), ).toBe('md'); expect( getFormat({ frontMatterFormat: 'detect', filePath: 'xyz.markdown', markdownConfigFormat: 'mdx', }), ).toBe('md'); expect( getFormat({ frontMatterFormat: 'detect', filePath: 'folder/xyz.md', markdownConfigFormat: 'mdx', }), ).toBe('md'); expect( getFormat({ frontMatterFormat: 'detect', filePath: 'folder/xyz.markdown', markdownConfigFormat: 'mdx', }), ).toBe('md'); expect( getFormat({ frontMatterFormat: 'detect', filePath: 'xyz.mdx', markdownConfigFormat: 'md', }), ).toBe('mdx'); expect( getFormat({ frontMatterFormat: 'detect', filePath: 'folder/xyz.mdx', markdownConfigFormat: 'md', }), ).toBe('mdx'); expect( getFormat({ frontMatterFormat: 'detect', filePath: 'xyz.unknown', markdownConfigFormat: 'md', }), ).toBe('mdx'); expect( getFormat({ frontMatterFormat: 'detect', filePath: 'folder/xyz.unknown', markdownConfigFormat: 'md', }), ).toBe('mdx'); }); it('fallbacks to markdown config format when front matter undefined', () => { expect( getFormat({ frontMatterFormat: undefined, filePath: 'xyz.md', markdownConfigFormat: 'mdx', }), ).toBe('mdx'); expect( getFormat({ frontMatterFormat: undefined, filePath: 'xyz.mdx', markdownConfigFormat: 'md', }), ).toBe('md'); expect( getFormat({ frontMatterFormat: undefined, filePath: 'xyz.md', markdownConfigFormat: 'detect', }), ).toBe('md'); expect( getFormat({ frontMatterFormat: undefined, filePath: 'xyz.mdx', markdownConfigFormat: 'detect', }), ).toBe('mdx'); }); });
939
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/__tests__/frontMatter.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import escapeStringRegexp from 'escape-string-regexp'; import { validateMDXFrontMatter, DefaultMDXFrontMatter, type MDXFrontMatter, } from '../frontMatter'; function testField(params: { prefix: string; validFrontMatters: MDXFrontMatter[]; convertibleFrontMatter?: [ ConvertibleFrontMatter: {[key: string]: unknown}, ConvertedFrontMatter: MDXFrontMatter, ][]; invalidFrontMatters?: [ InvalidFrontMatter: {[key: string]: unknown}, ErrorMessage: string, ][]; }) { // eslint-disable-next-line jest/require-top-level-describe test(`[${params.prefix}] accept valid values`, () => { params.validFrontMatters.forEach((frontMatter) => { expect(validateMDXFrontMatter(frontMatter)).toEqual(frontMatter); }); }); // eslint-disable-next-line jest/require-top-level-describe test(`[${params.prefix}] convert valid values`, () => { params.convertibleFrontMatter?.forEach( ([convertibleFrontMatter, convertedFrontMatter]) => { expect(validateMDXFrontMatter(convertibleFrontMatter)).toEqual( convertedFrontMatter, ); }, ); }); // eslint-disable-next-line jest/require-top-level-describe test(`[${params.prefix}] throw error for values`, () => { params.invalidFrontMatters?.forEach(([frontMatter, message]) => { try { validateMDXFrontMatter(frontMatter); throw new Error( `MDX front matter is expected to be rejected, but was accepted successfully:\n ${JSON.stringify( frontMatter, null, 2, )}`, ); } catch (err) { // eslint-disable-next-line jest/no-conditional-expect expect((err as Error).message).toMatch( new RegExp(escapeStringRegexp(message)), ); } }); }); } describe('MDX front matter schema', () => { it('accepts empty object', () => { const frontMatter: Partial<MDXFrontMatter> = {}; expect(validateMDXFrontMatter(frontMatter)).toEqual(DefaultMDXFrontMatter); }); it('accepts undefined object', () => { expect(validateMDXFrontMatter(undefined)).toEqual(DefaultMDXFrontMatter); }); it('rejects unknown field', () => { const frontMatter = {abc: '1'}; expect(() => validateMDXFrontMatter(frontMatter), ).toThrowErrorMatchingInlineSnapshot(`""abc" is not allowed"`); }); }); describe('validateDocFrontMatter format', () => { testField({ prefix: 'format', validFrontMatters: [ {}, {format: undefined}, {format: 'detect'}, {format: 'md'}, {format: 'mdx'}, ], invalidFrontMatters: [ [{format: 'xdm'}, '"format" must be one of [md, mdx, detect]'], [{format: ''}, '"format" must be one of [md, mdx, detect]'], [{format: null}, '"format" must be one of [md, mdx, detect]'], [{unknownAttribute: 'mdx'}, '"unknownAttribute" is not allowed'], ], }); });
940
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/__tests__/processor.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // import {createProcessor} from '../processor'; // import type {Options} from '../loader'; /* async function testProcess({ format, options, }: { format: 'md' | 'mdx'; options: Options; }) { return async (content: string) => { const processor = await createProcessor({format, options}); return processor.process(content); }; } */ describe('md processor', () => { it('parses simple commonmark', async () => { // TODO no tests for now, wait until ESM support // Jest does not support well ESM modules // It would require to vendor too much Unified modules as CJS // See https://mdxjs.com/docs/troubleshooting-mdx/#esm }); });
944
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/admonitions
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/admonitions/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import remark2rehype from 'remark-rehype'; import stringify from 'rehype-stringify'; import vfile from 'to-vfile'; import preprocessor from '../../../preprocessor'; import plugin, {DefaultAdmonitionOptions} from '../index'; import type {AdmonitionOptions} from '../index'; const processFixture = async ( name: string, options?: Partial<AdmonitionOptions>, ) => { const {remark} = await import('remark'); const {default: directives} = await import('remark-directive'); const filePath = path.join(__dirname, '__fixtures__', `${name}.md`); const file = await vfile.read(filePath); const fileContentPreprocessed = preprocessor({ fileContent: file.toString(), filePath, admonitions: DefaultAdmonitionOptions, markdownConfig: { mermaid: false, mdx1Compat: { admonitions: true, comments: false, headingIds: false, }, }, }); /* // TODO we shouldn't use rehype in these tests // this requires to re-implement admonitions with mdxJsxFlowElement const {default: mdx} = await import('remark-mdx'); const result = await remark() .use(directives) .use(plugin) .use(mdx) .process(fileContentPreprocessed); return result.value; */ const result = await remark() .use(directives) .use(plugin, options) .use(remark2rehype) .use(stringify) .process(fileContentPreprocessed); return result.value; }; describe('admonitions remark plugin', () => { it('base', async () => { const result = await processFixture('base'); await expect(result).toMatchSnapshot(); }); it('default behavior for custom keyword', async () => { const result = await processFixture('base', { keywords: ['tip'], extendDefaults: undefined, // By default we extend }); expect(result).toMatchSnapshot(); }); it('add custom keyword', async () => { const result = await processFixture('base', { keywords: ['tip'], extendDefaults: true, }); expect(result).toMatchSnapshot(); }); it('replace custom keyword', async () => { const result = await processFixture('base', { keywords: ['tip'], extendDefaults: false, }); expect(result).toMatchSnapshot(); }); it('interpolation', async () => { const result = await processFixture('interpolation'); expect(result).toMatchSnapshot(); }); it('nesting', async () => { const result = await processFixture('nesting'); expect(result).toMatchSnapshot(); }); });
948
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/admonitions/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/admonitions/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`admonitions remark plugin add custom keyword 1`] = ` "<p>The blog feature enables you to deploy in no time a full-featured blog.</p> <admonition title="Sample Title" type="info"><p>Check the <a href="./api/plugins/plugin-content-blog.md">Blog Plugin API Reference documentation</a> for an exhaustive list of options.</p></admonition> <h2>Initial setup {#initial-setup}</h2> <p>To set up your site's blog, start by creating a <code>blog</code> directory.</p> <admonition type="tip"><p>Use the <strong><a href="introduction.md#fast-track">Fast Track</a></strong> to understand Docusaurus in <strong>5 minutes ⏱</strong>!</p><p>Use <strong><a href="https://docusaurus.new">docusaurus.new</a></strong> to test Docusaurus immediately in your browser!</p></admonition> <p>++++tip</p> <p>Admonition with different syntax</p> <p>++++</p>" `; exports[`admonitions remark plugin base 1`] = ` "<p>The blog feature enables you to deploy in no time a full-featured blog.</p> <admonition title="Sample Title" type="info"><p>Check the <a href="./api/plugins/plugin-content-blog.md">Blog Plugin API Reference documentation</a> for an exhaustive list of options.</p></admonition> <h2>Initial setup {#initial-setup}</h2> <p>To set up your site's blog, start by creating a <code>blog</code> directory.</p> <admonition type="tip"><p>Use the <strong><a href="introduction.md#fast-track">Fast Track</a></strong> to understand Docusaurus in <strong>5 minutes ⏱</strong>!</p><p>Use <strong><a href="https://docusaurus.new">docusaurus.new</a></strong> to test Docusaurus immediately in your browser!</p></admonition> <p>++++tip</p> <p>Admonition with different syntax</p> <p>++++</p>" `; exports[`admonitions remark plugin default behavior for custom keyword 1`] = ` "<p>The blog feature enables you to deploy in no time a full-featured blog.</p> <div><p>Sample Title</p><p>Check the <a href="./api/plugins/plugin-content-blog.md">Blog Plugin API Reference documentation</a> for an exhaustive list of options.</p></div> <h2>Initial setup {#initial-setup}</h2> <p>To set up your site's blog, start by creating a <code>blog</code> directory.</p> <admonition type="tip"><p>Use the <strong><a href="introduction.md#fast-track">Fast Track</a></strong> to understand Docusaurus in <strong>5 minutes ⏱</strong>!</p><p>Use <strong><a href="https://docusaurus.new">docusaurus.new</a></strong> to test Docusaurus immediately in your browser!</p></admonition> <p>++++tip</p> <p>Admonition with different syntax</p> <p>++++</p>" `; exports[`admonitions remark plugin interpolation 1`] = ` "<p>Test admonition with interpolated title/body</p> <admonition type="tip"><mdxAdmonitionTitle>My <code>interpolated</code> <strong>title</strong> &#x3C;button style={{color: "red"}} onClick={() => alert("click")}>test</mdxAdmonitionTitle><p><code>body</code> <strong>interpolated</strong> content</p></admonition>" `; exports[`admonitions remark plugin nesting 1`] = ` "<p>Test nested Admonitions</p> <admonition type="info"><mdxAdmonitionTitle><strong>Weather</strong></mdxAdmonitionTitle><p>On nice days, you can enjoy skiing in the mountains.</p><admonition type="danger"><mdxAdmonitionTitle><em>Storms</em></mdxAdmonitionTitle><p>Take care of snowstorms...</p></admonition></admonition>" `; exports[`admonitions remark plugin replace custom keyword 1`] = ` "<p>The blog feature enables you to deploy in no time a full-featured blog.</p> <div><p>Sample Title</p><p>Check the <a href="./api/plugins/plugin-content-blog.md">Blog Plugin API Reference documentation</a> for an exhaustive list of options.</p></div> <h2>Initial setup {#initial-setup}</h2> <p>To set up your site's blog, start by creating a <code>blog</code> directory.</p> <admonition type="tip"><p>Use the <strong><a href="introduction.md#fast-track">Fast Track</a></strong> to understand Docusaurus in <strong>5 minutes ⏱</strong>!</p><p>Use <strong><a href="https://docusaurus.new">docusaurus.new</a></strong> to test Docusaurus immediately in your browser!</p></admonition> <p>++++tip</p> <p>Admonition with different syntax</p> <p>++++</p>" `;
950
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/contentTitle
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/contentTitle/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import plugin from '../index'; async function process( content: string, options: {removeContentTitle?: boolean} = {}, ) { const {remark} = await import('remark'); const processor = await remark().use({plugins: [[plugin, options]]}); return processor.process(content); } describe('contentTitle remark plugin', () => { describe('extracts data.contentTitle', () => { it('extracts h1 heading', async () => { const result = await process(` # contentTitle 1 ## Heading Two {#custom-heading-two} # contentTitle 2 some **markdown** *content* `); expect(result.data.contentTitle).toBe('contentTitle 1'); }); it('extracts h1 heading alt syntax', async () => { const result = await process(` contentTitle alt === # contentTitle 1 ## Heading Two {#custom-heading-two} # contentTitle 2 some **markdown** *content* `); expect(result.data.contentTitle).toBe('contentTitle alt'); }); it('works with no contentTitle', async () => { const result = await process(` ## Heading Two {#custom-heading-two} some **markdown** *content* `); expect(result.data.contentTitle).toBeUndefined(); }); it('ignore contentTitle if not in first position', async () => { const result = await process(` ## Heading Two {#custom-heading-two} # contentTitle 1 some **markdown** *content* `); expect(result.data.contentTitle).toBeUndefined(); }); it('is able to decently serialize Markdown syntax', async () => { const result = await process(` # some **markdown** \`content\` _italic_ some **markdown** *content* `); expect(result.data.contentTitle).toBe('some markdown content italic'); }); }); describe('returns appropriate content', () => { it('returns content unmodified', async () => { const content = ` # contentTitle 1 ## Heading Two {#custom-heading-two} # contentTitle 2 some **markdown** *content* `.trim(); const result = await process(content); expect(result.toString().trim()).toEqual(content); }); it('can strip contentTitle', async () => { const content = ` # contentTitle 1 ## Heading Two {#custom-heading-two} # contentTitle 2 some **markdown** *content* `.trim(); const result = await process(content, {removeContentTitle: true}); expect(result.toString().trim()).toEqual( ` ## Heading Two {#custom-heading-two} # contentTitle 2 some **markdown** *content* `.trim(), ); }); it('can strip contentTitle alt', async () => { const content = ` contentTitle alt === ## Heading Two {#custom-heading-two} # contentTitle 2 some **markdown** *content* `.trim(); const result = await process(content, {removeContentTitle: true}); expect(result.toString().trim()).toEqual( ` ## Heading Two {#custom-heading-two} # contentTitle 2 some **markdown** *content* `.trim(), ); }); }); });
952
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/details
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/details/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import details from '..'; async function process(content: string) { const {remark} = await import('remark'); const {default: mdx} = await import('remark-mdx'); const result = await remark().use(mdx).use(details).process(content); return result.value; } describe('details remark plugin', () => { it("does nothing if there's no details", async () => { const input = `# Heading 1 Some content `; const result = await process(input); expect(result).toEqual(result); }); it('can convert details', async () => { const input = `# Details element example <details> <summary>Toggle me!</summary> <div> <div>This is the detailed content</div> <br/> <details> <summary> Nested toggle! Some surprise inside... </summary> <div> 😲😲😲😲😲 </div> </details> </div> </details>`; const result = await process(input); expect(result).toMatchInlineSnapshot(` "# Details element example <Details> <summary>Toggle me!</summary> <div> <div>This is the detailed content</div> <br /> <Details> <summary> Nested toggle! Some surprise inside... </summary> <div> 😲😲😲😲😲 </div> </Details> </div> </Details> " `); }); });
954
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/head
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/head/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import head from '..'; async function process(content: string) { const {remark} = await import('remark'); const {default: mdx} = await import('remark-mdx'); const result = await remark().use(mdx).use(head).process(content); return result.value; } describe('head remark plugin', () => { it("does nothing if there's no details", async () => { const input = `# Heading <head> <html className="some-extra-html-class" /> <body className="other-extra-body-class" /> <title>Head Metadata customized title!</title> <meta charSet="utf-8" /> <meta name="twitter:card" content="summary" /> <link rel="canonical" href="https://docusaurus.io/docs/markdown-features/head-metadata" /> </head> Some content `; const result = await process(input); expect(result).toEqual(result); }); it('can convert head', async () => { const input = `# Heading <head> <html className="some-extra-html-class" /> <body className="other-extra-body-class" /> <title>Head Metadata customized title!</title> <meta charSet="utf-8" /> <meta name="twitter:card" content="summary" /> <link rel="canonical" href="https://docusaurus.io/docs/markdown-features/head-metadata" /> </head> Some content;`; const result = await process(input); expect(result).toMatchInlineSnapshot(` "# Heading <Head> <html className="some-extra-html-class" /> <body className="other-extra-body-class" /> <title>Head Metadata customized title!</title> <meta charSet="utf-8" /> <meta name="twitter:card" content="summary" /> <link rel="canonical" href="https://docusaurus.io/docs/markdown-features/head-metadata" /> </Head> Some content; " `); }); });
956
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/headings
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/headings/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* Based on remark-slug (https://github.com/remarkjs/remark-slug) and gatsby-remark-autolink-headers (https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-remark-autolink-headers) */ import u from 'unist-builder'; import {removePosition} from 'unist-util-remove-position'; import {toString} from 'mdast-util-to-string'; import {visit} from 'unist-util-visit'; import slug from '../index'; import type {Plugin} from 'unified'; import type {Parent} from 'unist'; async function process(doc: string, plugins: Plugin[] = []) { const {remark} = await import('remark'); const processor = await remark().use({plugins: [...plugins, slug]}); const result = await processor.run(processor.parse(doc)); removePosition(result, {force: true}); return result; } function heading(label: string | null, id: string) { return u( 'heading', {depth: 2, data: {id, hProperties: {id}}}, label ? [u('text', label)] : [], ); } describe('headings remark plugin', () => { it('patches `id`s and `data.hProperties.id', async () => { const result = await process('# Normal\n\n## Table of Contents\n\n# Baz\n'); const expected = u('root', [ u( 'heading', {depth: 1, data: {hProperties: {id: 'normal'}, id: 'normal'}}, [u('text', 'Normal')], ), u( 'heading', { depth: 2, data: { hProperties: {id: 'table-of-contents'}, id: 'table-of-contents', }, }, [u('text', 'Table of Contents')], ), u('heading', {depth: 1, data: {hProperties: {id: 'baz'}, id: 'baz'}}, [ u('text', 'Baz'), ]), ]); expect(result).toEqual(expected); }); it('does not overwrite `data` on headings', async () => { const result = await process('# Normal\n', [ () => (root) => { (root as Parent).children[0]!.data = {foo: 'bar'}; }, ]); const expected = u('root', [ u( 'heading', { depth: 1, data: {foo: 'bar', hProperties: {id: 'normal'}, id: 'normal'}, }, [u('text', 'Normal')], ), ]); expect(result).toEqual(expected); }); it('does not overwrite `data.hProperties` on headings', async () => { const result = await process('# Normal\n', [ () => (root) => { (root as Parent).children[0]!.data = { hProperties: {className: ['foo']}, }; }, ]); const expected = u('root', [ u( 'heading', { depth: 1, data: {hProperties: {className: ['foo'], id: 'normal'}, id: 'normal'}, }, [u('text', 'Normal')], ), ]); expect(result).toEqual(expected); }); it('generates `id`s and `hProperties.id`s, based on `hProperties.id` if they exist', async () => { const result = await process( [ '## Something', '## Something here', '## Something there', '## Something also', ].join('\n\n'), [ () => (root) => { (root as Parent).children[1]!.data = {hProperties: {id: 'here'}}; (root as Parent).children[3]!.data = {hProperties: {id: 'something'}}; }, ], ); const expected = u('root', [ u( 'heading', { depth: 2, data: {hProperties: {id: 'something'}, id: 'something'}, }, [u('text', 'Something')], ), u( 'heading', { depth: 2, data: {hProperties: {id: 'here'}, id: 'here'}, }, [u('text', 'Something here')], ), u( 'heading', { depth: 2, data: {hProperties: {id: 'something-there'}, id: 'something-there'}, }, [u('text', 'Something there')], ), u( 'heading', { depth: 2, data: {hProperties: {id: 'something-1'}, id: 'something-1'}, }, [u('text', 'Something also')], ), ]); expect(result).toEqual(expected); }); it('creates GitHub-style headings ids', async () => { const result = await process( [ '## I ♥ unicode', '', '## Dash-dash', '', '## en–dash', '', '## em–dash', '', '## 😄 unicode emoji', '', '## 😄-😄 unicode emoji', '', '## 😄_😄 unicode emoji', '', '##', '', '## ', '', '## Initial spaces', '', '## Final spaces ', '', '## Duplicate', '', '## Duplicate', '', '## :ok: No underscore', '', '## :ok_hand: Single', '', '## :ok_hand::hatched_chick: Two in a row with no spaces', '', '## :ok_hand: :hatched_chick: Two in a row', '', ].join('\n'), ); const expected = u('root', [ heading('I ♥ unicode', 'i--unicode'), heading('Dash-dash', 'dash-dash'), // cSpell:ignore endash heading('en–dash', 'endash'), // cSpell:ignore emdash heading('em–dash', 'emdash'), heading('😄 unicode emoji', '-unicode-emoji'), heading('😄-😄 unicode emoji', '--unicode-emoji'), heading('😄_😄 unicode emoji', '_-unicode-emoji'), heading(null, ''), heading(null, '-1'), heading('Initial spaces', 'initial-spaces'), heading('Final spaces', 'final-spaces'), heading('Duplicate', 'duplicate'), heading('Duplicate', 'duplicate-1'), heading(':ok: No underscore', 'ok-no-underscore'), heading(':ok_hand: Single', 'ok_hand-single'), heading( ':ok_hand::hatched_chick: Two in a row with no spaces', // cSpell:ignore handhatched 'ok_handhatched_chick-two-in-a-row-with-no-spaces', ), heading( ':ok_hand: :hatched_chick: Two in a row', 'ok_hand-hatched_chick-two-in-a-row', ), ]); expect(result).toEqual(expected); }); it('generates id from only text contents of headings if they contains HTML tags', async () => { const result = await process( '# <span class="normal-header">Normal</span>\n', ); const expected = u('root', [ u( 'heading', { depth: 1, data: {hProperties: {id: 'normal'}, id: 'normal'}, }, [ u('html', '<span class="normal-header">'), u('text', 'Normal'), u('html', '</span>'), ], ), ]); expect(result).toEqual(expected); }); it('creates custom headings ids', async () => { const result = await process(` # Heading One {#custom_h1} ## Heading Two {#custom-heading-two} # With *Bold* {#custom-with-bold} # With *Bold* hello{#custom-with-bold-hello} # With *Bold* hello2 {#custom-with-bold-hello2} # Snake-cased ID {#this_is_custom_id} # No custom ID # {#id-only} # {#text-after} custom ID `); const headers: {text: string; id: string}[] = []; visit(result, 'heading', (node) => { headers.push({text: toString(node), id: node.data!.id as string}); }); expect(headers).toEqual([ { id: 'custom_h1', text: 'Heading One', }, { id: 'custom-heading-two', text: 'Heading Two', }, { id: 'custom-with-bold', text: 'With Bold', }, { id: 'custom-with-bold-hello', text: 'With Bold hello', }, { id: 'custom-with-bold-hello2', text: 'With Bold hello2', }, { id: 'this_is_custom_id', text: 'Snake-cased ID', }, { id: 'no-custom-id', text: 'No custom ID', }, { id: 'id-only', text: '', }, { id: 'text-after-custom-id', text: '{#text-after} custom ID', }, ]); }); });
959
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/mermaid
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/mermaid/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import remark2rehype from 'remark-rehype'; import stringify from 'rehype-stringify'; import mermaid from '..'; async function process(content: string) { const {remark} = await import('remark'); // const {default: mdx} = await import('remark-mdx'); // const result = await remark().use(mermaid).use(mdx).process(content); const result = await remark() .use(mermaid) .use(remark2rehype) .use(stringify) .process(content); return result.value; } describe('mermaid remark plugin', () => { it("does nothing if there's no mermaid code block", async () => { const result = await process( `# Heading 1 No Mermaid diagram :( \`\`\`js this is not mermaid \`\`\` `, ); expect(result).toMatchInlineSnapshot(` "<h1>Heading 1</h1> <p>No Mermaid diagram :(</p> <pre><code class="language-js">this is not mermaid </code></pre>" `); }); it('works for basic mermaid code blocks', async () => { const result = await process(`# Heading 1 \`\`\`mermaid graph TD; A-->B; A-->C; B-->D; C-->D; \`\`\``); expect(result).toMatchInlineSnapshot(` "<h1>Heading 1</h1> <mermaid value="graph TD; A-->B; A-->C; B-->D; C-->D;"></mermaid>" `); }); });
961
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/toc
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/toc/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import vfile from 'to-vfile'; import plugin from '../index'; import headings from '../../headings/index'; const processFixture = async (name: string) => { const {remark} = await import('remark'); const {default: gfm} = await import('remark-gfm'); const {default: mdx} = await import('remark-mdx'); const filePath = path.join(__dirname, '__fixtures__', `${name}.md`); const file = await vfile.read(filePath); const result = await remark() .use(headings) .use(gfm) .use(mdx) .use(plugin) .process(file); return result.value; }; describe('toc remark plugin', () => { it('outputs empty array for no TOC', async () => { const result = await processFixture('no-heading'); expect(result).toMatchSnapshot(); }); // A very implicit API: we allow users to hand-write the toc variable. It will // get overwritten in most cases, but until we find a better way, better keep // supporting this it('does not overwrite TOC var if no TOC', async () => { const result = await processFixture('no-heading-with-toc-export'); expect(result).toMatchSnapshot(); }); it('works on non text phrasing content', async () => { const result = await processFixture('non-text-content'); expect(result).toMatchSnapshot(); }); it('escapes inline code', async () => { const result = await processFixture('inline-code'); expect(result).toMatchSnapshot(); }); it('works on text content', async () => { const result = await processFixture('just-content'); expect(result).toMatchSnapshot(); }); it('exports even with existing name', async () => { const result = await processFixture('name-exist'); expect(result).toMatchSnapshot(); }); it('inserts below imports', async () => { const result = await processFixture('insert-below-imports'); expect(result).toMatchSnapshot(); }); it('handles empty headings', async () => { const result = await processFixture('empty-headings'); expect(result).toMatchSnapshot(); }); });
970
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/toc/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/toc/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`toc remark plugin does not overwrite TOC var if no TOC 1`] = ` "foo \`bar\` \`\`\`js baz \`\`\` export const toc = 1; " `; exports[`toc remark plugin escapes inline code 1`] = ` "export const toc = [ { value: '<code>&lt;Head /&gt;</code>', id: 'head-', level: 2 }, { value: '<code>&lt;Head&gt;Test&lt;/Head&gt;</code>', id: 'headtesthead', level: 3 }, { value: '<code>&lt;div /&gt;</code>', id: 'div-', level: 2 }, { value: '<code>&lt;div&gt; Test &lt;/div&gt;</code>', id: 'div-test-div', level: 2 }, { value: '<code>&lt;div&gt;&lt;i&gt;Test&lt;/i&gt;&lt;/div&gt;</code>', id: 'divitestidiv', level: 2 }, { value: '<code>&lt;div&gt;&lt;i&gt;Test&lt;/i&gt;&lt;/div&gt;</code>', id: 'divitestidiv-1', level: 2 } ] ## \`<Head />\` ### \`<Head>Test</Head>\` ## \`<div />\` ## \`<div> Test </div>\` ## \`<div><i>Test</i></div>\` ## [\`<div><i>Test</i></div>\`](/some/link) " `; exports[`toc remark plugin exports even with existing name 1`] = ` "export const toc = [ { value: 'Thanos', id: 'thanos', level: 2 }, { value: 'Tony Stark', id: 'tony-stark', level: 2 }, { value: 'Avengers', id: 'avengers', level: 3 } ] ## Thanos ## Tony Stark ### Avengers " `; exports[`toc remark plugin handles empty headings 1`] = ` "export const toc = [] # Ignore this ## ## ![](an-image.svg) " `; exports[`toc remark plugin inserts below imports 1`] = ` "import something from 'something'; import somethingElse from 'something-else'; export const toc = [ { value: 'Title', id: 'title', level: 2 }, { value: 'Test', id: 'test', level: 2 }, { value: 'Again', id: 'again', level: 3 } ] ## Title ## Test ### Again Content. " `; exports[`toc remark plugin outputs empty array for no TOC 1`] = ` "export const toc = [] foo \`bar\` \`\`\`js baz \`\`\` " `; exports[`toc remark plugin works on non text phrasing content 1`] = ` "export const toc = [ { value: '<em>Emphasis</em>', id: 'emphasis', level: 2 }, { value: '<strong>Importance</strong>', id: 'importance', level: 3 }, { value: '<del>Strikethrough</del>', id: 'strikethrough', level: 2 }, { value: '<i>HTML</i>', id: 'html', level: 2 }, { value: '<code>inline.code()</code>', id: 'inlinecode', level: 2 }, { value: 'some <span class="some-class">styled</span> <strong>heading</strong> <span class="myClassName &lt;&gt; weird char"></span> test', id: 'some-styled-heading--test', level: 2 } ] ## *Emphasis* ### **Importance** ## ~~Strikethrough~~ ## <i>HTML</i> ## \`inline.code()\` ## some <span className="some-class" style={{border: "solid"}}>styled</span> <strong>heading</strong> <span class="myClass" className="myClassName <> weird char" data-random-attr="456" /> test " `; exports[`toc remark plugin works on text content 1`] = ` "export const toc = [ { value: 'Endi', id: 'endi', level: 3 }, { value: 'Endi', id: 'endi-1', level: 2 }, { value: 'Yangshun', id: 'yangshun', level: 3 }, { value: 'I ♥ unicode.', id: 'i--unicode', level: 2 } ] ### Endi \`\`\`md ## This is ignored \`\`\` ## Endi Lorem ipsum ### Yangshun Some content here ## I ♥ unicode. export const c = 1; " `;
972
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/transformImage
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import vfile from 'to-vfile'; import plugin, {type PluginOptions} from '../index'; const processFixture = async ( name: string, options: Partial<PluginOptions>, ) => { const {remark} = await import('remark'); const {default: mdx} = await import('remark-mdx'); const filePath = path.join(__dirname, `__fixtures__/${name}.md`); const file = await vfile.read(filePath); const result = await remark() .use(mdx) .use(plugin, {siteDir: __dirname, staticDirs: [], ...options}) .process(file); return result.value; }; const staticDirs = [ path.join(__dirname, '__fixtures__/static'), path.join(__dirname, '__fixtures__/static2'), ]; const siteDir = path.join(__dirname, '__fixtures__'); describe('transformImage plugin', () => { it('fail if image does not exist', async () => { await expect( processFixture('fail', {staticDirs}), ).rejects.toThrowErrorMatchingSnapshot(); }); it('fail if image relative path does not exist', async () => { await expect( processFixture('fail2', {staticDirs}), ).rejects.toThrowErrorMatchingSnapshot(); }); it('fail if image url is absent', async () => { await expect( processFixture('noUrl', {staticDirs}), ).rejects.toThrowErrorMatchingSnapshot(); }); it('transform md images to <img />', async () => { const result = await processFixture('img', {staticDirs, siteDir}); expect(result).toMatchSnapshot(); }); it('pathname protocol', async () => { const result = await processFixture('pathname', {staticDirs}); expect(result).toMatchSnapshot(); }); it('does not choke on invalid image', async () => { const errorMock = jest.spyOn(console, 'warn').mockImplementation(() => {}); const result = await processFixture('invalid-img', {staticDirs}); expect(result).toMatchSnapshot(); expect(errorMock).toHaveBeenCalledTimes(1); }); });
979
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`transformImage plugin does not choke on invalid image 1`] = ` "<img alt="invalid image" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/invalid.png").default} /> " `; exports[`transformImage plugin fail if image does not exist 1`] = `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static/img/doesNotExist.png or packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/static2/img/doesNotExist.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail.md not found."`; exports[`transformImage plugin fail if image relative path does not exist 1`] = `"Image packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/notFound.png used in packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/fail2.md not found."`; exports[`transformImage plugin fail if image url is absent 1`] = `"Markdown image URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformImage/__tests__/__fixtures__/noUrl.md" file"`; exports[`transformImage plugin pathname protocol 1`] = ` "![img](/img/unchecked.png) " `; exports[`transformImage plugin transform md images to <img /> 1`] = ` "![img](https://example.com/img.png) <img src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/img.png").default} width="200" height="200" /> <img alt="img" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/img.png").default} width="200" height="200" /> in paragraph <img alt="img" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/img.png").default} width="200" height="200" /> <img alt="img from second static folder" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static2/img2.png").default} width="256" height="82" /> <img alt="img from second static folder" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static2/img2.png").default} width="256" height="82" /> <img alt="img with URL encoded chars" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static2/img2 copy.png").default} width="256" height="82" /> <img alt="img" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/img.png").default} title="Title" width="200" height="200" /> <img alt="img" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/img.png").default} width="200" height="200" /> !/[img with "quotes"]/(./static/img.png ''Quoted' title') <img alt="site alias" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/img.png").default} width="200" height="200" /> <img alt="img with hash" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/img.png").default + '#light'} width="200" height="200" /> <img alt="img with hash" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/img.png").default + '#dark'} width="200" height="200" /> <img alt="img with query" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/img.png?w=10").default} width="200" height="200" /> <img alt="img with query" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/img.png?w=10&h=10").default} width="200" height="200" /> <img alt="img with both" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/img.png?w=10&h=10").default + '#light'} width="200" height="200" /> ## Heading \`\`\`md ![img](./static/img.png) \`\`\` " `;
981
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/transformLinks
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import vfile from 'to-vfile'; import plugin from '..'; import transformImage, {type PluginOptions} from '../../transformImage'; const processFixture = async (name: string, options?: PluginOptions) => { const {remark} = await import('remark'); const {default: mdx} = await import('remark-mdx'); const siteDir = path.join(__dirname, `__fixtures__`); const staticDirs = [ path.join(siteDir, 'static'), path.join(siteDir, 'static2'), ]; const file = await vfile.read(path.join(siteDir, `${name}.md`)); const result = await remark() .use(mdx) .use(transformImage, {...options, siteDir, staticDirs}) .use(plugin, { ...options, staticDirs, siteDir: path.join(__dirname, '__fixtures__'), }) .process(file); return result.value; }; describe('transformAsset plugin', () => { it('fail if asset url is absent', async () => { await expect( processFixture('noUrl'), ).rejects.toThrowErrorMatchingSnapshot(); }); it('fail if asset with site alias does not exist', async () => { await expect( processFixture('nonexistentSiteAlias'), ).rejects.toThrowErrorMatchingSnapshot(); }); it('transform md links to <a />', async () => { const result = await processFixture('asset'); expect(result).toMatchSnapshot(); }); it('pathname protocol', async () => { const result = await processFixture('pathname'); expect(result).toMatchSnapshot(); }); });
988
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`transformAsset plugin fail if asset url is absent 1`] = `"Markdown link URL is mandatory in "packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/noUrl.md" file (title: asset, line: 1)."`; exports[`transformAsset plugin fail if asset with site alias does not exist 1`] = `"Asset packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/foo.pdf used in packages/docusaurus-mdx-loader/src/remark/transformLinks/__tests__/__fixtures__/nonexistentSiteAlias.md not found."`; exports[`transformAsset plugin pathname protocol 1`] = ` "[asset](pathname:///asset/unchecked.pdf) " `; exports[`transformAsset plugin transform md links to <a /> 1`] = ` "[asset](https://example.com/asset.pdf) <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./asset.pdf").default} /> <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./asset.pdf").default}>asset</a> in paragraph <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./asset.pdf").default}>asset</a> <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./asset (2).pdf").default}>asset with URL encoded chars</a> <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./asset.pdf").default + '#page=2'}>asset with hash</a> <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./asset.pdf").default} title="Title">asset</a> [page](noUrl.md) ## Heading \`\`\`md [asset](./asset.pdf) \`\`\` [assets](!file-loader!./asset.pdf) [assets](/github/!file-loader!/assets.pdf) <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./asset.pdf").default}>asset</a> <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./static2/asset2.pdf").default}>asset2</a> <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./static/staticAsset.pdf").default}>staticAsset.pdf</a> <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./static/staticAsset.pdf").default}>@site/static/staticAsset.pdf</a> <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./static/staticAsset.pdf").default + '#page=2'} title="Title">@site/static/staticAsset.pdf</a> <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./static/staticAsset.pdf").default}>Just staticAsset.pdf</a>, and <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./static/staticAsset.pdf").default}>**awesome** staticAsset 2.pdf 'It is really "AWESOME"'</a>, but also <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./static/staticAsset.pdf").default}>coded \`staticAsset 3.pdf\`</a> <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./static/staticAssetImage.png").default}><img alt="Clickable Docusaurus logo" src={require("!<PROJECT_ROOT>/node_modules/url-loader/dist/cjs.js?limit=10000&name=assets/images/[name]-[contenthash].[ext]&fallback=<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js!./static/staticAssetImage.png").default} width="200" height="200" /></a> <a target="_blank" href={require("!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./asset.pdf").default}><span style={{color: "red"}}>Stylized link to asset file</span></a> <a target="_blank" href={require("./data.raw!=!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./data.json").default}>JSON</a> <a target="_blank" href={require("./static/static-json.raw!=!<PROJECT_ROOT>/node_modules/file-loader/dist/cjs.js?name=assets/files/[name]-[contenthash].[ext]!./static/static-json.json").default}>static JSON</a> " `;
990
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/unusedDirectives
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/unusedDirectives/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import remark2rehype from 'remark-rehype'; import stringify from 'rehype-stringify'; import vfile from 'to-vfile'; import plugin from '../index'; import admonition from '../../admonitions'; import type {WebpackCompilerName} from '@docusaurus/utils'; const processFixture = async ( name: string, {compilerName}: {compilerName: WebpackCompilerName}, ) => { const {remark} = await import('remark'); const {default: directives} = await import('remark-directive'); const filePath = path.join(__dirname, '__fixtures__', `${name}.md`); const file = await vfile.read(filePath); file.data.compilerName = compilerName; const result = await remark() .use(directives) .use(admonition) .use(plugin) .use(remark2rehype) .use(stringify) .process(file); return result.value; }; describe('directives remark plugin - client compiler', () => { const consoleMock = jest.spyOn(console, 'warn').mockImplementation(() => {}); beforeEach(() => jest.clearAllMocks()); const options = {compilerName: 'client'} as const; it('default behavior for container directives', async () => { const result = await processFixture('containerDirectives', options); expect(result).toMatchSnapshot('result'); expect(consoleMock).toHaveBeenCalledTimes(1); expect(consoleMock.mock.calls).toMatchSnapshot('console'); }); it('default behavior for leaf directives', async () => { const result = await processFixture('leafDirectives', options); expect(result).toMatchSnapshot('result'); expect(consoleMock).toHaveBeenCalledTimes(1); expect(consoleMock.mock.calls).toMatchSnapshot('console'); }); it('default behavior for text directives', async () => { const result = await processFixture('textDirectives', options); expect(result).toMatchSnapshot('result'); expect(consoleMock).toHaveBeenCalledTimes(1); expect(consoleMock.mock.calls).toMatchSnapshot('console'); }); }); describe('directives remark plugin - server compiler', () => { const consoleMock = jest.spyOn(console, 'warn').mockImplementation(() => {}); beforeEach(() => jest.clearAllMocks()); const options = {compilerName: 'server'} as const; it('default behavior for container directives', async () => { const result = await processFixture('containerDirectives', options); expect(result).toMatchSnapshot('result'); expect(consoleMock).toHaveBeenCalledTimes(0); }); it('default behavior for leaf directives', async () => { const result = await processFixture('leafDirectives', options); expect(result).toMatchSnapshot('result'); expect(consoleMock).toHaveBeenCalledTimes(0); }); it('default behavior for text directives', async () => { const result = await processFixture('textDirectives', options); expect(result).toMatchSnapshot('result'); expect(consoleMock).toHaveBeenCalledTimes(0); }); }); describe('directives remark plugin - client result === server result', () => { // It is important that client/server outputs are exactly the same // otherwise React hydration mismatches can occur async function testSameResult(name: string) { const resultClient = await processFixture(name, {compilerName: 'client'}); const resultServer = await processFixture(name, {compilerName: 'server'}); expect(resultClient).toEqual(resultServer); } it('for containerDirectives', async () => { await testSameResult('containerDirectives'); }); it('for leafDirectives', async () => { await testSameResult('leafDirectives'); }); it('for textDirectives', async () => { await testSameResult('textDirectives'); }); });
994
0
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/unusedDirectives/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-mdx-loader/src/remark/unusedDirectives/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`directives remark plugin - client compiler default behavior for container directives: console 1`] = ` [ [ "[WARNING] Docusaurus found 1 unused Markdown directives in file "packages/docusaurus-mdx-loader/src/remark/unusedDirectives/__tests__/__fixtures__/containerDirectives.md" - :::unusedDirective (7:1) Your content might render in an unexpected way. Visit https://github.com/facebook/docusaurus/pull/9394 to find out why and how to fix it.", ], ] `; exports[`directives remark plugin - client compiler default behavior for container directives: result 1`] = ` "<admonition type="danger"><p>Take care of snowstorms...</p></admonition> <div><p>unused directive content</p></div> <p>:::NotAContainerDirective with a phrase after</p> <p>:::</p> <p>Phrase before :::NotAContainerDirective</p> <p>:::</p>" `; exports[`directives remark plugin - client compiler default behavior for leaf directives: console 1`] = ` [ [ "[WARNING] Docusaurus found 1 unused Markdown directives in file "packages/docusaurus-mdx-loader/src/remark/unusedDirectives/__tests__/__fixtures__/leafDirectives.md" - ::unusedLeafDirective (1:1) Your content might render in an unexpected way. Visit https://github.com/facebook/docusaurus/pull/9394 to find out why and how to fix it.", ], ] `; exports[`directives remark plugin - client compiler default behavior for leaf directives: result 1`] = ` "<div></div> <p>Leaf directive in a phrase ::NotALeafDirective</p> <p>::NotALeafDirective with a phrase after</p>" `; exports[`directives remark plugin - client compiler default behavior for text directives: console 1`] = ` [ [ "[WARNING] Docusaurus found 2 unused Markdown directives in file "packages/docusaurus-mdx-loader/src/remark/unusedDirectives/__tests__/__fixtures__/textDirectives.md" - :textDirective3 (9:7) - :textDirective4 (11:7) Your content might render in an unexpected way. Visit https://github.com/facebook/docusaurus/pull/9394 to find out why and how to fix it.", ], ] `; exports[`directives remark plugin - client compiler default behavior for text directives: result 1`] = ` "<p>Simple: textDirective1</p> <pre><code class="language-sh">Simple: textDirectiveCode </code></pre> <p>Simple:textDirective2</p> <p>Simple<div>label</div></p> <p>Simple<div></div></p> <p>Simple:textDirective5</p> <pre><code class="language-sh">Simple:textDirectiveCode </code></pre>" `; exports[`directives remark plugin - server compiler default behavior for container directives: result 1`] = ` "<admonition type="danger"><p>Take care of snowstorms...</p></admonition> <div><p>unused directive content</p></div> <p>:::NotAContainerDirective with a phrase after</p> <p>:::</p> <p>Phrase before :::NotAContainerDirective</p> <p>:::</p>" `; exports[`directives remark plugin - server compiler default behavior for leaf directives: result 1`] = ` "<div></div> <p>Leaf directive in a phrase ::NotALeafDirective</p> <p>::NotALeafDirective with a phrase after</p>" `; exports[`directives remark plugin - server compiler default behavior for text directives: result 1`] = ` "<p>Simple: textDirective1</p> <pre><code class="language-sh">Simple: textDirectiveCode </code></pre> <p>Simple:textDirective2</p> <p>Simple<div>label</div></p> <p>Simple<div></div></p> <p>Simple:textDirective5</p> <pre><code class="language-sh">Simple:textDirectiveCode </code></pre>" `;
1,012
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__/collectRedirects.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {removeTrailingSlash} from '@docusaurus/utils'; import {normalizePluginOptions} from '@docusaurus/utils-validation'; import collectRedirects from '../collectRedirects'; import {validateOptions} from '../options'; import type {DocusaurusConfig} from '@docusaurus/types'; import type {Options} from '../options'; import type {PluginContext} from '../types'; function createTestPluginContext( options?: Options, relativeRoutesPaths: string[] = [], siteConfig: Partial<DocusaurusConfig> = {}, ): PluginContext { return { outDir: '/tmp', baseUrl: 'https://docusaurus.io', relativeRoutesPaths, options: validateOptions({validate: normalizePluginOptions, options}), siteConfig: {onDuplicateRoutes: 'warn', ...siteConfig} as DocusaurusConfig, }; } describe('collectRedirects', () => { it('collects no redirect for undefined config', () => { expect( collectRedirects( createTestPluginContext(undefined, ['/', '/path']), undefined, ), ).toEqual([]); }); it('collects no redirect for empty config', () => { expect(collectRedirects(createTestPluginContext({}), undefined)).toEqual( [], ); }); it('collects redirects from html/exe extension', () => { expect( collectRedirects( createTestPluginContext( { fromExtensions: ['html', 'exe'], }, ['/', '/somePath', '/otherPath.html'], ), undefined, ), ).toEqual([ { from: '/somePath.html', to: '/somePath', }, { from: '/somePath.exe', to: '/somePath', }, ]); }); it('collects redirects to html/exe extension', () => { expect( collectRedirects( createTestPluginContext( { toExtensions: ['html', 'exe'], }, ['/', '/somePath', '/otherPath.html'], ), undefined, ), ).toEqual([ { from: '/otherPath', to: '/otherPath.html', }, ]); }); it('collects redirects from plugin option redirects', () => { expect( collectRedirects( createTestPluginContext( { redirects: [ { from: '/someLegacyPath', to: '/somePath', }, { from: '/someLegacyPath2', to: '/some Path2', }, { from: '/someLegacyPath3', to: '/some%20Path3', }, { from: ['/someLegacyPathArray1', '/someLegacyPathArray2'], to: '/', }, { from: '/localQS', to: '/somePath?a=1&b=2', }, { from: '/localAnchor', to: '/somePath#anchor', }, { from: '/localQSAnchor', to: '/somePath?a=1&b=2#anchor', }, { from: '/absolute', to: 'https://docusaurus.io/somePath', }, { from: '/absoluteQS', to: 'https://docusaurus.io/somePath?a=1&b=2', }, { from: '/absoluteAnchor', to: 'https://docusaurus.io/somePath#anchor', }, { from: '/absoluteQSAnchor', to: 'https://docusaurus.io/somePath?a=1&b=2#anchor', }, ], }, ['/', '/somePath', '/some%20Path2', '/some Path3'], ), undefined, ), ).toEqual([ { from: '/someLegacyPath', to: '/somePath', }, { from: '/someLegacyPath2', to: '/some Path2', }, { from: '/someLegacyPath3', to: '/some%20Path3', }, { from: '/someLegacyPathArray1', to: '/', }, { from: '/someLegacyPathArray2', to: '/', }, { from: '/localQS', to: '/somePath?a=1&b=2', }, { from: '/localAnchor', to: '/somePath#anchor', }, { from: '/localQSAnchor', to: '/somePath?a=1&b=2#anchor', }, { from: '/absolute', to: 'https://docusaurus.io/somePath', }, { from: '/absoluteQS', to: 'https://docusaurus.io/somePath?a=1&b=2', }, { from: '/absoluteAnchor', to: 'https://docusaurus.io/somePath#anchor', }, { from: '/absoluteQSAnchor', to: 'https://docusaurus.io/somePath?a=1&b=2#anchor', }, ]); }); it('collects redirects from plugin option redirects with trailingSlash=true', () => { expect( collectRedirects( createTestPluginContext( { redirects: [ { from: '/someLegacyPath', to: '/somePath', }, { from: ['/someLegacyPathArray1', '/someLegacyPathArray2'], to: '/', }, ], }, ['/', '/somePath/'], ), true, ), ).toEqual([ { from: '/someLegacyPath', to: '/somePath/', }, { from: '/someLegacyPathArray1', to: '/', }, { from: '/someLegacyPathArray2', to: '/', }, ]); }); it('collects redirects from plugin option redirects with trailingSlash=false', () => { expect( collectRedirects( createTestPluginContext( { redirects: [ { from: '/someLegacyPath', to: '/somePath/', }, { from: ['/someLegacyPathArray1', '/someLegacyPathArray2'], to: '/', }, ], }, ['/', '/somePath'], ), false, ), ).toEqual([ { from: '/someLegacyPath', to: '/somePath', }, { from: '/someLegacyPathArray1', to: '/', }, { from: '/someLegacyPathArray2', to: '/', }, ]); }); it('throw if plugin option redirects contain invalid to paths', () => { expect(() => collectRedirects( createTestPluginContext( { redirects: [ { from: '/someLegacyPath', to: '/', }, { from: '/someLegacyPath', to: '/this/path/does/not/exist2', }, { from: '/someLegacyPath', to: '/this/path/does/not/exist3', }, { from: '/someLegacyPath', to: '/this/path/does/not/exist4?a=b#anchor', }, ], }, ['/', '/someExistingPath', '/anotherExistingPath'], ), undefined, ), ).toThrowErrorMatchingSnapshot(); }); it('tolerates mismatched trailing slash if option is undefined', () => { expect( collectRedirects( createTestPluginContext( { redirects: [ { from: '/someLegacyPath', to: '/somePath', }, ], }, ['/', '/somePath/'], {trailingSlash: undefined}, ), undefined, ), ).toEqual([ { from: '/someLegacyPath', to: '/somePath', }, ]); }); it('throw if plugin option redirects contain to paths with mismatching trailing slash', () => { expect(() => collectRedirects( createTestPluginContext( { redirects: [ { from: '/someLegacyPath', to: '/someExistingPath/', }, ], }, ['/', '/someExistingPath', '/anotherExistingPath'], {trailingSlash: false}, ), undefined, ), ).toThrowErrorMatchingSnapshot(); expect(() => collectRedirects( createTestPluginContext( { redirects: [ { from: '/someLegacyPath', to: '/someExistingPath', }, ], }, ['/', '/someExistingPath/', '/anotherExistingPath/'], {trailingSlash: true}, ), undefined, ), ).toThrowErrorMatchingSnapshot(); }); it('collects redirects with custom redirect creator', () => { expect( collectRedirects( createTestPluginContext( { createRedirects: (routePath) => [ `${removeTrailingSlash(routePath)}/some/path/suffix1`, `${removeTrailingSlash(routePath)}/some/other/path/suffix2`, ], }, ['/', '/testPath', '/otherPath.html'], ), undefined, ), ).toEqual([ { from: '/some/path/suffix1', to: '/', }, { from: '/some/other/path/suffix2', to: '/', }, { from: '/testPath/some/path/suffix1', to: '/testPath', }, { from: '/testPath/some/other/path/suffix2', to: '/testPath', }, { from: '/otherPath.html/some/path/suffix1', to: '/otherPath.html', }, { from: '/otherPath.html/some/other/path/suffix2', to: '/otherPath.html', }, ]); }); it('allows returning string / undefined', () => { expect( collectRedirects( createTestPluginContext( { createRedirects: (routePath) => { if (routePath === '/') { return `${routePath}foo`; } return undefined; }, }, ['/', '/testPath', '/otherPath.html'], ), undefined, ), ).toEqual([{from: '/foo', to: '/'}]); }); it('throws if redirect creator creates invalid redirects', () => { expect(() => collectRedirects( createTestPluginContext( { createRedirects: (routePath) => { if (routePath === '/') { return [ `https://google.com/`, `//abc`, `/def?queryString=toto`, ]; } return undefined; }, }, ['/'], ), undefined, ), ).toThrowErrorMatchingSnapshot(); }); it('throws if redirect creator creates array of array redirect', () => { expect(() => collectRedirects( createTestPluginContext( { // @ts-expect-error: for test createRedirects(routePath) { if (routePath === '/') { return [[`/fromPath`]]; } return undefined; }, }, ['/'], ), undefined, ), ).toThrowErrorMatchingSnapshot(); }); it('filters unwanted redirects', () => { expect( collectRedirects( createTestPluginContext( { fromExtensions: ['html', 'exe'], toExtensions: ['html', 'exe'], }, [ '/', '/somePath', '/somePath.html', '/somePath.exe', '/fromShouldWork.html', '/toShouldWork', ], ), undefined, ), ).toEqual([ { from: '/toShouldWork.html', to: '/toShouldWork', }, { from: '/toShouldWork.exe', to: '/toShouldWork', }, { from: '/fromShouldWork', to: '/fromShouldWork.html', }, ]); }); it('throws when creating duplicate redirect routes and onDuplicateRoutes=throw', () => { expect(() => collectRedirects( createTestPluginContext( { createRedirects() { return '/random-path'; }, }, ['/path-one', '/path-two'], {onDuplicateRoutes: 'throw'}, ), undefined, ), ).toThrowErrorMatchingInlineSnapshot(` "@docusaurus/plugin-client-redirects: multiple redirects are created with the same "from" pathname: "/random-path" It is not possible to redirect the same pathname to multiple destinations: - {"from":"/random-path","to":"/path-one"} - {"from":"/random-path","to":"/path-two"}" `); expect(() => collectRedirects( createTestPluginContext( { redirects: [ {from: '/path-three', to: '/path-one'}, {from: '/path-two', to: '/path-one'}, ], }, ['/path-one', '/path-two'], {onDuplicateRoutes: 'throw'}, ), undefined, ), ).toThrowErrorMatchingInlineSnapshot(` "@docusaurus/plugin-client-redirects: some redirects would override existing paths, and will be ignored: - {"from":"/path-two","to":"/path-one"}" `); }); });
1,013
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__/createRedirectPageContent.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import createRedirectPageContent from '../createRedirectPageContent'; describe('createRedirectPageContent', () => { it('works', () => { expect( createRedirectPageContent({toUrl: 'https://docusaurus.io/'}), ).toMatchSnapshot(); }); it('encodes uri special chars', () => { const result = createRedirectPageContent({ toUrl: 'https://docusaurus.io/gr/σελιδας/', }); expect(result).toContain( 'https://docusaurus.io/gr/%CF%83%CE%B5%CE%BB%CE%B9%CE%B4%CE%B1%CF%82/', ); expect(result).toMatchSnapshot(); }); });
1,014
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__/extensionRedirects.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { createFromExtensionsRedirects, createToExtensionsRedirects, } from '../extensionRedirects'; describe('createToExtensionsRedirects', () => { it('rejects empty extensions', () => { expect(() => { createToExtensionsRedirects(['/'], ['']); }).toThrowErrorMatchingInlineSnapshot(` "Extension "" is not allowed. If the redirect extension system is not good enough for your use case, you can create redirects yourself with the "createRedirects" plugin option." `); }); it('rejects extensions with "."', () => { expect(() => { createToExtensionsRedirects(['/'], ['.html']); }).toThrowErrorMatchingInlineSnapshot(` "Extension ".html" contains a "." (dot) which is not allowed. If the redirect extension system is not good enough for your use case, you can create redirects yourself with the "createRedirects" plugin option." `); }); it('rejects extensions with /', () => { expect(() => { createToExtensionsRedirects(['/'], ['ht/ml']); }).toThrowErrorMatchingInlineSnapshot(` "Extension "ht/ml" contains a "/" (slash) which is not allowed. If the redirect extension system is not good enough for your use case, you can create redirects yourself with the "createRedirects" plugin option." `); }); it('rejects extensions with illegal url char', () => { expect(() => { createToExtensionsRedirects(['/'], [',']); }).toThrowErrorMatchingInlineSnapshot(` "Extension "," contains invalid URI characters. If the redirect extension system is not good enough for your use case, you can create redirects yourself with the "createRedirects" plugin option." `); }); it('creates redirects from html/htm extensions', () => { const ext = ['html', 'htm']; expect(createToExtensionsRedirects([''], ext)).toEqual([]); expect(createToExtensionsRedirects(['/'], ext)).toEqual([]); expect(createToExtensionsRedirects(['/abc.html'], ext)).toEqual([ {from: '/abc', to: '/abc.html'}, ]); expect(createToExtensionsRedirects(['/abc.htm'], ext)).toEqual([ {from: '/abc', to: '/abc.htm'}, ]); expect(createToExtensionsRedirects(['/abc.xyz'], ext)).toEqual([]); }); it('creates "to" redirects when relativeRoutesPath contains a prefix', () => { expect( createToExtensionsRedirects(['/prefix/file.html'], ['html']), ).toEqual([{from: '/prefix/file', to: '/prefix/file.html'}]); }); it('does not create redirection for an empty extension array', () => { const ext: string[] = []; expect(createToExtensionsRedirects([''], ext)).toEqual([]); expect(createToExtensionsRedirects(['/'], ext)).toEqual([]); expect(createToExtensionsRedirects(['/abc.html'], ext)).toEqual([]); }); }); describe('createFromExtensionsRedirects', () => { it('rejects empty extensions', () => { expect(() => { createFromExtensionsRedirects(['/'], ['.html']); }).toThrowErrorMatchingInlineSnapshot(` "Extension ".html" contains a "." (dot) which is not allowed. If the redirect extension system is not good enough for your use case, you can create redirects yourself with the "createRedirects" plugin option." `); }); it('rejects extensions with "."', () => { expect(() => { createFromExtensionsRedirects(['/'], ['.html']); }).toThrowErrorMatchingInlineSnapshot(` "Extension ".html" contains a "." (dot) which is not allowed. If the redirect extension system is not good enough for your use case, you can create redirects yourself with the "createRedirects" plugin option." `); }); it('rejects extensions with /', () => { expect(() => { createFromExtensionsRedirects(['/'], ['ht/ml']); }).toThrowErrorMatchingInlineSnapshot(` "Extension "ht/ml" contains a "/" (slash) which is not allowed. If the redirect extension system is not good enough for your use case, you can create redirects yourself with the "createRedirects" plugin option." `); }); it('rejects extensions with illegal url char', () => { expect(() => { createFromExtensionsRedirects(['/'], [',']); }).toThrowErrorMatchingInlineSnapshot(` "Extension "," contains invalid URI characters. If the redirect extension system is not good enough for your use case, you can create redirects yourself with the "createRedirects" plugin option." `); }); it('creates redirects from html/htm extensions', () => { const ext = ['html', 'htm']; expect(createFromExtensionsRedirects([''], ext)).toEqual([]); expect(createFromExtensionsRedirects(['/'], ext)).toEqual([]); expect(createFromExtensionsRedirects(['/abc'], ext)).toEqual([ {from: '/abc.html', to: '/abc'}, {from: '/abc.htm', to: '/abc'}, ]); expect(createFromExtensionsRedirects(['/def.html'], ext)).toEqual([]); expect(createFromExtensionsRedirects(['/def/'], ext)).toEqual([ {from: '/def.html/', to: '/def/'}, {from: '/def.htm/', to: '/def/'}, ]); }); it('creates "from" redirects when relativeRoutesPath contains a prefix', () => { expect(createFromExtensionsRedirects(['/prefix/file'], ['html'])).toEqual([ {from: '/prefix/file.html', to: '/prefix/file'}, ]); }); it('does not create redirection for an empty extension array', () => { const ext: string[] = []; expect(createFromExtensionsRedirects([''], ext)).toEqual([]); expect(createFromExtensionsRedirects(['/'], ext)).toEqual([]); expect(createFromExtensionsRedirects(['/abc'], ext)).toEqual([]); expect(createFromExtensionsRedirects(['/def.html'], ext)).toEqual([]); expect(createFromExtensionsRedirects(['/def/'], ext)).toEqual([]); }); });
1,015
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__/options.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {normalizePluginOptions} from '@docusaurus/utils-validation'; import {validateOptions, DEFAULT_OPTIONS} from '../options'; import type {Options} from '../options'; function testValidate(options?: Options) { return validateOptions({validate: normalizePluginOptions, options}); } describe('normalizePluginOptions', () => { it('returns default options for undefined user options', () => { expect(testValidate(undefined)).toEqual({ ...DEFAULT_OPTIONS, id: 'default', }); }); it('returns default options for empty user options', () => { expect(testValidate({})).toEqual({...DEFAULT_OPTIONS, id: 'default'}); }); it('overrides one default options with valid user options', () => { expect( testValidate({ toExtensions: ['html'], }), ).toEqual({...DEFAULT_OPTIONS, id: 'default', toExtensions: ['html']}); }); it('overrides all default options with valid user options', () => { const createRedirects: Options['createRedirects'] = () => []; expect( testValidate({ fromExtensions: ['exe', 'zip'], toExtensions: ['html'], createRedirects, redirects: [{from: '/x', to: '/y'}], }), ).toEqual({ id: 'default', fromExtensions: ['exe', 'zip'], toExtensions: ['html'], createRedirects, redirects: [{from: '/x', to: '/y'}], }); }); it('rejects bad fromExtensions user inputs', () => { expect(() => testValidate({ // @ts-expect-error: for test fromExtensions: [null, undefined, 123, true], }), ).toThrowErrorMatchingSnapshot(); }); it('rejects bad toExtensions user inputs', () => { expect(() => testValidate({ // @ts-expect-error: for test toExtensions: [null, undefined, 123, true], }), ).toThrowErrorMatchingSnapshot(); }); it('rejects bad createRedirects user inputs', () => { expect(() => testValidate({ // @ts-expect-error: for test createRedirects: ['bad', 'value'], }), ).toThrowErrorMatchingSnapshot(); }); });
1,016
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__/redirectValidation.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {validateRedirect} from '../redirectValidation'; describe('validateRedirect', () => { it('validate good redirects without throwing', () => { expect(() => { validateRedirect({ from: '/fromSomePath', to: '/toSomePath', }); validateRedirect({ from: '/from/Some/Path', to: '/toSomePath', }); validateRedirect({ from: '/fromSomePath', to: '/toSomePath', }); validateRedirect({ from: '/fromSomePath', to: '/to/Some/Path', }); validateRedirect({ from: '/fromSomePath', to: '/toSomePath?a=1', }); validateRedirect({ from: '/fromSomePath', to: '/toSomePath#anchor', }); validateRedirect({ from: '/fromSomePath', to: '/toSomePath?a=1&b=2#anchor', }); }).not.toThrow(); }); it('throw for bad redirects', () => { expect(() => validateRedirect({ from: 'https://fb.com/fromSomePath', to: '/toSomePath', }), ).toThrowErrorMatchingSnapshot(); expect(() => validateRedirect({ from: '/fromSomePath?a=1', to: '/toSomePath', }), ).toThrowErrorMatchingSnapshot(); expect(() => validateRedirect({ from: '/fromSomePath#anchor', to: '/toSomePath', }), ).toThrowErrorMatchingSnapshot(); }); });
1,017
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__/writeRedirectFiles.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import fs from 'fs-extra'; import path from 'path'; import writeRedirectFiles, { toRedirectFiles, createToUrl, } from '../writeRedirectFiles'; // Test to fix toUrl bugs we had: // - https://github.com/facebook/docusaurus/issues/3886 // - https://github.com/facebook/docusaurus/issues/3925 describe('createToUrl', () => { it('creates appropriate redirect urls', () => { expect(createToUrl('/', '/docs/something/else')).toBe( '/docs/something/else', ); expect(createToUrl('/', '/docs/something/else/')).toBe( '/docs/something/else/', ); expect(createToUrl('/', 'docs/something/else')).toBe('docs/something/else'); expect(createToUrl('/', './docs/something/else')).toBe( './docs/something/else', ); expect(createToUrl('/', 'https://docs/something/else')).toBe( 'https://docs/something/else', ); }); it('creates appropriate redirect urls with baseUrl', () => { expect(createToUrl('/baseUrl/', '/docs/something/else')).toBe( '/baseUrl/docs/something/else', ); expect(createToUrl('/baseUrl/', '/docs/something/else/')).toBe( '/baseUrl/docs/something/else/', ); expect(createToUrl('/baseUrl/', 'docs/something/else')).toBe( 'docs/something/else', ); expect(createToUrl('/baseUrl/', './docs/something/else')).toBe( './docs/something/else', ); expect(createToUrl('/baseUrl/', 'https://docs/something/else')).toBe( 'https://docs/something/else', ); }); }); describe('toRedirectFiles', () => { it('creates appropriate metadata absolute url', () => { const pluginContext = { outDir: '/tmp/someFixedOutDir', baseUrl: '/', }; const redirectFiles = toRedirectFiles( [ {from: '/abc', to: 'https://docusaurus.io/'}, {from: '/def', to: 'https://docusaurus.io/docs/intro?a=1'}, {from: '/ijk', to: 'https://docusaurus.io/docs/intro#anchor'}, ], pluginContext, undefined, ); expect(redirectFiles.map((f) => f.fileAbsolutePath)).toEqual([ path.join(pluginContext.outDir, '/abc/index.html'), path.join(pluginContext.outDir, '/def/index.html'), path.join(pluginContext.outDir, '/ijk/index.html'), ]); expect(redirectFiles.map((f) => f.fileContent)).toMatchSnapshot( 'fileContent', ); }); it('creates appropriate metadata trailingSlash=undefined', () => { const pluginContext = { outDir: '/tmp/someFixedOutDir', baseUrl: 'https://docusaurus.io', }; const redirectFiles = toRedirectFiles( [ {from: '/abc.html', to: '/abc'}, {from: '/def', to: '/def.html'}, {from: '/xyz', to: '/'}, ], pluginContext, undefined, ); expect(redirectFiles.map((f) => f.fileAbsolutePath)).toEqual([ path.join(pluginContext.outDir, '/abc.html/index.html'), path.join(pluginContext.outDir, '/def/index.html'), path.join(pluginContext.outDir, '/xyz/index.html'), ]); expect(redirectFiles.map((f) => f.fileContent)).toMatchSnapshot( 'fileContent', ); }); it('creates appropriate metadata trailingSlash=true', () => { const pluginContext = { outDir: '/tmp/someFixedOutDir', baseUrl: 'https://docusaurus.io', }; const redirectFiles = toRedirectFiles( [ {from: '/abc.html', to: '/abc'}, {from: '/def', to: '/def.html'}, {from: '/xyz', to: '/'}, ], pluginContext, true, ); expect(redirectFiles.map((f) => f.fileAbsolutePath)).toEqual([ path.join(pluginContext.outDir, '/abc.html/index.html'), path.join(pluginContext.outDir, '/def/index.html'), path.join(pluginContext.outDir, '/xyz/index.html'), ]); expect(redirectFiles.map((f) => f.fileContent)).toMatchSnapshot( 'fileContent', ); }); it('creates appropriate metadata trailingSlash=false', () => { const pluginContext = { outDir: '/tmp/someFixedOutDir', baseUrl: 'https://docusaurus.io', }; const redirectFiles = toRedirectFiles( [ {from: '/abc.html', to: '/abc'}, {from: '/def', to: '/def.html'}, {from: '/xyz', to: '/'}, ], pluginContext, false, ); expect(redirectFiles.map((f) => f.fileAbsolutePath)).toEqual([ // Can't be used because /abc.html already exists, and file/folder can't // share same name on Unix! // path.join(pluginContext.outDir, '/abc.html/index.html'), path.join(pluginContext.outDir, '/abc.html.html'), // Weird but on purpose! path.join(pluginContext.outDir, '/def/index.html'), path.join(pluginContext.outDir, '/xyz/index.html'), ]); expect(redirectFiles.map((f) => f.fileContent)).toMatchSnapshot( 'fileContent', ); }); it('creates appropriate metadata for root baseUrl', () => { const pluginContext = { outDir: '/tmp/someFixedOutDir', baseUrl: '/', }; const redirectFiles = toRedirectFiles( [{from: '/abc.html', to: '/abc'}], pluginContext, undefined, ); expect(redirectFiles.map((f) => f.fileContent)).toMatchSnapshot( 'fileContent baseUrl=/', ); }); it('creates appropriate metadata for empty baseUrl', () => { const pluginContext = { outDir: '/tmp/someFixedOutDir', baseUrl: '', }; const redirectFiles = toRedirectFiles( [{from: '/abc.html', to: '/abc'}], pluginContext, undefined, ); expect(redirectFiles.map((f) => f.fileContent)).toMatchSnapshot( 'fileContent baseUrl=empty', ); }); }); describe('writeRedirectFiles', () => { it('write the files', async () => { const outDir = `/tmp/docusaurus_tests_${Math.random()}`; const filesMetadata = [ { fileAbsolutePath: path.join(outDir, 'someFileName'), fileContent: 'content 1', }, { fileAbsolutePath: path.join(outDir, '/some/nested/filename'), fileContent: 'content 2', }, ]; await writeRedirectFiles(filesMetadata); await expect( fs.readFile(filesMetadata[0]!.fileAbsolutePath, 'utf8'), ).resolves.toBe('content 1'); await expect( fs.readFile(filesMetadata[1]!.fileAbsolutePath, 'utf8'), ).resolves.toBe('content 2'); }); it('avoid overwriting existing files', async () => { const outDir = `/tmp/docusaurus_tests_${Math.random()}`; const filesMetadata = [ { fileAbsolutePath: path.join(outDir, 'someFileName/index.html'), fileContent: 'content 1', }, ]; await fs.outputFile( filesMetadata[0]!.fileAbsolutePath, 'file already exists!', ); await expect( writeRedirectFiles(filesMetadata), ).rejects.toThrowErrorMatchingInlineSnapshot( `"The redirect plugin is not supposed to override existing files."`, ); }); });
1,018
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/collectRedirects.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`collectRedirects throw if plugin option redirects contain invalid to paths 1`] = ` "You are trying to create client-side redirections to invalid paths. These paths are redirected to but do not exist: - /this/path/does/not/exist2 - /this/path/does/not/exist3 - /this/path/does/not/exist4 Valid paths you can redirect to: - / - /someExistingPath - /anotherExistingPath " `; exports[`collectRedirects throw if plugin option redirects contain to paths with mismatching trailing slash 1`] = ` "You are trying to create client-side redirections to invalid paths. These paths do exist, but because you have explicitly set trailingSlash=false, you need to write the path without trailing slash: - /someExistingPath/ " `; exports[`collectRedirects throw if plugin option redirects contain to paths with mismatching trailing slash 2`] = ` "You are trying to create client-side redirections to invalid paths. These paths do exist, but because you have explicitly set trailingSlash=true, you need to write the path with trailing slash: - /someExistingPath " `; exports[`collectRedirects throws if redirect creator creates array of array redirect 1`] = ` "Some created redirects are invalid: - {"from":["/fromPath"],"to":"/"} => Validation error: "from" must be a string " `; exports[`collectRedirects throws if redirect creator creates invalid redirects 1`] = ` "Some created redirects are invalid: - {"from":"https://google.com/","to":"/"} => Validation error: "from" (https://google.com/) is not a valid pathname. Pathname should start with slash and not contain any domain or query string. - {"from":"//abc","to":"/"} => Validation error: "from" (//abc) is not a valid pathname. Pathname should start with slash and not contain any domain or query string. - {"from":"/def?queryString=toto","to":"/"} => Validation error: "from" (/def?queryString=toto) is not a valid pathname. Pathname should start with slash and not contain any domain or query string. " `;
1,019
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/createRedirectPageContent.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`createRedirectPageContent encodes uri special chars 1`] = ` "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/gr/%CF%83%CE%B5%CE%BB%CE%B9%CE%B4%CE%B1%CF%82/"> <link rel="canonical" href="https://docusaurus.io/gr/%CF%83%CE%B5%CE%BB%CE%B9%CE%B4%CE%B1%CF%82/" /> </head> <script> window.location.href = 'https://docusaurus.io/gr/%CF%83%CE%B5%CE%BB%CE%B9%CE%B4%CE%B1%CF%82/' + window.location.search + window.location.hash; </script> </html>" `; exports[`createRedirectPageContent works 1`] = ` "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/"> <link rel="canonical" href="https://docusaurus.io/" /> </head> <script> window.location.href = 'https://docusaurus.io/' + window.location.search + window.location.hash; </script> </html>" `;
1,020
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/options.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`normalizePluginOptions rejects bad createRedirects user inputs 1`] = `""createRedirects" must be of type function"`; exports[`normalizePluginOptions rejects bad fromExtensions user inputs 1`] = `""fromExtensions[0]" contains an invalid value"`; exports[`normalizePluginOptions rejects bad toExtensions user inputs 1`] = `""toExtensions[0]" contains an invalid value"`;
1,021
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/redirectValidation.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`validateRedirect throw for bad redirects 1`] = `"{"from":"https://fb.com/fromSomePath","to":"/toSomePath"} => Validation error: "from" (https://fb.com/fromSomePath) is not a valid pathname. Pathname should start with slash and not contain any domain or query string."`; exports[`validateRedirect throw for bad redirects 2`] = `"{"from":"/fromSomePath?a=1","to":"/toSomePath"} => Validation error: "from" (/fromSomePath?a=1) is not a valid pathname. Pathname should start with slash and not contain any domain or query string."`; exports[`validateRedirect throw for bad redirects 3`] = `"{"from":"/fromSomePath#anchor","to":"/toSomePath"} => Validation error: "from" (/fromSomePath#anchor) is not a valid pathname. Pathname should start with slash and not contain any domain or query string."`;
1,022
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-client-redirects/src/__tests__/__snapshots__/writeRedirectFiles.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`toRedirectFiles creates appropriate metadata absolute url: fileContent 1`] = ` [ "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/"> <link rel="canonical" href="https://docusaurus.io/" /> </head> <script> window.location.href = 'https://docusaurus.io/' + window.location.search + window.location.hash; </script> </html>", "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/docs/intro?a=1"> <link rel="canonical" href="https://docusaurus.io/docs/intro?a=1" /> </head> <script> window.location.href = 'https://docusaurus.io/docs/intro?a=1'; </script> </html>", "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/docs/intro#anchor"> <link rel="canonical" href="https://docusaurus.io/docs/intro#anchor" /> </head> <script> window.location.href = 'https://docusaurus.io/docs/intro#anchor'; </script> </html>", ] `; exports[`toRedirectFiles creates appropriate metadata for empty baseUrl: fileContent baseUrl=empty 1`] = ` [ "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=/abc"> <link rel="canonical" href="/abc" /> </head> <script> window.location.href = '/abc' + window.location.search + window.location.hash; </script> </html>", ] `; exports[`toRedirectFiles creates appropriate metadata for root baseUrl: fileContent baseUrl=/ 1`] = ` [ "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=/abc"> <link rel="canonical" href="/abc" /> </head> <script> window.location.href = '/abc' + window.location.search + window.location.hash; </script> </html>", ] `; exports[`toRedirectFiles creates appropriate metadata trailingSlash=false: fileContent 1`] = ` [ "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/abc"> <link rel="canonical" href="https://docusaurus.io/abc" /> </head> <script> window.location.href = 'https://docusaurus.io/abc' + window.location.search + window.location.hash; </script> </html>", "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/def.html"> <link rel="canonical" href="https://docusaurus.io/def.html" /> </head> <script> window.location.href = 'https://docusaurus.io/def.html' + window.location.search + window.location.hash; </script> </html>", "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/"> <link rel="canonical" href="https://docusaurus.io/" /> </head> <script> window.location.href = 'https://docusaurus.io/' + window.location.search + window.location.hash; </script> </html>", ] `; exports[`toRedirectFiles creates appropriate metadata trailingSlash=true: fileContent 1`] = ` [ "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/abc"> <link rel="canonical" href="https://docusaurus.io/abc" /> </head> <script> window.location.href = 'https://docusaurus.io/abc' + window.location.search + window.location.hash; </script> </html>", "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/def.html"> <link rel="canonical" href="https://docusaurus.io/def.html" /> </head> <script> window.location.href = 'https://docusaurus.io/def.html' + window.location.search + window.location.hash; </script> </html>", "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/"> <link rel="canonical" href="https://docusaurus.io/" /> </head> <script> window.location.href = 'https://docusaurus.io/' + window.location.search + window.location.hash; </script> </html>", ] `; exports[`toRedirectFiles creates appropriate metadata trailingSlash=undefined: fileContent 1`] = ` [ "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/abc"> <link rel="canonical" href="https://docusaurus.io/abc" /> </head> <script> window.location.href = 'https://docusaurus.io/abc' + window.location.search + window.location.hash; </script> </html>", "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/def.html"> <link rel="canonical" href="https://docusaurus.io/def.html" /> </head> <script> window.location.href = 'https://docusaurus.io/def.html' + window.location.search + window.location.hash; </script> </html>", "<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://docusaurus.io/"> <link rel="canonical" href="https://docusaurus.io/" /> </head> <script> window.location.href = 'https://docusaurus.io/' + window.location.search + window.location.hash; </script> </html>", ] `;
1,039
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/authors.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import { type AuthorsMap, getAuthorsMap, getBlogPostAuthors, validateAuthorsMap, } from '../authors'; describe('getBlogPostAuthors', () => { it('can read no authors', () => { expect( getBlogPostAuthors({ frontMatter: {}, authorsMap: undefined, }), ).toEqual([]); expect( getBlogPostAuthors({ frontMatter: { authors: [], }, authorsMap: undefined, }), ).toEqual([]); }); it('can read author from legacy front matter', () => { expect( getBlogPostAuthors({ frontMatter: { author: 'Sébastien Lorber', }, authorsMap: undefined, }), ).toEqual([{name: 'Sébastien Lorber'}]); expect( getBlogPostAuthors({ frontMatter: { authorTitle: 'maintainer', }, authorsMap: undefined, }), ).toEqual([{title: 'maintainer'}]); expect( getBlogPostAuthors({ frontMatter: { authorImageURL: 'https://github.com/slorber.png', }, authorsMap: undefined, }), ).toEqual([{imageURL: 'https://github.com/slorber.png'}]); expect( getBlogPostAuthors({ frontMatter: { author: 'Sébastien Lorber', author_title: 'maintainer1', authorTitle: 'maintainer2', author_image_url: 'https://github.com/slorber1.png', authorImageURL: 'https://github.com/slorber2.png', author_url: 'https://github.com/slorber1', authorURL: 'https://github.com/slorber2', }, authorsMap: undefined, }), ).toEqual([ { name: 'Sébastien Lorber', title: 'maintainer1', imageURL: 'https://github.com/slorber1.png', url: 'https://github.com/slorber1', }, ]); }); it('can read authors string', () => { expect( getBlogPostAuthors({ frontMatter: { authors: 'slorber', }, authorsMap: {slorber: {name: 'Sébastien Lorber'}}, }), ).toEqual([{key: 'slorber', name: 'Sébastien Lorber'}]); }); it('can read authors string[]', () => { expect( getBlogPostAuthors({ frontMatter: { authors: ['slorber', 'yangshun'], }, authorsMap: { slorber: {name: 'Sébastien Lorber', title: 'maintainer'}, yangshun: {name: 'Yangshun Tay'}, }, }), ).toEqual([ {key: 'slorber', name: 'Sébastien Lorber', title: 'maintainer'}, {key: 'yangshun', name: 'Yangshun Tay'}, ]); }); it('can read authors Author', () => { expect( getBlogPostAuthors({ frontMatter: { authors: {name: 'Sébastien Lorber', title: 'maintainer'}, }, authorsMap: undefined, }), ).toEqual([{name: 'Sébastien Lorber', title: 'maintainer'}]); }); it('can read authors Author[]', () => { expect( getBlogPostAuthors({ frontMatter: { authors: [ {name: 'Sébastien Lorber', title: 'maintainer'}, {name: 'Yangshun Tay'}, ], }, authorsMap: undefined, }), ).toEqual([ {name: 'Sébastien Lorber', title: 'maintainer'}, {name: 'Yangshun Tay'}, ]); }); it('can read authors complex (string | Author)[] setup with keys and local overrides', () => { expect( getBlogPostAuthors({ frontMatter: { authors: [ 'slorber', { key: 'yangshun', title: 'Yangshun title local override', extra: 42, }, {name: 'Alexey'}, ], }, authorsMap: { slorber: {name: 'Sébastien Lorber', title: 'maintainer'}, yangshun: {name: 'Yangshun Tay', title: 'Yangshun title original'}, }, }), ).toEqual([ {key: 'slorber', name: 'Sébastien Lorber', title: 'maintainer'}, { key: 'yangshun', name: 'Yangshun Tay', title: 'Yangshun title local override', extra: 42, }, {name: 'Alexey'}, ]); }); it('throw when using author key with no authorsMap', () => { expect(() => getBlogPostAuthors({ frontMatter: { authors: 'slorber', }, authorsMap: undefined, }), ).toThrowErrorMatchingInlineSnapshot(` "Can't reference blog post authors by a key (such as 'slorber') because no authors map file could be loaded. Please double-check your blog plugin config (in particular 'authorsMapPath'), ensure the file exists at the configured path, is not empty, and is valid!" `); }); it('throw when using author key with empty authorsMap', () => { expect(() => getBlogPostAuthors({ frontMatter: { authors: 'slorber', }, authorsMap: {}, }), ).toThrowErrorMatchingInlineSnapshot(` "Can't reference blog post authors by a key (such as 'slorber') because no authors map file could be loaded. Please double-check your blog plugin config (in particular 'authorsMapPath'), ensure the file exists at the configured path, is not empty, and is valid!" `); }); it('throw when using bad author key in string', () => { expect(() => getBlogPostAuthors({ frontMatter: { authors: 'slorber', }, authorsMap: { yangshun: {name: 'Yangshun Tay'}, jmarcey: {name: 'Joel Marcey'}, }, }), ).toThrowErrorMatchingInlineSnapshot(` "Blog author with key "slorber" not found in the authors map file. Valid author keys are: - yangshun - jmarcey" `); }); it('throw when using bad author key in string[]', () => { expect(() => getBlogPostAuthors({ frontMatter: { authors: ['yangshun', 'jmarcey', 'slorber'], }, authorsMap: { yangshun: {name: 'Yangshun Tay'}, jmarcey: {name: 'Joel Marcey'}, }, }), ).toThrowErrorMatchingInlineSnapshot(` "Blog author with key "slorber" not found in the authors map file. Valid author keys are: - yangshun - jmarcey" `); }); it('throw when using bad author key in Author[].key', () => { expect(() => getBlogPostAuthors({ frontMatter: { authors: [{key: 'yangshun'}, {key: 'jmarcey'}, {key: 'slorber'}], }, authorsMap: { yangshun: {name: 'Yangshun Tay'}, jmarcey: {name: 'Joel Marcey'}, }, }), ).toThrowErrorMatchingInlineSnapshot(` "Blog author with key "slorber" not found in the authors map file. Valid author keys are: - yangshun - jmarcey" `); }); it('throw when mixing legacy/new authors front matter', () => { expect(() => getBlogPostAuthors({ frontMatter: { authors: [{name: 'Sébastien Lorber'}], author: 'Yangshun Tay', }, authorsMap: undefined, }), ).toThrowErrorMatchingInlineSnapshot(` "To declare blog post authors, use the 'authors' front matter in priority. Don't mix 'authors' with other existing 'author_*' front matter. Choose one or the other, not both at the same time." `); expect(() => getBlogPostAuthors({ frontMatter: { authors: [{key: 'slorber'}], author_title: 'legacy title', }, authorsMap: {slorber: {name: 'Sébastien Lorber'}}, }), ).toThrowErrorMatchingInlineSnapshot(` "To declare blog post authors, use the 'authors' front matter in priority. Don't mix 'authors' with other existing 'author_*' front matter. Choose one or the other, not both at the same time." `); }); }); describe('getAuthorsMap', () => { const fixturesDir = path.join(__dirname, '__fixtures__/authorsMapFiles'); const contentPaths = { contentPathLocalized: fixturesDir, contentPath: fixturesDir, }; it('getAuthorsMap can read yml file', async () => { await expect( getAuthorsMap({ contentPaths, authorsMapPath: 'authors.yml', }), ).resolves.toBeDefined(); }); it('getAuthorsMap can read json file', async () => { await expect( getAuthorsMap({ contentPaths, authorsMapPath: 'authors.json', }), ).resolves.toBeDefined(); }); it('getAuthorsMap can return undefined if yaml file not found', async () => { await expect( getAuthorsMap({ contentPaths, authorsMapPath: 'authors_does_not_exist.yml', }), ).resolves.toBeUndefined(); }); }); describe('validateAuthorsMap', () => { it('accept valid authors map', () => { const authorsMap: AuthorsMap = { slorber: { name: 'Sébastien Lorber', title: 'maintainer', url: 'https://sebastienlorber.com', imageURL: 'https://github.com/slorber.png', }, yangshun: { name: 'Yangshun Tay', imageURL: 'https://github.com/yangshun.png', randomField: 42, }, jmarcey: { name: 'Joel', title: 'creator of Docusaurus', hello: new Date(), }, }; expect(validateAuthorsMap(authorsMap)).toEqual(authorsMap); }); it('rename snake case image_url to camelCase imageURL', () => { const authorsMap: AuthorsMap = { slorber: { name: 'Sébastien Lorber', image_url: 'https://github.com/slorber.png', }, }; expect(validateAuthorsMap(authorsMap)).toEqual({ slorber: { name: 'Sébastien Lorber', imageURL: 'https://github.com/slorber.png', }, }); }); it('accept author with only image', () => { const authorsMap: AuthorsMap = { slorber: { imageURL: 'https://github.com/slorber.png', url: 'https://github.com/slorber', }, }; expect(validateAuthorsMap(authorsMap)).toEqual(authorsMap); }); it('reject author without name or image', () => { const authorsMap: AuthorsMap = { slorber: { title: 'foo', }, }; expect(() => validateAuthorsMap(authorsMap), ).toThrowErrorMatchingInlineSnapshot( `""slorber" must contain at least one of [name, imageURL]"`, ); }); it('reject undefined author', () => { expect(() => validateAuthorsMap({ slorber: undefined, }), ).toThrowErrorMatchingInlineSnapshot( `""slorber" cannot be undefined. It should be an author object containing properties like name, title, and imageURL."`, ); }); it('reject null author', () => { expect(() => validateAuthorsMap({ slorber: null, }), ).toThrowErrorMatchingInlineSnapshot( `""slorber" should be an author object containing properties like name, title, and imageURL."`, ); }); it('reject array author', () => { expect(() => validateAuthorsMap({slorber: []}), ).toThrowErrorMatchingInlineSnapshot( `""slorber" should be an author object containing properties like name, title, and imageURL."`, ); }); it('reject array content', () => { expect(() => validateAuthorsMap([])).toThrowErrorMatchingInlineSnapshot( `"The authors map file should contain an object where each entry contains an author key and the corresponding author's data."`, ); }); it('reject flat author', () => { expect(() => validateAuthorsMap({name: 'Sébastien'}), ).toThrowErrorMatchingInlineSnapshot( `""name" should be an author object containing properties like name, title, and imageURL."`, ); }); it('reject non-map author', () => { const authorsMap: AuthorsMap = { // @ts-expect-error: for tests slorber: [], }; expect(() => validateAuthorsMap(authorsMap), ).toThrowErrorMatchingInlineSnapshot( `""slorber" should be an author object containing properties like name, title, and imageURL."`, ); }); });
1,040
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/blogUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import fs from 'fs-extra'; import path from 'path'; import { truncate, parseBlogFileName, linkify, getSourceToPermalink, paginateBlogPosts, type LinkifyParams, } from '../blogUtils'; import type {BlogBrokenMarkdownLink, BlogContentPaths} from '../types'; import type {BlogPost} from '@docusaurus/plugin-content-blog'; describe('truncate', () => { it('truncates texts', () => { expect( truncate('aaa\n<!-- truncate -->\nbbb\n ccc', /<!-- truncate -->/), ).toBe('aaa\n'); expect( truncate('\n<!-- truncate -->\nbbb\n ccc', /<!-- truncate -->/), ).toBe('\n'); }); it('leaves texts without markers', () => { expect(truncate('aaa\nbbb\n ccc', /<!-- truncate -->/)).toBe( 'aaa\nbbb\n ccc', ); expect(truncate('', /<!-- truncate -->/)).toBe(''); }); }); describe('paginateBlogPosts', () => { it('generates right pages', () => { const blogPosts = [ {id: 'post1', metadata: {}, content: 'Foo 1'}, {id: 'post2', metadata: {}, content: 'Foo 2'}, {id: 'post3', metadata: {}, content: 'Foo 3'}, {id: 'post4', metadata: {}, content: 'Foo 4'}, {id: 'post5', metadata: {}, content: 'Foo 5'}, ] as BlogPost[]; expect( paginateBlogPosts({ blogPosts, basePageUrl: '/blog', blogTitle: 'Blog Title', blogDescription: 'Blog Description', postsPerPageOption: 2, }), ).toMatchSnapshot(); expect( paginateBlogPosts({ blogPosts, basePageUrl: '/', blogTitle: 'Blog Title', blogDescription: 'Blog Description', postsPerPageOption: 2, }), ).toMatchSnapshot(); expect( paginateBlogPosts({ blogPosts, basePageUrl: '/', blogTitle: 'Blog Title', blogDescription: 'Blog Description', postsPerPageOption: 10, }), ).toMatchSnapshot(); }); }); describe('parseBlogFileName', () => { it('parses file', () => { expect(parseBlogFileName('some-post.md')).toEqual({ date: undefined, text: 'some-post', slug: '/some-post', }); }); it('parses folder', () => { expect(parseBlogFileName('some-post/index.md')).toEqual({ date: undefined, text: 'some-post', slug: '/some-post', }); }); it('parses nested file', () => { expect(parseBlogFileName('some-post/some-file.md')).toEqual({ date: undefined, text: 'some-post/some-file', slug: '/some-post/some-file', }); }); it('parses nested folder', () => { expect(parseBlogFileName('some-post/some-subfolder/index.md')).toEqual({ date: undefined, text: 'some-post/some-subfolder', slug: '/some-post/some-subfolder', }); }); it('parses file respecting date convention', () => { expect( parseBlogFileName('2021-05-12-announcing-docusaurus-two-beta.md'), ).toEqual({ date: new Date('2021-05-12Z'), text: 'announcing-docusaurus-two-beta', slug: '/2021/05/12/announcing-docusaurus-two-beta', }); }); it('parses folder name respecting date convention', () => { expect( parseBlogFileName('2021-05-12-announcing-docusaurus-two-beta/index.md'), ).toEqual({ date: new Date('2021-05-12Z'), text: 'announcing-docusaurus-two-beta', slug: '/2021/05/12/announcing-docusaurus-two-beta', }); }); it('parses folder tree respecting date convention', () => { expect( parseBlogFileName('2021/05/12/announcing-docusaurus-two-beta/index.md'), ).toEqual({ date: new Date('2021-05-12Z'), text: 'announcing-docusaurus-two-beta', slug: '/2021/05/12/announcing-docusaurus-two-beta', }); }); it('parses folder name/tree (mixed) respecting date convention', () => { expect( parseBlogFileName('2021/05-12-announcing-docusaurus-two-beta/index.md'), ).toEqual({ date: new Date('2021-05-12Z'), text: 'announcing-docusaurus-two-beta', slug: '/2021/05/12/announcing-docusaurus-two-beta', }); }); it('parses nested folder tree respecting date convention', () => { expect( parseBlogFileName( '2021/05/12/announcing-docusaurus-two-beta/subfolder/file.md', ), ).toEqual({ date: new Date('2021-05-12Z'), text: 'announcing-docusaurus-two-beta/subfolder/file', slug: '/2021/05/12/announcing-docusaurus-two-beta/subfolder/file', }); }); it('parses date in the middle of path', () => { expect( parseBlogFileName('team-a/2021/05/12/announcing-docusaurus-two-beta.md'), ).toEqual({ date: new Date('2021-05-12Z'), text: 'announcing-docusaurus-two-beta', slug: '/2021/05/12/team-a/announcing-docusaurus-two-beta', }); }); it('parses date in the middle of a folder name', () => { expect( parseBlogFileName( 'team-a-2021-05-12-hey/announcing-docusaurus-two-beta.md', ), ).toEqual({ date: new Date('2021-05-12Z'), text: 'hey/announcing-docusaurus-two-beta', slug: '/2021/05/12/team-a-hey/announcing-docusaurus-two-beta', }); }); }); describe('linkify', () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const contentPaths: BlogContentPaths = { contentPath: path.join(siteDir, 'blog-with-ref'), contentPathLocalized: path.join(siteDir, 'blog-with-ref-localized'), }; const pluginDir = 'blog-with-ref'; const blogPosts: BlogPost[] = [ { id: 'Happy 1st Birthday Slash!', metadata: { permalink: '/blog/2018/12/14/Happy-First-Birthday-Slash', source: path.posix.join( '@site', pluginDir, '2018-12-14-Happy-First-Birthday-Slash.md', ), title: 'Happy 1st Birthday Slash!', description: `pattern name`, date: new Date('2018-12-14'), tags: [], prevItem: { permalink: '/blog/2019/01/01/date-matter', title: 'date-matter', }, hasTruncateMarker: false, frontMatter: {}, authors: [], formattedDate: '', }, content: '', }, ]; async function transform(filePath: string, options?: Partial<LinkifyParams>) { const fileContent = await fs.readFile(filePath, 'utf-8'); const transformedContent = linkify({ filePath, fileString: fileContent, siteDir, contentPaths, sourceToPermalink: getSourceToPermalink(blogPosts), onBrokenMarkdownLink: (brokenMarkdownLink) => { throw new Error( `Broken markdown link found: ${JSON.stringify(brokenMarkdownLink)}`, ); }, ...options, }); return [fileContent, transformedContent]; } it('transforms to correct link', async () => { const post = path.join(contentPaths.contentPath, 'post.md'); const [content, transformedContent] = await transform(post); expect(transformedContent).toMatchSnapshot(); expect(transformedContent).toContain( '](/blog/2018/12/14/Happy-First-Birthday-Slash', ); expect(transformedContent).not.toContain( '](2018-12-14-Happy-First-Birthday-Slash.md)', ); expect(content).not.toEqual(transformedContent); }); it('reports broken markdown links', async () => { const filePath = 'post-with-broken-links.md'; const folderPath = contentPaths.contentPath; const postWithBrokenLinks = path.join(folderPath, filePath); const onBrokenMarkdownLink = jest.fn(); const [, transformedContent] = await transform(postWithBrokenLinks, { onBrokenMarkdownLink, }); expect(transformedContent).toMatchSnapshot(); expect(onBrokenMarkdownLink).toHaveBeenCalledTimes(2); expect(onBrokenMarkdownLink).toHaveBeenNthCalledWith(1, { filePath: path.resolve(folderPath, filePath), contentPaths, link: 'postNotExist1.md', } as BlogBrokenMarkdownLink); expect(onBrokenMarkdownLink).toHaveBeenNthCalledWith(2, { filePath: path.resolve(folderPath, filePath), contentPaths, link: './postNotExist2.mdx', } as BlogBrokenMarkdownLink); }); });
1,041
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/feed.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import fs from 'fs-extra'; import {DEFAULT_OPTIONS} from '../options'; import {generateBlogPosts} from '../blogUtils'; import {createBlogFeedFiles} from '../feed'; import type {LoadContext, I18n} from '@docusaurus/types'; import type {BlogContentPaths} from '../types'; import type {PluginOptions} from '@docusaurus/plugin-content-blog'; const DefaultI18N: I18n = { currentLocale: 'en', locales: ['en'], defaultLocale: 'en', path: '1i8n', localeConfigs: { en: { label: 'English', direction: 'ltr', htmlLang: 'en', calendar: 'gregory', path: 'en', }, }, }; function getBlogContentPaths(siteDir: string): BlogContentPaths { return { contentPath: path.resolve(siteDir, 'blog'), contentPathLocalized: path.resolve( siteDir, 'i18n', 'en', 'docusaurus-plugin-content-blog', ), }; } async function testGenerateFeeds( context: LoadContext, options: PluginOptions, ): Promise<void> { const blogPosts = await generateBlogPosts( getBlogContentPaths(context.siteDir), context, options, ); await createBlogFeedFiles({ blogPosts, options, siteConfig: context.siteConfig, outDir: context.outDir, locale: 'en', }); } describe.each(['atom', 'rss', 'json'])('%s', (feedType) => { const fsMock = jest.spyOn(fs, 'outputFile').mockImplementation(() => {}); it('does not get generated without posts', async () => { const siteDir = __dirname; const siteConfig = { title: 'Hello', baseUrl: '/', url: 'https://docusaurus.io', favicon: 'image/favicon.ico', }; const outDir = path.join(siteDir, 'build-snap'); await testGenerateFeeds( { siteDir, siteConfig, i18n: DefaultI18N, outDir, } as LoadContext, { path: 'invalid-blog-path', routeBasePath: 'blog', tagsBasePath: 'tags', authorsMapPath: 'authors.yml', include: ['*.md', '*.mdx'], feedOptions: { type: [feedType], copyright: 'Copyright', }, readingTime: ({content, defaultReadingTime}) => defaultReadingTime({content}), truncateMarker: /<!--\s*truncate\s*-->/, } as PluginOptions, ); expect(fsMock).toHaveBeenCalledTimes(0); fsMock.mockClear(); }); it('has feed item for each post', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const outDir = path.join(siteDir, 'build-snap'); const siteConfig = { title: 'Hello', baseUrl: '/myBaseUrl/', url: 'https://docusaurus.io', favicon: 'image/favicon.ico', }; // Build is quite difficult to mock, so we built the blog beforehand and // copied the output to the fixture... await testGenerateFeeds( { siteDir, siteConfig, i18n: DefaultI18N, outDir, } as LoadContext, { path: 'blog', routeBasePath: 'blog', tagsBasePath: 'tags', authorsMapPath: 'authors.yml', include: DEFAULT_OPTIONS.include, exclude: DEFAULT_OPTIONS.exclude, feedOptions: { type: [feedType], copyright: 'Copyright', }, readingTime: ({content, defaultReadingTime}) => defaultReadingTime({content}), truncateMarker: /<!--\s*truncate\s*-->/, } as PluginOptions, ); expect( fsMock.mock.calls.map((call) => call[1] as string), ).toMatchSnapshot(); fsMock.mockClear(); }); it('filters to the first two entries', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const outDir = path.join(siteDir, 'build-snap'); const siteConfig = { title: 'Hello', baseUrl: '/myBaseUrl/', url: 'https://docusaurus.io', favicon: 'image/favicon.ico', }; // Build is quite difficult to mock, so we built the blog beforehand and // copied the output to the fixture... await testGenerateFeeds( { siteDir, siteConfig, i18n: DefaultI18N, outDir, } as LoadContext, { path: 'blog', routeBasePath: 'blog', tagsBasePath: 'tags', authorsMapPath: 'authors.yml', include: DEFAULT_OPTIONS.include, exclude: DEFAULT_OPTIONS.exclude, feedOptions: { type: [feedType], copyright: 'Copyright', createFeedItems: async (params) => { const {blogPosts, defaultCreateFeedItems, ...rest} = params; const blogPostsFiltered = blogPosts.filter( (item, index) => index < 2, ); return defaultCreateFeedItems({ blogPosts: blogPostsFiltered, ...rest, }); }, }, readingTime: ({content, defaultReadingTime}) => defaultReadingTime({content}), truncateMarker: /<!--\s*truncate\s*-->/, } as PluginOptions, ); expect( fsMock.mock.calls.map((call) => call[1] as string), ).toMatchSnapshot(); fsMock.mockClear(); }); it('filters to the first two entries using limit', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const outDir = path.join(siteDir, 'build-snap'); const siteConfig = { title: 'Hello', baseUrl: '/myBaseUrl/', url: 'https://docusaurus.io', favicon: 'image/favicon.ico', }; // Build is quite difficult to mock, so we built the blog beforehand and // copied the output to the fixture... await testGenerateFeeds( { siteDir, siteConfig, i18n: DefaultI18N, outDir, } as LoadContext, { path: 'blog', routeBasePath: 'blog', tagsBasePath: 'tags', authorsMapPath: 'authors.yml', include: DEFAULT_OPTIONS.include, exclude: DEFAULT_OPTIONS.exclude, feedOptions: { type: [feedType], copyright: 'Copyright', limit: 2, }, readingTime: ({content, defaultReadingTime}) => defaultReadingTime({content}), truncateMarker: /<!--\s*truncate\s*-->/, } as PluginOptions, ); expect( fsMock.mock.calls.map((call) => call[1] as string), ).toMatchSnapshot(); fsMock.mockClear(); }); });
1,042
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/frontMatter.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {escapeRegexp} from '@docusaurus/utils'; import {validateBlogPostFrontMatter} from '../frontMatter'; import type {BlogPostFrontMatter} from '@docusaurus/plugin-content-blog'; // TODO this abstraction reduce verbosity but it makes it harder to debug // It would be preferable to just expose helper methods function testField(params: { prefix: string; validFrontMatters: BlogPostFrontMatter[]; convertibleFrontMatter?: [ ConvertibleFrontMatter: {[key: string]: unknown}, ConvertedFrontMatter: BlogPostFrontMatter, ][]; invalidFrontMatters?: [ InvalidFrontMatter: {[key: string]: unknown}, ErrorMessage: string, ][]; }) { describe(`"${params.prefix}" field`, () => { it('accept valid values', () => { params.validFrontMatters.forEach((frontMatter) => { expect(validateBlogPostFrontMatter(frontMatter)).toEqual(frontMatter); }); }); it('convert valid values', () => { params.convertibleFrontMatter?.forEach( ([convertibleFrontMatter, convertedFrontMatter]) => { expect(validateBlogPostFrontMatter(convertibleFrontMatter)).toEqual( convertedFrontMatter, ); }, ); }); it('throw error for values', () => { params.invalidFrontMatters?.forEach(([frontMatter, message]) => { try { validateBlogPostFrontMatter(frontMatter); throw new Error( `Blog front matter is expected to be rejected, but was accepted successfully:\n ${JSON.stringify( frontMatter, null, 2, )}`, ); } catch (err) { // eslint-disable-next-line jest/no-conditional-expect expect((err as Error).message).toMatch( new RegExp(escapeRegexp(message)), ); } }); }); }); } describe('validateBlogPostFrontMatter', () => { it('accept empty object', () => { const frontMatter = {}; expect(validateBlogPostFrontMatter(frontMatter)).toEqual(frontMatter); }); it('accept unknown field', () => { const frontMatter = {abc: '1'}; expect(validateBlogPostFrontMatter(frontMatter)).toEqual(frontMatter); }); }); describe('validateBlogPostFrontMatter description', () => { testField({ prefix: 'description', validFrontMatters: [ // See https://github.com/facebook/docusaurus/issues/4591#issuecomment-822372398 {description: ''}, {description: 'description'}, ], }); }); describe('validateBlogPostFrontMatter title', () => { testField({ prefix: 'title', validFrontMatters: [ // See https://github.com/facebook/docusaurus/issues/4591#issuecomment-822372398 {title: ''}, {title: 'title'}, ], }); }); describe('validateBlogPostFrontMatter id', () => { testField({ prefix: 'id', validFrontMatters: [{id: '123'}, {id: 'id'}], invalidFrontMatters: [[{id: ''}, 'not allowed to be empty']], }); }); describe('validateBlogPostFrontMatter handles legacy/new author front matter', () => { it('allow legacy author front matter', () => { const frontMatter: BlogPostFrontMatter = { author: 'Sebastien', author_url: 'https://sebastienlorber.com', author_title: 'maintainer', author_image_url: 'https://github.com/slorber.png', }; expect(validateBlogPostFrontMatter(frontMatter)).toEqual(frontMatter); }); it('allow new authors front matter', () => { const frontMatter: BlogPostFrontMatter = { authors: [ 'slorber', {name: 'Yangshun'}, {key: 'JMarcey', title: 'creator', random: '42'}, ], }; expect(validateBlogPostFrontMatter(frontMatter)).toEqual(frontMatter); }); }); describe('validateBlogPostFrontMatter author', () => { testField({ prefix: 'author', validFrontMatters: [{author: '123'}, {author: 'author'}], invalidFrontMatters: [[{author: ''}, 'not allowed to be empty']], }); }); describe('validateBlogPostFrontMatter author_title', () => { testField({ prefix: 'author_title', validFrontMatters: [ {author: '123', author_title: '123'}, {author: '123', author_title: 'author_title'}, ], invalidFrontMatters: [[{author_title: ''}, 'not allowed to be empty']], }); testField({ prefix: 'authorTitle', validFrontMatters: [{authorTitle: '123'}, {authorTitle: 'authorTitle'}], invalidFrontMatters: [[{authorTitle: ''}, 'not allowed to be empty']], }); }); describe('validateBlogPostFrontMatter author_url', () => { testField({ prefix: 'author_url', validFrontMatters: [ {author_url: 'https://docusaurus.io'}, {author_url: '../../relative'}, {author_url: '/absolute'}, ], invalidFrontMatters: [ [ {author_url: ''}, '"author_url" does not look like a valid url (value=\'\')', ], ], }); testField({ prefix: 'authorURL', validFrontMatters: [ {authorURL: 'https://docusaurus.io'}, {authorURL: '../../relative'}, {authorURL: '/absolute'}, ], invalidFrontMatters: [ [ {authorURL: ''}, '"authorURL" does not look like a valid url (value=\'\')', ], ], }); }); describe('validateBlogPostFrontMatter author_image_url', () => { testField({ prefix: 'author_image_url', validFrontMatters: [ {author_image_url: 'https://docusaurus.io/asset/image.png'}, {author_image_url: '../../relative'}, {author_image_url: '/absolute'}, ], invalidFrontMatters: [ [ {author_image_url: ''}, '"author_image_url" does not look like a valid url (value=\'\')', ], ], }); testField({ prefix: 'authorImageURL', validFrontMatters: [ {authorImageURL: 'https://docusaurus.io/asset/image.png'}, {authorImageURL: '../../relative'}, {authorImageURL: '/absolute'}, ], invalidFrontMatters: [ [ {authorImageURL: ''}, '"authorImageURL" does not look like a valid url (value=\'\')', ], ], }); }); describe('validateBlogPostFrontMatter authors', () => { testField({ prefix: 'author', validFrontMatters: [ {authors: []}, {authors: 'authorKey'}, {authors: ['authorKey1', 'authorKey2']}, { authors: { name: 'Author Name', imageURL: '/absolute', }, }, { authors: { key: 'authorKey', title: 'Author title', }, }, { authors: [ 'authorKey1', {key: 'authorKey3'}, 'authorKey3', {name: 'Author Name 4'}, {key: 'authorKey5'}, ], }, ], invalidFrontMatters: [ [{authors: ''}, '"authors" is not allowed to be empty'], [ {authors: [undefined]}, '"authors[0]" does not look like a valid blog post author. Please use an author key or an author object (with a key and/or name).', ], [ {authors: [null]}, '"authors[0]" does not look like a valid blog post author. Please use an author key or an author object (with a key and/or name).', ], [ {authors: [{}]}, '"authors[0]" does not look like a valid blog post author. Please use an author key or an author object (with a key and/or name).', ], ], }); }); describe('validateBlogPostFrontMatter slug', () => { testField({ prefix: 'slug', validFrontMatters: [ {slug: 'blog/'}, {slug: '/blog'}, {slug: '/blog/'}, {slug: './blog'}, {slug: '../blog'}, {slug: '../../blog'}, {slug: '/api/plugins/@docusaurus/plugin-debug'}, {slug: '@site/api/asset/image.png'}, ], invalidFrontMatters: [[{slug: ''}, 'not allowed to be empty']], }); }); describe('validateBlogPostFrontMatter image', () => { testField({ prefix: 'image', validFrontMatters: [ {image: 'https://docusaurus.io/image.png'}, {image: 'blog/'}, {image: '/blog'}, {image: '/blog/'}, {image: './blog'}, {image: '../blog'}, {image: '../../blog'}, {image: '/api/plugins/@docusaurus/plugin-debug'}, {image: '@site/api/asset/image.png'}, ], invalidFrontMatters: [ [{image: ''}, '"image" does not look like a valid url (value=\'\')'], ], }); }); describe('validateBlogPostFrontMatter tags', () => { testField({ prefix: 'tags', validFrontMatters: [ {tags: []}, {tags: ['hello']}, {tags: ['hello', 'world']}, {tags: ['hello', 'world']}, {tags: ['hello', {label: 'tagLabel', permalink: '/tagPermalink'}]}, ], invalidFrontMatters: [ [ {tags: ''}, '"tags" does not look like a valid front matter Yaml array.', ], [{tags: ['']}, 'not allowed to be empty'], ], // See https://github.com/facebook/docusaurus/issues/4642 convertibleFrontMatter: [ [{tags: [42]}, {tags: ['42']}], [ {tags: [{label: 84, permalink: '/tagPermalink'}]}, {tags: [{label: '84', permalink: '/tagPermalink'}]}, ], ], }); }); describe('validateBlogPostFrontMatter keywords', () => { testField({ prefix: 'keywords', validFrontMatters: [ {keywords: ['hello']}, {keywords: ['hello', 'world']}, {keywords: ['hello', 'world']}, {keywords: ['hello']}, ], invalidFrontMatters: [ [{keywords: ''}, 'must be an array'], [{keywords: ['']}, 'not allowed to be empty'], [{keywords: []}, 'does not contain 1 required value(s)'], ], }); }); describe('validateBlogPostFrontMatter draft', () => { testField({ prefix: 'draft', validFrontMatters: [{draft: true}, {draft: false}], convertibleFrontMatter: [ [{draft: 'true'}, {draft: true}], [{draft: 'false'}, {draft: false}], ], invalidFrontMatters: [ [{draft: 'yes'}, 'must be a boolean'], [{draft: 'no'}, 'must be a boolean'], ], }); }); describe('validateBlogPostFrontMatter unlisted', () => { testField({ prefix: 'unlisted', validFrontMatters: [{unlisted: true}, {unlisted: false}], convertibleFrontMatter: [ [{unlisted: 'true'}, {unlisted: true}], [{unlisted: 'false'}, {unlisted: false}], ], invalidFrontMatters: [ [{unlisted: 'yes'}, 'must be a boolean'], [{unlisted: 'no'}, 'must be a boolean'], ], }); }); describe('validateDocFrontMatter draft XOR unlisted', () => { testField({ prefix: 'draft XOR unlisted', validFrontMatters: [ {draft: false}, {unlisted: false}, {draft: false, unlisted: false}, {draft: true, unlisted: false}, {draft: false, unlisted: true}, ], invalidFrontMatters: [ [ {draft: true, unlisted: true}, "Can't be draft and unlisted at the same time.", ], ], }); }); describe('validateBlogPostFrontMatter hide_table_of_contents', () => { testField({ prefix: 'hide_table_of_contents', validFrontMatters: [ {hide_table_of_contents: true}, {hide_table_of_contents: false}, ], convertibleFrontMatter: [ [{hide_table_of_contents: 'true'}, {hide_table_of_contents: true}], [{hide_table_of_contents: 'false'}, {hide_table_of_contents: false}], ], invalidFrontMatters: [ [{hide_table_of_contents: 'yes'}, 'must be a boolean'], [{hide_table_of_contents: 'no'}, 'must be a boolean'], ], }); }); describe('validateBlogPostFrontMatter date', () => { testField({ prefix: 'date', validFrontMatters: [ {date: new Date('2020-01-01')}, {date: '2020-01-01'}, {date: '2020'}, ], invalidFrontMatters: [ [{date: 'abc'}, 'must be a valid date'], [{date: ''}, 'must be a valid date'], ], }); });
1,043
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import {normalizePluginOptions} from '@docusaurus/utils-validation'; import {posixPath, getFileCommitDate} from '@docusaurus/utils'; import pluginContentBlog from '../index'; import {validateOptions} from '../options'; import type { DocusaurusConfig, LoadContext, I18n, Validate, } from '@docusaurus/types'; import type { BlogPost, Options, PluginOptions, EditUrlFunction, } from '@docusaurus/plugin-content-blog'; function findByTitle( blogPosts: BlogPost[], title: string, ): BlogPost | undefined { return blogPosts.find((v) => v.metadata.title === title); } function getByTitle(blogPosts: BlogPost[], title: string): BlogPost { const post = findByTitle(blogPosts, title); if (!post) { throw new Error(`can't find blog post with title ${title}. Available blog post titles are:\n- ${blogPosts .map((p) => p.metadata.title) .join('\n- ')}`); } return post; } function getI18n(locale: string): I18n { return { currentLocale: locale, locales: [locale], defaultLocale: locale, path: 'i18n', localeConfigs: { [locale]: { calendar: 'gregory', label: locale, htmlLang: locale, direction: 'ltr', path: locale, }, }, }; } const DefaultI18N: I18n = getI18n('en'); const PluginPath = 'blog'; const BaseEditUrl = 'https://baseEditUrl.com/edit'; const getPlugin = async ( siteDir: string, pluginOptions: Partial<PluginOptions> = {}, i18n: I18n = DefaultI18N, ) => { const generatedFilesDir: string = path.resolve(siteDir, '.docusaurus'); const localizationDir = path.join( siteDir, i18n.path, i18n.localeConfigs[i18n.currentLocale]!.path, ); const siteConfig = { title: 'Hello', baseUrl: '/', url: 'https://docusaurus.io', } as DocusaurusConfig; return pluginContentBlog( { siteDir, siteConfig, generatedFilesDir, i18n, localizationDir, } as LoadContext, validateOptions({ validate: normalizePluginOptions as Validate< Options | undefined, PluginOptions >, options: { path: PluginPath, editUrl: BaseEditUrl, ...pluginOptions, }, }), ); }; const getBlogPosts = async ( siteDir: string, pluginOptions: Partial<PluginOptions> = {}, i18n: I18n = DefaultI18N, ) => { const plugin = await getPlugin(siteDir, pluginOptions, i18n); const {blogPosts} = (await plugin.loadContent!())!; return blogPosts; }; const getBlogTags = async ( siteDir: string, pluginOptions: Partial<PluginOptions> = {}, i18n: I18n = DefaultI18N, ) => { const plugin = await getPlugin(siteDir, pluginOptions, i18n); const {blogTags} = (await plugin.loadContent!())!; return blogTags; }; describe('blog plugin', () => { it('getPathsToWatch returns right files', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const plugin = await getPlugin(siteDir); const pathsToWatch = plugin.getPathsToWatch!(); const relativePathsToWatch = pathsToWatch.map((p) => posixPath(path.relative(siteDir, p)), ); expect(relativePathsToWatch).toEqual([ 'i18n/en/docusaurus-plugin-content-blog/authors.yml', 'i18n/en/docusaurus-plugin-content-blog/**/*.{md,mdx}', 'blog/**/*.{md,mdx}', ]); }); it('builds a simple website', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const blogPosts = await getBlogPosts(siteDir); expect({ ...getByTitle(blogPosts, 'date-matter').metadata, ...{prevItem: undefined}, }).toEqual({ editUrl: `${BaseEditUrl}/blog/date-matter.md`, permalink: '/blog/date-matter', readingTime: 0.02, source: path.posix.join('@site', PluginPath, 'date-matter.md'), title: 'date-matter', description: `date inside front matter`, authors: [], date: new Date('2019-01-01'), formattedDate: 'January 1, 2019', frontMatter: { date: new Date('2019-01-01'), tags: ['date'], }, prevItem: undefined, tags: [ { label: 'date', permalink: '/blog/tags/date', }, ], nextItem: { permalink: '/blog/2018/12/14/Happy-First-Birthday-Slash', title: 'Happy 1st Birthday Slash! (translated)', }, hasTruncateMarker: false, unlisted: false, }); expect( getByTitle(blogPosts, 'Happy 1st Birthday Slash! (translated)').metadata, ).toEqual({ editUrl: `${BaseEditUrl}/blog/2018-12-14-Happy-First-Birthday-Slash.md`, permalink: '/blog/2018/12/14/Happy-First-Birthday-Slash', readingTime: 0.015, source: path.posix.join( '@site', path.posix.join('i18n', 'en', 'docusaurus-plugin-content-blog'), '2018-12-14-Happy-First-Birthday-Slash.md', ), title: 'Happy 1st Birthday Slash! (translated)', description: `Happy birthday! (translated)`, authors: [ { name: 'Yangshun Tay (translated)', }, { email: '[email protected]', key: 'slorber', name: 'Sébastien Lorber (translated)', title: 'Docusaurus maintainer (translated)', }, ], date: new Date('2018-12-14'), formattedDate: 'December 14, 2018', frontMatter: { authors: [ { name: 'Yangshun Tay (translated)', }, 'slorber', ], title: 'Happy 1st Birthday Slash! (translated)', }, tags: [], prevItem: { permalink: '/blog/date-matter', title: 'date-matter', }, hasTruncateMarker: false, unlisted: false, }); expect({ ...getByTitle(blogPosts, 'Complex Slug').metadata, ...{prevItem: undefined}, }).toEqual({ editUrl: `${BaseEditUrl}/blog/complex-slug.md`, permalink: '/blog/hey/my super path/héllô', readingTime: 0.015, source: path.posix.join('@site', PluginPath, 'complex-slug.md'), title: 'Complex Slug', description: `complex url slug`, authors: [], prevItem: undefined, nextItem: { permalink: '/blog/simple/slug', title: 'Simple Slug', }, date: new Date('2020-08-16'), formattedDate: 'August 16, 2020', frontMatter: { date: '2020/08/16', slug: '/hey/my super path/héllô', title: 'Complex Slug', tags: ['date', 'complex'], }, tags: [ { label: 'date', permalink: '/blog/tags/date', }, { label: 'complex', permalink: '/blog/tags/complex', }, ], hasTruncateMarker: false, unlisted: false, }); expect({ ...getByTitle(blogPosts, 'Simple Slug').metadata, ...{prevItem: undefined}, }).toEqual({ editUrl: `${BaseEditUrl}/blog/simple-slug.md`, permalink: '/blog/simple/slug', readingTime: 0.015, source: path.posix.join('@site', PluginPath, 'simple-slug.md'), title: 'Simple Slug', description: `simple url slug`, authors: [ { name: 'Sébastien Lorber', title: 'Docusaurus maintainer', url: 'https://sebastienlorber.com', imageURL: undefined, }, ], prevItem: undefined, nextItem: { permalink: '/blog/draft', title: 'draft', }, date: new Date('2020-08-15'), formattedDate: 'August 15, 2020', frontMatter: { author: 'Sébastien Lorber', author_title: 'Docusaurus maintainer', author_url: 'https://sebastienlorber.com', date: new Date('2020-08-15'), slug: '/simple/slug', title: 'Simple Slug', }, tags: [], hasTruncateMarker: false, unlisted: false, }); expect({ ...getByTitle(blogPosts, 'some heading').metadata, prevItem: undefined, }).toEqual({ editUrl: `${BaseEditUrl}/blog/heading-as-title.md`, permalink: '/blog/heading-as-title', readingTime: 0, source: path.posix.join('@site', PluginPath, 'heading-as-title.md'), title: 'some heading', description: '', authors: [], date: new Date('2019-01-02'), formattedDate: 'January 2, 2019', frontMatter: { date: new Date('2019-01-02'), }, prevItem: undefined, tags: [], nextItem: { permalink: '/blog/date-matter', title: 'date-matter', }, hasTruncateMarker: false, unlisted: false, }); }); it('builds simple website blog with localized dates', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const blogPostsFrench = await getBlogPosts(siteDir, {}, getI18n('fr')); expect(blogPostsFrench).toHaveLength(10); expect(blogPostsFrench[0]!.metadata.formattedDate).toMatchInlineSnapshot( `"23 juillet 2023"`, ); expect(blogPostsFrench[1]!.metadata.formattedDate).toMatchInlineSnapshot( `"6 mars 2021"`, ); expect(blogPostsFrench[2]!.metadata.formattedDate).toMatchInlineSnapshot( `"5 mars 2021"`, ); expect(blogPostsFrench[3]!.metadata.formattedDate).toMatchInlineSnapshot( `"16 août 2020"`, ); expect(blogPostsFrench[4]!.metadata.formattedDate).toMatchInlineSnapshot( `"15 août 2020"`, ); expect(blogPostsFrench[5]!.metadata.formattedDate).toMatchInlineSnapshot( `"27 février 2020"`, ); expect(blogPostsFrench[6]!.metadata.formattedDate).toMatchInlineSnapshot( `"27 février 2020"`, ); expect(blogPostsFrench[7]!.metadata.formattedDate).toMatchInlineSnapshot( `"2 janvier 2019"`, ); expect(blogPostsFrench[8]!.metadata.formattedDate).toMatchInlineSnapshot( `"1 janvier 2019"`, ); }); it('handles edit URL with editLocalizedBlogs: true', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const blogPosts = await getBlogPosts(siteDir, {editLocalizedFiles: true}); const localizedBlogPost = blogPosts.find( (v) => v.metadata.title === 'Happy 1st Birthday Slash! (translated)', )!; expect(localizedBlogPost.metadata.editUrl).toBe( `${BaseEditUrl}/i18n/en/docusaurus-plugin-content-blog/2018-12-14-Happy-First-Birthday-Slash.md`, ); }); it('handles edit URL with editUrl function', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const hardcodedEditUrl = 'hardcoded-edit-url'; const editUrlFunction: EditUrlFunction = jest.fn(() => hardcodedEditUrl); const blogPosts = await getBlogPosts(siteDir, {editUrl: editUrlFunction}); blogPosts.forEach((blogPost) => { expect(blogPost.metadata.editUrl).toEqual(hardcodedEditUrl); }); expect(editUrlFunction).toHaveBeenCalledTimes(10); expect(editUrlFunction).toHaveBeenCalledWith({ blogDirPath: 'blog', blogPath: 'date-matter.md', permalink: '/blog/date-matter', locale: 'en', }); expect(editUrlFunction).toHaveBeenCalledWith({ blogDirPath: 'blog', blogPath: 'draft.md', permalink: '/blog/draft', locale: 'en', }); expect(editUrlFunction).toHaveBeenCalledWith({ blogDirPath: 'blog', blogPath: 'mdx-blog-post.mdx', permalink: '/blog/mdx-blog-post', locale: 'en', }); expect(editUrlFunction).toHaveBeenCalledWith({ blogDirPath: 'blog', blogPath: 'mdx-require-blog-post.mdx', permalink: '/blog/mdx-require-blog-post', locale: 'en', }); expect(editUrlFunction).toHaveBeenCalledWith({ blogDirPath: 'blog', blogPath: 'complex-slug.md', permalink: '/blog/hey/my super path/héllô', locale: 'en', }); expect(editUrlFunction).toHaveBeenCalledWith({ blogDirPath: 'blog', blogPath: 'simple-slug.md', permalink: '/blog/simple/slug', locale: 'en', }); expect(editUrlFunction).toHaveBeenCalledWith({ blogDirPath: 'i18n/en/docusaurus-plugin-content-blog', blogPath: '2018-12-14-Happy-First-Birthday-Slash.md', permalink: '/blog/2018/12/14/Happy-First-Birthday-Slash', locale: 'en', }); expect(editUrlFunction).toHaveBeenCalledWith({ blogDirPath: 'blog', blogPath: 'heading-as-title.md', locale: 'en', permalink: '/blog/heading-as-title', }); }); it('excludes draft blog post from production build', async () => { const originalEnv = process.env; jest.resetModules(); process.env = {...originalEnv, NODE_ENV: 'production'}; const siteDir = path.join(__dirname, '__fixtures__', 'website'); const blogPosts = await getBlogPosts(siteDir); expect(blogPosts.find((v) => v.metadata.title === 'draft')).toBeUndefined(); process.env = originalEnv; }); it('creates blog post without date', async () => { const siteDir = path.join( __dirname, '__fixtures__', 'website-blog-without-date', ); const blogPosts = await getBlogPosts(siteDir); const noDateSource = path.posix.join('@site', PluginPath, 'no date.md'); const noDateSourceFile = path.posix.join(siteDir, PluginPath, 'no date.md'); // We know the file exists and we know we have git const result = getFileCommitDate(noDateSourceFile, {age: 'oldest'}); const noDateSourceTime = result.date; const formattedDate = Intl.DateTimeFormat('en', { day: 'numeric', month: 'long', year: 'numeric', }).format(noDateSourceTime); expect({ ...getByTitle(blogPosts, 'no date').metadata, ...{prevItem: undefined}, }).toEqual({ editUrl: `${BaseEditUrl}/blog/no date.md`, permalink: '/blog/no date', readingTime: 0.01, source: noDateSource, title: 'no date', description: `no date`, authors: [], date: noDateSourceTime, formattedDate, frontMatter: {}, tags: [], prevItem: undefined, nextItem: undefined, hasTruncateMarker: false, unlisted: false, }); }); it('can sort blog posts in ascending order', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'website'); const normalOrder = await getBlogPosts(siteDir); const reversedOrder = await getBlogPosts(siteDir, { sortPosts: 'ascending', }); expect(normalOrder.reverse().map((x) => x.metadata.date)).toEqual( reversedOrder.map((x) => x.metadata.date), ); }); it('works with blog tags', async () => { const siteDir = path.join( __dirname, '__fixtures__', 'website-blog-with-tags', ); const blogTags = await getBlogTags(siteDir, { postsPerPage: 2, }); expect(Object.keys(blogTags)).toHaveLength(3); expect(blogTags).toMatchSnapshot(); }); it('works on blog tags without pagination', async () => { const siteDir = path.join( __dirname, '__fixtures__', 'website-blog-with-tags', ); const blogTags = await getBlogTags(siteDir, { postsPerPage: 'ALL', }); expect(blogTags).toMatchSnapshot(); }); });
1,044
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/options.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {normalizePluginOptions} from '@docusaurus/utils-validation'; import {validateOptions, DEFAULT_OPTIONS} from '../options'; import type {Options, PluginOptions} from '@docusaurus/plugin-content-blog'; import type {Validate} from '@docusaurus/types'; function testValidate(options?: Options) { return validateOptions({ validate: normalizePluginOptions as Validate< Options | undefined, PluginOptions >, options, }); } // The type of remark/rehype plugins can be either function, object or array const markdownPluginsFunctionStub = () => {}; const markdownPluginsObjectStub = {}; const defaultOptions = {...DEFAULT_OPTIONS, id: 'default'}; describe('validateOptions', () => { it('returns default options for undefined user options', () => { expect(testValidate(undefined)).toEqual(defaultOptions); }); it('returns default options for empty user options', () => { expect(testValidate({})).toEqual(defaultOptions); }); it('accepts correctly defined user options', () => { const userOptions = { ...defaultOptions, feedOptions: {type: 'rss' as const, title: 'myTitle'}, path: 'not_blog', routeBasePath: '/myBlog', postsPerPage: 5, include: ['api/*', 'docs/*'], }; expect(testValidate(userOptions)).toEqual({ ...userOptions, feedOptions: {type: ['rss'], title: 'myTitle', copyright: '', limit: 20}, }); }); it('accepts valid user options', () => { const userOptions: Options = { ...defaultOptions, routeBasePath: '/myBlog', beforeDefaultRemarkPlugins: [], beforeDefaultRehypePlugins: [markdownPluginsFunctionStub], remarkPlugins: [[markdownPluginsFunctionStub, {option1: '42'}]], rehypePlugins: [ markdownPluginsObjectStub, [markdownPluginsFunctionStub, {option1: '42'}], ], }; expect(testValidate(userOptions)).toEqual(userOptions); }); it('throws Error in case of invalid options', () => { expect(() => testValidate({ path: 'not_blog', postsPerPage: -1, include: ['api/*', 'docs/*'], routeBasePath: 'not_blog', }), ).toThrowErrorMatchingSnapshot(); }); it('throws Error in case of invalid feed type', () => { expect(() => testValidate({ feedOptions: { // @ts-expect-error: test type: 'none', }, }), ).toThrowErrorMatchingSnapshot(); }); it('converts all feed type to array with other feed type', () => { expect( testValidate({ feedOptions: {type: 'all'}, }), ).toEqual({ ...defaultOptions, feedOptions: {type: ['rss', 'atom', 'json'], copyright: '', limit: 20}, }); }); it('accepts null type and return same', () => { expect( testValidate({ feedOptions: {type: null}, }), ).toEqual({ ...defaultOptions, feedOptions: {type: null, limit: 20}, }); }); it('contains array with rss + atom for missing feed type', () => { expect( testValidate({ feedOptions: {}, }), ).toEqual(defaultOptions); }); it('has array with rss + atom, title for missing feed type', () => { expect( testValidate({ feedOptions: {title: 'title'}, }), ).toEqual({ ...defaultOptions, feedOptions: { type: ['rss', 'atom'], title: 'title', copyright: '', limit: 20, }, }); }); it('accepts 0 sidebar count', () => { const userOptions = {blogSidebarCount: 0}; expect(testValidate(userOptions)).toEqual({ ...defaultOptions, ...userOptions, }); }); it('accepts "ALL" sidebar count', () => { const userOptions = {blogSidebarCount: 'ALL' as const}; expect(testValidate(userOptions)).toEqual({ ...defaultOptions, ...userOptions, }); }); it('rejects "abcdef" sidebar count', () => { const userOptions = {blogSidebarCount: 'abcdef'}; // @ts-expect-error: test expect(() => testValidate(userOptions)).toThrowErrorMatchingInlineSnapshot( `""blogSidebarCount" must be one of [ALL, number]"`, ); }); it('accepts "all posts" sidebar title', () => { const userOptions = {blogSidebarTitle: 'all posts'}; expect(testValidate(userOptions)).toEqual({ ...defaultOptions, ...userOptions, }); }); it('rejects 42 sidebar title', () => { const userOptions = {blogSidebarTitle: 42}; // @ts-expect-error: test expect(() => testValidate(userOptions)).toThrowErrorMatchingInlineSnapshot( `""blogSidebarTitle" must be a string"`, ); }); });
1,045
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/props.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {toTagsProp} from '../props'; describe('toTagsProp', () => { type Tags = Parameters<typeof toTagsProp>[0]['blogTags']; type Tag = Tags[number]; const tag1: Tag = { label: 'Tag 1', permalink: '/tag1', items: ['item1', 'item2'], pages: [], unlisted: false, }; const tag2: Tag = { label: 'Tag 2', permalink: '/tag2', items: ['item3'], pages: [], unlisted: false, }; function testTags(...tags: Tag[]) { const blogTags: Tags = {}; tags.forEach((tag) => { blogTags[tag.permalink] = tag; }); return toTagsProp({blogTags}); } it('works', () => { expect(testTags(tag1, tag2)).toEqual([ { count: tag1.items.length, label: tag1.label, permalink: tag1.permalink, }, { count: tag2.items.length, label: tag2.label, permalink: tag2.permalink, }, ]); }); it('filters unlisted tags', () => { expect(testTags(tag1, {...tag2, unlisted: true})).toEqual([ { count: tag1.items.length, label: tag1.label, permalink: tag1.permalink, }, ]); expect(testTags({...tag1, unlisted: true}, tag2)).toEqual([ { count: tag2.items.length, label: tag2.label, permalink: tag2.permalink, }, ]); }); });
1,046
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/translations.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {updateTranslationFileMessages} from '@docusaurus/utils'; import {getTranslationFiles, translateContent} from '../translations'; import {DEFAULT_OPTIONS} from '../options'; import type { PluginOptions, BlogPost, BlogContent, } from '@docusaurus/plugin-content-blog'; const sampleBlogOptions: PluginOptions = { ...DEFAULT_OPTIONS, blogSidebarTitle: 'All my posts', blogTitle: 'My blog', blogDescription: "Someone's random blog", }; const sampleBlogPosts: BlogPost[] = [ { id: 'hello', metadata: { permalink: '/blog/2021/06/19/hello', source: '/blog/2021/06/19/hello', description: '/blog/2021/06/19/hello', date: new Date(2021, 6, 19), formattedDate: 'June 19, 2021', tags: [], title: 'Hello', hasTruncateMarker: true, authors: [], frontMatter: {}, }, content: '', }, ]; const sampleBlogContent: BlogContent = { blogSidebarTitle: sampleBlogOptions.blogSidebarTitle, blogListPaginated: [ { items: ['hello'], metadata: { permalink: '/', page: 1, postsPerPage: 10, totalPages: 1, totalCount: 1, previousPage: undefined, nextPage: undefined, blogTitle: sampleBlogOptions.blogTitle, blogDescription: sampleBlogOptions.blogDescription, }, }, ], blogPosts: sampleBlogPosts, blogTags: {}, blogTagsListPath: '/tags', }; function getSampleTranslationFiles() { return getTranslationFiles(sampleBlogOptions); } function getSampleTranslationFilesTranslated() { const translationFiles = getSampleTranslationFiles(); return translationFiles.map((translationFile) => updateTranslationFileMessages( translationFile, (message) => `${message} (translated)`, ), ); } describe('getContentTranslationFiles', () => { it('returns translation files matching snapshot', () => { expect(getSampleTranslationFiles()).toMatchSnapshot(); }); }); describe('translateContent', () => { it('falls back when translation is incomplete', () => { expect( translateContent(sampleBlogContent, [{path: 'foo', content: {}}]), ).toMatchSnapshot(); }); it('does not translate anything if translation files are untranslated', () => { const translationFiles = getSampleTranslationFiles(); expect(translateContent(sampleBlogContent, translationFiles)).toEqual( sampleBlogContent, ); }); it('returns translated loaded', () => { const translationFiles = getSampleTranslationFilesTranslated(); expect( translateContent(sampleBlogContent, translationFiles), ).toMatchSnapshot(); }); });
1,106
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/__snapshots__/blogUtils.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`linkify reports broken markdown links 1`] = ` "--- title: This post links to another one! --- [Good link 1](/blog/2018/12/14/Happy-First-Birthday-Slash) [Good link 2](/blog/2018/12/14/Happy-First-Birthday-Slash) [Bad link 1](postNotExist1.md) [Bad link 1](./postNotExist2.mdx) " `; exports[`linkify transforms to correct link 1`] = ` "--- title: This post links to another one! --- [Linked post](/blog/2018/12/14/Happy-First-Birthday-Slash)" `; exports[`paginateBlogPosts generates right pages 1`] = ` [ { "items": [ "post1", "post2", ], "metadata": { "blogDescription": "Blog Description", "blogTitle": "Blog Title", "nextPage": "/blog/page/2", "page": 1, "permalink": "/blog", "postsPerPage": 2, "previousPage": undefined, "totalCount": 5, "totalPages": 3, }, }, { "items": [ "post3", "post4", ], "metadata": { "blogDescription": "Blog Description", "blogTitle": "Blog Title", "nextPage": "/blog/page/3", "page": 2, "permalink": "/blog/page/2", "postsPerPage": 2, "previousPage": "/blog", "totalCount": 5, "totalPages": 3, }, }, { "items": [ "post5", ], "metadata": { "blogDescription": "Blog Description", "blogTitle": "Blog Title", "nextPage": undefined, "page": 3, "permalink": "/blog/page/3", "postsPerPage": 2, "previousPage": "/blog/page/2", "totalCount": 5, "totalPages": 3, }, }, ] `; exports[`paginateBlogPosts generates right pages 2`] = ` [ { "items": [ "post1", "post2", ], "metadata": { "blogDescription": "Blog Description", "blogTitle": "Blog Title", "nextPage": "/page/2", "page": 1, "permalink": "/", "postsPerPage": 2, "previousPage": undefined, "totalCount": 5, "totalPages": 3, }, }, { "items": [ "post3", "post4", ], "metadata": { "blogDescription": "Blog Description", "blogTitle": "Blog Title", "nextPage": "/page/3", "page": 2, "permalink": "/page/2", "postsPerPage": 2, "previousPage": "/", "totalCount": 5, "totalPages": 3, }, }, { "items": [ "post5", ], "metadata": { "blogDescription": "Blog Description", "blogTitle": "Blog Title", "nextPage": undefined, "page": 3, "permalink": "/page/3", "postsPerPage": 2, "previousPage": "/page/2", "totalCount": 5, "totalPages": 3, }, }, ] `; exports[`paginateBlogPosts generates right pages 3`] = ` [ { "items": [ "post1", "post2", "post3", "post4", "post5", ], "metadata": { "blogDescription": "Blog Description", "blogTitle": "Blog Title", "nextPage": undefined, "page": 1, "permalink": "/", "postsPerPage": 10, "previousPage": undefined, "totalCount": 5, "totalPages": 1, }, }, ] `;
1,107
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/__snapshots__/feed.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`atom filters to the first two entries 1`] = ` [ "<?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <id>https://docusaurus.io/myBaseUrl/blog</id> <title>Hello Blog</title> <updated>2023-07-23T00:00:00.000Z</updated> <generator>https://github.com/jpmonette/feed</generator> <link rel="alternate" href="https://docusaurus.io/myBaseUrl/blog"/> <subtitle>Hello Blog</subtitle> <icon>https://docusaurus.io/myBaseUrl/image/favicon.ico</icon> <rights>Copyright</rights> <entry> <title type="html"><![CDATA[test links]]></title> <id>https://docusaurus.io/myBaseUrl/blog/blog-with-links</id> <link href="https://docusaurus.io/myBaseUrl/blog/blog-with-links"/> <updated>2023-07-23T00:00:00.000Z</updated> <summary type="html"><![CDATA[absolute full url]]></summary> <content type="html"><![CDATA[<p><a href="https://github.com/facebook/docusaurus" target="_blank" rel="noopener noreferrer">absolute full url</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">absolute pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">relative pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">md link</a></p> <p><a href="https://docusaurus.io/myBaseUrl/blog/blog-with-links#title">anchor</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title#title">relative pathname + anchor</a></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png" width="760" height="160" class="img_yGFe"></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/slash-introducing-411a16dd05086935b8e9ddae38ae9b45.svg" alt="" class="img_yGFe"></p> <img srcset="https://docusaurus.io/img/test-image.png 300w, https://docusaurus.io/img/docusaurus-social-card.png 500w"> <img src="https://docusaurus.io/img/test-image.png">]]></content> </entry> <entry> <title type="html"><![CDATA[MDX Blog Sample with require calls]]></title> <id>https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post</id> <link href="https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post"/> <updated>2021-03-06T00:00:00.000Z</updated> <summary type="html"><![CDATA[Test MDX with require calls]]></summary> <content type="html"><![CDATA[<p>Test MDX with require calls</p> <!-- --> <!-- --> <img src="https://docusaurus.io/img/test-image.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png">]]></content> </entry> </feed>", ] `; exports[`atom filters to the first two entries using limit 1`] = ` [ "<?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <id>https://docusaurus.io/myBaseUrl/blog</id> <title>Hello Blog</title> <updated>2023-07-23T00:00:00.000Z</updated> <generator>https://github.com/jpmonette/feed</generator> <link rel="alternate" href="https://docusaurus.io/myBaseUrl/blog"/> <subtitle>Hello Blog</subtitle> <icon>https://docusaurus.io/myBaseUrl/image/favicon.ico</icon> <rights>Copyright</rights> <entry> <title type="html"><![CDATA[test links]]></title> <id>https://docusaurus.io/myBaseUrl/blog/blog-with-links</id> <link href="https://docusaurus.io/myBaseUrl/blog/blog-with-links"/> <updated>2023-07-23T00:00:00.000Z</updated> <summary type="html"><![CDATA[absolute full url]]></summary> <content type="html"><![CDATA[<p><a href="https://github.com/facebook/docusaurus" target="_blank" rel="noopener noreferrer">absolute full url</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">absolute pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">relative pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">md link</a></p> <p><a href="https://docusaurus.io/myBaseUrl/blog/blog-with-links#title">anchor</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title#title">relative pathname + anchor</a></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png" width="760" height="160" class="img_yGFe"></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/slash-introducing-411a16dd05086935b8e9ddae38ae9b45.svg" alt="" class="img_yGFe"></p> <img srcset="https://docusaurus.io/img/test-image.png 300w, https://docusaurus.io/img/docusaurus-social-card.png 500w"> <img src="https://docusaurus.io/img/test-image.png">]]></content> </entry> <entry> <title type="html"><![CDATA[MDX Blog Sample with require calls]]></title> <id>https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post</id> <link href="https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post"/> <updated>2021-03-06T00:00:00.000Z</updated> <summary type="html"><![CDATA[Test MDX with require calls]]></summary> <content type="html"><![CDATA[<p>Test MDX with require calls</p> <!-- --> <!-- --> <img src="https://docusaurus.io/img/test-image.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png">]]></content> </entry> </feed>", ] `; exports[`atom has feed item for each post 1`] = ` [ "<?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <id>https://docusaurus.io/myBaseUrl/blog</id> <title>Hello Blog</title> <updated>2023-07-23T00:00:00.000Z</updated> <generator>https://github.com/jpmonette/feed</generator> <link rel="alternate" href="https://docusaurus.io/myBaseUrl/blog"/> <subtitle>Hello Blog</subtitle> <icon>https://docusaurus.io/myBaseUrl/image/favicon.ico</icon> <rights>Copyright</rights> <entry> <title type="html"><![CDATA[test links]]></title> <id>https://docusaurus.io/myBaseUrl/blog/blog-with-links</id> <link href="https://docusaurus.io/myBaseUrl/blog/blog-with-links"/> <updated>2023-07-23T00:00:00.000Z</updated> <summary type="html"><![CDATA[absolute full url]]></summary> <content type="html"><![CDATA[<p><a href="https://github.com/facebook/docusaurus" target="_blank" rel="noopener noreferrer">absolute full url</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">absolute pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">relative pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">md link</a></p> <p><a href="https://docusaurus.io/myBaseUrl/blog/blog-with-links#title">anchor</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title#title">relative pathname + anchor</a></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png" width="760" height="160" class="img_yGFe"></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/slash-introducing-411a16dd05086935b8e9ddae38ae9b45.svg" alt="" class="img_yGFe"></p> <img srcset="https://docusaurus.io/img/test-image.png 300w, https://docusaurus.io/img/docusaurus-social-card.png 500w"> <img src="https://docusaurus.io/img/test-image.png">]]></content> </entry> <entry> <title type="html"><![CDATA[MDX Blog Sample with require calls]]></title> <id>https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post</id> <link href="https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post"/> <updated>2021-03-06T00:00:00.000Z</updated> <summary type="html"><![CDATA[Test MDX with require calls]]></summary> <content type="html"><![CDATA[<p>Test MDX with require calls</p> <!-- --> <!-- --> <img src="https://docusaurus.io/img/test-image.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png">]]></content> </entry> <entry> <title type="html"><![CDATA[Full Blog Sample]]></title> <id>https://docusaurus.io/myBaseUrl/blog/mdx-blog-post</id> <link href="https://docusaurus.io/myBaseUrl/blog/mdx-blog-post"/> <updated>2021-03-05T00:00:00.000Z</updated> <summary type="html"><![CDATA[HTML Heading 1]]></summary> <content type="html"><![CDATA[<h1>HTML Heading 1</h1> <h2>HTML Heading 2</h2> <p>HTML Paragraph</p> <!-- --> <!-- --> <p>Import DOM</p> <h1>Heading 1</h1> <h2 class="anchor anchorWithHideOnScrollNavbar_G5V2" id="heading-2">Heading 2<a href="https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-2" class="hash-link" aria-label="Direct link to Heading 2" title="Direct link to Heading 2">​</a></h2> <h3 class="anchor anchorWithHideOnScrollNavbar_G5V2" id="heading-3">Heading 3<a href="https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-3" class="hash-link" aria-label="Direct link to Heading 3" title="Direct link to Heading 3">​</a></h3> <h4 class="anchor anchorWithHideOnScrollNavbar_G5V2" id="heading-4">Heading 4<a href="https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-4" class="hash-link" aria-label="Direct link to Heading 4" title="Direct link to Heading 4">​</a></h4> <h5 class="anchor anchorWithHideOnScrollNavbar_G5V2" id="heading-5">Heading 5<a href="https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-5" class="hash-link" aria-label="Direct link to Heading 5" title="Direct link to Heading 5">​</a></h5> <ul> <li>list1</li> <li>list2</li> <li>list3</li> </ul> <ul> <li>list1</li> <li>list2</li> <li>list3</li> </ul> <p>Normal Text <em>Italics Text</em> <strong>Bold Text</strong></p> <p><a href="https://v2.docusaurus.io/" target="_blank" rel="noopener noreferrer">link</a> <img loading="lazy" src="https://v2.docusaurus.io/" alt="image" class="img_yGFe"></p>]]></content> </entry> <entry> <title type="html"><![CDATA[Complex Slug]]></title> <id>https://docusaurus.io/myBaseUrl/blog/hey/my super path/héllô</id> <link href="https://docusaurus.io/myBaseUrl/blog/hey/my super path/héllô"/> <updated>2020-08-16T00:00:00.000Z</updated> <summary type="html"><![CDATA[complex url slug]]></summary> <content type="html"><![CDATA[<p>complex url slug</p>]]></content> <category label="date" term="date"/> <category label="complex" term="complex"/> </entry> <entry> <title type="html"><![CDATA[Simple Slug]]></title> <id>https://docusaurus.io/myBaseUrl/blog/simple/slug</id> <link href="https://docusaurus.io/myBaseUrl/blog/simple/slug"/> <updated>2020-08-15T00:00:00.000Z</updated> <summary type="html"><![CDATA[simple url slug]]></summary> <content type="html"><![CDATA[<p>simple url slug</p>]]></content> <author> <name>Sébastien Lorber</name> <uri>https://sebastienlorber.com</uri> </author> </entry> <entry> <title type="html"><![CDATA[some heading]]></title> <id>https://docusaurus.io/myBaseUrl/blog/heading-as-title</id> <link href="https://docusaurus.io/myBaseUrl/blog/heading-as-title"/> <updated>2019-01-02T00:00:00.000Z</updated> </entry> <entry> <title type="html"><![CDATA[date-matter]]></title> <id>https://docusaurus.io/myBaseUrl/blog/date-matter</id> <link href="https://docusaurus.io/myBaseUrl/blog/date-matter"/> <updated>2019-01-01T00:00:00.000Z</updated> <summary type="html"><![CDATA[date inside front matter]]></summary> <content type="html"><![CDATA[<p>date inside front matter</p>]]></content> <category label="date" term="date"/> </entry> <entry> <title type="html"><![CDATA[Happy 1st Birthday Slash! (translated)]]></title> <id>https://docusaurus.io/myBaseUrl/blog/2018/12/14/Happy-First-Birthday-Slash</id> <link href="https://docusaurus.io/myBaseUrl/blog/2018/12/14/Happy-First-Birthday-Slash"/> <updated>2018-12-14T00:00:00.000Z</updated> <summary type="html"><![CDATA[Happy birthday! (translated)]]></summary> <content type="html"><![CDATA[<p>Happy birthday! (translated)</p>]]></content> <author> <name>Yangshun Tay (translated)</name> </author> <author> <name>Sébastien Lorber (translated)</name> <email>[email protected]</email> </author> </entry> </feed>", ] `; exports[`json filters to the first two entries 1`] = ` [ "{ "version": "https://jsonfeed.org/version/1", "title": "Hello Blog", "home_page_url": "https://docusaurus.io/myBaseUrl/blog", "description": "Hello Blog", "items": [ { "id": "https://docusaurus.io/myBaseUrl/blog/blog-with-links", "content_html": "<p><a href=\\"https://github.com/facebook/docusaurus\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">absolute full url</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title\\">absolute pathname</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title\\">relative pathname</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title\\">md link</a></p>/n<p><a href=\\"https://docusaurus.io/myBaseUrl/blog/blog-with-links#title\\">anchor</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title#title\\">relative pathname + anchor</a></p>/n<p><img loading=\\"lazy\\" src=\\"https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png\\" width=\\"760\\" height=\\"160\\" class=\\"img_yGFe\\"></p>/n<p><img loading=\\"lazy\\" src=\\"https://docusaurus.io/assets/images/slash-introducing-411a16dd05086935b8e9ddae38ae9b45.svg\\" alt=\\"\\" class=\\"img_yGFe\\"></p>/n<img srcset=\\"https://docusaurus.io/img/test-image.png 300w, https://docusaurus.io/img/docusaurus-social-card.png 500w\\">/n<img src=\\"https://docusaurus.io/img/test-image.png\\">", "url": "https://docusaurus.io/myBaseUrl/blog/blog-with-links", "title": "test links", "summary": "absolute full url", "date_modified": "2023-07-23T00:00:00.000Z", "tags": [] }, { "id": "https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post", "content_html": "<p>Test MDX with require calls</p>/n<!-- -->/n<!-- -->/n<img src=\\"https://docusaurus.io/img/test-image.png\\">/n<img src=\\"https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png\\">/n<img src=\\"https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png\\">", "url": "https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post", "title": "MDX Blog Sample with require calls", "summary": "Test MDX with require calls", "date_modified": "2021-03-06T00:00:00.000Z", "tags": [] } ] }", ] `; exports[`json filters to the first two entries using limit 1`] = ` [ "{ "version": "https://jsonfeed.org/version/1", "title": "Hello Blog", "home_page_url": "https://docusaurus.io/myBaseUrl/blog", "description": "Hello Blog", "items": [ { "id": "https://docusaurus.io/myBaseUrl/blog/blog-with-links", "content_html": "<p><a href=\\"https://github.com/facebook/docusaurus\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">absolute full url</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title\\">absolute pathname</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title\\">relative pathname</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title\\">md link</a></p>/n<p><a href=\\"https://docusaurus.io/myBaseUrl/blog/blog-with-links#title\\">anchor</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title#title\\">relative pathname + anchor</a></p>/n<p><img loading=\\"lazy\\" src=\\"https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png\\" width=\\"760\\" height=\\"160\\" class=\\"img_yGFe\\"></p>/n<p><img loading=\\"lazy\\" src=\\"https://docusaurus.io/assets/images/slash-introducing-411a16dd05086935b8e9ddae38ae9b45.svg\\" alt=\\"\\" class=\\"img_yGFe\\"></p>/n<img srcset=\\"https://docusaurus.io/img/test-image.png 300w, https://docusaurus.io/img/docusaurus-social-card.png 500w\\">/n<img src=\\"https://docusaurus.io/img/test-image.png\\">", "url": "https://docusaurus.io/myBaseUrl/blog/blog-with-links", "title": "test links", "summary": "absolute full url", "date_modified": "2023-07-23T00:00:00.000Z", "tags": [] }, { "id": "https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post", "content_html": "<p>Test MDX with require calls</p>/n<!-- -->/n<!-- -->/n<img src=\\"https://docusaurus.io/img/test-image.png\\">/n<img src=\\"https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png\\">/n<img src=\\"https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png\\">", "url": "https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post", "title": "MDX Blog Sample with require calls", "summary": "Test MDX with require calls", "date_modified": "2021-03-06T00:00:00.000Z", "tags": [] } ] }", ] `; exports[`json has feed item for each post 1`] = ` [ "{ "version": "https://jsonfeed.org/version/1", "title": "Hello Blog", "home_page_url": "https://docusaurus.io/myBaseUrl/blog", "description": "Hello Blog", "items": [ { "id": "https://docusaurus.io/myBaseUrl/blog/blog-with-links", "content_html": "<p><a href=\\"https://github.com/facebook/docusaurus\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">absolute full url</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title\\">absolute pathname</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title\\">relative pathname</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title\\">md link</a></p>/n<p><a href=\\"https://docusaurus.io/myBaseUrl/blog/blog-with-links#title\\">anchor</a></p>/n<p><a href=\\"https://docusaurus.io/blog/heading-as-title#title\\">relative pathname + anchor</a></p>/n<p><img loading=\\"lazy\\" src=\\"https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png\\" width=\\"760\\" height=\\"160\\" class=\\"img_yGFe\\"></p>/n<p><img loading=\\"lazy\\" src=\\"https://docusaurus.io/assets/images/slash-introducing-411a16dd05086935b8e9ddae38ae9b45.svg\\" alt=\\"\\" class=\\"img_yGFe\\"></p>/n<img srcset=\\"https://docusaurus.io/img/test-image.png 300w, https://docusaurus.io/img/docusaurus-social-card.png 500w\\">/n<img src=\\"https://docusaurus.io/img/test-image.png\\">", "url": "https://docusaurus.io/myBaseUrl/blog/blog-with-links", "title": "test links", "summary": "absolute full url", "date_modified": "2023-07-23T00:00:00.000Z", "tags": [] }, { "id": "https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post", "content_html": "<p>Test MDX with require calls</p>/n<!-- -->/n<!-- -->/n<img src=\\"https://docusaurus.io/img/test-image.png\\">/n<img src=\\"https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png\\">/n<img src=\\"https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png\\">", "url": "https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post", "title": "MDX Blog Sample with require calls", "summary": "Test MDX with require calls", "date_modified": "2021-03-06T00:00:00.000Z", "tags": [] }, { "id": "https://docusaurus.io/myBaseUrl/blog/mdx-blog-post", "content_html": "<h1>HTML Heading 1</h1>/n<h2>HTML Heading 2</h2>/n<p>HTML Paragraph</p>/n<!-- -->/n<!-- -->/n<p>Import DOM</p>/n<h1>Heading 1</h1>/n<h2 class=\\"anchor anchorWithHideOnScrollNavbar_G5V2\\" id=\\"heading-2\\">Heading 2<a href=\\"https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-2\\" class=\\"hash-link\\" aria-label=\\"Direct link to Heading 2\\" title=\\"Direct link to Heading 2\\">​</a></h2>/n<h3 class=\\"anchor anchorWithHideOnScrollNavbar_G5V2\\" id=\\"heading-3\\">Heading 3<a href=\\"https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-3\\" class=\\"hash-link\\" aria-label=\\"Direct link to Heading 3\\" title=\\"Direct link to Heading 3\\">​</a></h3>/n<h4 class=\\"anchor anchorWithHideOnScrollNavbar_G5V2\\" id=\\"heading-4\\">Heading 4<a href=\\"https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-4\\" class=\\"hash-link\\" aria-label=\\"Direct link to Heading 4\\" title=\\"Direct link to Heading 4\\">​</a></h4>/n<h5 class=\\"anchor anchorWithHideOnScrollNavbar_G5V2\\" id=\\"heading-5\\">Heading 5<a href=\\"https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-5\\" class=\\"hash-link\\" aria-label=\\"Direct link to Heading 5\\" title=\\"Direct link to Heading 5\\">​</a></h5>/n<ul>/n<li>list1</li>/n<li>list2</li>/n<li>list3</li>/n</ul>/n<ul>/n<li>list1</li>/n<li>list2</li>/n<li>list3</li>/n</ul>/n<p>Normal Text <em>Italics Text</em> <strong>Bold Text</strong></p>/n<p><a href=\\"https://v2.docusaurus.io/\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">link</a> <img loading=\\"lazy\\" src=\\"https://v2.docusaurus.io/\\" alt=\\"image\\" class=\\"img_yGFe\\"></p>", "url": "https://docusaurus.io/myBaseUrl/blog/mdx-blog-post", "title": "Full Blog Sample", "summary": "HTML Heading 1", "date_modified": "2021-03-05T00:00:00.000Z", "tags": [] }, { "id": "https://docusaurus.io/myBaseUrl/blog/hey/my super path/héllô", "content_html": "<p>complex url slug</p>", "url": "https://docusaurus.io/myBaseUrl/blog/hey/my super path/héllô", "title": "Complex Slug", "summary": "complex url slug", "date_modified": "2020-08-16T00:00:00.000Z", "tags": [ "date", "complex" ] }, { "id": "https://docusaurus.io/myBaseUrl/blog/simple/slug", "content_html": "<p>simple url slug</p>", "url": "https://docusaurus.io/myBaseUrl/blog/simple/slug", "title": "Simple Slug", "summary": "simple url slug", "date_modified": "2020-08-15T00:00:00.000Z", "author": { "name": "Sébastien Lorber", "url": "https://sebastienlorber.com" }, "tags": [] }, { "id": "https://docusaurus.io/myBaseUrl/blog/heading-as-title", "content_html": "", "url": "https://docusaurus.io/myBaseUrl/blog/heading-as-title", "title": "some heading", "date_modified": "2019-01-02T00:00:00.000Z", "tags": [] }, { "id": "https://docusaurus.io/myBaseUrl/blog/date-matter", "content_html": "<p>date inside front matter</p>", "url": "https://docusaurus.io/myBaseUrl/blog/date-matter", "title": "date-matter", "summary": "date inside front matter", "date_modified": "2019-01-01T00:00:00.000Z", "tags": [ "date" ] }, { "id": "https://docusaurus.io/myBaseUrl/blog/2018/12/14/Happy-First-Birthday-Slash", "content_html": "<p>Happy birthday! (translated)</p>", "url": "https://docusaurus.io/myBaseUrl/blog/2018/12/14/Happy-First-Birthday-Slash", "title": "Happy 1st Birthday Slash! (translated)", "summary": "Happy birthday! (translated)", "date_modified": "2018-12-14T00:00:00.000Z", "author": { "name": "Yangshun Tay (translated)" }, "tags": [] } ] }", ] `; exports[`rss filters to the first two entries 1`] = ` [ "<?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"> <channel> <title>Hello Blog</title> <link>https://docusaurus.io/myBaseUrl/blog</link> <description>Hello Blog</description> <lastBuildDate>Sun, 23 Jul 2023 00:00:00 GMT</lastBuildDate> <docs>https://validator.w3.org/feed/docs/rss2.html</docs> <generator>https://github.com/jpmonette/feed</generator> <language>en</language> <copyright>Copyright</copyright> <item> <title><![CDATA[test links]]></title> <link>https://docusaurus.io/myBaseUrl/blog/blog-with-links</link> <guid>https://docusaurus.io/myBaseUrl/blog/blog-with-links</guid> <pubDate>Sun, 23 Jul 2023 00:00:00 GMT</pubDate> <description><![CDATA[absolute full url]]></description> <content:encoded><![CDATA[<p><a href="https://github.com/facebook/docusaurus" target="_blank" rel="noopener noreferrer">absolute full url</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">absolute pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">relative pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">md link</a></p> <p><a href="https://docusaurus.io/myBaseUrl/blog/blog-with-links#title">anchor</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title#title">relative pathname + anchor</a></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png" width="760" height="160" class="img_yGFe"></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/slash-introducing-411a16dd05086935b8e9ddae38ae9b45.svg" alt="" class="img_yGFe"></p> <img srcset="https://docusaurus.io/img/test-image.png 300w, https://docusaurus.io/img/docusaurus-social-card.png 500w"> <img src="https://docusaurus.io/img/test-image.png">]]></content:encoded> </item> <item> <title><![CDATA[MDX Blog Sample with require calls]]></title> <link>https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post</link> <guid>https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post</guid> <pubDate>Sat, 06 Mar 2021 00:00:00 GMT</pubDate> <description><![CDATA[Test MDX with require calls]]></description> <content:encoded><![CDATA[<p>Test MDX with require calls</p> <!-- --> <!-- --> <img src="https://docusaurus.io/img/test-image.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png">]]></content:encoded> </item> </channel> </rss>", ] `; exports[`rss filters to the first two entries using limit 1`] = ` [ "<?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"> <channel> <title>Hello Blog</title> <link>https://docusaurus.io/myBaseUrl/blog</link> <description>Hello Blog</description> <lastBuildDate>Sun, 23 Jul 2023 00:00:00 GMT</lastBuildDate> <docs>https://validator.w3.org/feed/docs/rss2.html</docs> <generator>https://github.com/jpmonette/feed</generator> <language>en</language> <copyright>Copyright</copyright> <item> <title><![CDATA[test links]]></title> <link>https://docusaurus.io/myBaseUrl/blog/blog-with-links</link> <guid>https://docusaurus.io/myBaseUrl/blog/blog-with-links</guid> <pubDate>Sun, 23 Jul 2023 00:00:00 GMT</pubDate> <description><![CDATA[absolute full url]]></description> <content:encoded><![CDATA[<p><a href="https://github.com/facebook/docusaurus" target="_blank" rel="noopener noreferrer">absolute full url</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">absolute pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">relative pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">md link</a></p> <p><a href="https://docusaurus.io/myBaseUrl/blog/blog-with-links#title">anchor</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title#title">relative pathname + anchor</a></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png" width="760" height="160" class="img_yGFe"></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/slash-introducing-411a16dd05086935b8e9ddae38ae9b45.svg" alt="" class="img_yGFe"></p> <img srcset="https://docusaurus.io/img/test-image.png 300w, https://docusaurus.io/img/docusaurus-social-card.png 500w"> <img src="https://docusaurus.io/img/test-image.png">]]></content:encoded> </item> <item> <title><![CDATA[MDX Blog Sample with require calls]]></title> <link>https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post</link> <guid>https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post</guid> <pubDate>Sat, 06 Mar 2021 00:00:00 GMT</pubDate> <description><![CDATA[Test MDX with require calls]]></description> <content:encoded><![CDATA[<p>Test MDX with require calls</p> <!-- --> <!-- --> <img src="https://docusaurus.io/img/test-image.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png">]]></content:encoded> </item> </channel> </rss>", ] `; exports[`rss has feed item for each post 1`] = ` [ "<?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"> <channel> <title>Hello Blog</title> <link>https://docusaurus.io/myBaseUrl/blog</link> <description>Hello Blog</description> <lastBuildDate>Sun, 23 Jul 2023 00:00:00 GMT</lastBuildDate> <docs>https://validator.w3.org/feed/docs/rss2.html</docs> <generator>https://github.com/jpmonette/feed</generator> <language>en</language> <copyright>Copyright</copyright> <item> <title><![CDATA[test links]]></title> <link>https://docusaurus.io/myBaseUrl/blog/blog-with-links</link> <guid>https://docusaurus.io/myBaseUrl/blog/blog-with-links</guid> <pubDate>Sun, 23 Jul 2023 00:00:00 GMT</pubDate> <description><![CDATA[absolute full url]]></description> <content:encoded><![CDATA[<p><a href="https://github.com/facebook/docusaurus" target="_blank" rel="noopener noreferrer">absolute full url</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">absolute pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">relative pathname</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title">md link</a></p> <p><a href="https://docusaurus.io/myBaseUrl/blog/blog-with-links#title">anchor</a></p> <p><a href="https://docusaurus.io/blog/heading-as-title#title">relative pathname + anchor</a></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png" width="760" height="160" class="img_yGFe"></p> <p><img loading="lazy" src="https://docusaurus.io/assets/images/slash-introducing-411a16dd05086935b8e9ddae38ae9b45.svg" alt="" class="img_yGFe"></p> <img srcset="https://docusaurus.io/img/test-image.png 300w, https://docusaurus.io/img/docusaurus-social-card.png 500w"> <img src="https://docusaurus.io/img/test-image.png">]]></content:encoded> </item> <item> <title><![CDATA[MDX Blog Sample with require calls]]></title> <link>https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post</link> <guid>https://docusaurus.io/myBaseUrl/blog/mdx-require-blog-post</guid> <pubDate>Sat, 06 Mar 2021 00:00:00 GMT</pubDate> <description><![CDATA[Test MDX with require calls]]></description> <content:encoded><![CDATA[<p>Test MDX with require calls</p> <!-- --> <!-- --> <img src="https://docusaurus.io/img/test-image.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png"> <img src="https://docusaurus.io/assets/images/test-image-742d39e51f41482e8132e79c09ad4eea.png">]]></content:encoded> </item> <item> <title><![CDATA[Full Blog Sample]]></title> <link>https://docusaurus.io/myBaseUrl/blog/mdx-blog-post</link> <guid>https://docusaurus.io/myBaseUrl/blog/mdx-blog-post</guid> <pubDate>Fri, 05 Mar 2021 00:00:00 GMT</pubDate> <description><![CDATA[HTML Heading 1]]></description> <content:encoded><![CDATA[<h1>HTML Heading 1</h1> <h2>HTML Heading 2</h2> <p>HTML Paragraph</p> <!-- --> <!-- --> <p>Import DOM</p> <h1>Heading 1</h1> <h2 class="anchor anchorWithHideOnScrollNavbar_G5V2" id="heading-2">Heading 2<a href="https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-2" class="hash-link" aria-label="Direct link to Heading 2" title="Direct link to Heading 2">​</a></h2> <h3 class="anchor anchorWithHideOnScrollNavbar_G5V2" id="heading-3">Heading 3<a href="https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-3" class="hash-link" aria-label="Direct link to Heading 3" title="Direct link to Heading 3">​</a></h3> <h4 class="anchor anchorWithHideOnScrollNavbar_G5V2" id="heading-4">Heading 4<a href="https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-4" class="hash-link" aria-label="Direct link to Heading 4" title="Direct link to Heading 4">​</a></h4> <h5 class="anchor anchorWithHideOnScrollNavbar_G5V2" id="heading-5">Heading 5<a href="https://docusaurus.io/myBaseUrl/blog/mdx-blog-post#heading-5" class="hash-link" aria-label="Direct link to Heading 5" title="Direct link to Heading 5">​</a></h5> <ul> <li>list1</li> <li>list2</li> <li>list3</li> </ul> <ul> <li>list1</li> <li>list2</li> <li>list3</li> </ul> <p>Normal Text <em>Italics Text</em> <strong>Bold Text</strong></p> <p><a href="https://v2.docusaurus.io/" target="_blank" rel="noopener noreferrer">link</a> <img loading="lazy" src="https://v2.docusaurus.io/" alt="image" class="img_yGFe"></p>]]></content:encoded> </item> <item> <title><![CDATA[Complex Slug]]></title> <link>https://docusaurus.io/myBaseUrl/blog/hey/my super path/héllô</link> <guid>https://docusaurus.io/myBaseUrl/blog/hey/my super path/héllô</guid> <pubDate>Sun, 16 Aug 2020 00:00:00 GMT</pubDate> <description><![CDATA[complex url slug]]></description> <content:encoded><![CDATA[<p>complex url slug</p>]]></content:encoded> <category>date</category> <category>complex</category> </item> <item> <title><![CDATA[Simple Slug]]></title> <link>https://docusaurus.io/myBaseUrl/blog/simple/slug</link> <guid>https://docusaurus.io/myBaseUrl/blog/simple/slug</guid> <pubDate>Sat, 15 Aug 2020 00:00:00 GMT</pubDate> <description><![CDATA[simple url slug]]></description> <content:encoded><![CDATA[<p>simple url slug</p>]]></content:encoded> </item> <item> <title><![CDATA[some heading]]></title> <link>https://docusaurus.io/myBaseUrl/blog/heading-as-title</link> <guid>https://docusaurus.io/myBaseUrl/blog/heading-as-title</guid> <pubDate>Wed, 02 Jan 2019 00:00:00 GMT</pubDate> </item> <item> <title><![CDATA[date-matter]]></title> <link>https://docusaurus.io/myBaseUrl/blog/date-matter</link> <guid>https://docusaurus.io/myBaseUrl/blog/date-matter</guid> <pubDate>Tue, 01 Jan 2019 00:00:00 GMT</pubDate> <description><![CDATA[date inside front matter]]></description> <content:encoded><![CDATA[<p>date inside front matter</p>]]></content:encoded> <category>date</category> </item> <item> <title><![CDATA[Happy 1st Birthday Slash! (translated)]]></title> <link>https://docusaurus.io/myBaseUrl/blog/2018/12/14/Happy-First-Birthday-Slash</link> <guid>https://docusaurus.io/myBaseUrl/blog/2018/12/14/Happy-First-Birthday-Slash</guid> <pubDate>Fri, 14 Dec 2018 00:00:00 GMT</pubDate> <description><![CDATA[Happy birthday! (translated)]]></description> <content:encoded><![CDATA[<p>Happy birthday! (translated)</p>]]></content:encoded> <author>[email protected] (Sébastien Lorber (translated))</author> </item> </channel> </rss>", ] `;
1,108
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`blog plugin works on blog tags without pagination 1`] = ` { "/blog/tags/tag-1": { "items": [ "/simple/slug/another", "/another/tags", "/another/tags2", ], "label": "tag1", "pages": [ { "items": [ "/simple/slug/another", "/another/tags", "/another/tags2", ], "metadata": { "blogDescription": "Blog", "blogTitle": "Blog", "nextPage": undefined, "page": 1, "permalink": "/blog/tags/tag-1", "postsPerPage": 3, "previousPage": undefined, "totalCount": 3, "totalPages": 1, }, }, ], "permalink": "/blog/tags/tag-1", "unlisted": false, }, "/blog/tags/tag-2": { "items": [ "/another/tags", "/another/tags2", ], "label": "tag2", "pages": [ { "items": [ "/another/tags", "/another/tags2", ], "metadata": { "blogDescription": "Blog", "blogTitle": "Blog", "nextPage": undefined, "page": 1, "permalink": "/blog/tags/tag-2", "postsPerPage": 2, "previousPage": undefined, "totalCount": 2, "totalPages": 1, }, }, ], "permalink": "/blog/tags/tag-2", "unlisted": false, }, "/blog/tags/unlisted": { "items": [ "/another/blog-with-tags-unlisted", ], "label": "unlisted", "pages": [ { "items": [ "/another/blog-with-tags-unlisted", ], "metadata": { "blogDescription": "Blog", "blogTitle": "Blog", "nextPage": undefined, "page": 1, "permalink": "/blog/tags/unlisted", "postsPerPage": 1, "previousPage": undefined, "totalCount": 1, "totalPages": 1, }, }, ], "permalink": "/blog/tags/unlisted", "unlisted": false, }, } `; exports[`blog plugin works with blog tags 1`] = ` { "/blog/tags/tag-1": { "items": [ "/simple/slug/another", "/another/tags", "/another/tags2", ], "label": "tag1", "pages": [ { "items": [ "/simple/slug/another", "/another/tags", ], "metadata": { "blogDescription": "Blog", "blogTitle": "Blog", "nextPage": "/blog/tags/tag-1/page/2", "page": 1, "permalink": "/blog/tags/tag-1", "postsPerPage": 2, "previousPage": undefined, "totalCount": 3, "totalPages": 2, }, }, { "items": [ "/another/tags2", ], "metadata": { "blogDescription": "Blog", "blogTitle": "Blog", "nextPage": undefined, "page": 2, "permalink": "/blog/tags/tag-1/page/2", "postsPerPage": 2, "previousPage": "/blog/tags/tag-1", "totalCount": 3, "totalPages": 2, }, }, ], "permalink": "/blog/tags/tag-1", "unlisted": false, }, "/blog/tags/tag-2": { "items": [ "/another/tags", "/another/tags2", ], "label": "tag2", "pages": [ { "items": [ "/another/tags", "/another/tags2", ], "metadata": { "blogDescription": "Blog", "blogTitle": "Blog", "nextPage": undefined, "page": 1, "permalink": "/blog/tags/tag-2", "postsPerPage": 2, "previousPage": undefined, "totalCount": 2, "totalPages": 1, }, }, ], "permalink": "/blog/tags/tag-2", "unlisted": false, }, "/blog/tags/unlisted": { "items": [ "/another/blog-with-tags-unlisted", ], "label": "unlisted", "pages": [ { "items": [ "/another/blog-with-tags-unlisted", ], "metadata": { "blogDescription": "Blog", "blogTitle": "Blog", "nextPage": undefined, "page": 1, "permalink": "/blog/tags/unlisted", "postsPerPage": 2, "previousPage": undefined, "totalCount": 1, "totalPages": 1, }, }, ], "permalink": "/blog/tags/unlisted", "unlisted": false, }, } `;
1,109
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/__snapshots__/options.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`validateOptions throws Error in case of invalid feed type 1`] = `""feedOptions.type" does not match any of the allowed types"`; exports[`validateOptions throws Error in case of invalid options 1`] = `""postsPerPage" must be greater than or equal to 1"`;
1,110
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/__tests__/__snapshots__/translations.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`getContentTranslationFiles returns translation files matching snapshot 1`] = ` [ { "content": { "description": { "description": "The description for the blog used in SEO", "message": "Someone's random blog", }, "sidebar.title": { "description": "The label for the left sidebar", "message": "All my posts", }, "title": { "description": "The title for the blog used in SEO", "message": "My blog", }, }, "path": "options", }, ] `; exports[`translateContent falls back when translation is incomplete 1`] = ` { "blogListPaginated": [ { "items": [ "hello", ], "metadata": { "blogDescription": "Someone's random blog", "blogTitle": "My blog", "nextPage": undefined, "page": 1, "permalink": "/", "postsPerPage": 10, "previousPage": undefined, "totalCount": 1, "totalPages": 1, }, }, ], "blogPosts": [ { "content": "", "id": "hello", "metadata": { "authors": [], "date": 2021-07-19T00:00:00.000Z, "description": "/blog/2021/06/19/hello", "formattedDate": "June 19, 2021", "frontMatter": {}, "hasTruncateMarker": true, "permalink": "/blog/2021/06/19/hello", "source": "/blog/2021/06/19/hello", "tags": [], "title": "Hello", }, }, ], "blogSidebarTitle": "All my posts", "blogTags": {}, "blogTagsListPath": "/tags", } `; exports[`translateContent returns translated loaded 1`] = ` { "blogListPaginated": [ { "items": [ "hello", ], "metadata": { "blogDescription": "Someone's random blog (translated)", "blogTitle": "My blog (translated)", "nextPage": undefined, "page": 1, "permalink": "/", "postsPerPage": 10, "previousPage": undefined, "totalCount": 1, "totalPages": 1, }, }, ], "blogPosts": [ { "content": "", "id": "hello", "metadata": { "authors": [], "date": 2021-07-19T00:00:00.000Z, "description": "/blog/2021/06/19/hello", "formattedDate": "June 19, 2021", "frontMatter": {}, "hasTruncateMarker": true, "permalink": "/blog/2021/06/19/hello", "source": "/blog/2021/06/19/hello", "tags": [], "title": "Hello", }, }, ], "blogSidebarTitle": "All my posts (translated)", "blogTags": {}, "blogTagsListPath": "/tags", } `;
1,112
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/remark
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/remark/__tests__/footnoteIDFixer.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import path from 'path'; import vfile from 'to-vfile'; import {simpleHash} from '@docusaurus/utils'; import footnoteIDFixer from '../footnoteIDFixer'; const processFixture = async (name: string) => { const mdx = await import('@mdx-js/mdx'); const {default: gfm} = await import('remark-gfm'); const filePath = path.join(__dirname, `__fixtures__/${name}.md`); const file = await vfile.read(filePath); const result = await mdx.compile(file, { remarkPlugins: [gfm, footnoteIDFixer], }); return result.value; }; describe('footnoteIDFixer remark plugin', () => { it('appends a hash to each footnote def/ref', async () => { const hash = simpleHash(path.join(__dirname, `__fixtures__/post.md`), 6); expect( (await processFixture('post')).replace(new RegExp(hash, 'g'), '[HASH]'), ).toMatchSnapshot(); }); it('produces different hashes for different posts but same hash for the same path', async () => { const file1 = await processFixture('post'); const file1again = await processFixture('post'); const file2 = await processFixture('post2'); expect(file1).toBe(file1again); expect(file1).not.toBe(file2); }); });
1,115
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/remark/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-blog/src/remark/__tests__/__snapshots__/footnoteIDFixer.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`footnoteIDFixer remark plugin appends a hash to each footnote def/ref 1`] = ` "import {Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs} from "react/jsx-runtime"; function _createMdxContent(props) { const _components = { a: "a", h2: "h2", li: "li", ol: "ol", p: "p", section: "section", sup: "sup", ...props.components }; return _jsxs(_Fragment, { children: [_jsxs(_components.p, { children: ["foo", _jsx(_components.sup, { children: _jsx(_components.a, { href: "#user-content-fn-1-[HASH]", id: "user-content-fnref-1-[HASH]", "data-footnote-ref": true, "aria-describedby": "footnote-label", children: "1" }) })] }), "/n", _jsxs(_components.p, { children: ["bar", _jsx(_components.sup, { children: _jsx(_components.a, { href: "#user-content-fn-2-[HASH]", id: "user-content-fnref-2-[HASH]", "data-footnote-ref": true, "aria-describedby": "footnote-label", children: "2" }) })] }), "/n", _jsxs(_components.p, { children: ["baz", _jsx(_components.sup, { children: _jsx(_components.a, { href: "#user-content-fn-3-[HASH]", id: "user-content-fnref-3-[HASH]", "data-footnote-ref": true, "aria-describedby": "footnote-label", children: "3" }) })] }), "/n", _jsxs(_components.section, { "data-footnotes": true, className: "footnotes", children: [_jsx(_components.h2, { className: "sr-only", id: "footnote-label", children: "Footnotes" }), "/n", _jsxs(_components.ol, { children: ["/n", _jsxs(_components.li, { id: "user-content-fn-1-[HASH]", children: ["/n", _jsxs(_components.p, { children: ["foo ", _jsx(_components.a, { href: "#user-content-fnref-1-[HASH]", "data-footnote-backref": "", "aria-label": "Back to reference 1", className: "data-footnote-backref", children: "↩" })] }), "/n"] }), "/n", _jsxs(_components.li, { id: "user-content-fn-2-[HASH]", children: ["/n", _jsxs(_components.p, { children: ["foo ", _jsx(_components.a, { href: "#user-content-fnref-2-[HASH]", "data-footnote-backref": "", "aria-label": "Back to reference 2", className: "data-footnote-backref", children: "↩" })] }), "/n"] }), "/n", _jsxs(_components.li, { id: "user-content-fn-3-[HASH]", children: ["/n", _jsxs(_components.p, { children: ["foo ", _jsx(_components.a, { href: "#user-content-fnref-3-[HASH]", "data-footnote-backref": "", "aria-label": "Back to reference 3", className: "data-footnote-backref", children: "↩" })] }), "/n"] }), "/n"] }), "/n"] })] }); } export default function MDXContent(props = {}) { const {wrapper: MDXLayout} = props.components || ({}); return MDXLayout ? _jsx(MDXLayout, { ...props, children: _jsx(_createMdxContent, { ...props }) }) : _createMdxContent(props); } " `;
1,139
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import fs from 'fs-extra'; import path from 'path'; import {DEFAULT_PLUGIN_ID} from '@docusaurus/utils'; import {cliDocsVersionCommand} from '../cli'; import { getVersionDocsDirPath, getVersionsFilePath, getVersionSidebarsPath, } from '../versions/files'; import type {PluginOptions} from '@docusaurus/plugin-content-docs'; import type {LoadContext} from '@docusaurus/types'; const fixtureDir = path.join(__dirname, '__fixtures__'); describe('docsVersion', () => { const simpleSiteDir = path.join(fixtureDir, 'simple-site'); const versionedSiteDir = path.join(fixtureDir, 'versioned-site'); const customI18nSiteDir = path.join(fixtureDir, 'site-with-custom-i18n-path'); const DEFAULT_OPTIONS = { id: 'default', path: 'docs', sidebarPath: '', sidebarCollapsed: true, sidebarCollapsible: true, } as PluginOptions; it('no version tag provided', async () => { await expect(() => cliDocsVersionCommand(null, DEFAULT_OPTIONS, { siteDir: simpleSiteDir, } as LoadContext), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Versions should be strings. Found type "object" for version null."`, ); await expect(() => cliDocsVersionCommand(undefined, DEFAULT_OPTIONS, { siteDir: simpleSiteDir, } as LoadContext), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Versions should be strings. Found type "undefined" for version undefined."`, ); await expect(() => cliDocsVersionCommand('', DEFAULT_OPTIONS, { siteDir: simpleSiteDir, } as LoadContext), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid version name "": version name must contain at least one non-whitespace character."`, ); }); it('version tag should not have slash', async () => { await expect(() => cliDocsVersionCommand('foo/bar', DEFAULT_OPTIONS, { siteDir: simpleSiteDir, } as LoadContext), ).rejects.toThrow( 'Invalid version name "foo/bar": version name should not include slash (/) or backslash (\\).', ); await expect(() => cliDocsVersionCommand('foo\\bar', DEFAULT_OPTIONS, { siteDir: simpleSiteDir, } as LoadContext), ).rejects.toThrow( 'Invalid version name "foo\\bar": version name should not include slash (/) or backslash (\\).', ); }); it('version tag should not be too long', async () => { await expect(() => cliDocsVersionCommand('a'.repeat(255), DEFAULT_OPTIONS, { siteDir: simpleSiteDir, } as LoadContext), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid version name "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": version name cannot be longer than 32 characters."`, ); }); it('version tag should not be a dot or two dots', async () => { await expect(() => cliDocsVersionCommand('..', DEFAULT_OPTIONS, { siteDir: simpleSiteDir, } as LoadContext), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid version name "..": version name should not be "." or ".."."`, ); await expect(() => cliDocsVersionCommand('.', DEFAULT_OPTIONS, { siteDir: simpleSiteDir, } as LoadContext), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid version name ".": version name should not be "." or ".."."`, ); }); it('version tag should be a valid pathname', async () => { await expect(() => cliDocsVersionCommand('<foo|bar>', DEFAULT_OPTIONS, { siteDir: simpleSiteDir, } as LoadContext), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid version name "<foo|bar>": version name should be a valid file path."`, ); await expect(() => cliDocsVersionCommand('foo\x00bar', DEFAULT_OPTIONS, { siteDir: simpleSiteDir, } as LoadContext), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid version name "foobar": version name should be a valid file path."`, ); await expect(() => cliDocsVersionCommand('foo:bar', DEFAULT_OPTIONS, { siteDir: simpleSiteDir, } as LoadContext), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid version name "foo:bar": version name should be a valid file path."`, ); }); it('version tag already exist', async () => { await expect(() => cliDocsVersionCommand('1.0.0', DEFAULT_OPTIONS, { siteDir: versionedSiteDir, } as LoadContext), ).rejects.toThrowErrorMatchingInlineSnapshot( `"[docs]: this version already exists! Use a version tag that does not already exist."`, ); }); it('no docs file to version', async () => { const emptySiteDir = path.join(fixtureDir, 'empty-site'); await expect(() => cliDocsVersionCommand('1.0.0', DEFAULT_OPTIONS, { siteDir: emptySiteDir, i18n: { locales: ['en', 'zh-Hans'], defaultLocale: 'en', path: 'i18n', localeConfigs: {en: {path: 'en'}, 'zh-Hans': {path: 'zh-Hans'}}, }, } as unknown as LoadContext), ).rejects.toThrowErrorMatchingInlineSnapshot( `"[docs]: no docs found in "<PROJECT_ROOT>/packages/docusaurus-plugin-content-docs/src/__tests__/__fixtures__/empty-site/docs"."`, ); }); it('first time versioning', async () => { const copyMock = jest.spyOn(fs, 'copy').mockImplementation(() => {}); const writeMock = jest.spyOn(fs, 'outputFile'); let versionedSidebar!: unknown; let versionedSidebarPath!: string; writeMock.mockImplementationOnce((filepath, content: string) => { versionedSidebarPath = filepath; versionedSidebar = JSON.parse(content); }); let versionsPath!: string; let versions!: unknown; writeMock.mockImplementationOnce((filepath, content: string) => { versionsPath = filepath; versions = JSON.parse(content); }); const consoleMock = jest.spyOn(console, 'log').mockImplementation(() => {}); const options = { ...DEFAULT_OPTIONS, sidebarPath: path.join(simpleSiteDir, 'sidebars.json'), }; await cliDocsVersionCommand('1.0.0', options, { siteDir: simpleSiteDir, i18n: { locales: ['en', 'zh-Hans'], defaultLocale: 'en', path: 'i18n', localeConfigs: {en: {path: 'en'}, 'zh-Hans': {path: 'zh-Hans'}}, }, } as unknown as LoadContext); expect(copyMock).toHaveBeenCalledWith( path.join(simpleSiteDir, options.path), getVersionDocsDirPath(simpleSiteDir, DEFAULT_PLUGIN_ID, '1.0.0'), ); expect(copyMock).toHaveBeenCalledWith( path.join( simpleSiteDir, 'i18n/zh-Hans/docusaurus-plugin-content-docs/current', ), path.join( simpleSiteDir, 'i18n/zh-Hans/docusaurus-plugin-content-docs/version-1.0.0', ), ); expect(versionedSidebar).toMatchSnapshot(); expect(versionedSidebarPath).toEqual( getVersionSidebarsPath(simpleSiteDir, DEFAULT_PLUGIN_ID, '1.0.0'), ); expect(versionsPath).toEqual( getVersionsFilePath(simpleSiteDir, DEFAULT_PLUGIN_ID), ); expect(versions).toEqual(['1.0.0']); expect(consoleMock).toHaveBeenCalledWith( expect.stringMatching( /.*\[SUCCESS\].*\[docs\].*: version .*1\.0\.0.* created!.*/, ), ); copyMock.mockRestore(); writeMock.mockRestore(); consoleMock.mockRestore(); }); it('works with custom i18n paths', async () => { const copyMock = jest.spyOn(fs, 'copy').mockImplementation(() => {}); const writeMock = jest.spyOn(fs, 'outputFile'); let versionedSidebar!: unknown; let versionedSidebarPath!: string; writeMock.mockImplementationOnce((filepath, content: string) => { versionedSidebarPath = filepath; versionedSidebar = JSON.parse(content); }); let versionsPath!: string; let versions!: unknown; writeMock.mockImplementationOnce((filepath, content: string) => { versionsPath = filepath; versions = JSON.parse(content); }); const consoleMock = jest.spyOn(console, 'log').mockImplementation(() => {}); const options = { ...DEFAULT_OPTIONS, sidebarPath: path.join(customI18nSiteDir, 'sidebars.json'), }; await cliDocsVersionCommand('1.0.0', options, { siteDir: customI18nSiteDir, i18n: { locales: ['en', 'zh-Hans'], defaultLocale: 'en', path: 'i18n-custom', localeConfigs: { en: {path: 'en-custom'}, 'zh-Hans': {path: 'zh-Hans-custom'}, }, }, } as unknown as LoadContext); expect(copyMock).toHaveBeenCalledWith( path.join(customI18nSiteDir, options.path), getVersionDocsDirPath(customI18nSiteDir, DEFAULT_PLUGIN_ID, '1.0.0'), ); expect(copyMock).toHaveBeenCalledWith( path.join( customI18nSiteDir, 'i18n-custom/zh-Hans-custom/docusaurus-plugin-content-docs/current', ), path.join( customI18nSiteDir, 'i18n-custom/zh-Hans-custom/docusaurus-plugin-content-docs/version-1.0.0', ), ); expect(versionedSidebar).toMatchSnapshot(); expect(versionedSidebarPath).toEqual( getVersionSidebarsPath(customI18nSiteDir, DEFAULT_PLUGIN_ID, '1.0.0'), ); expect(versionsPath).toEqual( getVersionsFilePath(customI18nSiteDir, DEFAULT_PLUGIN_ID), ); expect(versions).toEqual(['1.0.0']); expect(consoleMock).toHaveBeenCalledWith( expect.stringMatching( /.*\[SUCCESS\].*\[docs\].*: version .*1\.0\.0.* created!.*/, ), ); copyMock.mockRestore(); writeMock.mockRestore(); consoleMock.mockRestore(); }); it('not the first time versioning', async () => { const copyMock = jest.spyOn(fs, 'copy').mockImplementation(() => {}); const writeMock = jest.spyOn(fs, 'outputFile'); let versionedSidebar!: unknown; let versionedSidebarPath!: string; writeMock.mockImplementationOnce((filepath, content: string) => { versionedSidebarPath = filepath; versionedSidebar = JSON.parse(content); }); let versionsPath!: string; let versions!: unknown; writeMock.mockImplementationOnce((filepath, content: string) => { versionsPath = filepath; versions = JSON.parse(content); }); const consoleMock = jest.spyOn(console, 'log').mockImplementation(() => {}); const warnMock = jest.spyOn(console, 'warn').mockImplementation(() => {}); const options = { ...DEFAULT_OPTIONS, sidebarPath: path.join(versionedSiteDir, 'sidebars.json'), }; await cliDocsVersionCommand('2.0.0', options, { siteDir: versionedSiteDir, i18n: { locales: ['en', 'zh-Hans'], defaultLocale: 'en', path: 'i18n', localeConfigs: {en: {path: 'en'}, 'zh-Hans': {path: 'zh-Hans'}}, }, } as unknown as LoadContext); expect(copyMock).toHaveBeenCalledWith( path.join(versionedSiteDir, options.path), getVersionDocsDirPath(versionedSiteDir, DEFAULT_PLUGIN_ID, '2.0.0'), ); expect(versionedSidebar).toMatchSnapshot(); expect(versionedSidebarPath).toEqual( getVersionSidebarsPath(versionedSiteDir, DEFAULT_PLUGIN_ID, '2.0.0'), ); expect(versionsPath).toEqual( getVersionsFilePath(versionedSiteDir, DEFAULT_PLUGIN_ID), ); expect(versions).toEqual(['2.0.0', '1.0.1', '1.0.0', 'withSlugs']); expect(consoleMock).toHaveBeenCalledWith( expect.stringMatching( /.*\[SUCCESS\].*\[docs\].*: version .*2\.0\.0.* created!.*/, ), ); expect(warnMock.mock.calls[0]![0]).toMatchInlineSnapshot( `"[WARNING] [docs]: no docs found in "<PROJECT_ROOT>/packages/docusaurus-plugin-content-docs/src/__tests__/__fixtures__/versioned-site/i18n/zh-Hans/docusaurus-plugin-content-docs/current". Skipping."`, ); warnMock.mockRestore(); copyMock.mockRestore(); writeMock.mockRestore(); consoleMock.mockRestore(); }); it('second docs instance versioning', async () => { const pluginId = 'community'; const copyMock = jest.spyOn(fs, 'copy').mockImplementation(() => {}); const writeMock = jest.spyOn(fs, 'outputFile'); let versionedSidebar!: unknown; let versionedSidebarPath!: string; writeMock.mockImplementationOnce((filepath, content: string) => { versionedSidebarPath = filepath; versionedSidebar = JSON.parse(content); }); let versionsPath!: string; let versions!: unknown; writeMock.mockImplementationOnce((filepath, content: string) => { versionsPath = filepath; versions = JSON.parse(content); }); const consoleMock = jest.spyOn(console, 'log').mockImplementation(() => {}); const options = { ...DEFAULT_OPTIONS, id: pluginId, path: 'community', sidebarPath: path.join(versionedSiteDir, 'community_sidebars.json'), }; await cliDocsVersionCommand('2.0.0', options, { siteDir: versionedSiteDir, i18n: { locales: ['en', 'fr'], defaultLocale: 'en', path: 'i18n', localeConfigs: {en: {path: 'en'}, fr: {path: 'fr'}}, }, } as unknown as LoadContext); expect(copyMock).toHaveBeenCalledWith( path.join(versionedSiteDir, options.path), getVersionDocsDirPath(versionedSiteDir, pluginId, '2.0.0'), ); expect(copyMock).toHaveBeenCalledWith( path.join( versionedSiteDir, 'i18n/fr/docusaurus-plugin-content-docs-community/current', ), path.join( versionedSiteDir, 'i18n/fr/docusaurus-plugin-content-docs-community/version-2.0.0', ), ); expect(versionedSidebar).toMatchSnapshot(); expect(versionedSidebarPath).toEqual( getVersionSidebarsPath(versionedSiteDir, pluginId, '2.0.0'), ); expect(versionsPath).toEqual( getVersionsFilePath(versionedSiteDir, pluginId), ); expect(versions).toEqual(['2.0.0', '1.0.0']); expect(consoleMock).toHaveBeenCalledWith( expect.stringMatching( /.*\[SUCCESS\].*\[community\].*: version .*2.0.0.* created!.*/, ), ); copyMock.mockRestore(); writeMock.mockRestore(); consoleMock.mockRestore(); }); });
1,140
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/docs.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import {loadContext} from '@docusaurus/core/src/server/index'; import {createSlugger, posixPath, DEFAULT_PLUGIN_ID} from '@docusaurus/utils'; import {createSidebarsUtils} from '../sidebars/utils'; import { processDocMetadata, readVersionDocs, readDocFile, addDocNavigation, isCategoryIndex, type DocEnv, } from '../docs'; import {loadSidebars} from '../sidebars'; import {readVersionsMetadata} from '../versions'; import {DEFAULT_OPTIONS} from '../options'; import type {Sidebars} from '../sidebars/types'; import type {DocFile} from '../types'; import type { MetadataOptions, PluginOptions, EditUrlFunction, DocMetadataBase, VersionMetadata, PropNavigationLink, } from '@docusaurus/plugin-content-docs'; import type {LoadContext} from '@docusaurus/types'; import type {Optional} from 'utility-types'; const fixtureDir = path.join(__dirname, '__fixtures__'); const createFakeDocFile = ({ source, frontMatter = {}, markdown = 'some markdown content', }: { source: string; frontMatter?: {[key: string]: string}; markdown?: string; }): DocFile => { const content = `--- ${Object.entries(frontMatter) .map(([key, value]) => `${key}: ${value}`) .join('\n')} --- ${markdown} `; return { source, content, contentPath: 'docs', filePath: source, }; }; type TestUtilsArg = { siteDir: string; context: LoadContext; versionMetadata: VersionMetadata; options: MetadataOptions; env?: DocEnv; }; function createTestUtils({ siteDir, context, versionMetadata, options, env = 'production', }: TestUtilsArg) { async function readDoc(docFileSource: string) { return readDocFile(versionMetadata, docFileSource); } async function processDocFile(docFileArg: DocFile | string) { const docFile: DocFile = typeof docFileArg === 'string' ? await readDoc(docFileArg) : docFileArg; return processDocMetadata({ docFile, versionMetadata, options, context, env, }); } // Makes it easier to assert failure cases async function getProcessDocFileError( docFileArg: DocFile | string, ): Promise<Error> { try { await processDocFile(docFileArg); return new Error("unexpected: getProcessDocFileError didn't crash"); } catch (e) { return e as Error; } } async function testMeta( docFileSource: string, expectedMetadata: Optional< DocMetadataBase, 'source' | 'lastUpdatedBy' | 'lastUpdatedAt' | 'editUrl' | 'draft' >, ) { const docFile = await readDoc(docFileSource); const metadata = await processDocFile(docFile); expect(metadata).toEqual({ lastUpdatedBy: undefined, lastUpdatedAt: undefined, editUrl: undefined, draft: false, source: path.posix.join( '@site', posixPath(path.relative(siteDir, versionMetadata.contentPath)), posixPath(docFileSource), ), ...expectedMetadata, }); } async function testSlug(docFileSource: string, expectedPermalink: string) { const docFile = await readDoc(docFileSource); const metadata = await processDocMetadata({ docFile, versionMetadata, context, options, env, }); expect(metadata.permalink).toEqual(expectedPermalink); } async function generateNavigation(docFiles: DocFile[]): Promise<{ pagination: { prev?: PropNavigationLink; next?: PropNavigationLink; id: string; }[]; sidebars: Sidebars; }> { const rawDocs = await Promise.all( docFiles.map(async (docFile) => processDocMetadata({ docFile, versionMetadata, context, options, env, }), ), ); const sidebars = await loadSidebars(versionMetadata.sidebarFilePath, { sidebarItemsGenerator: ({defaultSidebarItemsGenerator, ...args}) => defaultSidebarItemsGenerator({...args}), numberPrefixParser: options.numberPrefixParser, docs: rawDocs, drafts: [], version: versionMetadata, sidebarOptions: { sidebarCollapsed: false, sidebarCollapsible: true, }, categoryLabelSlugger: createSlugger(), }); const sidebarsUtils = createSidebarsUtils(sidebars); return { pagination: addDocNavigation({ docs: rawDocs, sidebarsUtils, sidebarFilePath: versionMetadata.sidebarFilePath as string, }).map((doc) => ({prev: doc.previous, next: doc.next, id: doc.id})), sidebars, }; } return { processDocFile, getProcessDocFileError, testMeta, testSlug, generateNavigation, }; } describe('simple site', () => { async function loadSite( loadSiteOptions: {options: Partial<PluginOptions>} = {options: {}}, ) { const siteDir = path.join(fixtureDir, 'simple-site'); const context = await loadContext({siteDir}); const options = { id: DEFAULT_PLUGIN_ID, ...DEFAULT_OPTIONS, ...loadSiteOptions.options, }; const versionsMetadata = await readVersionsMetadata({ context, options, }); expect(versionsMetadata).toHaveLength(1); const currentVersion = versionsMetadata[0]!; function createTestUtilsPartial(args: Partial<TestUtilsArg>) { return createTestUtils({ siteDir, context, options, versionMetadata: currentVersion, ...args, }); } const defaultTestUtils = createTestUtilsPartial({}); return { siteDir, context, options, versionsMetadata, defaultTestUtils, createTestUtilsPartial, currentVersion, }; } it('readVersionDocs', async () => { const {options, currentVersion} = await loadSite(); const docs = await readVersionDocs(currentVersion, options); expect(docs.map((doc) => doc.source).sort()).toEqual( [ 'hello.md', 'ipsum.md', 'lorem.md', 'rootAbsoluteSlug.md', 'rootRelativeSlug.md', 'rootResolvedSlug.md', 'rootTryToEscapeSlug.md', 'headingAsTitle.md', 'doc with space.md', 'doc-draft.md', 'doc-unlisted.md', 'customLastUpdate.md', 'lastUpdateAuthorOnly.md', 'lastUpdateDateOnly.md', 'foo/bar.md', 'foo/baz.md', 'slugs/absoluteSlug.md', 'slugs/relativeSlug.md', 'slugs/resolvedSlug.md', 'slugs/tryToEscapeSlug.md', 'unlisted-category/index.md', 'unlisted-category/unlisted-category-doc.md', ].sort(), ); }); it('normal docs', async () => { const {defaultTestUtils} = await loadSite(); await defaultTestUtils.testMeta(path.join('foo', 'bar.md'), { version: 'current', id: 'foo/bar', sourceDirName: 'foo', permalink: '/docs/foo/bar', slug: '/foo/bar', title: 'Bar', description: 'This is custom description', frontMatter: { description: 'This is custom description', id: 'bar', title: 'Bar', pagination_next: null, pagination_prev: null, }, tags: [], unlisted: false, }); await defaultTestUtils.testMeta(path.join('hello.md'), { version: 'current', id: 'hello', sourceDirName: '.', permalink: '/docs/', slug: '/', title: 'Hello, World !', description: `Hi, Endilie here :)`, frontMatter: { id: 'hello', title: 'Hello, World !', sidebar_label: 'Hello sidebar_label', slug: '/', tags: ['tag-1', 'tag 3'], }, tags: [ { label: 'tag-1', permalink: '/docs/tags/tag-1', }, { label: 'tag 3', permalink: '/docs/tags/tag-3', }, ], unlisted: false, }); }); it('docs with editUrl', async () => { const {siteDir, context, options, currentVersion, createTestUtilsPartial} = await loadSite({ options: { editUrl: 'https://github.com/facebook/docusaurus/edit/main/website', }, }); const testUtilsLocal = createTestUtilsPartial({ siteDir, context, options, versionMetadata: currentVersion, }); await testUtilsLocal.testMeta(path.join('foo', 'baz.md'), { version: 'current', id: 'foo/baz', sourceDirName: 'foo', permalink: '/docs/foo/bazSlug.html', slug: '/foo/bazSlug.html', title: 'baz', editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/docs/foo/baz.md', description: 'Images', frontMatter: { id: 'baz', slug: 'bazSlug.html', title: 'baz', pagination_label: 'baz pagination_label', tags: [ 'tag 1', 'tag-1', {label: 'tag 2', permalink: 'tag2-custom-permalink'}, ], }, tags: [ { label: 'tag 1', permalink: '/docs/tags/tag-1', }, { label: 'tag 2', permalink: '/docs/tags/tag2-custom-permalink', }, ], unlisted: false, }); }); it('docs with custom editUrl & unrelated frontMatter', async () => { const {defaultTestUtils} = await loadSite(); await defaultTestUtils.testMeta('lorem.md', { version: 'current', id: 'lorem', sourceDirName: '.', permalink: '/docs/lorem', slug: '/lorem', title: 'lorem', editUrl: 'https://github.com/customUrl/docs/lorem.md', description: 'Lorem ipsum.', frontMatter: { custom_edit_url: 'https://github.com/customUrl/docs/lorem.md', unrelated_front_matter: "won't be part of metadata", }, tags: [], unlisted: false, }); }); it('docs with function editUrl', async () => { const hardcodedEditUrl = 'hardcoded-edit-url'; const editUrlFunction: EditUrlFunction = jest.fn(() => hardcodedEditUrl); const {siteDir, context, options, currentVersion, createTestUtilsPartial} = await loadSite({ options: { editUrl: editUrlFunction, }, }); const testUtilsLocal = createTestUtilsPartial({ siteDir, context, options, versionMetadata: currentVersion, }); await testUtilsLocal.testMeta(path.join('foo', 'baz.md'), { version: 'current', id: 'foo/baz', sourceDirName: 'foo', permalink: '/docs/foo/bazSlug.html', slug: '/foo/bazSlug.html', title: 'baz', editUrl: hardcodedEditUrl, description: 'Images', frontMatter: { id: 'baz', slug: 'bazSlug.html', title: 'baz', pagination_label: 'baz pagination_label', tags: [ 'tag 1', 'tag-1', {label: 'tag 2', permalink: 'tag2-custom-permalink'}, ], }, tags: [ { label: 'tag 1', permalink: '/docs/tags/tag-1', }, { label: 'tag 2', permalink: '/docs/tags/tag2-custom-permalink', }, ], unlisted: false, }); expect(editUrlFunction).toHaveBeenCalledTimes(1); expect(editUrlFunction).toHaveBeenCalledWith({ version: 'current', versionDocsDirPath: 'docs', docPath: path.posix.join('foo', 'baz.md'), permalink: '/docs/foo/bazSlug.html', locale: 'en', }); }); it('docs with last update time and author', async () => { const {siteDir, context, options, currentVersion, createTestUtilsPartial} = await loadSite({ options: { showLastUpdateAuthor: true, showLastUpdateTime: true, }, }); const testUtilsLocal = createTestUtilsPartial({ siteDir, context, options, versionMetadata: currentVersion, }); await testUtilsLocal.testMeta('lorem.md', { version: 'current', id: 'lorem', sourceDirName: '.', permalink: '/docs/lorem', slug: '/lorem', title: 'lorem', editUrl: 'https://github.com/customUrl/docs/lorem.md', description: 'Lorem ipsum.', frontMatter: { custom_edit_url: 'https://github.com/customUrl/docs/lorem.md', unrelated_front_matter: "won't be part of metadata", }, lastUpdatedAt: 1539502055, formattedLastUpdatedAt: 'Oct 14, 2018', lastUpdatedBy: 'Author', tags: [], unlisted: false, }); }); it('docs with draft frontmatter', async () => { const {createTestUtilsPartial} = await loadSite(); const testUtilsProd = createTestUtilsPartial({ env: 'production', }); await expect( testUtilsProd.processDocFile('doc-draft.md'), ).resolves.toMatchObject({ draft: true, }); const testUtilsDev = createTestUtilsPartial({ env: 'development', }); await expect( testUtilsDev.processDocFile('doc-draft.md'), ).resolves.toMatchObject({ draft: false, }); }); it('docs with unlisted frontmatter', async () => { const {createTestUtilsPartial} = await loadSite(); const baseMeta = { version: 'current', id: 'doc-unlisted', sourceDirName: '.', permalink: '/docs/doc-unlisted', slug: '/doc-unlisted', title: 'doc-unlisted', description: 'This is an unlisted document', frontMatter: { unlisted: true, }, sidebarPosition: undefined, tags: [], }; const testUtilsProd = createTestUtilsPartial({ env: 'production', }); await testUtilsProd.testMeta('doc-unlisted.md', { ...baseMeta, unlisted: true, }); const testUtilsDev = createTestUtilsPartial({ env: 'development', }); await testUtilsDev.testMeta('doc-unlisted.md', { ...baseMeta, unlisted: false, }); }); it('docs with last_update front matter', async () => { const {siteDir, context, options, currentVersion, createTestUtilsPartial} = await loadSite({ options: { showLastUpdateAuthor: true, showLastUpdateTime: true, }, }); const testUtilsLocal = createTestUtilsPartial({ siteDir, context, options, versionMetadata: currentVersion, }); await testUtilsLocal.testMeta('customLastUpdate.md', { version: 'current', id: 'customLastUpdate', sourceDirName: '.', permalink: '/docs/customLastUpdate', slug: '/customLastUpdate', title: 'Custom Last Update', description: 'Custom last update', frontMatter: { last_update: { author: 'Custom Author', date: '1/1/2000', }, title: 'Custom Last Update', }, lastUpdatedAt: new Date('1/1/2000').getTime() / 1000, formattedLastUpdatedAt: 'Jan 1, 2000', lastUpdatedBy: 'Custom Author', sidebarPosition: undefined, tags: [], unlisted: false, }); }); it('docs with only last_update author front matter', async () => { const {siteDir, context, options, currentVersion, createTestUtilsPartial} = await loadSite({ options: { showLastUpdateAuthor: true, showLastUpdateTime: true, }, }); const testUtilsLocal = createTestUtilsPartial({ siteDir, context, options, versionMetadata: currentVersion, }); await testUtilsLocal.testMeta('lastUpdateAuthorOnly.md', { version: 'current', id: 'lastUpdateAuthorOnly', sourceDirName: '.', permalink: '/docs/lastUpdateAuthorOnly', slug: '/lastUpdateAuthorOnly', title: 'Last Update Author Only', description: 'Only custom author, so it will still use the date from Git', frontMatter: { last_update: { author: 'Custom Author', }, title: 'Last Update Author Only', }, lastUpdatedAt: 1539502055, formattedLastUpdatedAt: 'Oct 14, 2018', lastUpdatedBy: 'Custom Author', sidebarPosition: undefined, tags: [], unlisted: false, }); }); it('docs with only last_update date front matter', async () => { const {siteDir, context, options, currentVersion, createTestUtilsPartial} = await loadSite({ options: { showLastUpdateAuthor: true, showLastUpdateTime: true, }, }); const testUtilsLocal = createTestUtilsPartial({ siteDir, context, options, versionMetadata: currentVersion, }); await testUtilsLocal.testMeta('lastUpdateDateOnly.md', { version: 'current', id: 'lastUpdateDateOnly', sourceDirName: '.', permalink: '/docs/lastUpdateDateOnly', slug: '/lastUpdateDateOnly', title: 'Last Update Date Only', description: 'Only custom date, so it will still use the author from Git', frontMatter: { last_update: { date: '1/1/2000', }, title: 'Last Update Date Only', }, lastUpdatedAt: new Date('1/1/2000').getTime() / 1000, formattedLastUpdatedAt: 'Jan 1, 2000', lastUpdatedBy: 'Author', sidebarPosition: undefined, tags: [], unlisted: false, }); }); it('docs with last_update front matter disabled', async () => { const {siteDir, context, options, currentVersion, createTestUtilsPartial} = await loadSite({ options: { showLastUpdateAuthor: false, showLastUpdateTime: false, }, }); const testUtilsLocal = createTestUtilsPartial({ siteDir, context, options, versionMetadata: currentVersion, }); await testUtilsLocal.testMeta('customLastUpdate.md', { version: 'current', id: 'customLastUpdate', sourceDirName: '.', permalink: '/docs/customLastUpdate', slug: '/customLastUpdate', title: 'Custom Last Update', description: 'Custom last update', frontMatter: { last_update: { author: 'Custom Author', date: '1/1/2000', }, title: 'Custom Last Update', }, lastUpdatedAt: undefined, formattedLastUpdatedAt: undefined, lastUpdatedBy: undefined, sidebarPosition: undefined, tags: [], unlisted: false, }); }); it('docs with slugs', async () => { const {defaultTestUtils} = await loadSite(); await defaultTestUtils.testSlug( path.join('rootRelativeSlug.md'), '/docs/rootRelativeSlug', ); await defaultTestUtils.testSlug( path.join('rootAbsoluteSlug.md'), '/docs/rootAbsoluteSlug', ); await defaultTestUtils.testSlug( path.join('rootResolvedSlug.md'), '/docs/hey/rootResolvedSlug', ); await defaultTestUtils.testSlug( path.join('rootTryToEscapeSlug.md'), '/docs/rootTryToEscapeSlug', ); await defaultTestUtils.testSlug( path.join('slugs', 'absoluteSlug.md'), '/docs/absoluteSlug', ); await defaultTestUtils.testSlug( path.join('slugs', 'relativeSlug.md'), '/docs/slugs/relativeSlug', ); await defaultTestUtils.testSlug( path.join('slugs', 'resolvedSlug.md'), '/docs/slugs/hey/resolvedSlug', ); await defaultTestUtils.testSlug( path.join('slugs', 'tryToEscapeSlug.md'), '/docs/tryToEscapeSlug', ); }); it('docs with invalid id', async () => { const {defaultTestUtils} = await loadSite(); const error = await defaultTestUtils.getProcessDocFileError( createFakeDocFile({ source: 'some/fake/path', frontMatter: { id: 'Hello/world', }, }), ); expect(error.message).toMatchInlineSnapshot( `"Can't process doc metadata for doc at path path=some/fake/path in version name=current"`, ); expect(error.cause).toBeDefined(); expect(error.cause!.message).toMatchInlineSnapshot( `"Document id "Hello/world" cannot include slash."`, ); }); it('custom pagination - production', async () => { const {createTestUtilsPartial, options, versionsMetadata} = await loadSite(); const testUtils = createTestUtilsPartial({env: 'production'}); const docs = await readVersionDocs(versionsMetadata[0]!, options); await expect(testUtils.generateNavigation(docs)).resolves.toMatchSnapshot(); }); it('custom pagination - development', async () => { const {createTestUtilsPartial, options, versionsMetadata} = await loadSite(); const testUtils = createTestUtilsPartial({env: 'development'}); const docs = await readVersionDocs(versionsMetadata[0]!, options); await expect(testUtils.generateNavigation(docs)).resolves.toMatchSnapshot(); }); it('bad pagination', async () => { const {defaultTestUtils, options, versionsMetadata} = await loadSite(); const docs = await readVersionDocs(versionsMetadata[0]!, options); docs.push( createFakeDocFile({ source: 'bad', frontMatter: {pagination_prev: 'nonexistent'}, }), ); await expect( defaultTestUtils.generateNavigation(docs), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Error when loading bad in .: the pagination_prev front matter points to a non-existent ID nonexistent."`, ); }); }); describe('versioned site', () => { async function loadSite( loadSiteOptions: {options: Partial<PluginOptions>; locale?: string} = { options: {}, }, ) { const siteDir = path.join(fixtureDir, 'versioned-site'); const context = await loadContext({ siteDir, locale: loadSiteOptions.locale, }); const options = { id: DEFAULT_PLUGIN_ID, ...DEFAULT_OPTIONS, ...loadSiteOptions.options, }; const versionsMetadata = await readVersionsMetadata({ context, options, }); expect(versionsMetadata).toHaveLength(4); const currentVersion = versionsMetadata[0]!; const version101 = versionsMetadata[1]!; const version100 = versionsMetadata[2]!; const versionWithSlugs = versionsMetadata[3]!; const currentVersionTestUtils = createTestUtils({ siteDir, context, options, versionMetadata: currentVersion, }); const version101TestUtils = createTestUtils({ siteDir, context, options, versionMetadata: version101, }); const version100TestUtils = createTestUtils({ siteDir, context, options, versionMetadata: version100, }); const versionWithSlugsTestUtils = createTestUtils({ siteDir, context, options, versionMetadata: versionWithSlugs, }); return { siteDir, context, options, versionsMetadata, currentVersionTestUtils, version101TestUtils, version100, version100TestUtils, versionWithSlugsTestUtils, }; } it('next docs', async () => { const {currentVersionTestUtils} = await loadSite(); await currentVersionTestUtils.testMeta(path.join('foo', 'bar.md'), { id: 'foo/bar', version: 'current', sourceDirName: 'foo', permalink: '/docs/next/foo/barSlug', slug: '/foo/barSlug', title: 'bar', description: 'This is next version of bar.', frontMatter: { slug: 'barSlug', tags: [ 'barTag 1', 'barTag-2', { label: 'barTag 3', permalink: 'barTag-3-permalink', }, ], }, tags: [ { label: 'barTag 1', permalink: '/docs/next/tags/bar-tag-1', }, { label: 'barTag-2', permalink: '/docs/next/tags/bar-tag-2', }, { label: 'barTag 3', permalink: '/docs/next/tags/barTag-3-permalink', }, ], unlisted: false, }); await currentVersionTestUtils.testMeta(path.join('hello.md'), { id: 'hello', version: 'current', sourceDirName: '.', permalink: '/docs/next/', slug: '/', title: 'hello', description: 'Hello next !', frontMatter: { slug: '/', }, tags: [], unlisted: false, }); }); it('versioned docs', async () => { const {version101TestUtils, version100TestUtils} = await loadSite(); await version100TestUtils.testMeta(path.join('foo', 'bar.md'), { id: 'foo/bar', sourceDirName: 'foo', permalink: '/docs/1.0.0/foo/barSlug', slug: '/foo/barSlug', title: 'bar', description: 'Bar 1.0.0 !', frontMatter: {slug: 'barSlug'}, version: '1.0.0', tags: [], unlisted: false, }); await version100TestUtils.testMeta(path.join('hello.md'), { id: 'hello', sourceDirName: '.', permalink: '/docs/1.0.0/', slug: '/', title: 'hello', description: 'Hello 1.0.0 ! (translated en)', frontMatter: { slug: '/', }, version: '1.0.0', source: '@site/i18n/en/docusaurus-plugin-content-docs/version-1.0.0/hello.md', tags: [], unlisted: false, }); await version101TestUtils.testMeta(path.join('foo', 'bar.md'), { id: 'foo/bar', sourceDirName: 'foo', permalink: '/docs/foo/bar', slug: '/foo/bar', title: 'bar', description: 'Bar 1.0.1 !', version: '1.0.1', frontMatter: {}, tags: [], unlisted: false, }); await version101TestUtils.testMeta(path.join('hello.md'), { id: 'hello', sourceDirName: '.', permalink: '/docs/', slug: '/', title: 'hello', description: 'Hello 1.0.1 !', version: '1.0.1', frontMatter: { slug: '/', }, tags: [], unlisted: false, }); }); it('next doc slugs', async () => { const {currentVersionTestUtils} = await loadSite(); await currentVersionTestUtils.testSlug( path.join('slugs', 'absoluteSlug.md'), '/docs/next/absoluteSlug', ); await currentVersionTestUtils.testSlug( path.join('slugs', 'relativeSlug.md'), '/docs/next/slugs/relativeSlug', ); await currentVersionTestUtils.testSlug( path.join('slugs', 'resolvedSlug.md'), '/docs/next/slugs/hey/resolvedSlug', ); await currentVersionTestUtils.testSlug( path.join('slugs', 'tryToEscapeSlug.md'), '/docs/next/tryToEscapeSlug', ); }); it('versioned doc slugs', async () => { const {versionWithSlugsTestUtils} = await loadSite(); await versionWithSlugsTestUtils.testSlug( path.join('rootAbsoluteSlug.md'), '/docs/withSlugs/rootAbsoluteSlug', ); await versionWithSlugsTestUtils.testSlug( path.join('rootRelativeSlug.md'), '/docs/withSlugs/rootRelativeSlug', ); await versionWithSlugsTestUtils.testSlug( path.join('rootResolvedSlug.md'), '/docs/withSlugs/hey/rootResolvedSlug', ); await versionWithSlugsTestUtils.testSlug( path.join('rootTryToEscapeSlug.md'), '/docs/withSlugs/rootTryToEscapeSlug', ); await versionWithSlugsTestUtils.testSlug( path.join('slugs', 'absoluteSlug.md'), '/docs/withSlugs/absoluteSlug', ); await versionWithSlugsTestUtils.testSlug( path.join('slugs', 'relativeSlug.md'), '/docs/withSlugs/slugs/relativeSlug', ); await versionWithSlugsTestUtils.testSlug( path.join('slugs', 'resolvedSlug.md'), '/docs/withSlugs/slugs/hey/resolvedSlug', ); await versionWithSlugsTestUtils.testSlug( path.join('slugs', 'tryToEscapeSlug.md'), '/docs/withSlugs/tryToEscapeSlug', ); }); it('doc with editUrl function', async () => { const hardcodedEditUrl = 'hardcoded-edit-url'; const editUrlFunction: EditUrlFunction = jest.fn(() => hardcodedEditUrl); const {siteDir, context, options, version100} = await loadSite({ options: { editUrl: editUrlFunction, }, }); const testUtilsLocal = createTestUtils({ siteDir, context, options, versionMetadata: version100, }); await testUtilsLocal.testMeta(path.join('hello.md'), { id: 'hello', sourceDirName: '.', permalink: '/docs/1.0.0/', slug: '/', title: 'hello', description: 'Hello 1.0.0 ! (translated en)', frontMatter: { slug: '/', }, version: '1.0.0', source: '@site/i18n/en/docusaurus-plugin-content-docs/version-1.0.0/hello.md', editUrl: hardcodedEditUrl, tags: [], unlisted: false, }); expect(editUrlFunction).toHaveBeenCalledTimes(1); expect(editUrlFunction).toHaveBeenCalledWith({ version: '1.0.0', versionDocsDirPath: 'versioned_docs/version-1.0.0', docPath: path.join('hello.md'), permalink: '/docs/1.0.0/', locale: 'en', }); }); it('translated doc with editUrl', async () => { const {siteDir, context, options, version100} = await loadSite({ options: { editUrl: 'https://github.com/facebook/docusaurus/edit/main/website', }, }); const testUtilsLocal = createTestUtils({ siteDir, context, options, versionMetadata: version100, }); await testUtilsLocal.testMeta(path.join('hello.md'), { id: 'hello', sourceDirName: '.', permalink: '/docs/1.0.0/', slug: '/', title: 'hello', description: 'Hello 1.0.0 ! (translated en)', frontMatter: { slug: '/', }, version: '1.0.0', source: '@site/i18n/en/docusaurus-plugin-content-docs/version-1.0.0/hello.md', editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/versioned_docs/version-1.0.0/hello.md', tags: [], unlisted: false, }); }); it('translated en doc with editUrl and editCurrentVersion=true', async () => { const {siteDir, context, options, version100} = await loadSite({ options: { editUrl: 'https://github.com/facebook/docusaurus/edit/main/website', editCurrentVersion: true, }, }); const testUtilsLocal = createTestUtils({ siteDir, context, options, versionMetadata: version100, }); await testUtilsLocal.testMeta(path.join('hello.md'), { id: 'hello', sourceDirName: '.', permalink: '/docs/1.0.0/', slug: '/', title: 'hello', description: 'Hello 1.0.0 ! (translated en)', frontMatter: { slug: '/', }, version: '1.0.0', source: '@site/i18n/en/docusaurus-plugin-content-docs/version-1.0.0/hello.md', editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/docs/hello.md', tags: [], unlisted: false, }); }); it('translated fr doc with editUrl and editLocalizedFiles=true', async () => { const {siteDir, context, options, version100} = await loadSite({ options: { editUrl: 'https://github.com/facebook/docusaurus/edit/main/website', editLocalizedFiles: true, }, locale: 'fr', }); const testUtilsLocal = createTestUtils({ siteDir, context, options, versionMetadata: version100, }); await testUtilsLocal.testMeta(path.join('hello.md'), { id: 'hello', sourceDirName: '.', permalink: '/fr/docs/1.0.0/', slug: '/', title: 'hello', description: 'Hello 1.0.0 ! (translated fr)', frontMatter: { slug: '/', }, version: '1.0.0', source: '@site/i18n/fr/docusaurus-plugin-content-docs/version-1.0.0/hello.md', editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/i18n/fr/docusaurus-plugin-content-docs/version-1.0.0/hello.md', tags: [], unlisted: false, }); }); it('translated fr doc with editUrl and editLocalizedFiles=true + editCurrentVersion=true', async () => { const {siteDir, context, options, version100} = await loadSite({ options: { editUrl: 'https://github.com/facebook/docusaurus/edit/main/website', editCurrentVersion: true, editLocalizedFiles: true, }, locale: 'fr', }); const testUtilsLocal = createTestUtils({ siteDir, context, options, versionMetadata: version100, }); await testUtilsLocal.testMeta(path.join('hello.md'), { id: 'hello', sourceDirName: '.', permalink: '/fr/docs/1.0.0/', slug: '/', title: 'hello', description: 'Hello 1.0.0 ! (translated fr)', frontMatter: { slug: '/', }, version: '1.0.0', source: '@site/i18n/fr/docusaurus-plugin-content-docs/version-1.0.0/hello.md', editUrl: 'https://github.com/facebook/docusaurus/edit/main/website/i18n/fr/docusaurus-plugin-content-docs/current/hello.md', tags: [], unlisted: false, }); }); }); describe('isConventionalDocIndex', () => { it('supports readme', () => { expect( isCategoryIndex({ fileName: 'readme', directories: ['doesNotMatter'], extension: '.md', }), ).toBe(true); expect( isCategoryIndex({ fileName: 'readme', directories: ['doesNotMatter'], extension: '.mdx', }), ).toBe(true); expect( isCategoryIndex({ fileName: 'README', directories: ['doesNotMatter'], extension: '.md', }), ).toBe(true); expect( isCategoryIndex({ fileName: 'ReAdMe', directories: ['doesNotMatter'], extension: '', }), ).toBe(true); }); it('supports index', () => { expect( isCategoryIndex({ fileName: 'index', directories: ['doesNotMatter'], extension: '.md', }), ).toBe(true); expect( isCategoryIndex({ fileName: 'index', directories: ['doesNotMatter'], extension: '.mdx', }), ).toBe(true); expect( isCategoryIndex({ fileName: 'INDEX', directories: ['doesNotMatter'], extension: '.md', }), ).toBe(true); expect( isCategoryIndex({ fileName: 'InDeX', directories: ['doesNotMatter'], extension: '', }), ).toBe(true); }); it('supports <categoryName>/<categoryName>.md', () => { expect( isCategoryIndex({ fileName: 'someCategory', directories: ['someCategory', 'doesNotMatter'], extension: '', }), ).toBe(true); expect( isCategoryIndex({ fileName: 'someCategory', directories: ['someCategory'], extension: '.md', }), ).toBe(true); expect( isCategoryIndex({ fileName: 'someCategory', directories: ['someCategory'], extension: '.mdx', }), ).toBe(true); expect( isCategoryIndex({ fileName: 'SOME_CATEGORY', directories: ['some_category'], extension: '.md', }), ).toBe(true); expect( isCategoryIndex({ fileName: 'some_category', directories: ['some_category'], extension: '', }), ).toBe(true); }); it('reject other cases', () => { expect( isCategoryIndex({ fileName: 'some_Category', directories: ['someCategory'], extension: '', }), ).toBe(false); expect( isCategoryIndex({ fileName: 'read_me', directories: ['doesNotMatter'], extension: '', }), ).toBe(false); expect( isCategoryIndex({ fileName: 'the index', directories: ['doesNotMatter'], extension: '', }), ).toBe(false); }); });
1,141
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/frontMatter.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {escapeRegexp} from '@docusaurus/utils'; import {validateDocFrontMatter} from '../frontMatter'; import type {DocFrontMatter} from '@docusaurus/plugin-content-docs'; function testField(params: { prefix: string; validFrontMatters: DocFrontMatter[]; convertibleFrontMatter?: [ ConvertibleFrontMatter: {[key: string]: unknown}, ConvertedFrontMatter: DocFrontMatter, ][]; invalidFrontMatters?: [ InvalidFrontMatter: {[key: string]: unknown}, ErrorMessage: string, ][]; }) { // eslint-disable-next-line jest/require-top-level-describe test(`[${params.prefix}] accept valid values`, () => { params.validFrontMatters.forEach((frontMatter) => { expect(validateDocFrontMatter(frontMatter)).toEqual(frontMatter); }); }); // eslint-disable-next-line jest/require-top-level-describe test(`[${params.prefix}] convert valid values`, () => { params.convertibleFrontMatter?.forEach( ([convertibleFrontMatter, convertedFrontMatter]) => { expect(validateDocFrontMatter(convertibleFrontMatter)).toEqual( convertedFrontMatter, ); }, ); }); // eslint-disable-next-line jest/require-top-level-describe test(`[${params.prefix}] throw error for values`, () => { params.invalidFrontMatters?.forEach(([frontMatter, message]) => { try { validateDocFrontMatter(frontMatter); throw new Error( `Doc front matter is expected to be rejected, but was accepted successfully:\n ${JSON.stringify( frontMatter, null, 2, )}`, ); } catch (err) { // eslint-disable-next-line jest/no-conditional-expect expect((err as Error).message).toMatch( new RegExp(escapeRegexp(message)), ); } }); }); } describe('doc front matter schema', () => { it('accepts empty object', () => { const frontMatter: DocFrontMatter = {}; expect(validateDocFrontMatter(frontMatter)).toEqual(frontMatter); }); it('accepts unknown field', () => { const frontMatter = {abc: '1'}; expect(validateDocFrontMatter(frontMatter)).toEqual(frontMatter); }); }); describe('validateDocFrontMatter id', () => { testField({ prefix: 'id', validFrontMatters: [{id: '123'}, {id: 'unique_id'}], invalidFrontMatters: [[{id: ''}, 'is not allowed to be empty']], }); }); describe('validateDocFrontMatter title', () => { testField({ prefix: 'title', validFrontMatters: [ // See https://github.com/facebook/docusaurus/issues/4591#issuecomment-822372398 {title: ''}, {title: 'title'}, ], }); }); describe('validateDocFrontMatter hide_title', () => { testField({ prefix: 'hide_title', validFrontMatters: [{hide_title: true}, {hide_title: false}], convertibleFrontMatter: [ [{hide_title: 'true'}, {hide_title: true}], [{hide_title: 'false'}, {hide_title: false}], ], invalidFrontMatters: [ [{hide_title: 'yes'}, 'must be a boolean'], [{hide_title: 'no'}, 'must be a boolean'], [{hide_title: ''}, 'must be a boolean'], ], }); }); describe('validateDocFrontMatter hide_table_of_contents', () => { testField({ prefix: 'hide_table_of_contents', validFrontMatters: [ {hide_table_of_contents: true}, {hide_table_of_contents: false}, ], convertibleFrontMatter: [ [{hide_table_of_contents: 'true'}, {hide_table_of_contents: true}], [{hide_table_of_contents: 'false'}, {hide_table_of_contents: false}], ], invalidFrontMatters: [ [{hide_table_of_contents: 'yes'}, 'must be a boolean'], [{hide_table_of_contents: 'no'}, 'must be a boolean'], [{hide_table_of_contents: ''}, 'must be a boolean'], ], }); }); describe('validateDocFrontMatter keywords', () => { testField({ prefix: 'keywords', validFrontMatters: [ {keywords: ['hello']}, {keywords: ['hello', 'world']}, {keywords: ['hello', 'world']}, {keywords: ['hello']}, ], invalidFrontMatters: [ [{keywords: ''}, 'must be an array'], [{keywords: ['']}, 'is not allowed to be empty'], [{keywords: []}, 'does not contain 1 required value(s)'], ], }); }); describe('validateDocFrontMatter image', () => { testField({ prefix: 'image', validFrontMatters: [ {image: 'https://docusaurus.io/blog/image.png'}, {image: '/absolute/image.png'}, {image: '../relative/image.png'}, ], invalidFrontMatters: [ [{image: ''}, '"image" does not look like a valid url (value=\'\')'], ], }); }); describe('validateDocFrontMatter description', () => { testField({ prefix: 'description', validFrontMatters: [ // See https://github.com/facebook/docusaurus/issues/4591#issuecomment-822372398 {description: ''}, {description: 'description'}, ], }); }); describe('validateDocFrontMatter slug', () => { testField({ prefix: 'slug', validFrontMatters: [ {slug: '/'}, {slug: 'slug'}, {slug: '/slug/'}, {slug: './slug'}, {slug: '../../slug'}, {slug: '/api/plugins/@docusaurus'}, {slug: '@site/api/asset'}, {slug: 'slug1 slug2'}, ], invalidFrontMatters: [[{slug: ''}, 'is not allowed to be empty']], }); }); describe('validateDocFrontMatter sidebar_label', () => { testField({ prefix: 'sidebar_label', validFrontMatters: [{sidebar_label: 'Awesome docs'}], invalidFrontMatters: [[{sidebar_label: ''}, 'is not allowed to be empty']], }); }); describe('validateDocFrontMatter sidebar_position', () => { testField({ prefix: 'sidebar_position', validFrontMatters: [ {sidebar_position: -5}, {sidebar_position: -3.5}, {sidebar_position: 0}, {sidebar_position: 5}, {sidebar_position: 3.5}, ], convertibleFrontMatter: [ [{sidebar_position: '-1.5'}, {sidebar_position: -1.5}], [{sidebar_position: '1'}, {sidebar_position: 1}], [{sidebar_position: '1.5'}, {sidebar_position: 1.5}], ], }); }); describe('validateDocFrontMatter sidebar_custom_props', () => { testField({ prefix: 'sidebar_custom_props', validFrontMatters: [ {sidebar_custom_props: {}}, {sidebar_custom_props: {prop: 'custom', number: 1, boolean: true}}, ], invalidFrontMatters: [ [{sidebar_custom_props: ''}, 'must be of type object'], ], }); }); describe('validateDocFrontMatter custom_edit_url', () => { testField({ prefix: 'custom_edit_url', validFrontMatters: [ // See https://github.com/demisto/content-docs/pull/616#issuecomment-827087566 {custom_edit_url: ''}, {custom_edit_url: null}, {custom_edit_url: 'https://github.com/facebook/docusaurus/markdown.md'}, {custom_edit_url: '../../api/docs/markdown.md'}, {custom_edit_url: '@site/api/docs/markdown.md'}, ], }); }); describe('validateDocFrontMatter parse_number_prefixes', () => { testField({ prefix: 'parse_number_prefixes', validFrontMatters: [ {parse_number_prefixes: true}, {parse_number_prefixes: false}, ], convertibleFrontMatter: [ [{parse_number_prefixes: 'true'}, {parse_number_prefixes: true}], [{parse_number_prefixes: 'false'}, {parse_number_prefixes: false}], ], invalidFrontMatters: [ [{parse_number_prefixes: 'yes'}, 'must be a boolean'], [{parse_number_prefixes: 'no'}, 'must be a boolean'], [{parse_number_prefixes: ''}, 'must be a boolean'], ], }); }); describe('validateDocFrontMatter tags', () => { testField({ prefix: 'tags', validFrontMatters: [{}, {tags: undefined}, {tags: ['tag1', 'tag2']}], convertibleFrontMatter: [[{tags: ['tag1', 42]}, {tags: ['tag1', '42']}]], invalidFrontMatters: [ [ {tags: 42}, '"tags" does not look like a valid front matter Yaml array.', ], [ {tags: 'tag1, tag2'}, '"tags" does not look like a valid front matter Yaml array.', ], [{tags: [{}]}, '"tags[0]" does not look like a valid tag'], [{tags: [true]}, '"tags[0]" does not look like a valid tag'], [ {tags: ['tag1', {hey: 'test'}]}, '"tags[1]" does not look like a valid tag', ], ], }); }); describe('toc_min_heading_level', () => { testField({ prefix: 'toc_min_heading_level', validFrontMatters: [ {}, {toc_min_heading_level: undefined}, {toc_min_heading_level: 2}, {toc_min_heading_level: 3}, {toc_min_heading_level: 4}, {toc_min_heading_level: 5}, {toc_min_heading_level: 6}, ], convertibleFrontMatter: [ [{toc_min_heading_level: '2'}, {toc_min_heading_level: 2}], ], invalidFrontMatters: [ [ {toc_min_heading_level: 1}, '"toc_min_heading_level" must be greater than or equal to 2', ], [ {toc_min_heading_level: 7}, '"toc_min_heading_level" must be less than or equal to 6', ], [ {toc_min_heading_level: 'hello'}, '"toc_min_heading_level" must be a number', ], [ {toc_min_heading_level: true}, '"toc_min_heading_level" must be a number', ], ], }); }); describe('toc_max_heading_level', () => { testField({ prefix: 'toc_max_heading_level', validFrontMatters: [ {}, {toc_max_heading_level: undefined}, {toc_max_heading_level: 2}, {toc_max_heading_level: 3}, {toc_max_heading_level: 4}, {toc_max_heading_level: 5}, {toc_max_heading_level: 6}, ], convertibleFrontMatter: [ [{toc_max_heading_level: '2'}, {toc_max_heading_level: 2}], ], invalidFrontMatters: [ [ {toc_max_heading_level: 1}, '"toc_max_heading_level" must be greater than or equal to 2', ], [ {toc_max_heading_level: 7}, '"toc_max_heading_level" must be less than or equal to 6', ], [ {toc_max_heading_level: 'hello'}, '"toc_max_heading_level" must be a number', ], [ {toc_max_heading_level: true}, '"toc_max_heading_level" must be a number', ], ], }); }); describe('toc min/max consistency', () => { testField({ prefix: 'toc min/max', validFrontMatters: [ {}, {toc_min_heading_level: undefined, toc_max_heading_level: undefined}, {toc_min_heading_level: 2, toc_max_heading_level: 2}, {toc_min_heading_level: 2, toc_max_heading_level: 6}, {toc_min_heading_level: 2, toc_max_heading_level: 3}, {toc_min_heading_level: 3, toc_max_heading_level: 3}, ], invalidFrontMatters: [ [ {toc_min_heading_level: 4, toc_max_heading_level: 3}, '"toc_min_heading_level" must be less than or equal to ref:toc_max_heading_level', ], [ {toc_min_heading_level: 6, toc_max_heading_level: 2}, '"toc_min_heading_level" must be less than or equal to ref:toc_max_heading_level', ], ], }); }); describe('validateDocFrontMatter draft', () => { testField({ prefix: 'draft', validFrontMatters: [{draft: true}, {draft: false}], convertibleFrontMatter: [ [{draft: 'true'}, {draft: true}], [{draft: 'false'}, {draft: false}], ], invalidFrontMatters: [ [{draft: 'yes'}, 'must be a boolean'], [{draft: 'no'}, 'must be a boolean'], [{draft: ''}, 'must be a boolean'], ], }); }); describe('validateDocFrontMatter unlisted', () => { testField({ prefix: 'unlisted', validFrontMatters: [{unlisted: true}, {unlisted: false}], convertibleFrontMatter: [ [{unlisted: 'true'}, {unlisted: true}], [{unlisted: 'false'}, {unlisted: false}], ], invalidFrontMatters: [ [{unlisted: 'yes'}, 'must be a boolean'], [{unlisted: 'no'}, 'must be a boolean'], [{unlisted: ''}, 'must be a boolean'], ], }); }); describe('validateDocFrontMatter draft XOR unlisted', () => { testField({ prefix: 'draft XOR unlisted', validFrontMatters: [ {draft: false}, {unlisted: false}, {draft: false, unlisted: false}, {draft: true, unlisted: false}, {draft: false, unlisted: true}, ], invalidFrontMatters: [ [ {draft: true, unlisted: true}, "Can't be draft and unlisted at the same time.", ], ], }); }); describe('validateDocFrontMatter last_update', () => { testField({ prefix: 'last_update', validFrontMatters: [ {last_update: undefined}, {last_update: {author: 'test author', date: undefined}}, {last_update: {author: undefined, date: '1/1/2000'}}, {last_update: {author: undefined, date: new Date('1/1/2000')}}, {last_update: {author: 'test author', date: '1/1/2000'}}, {last_update: {author: 'test author', date: '1995-12-17T03:24:00'}}, {last_update: {author: undefined, date: 'December 17, 1995 03:24:00'}}, ], invalidFrontMatters: [ [ {last_update: null}, 'does not look like a valid front matter FileChange object. Please use a FileChange object (with an author and/or date).', ], [ {last_update: {}}, 'does not look like a valid front matter FileChange object. Please use a FileChange object (with an author and/or date).', ], [ {last_update: ''}, 'does not look like a valid front matter FileChange object. Please use a FileChange object (with an author and/or date).', ], [ {last_update: {invalid: 'key'}}, 'does not look like a valid front matter FileChange object. Please use a FileChange object (with an author and/or date).', ], [ {last_update: {author: 'test author', date: 'I am not a date :('}}, 'must be a valid date', ], [ {last_update: {author: 'test author', date: '2011-10-45'}}, 'must be a valid date', ], [ {last_update: {author: 'test author', date: '2011-0-10'}}, 'must be a valid date', ], [ {last_update: {author: 'test author', date: ''}}, 'must be a valid date', ], ], }); });
1,142
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/globalData.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {toGlobalDataVersion} from '../globalData'; import {createSidebarsUtils} from '../sidebars/utils'; import {getCategoryGeneratedIndexMetadataList} from '../categoryGeneratedIndex'; import type {Sidebars} from '../sidebars/types'; import type {DocMetadata} from '@docusaurus/plugin-content-docs'; describe('toGlobalDataVersion', () => { it('generates the right docs, sidebars, and metadata', () => { const docs = [ { id: 'main', permalink: '/current/main', sidebar: 'tutorial', frontMatter: {}, unlisted: false, }, { id: 'doc', permalink: '/current/doc', sidebar: 'tutorial', frontMatter: {}, unlisted: undefined, }, { id: 'docNoSidebarUnlisted', permalink: '/current/docNoSidebarUnlisted', sidebar: undefined, frontMatter: {}, unlisted: true, }, ] as DocMetadata[]; const sidebars: Sidebars = { tutorial: [ { type: 'doc', id: 'main', }, { type: 'category', label: 'Generated', link: { type: 'generated-index', permalink: '/current/generated', slug: '/current/generated', }, items: [ { type: 'doc', id: 'doc', }, ], collapsed: false, collapsible: true, }, ], links: [ { type: 'link', href: 'foo', label: 'Foo', }, { type: 'link', href: 'bar', label: 'Bar', }, ], another: [ { type: 'category', label: 'Generated', link: { type: 'generated-index', permalink: '/current/generated-2', slug: '/current/generated-2', }, items: [ { type: 'doc', id: 'doc', }, ], collapsed: false, collapsible: true, }, ], }; const sidebarsUtils = createSidebarsUtils(sidebars); expect( toGlobalDataVersion({ versionName: 'current', label: 'Label', isLast: true, path: '/current', docs, drafts: [ { id: 'some-draft-id', permalink: '/current/draft', sidebar: undefined, }, ] as DocMetadata[], sidebars, categoryGeneratedIndices: getCategoryGeneratedIndexMetadataList({ docs, sidebarsUtils, }), sidebarsUtils, banner: 'unreleased', badge: true, className: 'current-cls', tagsPath: '/current/tags', contentPath: '', contentPathLocalized: '', sidebarFilePath: '', routePriority: 0.5, }), ).toMatchSnapshot(); }); });
1,143
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import fs from 'fs-extra'; import _ from 'lodash'; import {isMatch} from 'picomatch'; import commander from 'commander'; import webpack from 'webpack'; import {loadContext} from '@docusaurus/core/src/server/index'; import {applyConfigureWebpack} from '@docusaurus/core/src/webpack/utils'; import {sortConfig} from '@docusaurus/core/src/server/plugins/routeConfig'; import {posixPath} from '@docusaurus/utils'; import {normalizePluginOptions} from '@docusaurus/utils-validation'; import pluginContentDocs from '../index'; import {toSidebarsProp} from '../props'; import {DefaultSidebarItemsGenerator} from '../sidebars/generator'; import {DisabledSidebars} from '../sidebars'; import * as cliDocs from '../cli'; import {validateOptions} from '../options'; import type {RouteConfig, Validate, Plugin} from '@docusaurus/types'; import type { LoadedVersion, Options, PluginOptions, PropSidebarItemLink, PropSidebars, } from '@docusaurus/plugin-content-docs'; import type { SidebarItemsGeneratorOption, NormalizedSidebar, } from '../sidebars/types'; function findDocById(version: LoadedVersion | undefined, id: string) { if (!version) { throw new Error('Version not found'); } return version.docs.find((item) => item.id === id); } function getDocById(version: LoadedVersion | undefined, id: string) { if (!version) { throw new Error('Version not found'); } const doc = findDocById(version, id); if (!doc) { throw new Error( `No doc found with id "${id}" in version ${version.versionName}. Available ids are:\n- ${version.docs.map((d) => d.id).join('\n- ')}`, ); } return doc; } const createFakeActions = (contentDir: string) => { const routeConfigs: RouteConfig[] = []; const dataContainer: {[key: string]: unknown} = {}; const globalDataContainer: {pluginName?: {pluginId: unknown}} = {}; const actions = { addRoute: (config: RouteConfig) => { routeConfigs.push(config); }, createData: (name: string, content: unknown) => { dataContainer[name] = content; return Promise.resolve(path.join(contentDir, name)); }, setGlobalData: (data: unknown) => { globalDataContainer.pluginName = {pluginId: data}; }, }; // Query by prefix, because files have a hash at the end so it's not // convenient to query by full filename function getCreatedDataByPrefix(prefix: string) { const entry = Object.entries(dataContainer).find(([key]) => key.startsWith(prefix), ); if (!entry) { throw new Error(`No created entry found for prefix "${prefix}". Entries created: - ${Object.keys(dataContainer).join('\n- ')} `); } return JSON.parse(entry[1] as string) as PropSidebars; } // Extra fns useful for tests! const utils = { getGlobalData: () => globalDataContainer, getRouteConfigs: () => routeConfigs, checkVersionMetadataPropCreated: (version: LoadedVersion | undefined) => { if (!version) { throw new Error('Version not found'); } const versionMetadataProp = getCreatedDataByPrefix( `version-${_.kebabCase(version.versionName)}-metadata-prop`, ); expect(versionMetadataProp.docsSidebars).toEqual(toSidebarsProp(version)); }, expectSnapshot: () => { // Sort the route config like in src/server/plugins/index.ts for // consistent snapshot ordering sortConfig(routeConfigs); expect(routeConfigs).not.toEqual([]); expect(routeConfigs).toMatchSnapshot('route config'); expect(dataContainer).toMatchSnapshot('data'); expect(globalDataContainer).toMatchSnapshot('global data'); }, }; return { actions, utils, }; }; describe('sidebar', () => { it('site with wrong sidebar content', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'simple-site'); const context = await loadContext({siteDir}); const sidebarPath = path.join(siteDir, 'wrong-sidebars.json'); const plugin = await pluginContentDocs( context, validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { sidebarPath, }, }), ); await expect(plugin.loadContent!()).rejects.toThrowErrorMatchingSnapshot(); }); it('site with wrong sidebar file path', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'site-with-doc-label'); const context = await loadContext({siteDir}); await expect(async () => { const plugin = await pluginContentDocs( context, validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { sidebarPath: 'wrong-path-sidebar.json', }, }), ); await plugin.loadContent!(); }).rejects.toThrowErrorMatchingInlineSnapshot(` "The path to the sidebar file does not exist at "wrong-path-sidebar.json". Please set the docs "sidebarPath" field in your config file to: - a sidebars path that exists - false: to disable the sidebar - undefined: for Docusaurus to generate it automatically" `); }); it('site with undefined sidebar', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'site-with-doc-label'); const context = await loadContext({siteDir}); const plugin = await pluginContentDocs( context, validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { sidebarPath: undefined, }, }), ); const result = await plugin.loadContent!(); expect(result.loadedVersions).toHaveLength(1); expect(result.loadedVersions[0]!.sidebars).toMatchSnapshot(); }); it('site with disabled sidebar', async () => { const siteDir = path.join(__dirname, '__fixtures__', 'site-with-doc-label'); const context = await loadContext({siteDir}); const plugin = await pluginContentDocs( context, validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { sidebarPath: false, }, }), ); const result = await plugin.loadContent!(); expect(result.loadedVersions).toHaveLength(1); expect(result.loadedVersions[0]!.sidebars).toEqual(DisabledSidebars); }); }); describe('empty/no docs website', () => { const siteDir = path.join(__dirname, '__fixtures__', 'empty-site'); it('no files in docs folder', async () => { const context = await loadContext({siteDir}); await fs.ensureDir(path.join(siteDir, 'docs')); const plugin = await pluginContentDocs( context, validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: {}, }), ); await expect( plugin.loadContent!(), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Docs version "current" has no docs! At least one doc should exist at "docs"."`, ); }); it('docs folder does not exist', async () => { const context = await loadContext({siteDir}); await expect( pluginContentDocs( context, validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { path: 'path/does/not/exist', }, }), ), ).rejects.toThrowErrorMatchingInlineSnapshot( `"The docs folder does not exist for version "current". A docs folder is expected to be found at path/does/not/exist."`, ); }); }); describe('simple website', () => { async function loadSite() { const siteDir = path.join(__dirname, '__fixtures__', 'simple-site'); const context = await loadContext({siteDir}); const sidebarPath = path.join(siteDir, 'sidebars.json'); const options = validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { path: 'docs', sidebarPath, }, }); const plugin = await pluginContentDocs(context, options); const pluginContentDir = path.join(context.generatedFilesDir, plugin.name); return {siteDir, context, sidebarPath, plugin, options, pluginContentDir}; } it('extendCli - docsVersion', async () => { const {plugin, options, context} = await loadSite(); const mock = jest .spyOn(cliDocs, 'cliDocsVersionCommand') .mockImplementation(async () => {}); const cli = new commander.Command(); // @ts-expect-error: in actual usage, we pass the static commander instead // of the new command plugin.extendCli!(cli); cli.parse(['node', 'test', 'docs:version', '1.0.0']); expect(mock).toHaveBeenCalledTimes(1); expect(mock).toHaveBeenCalledWith('1.0.0', options, context); mock.mockRestore(); }); it('getPathToWatch', async () => { const {siteDir, plugin} = await loadSite(); const pathToWatch = plugin.getPathsToWatch!(); const matchPattern = pathToWatch.map((filepath) => posixPath(path.relative(siteDir, filepath)), ); expect(matchPattern).toMatchSnapshot(); expect(isMatch('docs/hello.md', matchPattern)).toBe(true); expect(isMatch('docs/hello.mdx', matchPattern)).toBe(true); expect(isMatch('docs/foo/bar.md', matchPattern)).toBe(true); expect(isMatch('docs/hello.js', matchPattern)).toBe(false); expect(isMatch('docs/super.mdl', matchPattern)).toBe(false); expect(isMatch('docs/mdx', matchPattern)).toBe(false); expect(isMatch('docs/headingAsTitle.md', matchPattern)).toBe(true); expect(isMatch('sidebars.json', matchPattern)).toBe(true); expect(isMatch('versioned_docs/hello.md', matchPattern)).toBe(false); expect(isMatch('hello.md', matchPattern)).toBe(false); expect(isMatch('super/docs/hello.md', matchPattern)).toBe(false); }); it('configureWebpack', async () => { const {plugin} = await loadSite(); const content = await plugin.loadContent?.(); const config = applyConfigureWebpack( plugin.configureWebpack as NonNullable<Plugin['configureWebpack']>, { entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist'), }, }, false, undefined, content, ); const errors = webpack.validate(config); expect(errors).toBeUndefined(); }); it('content', async () => { const {plugin, pluginContentDir} = await loadSite(); const content = await plugin.loadContent!(); expect(content.loadedVersions).toHaveLength(1); const [currentVersion] = content.loadedVersions; expect(findDocById(currentVersion, 'foo/baz')).toMatchSnapshot(); expect(findDocById(currentVersion, 'hello')).toMatchSnapshot(); expect(getDocById(currentVersion, 'foo/bar')).toMatchSnapshot(); expect(currentVersion!.sidebars).toMatchSnapshot(); const {actions, utils} = createFakeActions(pluginContentDir); await plugin.contentLoaded!({ content, actions, allContent: {}, }); utils.checkVersionMetadataPropCreated(currentVersion); utils.expectSnapshot(); expect(utils.getGlobalData()).toMatchSnapshot(); }); }); describe('versioned website', () => { async function loadSite() { const siteDir = path.join(__dirname, '__fixtures__', 'versioned-site'); const context = await loadContext({siteDir}); const sidebarPath = path.join(siteDir, 'sidebars.json'); const routeBasePath = 'docs'; const options = validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { routeBasePath, sidebarPath, versions: { '1.0.1': { noIndex: true, }, }, }, }); const plugin = await pluginContentDocs(context, options); const pluginContentDir = path.join(context.generatedFilesDir, plugin.name); return { siteDir, context, routeBasePath, sidebarPath, options, plugin, pluginContentDir, }; } it('extendCli - docsVersion', async () => { const {plugin, context, options} = await loadSite(); const mock = jest .spyOn(cliDocs, 'cliDocsVersionCommand') .mockImplementation(async () => {}); const cli = new commander.Command(); // @ts-expect-error: in actual usage, we pass the static commander instead // of the new command plugin.extendCli!(cli); cli.parse(['node', 'test', 'docs:version', '2.0.0']); expect(mock).toHaveBeenCalledTimes(1); expect(mock).toHaveBeenCalledWith('2.0.0', options, context); mock.mockRestore(); }); it('getPathToWatch', async () => { const {siteDir, plugin} = await loadSite(); const pathToWatch = plugin.getPathsToWatch!(); const matchPattern = pathToWatch.map((filepath) => posixPath(path.relative(siteDir, filepath)), ); expect(matchPattern).not.toEqual([]); expect(matchPattern).toMatchSnapshot(); expect(isMatch('docs/hello.md', matchPattern)).toBe(true); expect(isMatch('docs/hello.mdx', matchPattern)).toBe(true); expect(isMatch('docs/foo/bar.md', matchPattern)).toBe(true); expect(isMatch('sidebars.json', matchPattern)).toBe(true); expect(isMatch('versioned_docs/version-1.0.0/hello.md', matchPattern)).toBe( true, ); expect( isMatch('versioned_docs/version-1.0.0/foo/bar.md', matchPattern), ).toBe(true); expect( isMatch('versioned_sidebars/version-1.0.0-sidebars.json', matchPattern), ).toBe(true); // Non existing version expect( isMatch('versioned_docs/version-2.0.0/foo/bar.md', matchPattern), ).toBe(false); expect(isMatch('versioned_docs/version-2.0.0/hello.md', matchPattern)).toBe( false, ); expect( isMatch('versioned_sidebars/version-2.0.0-sidebars.json', matchPattern), ).toBe(false); expect(isMatch('docs/hello.js', matchPattern)).toBe(false); expect(isMatch('docs/super.mdl', matchPattern)).toBe(false); expect(isMatch('docs/mdx', matchPattern)).toBe(false); expect(isMatch('hello.md', matchPattern)).toBe(false); expect(isMatch('super/docs/hello.md', matchPattern)).toBe(false); }); it('content', async () => { const {plugin, pluginContentDir} = await loadSite(); const content = await plugin.loadContent!(); expect(content.loadedVersions).toHaveLength(4); const [currentVersion, version101, version100, versionWithSlugs] = content.loadedVersions; // foo/baz.md only exists in version -1.0.0 expect(findDocById(currentVersion, 'foo/baz')).toBeUndefined(); expect(findDocById(version101, 'foo/baz')).toBeUndefined(); expect(findDocById(versionWithSlugs, 'foo/baz')).toBeUndefined(); expect(getDocById(currentVersion, 'foo/bar')).toMatchSnapshot(); expect(getDocById(version101, 'foo/bar')).toMatchSnapshot(); expect(getDocById(currentVersion, 'hello')).toMatchSnapshot(); expect(getDocById(version101, 'hello')).toMatchSnapshot(); expect(getDocById(version100, 'foo/baz')).toMatchSnapshot(); expect(currentVersion!.sidebars).toMatchSnapshot( 'current version sidebars', ); expect(version101!.sidebars).toMatchSnapshot('101 version sidebars'); expect(version100!.sidebars).toMatchSnapshot('100 version sidebars'); expect(versionWithSlugs!.sidebars).toMatchSnapshot( 'withSlugs version sidebars', ); const {actions, utils} = createFakeActions(pluginContentDir); await plugin.contentLoaded!({ content, actions, allContent: {}, }); utils.checkVersionMetadataPropCreated(currentVersion); utils.checkVersionMetadataPropCreated(version101); utils.checkVersionMetadataPropCreated(version100); utils.checkVersionMetadataPropCreated(versionWithSlugs); utils.expectSnapshot(); }); }); describe('versioned website (community)', () => { async function loadSite() { const siteDir = path.join(__dirname, '__fixtures__', 'versioned-site'); const context = await loadContext({siteDir}); const sidebarPath = path.join(siteDir, 'community_sidebars.json'); const routeBasePath = 'community'; const pluginId = 'community'; const options = validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { id: 'community', path: 'community', routeBasePath, sidebarPath, }, }); const plugin = await pluginContentDocs(context, options); const pluginContentDir = path.join(context.generatedFilesDir, plugin.name); return { siteDir, context, routeBasePath, sidebarPath, pluginId, options, plugin, pluginContentDir, }; } it('extendCli - docsVersion', async () => { const {pluginId, plugin, options, context} = await loadSite(); const mock = jest .spyOn(cliDocs, 'cliDocsVersionCommand') .mockImplementation(async () => {}); const cli = new commander.Command(); // @ts-expect-error: in actual usage, we pass the static commander instead // of the new command plugin.extendCli!(cli); cli.parse(['node', 'test', `docs:version:${pluginId}`, '2.0.0']); expect(mock).toHaveBeenCalledTimes(1); expect(mock).toHaveBeenCalledWith('2.0.0', options, context); mock.mockRestore(); }); it('getPathToWatch', async () => { const {siteDir, plugin} = await loadSite(); const pathToWatch = plugin.getPathsToWatch!(); const matchPattern = pathToWatch.map((filepath) => posixPath(path.relative(siteDir, filepath)), ); expect(matchPattern).not.toEqual([]); expect(matchPattern).toMatchSnapshot(); expect(isMatch('community/team.md', matchPattern)).toBe(true); expect( isMatch('community_versioned_docs/version-1.0.0/team.md', matchPattern), ).toBe(true); // Non existing version expect( isMatch('community_versioned_docs/version-2.0.0/team.md', matchPattern), ).toBe(false); expect( isMatch( 'community_versioned_sidebars/version-2.0.0-sidebars.json', matchPattern, ), ).toBe(false); expect(isMatch('community/team.js', matchPattern)).toBe(false); expect( isMatch('community_versioned_docs/version-1.0.0/team.js', matchPattern), ).toBe(false); }); it('content', async () => { const {plugin, pluginContentDir} = await loadSite(); const content = await plugin.loadContent!(); expect(content.loadedVersions).toHaveLength(2); const [currentVersion, version100] = content.loadedVersions; expect(getDocById(currentVersion, 'team')).toMatchSnapshot(); expect(getDocById(version100, 'team')).toMatchSnapshot(); expect(currentVersion!.sidebars).toMatchSnapshot( 'current version sidebars', ); expect(version100!.sidebars).toMatchSnapshot('100 version sidebars'); const {actions, utils} = createFakeActions(pluginContentDir); await plugin.contentLoaded!({ content, actions, allContent: {}, }); utils.checkVersionMetadataPropCreated(currentVersion); utils.checkVersionMetadataPropCreated(version100); utils.expectSnapshot(); }); }); describe('site with doc label', () => { async function loadSite() { const siteDir = path.join(__dirname, '__fixtures__', 'site-with-doc-label'); const context = await loadContext({siteDir}); const sidebarPath = path.join(siteDir, 'sidebars.json'); const plugin = await pluginContentDocs( context, validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { path: 'docs', sidebarPath, }, }), ); const content = (await plugin.loadContent?.())!; return {content}; } it('label in sidebar.json is used', async () => { const {content} = await loadSite(); const loadedVersion = content.loadedVersions[0]!; const sidebarProps = toSidebarsProp(loadedVersion); expect((sidebarProps.docs![0] as PropSidebarItemLink).label).toBe( 'Hello One', ); }); it('sidebar_label in doc has higher precedence over label in sidebar.json', async () => { const {content} = await loadSite(); const loadedVersion = content.loadedVersions[0]!; const sidebarProps = toSidebarsProp(loadedVersion); expect((sidebarProps.docs![1] as PropSidebarItemLink).label).toBe( 'Hello 2 From Doc', ); }); }); describe('site with full autogenerated sidebar', () => { async function loadSite() { const siteDir = path.join( __dirname, '__fixtures__', 'site-with-autogenerated-sidebar', ); const context = await loadContext({siteDir}); const plugin = await pluginContentDocs( context, validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { path: 'docs', }, }), ); const content = (await plugin.loadContent?.())!; return {content, siteDir}; } it('sidebar is fully autogenerated', async () => { const {content} = await loadSite(); const version = content.loadedVersions[0]!; expect(version.sidebars).toMatchSnapshot(); }); it('docs in fully generated sidebar have correct metadata', async () => { const {content} = await loadSite(); const version = content.loadedVersions[0]!; expect(getDocById(version, 'getting-started')).toMatchSnapshot(); expect(getDocById(version, 'installation')).toMatchSnapshot(); expect(getDocById(version, 'Guides/guide1')).toMatchSnapshot(); expect(getDocById(version, 'Guides/guide2')).toMatchSnapshot(); expect(getDocById(version, 'Guides/guide2.5')).toMatchSnapshot(); expect(getDocById(version, 'Guides/guide3')).toMatchSnapshot(); expect(getDocById(version, 'Guides/guide4')).toMatchSnapshot(); expect(getDocById(version, 'Guides/guide5')).toMatchSnapshot(); expect(getDocById(version, 'API/api-overview')).toMatchSnapshot(); expect(getDocById(version, 'API/Core APIs/Client API')).toMatchSnapshot(); expect(getDocById(version, 'API/Core APIs/Server API')).toMatchSnapshot(); expect( getDocById(version, 'API/Extension APIs/Plugin API'), ).toMatchSnapshot(); expect( getDocById(version, 'API/Extension APIs/Theme API'), ).toMatchSnapshot(); expect(getDocById(version, 'API/api-end')).toMatchSnapshot(); }); }); describe('site with partial autogenerated sidebars', () => { async function loadSite() { const siteDir = path.join( __dirname, '__fixtures__', 'site-with-autogenerated-sidebar', ); const context = await loadContext({siteDir}); const plugin = await pluginContentDocs( context, validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { path: 'docs', sidebarPath: path.join( __dirname, '__fixtures__', 'site-with-autogenerated-sidebar', 'partialAutogeneratedSidebars.js', ), }, }), ); const content = (await plugin.loadContent?.())!; return {content, siteDir}; } it('sidebar is partially autogenerated', async () => { const {content} = await loadSite(); const version = content.loadedVersions[0]!; expect(version.sidebars).toMatchSnapshot(); }); it('docs in partially generated sidebar have correct metadata', async () => { const {content} = await loadSite(); const version = content.loadedVersions[0]!; // Only looking at the docs of the autogen sidebar, others metadata should // not be affected expect(getDocById(version, 'API/api-end')).toMatchSnapshot(); expect(getDocById(version, 'API/api-overview')).toMatchSnapshot(); expect( getDocById(version, 'API/Extension APIs/Plugin API'), ).toMatchSnapshot(); expect( getDocById(version, 'API/Extension APIs/Theme API'), ).toMatchSnapshot(); }); }); describe('site with partial autogenerated sidebars 2 (fix #4638)', () => { // Test added for edge case https://github.com/facebook/docusaurus/issues/4638 async function loadSite() { const siteDir = path.join( __dirname, '__fixtures__', 'site-with-autogenerated-sidebar', ); const context = await loadContext({siteDir}); const plugin = await pluginContentDocs( context, validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { path: 'docs', sidebarPath: path.join( __dirname, '__fixtures__', 'site-with-autogenerated-sidebar', 'partialAutogeneratedSidebars2.js', ), }, }), ); const content = (await plugin.loadContent?.())!; return {content, siteDir}; } it('sidebar is partially autogenerated', async () => { const {content} = await loadSite(); const version = content.loadedVersions[0]!; expect(version.sidebars).toMatchSnapshot(); }); }); describe('site with custom sidebar items generator', () => { async function loadSite(sidebarItemsGenerator: SidebarItemsGeneratorOption) { const siteDir = path.join( __dirname, '__fixtures__', 'site-with-autogenerated-sidebar', ); const context = await loadContext({siteDir}); const plugin = await pluginContentDocs( context, validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options: { path: 'docs', sidebarItemsGenerator, }, }), ); const content = (await plugin.loadContent?.())!; return {content, siteDir}; } it('sidebarItemsGenerator is called with appropriate data', async () => { const customSidebarItemsGeneratorMock = jest.fn(async () => []); const {siteDir} = await loadSite(customSidebarItemsGeneratorMock); const generatorArg = ( customSidebarItemsGeneratorMock.mock .calls[0] as unknown as Parameters<SidebarItemsGeneratorOption> )[0]; // Make test pass even if docs are in different order and paths are // absolutes function makeDeterministic( arg: Parameters<SidebarItemsGeneratorOption>[0], ): Parameters<SidebarItemsGeneratorOption>[0] { return { ...arg, docs: _.orderBy(arg.docs, 'id'), version: { ...arg.version, contentPath: path.relative(siteDir, arg.version.contentPath), }, }; } expect(makeDeterministic(generatorArg)).toMatchSnapshot(); expect(generatorArg.defaultSidebarItemsGenerator).toEqual( DefaultSidebarItemsGenerator, ); }); it('sidebar is autogenerated according to a custom sidebarItemsGenerator', async () => { const customSidebarItemsGenerator: SidebarItemsGeneratorOption = async () => [ {type: 'doc', id: 'API/api-overview'}, {type: 'doc', id: 'API/api-end'}, ]; const {content} = await loadSite(customSidebarItemsGenerator); const version = content.loadedVersions[0]; expect(version!.sidebars).toMatchSnapshot(); }); it('sidebarItemsGenerator can wrap/enhance/sort/reverse the default sidebar generator', async () => { function reverseSidebarItems(items: NormalizedSidebar): NormalizedSidebar { const result: NormalizedSidebar = items.map((item) => { if (item.type === 'category') { return {...item, items: reverseSidebarItems(item.items)}; } return item; }); result.reverse(); return result; } const reversedSidebarItemsGenerator: SidebarItemsGeneratorOption = async ({ defaultSidebarItemsGenerator, ...args }) => { const sidebarItems = await defaultSidebarItemsGenerator(args); return reverseSidebarItems(sidebarItems); }; const {content} = await loadSite(reversedSidebarItemsGenerator); const version = content.loadedVersions[0]!; expect(version.sidebars).toMatchSnapshot(); }); });
1,144
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/lastUpdate.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import fs from 'fs-extra'; import path from 'path'; import shell from 'shelljs'; import {createTempRepo} from '@testing-utils/git'; import {getFileLastUpdate} from '../lastUpdate'; describe('getFileLastUpdate', () => { const existingFilePath = path.join( __dirname, '__fixtures__/simple-site/docs/hello.md', ); it('existing test file in repository with Git timestamp', async () => { const lastUpdateData = await getFileLastUpdate(existingFilePath); expect(lastUpdateData).not.toBeNull(); const {author, timestamp} = lastUpdateData!; expect(author).not.toBeNull(); expect(typeof author).toBe('string'); expect(timestamp).not.toBeNull(); expect(typeof timestamp).toBe('number'); }); it('existing test file with spaces in path', async () => { const filePathWithSpace = path.join( __dirname, '__fixtures__/simple-site/docs/doc with space.md', ); const lastUpdateData = await getFileLastUpdate(filePathWithSpace); expect(lastUpdateData).not.toBeNull(); const {author, timestamp} = lastUpdateData!; expect(author).not.toBeNull(); expect(typeof author).toBe('string'); expect(timestamp).not.toBeNull(); expect(typeof timestamp).toBe('number'); }); it('non-existing file', async () => { const consoleMock = jest .spyOn(console, 'warn') .mockImplementation(() => {}); const nonExistingFileName = '.nonExisting'; const nonExistingFilePath = path.join( __dirname, '__fixtures__', nonExistingFileName, ); await expect(getFileLastUpdate(nonExistingFilePath)).resolves.toBeNull(); expect(consoleMock).toHaveBeenCalledTimes(1); expect(consoleMock).toHaveBeenLastCalledWith( expect.stringMatching(/because the file does not exist./), ); consoleMock.mockRestore(); }); it('temporary created file that is not tracked by git', async () => { const consoleMock = jest .spyOn(console, 'warn') .mockImplementation(() => {}); const {repoDir} = createTempRepo(); const tempFilePath = path.join(repoDir, 'file.md'); await fs.writeFile(tempFilePath, 'Lorem ipsum :)'); await expect(getFileLastUpdate(tempFilePath)).resolves.toBeNull(); expect(consoleMock).toHaveBeenCalledTimes(1); expect(consoleMock).toHaveBeenLastCalledWith( expect.stringMatching(/not tracked by git./), ); await fs.unlink(tempFilePath); }); it('multiple files not tracked by git', async () => { const consoleMock = jest .spyOn(console, 'warn') .mockImplementation(() => {}); const {repoDir} = createTempRepo(); const tempFilePath1 = path.join(repoDir, 'file1.md'); const tempFilePath2 = path.join(repoDir, 'file2.md'); await fs.writeFile(tempFilePath1, 'Lorem ipsum :)'); await fs.writeFile(tempFilePath2, 'Lorem ipsum :)'); await expect(getFileLastUpdate(tempFilePath1)).resolves.toBeNull(); await expect(getFileLastUpdate(tempFilePath2)).resolves.toBeNull(); expect(consoleMock).toHaveBeenCalledTimes(1); expect(consoleMock).toHaveBeenLastCalledWith( expect.stringMatching(/not tracked by git./), ); await fs.unlink(tempFilePath1); await fs.unlink(tempFilePath2); }); it('git does not exist', async () => { const mock = jest.spyOn(shell, 'which').mockImplementationOnce(() => null); const consoleMock = jest .spyOn(console, 'warn') .mockImplementation(() => {}); const lastUpdateData = await getFileLastUpdate(existingFilePath); expect(lastUpdateData).toBeNull(); expect(consoleMock).toHaveBeenLastCalledWith( expect.stringMatching( /.*\[WARNING\].* Sorry, the docs plugin last update options require Git\..*/, ), ); consoleMock.mockRestore(); mock.mockRestore(); }); });
1,145
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/numberPrefix.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { DefaultNumberPrefixParser, DisabledNumberPrefixParser, stripNumberPrefix, stripPathNumberPrefixes, } from '../numberPrefix'; const IgnoredNumberPrefixPatterns = [ // Patterns without number prefix 'MyDoc', 'a1-My Doc', 'My Doc-000', 'My Doc - 1', 'My Doc - 02', 'Hey - 03 - My Doc', '00abc01-My Doc', 'My 001- Doc', 'My -001 Doc', // Ignore common date-like patterns: https://github.com/facebook/docusaurus/issues/4640 '2021-01-31 - Doc', '31-01-2021 - Doc', '2021_01_31 - Doc', '31_01_2021 - Doc', '2021.01.31 - Doc', '31.01.2021 - Doc', '2021-01 - Doc', '2021_01 - Doc', '2021.01 - Doc', '01-2021 - Doc', '01_2021 - Doc', '01.2021 - Doc', // Date patterns without suffix '2021-01-31', '2021-01', '21-01-31', '21-01', '2021_01_31', '2021_01', '21_01_31', '21_01', '01_31', '01', '2021', '01', // Ignore common versioning patterns: https://github.com/facebook/docusaurus/issues/4653 '8.0', '8.0.0', '14.2.16', '18.2', '8.0 - Doc', '8.0.0 - Doc', '8_0', '8_0_0', '14_2_16', '18_2', '8.0 - Doc', '8.0.0 - Doc', ]; describe('stripNumberPrefix', () => { function stripNumberPrefixDefault(str: string) { return stripNumberPrefix(str, DefaultNumberPrefixParser); } it('strips number prefix if present', () => { expect(stripNumberPrefixDefault('1-My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('01-My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001-My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001 - My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001 - My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('999 - My Doc')).toBe('My Doc'); // expect(stripNumberPrefixDefault('1---My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('01---My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001---My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001 --- My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001 --- My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('999 --- My Doc')).toBe( 'My Doc', ); // expect(stripNumberPrefixDefault('1___My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('01___My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001___My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001 ___ My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001 ___ My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('999 ___ My Doc')).toBe( 'My Doc', ); // expect(stripNumberPrefixDefault('1.My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('01.My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001.My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001 . My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('001 . My Doc')).toBe('My Doc'); expect(stripNumberPrefixDefault('999 . My Doc')).toBe('My Doc'); }); it('does not strip number prefix if pattern does not match', () => { IgnoredNumberPrefixPatterns.forEach((badPattern) => { expect(stripNumberPrefixDefault(badPattern)).toEqual(badPattern); }); }); }); describe('stripPathNumberPrefix', () => { it('strips number prefixes in paths', () => { expect( stripPathNumberPrefixes( '0-MyRootFolder0/1 - MySubFolder1/2. MyDeepFolder2/3 _MyDoc3', DefaultNumberPrefixParser, ), ).toBe('MyRootFolder0/MySubFolder1/MyDeepFolder2/MyDoc3'); }); it('strips number prefixes in paths with custom parser', () => { function stripPathNumberPrefixCustom(str: string) { return { filename: str.substring(1, str.length), numberPrefix: 0, }; } expect( stripPathNumberPrefixes('aaaa/bbbb/cccc', stripPathNumberPrefixCustom), ).toBe('aaa/bbb/ccc'); }); it('does not strip number prefixes in paths with disabled parser', () => { expect( stripPathNumberPrefixes( '0-MyRootFolder0/1 - MySubFolder1/2. MyDeepFolder2/3 _MyDoc3', DisabledNumberPrefixParser, ), ).toBe('0-MyRootFolder0/1 - MySubFolder1/2. MyDeepFolder2/3 _MyDoc3'); }); }); describe('DefaultNumberPrefixParser', () => { it('extracts number prefix if present', () => { expect(DefaultNumberPrefixParser('0-My Doc')).toEqual({ filename: 'My Doc', numberPrefix: 0, }); expect(DefaultNumberPrefixParser('1-My Doc')).toEqual({ filename: 'My Doc', numberPrefix: 1, }); expect(DefaultNumberPrefixParser('01-My Doc')).toEqual({ filename: 'My Doc', numberPrefix: 1, }); expect(DefaultNumberPrefixParser('001-My Doc')).toEqual({ filename: 'My Doc', numberPrefix: 1, }); expect(DefaultNumberPrefixParser('001 - My Doc')).toEqual({ filename: 'My Doc', numberPrefix: 1, }); expect(DefaultNumberPrefixParser('001 - My Doc')).toEqual({ filename: 'My Doc', numberPrefix: 1, }); expect(DefaultNumberPrefixParser('999 - My Doc')).toEqual({ filename: 'My Doc', numberPrefix: 999, }); expect(DefaultNumberPrefixParser('0046036 - My Doc')).toEqual({ filename: 'My Doc', numberPrefix: 46036, }); }); it('does not extract number prefix if pattern does not match', () => { IgnoredNumberPrefixPatterns.forEach((badPattern) => { expect(DefaultNumberPrefixParser(badPattern)).toEqual({ filename: badPattern, numberPrefix: undefined, }); }); }); });
1,146
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/options.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {GlobExcludeDefault} from '@docusaurus/utils'; import {normalizePluginOptions} from '@docusaurus/utils-validation'; import {validateOptions, DEFAULT_OPTIONS} from '../options'; import {DefaultSidebarItemsGenerator} from '../sidebars/generator'; import { DefaultNumberPrefixParser, DisabledNumberPrefixParser, } from '../numberPrefix'; import type {Options, PluginOptions} from '@docusaurus/plugin-content-docs'; import type {Validate} from '@docusaurus/types'; // The type of remark/rehype plugins can be function/object const markdownPluginsFunctionStub = () => {}; const markdownPluginsObjectStub = {}; function testValidate(options: Options) { return validateOptions({ validate: normalizePluginOptions as Validate<Options, PluginOptions>, options, }); } const defaultOptions = { ...DEFAULT_OPTIONS, id: 'default', // The admonitions plugin is automatically added. Not really worth testing remarkPlugins: expect.any(Array), }; describe('normalizeDocsPluginOptions', () => { it('returns default options for undefined user options', () => { expect(testValidate({})).toEqual(defaultOptions); }); it('accepts correctly defined user options', () => { const userOptions: Options = { path: 'my-docs', // Path to data on filesystem, relative to site dir. routeBasePath: '/my-docs', // URL Route. tagsBasePath: 'tags', // URL Tags Route. include: ['**/*.{md,mdx}'], // Extensions to include. exclude: GlobExcludeDefault, sidebarPath: 'my-sidebar', // Path to sidebar configuration for showing a list of markdown pages. sidebarItemsGenerator: DefaultSidebarItemsGenerator, numberPrefixParser: DefaultNumberPrefixParser, docsRootComponent: '@theme/DocsRoot', docVersionRootComponent: '@theme/DocVersionRoot', docRootComponent: '@theme/DocRoot', docItemComponent: '@theme/DocItem', docTagDocListComponent: '@theme/DocTagDocListPage', docTagsListComponent: '@theme/DocTagsListPage', docCategoryGeneratedIndexComponent: '@theme/DocCategoryGeneratedIndexPage', // @ts-expect-error: it seems to work in practice? remarkPlugins: [markdownPluginsObjectStub], rehypePlugins: [markdownPluginsFunctionStub], beforeDefaultRehypePlugins: [], beforeDefaultRemarkPlugins: [], breadcrumbs: true, showLastUpdateTime: true, showLastUpdateAuthor: true, admonitions: false, includeCurrentVersion: false, disableVersioning: true, editCurrentVersion: true, editLocalizedFiles: true, versions: { current: { path: 'next', label: 'next', }, version1: { path: 'hello', label: 'world', noIndex: true, }, }, sidebarCollapsible: false, sidebarCollapsed: false, }; expect(testValidate(userOptions)).toEqual({ ...defaultOptions, ...userOptions, }); }); it('accepts correctly defined remark and rehype plugin options', () => { const userOptions: Options = { beforeDefaultRemarkPlugins: [], beforeDefaultRehypePlugins: [markdownPluginsFunctionStub], remarkPlugins: [[markdownPluginsFunctionStub, {option1: '42'}]], rehypePlugins: [ // @ts-expect-error: it seems to work in practice markdownPluginsObjectStub, [markdownPluginsFunctionStub, {option1: '42'}], ], }; expect(testValidate(userOptions)).toEqual({ ...defaultOptions, ...userOptions, }); }); it('accepts admonitions false', () => { const admonitionsFalse: Options = { admonitions: false, }; expect(testValidate(admonitionsFalse)).toEqual({ ...defaultOptions, ...admonitionsFalse, }); }); it('rejects admonitions array', () => { expect(() => testValidate({ // @ts-expect-error: rejected value admonitions: [], }), ).toThrowErrorMatchingInlineSnapshot( `""admonitions" does not look like a valid admonitions config"`, ); }); it('accepts numberPrefixParser function', () => { function customNumberPrefixParser() {} expect( testValidate({ numberPrefixParser: customNumberPrefixParser as unknown as Options['numberPrefixParser'], }), ).toEqual({ ...defaultOptions, numberPrefixParser: customNumberPrefixParser, }); }); it('accepts numberPrefixParser false', () => { expect(testValidate({numberPrefixParser: false})).toEqual({ ...defaultOptions, numberPrefixParser: DisabledNumberPrefixParser, }); }); it('accepts numberPrefixParser true', () => { expect(testValidate({numberPrefixParser: true})).toEqual({ ...defaultOptions, numberPrefixParser: DefaultNumberPrefixParser, }); }); it('rejects invalid remark plugin options', () => { expect(() => testValidate({ // @ts-expect-error: test remarkPlugins: [[{option1: '42'}, markdownPluginsFunctionStub]], }), ).toThrowErrorMatchingInlineSnapshot(` ""remarkPlugins[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `); }); it('rejects invalid rehype plugin options', () => { expect(() => testValidate({ rehypePlugins: [ // @ts-expect-error: test [ markdownPluginsFunctionStub, {option1: '42'}, markdownPluginsFunctionStub, ], ], }), ).toThrowErrorMatchingInlineSnapshot(` ""rehypePlugins[0]" does not look like a valid MDX plugin config. A plugin config entry should be one of: - A tuple, like \`[require("rehype-katex"), { strict: false }]\`, or - A simple module, like \`require("remark-math")\`" `); }); it('rejects bad path inputs', () => { // @ts-expect-error: test expect(() => testValidate({path: 2})).toThrowErrorMatchingInlineSnapshot( `""path" must be a string"`, ); }); it('rejects bad include inputs', () => { expect(() => // @ts-expect-error: test testValidate({include: '**/*.{md,mdx}'}), ).toThrowErrorMatchingInlineSnapshot(`""include" must be an array"`); }); it('rejects bad showLastUpdateTime inputs', () => { expect(() => // @ts-expect-error: test testValidate({showLastUpdateTime: 'true'}), ).toThrowErrorMatchingInlineSnapshot( `""showLastUpdateTime" must be a boolean"`, ); }); it('rejects bad remarkPlugins input', () => { expect(() => // @ts-expect-error: test testValidate({remarkPlugins: 'remark-math'}), ).toThrowErrorMatchingInlineSnapshot(`""remarkPlugins" must be an array"`); }); it('rejects bad lastVersion', () => { expect(() => // @ts-expect-error: test testValidate({lastVersion: false}), ).toThrowErrorMatchingInlineSnapshot(`""lastVersion" must be a string"`); }); it('rejects bad versions', () => { expect(() => testValidate({ versions: { current: { // @ts-expect-error: test hey: 3, }, version1: { path: 'hello', label: 'world', }, }, }), ).toThrowErrorMatchingInlineSnapshot( `""versions.current.hey" is not allowed"`, ); }); it('handles sidebarCollapsed option inconsistencies', () => { expect( testValidate({ sidebarCollapsible: true, sidebarCollapsed: undefined, }).sidebarCollapsed, ).toBe(true); expect( testValidate({ sidebarCollapsible: false, sidebarCollapsed: undefined, }).sidebarCollapsed, ).toBe(false); expect( testValidate({ sidebarCollapsible: false, sidebarCollapsed: true, }).sidebarCollapsed, ).toBe(false); }); });
1,147
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/props.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {toSidebarDocItemLinkProp, toTagDocListProp} from '../props'; describe('toTagDocListProp', () => { type Params = Parameters<typeof toTagDocListProp>[0]; type Tag = Params['tag']; type Doc = Params['docs'][number]; const allTagsPath = '/all/tags'; it('works', () => { const tag: Tag = { label: 'tag1', permalink: '/tag1', docIds: ['id1', 'id3'], unlisted: false, }; const doc1 = { id: 'id1', title: 'ZZZ 1', description: 'Description 1', permalink: '/doc1', } as Doc; const doc2 = { id: 'id2', title: 'XXX 2', description: 'Description 2', permalink: '/doc2', } as Doc; const doc3 = { id: 'id3', title: 'AAA 3', description: 'Description 3', permalink: '/doc3', } as Doc; const doc4 = { id: 'id4', title: 'UUU 4', description: 'Description 4', permalink: '/doc4', } as Doc; const result = toTagDocListProp({ allTagsPath, tag, docs: [doc1, doc2, doc3, doc4], }); expect(result).toEqual({ allTagsPath, count: 2, label: tag.label, permalink: tag.permalink, unlisted: false, items: [doc3, doc1], // Docs sorted by title, ignore "id5" absence }); }); }); describe('toSidebarDocItemLinkProp', () => { type Params = Parameters<typeof toSidebarDocItemLinkProp>[0]; type Result = ReturnType<typeof toSidebarDocItemLinkProp>; type DocSidebarItem = Params['item']; type Doc = Params['doc']; const id = 'some-doc-id'; const item: DocSidebarItem = { type: 'doc', id, label: 'doc sidebar item label', }; const doc: Doc = { id, title: 'doc title', permalink: '/docPermalink', frontMatter: {}, unlisted: false, }; it('works', () => { const result = toSidebarDocItemLinkProp({ item, doc, }); expect(result).toEqual({ type: 'link', docId: id, unlisted: false, label: item.label, autoAddBaseUrl: undefined, className: undefined, href: doc.permalink, customProps: undefined, } as Result); }); it('uses unlisted from metadata and ignores frontMatter', () => { expect( toSidebarDocItemLinkProp({ item, doc: { ...doc, unlisted: true, frontMatter: { unlisted: false, }, }, }).unlisted, ).toBe(true); expect( toSidebarDocItemLinkProp({ item, doc: { ...doc, unlisted: false, frontMatter: { unlisted: true, }, }, }).unlisted, ).toBe(false); }); });
1,148
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/slug.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import getSlug from '../slug'; describe('getSlug', () => { it('defaults to dirname/id', () => { expect( getSlug({ baseID: 'doc', source: '@site/docs/dir/doc.md', sourceDirName: '/dir', }), ).toBe('/dir/doc'); expect( getSlug({ baseID: 'doc', source: '@site/docs/dir/subdir/doc.md', sourceDirName: '/dir/subdir', }), ).toBe('/dir/subdir/doc'); }); it('handles conventional doc indexes', () => { expect( getSlug({ baseID: 'doc', source: '@site/docs/dir/subdir/index.md', sourceDirName: '/dir/subdir', }), ).toBe('/dir/subdir/'); expect( getSlug({ baseID: 'doc', source: '@site/docs/dir/subdir/inDEx.mdx', sourceDirName: '/dir/subdir', }), ).toBe('/dir/subdir/'); expect( getSlug({ baseID: 'doc', source: '@site/docs/dir/subdir/readme.md', sourceDirName: '/dir/subdir', }), ).toBe('/dir/subdir/'); expect( getSlug({ baseID: 'doc', source: '@site/docs/dir/subdir/reADMe.mdx', sourceDirName: '/dir/subdir', }), ).toBe('/dir/subdir/'); expect( getSlug({ baseID: 'doc', source: '@site/docs/dir/subdir/subdir.md', sourceDirName: '/dir/subdir', }), ).toBe('/dir/subdir/'); expect( getSlug({ baseID: 'doc', source: '@site/docs/dir/subdir/suBDir.mdx', sourceDirName: '/dir/subdir', }), ).toBe('/dir/subdir/'); }); it('ignores conventional doc index when explicit slug front matter is provided', () => { expect( getSlug({ baseID: 'doc', source: '@site/docs/dir/subdir/index.md', sourceDirName: '/dir/subdir', frontMatterSlug: '/my/frontMatterSlug', }), ).toBe('/my/frontMatterSlug'); }); it('can strip dir number prefixes', () => { expect( getSlug({ baseID: 'doc', source: '@site/docs/001-dir1/002-dir2/doc.md', sourceDirName: '/001-dir1/002-dir2', stripDirNumberPrefixes: true, }), ).toBe('/dir1/dir2/doc'); expect( getSlug({ baseID: 'doc', source: '@site/docs/001-dir1/002-dir2/doc.md', sourceDirName: '/001-dir1/002-dir2', stripDirNumberPrefixes: false, }), ).toBe('/001-dir1/002-dir2/doc'); }); // See https://github.com/facebook/docusaurus/issues/3223 it('handles special chars in doc path', () => { expect( getSlug({ baseID: 'my dôc', source: '@site/docs/dir with spâce/hey $hello/doc.md', sourceDirName: '/dir with spâce/hey $hello', }), ).toBe('/dir with spâce/hey $hello/my dôc'); }); it('throws for invalid routes', () => { expect(() => getSlug({ baseID: 'my dôc', source: '@site/docs/dir with spâce/hey $hello/doc.md', sourceDirName: '/dir with spâce/hey $hello', frontMatterSlug: '//', }), ).toThrowErrorMatchingInlineSnapshot(` "We couldn't compute a valid slug for document with ID "my dôc" in "/dir with spâce/hey $hello" directory. The slug we computed looks invalid: //. Maybe your slug front matter is incorrect or there are special characters in the file path? By using front matter to set a custom slug, you should be able to fix this error: --- slug: /my/customDocPath --- " `); }); it('handles current dir', () => { expect( getSlug({baseID: 'doc', source: '@site/docs/doc.md', sourceDirName: '.'}), ).toBe('/doc'); expect( getSlug({baseID: 'doc', source: '@site/docs/doc.md', sourceDirName: '/'}), ).toBe('/doc'); }); it('resolves absolute slug front matter', () => { expect( getSlug({ baseID: 'any', source: '@site/docs/doc.md', sourceDirName: '.', frontMatterSlug: '/abc/def', }), ).toBe('/abc/def'); expect( getSlug({ baseID: 'any', source: '@site/docs/any/doc.md', sourceDirName: './any', frontMatterSlug: '/abc/def', }), ).toBe('/abc/def'); expect( getSlug({ baseID: 'any', source: '@site/docs/any/any/doc.md', sourceDirName: './any/any', frontMatterSlug: '/abc/def', }), ).toBe('/abc/def'); }); it('resolves relative slug front matter', () => { expect( getSlug({ baseID: 'any', source: '@site/docs/doc.md', sourceDirName: '.', frontMatterSlug: 'abc/def', }), ).toBe('/abc/def'); expect( getSlug({ baseID: 'any', source: '@site/docs/dir/doc.md', sourceDirName: '/dir', frontMatterSlug: 'abc/def', }), ).toBe('/dir/abc/def'); expect( getSlug({ baseID: 'any', source: '@site/docs/nonSlashedDir/doc.md', sourceDirName: 'nonSlashedDir', frontMatterSlug: 'abc/def', }), ).toBe('/nonSlashedDir/abc/def'); expect( getSlug({ baseID: 'any', source: '@site/docs/dir/subdir/doc.md', sourceDirName: 'dir/subdir', frontMatterSlug: 'abc/def', }), ).toBe('/dir/subdir/abc/def'); expect( getSlug({ baseID: 'any', source: '@site/docs/dir/doc.md', sourceDirName: '/dir', frontMatterSlug: './abc/def', }), ).toBe('/dir/abc/def'); expect( getSlug({ baseID: 'any', source: '@site/docs/dir/doc.md', sourceDirName: '/dir', frontMatterSlug: './abc/../def', }), ).toBe('/dir/def'); expect( getSlug({ baseID: 'any', source: '@site/docs/dir/subdir/doc.md', sourceDirName: '/dir/subdir', frontMatterSlug: '../abc/def', }), ).toBe('/dir/abc/def'); expect( getSlug({ baseID: 'any', source: '@site/docs/dir/subdirDoc.md', sourceDirName: '/dir/subdir', frontMatterSlug: '../../../../../abc/../def', }), ).toBe('/def'); }); });
1,149
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/translations.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {updateTranslationFileMessages} from '@docusaurus/utils'; import {CURRENT_VERSION_NAME} from '../constants'; import { getLoadedContentTranslationFiles, translateLoadedContent, } from '../translations'; import type { DocMetadata, LoadedContent, LoadedVersion, } from '@docusaurus/plugin-content-docs'; function createSampleDoc(doc: Pick<DocMetadata, 'id'>): DocMetadata { return { sourceDirName: '', draft: false, tags: [], editUrl: 'any', lastUpdatedAt: 0, lastUpdatedBy: 'any', next: undefined, previous: undefined, permalink: 'any', slug: 'any', source: 'any', version: 'any', title: `${doc.id} title`, frontMatter: { sidebar_label: `${doc.id} title`, }, description: `${doc.id} description`, ...doc, }; } function createSampleVersion( version: Pick<LoadedVersion, 'versionName'>, ): LoadedVersion { return { label: `${version.versionName} label`, path: '/docs/', routePriority: undefined, sidebarFilePath: 'any', isLast: true, contentPath: 'any', contentPathLocalized: 'any', tagsPath: '/tags/', banner: null, badge: true, className: '', drafts: [], docs: [ createSampleDoc({id: 'doc1'}), createSampleDoc({id: 'doc2'}), createSampleDoc({id: 'doc3'}), createSampleDoc({id: 'doc4'}), createSampleDoc({id: 'doc5'}), ], sidebars: { docs: [ { type: 'category', label: 'Getting started', collapsed: false, collapsible: true, link: { type: 'generated-index', slug: '/category/getting-started-index-slug', permalink: '/docs/category/getting-started-index-slug', title: 'Getting started index title', description: 'Getting started index description', }, items: [ { type: 'doc', id: 'doc1', }, { type: 'doc', id: 'doc2', label: 'Second doc translatable', translatable: true, }, { type: 'link', label: 'Link label', href: 'https://facebook.com', }, { type: 'ref', id: 'doc1', }, ], }, { type: 'doc', id: 'doc3', }, ], otherSidebar: [ { type: 'doc', id: 'doc4', }, { type: 'ref', id: 'doc5', label: 'Fifth doc translatable', translatable: true, }, ], }, ...version, }; } const SampleLoadedContent: LoadedContent = { loadedVersions: [ createSampleVersion({ versionName: CURRENT_VERSION_NAME, }), createSampleVersion({ versionName: '2.0.0', }), createSampleVersion({ versionName: '1.0.0', }), ], }; function getSampleTranslationFiles() { return getLoadedContentTranslationFiles(SampleLoadedContent); } function getSampleTranslationFilesTranslated() { const translationFiles = getSampleTranslationFiles(); return translationFiles.map((translationFile) => updateTranslationFileMessages( translationFile, (message) => `${message} (translated)`, ), ); } describe('getLoadedContentTranslationFiles', () => { it('returns translation files', () => { expect(getSampleTranslationFiles()).toMatchSnapshot(); }); }); describe('translateLoadedContent', () => { it('does not translate anything if translation files are untranslated', () => { const translationFiles = getSampleTranslationFiles(); expect( translateLoadedContent(SampleLoadedContent, translationFiles), ).toEqual(SampleLoadedContent); }); it('returns translated loaded content', () => { const translationFiles = getSampleTranslationFilesTranslated(); expect( translateLoadedContent(SampleLoadedContent, translationFiles), ).toMatchSnapshot(); }); });
1,243
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/cli.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`docsVersion first time versioning 1`] = ` { "docs": { "Guides": [ "hello", ], "Test": [ { "items": [ "foo/bar", "doc-unlisted", "foo/baz", ], "label": "foo", "type": "category", }, { "items": [ "unlisted-category/unlisted-category-doc", ], "label": "Unlisted category", "link": { "id": "unlisted-category/unlisted-category-index", "type": "doc", }, "type": "category", }, { "items": [ "rootAbsoluteSlug", "rootRelativeSlug", "rootResolvedSlug", "rootTryToEscapeSlug", ], "label": "Slugs", "link": { "type": "generated-index", }, "type": "category", }, { "id": "headingAsTitle", "type": "doc", }, { "href": "https://github.com", "label": "GitHub", "type": "link", }, { "id": "hello", "type": "ref", }, ], }, } `; exports[`docsVersion not the first time versioning 1`] = ` { "docs": { "Guides": [ "hello", ], "Test": [ "foo/bar", ], }, } `; exports[`docsVersion second docs instance versioning 1`] = ` { "community": [ "team", ], } `; exports[`docsVersion works with custom i18n paths 1`] = ` [ { "dirName": ".", "type": "autogenerated", }, ] `;
1,244
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/docs.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`simple site custom pagination - development 1`] = ` { "pagination": [ { "id": "customLastUpdate", "next": { "permalink": "/docs/doc with space", "title": "Hoo hoo, if this path tricks you...", }, "prev": undefined, }, { "id": "doc with space", "next": { "permalink": "/docs/doc-draft", "title": "doc-draft", }, "prev": { "permalink": "/docs/customLastUpdate", "title": "Custom Last Update", }, }, { "id": "doc-draft", "next": { "permalink": "/docs/doc-unlisted", "title": "doc-unlisted", }, "prev": { "permalink": "/docs/doc with space", "title": "Hoo hoo, if this path tricks you...", }, }, { "id": "doc-unlisted", "next": { "permalink": "/docs/foo/bar", "title": "Bar", }, "prev": { "permalink": "/docs/doc-draft", "title": "doc-draft", }, }, { "id": "foo/bar", "next": undefined, "prev": undefined, }, { "id": "foo/baz", "next": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, "prev": { "permalink": "/docs/foo/bar", "title": "Bar", }, }, { "id": "headingAsTitle", "next": { "permalink": "/docs/", "title": "Hello sidebar_label", }, "prev": { "permalink": "/docs/foo/bazSlug.html", "title": "baz pagination_label", }, }, { "id": "hello", "next": { "permalink": "/docs/ipsum", "title": "ipsum", }, "prev": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, }, { "id": "ipsum", "next": { "permalink": "/docs/doc-unlisted", "title": "doc-unlisted", }, "prev": { "permalink": "/docs/", "title": "Hello sidebar_label", }, }, { "id": "lastUpdateAuthorOnly", "next": { "permalink": "/docs/lastUpdateDateOnly", "title": "Last Update Date Only", }, "prev": { "permalink": "/docs/ipsum", "title": "ipsum", }, }, { "id": "lastUpdateDateOnly", "next": { "permalink": "/docs/lorem", "title": "lorem", }, "prev": { "permalink": "/docs/lastUpdateAuthorOnly", "title": "Last Update Author Only", }, }, { "id": "lorem", "next": { "permalink": "/docs/rootAbsoluteSlug", "title": "rootAbsoluteSlug", }, "prev": { "permalink": "/docs/lastUpdateDateOnly", "title": "Last Update Date Only", }, }, { "id": "rootAbsoluteSlug", "next": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, "prev": { "permalink": "/docs/foo/bazSlug.html", "title": "baz pagination_label", }, }, { "id": "rootRelativeSlug", "next": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, "prev": { "permalink": "/docs/foo/bazSlug.html", "title": "baz pagination_label", }, }, { "id": "rootResolvedSlug", "next": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, "prev": { "permalink": "/docs/foo/bazSlug.html", "title": "baz pagination_label", }, }, { "id": "rootTryToEscapeSlug", "next": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, "prev": { "permalink": "/docs/foo/bazSlug.html", "title": "baz pagination_label", }, }, { "id": "slugs/absoluteSlug", "next": { "permalink": "/docs/slugs/relativeSlug", "title": "relativeSlug", }, "prev": { "permalink": "/docs/rootTryToEscapeSlug", "title": "rootTryToEscapeSlug", }, }, { "id": "slugs/relativeSlug", "next": { "permalink": "/docs/slugs/hey/resolvedSlug", "title": "resolvedSlug", }, "prev": { "permalink": "/docs/absoluteSlug", "title": "absoluteSlug", }, }, { "id": "slugs/resolvedSlug", "next": { "permalink": "/docs/tryToEscapeSlug", "title": "tryToEscapeSlug", }, "prev": { "permalink": "/docs/slugs/relativeSlug", "title": "relativeSlug", }, }, { "id": "slugs/tryToEscapeSlug", "next": { "permalink": "/docs/unlisted-category/", "title": "unlisted-category-index", }, "prev": { "permalink": "/docs/slugs/hey/resolvedSlug", "title": "resolvedSlug", }, }, { "id": "unlisted-category/unlisted-category-doc", "next": undefined, "prev": { "permalink": "/docs/unlisted-category/", "title": "unlisted-category-index", }, }, { "id": "unlisted-category/unlisted-category-index", "next": { "permalink": "/docs/unlisted-category/unlisted-category-doc", "title": "unlisted-category-doc", }, "prev": { "permalink": "/docs/tryToEscapeSlug", "title": "tryToEscapeSlug", }, }, ], "sidebars": { "defaultSidebar": [ { "id": "customLastUpdate", "type": "doc", }, { "id": "doc with space", "type": "doc", }, { "id": "doc-draft", "type": "doc", }, { "id": "doc-unlisted", "type": "doc", }, { "collapsed": false, "collapsible": true, "items": [ { "id": "foo/bar", "type": "doc", }, { "id": "foo/baz", "type": "doc", }, ], "label": "foo", "link": undefined, "type": "category", }, { "id": "headingAsTitle", "type": "doc", }, { "id": "hello", "label": "Hello sidebar_label", "type": "doc", }, { "id": "ipsum", "type": "doc", }, { "id": "lastUpdateAuthorOnly", "type": "doc", }, { "id": "lastUpdateDateOnly", "type": "doc", }, { "id": "lorem", "type": "doc", }, { "id": "rootAbsoluteSlug", "type": "doc", }, { "id": "rootRelativeSlug", "type": "doc", }, { "id": "rootResolvedSlug", "type": "doc", }, { "id": "rootTryToEscapeSlug", "type": "doc", }, { "collapsed": false, "collapsible": true, "items": [ { "id": "slugs/absoluteSlug", "type": "doc", }, { "id": "slugs/relativeSlug", "type": "doc", }, { "id": "slugs/resolvedSlug", "type": "doc", }, { "id": "slugs/tryToEscapeSlug", "type": "doc", }, ], "label": "slugs", "link": undefined, "type": "category", }, { "collapsed": false, "collapsible": true, "items": [ { "id": "unlisted-category/unlisted-category-doc", "type": "doc", }, ], "label": "unlisted-category-index", "link": { "id": "unlisted-category/unlisted-category-index", "type": "doc", }, "type": "category", }, ], }, } `; exports[`simple site custom pagination - production 1`] = ` { "pagination": [ { "id": "customLastUpdate", "next": { "permalink": "/docs/doc with space", "title": "Hoo hoo, if this path tricks you...", }, "prev": undefined, }, { "id": "doc with space", "next": { "permalink": "/docs/doc-draft", "title": "doc-draft", }, "prev": { "permalink": "/docs/customLastUpdate", "title": "Custom Last Update", }, }, { "id": "doc-draft", "next": { "permalink": "/docs/foo/bar", "title": "Bar", }, "prev": { "permalink": "/docs/doc with space", "title": "Hoo hoo, if this path tricks you...", }, }, { "id": "doc-unlisted", "next": undefined, "prev": undefined, }, { "id": "foo/bar", "next": undefined, "prev": undefined, }, { "id": "foo/baz", "next": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, "prev": { "permalink": "/docs/foo/bar", "title": "Bar", }, }, { "id": "headingAsTitle", "next": { "permalink": "/docs/", "title": "Hello sidebar_label", }, "prev": { "permalink": "/docs/foo/bazSlug.html", "title": "baz pagination_label", }, }, { "id": "hello", "next": { "permalink": "/docs/ipsum", "title": "ipsum", }, "prev": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, }, { "id": "ipsum", "next": undefined, "prev": { "permalink": "/docs/", "title": "Hello sidebar_label", }, }, { "id": "lastUpdateAuthorOnly", "next": { "permalink": "/docs/lastUpdateDateOnly", "title": "Last Update Date Only", }, "prev": { "permalink": "/docs/ipsum", "title": "ipsum", }, }, { "id": "lastUpdateDateOnly", "next": { "permalink": "/docs/lorem", "title": "lorem", }, "prev": { "permalink": "/docs/lastUpdateAuthorOnly", "title": "Last Update Author Only", }, }, { "id": "lorem", "next": { "permalink": "/docs/rootAbsoluteSlug", "title": "rootAbsoluteSlug", }, "prev": { "permalink": "/docs/lastUpdateDateOnly", "title": "Last Update Date Only", }, }, { "id": "rootAbsoluteSlug", "next": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, "prev": { "permalink": "/docs/foo/bazSlug.html", "title": "baz pagination_label", }, }, { "id": "rootRelativeSlug", "next": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, "prev": { "permalink": "/docs/foo/bazSlug.html", "title": "baz pagination_label", }, }, { "id": "rootResolvedSlug", "next": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, "prev": { "permalink": "/docs/foo/bazSlug.html", "title": "baz pagination_label", }, }, { "id": "rootTryToEscapeSlug", "next": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, "prev": { "permalink": "/docs/foo/bazSlug.html", "title": "baz pagination_label", }, }, { "id": "slugs/absoluteSlug", "next": { "permalink": "/docs/slugs/relativeSlug", "title": "relativeSlug", }, "prev": { "permalink": "/docs/rootTryToEscapeSlug", "title": "rootTryToEscapeSlug", }, }, { "id": "slugs/relativeSlug", "next": { "permalink": "/docs/slugs/hey/resolvedSlug", "title": "resolvedSlug", }, "prev": { "permalink": "/docs/absoluteSlug", "title": "absoluteSlug", }, }, { "id": "slugs/resolvedSlug", "next": { "permalink": "/docs/tryToEscapeSlug", "title": "tryToEscapeSlug", }, "prev": { "permalink": "/docs/slugs/relativeSlug", "title": "relativeSlug", }, }, { "id": "slugs/tryToEscapeSlug", "next": undefined, "prev": { "permalink": "/docs/slugs/hey/resolvedSlug", "title": "resolvedSlug", }, }, { "id": "unlisted-category/unlisted-category-doc", "next": undefined, "prev": undefined, }, { "id": "unlisted-category/unlisted-category-index", "next": undefined, "prev": undefined, }, ], "sidebars": { "defaultSidebar": [ { "id": "customLastUpdate", "type": "doc", }, { "id": "doc with space", "type": "doc", }, { "id": "doc-draft", "type": "doc", }, { "id": "doc-unlisted", "type": "doc", }, { "collapsed": false, "collapsible": true, "items": [ { "id": "foo/bar", "type": "doc", }, { "id": "foo/baz", "type": "doc", }, ], "label": "foo", "link": undefined, "type": "category", }, { "id": "headingAsTitle", "type": "doc", }, { "id": "hello", "label": "Hello sidebar_label", "type": "doc", }, { "id": "ipsum", "type": "doc", }, { "id": "lastUpdateAuthorOnly", "type": "doc", }, { "id": "lastUpdateDateOnly", "type": "doc", }, { "id": "lorem", "type": "doc", }, { "id": "rootAbsoluteSlug", "type": "doc", }, { "id": "rootRelativeSlug", "type": "doc", }, { "id": "rootResolvedSlug", "type": "doc", }, { "id": "rootTryToEscapeSlug", "type": "doc", }, { "collapsed": false, "collapsible": true, "items": [ { "id": "slugs/absoluteSlug", "type": "doc", }, { "id": "slugs/relativeSlug", "type": "doc", }, { "id": "slugs/resolvedSlug", "type": "doc", }, { "id": "slugs/tryToEscapeSlug", "type": "doc", }, ], "label": "slugs", "link": undefined, "type": "category", }, { "collapsed": false, "collapsible": true, "items": [ { "id": "unlisted-category/unlisted-category-doc", "type": "doc", }, ], "label": "unlisted-category-index", "link": { "id": "unlisted-category/unlisted-category-index", "type": "doc", }, "type": "category", }, ], }, } `;
1,245
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/globalData.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`toGlobalDataVersion generates the right docs, sidebars, and metadata 1`] = ` { "docs": [ { "id": "main", "path": "/current/main", "sidebar": "tutorial", }, { "id": "doc", "path": "/current/doc", "sidebar": "tutorial", }, { "id": "docNoSidebarUnlisted", "path": "/current/docNoSidebarUnlisted", "sidebar": undefined, "unlisted": true, }, { "id": "/current/generated", "path": "/current/generated", "sidebar": "tutorial", }, { "id": "/current/generated-2", "path": "/current/generated-2", "sidebar": "another", }, ], "draftIds": [ "some-draft-id", ], "isLast": true, "label": "Label", "mainDocId": "main", "name": "current", "path": "/current", "sidebars": { "another": { "link": { "label": "Generated", "path": "/current/generated-2", }, }, "links": {}, "tutorial": { "link": { "label": "main", "path": "/current/main", }, }, }, } `;
1,246
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/index.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`sidebar site with undefined sidebar 1`] = ` { "defaultSidebar": [ { "id": "hello-1", "type": "doc", }, { "id": "hello-2", "label": "Hello 2 From Doc", "type": "doc", }, ], } `; exports[`sidebar site with wrong sidebar content 1`] = ` "Invalid sidebar file at "packages/docusaurus-plugin-content-docs/src/__tests__/__fixtures__/simple-site/wrong-sidebars.json". These sidebar document ids do not exist: - nonExistent Available document ids are: - customLastUpdate - doc with space - doc-draft - doc-unlisted - foo/bar - foo/baz - headingAsTitle - hello - ipsum - lastUpdateAuthorOnly - lastUpdateDateOnly - lorem - rootAbsoluteSlug - rootRelativeSlug - rootResolvedSlug - rootTryToEscapeSlug - slugs/absoluteSlug - slugs/relativeSlug - slugs/resolvedSlug - slugs/tryToEscapeSlug - unlisted-category/unlisted-category-doc - unlisted-category/unlisted-category-index " `; exports[`simple website content 1`] = ` { "description": "Images", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "id": "baz", "pagination_label": "baz pagination_label", "slug": "bazSlug.html", "tags": [ "tag 1", "tag-1", { "label": "tag 2", "permalink": "tag2-custom-permalink", }, ], "title": "baz", }, "id": "foo/baz", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/unlisted-category/", "title": "unlisted-category-index", }, "permalink": "/docs/foo/bazSlug.html", "previous": { "permalink": "/docs/doc-unlisted", "title": "doc-unlisted", }, "sidebar": "docs", "sidebarPosition": undefined, "slug": "/foo/bazSlug.html", "source": "@site/docs/foo/baz.md", "sourceDirName": "foo", "tags": [ { "label": "tag 1", "permalink": "/docs/tags/tag-1", }, { "label": "tag 2", "permalink": "/docs/tags/tag2-custom-permalink", }, ], "title": "baz", "unlisted": false, "version": "current", } `; exports[`simple website content 2`] = ` { "description": "Hi, Endilie here :)", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "id": "hello", "sidebar_label": "Hello sidebar_label", "slug": "/", "tags": [ "tag-1", "tag 3", ], "title": "Hello, World !", }, "id": "hello", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": undefined, "permalink": "/docs/", "previous": { "permalink": "/docs/headingAsTitle", "title": "My heading as title", }, "sidebar": "docs", "sidebarPosition": undefined, "slug": "/", "source": "@site/docs/hello.md", "sourceDirName": ".", "tags": [ { "label": "tag-1", "permalink": "/docs/tags/tag-1", }, { "label": "tag 3", "permalink": "/docs/tags/tag-3", }, ], "title": "Hello, World !", "unlisted": false, "version": "current", } `; exports[`simple website content 3`] = ` { "description": "This is custom description", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "description": "This is custom description", "id": "bar", "pagination_next": null, "pagination_prev": null, "title": "Bar", }, "id": "foo/bar", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": undefined, "permalink": "/docs/foo/bar", "previous": undefined, "sidebar": "docs", "sidebarPosition": undefined, "slug": "/foo/bar", "source": "@site/docs/foo/bar.md", "sourceDirName": "foo", "tags": [], "title": "Bar", "unlisted": false, "version": "current", } `; exports[`simple website content 4`] = ` { "docs": [ { "collapsed": true, "collapsible": true, "items": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "foo/bar", "type": "doc", }, { "id": "doc-unlisted", "type": "doc", }, { "id": "foo/baz", "type": "doc", }, ], "label": "foo", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "unlisted-category/unlisted-category-doc", "type": "doc", }, ], "label": "Unlisted category", "link": { "id": "unlisted-category/unlisted-category-index", "type": "doc", }, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "rootAbsoluteSlug", "type": "doc", }, { "id": "rootRelativeSlug", "type": "doc", }, { "id": "rootResolvedSlug", "type": "doc", }, { "id": "rootTryToEscapeSlug", "type": "doc", }, ], "label": "Slugs", "link": { "permalink": "/docs/category/slugs", "slug": "/category/slugs", "type": "generated-index", }, "type": "category", }, { "id": "headingAsTitle", "type": "doc", }, { "href": "https://github.com", "label": "GitHub", "type": "link", }, { "id": "hello", "type": "ref", }, ], "label": "Test", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "hello", "type": "doc", }, ], "label": "Guides", "link": undefined, "type": "category", }, ], } `; exports[`simple website content 5`] = ` { "pluginName": { "pluginId": { "breadcrumbs": true, "path": "/docs", "versions": [ { "docs": [ { "id": "customLastUpdate", "path": "/docs/customLastUpdate", "sidebar": undefined, }, { "id": "doc with space", "path": "/docs/doc with space", "sidebar": undefined, }, { "id": "doc-draft", "path": "/docs/doc-draft", "sidebar": undefined, }, { "id": "doc-unlisted", "path": "/docs/doc-unlisted", "sidebar": "docs", }, { "id": "foo/bar", "path": "/docs/foo/bar", "sidebar": "docs", }, { "id": "foo/baz", "path": "/docs/foo/bazSlug.html", "sidebar": "docs", }, { "id": "headingAsTitle", "path": "/docs/headingAsTitle", "sidebar": "docs", }, { "id": "hello", "path": "/docs/", "sidebar": "docs", }, { "id": "ipsum", "path": "/docs/ipsum", "sidebar": undefined, }, { "id": "lastUpdateAuthorOnly", "path": "/docs/lastUpdateAuthorOnly", "sidebar": undefined, }, { "id": "lastUpdateDateOnly", "path": "/docs/lastUpdateDateOnly", "sidebar": undefined, }, { "id": "lorem", "path": "/docs/lorem", "sidebar": undefined, }, { "id": "rootAbsoluteSlug", "path": "/docs/rootAbsoluteSlug", "sidebar": "docs", }, { "id": "rootRelativeSlug", "path": "/docs/rootRelativeSlug", "sidebar": "docs", }, { "id": "rootResolvedSlug", "path": "/docs/hey/rootResolvedSlug", "sidebar": "docs", }, { "id": "rootTryToEscapeSlug", "path": "/docs/rootTryToEscapeSlug", "sidebar": "docs", }, { "id": "slugs/absoluteSlug", "path": "/docs/absoluteSlug", "sidebar": undefined, }, { "id": "slugs/relativeSlug", "path": "/docs/slugs/relativeSlug", "sidebar": undefined, }, { "id": "slugs/resolvedSlug", "path": "/docs/slugs/hey/resolvedSlug", "sidebar": undefined, }, { "id": "slugs/tryToEscapeSlug", "path": "/docs/tryToEscapeSlug", "sidebar": undefined, }, { "id": "unlisted-category/unlisted-category-doc", "path": "/docs/unlisted-category/unlisted-category-doc", "sidebar": "docs", }, { "id": "unlisted-category/unlisted-category-index", "path": "/docs/unlisted-category/", "sidebar": "docs", }, { "id": "/category/slugs", "path": "/docs/category/slugs", "sidebar": "docs", }, ], "draftIds": [], "isLast": true, "label": "Next", "mainDocId": "hello", "name": "current", "path": "/docs", "sidebars": { "docs": { "link": { "label": "foo/bar", "path": "/docs/foo/bar", }, }, }, }, ], }, }, } `; exports[`simple website content: data 1`] = ` { "category-docs-docs-category-slugs-0fe.json": "{ "title": "Slugs", "slug": "/category/slugs", "permalink": "/docs/category/slugs", "navigation": { "previous": { "title": "unlisted-category-doc", "permalink": "/docs/unlisted-category/unlisted-category-doc" }, "next": { "title": "rootAbsoluteSlug", "permalink": "/docs/rootAbsoluteSlug" } } }", "site-docs-custom-last-update-md-b8d.json": "{ "id": "customLastUpdate", "title": "Custom Last Update", "description": "Custom last update", "source": "@site/docs/customLastUpdate.md", "sourceDirName": ".", "slug": "/customLastUpdate", "permalink": "/docs/customLastUpdate", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "title": "Custom Last Update", "last_update": { "author": "Custom Author", "date": "1/1/2000" } } }", "site-docs-doc-draft-md-584.json": "{ "id": "doc-draft", "title": "doc-draft", "description": "This is a draft document", "source": "@site/docs/doc-draft.md", "sourceDirName": ".", "slug": "/doc-draft", "permalink": "/docs/doc-draft", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "draft": true } }", "site-docs-doc-unlisted-md-80b.json": "{ "id": "doc-unlisted", "title": "doc-unlisted", "description": "This is an unlisted document", "source": "@site/docs/doc-unlisted.md", "sourceDirName": ".", "slug": "/doc-unlisted", "permalink": "/docs/doc-unlisted", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "unlisted": true }, "sidebar": "docs", "previous": { "title": "Bar", "permalink": "/docs/foo/bar" }, "next": { "title": "baz pagination_label", "permalink": "/docs/foo/bazSlug.html" } }", "site-docs-doc-with-space-md-e90.json": "{ "id": "doc with space", "title": "Hoo hoo, if this path tricks you...", "description": "", "source": "@site/docs/doc with space.md", "sourceDirName": ".", "slug": "/doc with space", "permalink": "/docs/doc with space", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": {} }", "site-docs-foo-bar-md-8c2.json": "{ "id": "foo/bar", "title": "Bar", "description": "This is custom description", "source": "@site/docs/foo/bar.md", "sourceDirName": "foo", "slug": "/foo/bar", "permalink": "/docs/foo/bar", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "id": "bar", "title": "Bar", "description": "This is custom description", "pagination_next": null, "pagination_prev": null }, "sidebar": "docs" }", "site-docs-foo-baz-md-a69.json": "{ "id": "foo/baz", "title": "baz", "description": "Images", "source": "@site/docs/foo/baz.md", "sourceDirName": "foo", "slug": "/foo/bazSlug.html", "permalink": "/docs/foo/bazSlug.html", "draft": false, "unlisted": false, "tags": [ { "label": "tag 1", "permalink": "/docs/tags/tag-1" }, { "label": "tag 2", "permalink": "/docs/tags/tag2-custom-permalink" } ], "version": "current", "frontMatter": { "id": "baz", "title": "baz", "slug": "bazSlug.html", "pagination_label": "baz pagination_label", "tags": [ "tag 1", "tag-1", { "label": "tag 2", "permalink": "tag2-custom-permalink" } ] }, "sidebar": "docs", "previous": { "title": "doc-unlisted", "permalink": "/docs/doc-unlisted" }, "next": { "title": "unlisted-category-index", "permalink": "/docs/unlisted-category/" } }", "site-docs-heading-as-title-md-c6d.json": "{ "id": "headingAsTitle", "title": "My heading as title", "description": "", "source": "@site/docs/headingAsTitle.md", "sourceDirName": ".", "slug": "/headingAsTitle", "permalink": "/docs/headingAsTitle", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": {}, "sidebar": "docs", "previous": { "title": "rootTryToEscapeSlug", "permalink": "/docs/rootTryToEscapeSlug" }, "next": { "title": "Hello sidebar_label", "permalink": "/docs/" } }", "site-docs-hello-md-9df.json": "{ "id": "hello", "title": "Hello, World !", "description": "Hi, Endilie here :)", "source": "@site/docs/hello.md", "sourceDirName": ".", "slug": "/", "permalink": "/docs/", "draft": false, "unlisted": false, "tags": [ { "label": "tag-1", "permalink": "/docs/tags/tag-1" }, { "label": "tag 3", "permalink": "/docs/tags/tag-3" } ], "version": "current", "frontMatter": { "id": "hello", "title": "Hello, World !", "sidebar_label": "Hello sidebar_label", "tags": [ "tag-1", "tag 3" ], "slug": "/" }, "sidebar": "docs", "previous": { "title": "My heading as title", "permalink": "/docs/headingAsTitle" } }", "site-docs-ipsum-md-c61.json": "{ "id": "ipsum", "title": "ipsum", "description": "Lorem ipsum.", "source": "@site/docs/ipsum.md", "sourceDirName": ".", "slug": "/ipsum", "permalink": "/docs/ipsum", "draft": false, "unlisted": false, "editUrl": null, "tags": [], "version": "current", "frontMatter": { "custom_edit_url": null, "pagination_next": "doc-unlisted" }, "next": { "title": "doc-unlisted", "permalink": "/docs/doc-unlisted" } }", "site-docs-last-update-author-only-md-352.json": "{ "id": "lastUpdateAuthorOnly", "title": "Last Update Author Only", "description": "Only custom author, so it will still use the date from Git", "source": "@site/docs/lastUpdateAuthorOnly.md", "sourceDirName": ".", "slug": "/lastUpdateAuthorOnly", "permalink": "/docs/lastUpdateAuthorOnly", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "title": "Last Update Author Only", "last_update": { "author": "Custom Author" } } }", "site-docs-last-update-date-only-md-987.json": "{ "id": "lastUpdateDateOnly", "title": "Last Update Date Only", "description": "Only custom date, so it will still use the author from Git", "source": "@site/docs/lastUpdateDateOnly.md", "sourceDirName": ".", "slug": "/lastUpdateDateOnly", "permalink": "/docs/lastUpdateDateOnly", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "title": "Last Update Date Only", "last_update": { "date": "1/1/2000" } } }", "site-docs-lorem-md-b27.json": "{ "id": "lorem", "title": "lorem", "description": "Lorem ipsum.", "source": "@site/docs/lorem.md", "sourceDirName": ".", "slug": "/lorem", "permalink": "/docs/lorem", "draft": false, "unlisted": false, "editUrl": "https://github.com/customUrl/docs/lorem.md", "tags": [], "version": "current", "frontMatter": { "custom_edit_url": "https://github.com/customUrl/docs/lorem.md", "unrelated_front_matter": "won't be part of metadata" } }", "site-docs-root-absolute-slug-md-db5.json": "{ "id": "rootAbsoluteSlug", "title": "rootAbsoluteSlug", "description": "Lorem", "source": "@site/docs/rootAbsoluteSlug.md", "sourceDirName": ".", "slug": "/rootAbsoluteSlug", "permalink": "/docs/rootAbsoluteSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "/rootAbsoluteSlug", "pagination_next": "headingAsTitle", "pagination_prev": "foo/baz" }, "sidebar": "docs", "previous": { "title": "baz pagination_label", "permalink": "/docs/foo/bazSlug.html" }, "next": { "title": "My heading as title", "permalink": "/docs/headingAsTitle" } }", "site-docs-root-relative-slug-md-3dd.json": "{ "id": "rootRelativeSlug", "title": "rootRelativeSlug", "description": "Lorem", "source": "@site/docs/rootRelativeSlug.md", "sourceDirName": ".", "slug": "/rootRelativeSlug", "permalink": "/docs/rootRelativeSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "rootRelativeSlug", "pagination_next": "headingAsTitle", "pagination_prev": "foo/baz" }, "sidebar": "docs", "previous": { "title": "baz pagination_label", "permalink": "/docs/foo/bazSlug.html" }, "next": { "title": "My heading as title", "permalink": "/docs/headingAsTitle" } }", "site-docs-root-resolved-slug-md-4d1.json": "{ "id": "rootResolvedSlug", "title": "rootResolvedSlug", "description": "Lorem", "source": "@site/docs/rootResolvedSlug.md", "sourceDirName": ".", "slug": "/hey/rootResolvedSlug", "permalink": "/docs/hey/rootResolvedSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "./hey/ho/../rootResolvedSlug", "pagination_next": "headingAsTitle", "pagination_prev": "foo/baz" }, "sidebar": "docs", "previous": { "title": "baz pagination_label", "permalink": "/docs/foo/bazSlug.html" }, "next": { "title": "My heading as title", "permalink": "/docs/headingAsTitle" } }", "site-docs-root-try-to-escape-slug-md-9ee.json": "{ "id": "rootTryToEscapeSlug", "title": "rootTryToEscapeSlug", "description": "Lorem", "source": "@site/docs/rootTryToEscapeSlug.md", "sourceDirName": ".", "slug": "/rootTryToEscapeSlug", "permalink": "/docs/rootTryToEscapeSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "../../../../../../../../rootTryToEscapeSlug", "pagination_next": "headingAsTitle", "pagination_prev": "foo/baz" }, "sidebar": "docs", "previous": { "title": "baz pagination_label", "permalink": "/docs/foo/bazSlug.html" }, "next": { "title": "My heading as title", "permalink": "/docs/headingAsTitle" } }", "site-docs-slugs-absolute-slug-md-4e8.json": "{ "id": "slugs/absoluteSlug", "title": "absoluteSlug", "description": "Lorem", "source": "@site/docs/slugs/absoluteSlug.md", "sourceDirName": "slugs", "slug": "/absoluteSlug", "permalink": "/docs/absoluteSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "/absoluteSlug" } }", "site-docs-slugs-relative-slug-md-d1c.json": "{ "id": "slugs/relativeSlug", "title": "relativeSlug", "description": "Lorem", "source": "@site/docs/slugs/relativeSlug.md", "sourceDirName": "slugs", "slug": "/slugs/relativeSlug", "permalink": "/docs/slugs/relativeSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "relativeSlug" } }", "site-docs-slugs-resolved-slug-md-02b.json": "{ "id": "slugs/resolvedSlug", "title": "resolvedSlug", "description": "Lorem", "source": "@site/docs/slugs/resolvedSlug.md", "sourceDirName": "slugs", "slug": "/slugs/hey/resolvedSlug", "permalink": "/docs/slugs/hey/resolvedSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "./hey/ho/../resolvedSlug" } }", "site-docs-slugs-try-to-escape-slug-md-70d.json": "{ "id": "slugs/tryToEscapeSlug", "title": "tryToEscapeSlug", "description": "Lorem", "source": "@site/docs/slugs/tryToEscapeSlug.md", "sourceDirName": "slugs", "slug": "/tryToEscapeSlug", "permalink": "/docs/tryToEscapeSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "../../../../../../../../tryToEscapeSlug" } }", "site-docs-unlisted-category-index-md-efa.json": "{ "id": "unlisted-category/unlisted-category-index", "title": "unlisted-category-index", "description": "This is an unlisted category index", "source": "@site/docs/unlisted-category/index.md", "sourceDirName": "unlisted-category", "slug": "/unlisted-category/", "permalink": "/docs/unlisted-category/", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "id": "unlisted-category-index", "unlisted": true }, "sidebar": "docs", "previous": { "title": "baz pagination_label", "permalink": "/docs/foo/bazSlug.html" }, "next": { "title": "unlisted-category-doc", "permalink": "/docs/unlisted-category/unlisted-category-doc" } }", "site-docs-unlisted-category-unlisted-category-doc-md-bd6.json": "{ "id": "unlisted-category/unlisted-category-doc", "title": "unlisted-category-doc", "description": "This is an unlisted category doc", "source": "@site/docs/unlisted-category/unlisted-category-doc.md", "sourceDirName": "unlisted-category", "slug": "/unlisted-category/unlisted-category-doc", "permalink": "/docs/unlisted-category/unlisted-category-doc", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "id": "unlisted-category-doc", "unlisted": true }, "sidebar": "docs", "previous": { "title": "unlisted-category-index", "permalink": "/docs/unlisted-category/" }, "next": { "title": "Slugs", "permalink": "/docs/category/slugs" } }", "tag-docs-tags-tag-1-b3f.json": "{ "label": "tag 1", "permalink": "/docs/tags/tag-1", "allTagsPath": "/docs/tags", "count": 2, "items": [ { "id": "foo/baz", "title": "baz", "description": "Images", "permalink": "/docs/foo/bazSlug.html" }, { "id": "hello", "title": "Hello, World !", "description": "Hi, Endilie here :)", "permalink": "/docs/" } ], "unlisted": false }", "tag-docs-tags-tag-2-custom-permalink-825.json": "{ "label": "tag 2", "permalink": "/docs/tags/tag2-custom-permalink", "allTagsPath": "/docs/tags", "count": 1, "items": [ { "id": "foo/baz", "title": "baz", "description": "Images", "permalink": "/docs/foo/bazSlug.html" } ], "unlisted": false }", "tag-docs-tags-tag-3-ab5.json": "{ "label": "tag 3", "permalink": "/docs/tags/tag-3", "allTagsPath": "/docs/tags", "count": 1, "items": [ { "id": "hello", "title": "Hello, World !", "description": "Hi, Endilie here :)", "permalink": "/docs/" } ], "unlisted": false }", "tags-list-current-prop-15a.json": "[ { "label": "tag 1", "permalink": "/docs/tags/tag-1", "count": 2 }, { "label": "tag 2", "permalink": "/docs/tags/tag2-custom-permalink", "count": 1 }, { "label": "tag 3", "permalink": "/docs/tags/tag-3", "count": 1 } ]", "version-current-metadata-prop-751.json": "{ "pluginId": "default", "version": "current", "label": "Next", "banner": null, "badge": false, "noIndex": false, "className": "docs-version-current", "isLast": true, "docsSidebars": { "docs": [ { "type": "category", "label": "Test", "items": [ { "type": "category", "label": "foo", "items": [ { "type": "link", "label": "Bar", "href": "/docs/foo/bar", "docId": "foo/bar", "unlisted": false }, { "type": "link", "label": "doc-unlisted", "href": "/docs/doc-unlisted", "docId": "doc-unlisted", "unlisted": false }, { "type": "link", "label": "baz", "href": "/docs/foo/bazSlug.html", "docId": "foo/baz", "unlisted": false } ], "collapsed": true, "collapsible": true }, { "type": "category", "label": "Unlisted category", "items": [ { "type": "link", "label": "unlisted-category-doc", "href": "/docs/unlisted-category/unlisted-category-doc", "docId": "unlisted-category/unlisted-category-doc", "unlisted": false } ], "collapsed": true, "collapsible": true, "href": "/docs/unlisted-category/" }, { "type": "category", "label": "Slugs", "items": [ { "type": "link", "label": "rootAbsoluteSlug", "href": "/docs/rootAbsoluteSlug", "docId": "rootAbsoluteSlug", "unlisted": false }, { "type": "link", "label": "rootRelativeSlug", "href": "/docs/rootRelativeSlug", "docId": "rootRelativeSlug", "unlisted": false }, { "type": "link", "label": "rootResolvedSlug", "href": "/docs/hey/rootResolvedSlug", "docId": "rootResolvedSlug", "unlisted": false }, { "type": "link", "label": "rootTryToEscapeSlug", "href": "/docs/rootTryToEscapeSlug", "docId": "rootTryToEscapeSlug", "unlisted": false } ], "collapsed": true, "collapsible": true, "href": "/docs/category/slugs" }, { "type": "link", "label": "My heading as title", "href": "/docs/headingAsTitle", "docId": "headingAsTitle", "unlisted": false }, { "type": "link", "label": "GitHub", "href": "https://github.com" }, { "type": "link", "label": "Hello sidebar_label", "href": "/docs/", "docId": "hello", "unlisted": false } ], "collapsed": true, "collapsible": true }, { "type": "category", "label": "Guides", "items": [ { "type": "link", "label": "Hello sidebar_label", "href": "/docs/", "docId": "hello", "unlisted": false } ], "collapsed": true, "collapsible": true } ] }, "docs": { "customLastUpdate": { "id": "customLastUpdate", "title": "Custom Last Update", "description": "Custom last update" }, "doc with space": { "id": "doc with space", "title": "Hoo hoo, if this path tricks you...", "description": "" }, "doc-draft": { "id": "doc-draft", "title": "doc-draft", "description": "This is a draft document" }, "doc-unlisted": { "id": "doc-unlisted", "title": "doc-unlisted", "description": "This is an unlisted document", "sidebar": "docs" }, "foo/bar": { "id": "foo/bar", "title": "Bar", "description": "This is custom description", "sidebar": "docs" }, "foo/baz": { "id": "foo/baz", "title": "baz", "description": "Images", "sidebar": "docs" }, "headingAsTitle": { "id": "headingAsTitle", "title": "My heading as title", "description": "", "sidebar": "docs" }, "hello": { "id": "hello", "title": "Hello, World !", "description": "Hi, Endilie here :)", "sidebar": "docs" }, "ipsum": { "id": "ipsum", "title": "ipsum", "description": "Lorem ipsum." }, "lastUpdateAuthorOnly": { "id": "lastUpdateAuthorOnly", "title": "Last Update Author Only", "description": "Only custom author, so it will still use the date from Git" }, "lastUpdateDateOnly": { "id": "lastUpdateDateOnly", "title": "Last Update Date Only", "description": "Only custom date, so it will still use the author from Git" }, "lorem": { "id": "lorem", "title": "lorem", "description": "Lorem ipsum." }, "rootAbsoluteSlug": { "id": "rootAbsoluteSlug", "title": "rootAbsoluteSlug", "description": "Lorem", "sidebar": "docs" }, "rootRelativeSlug": { "id": "rootRelativeSlug", "title": "rootRelativeSlug", "description": "Lorem", "sidebar": "docs" }, "rootResolvedSlug": { "id": "rootResolvedSlug", "title": "rootResolvedSlug", "description": "Lorem", "sidebar": "docs" }, "rootTryToEscapeSlug": { "id": "rootTryToEscapeSlug", "title": "rootTryToEscapeSlug", "description": "Lorem", "sidebar": "docs" }, "slugs/absoluteSlug": { "id": "slugs/absoluteSlug", "title": "absoluteSlug", "description": "Lorem" }, "slugs/relativeSlug": { "id": "slugs/relativeSlug", "title": "relativeSlug", "description": "Lorem" }, "slugs/resolvedSlug": { "id": "slugs/resolvedSlug", "title": "resolvedSlug", "description": "Lorem" }, "slugs/tryToEscapeSlug": { "id": "slugs/tryToEscapeSlug", "title": "tryToEscapeSlug", "description": "Lorem" }, "unlisted-category/unlisted-category-doc": { "id": "unlisted-category/unlisted-category-doc", "title": "unlisted-category-doc", "description": "This is an unlisted category doc", "sidebar": "docs" }, "unlisted-category/unlisted-category-index": { "id": "unlisted-category/unlisted-category-index", "title": "unlisted-category-index", "description": "This is an unlisted category index", "sidebar": "docs" } } }", } `; exports[`simple website content: global data 1`] = ` { "pluginName": { "pluginId": { "breadcrumbs": true, "path": "/docs", "versions": [ { "docs": [ { "id": "customLastUpdate", "path": "/docs/customLastUpdate", "sidebar": undefined, }, { "id": "doc with space", "path": "/docs/doc with space", "sidebar": undefined, }, { "id": "doc-draft", "path": "/docs/doc-draft", "sidebar": undefined, }, { "id": "doc-unlisted", "path": "/docs/doc-unlisted", "sidebar": "docs", }, { "id": "foo/bar", "path": "/docs/foo/bar", "sidebar": "docs", }, { "id": "foo/baz", "path": "/docs/foo/bazSlug.html", "sidebar": "docs", }, { "id": "headingAsTitle", "path": "/docs/headingAsTitle", "sidebar": "docs", }, { "id": "hello", "path": "/docs/", "sidebar": "docs", }, { "id": "ipsum", "path": "/docs/ipsum", "sidebar": undefined, }, { "id": "lastUpdateAuthorOnly", "path": "/docs/lastUpdateAuthorOnly", "sidebar": undefined, }, { "id": "lastUpdateDateOnly", "path": "/docs/lastUpdateDateOnly", "sidebar": undefined, }, { "id": "lorem", "path": "/docs/lorem", "sidebar": undefined, }, { "id": "rootAbsoluteSlug", "path": "/docs/rootAbsoluteSlug", "sidebar": "docs", }, { "id": "rootRelativeSlug", "path": "/docs/rootRelativeSlug", "sidebar": "docs", }, { "id": "rootResolvedSlug", "path": "/docs/hey/rootResolvedSlug", "sidebar": "docs", }, { "id": "rootTryToEscapeSlug", "path": "/docs/rootTryToEscapeSlug", "sidebar": "docs", }, { "id": "slugs/absoluteSlug", "path": "/docs/absoluteSlug", "sidebar": undefined, }, { "id": "slugs/relativeSlug", "path": "/docs/slugs/relativeSlug", "sidebar": undefined, }, { "id": "slugs/resolvedSlug", "path": "/docs/slugs/hey/resolvedSlug", "sidebar": undefined, }, { "id": "slugs/tryToEscapeSlug", "path": "/docs/tryToEscapeSlug", "sidebar": undefined, }, { "id": "unlisted-category/unlisted-category-doc", "path": "/docs/unlisted-category/unlisted-category-doc", "sidebar": "docs", }, { "id": "unlisted-category/unlisted-category-index", "path": "/docs/unlisted-category/", "sidebar": "docs", }, { "id": "/category/slugs", "path": "/docs/category/slugs", "sidebar": "docs", }, ], "draftIds": [], "isLast": true, "label": "Next", "mainDocId": "hello", "name": "current", "path": "/docs", "sidebars": { "docs": { "link": { "label": "foo/bar", "path": "/docs/foo/bar", }, }, }, }, ], }, }, } `; exports[`simple website content: route config 1`] = ` [ { "component": "@theme/DocsRoot", "exact": false, "path": "/docs", "routes": [ { "component": "@theme/DocVersionRoot", "exact": false, "modules": { "version": "~docs/version-current-metadata-prop-751.json", }, "path": "/docs", "priority": -1, "routes": [ { "component": "@theme/DocTagsListPage", "exact": true, "modules": { "tags": "~docs/tags-list-current-prop-15a.json", }, "path": "/docs/tags", }, { "component": "@theme/DocTagDocListPage", "exact": true, "modules": { "tag": "~docs/tag-docs-tags-tag-1-b3f.json", }, "path": "/docs/tags/tag-1", }, { "component": "@theme/DocTagDocListPage", "exact": true, "modules": { "tag": "~docs/tag-docs-tags-tag-3-ab5.json", }, "path": "/docs/tags/tag-3", }, { "component": "@theme/DocTagDocListPage", "exact": true, "modules": { "tag": "~docs/tag-docs-tags-tag-2-custom-permalink-825.json", }, "path": "/docs/tags/tag2-custom-permalink", }, { "component": "@theme/DocRoot", "exact": false, "path": "/docs", "routes": [ { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/hello.md", }, "path": "/docs/", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/slugs/absoluteSlug.md", }, "path": "/docs/absoluteSlug", }, { "component": "@theme/DocCategoryGeneratedIndexPage", "exact": true, "modules": { "categoryGeneratedIndex": "~docs/category-docs-docs-category-slugs-0fe.json", }, "path": "/docs/category/slugs", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/customLastUpdate.md", }, "path": "/docs/customLastUpdate", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/doc with space.md", }, "path": "/docs/doc with space", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/doc-draft.md", }, "path": "/docs/doc-draft", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/doc-unlisted.md", }, "path": "/docs/doc-unlisted", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/foo/bar.md", }, "path": "/docs/foo/bar", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/foo/baz.md", }, "path": "/docs/foo/bazSlug.html", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/headingAsTitle.md", }, "path": "/docs/headingAsTitle", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/rootResolvedSlug.md", }, "path": "/docs/hey/rootResolvedSlug", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/ipsum.md", }, "path": "/docs/ipsum", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/lastUpdateAuthorOnly.md", }, "path": "/docs/lastUpdateAuthorOnly", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/lastUpdateDateOnly.md", }, "path": "/docs/lastUpdateDateOnly", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/lorem.md", }, "path": "/docs/lorem", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/rootAbsoluteSlug.md", }, "path": "/docs/rootAbsoluteSlug", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/rootRelativeSlug.md", }, "path": "/docs/rootRelativeSlug", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/rootTryToEscapeSlug.md", }, "path": "/docs/rootTryToEscapeSlug", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/slugs/resolvedSlug.md", }, "path": "/docs/slugs/hey/resolvedSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/slugs/relativeSlug.md", }, "path": "/docs/slugs/relativeSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/slugs/tryToEscapeSlug.md", }, "path": "/docs/tryToEscapeSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/unlisted-category/index.md", }, "path": "/docs/unlisted-category/", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/unlisted-category/unlisted-category-doc.md", }, "path": "/docs/unlisted-category/unlisted-category-doc", "sidebar": "docs", }, ], }, ], }, ], }, ] `; exports[`simple website getPathToWatch 1`] = ` [ "sidebars.json", "i18n/en/docusaurus-plugin-content-docs/current/**/*.{md,mdx}", "docs/**/*.{md,mdx}", "docs/**/_category_.{json,yml,yaml}", ] `; exports[`site with custom sidebar items generator sidebar is autogenerated according to a custom sidebarItemsGenerator 1`] = ` { "defaultSidebar": [ { "id": "API/api-overview", "type": "doc", }, { "id": "API/api-end", "type": "doc", }, ], } `; exports[`site with custom sidebar items generator sidebarItemsGenerator can wrap/enhance/sort/reverse the default sidebar generator 1`] = ` { "defaultSidebar": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "API/api-end", "type": "doc", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "API/Extension APIs/Theme API", "type": "doc", }, { "id": "API/Extension APIs/Plugin API", "type": "doc", }, ], "label": "Extension APIs (label from _category_.yml)", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "API/Core APIs/Server API", "type": "doc", }, { "id": "API/Core APIs/Client API", "type": "doc", }, ], "label": "Core APIs", "link": undefined, "type": "category", }, { "id": "API/api-overview", "type": "doc", }, ], "label": "API (label from _category_.json)", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "Guides/guide5", "type": "doc", }, { "id": "Guides/guide4", "type": "doc", }, { "id": "Guides/guide3", "type": "doc", }, { "id": "Guides/guide2.5", "type": "doc", }, { "id": "Guides/guide2", "type": "doc", }, { "id": "Guides/guide1", "type": "doc", }, ], "label": "Guides", "link": undefined, "type": "category", }, { "id": "installation", "type": "doc", }, { "id": "getting-started", "type": "doc", }, ], } `; exports[`site with custom sidebar items generator sidebarItemsGenerator is called with appropriate data 1`] = ` { "categoriesMetadata": { "3-API": { "label": "API (label from _category_.json)", }, "3-API/02_Extension APIs": { "label": "Extension APIs (label from _category_.yml)", }, "Guides": { "position": 2, }, }, "defaultSidebarItemsGenerator": [Function], "docs": [ { "frontMatter": {}, "id": "API/Core APIs/Client API", "sidebarPosition": 0, "source": "@site/docs/3-API/01_Core APIs/0 --- Client API.md", "sourceDirName": "3-API/01_Core APIs", "title": "Client API", }, { "frontMatter": {}, "id": "API/Core APIs/Server API", "sidebarPosition": 1, "source": "@site/docs/3-API/01_Core APIs/1 --- Server API.md", "sourceDirName": "3-API/01_Core APIs", "title": "Server API", }, { "frontMatter": {}, "id": "API/Extension APIs/Plugin API", "sidebarPosition": 0, "source": "@site/docs/3-API/02_Extension APIs/0. Plugin API.md", "sourceDirName": "3-API/02_Extension APIs", "title": "Plugin API", }, { "frontMatter": {}, "id": "API/Extension APIs/Theme API", "sidebarPosition": 1, "source": "@site/docs/3-API/02_Extension APIs/1. Theme API.md", "sourceDirName": "3-API/02_Extension APIs", "title": "Theme API", }, { "frontMatter": {}, "id": "API/api-end", "sidebarPosition": 3, "source": "@site/docs/3-API/03_api-end.md", "sourceDirName": "3-API", "title": "API End", }, { "frontMatter": {}, "id": "API/api-overview", "sidebarPosition": 0, "source": "@site/docs/3-API/00_api-overview.md", "sourceDirName": "3-API", "title": "API Overview", }, { "frontMatter": { "id": "guide1", "sidebar_position": 1, }, "id": "Guides/guide1", "sidebarPosition": 1, "source": "@site/docs/Guides/z-guide1.md", "sourceDirName": "Guides", "title": "Guide 1", }, { "frontMatter": { "id": "guide2", }, "id": "Guides/guide2", "sidebarPosition": 2, "source": "@site/docs/Guides/02-guide2.md", "sourceDirName": "Guides", "title": "Guide 2", }, { "frontMatter": { "id": "guide2.5", "sidebar_position": 2.5, }, "id": "Guides/guide2.5", "sidebarPosition": 2.5, "source": "@site/docs/Guides/0-guide2.5.md", "sourceDirName": "Guides", "title": "Guide 2.5", }, { "frontMatter": { "id": "guide3", "sidebar_position": 3, }, "id": "Guides/guide3", "sidebarPosition": 3, "source": "@site/docs/Guides/guide3.md", "sourceDirName": "Guides", "title": "Guide 3", }, { "frontMatter": { "id": "guide4", }, "id": "Guides/guide4", "sidebarPosition": undefined, "source": "@site/docs/Guides/a-guide4.md", "sourceDirName": "Guides", "title": "Guide 4", }, { "frontMatter": { "id": "guide5", }, "id": "Guides/guide5", "sidebarPosition": undefined, "source": "@site/docs/Guides/b-guide5.md", "sourceDirName": "Guides", "title": "Guide 5", }, { "frontMatter": {}, "id": "getting-started", "sidebarPosition": 0, "source": "@site/docs/0-getting-started.md", "sourceDirName": ".", "title": "Getting Started", }, { "frontMatter": {}, "id": "installation", "sidebarPosition": 1, "source": "@site/docs/1-installation.md", "sourceDirName": ".", "title": "Installation", }, ], "isCategoryIndex": [Function], "item": { "dirName": ".", "type": "autogenerated", }, "numberPrefixParser": [Function], "version": { "contentPath": "docs", "versionName": "current", }, } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 1`] = ` { "description": "Getting started text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "getting-started", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/installation", "title": "Installation", }, "permalink": "/docs/getting-started", "previous": undefined, "sidebar": "defaultSidebar", "sidebarPosition": 0, "slug": "/getting-started", "source": "@site/docs/0-getting-started.md", "sourceDirName": ".", "tags": [], "title": "Getting Started", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 2`] = ` { "description": "Installation text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "installation", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/Guides/guide1", "title": "Guide 1", }, "permalink": "/docs/installation", "previous": { "permalink": "/docs/getting-started", "title": "Getting Started", }, "sidebar": "defaultSidebar", "sidebarPosition": 1, "slug": "/installation", "source": "@site/docs/1-installation.md", "sourceDirName": ".", "tags": [], "title": "Installation", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 3`] = ` { "description": "Guide 1 text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "id": "guide1", "sidebar_position": 1, }, "id": "Guides/guide1", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/Guides/guide2", "title": "Guide 2", }, "permalink": "/docs/Guides/guide1", "previous": { "permalink": "/docs/installation", "title": "Installation", }, "sidebar": "defaultSidebar", "sidebarPosition": 1, "slug": "/Guides/guide1", "source": "@site/docs/Guides/z-guide1.md", "sourceDirName": "Guides", "tags": [], "title": "Guide 1", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 4`] = ` { "description": "Guide 2 text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "id": "guide2", }, "id": "Guides/guide2", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/Guides/guide2.5", "title": "Guide 2.5", }, "permalink": "/docs/Guides/guide2", "previous": { "permalink": "/docs/Guides/guide1", "title": "Guide 1", }, "sidebar": "defaultSidebar", "sidebarPosition": 2, "slug": "/Guides/guide2", "source": "@site/docs/Guides/02-guide2.md", "sourceDirName": "Guides", "tags": [], "title": "Guide 2", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 5`] = ` { "description": "Guide 2.5 text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "id": "guide2.5", "sidebar_position": 2.5, }, "id": "Guides/guide2.5", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/Guides/guide3", "title": "Guide 3", }, "permalink": "/docs/Guides/guide2.5", "previous": { "permalink": "/docs/Guides/guide2", "title": "Guide 2", }, "sidebar": "defaultSidebar", "sidebarPosition": 2.5, "slug": "/Guides/guide2.5", "source": "@site/docs/Guides/0-guide2.5.md", "sourceDirName": "Guides", "tags": [], "title": "Guide 2.5", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 6`] = ` { "description": "Guide 3 text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "id": "guide3", "sidebar_position": 3, }, "id": "Guides/guide3", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/Guides/guide4", "title": "Guide 4", }, "permalink": "/docs/Guides/guide3", "previous": { "permalink": "/docs/Guides/guide2.5", "title": "Guide 2.5", }, "sidebar": "defaultSidebar", "sidebarPosition": 3, "slug": "/Guides/guide3", "source": "@site/docs/Guides/guide3.md", "sourceDirName": "Guides", "tags": [], "title": "Guide 3", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 7`] = ` { "description": "Guide 4 text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "id": "guide4", }, "id": "Guides/guide4", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/Guides/guide5", "title": "Guide 5", }, "permalink": "/docs/Guides/guide4", "previous": { "permalink": "/docs/Guides/guide3", "title": "Guide 3", }, "sidebar": "defaultSidebar", "sidebarPosition": undefined, "slug": "/Guides/guide4", "source": "@site/docs/Guides/a-guide4.md", "sourceDirName": "Guides", "tags": [], "title": "Guide 4", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 8`] = ` { "description": "Guide 5 text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "id": "guide5", }, "id": "Guides/guide5", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/API/api-overview", "title": "API Overview", }, "permalink": "/docs/Guides/guide5", "previous": { "permalink": "/docs/Guides/guide4", "title": "Guide 4", }, "sidebar": "defaultSidebar", "sidebarPosition": undefined, "slug": "/Guides/guide5", "source": "@site/docs/Guides/b-guide5.md", "sourceDirName": "Guides", "tags": [], "title": "Guide 5", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 9`] = ` { "description": "API Overview text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "API/api-overview", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/API/Core APIs/Client API", "title": "Client API", }, "permalink": "/docs/API/api-overview", "previous": { "permalink": "/docs/Guides/guide5", "title": "Guide 5", }, "sidebar": "defaultSidebar", "sidebarPosition": 0, "slug": "/API/api-overview", "source": "@site/docs/3-API/00_api-overview.md", "sourceDirName": "3-API", "tags": [], "title": "API Overview", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 10`] = ` { "description": "Client API text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "API/Core APIs/Client API", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/API/Core APIs/Server API", "title": "Server API", }, "permalink": "/docs/API/Core APIs/Client API", "previous": { "permalink": "/docs/API/api-overview", "title": "API Overview", }, "sidebar": "defaultSidebar", "sidebarPosition": 0, "slug": "/API/Core APIs/Client API", "source": "@site/docs/3-API/01_Core APIs/0 --- Client API.md", "sourceDirName": "3-API/01_Core APIs", "tags": [], "title": "Client API", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 11`] = ` { "description": "Server API text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "API/Core APIs/Server API", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/API/Extension APIs/Plugin API", "title": "Plugin API", }, "permalink": "/docs/API/Core APIs/Server API", "previous": { "permalink": "/docs/API/Core APIs/Client API", "title": "Client API", }, "sidebar": "defaultSidebar", "sidebarPosition": 1, "slug": "/API/Core APIs/Server API", "source": "@site/docs/3-API/01_Core APIs/1 --- Server API.md", "sourceDirName": "3-API/01_Core APIs", "tags": [], "title": "Server API", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 12`] = ` { "description": "Plugin API text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "API/Extension APIs/Plugin API", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/API/Extension APIs/Theme API", "title": "Theme API", }, "permalink": "/docs/API/Extension APIs/Plugin API", "previous": { "permalink": "/docs/API/Core APIs/Server API", "title": "Server API", }, "sidebar": "defaultSidebar", "sidebarPosition": 0, "slug": "/API/Extension APIs/Plugin API", "source": "@site/docs/3-API/02_Extension APIs/0. Plugin API.md", "sourceDirName": "3-API/02_Extension APIs", "tags": [], "title": "Plugin API", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 13`] = ` { "description": "Theme API text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "API/Extension APIs/Theme API", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/API/api-end", "title": "API End", }, "permalink": "/docs/API/Extension APIs/Theme API", "previous": { "permalink": "/docs/API/Extension APIs/Plugin API", "title": "Plugin API", }, "sidebar": "defaultSidebar", "sidebarPosition": 1, "slug": "/API/Extension APIs/Theme API", "source": "@site/docs/3-API/02_Extension APIs/1. Theme API.md", "sourceDirName": "3-API/02_Extension APIs", "tags": [], "title": "Theme API", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar docs in fully generated sidebar have correct metadata 14`] = ` { "description": "API End text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "API/api-end", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": undefined, "permalink": "/docs/API/api-end", "previous": { "permalink": "/docs/API/Extension APIs/Theme API", "title": "Theme API", }, "sidebar": "defaultSidebar", "sidebarPosition": 3, "slug": "/API/api-end", "source": "@site/docs/3-API/03_api-end.md", "sourceDirName": "3-API", "tags": [], "title": "API End", "unlisted": false, "version": "current", } `; exports[`site with full autogenerated sidebar sidebar is fully autogenerated 1`] = ` { "defaultSidebar": [ { "id": "getting-started", "type": "doc", }, { "id": "installation", "type": "doc", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "Guides/guide1", "type": "doc", }, { "id": "Guides/guide2", "type": "doc", }, { "id": "Guides/guide2.5", "type": "doc", }, { "id": "Guides/guide3", "type": "doc", }, { "id": "Guides/guide4", "type": "doc", }, { "id": "Guides/guide5", "type": "doc", }, ], "label": "Guides", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "API/api-overview", "type": "doc", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "API/Core APIs/Client API", "type": "doc", }, { "id": "API/Core APIs/Server API", "type": "doc", }, ], "label": "Core APIs", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "API/Extension APIs/Plugin API", "type": "doc", }, { "id": "API/Extension APIs/Theme API", "type": "doc", }, ], "label": "Extension APIs (label from _category_.yml)", "link": undefined, "type": "category", }, { "id": "API/api-end", "type": "doc", }, ], "label": "API (label from _category_.json)", "link": undefined, "type": "category", }, ], } `; exports[`site with partial autogenerated sidebars 2 (fix #4638) sidebar is partially autogenerated 1`] = ` { "someSidebar": [ { "id": "API/api-end", "type": "doc", }, { "id": "API/api-overview", "type": "doc", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "API/Core APIs/Client API", "type": "doc", }, { "id": "API/Core APIs/Server API", "type": "doc", }, ], "label": "Core APIs", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "API/Extension APIs/Plugin API", "type": "doc", }, { "id": "API/Extension APIs/Theme API", "type": "doc", }, ], "label": "Extension APIs (label from _category_.yml)", "link": undefined, "type": "category", }, { "id": "API/api-end", "type": "doc", }, ], } `; exports[`site with partial autogenerated sidebars docs in partially generated sidebar have correct metadata 1`] = ` { "description": "API End text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "API/api-end", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/API/api-overview", "title": "API Overview", }, "permalink": "/docs/API/api-end", "previous": undefined, "sidebar": "someSidebar", "sidebarPosition": 3, "slug": "/API/api-end", "source": "@site/docs/3-API/03_api-end.md", "sourceDirName": "3-API", "tags": [], "title": "API End", "unlisted": false, "version": "current", } `; exports[`site with partial autogenerated sidebars docs in partially generated sidebar have correct metadata 2`] = ` { "description": "API Overview text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "API/api-overview", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/API/Extension APIs/Plugin API", "title": "Plugin API", }, "permalink": "/docs/API/api-overview", "previous": { "permalink": "/docs/API/api-end", "title": "API End", }, "sidebar": "someSidebar", "sidebarPosition": 0, "slug": "/API/api-overview", "source": "@site/docs/3-API/00_api-overview.md", "sourceDirName": "3-API", "tags": [], "title": "API Overview", "unlisted": false, "version": "current", } `; exports[`site with partial autogenerated sidebars docs in partially generated sidebar have correct metadata 3`] = ` { "description": "Plugin API text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "API/Extension APIs/Plugin API", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/API/Extension APIs/Theme API", "title": "Theme API", }, "permalink": "/docs/API/Extension APIs/Plugin API", "previous": { "permalink": "/docs/API/api-overview", "title": "API Overview", }, "sidebar": "someSidebar", "sidebarPosition": 0, "slug": "/API/Extension APIs/Plugin API", "source": "@site/docs/3-API/02_Extension APIs/0. Plugin API.md", "sourceDirName": "3-API/02_Extension APIs", "tags": [], "title": "Plugin API", "unlisted": false, "version": "current", } `; exports[`site with partial autogenerated sidebars docs in partially generated sidebar have correct metadata 4`] = ` { "description": "Theme API text", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "API/Extension APIs/Theme API", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": undefined, "permalink": "/docs/API/Extension APIs/Theme API", "previous": { "permalink": "/docs/API/Extension APIs/Plugin API", "title": "Plugin API", }, "sidebar": "someSidebar", "sidebarPosition": 1, "slug": "/API/Extension APIs/Theme API", "source": "@site/docs/3-API/02_Extension APIs/1. Theme API.md", "sourceDirName": "3-API/02_Extension APIs", "tags": [], "title": "Theme API", "unlisted": false, "version": "current", } `; exports[`site with partial autogenerated sidebars sidebar is partially autogenerated 1`] = ` { "someSidebar": [ { "id": "API/api-end", "type": "doc", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "API/api-overview", "type": "doc", }, { "id": "API/Extension APIs/Plugin API", "type": "doc", }, { "id": "API/Extension APIs/Theme API", "type": "doc", }, ], "label": "Some category", "link": undefined, "type": "category", }, ], } `; exports[`versioned website (community) content 1`] = ` { "description": "Team current version (translated)", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "title": "Team title translated", }, "id": "team", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": undefined, "permalink": "/community/next/team", "previous": undefined, "sidebar": "community", "sidebarPosition": undefined, "slug": "/team", "source": "@site/i18n/en/docusaurus-plugin-content-docs-community/current/team.md", "sourceDirName": ".", "tags": [], "title": "Team title translated", "unlisted": false, "version": "current", } `; exports[`versioned website (community) content 2`] = ` { "description": "Team 1.0.0", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "team", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": undefined, "permalink": "/community/team", "previous": undefined, "sidebar": "community", "sidebarPosition": undefined, "slug": "/team", "source": "@site/community_versioned_docs/version-1.0.0/team.md", "sourceDirName": ".", "tags": [], "title": "team", "unlisted": false, "version": "1.0.0", } `; exports[`versioned website (community) content: 100 version sidebars 1`] = ` { "community": [ { "id": "team", "type": "doc", }, ], } `; exports[`versioned website (community) content: current version sidebars 1`] = ` { "community": [ { "id": "team", "type": "doc", }, ], } `; exports[`versioned website (community) content: data 1`] = ` { "site-community-versioned-docs-version-1-0-0-team-md-359.json": "{ "id": "team", "title": "team", "description": "Team 1.0.0", "source": "@site/community_versioned_docs/version-1.0.0/team.md", "sourceDirName": ".", "slug": "/team", "permalink": "/community/team", "draft": false, "unlisted": false, "tags": [], "version": "1.0.0", "frontMatter": {}, "sidebar": "community" }", "site-i-18-n-en-docusaurus-plugin-content-docs-community-current-team-md-7e5.json": "{ "id": "team", "title": "Team title translated", "description": "Team current version (translated)", "source": "@site/i18n/en/docusaurus-plugin-content-docs-community/current/team.md", "sourceDirName": ".", "slug": "/team", "permalink": "/community/next/team", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "title": "Team title translated" }, "sidebar": "community" }", "version-1-0-0-metadata-prop-608.json": "{ "pluginId": "community", "version": "1.0.0", "label": "1.0.0", "banner": null, "badge": true, "noIndex": false, "className": "docs-version-1.0.0", "isLast": true, "docsSidebars": { "community": [ { "type": "link", "label": "team", "href": "/community/team", "docId": "team", "unlisted": false } ] }, "docs": { "team": { "id": "team", "title": "team", "description": "Team 1.0.0", "sidebar": "community" } } }", "version-current-metadata-prop-751.json": "{ "pluginId": "community", "version": "current", "label": "Next", "banner": "unreleased", "badge": true, "noIndex": false, "className": "docs-version-current", "isLast": false, "docsSidebars": { "community": [ { "type": "link", "label": "Team title translated", "href": "/community/next/team", "docId": "team", "unlisted": false } ] }, "docs": { "team": { "id": "team", "title": "Team title translated", "description": "Team current version (translated)", "sidebar": "community" } } }", } `; exports[`versioned website (community) content: global data 1`] = ` { "pluginName": { "pluginId": { "breadcrumbs": true, "path": "/community", "versions": [ { "docs": [ { "id": "team", "path": "/community/next/team", "sidebar": "community", }, ], "draftIds": [], "isLast": false, "label": "Next", "mainDocId": "team", "name": "current", "path": "/community/next", "sidebars": { "community": { "link": { "label": "team", "path": "/community/next/team", }, }, }, }, { "docs": [ { "id": "team", "path": "/community/team", "sidebar": "community", }, ], "draftIds": [], "isLast": true, "label": "1.0.0", "mainDocId": "team", "name": "1.0.0", "path": "/community", "sidebars": { "community": { "link": { "label": "team", "path": "/community/team", }, }, }, }, ], }, }, } `; exports[`versioned website (community) content: route config 1`] = ` [ { "component": "@theme/DocsRoot", "exact": false, "path": "/community", "routes": [ { "component": "@theme/DocVersionRoot", "exact": false, "modules": { "version": "~docs/version-current-metadata-prop-751.json", }, "path": "/community/next", "priority": undefined, "routes": [ { "component": "@theme/DocRoot", "exact": false, "path": "/community/next", "routes": [ { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/i18n/en/docusaurus-plugin-content-docs-community/current/team.md", }, "path": "/community/next/team", "sidebar": "community", }, ], }, ], }, { "component": "@theme/DocVersionRoot", "exact": false, "modules": { "version": "~docs/version-1-0-0-metadata-prop-608.json", }, "path": "/community", "priority": -1, "routes": [ { "component": "@theme/DocRoot", "exact": false, "path": "/community", "routes": [ { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/community_versioned_docs/version-1.0.0/team.md", }, "path": "/community/team", "sidebar": "community", }, ], }, ], }, ], }, ] `; exports[`versioned website (community) getPathToWatch 1`] = ` [ "community_sidebars.json", "i18n/en/docusaurus-plugin-content-docs-community/current/**/*.{md,mdx}", "community/**/*.{md,mdx}", "community/**/_category_.{json,yml,yaml}", "community_versioned_sidebars/version-1.0.0-sidebars.json", "i18n/en/docusaurus-plugin-content-docs-community/version-1.0.0/**/*.{md,mdx}", "community_versioned_docs/version-1.0.0/**/*.{md,mdx}", "community_versioned_docs/version-1.0.0/**/_category_.{json,yml,yaml}", ] `; exports[`versioned website content 1`] = ` { "description": "This is next version of bar.", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "slug": "barSlug", "tags": [ "barTag 1", "barTag-2", { "label": "barTag 3", "permalink": "barTag-3-permalink", }, ], }, "id": "foo/bar", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/next/", "title": "hello", }, "permalink": "/docs/next/foo/barSlug", "previous": undefined, "sidebar": "docs", "sidebarPosition": undefined, "slug": "/foo/barSlug", "source": "@site/docs/foo/bar.md", "sourceDirName": "foo", "tags": [ { "label": "barTag 1", "permalink": "/docs/next/tags/bar-tag-1", }, { "label": "barTag-2", "permalink": "/docs/next/tags/bar-tag-2", }, { "label": "barTag 3", "permalink": "/docs/next/tags/barTag-3-permalink", }, ], "title": "bar", "unlisted": false, "version": "current", } `; exports[`versioned website content 2`] = ` { "description": "Bar 1.0.1 !", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "foo/bar", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/", "title": "hello", }, "permalink": "/docs/foo/bar", "previous": undefined, "sidebar": "VersionedSideBarNameDoesNotMatter/docs", "sidebarPosition": undefined, "slug": "/foo/bar", "source": "@site/versioned_docs/version-1.0.1/foo/bar.md", "sourceDirName": "foo", "tags": [], "title": "bar", "unlisted": false, "version": "1.0.1", } `; exports[`versioned website content 3`] = ` { "description": "Hello next !", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "slug": "/", }, "id": "hello", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": undefined, "permalink": "/docs/next/", "previous": { "permalink": "/docs/next/foo/barSlug", "title": "bar", }, "sidebar": "docs", "sidebarPosition": undefined, "slug": "/", "source": "@site/docs/hello.md", "sourceDirName": ".", "tags": [], "title": "hello", "unlisted": false, "version": "current", } `; exports[`versioned website content 4`] = ` { "description": "Hello 1.0.1 !", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": { "slug": "/", }, "id": "hello", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": undefined, "permalink": "/docs/", "previous": { "permalink": "/docs/foo/bar", "title": "bar", }, "sidebar": "VersionedSideBarNameDoesNotMatter/docs", "sidebarPosition": undefined, "slug": "/", "source": "@site/versioned_docs/version-1.0.1/hello.md", "sourceDirName": ".", "tags": [], "title": "hello", "unlisted": false, "version": "1.0.1", } `; exports[`versioned website content 5`] = ` { "description": "Baz 1.0.0 ! This will be deleted in next subsequent versions.", "draft": false, "editUrl": undefined, "formattedLastUpdatedAt": undefined, "frontMatter": {}, "id": "foo/baz", "lastUpdatedAt": undefined, "lastUpdatedBy": undefined, "next": { "permalink": "/docs/1.0.0/", "title": "hello", }, "permalink": "/docs/1.0.0/foo/baz", "previous": { "permalink": "/docs/1.0.0/foo/barSlug", "title": "bar", }, "sidebar": "docs", "sidebarPosition": undefined, "slug": "/foo/baz", "source": "@site/versioned_docs/version-1.0.0/foo/baz.md", "sourceDirName": "foo", "tags": [], "title": "baz", "unlisted": false, "version": "1.0.0", } `; exports[`versioned website content: 100 version sidebars 1`] = ` { "docs": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "foo/bar", "type": "doc", }, { "id": "foo/baz", "type": "doc", }, ], "label": "Test", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "hello", "type": "doc", }, ], "label": "Guides", "link": undefined, "type": "category", }, ], } `; exports[`versioned website content: 101 version sidebars 1`] = ` { "VersionedSideBarNameDoesNotMatter/docs": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "foo/bar", "type": "doc", }, ], "label": "Test", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "hello", "type": "doc", }, ], "label": "Guides", "link": undefined, "type": "category", }, ], } `; exports[`versioned website content: current version sidebars 1`] = ` { "docs": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "foo/bar", "type": "doc", }, ], "label": "Test", "link": undefined, "type": "category", }, { "collapsed": true, "collapsible": true, "items": [ { "id": "hello", "type": "doc", }, ], "label": "Guides", "link": undefined, "type": "category", }, ], } `; exports[`versioned website content: data 1`] = ` { "site-docs-foo-bar-md-8c2.json": "{ "id": "foo/bar", "title": "bar", "description": "This is next version of bar.", "source": "@site/docs/foo/bar.md", "sourceDirName": "foo", "slug": "/foo/barSlug", "permalink": "/docs/next/foo/barSlug", "draft": false, "unlisted": false, "tags": [ { "label": "barTag 1", "permalink": "/docs/next/tags/bar-tag-1" }, { "label": "barTag-2", "permalink": "/docs/next/tags/bar-tag-2" }, { "label": "barTag 3", "permalink": "/docs/next/tags/barTag-3-permalink" } ], "version": "current", "frontMatter": { "slug": "barSlug", "tags": [ "barTag 1", "barTag-2", { "label": "barTag 3", "permalink": "barTag-3-permalink" } ] }, "sidebar": "docs", "next": { "title": "hello", "permalink": "/docs/next/" } }", "site-docs-hello-md-9df.json": "{ "id": "hello", "title": "hello", "description": "Hello next !", "source": "@site/docs/hello.md", "sourceDirName": ".", "slug": "/", "permalink": "/docs/next/", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "/" }, "sidebar": "docs", "previous": { "title": "bar", "permalink": "/docs/next/foo/barSlug" } }", "site-docs-slugs-absolute-slug-md-4e8.json": "{ "id": "slugs/absoluteSlug", "title": "absoluteSlug", "description": "Lorem", "source": "@site/docs/slugs/absoluteSlug.md", "sourceDirName": "slugs", "slug": "/absoluteSlug", "permalink": "/docs/next/absoluteSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "/absoluteSlug" } }", "site-docs-slugs-relative-slug-md-d1c.json": "{ "id": "slugs/relativeSlug", "title": "relativeSlug", "description": "Lorem", "source": "@site/docs/slugs/relativeSlug.md", "sourceDirName": "slugs", "slug": "/slugs/relativeSlug", "permalink": "/docs/next/slugs/relativeSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "relativeSlug" } }", "site-docs-slugs-resolved-slug-md-02b.json": "{ "id": "slugs/resolvedSlug", "title": "resolvedSlug", "description": "Lorem", "source": "@site/docs/slugs/resolvedSlug.md", "sourceDirName": "slugs", "slug": "/slugs/hey/resolvedSlug", "permalink": "/docs/next/slugs/hey/resolvedSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "./hey/ho/../resolvedSlug" } }", "site-docs-slugs-try-to-escape-slug-md-70d.json": "{ "id": "slugs/tryToEscapeSlug", "title": "tryToEscapeSlug", "description": "Lorem", "source": "@site/docs/slugs/tryToEscapeSlug.md", "sourceDirName": "slugs", "slug": "/tryToEscapeSlug", "permalink": "/docs/next/tryToEscapeSlug", "draft": false, "unlisted": false, "tags": [], "version": "current", "frontMatter": { "slug": "../../../../../../../../tryToEscapeSlug" } }", "site-i-18-n-en-docusaurus-plugin-content-docs-version-1-0-0-hello-md-fe5.json": "{ "id": "hello", "title": "hello", "description": "Hello 1.0.0 ! (translated en)", "source": "@site/i18n/en/docusaurus-plugin-content-docs/version-1.0.0/hello.md", "sourceDirName": ".", "slug": "/", "permalink": "/docs/1.0.0/", "draft": false, "unlisted": false, "tags": [], "version": "1.0.0", "frontMatter": { "slug": "/" }, "sidebar": "docs", "previous": { "title": "baz", "permalink": "/docs/1.0.0/foo/baz" } }", "site-versioned-docs-version-1-0-0-foo-bar-md-7a6.json": "{ "id": "foo/bar", "title": "bar", "description": "Bar 1.0.0 !", "source": "@site/versioned_docs/version-1.0.0/foo/bar.md", "sourceDirName": "foo", "slug": "/foo/barSlug", "permalink": "/docs/1.0.0/foo/barSlug", "draft": false, "unlisted": false, "tags": [], "version": "1.0.0", "frontMatter": { "slug": "barSlug" }, "sidebar": "docs", "next": { "title": "baz", "permalink": "/docs/1.0.0/foo/baz" } }", "site-versioned-docs-version-1-0-0-foo-baz-md-883.json": "{ "id": "foo/baz", "title": "baz", "description": "Baz 1.0.0 ! This will be deleted in next subsequent versions.", "source": "@site/versioned_docs/version-1.0.0/foo/baz.md", "sourceDirName": "foo", "slug": "/foo/baz", "permalink": "/docs/1.0.0/foo/baz", "draft": false, "unlisted": false, "tags": [], "version": "1.0.0", "frontMatter": {}, "sidebar": "docs", "previous": { "title": "bar", "permalink": "/docs/1.0.0/foo/barSlug" }, "next": { "title": "hello", "permalink": "/docs/1.0.0/" } }", "site-versioned-docs-version-1-0-1-foo-bar-md-7a3.json": "{ "id": "foo/bar", "title": "bar", "description": "Bar 1.0.1 !", "source": "@site/versioned_docs/version-1.0.1/foo/bar.md", "sourceDirName": "foo", "slug": "/foo/bar", "permalink": "/docs/foo/bar", "draft": false, "unlisted": false, "tags": [], "version": "1.0.1", "frontMatter": {}, "sidebar": "VersionedSideBarNameDoesNotMatter/docs", "next": { "title": "hello", "permalink": "/docs/" } }", "site-versioned-docs-version-1-0-1-hello-md-0c7.json": "{ "id": "hello", "title": "hello", "description": "Hello 1.0.1 !", "source": "@site/versioned_docs/version-1.0.1/hello.md", "sourceDirName": ".", "slug": "/", "permalink": "/docs/", "draft": false, "unlisted": false, "tags": [], "version": "1.0.1", "frontMatter": { "slug": "/" }, "sidebar": "VersionedSideBarNameDoesNotMatter/docs", "previous": { "title": "bar", "permalink": "/docs/foo/bar" } }", "site-versioned-docs-version-with-slugs-root-absolute-slug-md-4d2.json": "{ "id": "rootAbsoluteSlug", "title": "rootAbsoluteSlug", "description": "Lorem", "source": "@site/versioned_docs/version-withSlugs/rootAbsoluteSlug.md", "sourceDirName": ".", "slug": "/rootAbsoluteSlug", "permalink": "/docs/withSlugs/rootAbsoluteSlug", "draft": false, "unlisted": false, "tags": [], "version": "withSlugs", "frontMatter": { "slug": "/rootAbsoluteSlug" }, "sidebar": "docs" }", "site-versioned-docs-version-with-slugs-root-relative-slug-md-32a.json": "{ "id": "rootRelativeSlug", "title": "rootRelativeSlug", "description": "Lorem", "source": "@site/versioned_docs/version-withSlugs/rootRelativeSlug.md", "sourceDirName": ".", "slug": "/rootRelativeSlug", "permalink": "/docs/withSlugs/rootRelativeSlug", "draft": false, "unlisted": false, "tags": [], "version": "withSlugs", "frontMatter": { "slug": "rootRelativeSlug" } }", "site-versioned-docs-version-with-slugs-root-resolved-slug-md-aee.json": "{ "id": "rootResolvedSlug", "title": "rootResolvedSlug", "description": "Lorem", "source": "@site/versioned_docs/version-withSlugs/rootResolvedSlug.md", "sourceDirName": ".", "slug": "/hey/rootResolvedSlug", "permalink": "/docs/withSlugs/hey/rootResolvedSlug", "draft": false, "unlisted": false, "tags": [], "version": "withSlugs", "frontMatter": { "slug": "./hey/ho/../rootResolvedSlug" } }", "site-versioned-docs-version-with-slugs-root-try-to-escape-slug-md-b5d.json": "{ "id": "rootTryToEscapeSlug", "title": "rootTryToEscapeSlug", "description": "Lorem", "source": "@site/versioned_docs/version-withSlugs/rootTryToEscapeSlug.md", "sourceDirName": ".", "slug": "/rootTryToEscapeSlug", "permalink": "/docs/withSlugs/rootTryToEscapeSlug", "draft": false, "unlisted": false, "tags": [], "version": "withSlugs", "frontMatter": { "slug": "../../../../../../../../rootTryToEscapeSlug" } }", "site-versioned-docs-version-with-slugs-slugs-absolute-slug-md-47a.json": "{ "id": "slugs/absoluteSlug", "title": "absoluteSlug", "description": "Lorem", "source": "@site/versioned_docs/version-withSlugs/slugs/absoluteSlug.md", "sourceDirName": "slugs", "slug": "/absoluteSlug", "permalink": "/docs/withSlugs/absoluteSlug", "draft": false, "unlisted": false, "tags": [], "version": "withSlugs", "frontMatter": { "slug": "/absoluteSlug" } }", "site-versioned-docs-version-with-slugs-slugs-relative-slug-md-a95.json": "{ "id": "slugs/relativeSlug", "title": "relativeSlug", "description": "Lorem", "source": "@site/versioned_docs/version-withSlugs/slugs/relativeSlug.md", "sourceDirName": "slugs", "slug": "/slugs/relativeSlug", "permalink": "/docs/withSlugs/slugs/relativeSlug", "draft": false, "unlisted": false, "tags": [], "version": "withSlugs", "frontMatter": { "slug": "relativeSlug" } }", "site-versioned-docs-version-with-slugs-slugs-resolved-slug-md-5a1.json": "{ "id": "slugs/resolvedSlug", "title": "resolvedSlug", "description": "Lorem", "source": "@site/versioned_docs/version-withSlugs/slugs/resolvedSlug.md", "sourceDirName": "slugs", "slug": "/slugs/hey/resolvedSlug", "permalink": "/docs/withSlugs/slugs/hey/resolvedSlug", "draft": false, "unlisted": false, "tags": [], "version": "withSlugs", "frontMatter": { "slug": "./hey/ho/../resolvedSlug" } }", "site-versioned-docs-version-with-slugs-slugs-try-to-escape-slug-md-4e1.json": "{ "id": "slugs/tryToEscapeSlug", "title": "tryToEscapeSlug", "description": "Lorem", "source": "@site/versioned_docs/version-withSlugs/slugs/tryToEscapeSlug.md", "sourceDirName": "slugs", "slug": "/tryToEscapeSlug", "permalink": "/docs/withSlugs/tryToEscapeSlug", "draft": false, "unlisted": false, "tags": [], "version": "withSlugs", "frontMatter": { "slug": "../../../../../../../../tryToEscapeSlug" } }", "tag-docs-next-tags-bar-tag-1-a8f.json": "{ "label": "barTag 1", "permalink": "/docs/next/tags/bar-tag-1", "allTagsPath": "/docs/next/tags", "count": 1, "items": [ { "id": "foo/bar", "title": "bar", "description": "This is next version of bar.", "permalink": "/docs/next/foo/barSlug" } ], "unlisted": false }", "tag-docs-next-tags-bar-tag-2-216.json": "{ "label": "barTag-2", "permalink": "/docs/next/tags/bar-tag-2", "allTagsPath": "/docs/next/tags", "count": 1, "items": [ { "id": "foo/bar", "title": "bar", "description": "This is next version of bar.", "permalink": "/docs/next/foo/barSlug" } ], "unlisted": false }", "tag-docs-next-tags-bar-tag-3-permalink-94a.json": "{ "label": "barTag 3", "permalink": "/docs/next/tags/barTag-3-permalink", "allTagsPath": "/docs/next/tags", "count": 1, "items": [ { "id": "foo/bar", "title": "bar", "description": "This is next version of bar.", "permalink": "/docs/next/foo/barSlug" } ], "unlisted": false }", "tags-list-current-prop-15a.json": "[ { "label": "barTag 1", "permalink": "/docs/next/tags/bar-tag-1", "count": 1 }, { "label": "barTag-2", "permalink": "/docs/next/tags/bar-tag-2", "count": 1 }, { "label": "barTag 3", "permalink": "/docs/next/tags/barTag-3-permalink", "count": 1 } ]", "version-1-0-0-metadata-prop-608.json": "{ "pluginId": "default", "version": "1.0.0", "label": "1.0.0", "banner": "unmaintained", "badge": true, "noIndex": false, "className": "docs-version-1.0.0", "isLast": false, "docsSidebars": { "docs": [ { "type": "category", "label": "Test", "items": [ { "type": "link", "label": "bar", "href": "/docs/1.0.0/foo/barSlug", "docId": "foo/bar", "unlisted": false }, { "type": "link", "label": "baz", "href": "/docs/1.0.0/foo/baz", "docId": "foo/baz", "unlisted": false } ], "collapsed": true, "collapsible": true }, { "type": "category", "label": "Guides", "items": [ { "type": "link", "label": "hello", "href": "/docs/1.0.0/", "docId": "hello", "unlisted": false } ], "collapsed": true, "collapsible": true } ] }, "docs": { "foo/bar": { "id": "foo/bar", "title": "bar", "description": "Bar 1.0.0 !", "sidebar": "docs" }, "foo/baz": { "id": "foo/baz", "title": "baz", "description": "Baz 1.0.0 ! This will be deleted in next subsequent versions.", "sidebar": "docs" }, "hello": { "id": "hello", "title": "hello", "description": "Hello 1.0.0 ! (translated en)", "sidebar": "docs" } } }", "version-1-0-1-metadata-prop-e87.json": "{ "pluginId": "default", "version": "1.0.1", "label": "1.0.1", "banner": null, "badge": true, "noIndex": true, "className": "docs-version-1.0.1", "isLast": true, "docsSidebars": { "VersionedSideBarNameDoesNotMatter/docs": [ { "type": "category", "label": "Test", "items": [ { "type": "link", "label": "bar", "href": "/docs/foo/bar", "docId": "foo/bar", "unlisted": false } ], "collapsed": true, "collapsible": true }, { "type": "category", "label": "Guides", "items": [ { "type": "link", "label": "hello", "href": "/docs/", "docId": "hello", "unlisted": false } ], "collapsed": true, "collapsible": true } ] }, "docs": { "foo/bar": { "id": "foo/bar", "title": "bar", "description": "Bar 1.0.1 !", "sidebar": "VersionedSideBarNameDoesNotMatter/docs" }, "hello": { "id": "hello", "title": "hello", "description": "Hello 1.0.1 !", "sidebar": "VersionedSideBarNameDoesNotMatter/docs" } } }", "version-current-metadata-prop-751.json": "{ "pluginId": "default", "version": "current", "label": "Next", "banner": "unreleased", "badge": true, "noIndex": false, "className": "docs-version-current", "isLast": false, "docsSidebars": { "docs": [ { "type": "category", "label": "Test", "items": [ { "type": "link", "label": "bar", "href": "/docs/next/foo/barSlug", "docId": "foo/bar", "unlisted": false } ], "collapsed": true, "collapsible": true }, { "type": "category", "label": "Guides", "items": [ { "type": "link", "label": "hello", "href": "/docs/next/", "docId": "hello", "unlisted": false } ], "collapsed": true, "collapsible": true } ] }, "docs": { "foo/bar": { "id": "foo/bar", "title": "bar", "description": "This is next version of bar.", "sidebar": "docs" }, "hello": { "id": "hello", "title": "hello", "description": "Hello next !", "sidebar": "docs" }, "slugs/absoluteSlug": { "id": "slugs/absoluteSlug", "title": "absoluteSlug", "description": "Lorem" }, "slugs/relativeSlug": { "id": "slugs/relativeSlug", "title": "relativeSlug", "description": "Lorem" }, "slugs/resolvedSlug": { "id": "slugs/resolvedSlug", "title": "resolvedSlug", "description": "Lorem" }, "slugs/tryToEscapeSlug": { "id": "slugs/tryToEscapeSlug", "title": "tryToEscapeSlug", "description": "Lorem" } } }", "version-with-slugs-metadata-prop-2bf.json": "{ "pluginId": "default", "version": "withSlugs", "label": "withSlugs", "banner": "unmaintained", "badge": true, "noIndex": false, "className": "docs-version-withSlugs", "isLast": false, "docsSidebars": { "docs": [ { "type": "category", "label": "Test", "items": [ { "type": "link", "label": "rootAbsoluteSlug", "href": "/docs/withSlugs/rootAbsoluteSlug", "docId": "rootAbsoluteSlug", "unlisted": false } ], "collapsed": true, "collapsible": true } ] }, "docs": { "rootAbsoluteSlug": { "id": "rootAbsoluteSlug", "title": "rootAbsoluteSlug", "description": "Lorem", "sidebar": "docs" }, "rootRelativeSlug": { "id": "rootRelativeSlug", "title": "rootRelativeSlug", "description": "Lorem" }, "rootResolvedSlug": { "id": "rootResolvedSlug", "title": "rootResolvedSlug", "description": "Lorem" }, "rootTryToEscapeSlug": { "id": "rootTryToEscapeSlug", "title": "rootTryToEscapeSlug", "description": "Lorem" }, "slugs/absoluteSlug": { "id": "slugs/absoluteSlug", "title": "absoluteSlug", "description": "Lorem" }, "slugs/relativeSlug": { "id": "slugs/relativeSlug", "title": "relativeSlug", "description": "Lorem" }, "slugs/resolvedSlug": { "id": "slugs/resolvedSlug", "title": "resolvedSlug", "description": "Lorem" }, "slugs/tryToEscapeSlug": { "id": "slugs/tryToEscapeSlug", "title": "tryToEscapeSlug", "description": "Lorem" } } }", } `; exports[`versioned website content: global data 1`] = ` { "pluginName": { "pluginId": { "breadcrumbs": true, "path": "/docs", "versions": [ { "docs": [ { "id": "foo/bar", "path": "/docs/next/foo/barSlug", "sidebar": "docs", }, { "id": "hello", "path": "/docs/next/", "sidebar": "docs", }, { "id": "slugs/absoluteSlug", "path": "/docs/next/absoluteSlug", "sidebar": undefined, }, { "id": "slugs/relativeSlug", "path": "/docs/next/slugs/relativeSlug", "sidebar": undefined, }, { "id": "slugs/resolvedSlug", "path": "/docs/next/slugs/hey/resolvedSlug", "sidebar": undefined, }, { "id": "slugs/tryToEscapeSlug", "path": "/docs/next/tryToEscapeSlug", "sidebar": undefined, }, ], "draftIds": [], "isLast": false, "label": "Next", "mainDocId": "hello", "name": "current", "path": "/docs/next", "sidebars": { "docs": { "link": { "label": "foo/bar", "path": "/docs/next/foo/barSlug", }, }, }, }, { "docs": [ { "id": "foo/bar", "path": "/docs/foo/bar", "sidebar": "VersionedSideBarNameDoesNotMatter/docs", }, { "id": "hello", "path": "/docs/", "sidebar": "VersionedSideBarNameDoesNotMatter/docs", }, ], "draftIds": [], "isLast": true, "label": "1.0.1", "mainDocId": "hello", "name": "1.0.1", "path": "/docs", "sidebars": { "VersionedSideBarNameDoesNotMatter/docs": { "link": { "label": "foo/bar", "path": "/docs/foo/bar", }, }, }, }, { "docs": [ { "id": "foo/bar", "path": "/docs/1.0.0/foo/barSlug", "sidebar": "docs", }, { "id": "foo/baz", "path": "/docs/1.0.0/foo/baz", "sidebar": "docs", }, { "id": "hello", "path": "/docs/1.0.0/", "sidebar": "docs", }, ], "draftIds": [], "isLast": false, "label": "1.0.0", "mainDocId": "hello", "name": "1.0.0", "path": "/docs/1.0.0", "sidebars": { "docs": { "link": { "label": "foo/bar", "path": "/docs/1.0.0/foo/barSlug", }, }, }, }, { "docs": [ { "id": "rootAbsoluteSlug", "path": "/docs/withSlugs/rootAbsoluteSlug", "sidebar": "docs", }, { "id": "rootRelativeSlug", "path": "/docs/withSlugs/rootRelativeSlug", "sidebar": undefined, }, { "id": "rootResolvedSlug", "path": "/docs/withSlugs/hey/rootResolvedSlug", "sidebar": undefined, }, { "id": "rootTryToEscapeSlug", "path": "/docs/withSlugs/rootTryToEscapeSlug", "sidebar": undefined, }, { "id": "slugs/absoluteSlug", "path": "/docs/withSlugs/absoluteSlug", "sidebar": undefined, }, { "id": "slugs/relativeSlug", "path": "/docs/withSlugs/slugs/relativeSlug", "sidebar": undefined, }, { "id": "slugs/resolvedSlug", "path": "/docs/withSlugs/slugs/hey/resolvedSlug", "sidebar": undefined, }, { "id": "slugs/tryToEscapeSlug", "path": "/docs/withSlugs/tryToEscapeSlug", "sidebar": undefined, }, ], "draftIds": [], "isLast": false, "label": "withSlugs", "mainDocId": "rootAbsoluteSlug", "name": "withSlugs", "path": "/docs/withSlugs", "sidebars": { "docs": { "link": { "label": "rootAbsoluteSlug", "path": "/docs/withSlugs/rootAbsoluteSlug", }, }, }, }, ], }, }, } `; exports[`versioned website content: route config 1`] = ` [ { "component": "@theme/DocsRoot", "exact": false, "path": "/docs", "routes": [ { "component": "@theme/DocVersionRoot", "exact": false, "modules": { "version": "~docs/version-1-0-0-metadata-prop-608.json", }, "path": "/docs/1.0.0", "priority": undefined, "routes": [ { "component": "@theme/DocRoot", "exact": false, "path": "/docs/1.0.0", "routes": [ { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/i18n/en/docusaurus-plugin-content-docs/version-1.0.0/hello.md", }, "path": "/docs/1.0.0/", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-1.0.0/foo/bar.md", }, "path": "/docs/1.0.0/foo/barSlug", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-1.0.0/foo/baz.md", }, "path": "/docs/1.0.0/foo/baz", "sidebar": "docs", }, ], }, ], }, { "component": "@theme/DocVersionRoot", "exact": false, "modules": { "version": "~docs/version-current-metadata-prop-751.json", }, "path": "/docs/next", "priority": undefined, "routes": [ { "component": "@theme/DocTagsListPage", "exact": true, "modules": { "tags": "~docs/tags-list-current-prop-15a.json", }, "path": "/docs/next/tags", }, { "component": "@theme/DocTagDocListPage", "exact": true, "modules": { "tag": "~docs/tag-docs-next-tags-bar-tag-1-a8f.json", }, "path": "/docs/next/tags/bar-tag-1", }, { "component": "@theme/DocTagDocListPage", "exact": true, "modules": { "tag": "~docs/tag-docs-next-tags-bar-tag-2-216.json", }, "path": "/docs/next/tags/bar-tag-2", }, { "component": "@theme/DocTagDocListPage", "exact": true, "modules": { "tag": "~docs/tag-docs-next-tags-bar-tag-3-permalink-94a.json", }, "path": "/docs/next/tags/barTag-3-permalink", }, { "component": "@theme/DocRoot", "exact": false, "path": "/docs/next", "routes": [ { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/hello.md", }, "path": "/docs/next/", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/slugs/absoluteSlug.md", }, "path": "/docs/next/absoluteSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/foo/bar.md", }, "path": "/docs/next/foo/barSlug", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/slugs/resolvedSlug.md", }, "path": "/docs/next/slugs/hey/resolvedSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/slugs/relativeSlug.md", }, "path": "/docs/next/slugs/relativeSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/docs/slugs/tryToEscapeSlug.md", }, "path": "/docs/next/tryToEscapeSlug", }, ], }, ], }, { "component": "@theme/DocVersionRoot", "exact": false, "modules": { "version": "~docs/version-with-slugs-metadata-prop-2bf.json", }, "path": "/docs/withSlugs", "priority": undefined, "routes": [ { "component": "@theme/DocRoot", "exact": false, "path": "/docs/withSlugs", "routes": [ { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-withSlugs/slugs/absoluteSlug.md", }, "path": "/docs/withSlugs/absoluteSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-withSlugs/rootResolvedSlug.md", }, "path": "/docs/withSlugs/hey/rootResolvedSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-withSlugs/rootAbsoluteSlug.md", }, "path": "/docs/withSlugs/rootAbsoluteSlug", "sidebar": "docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-withSlugs/rootRelativeSlug.md", }, "path": "/docs/withSlugs/rootRelativeSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-withSlugs/rootTryToEscapeSlug.md", }, "path": "/docs/withSlugs/rootTryToEscapeSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-withSlugs/slugs/resolvedSlug.md", }, "path": "/docs/withSlugs/slugs/hey/resolvedSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-withSlugs/slugs/relativeSlug.md", }, "path": "/docs/withSlugs/slugs/relativeSlug", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-withSlugs/slugs/tryToEscapeSlug.md", }, "path": "/docs/withSlugs/tryToEscapeSlug", }, ], }, ], }, { "component": "@theme/DocVersionRoot", "exact": false, "modules": { "version": "~docs/version-1-0-1-metadata-prop-e87.json", }, "path": "/docs", "priority": -1, "routes": [ { "component": "@theme/DocRoot", "exact": false, "path": "/docs", "routes": [ { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-1.0.1/hello.md", }, "path": "/docs/", "sidebar": "VersionedSideBarNameDoesNotMatter/docs", }, { "component": "@theme/DocItem", "exact": true, "modules": { "content": "@site/versioned_docs/version-1.0.1/foo/bar.md", }, "path": "/docs/foo/bar", "sidebar": "VersionedSideBarNameDoesNotMatter/docs", }, ], }, ], }, ], }, ] `; exports[`versioned website content: withSlugs version sidebars 1`] = ` { "docs": [ { "collapsed": true, "collapsible": true, "items": [ { "id": "rootAbsoluteSlug", "type": "doc", }, ], "label": "Test", "link": undefined, "type": "category", }, ], } `; exports[`versioned website getPathToWatch 1`] = ` [ "sidebars.json", "i18n/en/docusaurus-plugin-content-docs/current/**/*.{md,mdx}", "docs/**/*.{md,mdx}", "docs/**/_category_.{json,yml,yaml}", "versioned_sidebars/version-1.0.1-sidebars.json", "i18n/en/docusaurus-plugin-content-docs/version-1.0.1/**/*.{md,mdx}", "versioned_docs/version-1.0.1/**/*.{md,mdx}", "versioned_docs/version-1.0.1/**/_category_.{json,yml,yaml}", "versioned_sidebars/version-1.0.0-sidebars.json", "i18n/en/docusaurus-plugin-content-docs/version-1.0.0/**/*.{md,mdx}", "versioned_docs/version-1.0.0/**/*.{md,mdx}", "versioned_docs/version-1.0.0/**/_category_.{json,yml,yaml}", "versioned_sidebars/version-withSlugs-sidebars.json", "i18n/en/docusaurus-plugin-content-docs/version-withSlugs/**/*.{md,mdx}", "versioned_docs/version-withSlugs/**/*.{md,mdx}", "versioned_docs/version-withSlugs/**/_category_.{json,yml,yaml}", ] `;
1,247
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/__tests__/__snapshots__/translations.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`getLoadedContentTranslationFiles returns translation files 1`] = ` [ { "content": { "sidebar.docs.category.Getting started": { "description": "The label for category Getting started in sidebar docs", "message": "Getting started", }, "sidebar.docs.category.Getting started.link.generated-index.description": { "description": "The generated-index page description for category Getting started in sidebar docs", "message": "Getting started index description", }, "sidebar.docs.category.Getting started.link.generated-index.title": { "description": "The generated-index page title for category Getting started in sidebar docs", "message": "Getting started index title", }, "sidebar.docs.doc.Second doc translatable": { "description": "The label for the doc item Second doc translatable in sidebar docs, linking to the doc doc2", "message": "Second doc translatable", }, "sidebar.docs.link.Link label": { "description": "The label for link Link label in sidebar docs, linking to https://facebook.com", "message": "Link label", }, "sidebar.otherSidebar.doc.Fifth doc translatable": { "description": "The label for the doc item Fifth doc translatable in sidebar otherSidebar, linking to the doc doc5", "message": "Fifth doc translatable", }, "version.label": { "description": "The label for version current", "message": "current label", }, }, "path": "current", }, { "content": { "sidebar.docs.category.Getting started": { "description": "The label for category Getting started in sidebar docs", "message": "Getting started", }, "sidebar.docs.category.Getting started.link.generated-index.description": { "description": "The generated-index page description for category Getting started in sidebar docs", "message": "Getting started index description", }, "sidebar.docs.category.Getting started.link.generated-index.title": { "description": "The generated-index page title for category Getting started in sidebar docs", "message": "Getting started index title", }, "sidebar.docs.doc.Second doc translatable": { "description": "The label for the doc item Second doc translatable in sidebar docs, linking to the doc doc2", "message": "Second doc translatable", }, "sidebar.docs.link.Link label": { "description": "The label for link Link label in sidebar docs, linking to https://facebook.com", "message": "Link label", }, "sidebar.otherSidebar.doc.Fifth doc translatable": { "description": "The label for the doc item Fifth doc translatable in sidebar otherSidebar, linking to the doc doc5", "message": "Fifth doc translatable", }, "version.label": { "description": "The label for version 2.0.0", "message": "2.0.0 label", }, }, "path": "version-2.0.0", }, { "content": { "sidebar.docs.category.Getting started": { "description": "The label for category Getting started in sidebar docs", "message": "Getting started", }, "sidebar.docs.category.Getting started.link.generated-index.description": { "description": "The generated-index page description for category Getting started in sidebar docs", "message": "Getting started index description", }, "sidebar.docs.category.Getting started.link.generated-index.title": { "description": "The generated-index page title for category Getting started in sidebar docs", "message": "Getting started index title", }, "sidebar.docs.doc.Second doc translatable": { "description": "The label for the doc item Second doc translatable in sidebar docs, linking to the doc doc2", "message": "Second doc translatable", }, "sidebar.docs.link.Link label": { "description": "The label for link Link label in sidebar docs, linking to https://facebook.com", "message": "Link label", }, "sidebar.otherSidebar.doc.Fifth doc translatable": { "description": "The label for the doc item Fifth doc translatable in sidebar otherSidebar, linking to the doc doc5", "message": "Fifth doc translatable", }, "version.label": { "description": "The label for version 1.0.0", "message": "1.0.0 label", }, }, "path": "version-1.0.0", }, ] `; exports[`translateLoadedContent returns translated loaded content 1`] = ` { "loadedVersions": [ { "badge": true, "banner": null, "className": "", "contentPath": "any", "contentPathLocalized": "any", "docs": [ { "description": "doc1 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc1 title", }, "id": "doc1", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc1 title", "version": "any", }, { "description": "doc2 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc2 title", }, "id": "doc2", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc2 title", "version": "any", }, { "description": "doc3 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc3 title", }, "id": "doc3", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc3 title", "version": "any", }, { "description": "doc4 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc4 title", }, "id": "doc4", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc4 title", "version": "any", }, { "description": "doc5 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc5 title", }, "id": "doc5", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc5 title", "version": "any", }, ], "drafts": [], "isLast": true, "label": "current label (translated)", "path": "/docs/", "routePriority": undefined, "sidebarFilePath": "any", "sidebars": { "docs": [ { "collapsed": false, "collapsible": true, "items": [ { "id": "doc1", "type": "doc", }, { "id": "doc2", "label": "Second doc translatable (translated)", "translatable": true, "type": "doc", }, { "href": "https://facebook.com", "label": "Link label (translated)", "type": "link", }, { "id": "doc1", "type": "ref", }, ], "label": "Getting started (translated)", "link": { "description": "Getting started index description (translated)", "permalink": "/docs/category/getting-started-index-slug", "slug": "/category/getting-started-index-slug", "title": "Getting started index title (translated)", "type": "generated-index", }, "type": "category", }, { "id": "doc3", "type": "doc", }, ], "otherSidebar": [ { "id": "doc4", "type": "doc", }, { "id": "doc5", "label": "Fifth doc translatable (translated)", "translatable": true, "type": "ref", }, ], }, "tagsPath": "/tags/", "versionName": "current", }, { "badge": true, "banner": null, "className": "", "contentPath": "any", "contentPathLocalized": "any", "docs": [ { "description": "doc1 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc1 title", }, "id": "doc1", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc1 title", "version": "any", }, { "description": "doc2 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc2 title", }, "id": "doc2", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc2 title", "version": "any", }, { "description": "doc3 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc3 title", }, "id": "doc3", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc3 title", "version": "any", }, { "description": "doc4 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc4 title", }, "id": "doc4", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc4 title", "version": "any", }, { "description": "doc5 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc5 title", }, "id": "doc5", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc5 title", "version": "any", }, ], "drafts": [], "isLast": true, "label": "2.0.0 label (translated)", "path": "/docs/", "routePriority": undefined, "sidebarFilePath": "any", "sidebars": { "docs": [ { "collapsed": false, "collapsible": true, "items": [ { "id": "doc1", "type": "doc", }, { "id": "doc2", "label": "Second doc translatable (translated)", "translatable": true, "type": "doc", }, { "href": "https://facebook.com", "label": "Link label (translated)", "type": "link", }, { "id": "doc1", "type": "ref", }, ], "label": "Getting started (translated)", "link": { "description": "Getting started index description (translated)", "permalink": "/docs/category/getting-started-index-slug", "slug": "/category/getting-started-index-slug", "title": "Getting started index title (translated)", "type": "generated-index", }, "type": "category", }, { "id": "doc3", "type": "doc", }, ], "otherSidebar": [ { "id": "doc4", "type": "doc", }, { "id": "doc5", "label": "Fifth doc translatable (translated)", "translatable": true, "type": "ref", }, ], }, "tagsPath": "/tags/", "versionName": "2.0.0", }, { "badge": true, "banner": null, "className": "", "contentPath": "any", "contentPathLocalized": "any", "docs": [ { "description": "doc1 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc1 title", }, "id": "doc1", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc1 title", "version": "any", }, { "description": "doc2 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc2 title", }, "id": "doc2", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc2 title", "version": "any", }, { "description": "doc3 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc3 title", }, "id": "doc3", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc3 title", "version": "any", }, { "description": "doc4 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc4 title", }, "id": "doc4", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc4 title", "version": "any", }, { "description": "doc5 description", "draft": false, "editUrl": "any", "frontMatter": { "sidebar_label": "doc5 title", }, "id": "doc5", "lastUpdatedAt": 0, "lastUpdatedBy": "any", "next": undefined, "permalink": "any", "previous": undefined, "slug": "any", "source": "any", "sourceDirName": "", "tags": [], "title": "doc5 title", "version": "any", }, ], "drafts": [], "isLast": true, "label": "1.0.0 label (translated)", "path": "/docs/", "routePriority": undefined, "sidebarFilePath": "any", "sidebars": { "docs": [ { "collapsed": false, "collapsible": true, "items": [ { "id": "doc1", "type": "doc", }, { "id": "doc2", "label": "Second doc translatable (translated)", "translatable": true, "type": "doc", }, { "href": "https://facebook.com", "label": "Link label (translated)", "type": "link", }, { "id": "doc1", "type": "ref", }, ], "label": "Getting started (translated)", "link": { "description": "Getting started index description (translated)", "permalink": "/docs/category/getting-started-index-slug", "slug": "/category/getting-started-index-slug", "title": "Getting started index title (translated)", "type": "generated-index", }, "type": "category", }, { "id": "doc3", "type": "doc", }, ], "otherSidebar": [ { "id": "doc4", "type": "doc", }, { "id": "doc5", "label": "Fifth doc translatable (translated)", "translatable": true, "type": "ref", }, ], }, "tagsPath": "/tags/", "versionName": "1.0.0", }, ], } `;
1,250
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/client
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/client/__tests__/docsClientUtils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import _ from 'lodash'; import { getActivePlugin, getLatestVersion, getActiveDocContext, getActiveVersion, getDocVersionSuggestions, } from '../docsClientUtils'; import type { GlobalPluginData, GlobalVersion, ActivePlugin, GlobalDoc, } from '@docusaurus/plugin-content-docs/client'; describe('docsClientUtils', () => { it('getActivePlugin', () => { const data: {[key: string]: GlobalPluginData} = { pluginIosId: { path: '/ios', versions: [], breadcrumbs: true, }, pluginAndroidId: { path: '/android', versions: [], breadcrumbs: true, }, }; expect(getActivePlugin(data, '/')).toBeUndefined(); expect(getActivePlugin(data, '/xyz')).toBeUndefined(); expect(() => getActivePlugin(data, '/', {failfast: true}), ).toThrowErrorMatchingInlineSnapshot( `"Can't find active docs plugin for "/" pathname, while it was expected to be found. Maybe you tried to use a docs feature that can only be used on a docs-related page? Existing docs plugin paths are: /ios, /android"`, ); expect(() => getActivePlugin(data, '/xyz', {failfast: true}), ).toThrowErrorMatchingInlineSnapshot( `"Can't find active docs plugin for "/xyz" pathname, while it was expected to be found. Maybe you tried to use a docs feature that can only be used on a docs-related page? Existing docs plugin paths are: /ios, /android"`, ); const activePluginIos: ActivePlugin = { pluginId: 'pluginIosId', pluginData: data.pluginIosId!, }; expect(getActivePlugin(data, '/ios')).toEqual(activePluginIos); expect(getActivePlugin(data, '/ios/')).toEqual(activePluginIos); expect(getActivePlugin(data, '/ios/abc/def')).toEqual(activePluginIos); const activePluginAndroid: ActivePlugin = { pluginId: 'pluginAndroidId', pluginData: data.pluginAndroidId!, }; expect(getActivePlugin(data, '/android')).toEqual(activePluginAndroid); expect(getActivePlugin(data, '/android/')).toEqual(activePluginAndroid); expect(getActivePlugin(data, '/android/ijk')).toEqual(activePluginAndroid); // https://github.com/facebook/docusaurus/issues/6434 const onePluginAtRoot: {[key: string]: GlobalPluginData} = { pluginIosId: { path: '/', versions: [], breadcrumbs: true, }, pluginAndroidId: { path: '/android', versions: [], breadcrumbs: true, }, }; expect(getActivePlugin(onePluginAtRoot, '/android/foo')!.pluginId).toBe( 'pluginAndroidId', ); const onePluginAtRootReversed: {[key: string]: GlobalPluginData} = { pluginAndroidId: { path: '/android', versions: [], breadcrumbs: true, }, pluginIosId: { path: '/', versions: [], breadcrumbs: true, }, }; expect( getActivePlugin(onePluginAtRootReversed, '/android/foo')!.pluginId, ).toBe('pluginAndroidId'); }); it('getLatestVersion', () => { const versions: GlobalVersion[] = [ { name: 'version1', label: 'version1', path: '/???', isLast: false, docs: [], mainDocId: '???', draftIds: [], }, { name: 'version2', label: 'version2', path: '/???', isLast: true, docs: [], mainDocId: '???', draftIds: [], }, { name: 'version3', label: 'version3', path: '/???', isLast: false, docs: [], mainDocId: '???', draftIds: [], }, ]; expect( getLatestVersion({ path: '???', versions, breadcrumbs: true, }), ).toEqual(versions[1]); }); it('getActiveVersion', () => { const data: GlobalPluginData = { path: 'docs', versions: [ { name: 'next', label: 'next', isLast: false, path: '/docs/next', docs: [], mainDocId: '???', draftIds: [], }, { name: 'version2', label: 'version2', isLast: true, path: '/docs', docs: [], mainDocId: '???', draftIds: [], }, { name: 'version1', label: 'version1', isLast: false, path: '/docs/version1', docs: [], mainDocId: '???', draftIds: [], }, ], breadcrumbs: true, }; expect(getActiveVersion(data, '/someUnknownPath')).toBeUndefined(); expect(getActiveVersion(data, '/docs/next')?.name).toBe('next'); expect(getActiveVersion(data, '/docs/next/')?.name).toBe('next'); expect(getActiveVersion(data, '/docs/next/someDoc')?.name).toBe('next'); expect(getActiveVersion(data, '/docs')?.name).toBe('version2'); expect(getActiveVersion(data, '/docs/')?.name).toBe('version2'); expect(getActiveVersion(data, '/docs/someDoc')?.name).toBe('version2'); expect(getActiveVersion(data, '/docs/version1')?.name).toBe('version1'); expect(getActiveVersion(data, '/docs/version1')?.name).toBe('version1'); expect(getActiveVersion(data, '/docs/version1/someDoc')?.name).toBe( 'version1', ); }); it('getActiveDocContext', () => { const versionNext: GlobalVersion = { name: 'next', label: 'next', path: '/docs/next', isLast: false, mainDocId: 'doc1', docs: [ { id: 'doc1', path: '/docs/next/', }, { id: 'doc2', path: '/docs/next/doc2', }, ] as GlobalDoc[], draftIds: [], }; const version2: GlobalVersion = { name: 'version2', label: 'version2', isLast: true, path: '/docs', mainDocId: 'doc1', docs: [ { id: 'doc1', path: '/docs/', }, { id: 'doc2', path: '/docs/doc2', }, ] as GlobalDoc[], draftIds: [], }; const version1: GlobalVersion = { name: 'version1', label: 'version1', path: '/docs/version1', isLast: false, mainDocId: 'doc1', docs: [ { id: 'doc1', path: '/docs/version1/', }, ] as GlobalDoc[], draftIds: [], }; // Shuffle, because order shouldn't matter const versions: GlobalVersion[] = _.shuffle([ versionNext, version2, version1, ]); const data: GlobalPluginData = { path: 'docs', versions, breadcrumbs: true, }; expect(getActiveDocContext(data, '/doesNotExist')).toEqual({ activeVersion: undefined, activeDoc: undefined, alternateDocVersions: {}, }); expect(getActiveDocContext(data, '/docs/next/doesNotExist')).toEqual({ activeVersion: versionNext, activeDoc: undefined, alternateDocVersions: {}, }); expect(getActiveDocContext(data, '/docs/next')).toEqual({ activeVersion: versionNext, activeDoc: versionNext.docs[0], alternateDocVersions: { next: versionNext.docs[0], version2: version2.docs[0], version1: version1.docs[0], }, }); expect(getActiveDocContext(data, '/docs/next/doc2')).toEqual({ activeVersion: versionNext, activeDoc: versionNext.docs[1], alternateDocVersions: { next: versionNext.docs[1], version2: version2.docs[1], version1: undefined, }, }); expect(getActiveDocContext(data, '/docs/')).toEqual({ activeVersion: version2, activeDoc: version2.docs[0], alternateDocVersions: { next: versionNext.docs[0], version2: version2.docs[0], version1: version1.docs[0], }, }); expect(getActiveDocContext(data, '/docs/doc2')).toEqual({ activeVersion: version2, activeDoc: version2.docs[1], alternateDocVersions: { next: versionNext.docs[1], version2: version2.docs[1], version1: undefined, }, }); expect(getActiveDocContext(data, '/docs/version1')).toEqual({ activeVersion: version1, activeDoc: version1.docs[0], alternateDocVersions: { next: versionNext.docs[0], version2: version2.docs[0], version1: version1.docs[0], }, }); expect(getActiveDocContext(data, '/docs/version1/doc2')).toEqual({ activeVersion: version1, activeDoc: undefined, alternateDocVersions: {}, }); }); it('getDocVersionSuggestions', () => { const versionNext: GlobalVersion = { name: 'next', label: 'next', isLast: false, path: '/docs/next', mainDocId: 'doc1', docs: [ { id: 'doc1', path: '/docs/next/', }, { id: 'doc2', path: '/docs/next/doc2', }, ] as GlobalDoc[], draftIds: [], }; const version2: GlobalVersion = { name: 'version2', label: 'version2', path: '/docs', isLast: true, mainDocId: 'doc1', docs: [ { id: 'doc1', path: '/docs/', }, { id: 'doc2', path: '/docs/doc2', }, ] as GlobalDoc[], draftIds: [], }; const version1: GlobalVersion = { name: 'version1', label: 'version1', isLast: false, path: '/docs/version1', mainDocId: 'doc1', docs: [ { id: 'doc1', path: '/docs/version1/', }, ] as GlobalDoc[], draftIds: [], }; // Shuffle, because order shouldn't matter const versions: GlobalVersion[] = _.shuffle([ versionNext, version2, version1, ]); const data: GlobalPluginData = { path: 'docs', versions, breadcrumbs: true, }; expect(getDocVersionSuggestions(data, '/doesNotExist')).toEqual({ latestDocSuggestion: undefined, latestVersionSuggestion: version2, }); expect(getDocVersionSuggestions(data, '/docs/next')).toEqual({ latestDocSuggestion: version2.docs[0], latestVersionSuggestion: version2, }); expect(getDocVersionSuggestions(data, '/docs/next/doc2')).toEqual({ latestDocSuggestion: version2.docs[1], latestVersionSuggestion: version2, }); expect(getDocVersionSuggestions(data, '/docs/')).toEqual({ latestDocSuggestion: version2.docs[0], latestVersionSuggestion: version2, }); expect(getDocVersionSuggestions(data, '/docs/doc2')).toEqual({ latestDocSuggestion: version2.docs[1], latestVersionSuggestion: version2, }); expect(getDocVersionSuggestions(data, '/docs/version1/')).toEqual({ latestDocSuggestion: version2.docs[0], latestVersionSuggestion: version2, }); expect(getDocVersionSuggestions(data, '/docs/version1/doc2')).toEqual({ latestDocSuggestion: undefined, // Because /docs/version1/doc2 does not exist latestVersionSuggestion: version2, }); }); });
1,253
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/markdown
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/markdown/__tests__/linkify.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import fs from 'fs-extra'; import path from 'path'; import {linkify} from '../linkify'; import {VERSIONED_DOCS_DIR, CURRENT_VERSION_NAME} from '../../constants'; import type { DocsMarkdownOption, SourceToPermalink, DocBrokenMarkdownLink, } from '../../types'; import type {VersionMetadata} from '@docusaurus/plugin-content-docs'; function createFakeVersion({ versionName, contentPath, contentPathLocalized, }: { versionName: string; contentPath: string; contentPathLocalized: string; }): VersionMetadata { return { versionName, label: 'Any', path: 'any', badge: true, banner: null, tagsPath: '/tags/', className: '', contentPath, contentPathLocalized, sidebarFilePath: 'any', routePriority: undefined, isLast: false, }; } const siteDir = path.join(__dirname, '__fixtures__'); const versionCurrent = createFakeVersion({ versionName: CURRENT_VERSION_NAME, contentPath: path.join(siteDir, 'docs'), contentPathLocalized: path.join( siteDir, 'i18n', 'fr', 'docusaurus-plugin-content-docs', CURRENT_VERSION_NAME, ), }); const version100 = createFakeVersion({ versionName: '1.0.0', contentPath: path.join(siteDir, VERSIONED_DOCS_DIR, 'version-1.0.0'), contentPathLocalized: path.join( siteDir, 'i18n', 'fr', 'docusaurus-plugin-content-docs', 'version-1.0.0', ), }); const sourceToPermalink: SourceToPermalink = { '@site/docs/doc1.md': '/docs/doc1', '@site/docs/doc2.md': '/docs/doc2', '@site/docs/subdir/doc3.md': '/docs/subdir/doc3', '@site/docs/doc4.md': '/docs/doc4', '@site/versioned_docs/version-1.0.0/doc2.md': '/docs/1.0.0/doc2', '@site/versioned_docs/version-1.0.0/subdir/doc1.md': '/docs/1.0.0/subdir/doc1', '@site/i18n/fr/docusaurus-plugin-content-docs/current/doc-localized.md': '/fr/doc-localized', '@site/docs/doc-localized.md': '/doc-localized', }; function createMarkdownOptions( options?: Partial<DocsMarkdownOption>, ): DocsMarkdownOption { return { sourceToPermalink, onBrokenMarkdownLink: () => {}, versionsMetadata: [versionCurrent, version100], siteDir, ...options, }; } const transform = async ( filepath: string, options?: Partial<DocsMarkdownOption>, ) => { const markdownOptions = createMarkdownOptions(options); const content = await fs.readFile(filepath, 'utf-8'); const transformedContent = linkify(content, filepath, markdownOptions); return [content, transformedContent]; }; describe('linkify', () => { it('transforms nothing with no links', async () => { const doc1 = path.join(versionCurrent.contentPath, 'doc1.md'); const [content, transformedContent] = await transform(doc1); expect(transformedContent).toMatchSnapshot(); expect(content).toEqual(transformedContent); }); it('transforms to correct links', async () => { const doc2 = path.join(versionCurrent.contentPath, 'doc2.md'); const [content, transformedContent] = await transform(doc2); expect(transformedContent).toMatchSnapshot(); expect(transformedContent).toContain('](/docs/doc1'); expect(transformedContent).toContain('](/docs/doc2'); expect(transformedContent).toContain('](/docs/subdir/doc3'); expect(transformedContent).toContain('](/fr/doc-localized'); expect(transformedContent).not.toContain('](doc1.md)'); expect(transformedContent).not.toContain('](./doc2.md)'); expect(transformedContent).not.toContain('](subdir/doc3.md)'); expect(transformedContent).not.toContain('](/doc-localized'); expect(content).not.toEqual(transformedContent); }); it('transforms relative links', async () => { const doc3 = path.join(versionCurrent.contentPath, 'subdir', 'doc3.md'); const [content, transformedContent] = await transform(doc3); expect(transformedContent).toMatchSnapshot(); expect(transformedContent).toContain('](/docs/doc2'); expect(transformedContent).not.toContain('](../doc2.md)'); expect(content).not.toEqual(transformedContent); }); it('transforms reference links', async () => { const doc4 = path.join(versionCurrent.contentPath, 'doc4.md'); const [content, transformedContent] = await transform(doc4); expect(transformedContent).toMatchSnapshot(); expect(transformedContent).toContain('[doc1]: /docs/doc1'); expect(transformedContent).toContain('[doc2]: /docs/doc2'); expect(transformedContent).not.toContain('[doc1]: doc1.md'); expect(transformedContent).not.toContain('[doc2]: ./doc2.md'); expect(content).not.toEqual(transformedContent); }); it('reports broken markdown links', async () => { const doc5 = path.join(versionCurrent.contentPath, 'doc5.md'); const onBrokenMarkdownLink = jest.fn(); const [content, transformedContent] = await transform(doc5, { onBrokenMarkdownLink, }); expect(transformedContent).toEqual(content); expect(onBrokenMarkdownLink).toHaveBeenCalledTimes(4); expect(onBrokenMarkdownLink).toHaveBeenNthCalledWith(1, { filePath: doc5, link: 'docNotExist1.md', contentPaths: versionCurrent, } as DocBrokenMarkdownLink); expect(onBrokenMarkdownLink).toHaveBeenNthCalledWith(2, { filePath: doc5, link: './docNotExist2.mdx', contentPaths: versionCurrent, } as DocBrokenMarkdownLink); expect(onBrokenMarkdownLink).toHaveBeenNthCalledWith(3, { filePath: doc5, link: '../docNotExist3.mdx', contentPaths: versionCurrent, } as DocBrokenMarkdownLink); expect(onBrokenMarkdownLink).toHaveBeenNthCalledWith(4, { filePath: doc5, link: './subdir/docNotExist4.md', contentPaths: versionCurrent, } as DocBrokenMarkdownLink); }); it('transforms absolute links in versioned docs', async () => { const doc2 = path.join(version100.contentPath, 'doc2.md'); const [content, transformedContent] = await transform(doc2); expect(transformedContent).toMatchSnapshot(); expect(transformedContent).toContain('](/docs/1.0.0/subdir/doc1'); expect(transformedContent).toContain('](/docs/1.0.0/doc2#existing-docs'); expect(transformedContent).not.toContain('](subdir/doc1.md)'); expect(transformedContent).not.toContain('](doc2.md#existing-docs)'); expect(content).not.toEqual(transformedContent); }); it('transforms relative links in versioned docs', async () => { const doc1 = path.join(version100.contentPath, 'subdir', 'doc1.md'); const [content, transformedContent] = await transform(doc1); expect(transformedContent).toMatchSnapshot(); expect(transformedContent).toContain('](/docs/1.0.0/doc2'); expect(transformedContent).not.toContain('](../doc2.md)'); expect(content).not.toEqual(transformedContent); }); // See comment in linkify.ts it('throws for file outside version', async () => { const doc1 = path.join(__dirname, '__fixtures__/outside/doc1.md'); await expect(() => transform(doc1), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Unexpected error: Markdown file at "<PROJECT_ROOT>/packages/docusaurus-plugin-content-docs/src/markdown/__tests__/__fixtures__/outside/doc1.md" does not belong to any docs version!"`, ); }); });
1,263
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/markdown/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/markdown/__tests__/__snapshots__/linkify.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`linkify transforms absolute links in versioned docs 1`] = ` "### Existing Docs - [doc1](/docs/1.0.0/subdir/doc1) ### With hash - [doc2](/docs/1.0.0/doc2#existing-docs) " `; exports[`linkify transforms nothing with no links 1`] = ` "# Don't transform any link here ![image1](assets/image1.png) # Don't replace inside fenced codeblock \`\`\`md ![doc4](doc4.md) \`\`\` ### Non-existing Docs - [hahaha](hahaha.md) " `; exports[`linkify transforms reference links 1`] = ` "### Existing Docs - [doc1][doc1] - [doc2][doc2] ## Repeating Docs - [doc1][doc1] - [doc2][doc2] ## Do not replace this \`\`\`md ![image1][image1] \`\`\` [doc1]: /docs/doc1 [doc2]: /docs/doc2 [image1]: assets/image1.png " `; exports[`linkify transforms relative links 1`] = ` "### Relative linking - [doc1](/docs/doc2) " `; exports[`linkify transforms relative links in versioned docs 1`] = ` "### Relative linking - [doc1](/docs/1.0.0/doc2) " `; exports[`linkify transforms to correct links 1`] = ` "### Existing Docs - [doc1](/docs/doc1) - [doc2](/docs/doc2) - [doc3](/docs/subdir/doc3) ## Repeating Docs - [doc1](/docs/doc1) - [doc2](/docs/doc2) - [doc-localized](/fr/doc-localized) " `;
1,273
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/generator.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import {DefaultSidebarItemsGenerator} from '../generator'; import {DefaultNumberPrefixParser} from '../../numberPrefix'; import {isCategoryIndex} from '../../docs'; import type {SidebarItemsGenerator} from '../types'; describe('DefaultSidebarItemsGenerator', () => { function testDefaultSidebarItemsGenerator( params: Partial<Parameters<SidebarItemsGenerator>[0]>, ) { return DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, isCategoryIndex, item: { type: 'autogenerated', dirName: '.', }, version: { versionName: 'current', contentPath: 'docs', }, docs: [], categoriesMetadata: {}, ...params, }); } it('generates empty sidebar slice when no docs and emit a warning', async () => { const consoleWarn = jest.spyOn(console, 'warn'); const sidebarSlice = await testDefaultSidebarItemsGenerator({ docs: [], }); expect(sidebarSlice).toEqual([]); expect(consoleWarn).toHaveBeenCalledWith( expect.stringMatching( /.*\[WARNING\].* No docs found in [^.]*\..*: can't auto-generate a sidebar\..*/, ), ); }); it('generates simple flat sidebar', async () => { const sidebarSlice = await DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, item: { type: 'autogenerated', dirName: '.', }, version: { versionName: 'current', contentPath: '', }, docs: [ { id: 'doc1', source: 'doc1.md', sourceDirName: '.', sidebarPosition: 2, frontMatter: { sidebar_label: 'doc1 sidebar label', sidebar_custom_props: {custom: 'prop'}, }, title: '', }, { id: 'doc2', source: 'doc2.md', sourceDirName: '.', sidebarPosition: 3, frontMatter: {}, title: '', }, { id: 'doc3', source: 'doc3.md', sourceDirName: '.', sidebarPosition: 1, frontMatter: {}, title: '', }, { id: 'doc4', source: 'doc4.md', sourceDirName: '.', sidebarPosition: 1.5, frontMatter: {}, title: '', }, { id: 'doc5', source: 'doc5.md', sourceDirName: '.', sidebarPosition: undefined, frontMatter: {}, title: '', }, ], isCategoryIndex: () => false, categoriesMetadata: {}, }); expect(sidebarSlice).toMatchSnapshot(); }); it('generates complex nested sidebar', async () => { const sidebarSlice = await DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, isCategoryIndex, item: { type: 'autogenerated', dirName: '.', }, version: { versionName: 'current', contentPath: '', }, categoriesMetadata: { '02-Guides': { collapsed: false, customProps: { description: 'foo', }, }, '02-Guides/01-SubGuides': { label: 'SubGuides (metadata file label)', link: { type: 'generated-index', slug: 'subGuides-generated-index-slug', title: 'subGuides-title', description: 'subGuides-description', }, }, }, docs: [ { id: 'intro', source: '@site/docs/intro.md', sourceDirName: '.', sidebarPosition: 0, frontMatter: {}, title: '', }, { id: 'tutorials-index', source: '@site/docs/01-Tutorials/index.md', sourceDirName: '01-Tutorials', sidebarPosition: 2, frontMatter: {}, title: 'Tutorials', }, { id: 'tutorial2', source: '@site/docs/01-Tutorials/tutorial2.md', sourceDirName: '01-Tutorials', sidebarPosition: 2, frontMatter: {}, title: '', }, { id: 'tutorial1', source: '@site/docs/01-Tutorials/tutorial1.md', sourceDirName: '01-Tutorials', sidebarPosition: 1, frontMatter: {}, title: '', }, { id: 'guides-index', source: '@site/docs/02-Guides/02-Guides.md', // TODO should we allow to just use "Guides.md" to have an index? sourceDirName: '02-Guides', frontMatter: {}, title: 'Guides', }, { id: 'guide2', source: '@site/docs/02-Guides/guide2.md', sourceDirName: '02-Guides', sidebarPosition: 2, frontMatter: {}, title: '', }, { id: 'guide1', source: '@site/docs/02-Guides/guide1.md', sourceDirName: '02-Guides', sidebarPosition: 0, frontMatter: { sidebar_class_name: 'foo', }, title: '', }, { id: 'nested-guide', source: '@site/docs/02-Guides/01-SubGuides/nested-guide.md', sourceDirName: '02-Guides/01-SubGuides', sidebarPosition: undefined, frontMatter: {}, title: '', }, { id: 'end', source: '@site/docs/end.md', sourceDirName: '.', sidebarPosition: 3, frontMatter: {}, title: '', }, ], }); expect(sidebarSlice).toMatchSnapshot(); }); it('generates subfolder sidebar', async () => { // Ensure that category metadata file is correctly read // fix edge case found in https://github.com/facebook/docusaurus/issues/4638 const sidebarSlice = await DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, isCategoryIndex, item: { type: 'autogenerated', dirName: 'subfolder/subsubfolder', }, version: { versionName: 'current', contentPath: '', }, categoriesMetadata: { 'subfolder/subsubfolder/subsubsubfolder2': { position: 2, label: 'subsubsubfolder2 (_category_.yml label)', className: 'bar', }, 'subfolder/subsubfolder/subsubsubfolder3': { position: 1, // This item's label is defined from the index doc instead link: { type: 'doc', id: 'doc1', // This is a "fully-qualified" ID that can't be found locally }, }, }, docs: [ { id: 'doc1', source: 'doc1.md', sourceDirName: 'subfolder/subsubfolder', title: 'Subsubsubfolder category label', sidebarPosition: undefined, frontMatter: {}, }, { id: 'doc2', source: 'doc2.md', sourceDirName: 'subfolder', sidebarPosition: undefined, frontMatter: {}, title: '', }, { id: 'doc3', source: 'doc3.md', sourceDirName: '.', sidebarPosition: undefined, frontMatter: {}, title: '', }, { id: 'doc4', source: 'doc4.md', sourceDirName: 'subfolder/subsubfolder', sidebarPosition: undefined, frontMatter: {}, title: '', }, { id: 'doc5', source: 'doc5.md', sourceDirName: 'subfolder/subsubfolder/subsubsubfolder', sidebarPosition: undefined, frontMatter: {}, title: '', }, { id: 'doc6', source: 'doc6.md', sourceDirName: 'subfolder/subsubfolder/subsubsubfolder2', sidebarPosition: undefined, frontMatter: {}, title: '', }, { id: 'doc7', source: 'doc7.md', sourceDirName: 'subfolder/subsubfolder/subsubsubfolder3', sidebarPosition: 2, frontMatter: {}, title: '', }, { id: 'doc8', source: 'doc8.md', sourceDirName: 'subfolder/subsubfolder/subsubsubfolder3', sidebarPosition: 1, frontMatter: {}, title: '', }, ], }); expect(sidebarSlice).toMatchSnapshot(); }); it('uses explicit link over the index/readme.{md,mdx} naming convention', async () => { const sidebarSlice = await DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, item: { type: 'autogenerated', dirName: '.', }, version: { versionName: 'current', contentPath: '', }, categoriesMetadata: { Category: { label: 'Category label', link: { type: 'doc', id: 'doc3', // Using a "local doc id" ("doc1" instead of "parent/doc1") on purpose }, }, Category2: { label: 'Category 2 label', link: null, }, }, docs: [ { id: 'parent/doc1', source: '@site/docs/Category/index.md', sourceDirName: 'Category', frontMatter: {}, title: '', }, { id: 'parent/doc2', source: '@site/docs/Category/doc2.md', sourceDirName: 'Category', frontMatter: {}, title: '', }, { id: 'parent/doc3', source: '@site/docs/Category/doc3.md', sourceDirName: 'Category', frontMatter: {}, title: '', }, { id: 'parent/doc4', source: '@site/docs/Category2/doc1.md', sourceDirName: 'Category2', frontMatter: {}, title: '', }, { id: 'parent/doc5', source: '@site/docs/Category2/index.md', sourceDirName: 'Category2', frontMatter: {}, title: '', }, { id: 'parent/doc6', source: '@site/docs/Category2/doc3.md', sourceDirName: 'Category2', frontMatter: {}, title: '', }, ], isCategoryIndex: () => false, }); expect(sidebarSlice).toMatchSnapshot(); }); it('respects custom isCategoryIndex', async () => { const sidebarSlice = await DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, isCategoryIndex({fileName, directories}) { return ( fileName.replace( `${DefaultNumberPrefixParser( directories[0]!, ).filename.toLowerCase()}-`, '', ) === 'index' ); }, item: { type: 'autogenerated', dirName: '.', }, version: { versionName: 'current', contentPath: '', }, categoriesMetadata: {}, docs: [ { id: 'intro', source: '@site/docs/intro.md', sourceDirName: '.', sidebarPosition: 0, frontMatter: {}, title: '', }, { id: 'tutorials-index', source: '@site/docs/01-Tutorials/tutorials-index.md', sourceDirName: '01-Tutorials', sidebarPosition: 2, frontMatter: {}, title: 'Tutorials', }, { id: 'tutorial2', source: '@site/docs/01-Tutorials/tutorial2.md', sourceDirName: '01-Tutorials', sidebarPosition: 2, frontMatter: {}, title: '', }, { id: 'tutorial1', source: '@site/docs/01-Tutorials/tutorial1.md', sourceDirName: '01-Tutorials', sidebarPosition: 1, frontMatter: {}, title: '', }, { id: 'not-guides-index', source: '@site/docs/02-Guides/README.md', sourceDirName: '02-Guides', frontMatter: {}, title: 'Guides', }, { id: 'guide2', source: '@site/docs/02-Guides/guide2.md', sourceDirName: '02-Guides', sidebarPosition: 2, frontMatter: {}, title: 'guide2', }, { id: 'guide1', source: '@site/docs/02-Guides/guide1.md', sourceDirName: '02-Guides', sidebarPosition: 1, frontMatter: { sidebar_class_name: 'foo', }, title: '', }, ], }); expect(sidebarSlice).toMatchSnapshot(); }); it('throws for unknown index link', () => { const generateSidebar = () => DefaultSidebarItemsGenerator({ numberPrefixParser: DefaultNumberPrefixParser, isCategoryIndex, item: { type: 'autogenerated', dirName: '.', }, version: { versionName: 'current', contentPath: '', }, categoriesMetadata: { category: { link: { type: 'doc', id: 'foo', }, }, }, docs: [ { id: 'intro', source: '@site/docs/category/intro.md', sourceDirName: 'category', frontMatter: {}, title: '', }, ], }); expect(() => generateSidebar()).toThrowErrorMatchingInlineSnapshot(` "Can't find any doc with ID foo. Available doc IDs: - intro" `); }); });
1,274
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/index.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import path from 'path'; import {createSlugger} from '@docusaurus/utils'; import {loadSidebars, DisabledSidebars} from '../index'; import {DefaultSidebarItemsGenerator} from '../generator'; import type {SidebarProcessorParams} from '../types'; import type { DocMetadata, VersionMetadata, } from '@docusaurus/plugin-content-docs'; describe('loadSidebars', () => { const fixtureDir = path.join(__dirname, '__fixtures__', 'sidebars'); const params: SidebarProcessorParams = { sidebarItemsGenerator: DefaultSidebarItemsGenerator, numberPrefixParser: (filename) => ({filename}), docs: [ { source: '@site/docs/foo/bar.md', sourceDirName: 'foo', id: 'bar', frontMatter: {}, }, ] as DocMetadata[], drafts: [], version: { path: 'version', contentPath: path.join(fixtureDir, 'docs'), contentPathLocalized: path.join(fixtureDir, 'docs'), } as VersionMetadata, categoryLabelSlugger: {slug: (v) => v}, sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: true}, }; it('sidebars with known sidebar item type', async () => { const sidebarPath = path.join(fixtureDir, 'sidebars.json'); const result = await loadSidebars(sidebarPath, params); expect(result).toMatchSnapshot(); }); it('sidebars with some draft items', async () => { const sidebarPath = path.join(fixtureDir, 'sidebars.json'); const paramsWithDrafts: SidebarProcessorParams = { ...params, drafts: [{id: 'foo/baz'} as DocMetadata, {id: 'hello'} as DocMetadata], }; const result = await loadSidebars(sidebarPath, paramsWithDrafts); expect(result).toMatchSnapshot(); }); it('sidebars with deep level of category', async () => { const sidebarPath = path.join(fixtureDir, 'sidebars-category.js'); const result = await loadSidebars(sidebarPath, params); expect(result).toMatchSnapshot(); }); it('sidebars shorthand and longhand lead to exact same sidebar', async () => { const sidebarPath1 = path.join(fixtureDir, 'sidebars-category.js'); const sidebarPath2 = path.join( fixtureDir, 'sidebars-category-shorthand.js', ); const sidebar1 = await loadSidebars(sidebarPath1, params); const sidebar2 = await loadSidebars(sidebarPath2, params); expect(sidebar1).toEqual(sidebar2); }); it('sidebars with category but category.items is not an array', async () => { const sidebarPath = path.join( fixtureDir, 'sidebars-category-wrong-items.json', ); await expect(() => loadSidebars(sidebarPath, params), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Invalid sidebar items collection \`"doc1"\` in \`items\` of the category Category Label: it must either be an array of sidebar items or a shorthand notation (which doesn't contain a \`type\` property). See https://docusaurus.io/docs/sidebar/items for all valid syntaxes."`, ); }); it('sidebars with first level not a category', async () => { const sidebarPath = path.join( fixtureDir, 'sidebars-first-level-not-category.js', ); const result = await loadSidebars(sidebarPath, params); expect(result).toMatchSnapshot(); }); it('sidebars link', async () => { const sidebarPath = path.join(fixtureDir, 'sidebars-link.json'); const result = await loadSidebars(sidebarPath, params); expect(result).toMatchSnapshot(); }); it('nonexistent path', async () => { await expect(loadSidebars('bad/path', params)).resolves.toEqual( DisabledSidebars, ); }); it('undefined path', async () => { await expect(loadSidebars(undefined, params)).resolves.toMatchSnapshot(); }); it('literal false path', async () => { await expect(loadSidebars(false, params)).resolves.toEqual( DisabledSidebars, ); }); it('sidebars with category.collapsed property', async () => { const sidebarPath = path.join(fixtureDir, 'sidebars-collapsed.json'); const result = await loadSidebars(sidebarPath, params); expect(result).toMatchSnapshot(); }); it('sidebars with category.collapsed property at first level', async () => { const sidebarPath = path.join( fixtureDir, 'sidebars-collapsed-first-level.json', ); const result = await loadSidebars(sidebarPath, params); expect(result).toMatchSnapshot(); }); it('loads sidebars with index-only categories', async () => { const sidebarPath = path.join(fixtureDir, 'sidebars-category-index.json'); const result = await loadSidebars(sidebarPath, { ...params, docs: [ { id: 'tutorials/tutorial-basics', source: '@site/docs/tutorials/tutorial-basics/index.md', sourceDirName: 'tutorials/tutorial-basics', frontMatter: {}, }, ] as DocMetadata[], }); expect(result).toMatchSnapshot(); }); it('loads sidebars with interspersed draft items', async () => { const sidebarPath = path.join(fixtureDir, 'sidebars-drafts.json'); const result = await loadSidebars(sidebarPath, { ...params, drafts: [{id: 'draft1'}, {id: 'draft2'}, {id: 'draft3'}] as DocMetadata[], categoryLabelSlugger: createSlugger(), }); expect(result).toMatchSnapshot(); }); it('duplicate category metadata files', async () => { const sidebarPath = path.join( fixtureDir, 'sidebars-collapsed-first-level.json', ); const consoleWarnMock = jest .spyOn(console, 'warn') .mockImplementation(() => {}); const consoleErrorMock = jest .spyOn(console, 'error') .mockImplementation(() => {}); await expect(() => loadSidebars(sidebarPath, { ...params, version: { contentPath: path.join(fixtureDir, 'invalid-docs'), contentPathLocalized: path.join(fixtureDir, 'invalid-docs'), } as VersionMetadata, }), ).rejects.toThrowErrorMatchingInlineSnapshot(`""foo" is not allowed"`); expect(consoleWarnMock).toHaveBeenCalledWith( expect.stringMatching( /.*\[WARNING\].* There are more than one category metadata files for .*foo.*: foo\/_category_.json, foo\/_category_.yml. The behavior is undetermined./, ), ); expect(consoleErrorMock).toHaveBeenCalledWith( expect.stringMatching( /.*\[ERROR\].* The docs sidebar category metadata file .*foo\/_category_.json.* looks invalid!/, ), ); }); });
1,275
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/normalization.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {normalizeSidebars} from '../normalization'; describe('normalization', () => { it('normalizes shorthands', () => { expect( normalizeSidebars({ sidebar: { Category: ['doc1', 'doc2'], 'Category 2': { 'Subcategory 1': ['doc3', 'doc4'], 'Subcategory 2': ['doc5', 'doc6'], }, }, }), ).toMatchSnapshot(); expect( normalizeSidebars({ sidebar: [ { type: 'link', label: 'Google', href: 'https://google.com', }, { 'Category 1': ['doc1', 'doc2'], 'Category 2': ['doc3', 'doc4'], }, ], }), ).toMatchSnapshot(); }); it('rejects some invalid cases', () => { expect(() => normalizeSidebars({ sidebar: { // @ts-expect-error: test Category: {type: 'autogenerated', dirName: 'foo'}, // @ts-expect-error: test Category2: {type: 'autogenerated', dirName: 'bar'}, }, }), ).toThrowErrorMatchingInlineSnapshot( `"Invalid sidebar items collection \`{"type":"autogenerated","dirName":"foo"}\` in \`items\` of the category Category: it must either be an array of sidebar items or a shorthand notation (which doesn't contain a \`type\` property). See https://docusaurus.io/docs/sidebar/items for all valid syntaxes."`, ); expect(() => normalizeSidebars({ sidebar: [ 'foo', { Category: { // @ts-expect-error: test type: 'category', items: ['bar', 'baz'], }, }, ], }), ).toThrowErrorMatchingInlineSnapshot( `"Invalid sidebar items collection \`{"type":"category","items":["bar","baz"]}\` in \`items\` of the category Category: it must either be an array of sidebar items or a shorthand notation (which doesn't contain a \`type\` property). See https://docusaurus.io/docs/sidebar/items for all valid syntaxes."`, ); expect(() => normalizeSidebars({ sidebar: [ 'foo', { // @ts-expect-error: test Category: 'bar', }, ], }), ).toThrowErrorMatchingInlineSnapshot( `"Invalid sidebar items collection \`"bar"\` in \`items\` of the category Category: it must either be an array of sidebar items or a shorthand notation (which doesn't contain a \`type\` property). See https://docusaurus.io/docs/sidebar/items for all valid syntaxes."`, ); expect(() => normalizeSidebars({ // @ts-expect-error: test sidebar: 'item', }), ).toThrowErrorMatchingInlineSnapshot( `"Invalid sidebar items collection \`"item"\` in sidebar sidebar: it must either be an array of sidebar items or a shorthand notation (which doesn't contain a \`type\` property). See https://docusaurus.io/docs/sidebar/items for all valid syntaxes."`, ); }); it('adds a translatable marker for labels defined in sidebars.js', () => { expect( normalizeSidebars({ sidebar: [ { type: 'doc', id: 'google', label: 'Google', }, { 'Category 1': ['doc1', 'doc2'], 'Category 2': [ 'doc3', 'doc4', { type: 'ref', id: 'msft', label: 'Microsoft', }, ], }, ], }), ).toMatchSnapshot(); }); });
1,276
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/postProcessor.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { postProcessSidebars, type SidebarPostProcessorParams, } from '../postProcessor'; describe('postProcess', () => { it('transforms category without subitems', () => { const processedSidebar = postProcessSidebars( { sidebar: [ { type: 'category', label: 'Category', link: { type: 'generated-index', slug: 'generated/permalink', }, items: [], }, { type: 'category', label: 'Category 2', link: { type: 'doc', id: 'doc ID', }, items: [], }, ], }, { sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: true}, version: {path: 'version'}, drafts: [], } as unknown as SidebarPostProcessorParams, ); expect(processedSidebar).toMatchSnapshot(); expect(() => { postProcessSidebars( { sidebar: [ { type: 'category', label: 'Bad category', items: [], }, ], }, { sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: true}, version: {path: 'version'}, drafts: [], } as unknown as SidebarPostProcessorParams, ); }).toThrowErrorMatchingInlineSnapshot( `"Sidebar category Bad category has neither any subitem nor a link. This makes this item not able to link to anything."`, ); }); it('corrects collapsed state inconsistencies', () => { expect( postProcessSidebars( { sidebar: [ { type: 'category', label: 'Category', collapsed: true, collapsible: false, items: [{type: 'doc', id: 'foo'}], }, ], }, { sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: true}, version: {path: 'version'}, drafts: [], } as unknown as SidebarPostProcessorParams, ), ).toMatchSnapshot(); expect( postProcessSidebars( { sidebar: [ { type: 'category', label: 'Category', collapsed: true, items: [{type: 'doc', id: 'foo'}], }, ], }, { sidebarOptions: {sidebarCollapsed: false, sidebarCollapsible: false}, version: {path: 'version'}, drafts: [], } as unknown as SidebarPostProcessorParams, ), ).toMatchSnapshot(); expect( postProcessSidebars( { sidebar: [ { type: 'category', label: 'Category', items: [{type: 'doc', id: 'foo'}], }, ], }, { sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: false}, version: {path: 'version'}, drafts: [], } as unknown as SidebarPostProcessorParams, ), ).toMatchSnapshot(); }); it('filters draft items', () => { expect( postProcessSidebars( { sidebar: [ { type: 'category', label: 'Category', items: [{type: 'doc', id: 'foo'}], }, { type: 'category', label: 'Category', link: { type: 'doc', id: 'another', }, items: [{type: 'doc', id: 'foo'}], }, ], }, { sidebarOptions: {sidebarCollapsed: true, sidebarCollapsible: true}, version: {path: 'version'}, drafts: [{id: 'foo'}], } as unknown as SidebarPostProcessorParams, ), ).toMatchSnapshot(); }); });
1,277
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/processor.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {jest} from '@jest/globals'; import {createSlugger} from '@docusaurus/utils'; import {processSidebars} from '../processor'; import {DefaultSidebarItemsGenerator} from '../generator'; import {DefaultNumberPrefixParser} from '../../numberPrefix'; import {isCategoryIndex} from '../../docs'; import type { Sidebar, SidebarItemsGenerator, NormalizedSidebar, NormalizedSidebars, SidebarProcessorParams, CategoryMetadataFile, ProcessedSidebars, } from '../types'; import type {VersionMetadata} from '@docusaurus/plugin-content-docs'; describe('processSidebars', () => { function createStaticSidebarItemGenerator( sidebarSlice: NormalizedSidebar, ): SidebarItemsGenerator { return jest.fn(() => sidebarSlice); } const StaticGeneratedSidebarSlice: Sidebar = [ {type: 'doc', id: 'doc-generated-id-1'}, {type: 'doc', id: 'doc-generated-id-2'}, ]; const StaticSidebarItemsGenerator: SidebarItemsGenerator = createStaticSidebarItemGenerator(StaticGeneratedSidebarSlice); // @ts-expect-error: good enough for this test const version: VersionMetadata = { versionName: '1.0.0', path: '/docs/1.0.0', }; const params: SidebarProcessorParams = { sidebarItemsGenerator: StaticSidebarItemsGenerator, docs: [], drafts: [], version, numberPrefixParser: DefaultNumberPrefixParser, categoryLabelSlugger: createSlugger(), sidebarOptions: { sidebarCollapsed: true, sidebarCollapsible: true, }, }; async function testProcessSidebars( unprocessedSidebars: NormalizedSidebars, categoriesMetadata: {[filePath: string]: CategoryMetadataFile} = {}, paramsOverrides: Partial<SidebarProcessorParams> = {}, ) { return processSidebars(unprocessedSidebars, categoriesMetadata, { ...params, ...paramsOverrides, }); } it('leaves sidebars without autogenerated items untouched', async () => { const unprocessedSidebars: NormalizedSidebars = { someSidebar: [ {type: 'doc', id: 'doc1'}, { type: 'category', collapsed: false, collapsible: true, items: [{type: 'doc', id: 'doc2'}], label: 'Category', }, {type: 'link', href: 'https://facebook.com', label: 'FB'}, ], secondSidebar: [ {type: 'doc', id: 'doc3'}, {type: 'link', href: 'https://instagram.com', label: 'IG'}, { type: 'category', collapsed: false, collapsible: true, items: [{type: 'doc', id: 'doc4'}], label: 'Category', }, ], }; const processedSidebar = await testProcessSidebars(unprocessedSidebars); expect(processedSidebar).toEqual(unprocessedSidebars); }); it('replaces autogenerated items by generated sidebars slices', async () => { const unprocessedSidebars: NormalizedSidebars = { someSidebar: [ {type: 'doc', id: 'doc1'}, { type: 'category', label: 'Category', link: { type: 'generated-index', slug: 'category-generated-index-slug', }, items: [ {type: 'doc', id: 'doc2'}, {type: 'autogenerated', dirName: 'dir1'}, ], }, {type: 'link', href: 'https://facebook.com', label: 'FB'}, ], secondSidebar: [ {type: 'doc', id: 'doc3'}, {type: 'autogenerated', dirName: 'dir2'}, {type: 'link', href: 'https://instagram.com', label: 'IG'}, {type: 'autogenerated', dirName: 'dir3'}, { type: 'category', label: 'Category', collapsed: false, collapsible: true, items: [{type: 'doc', id: 'doc4'}], }, ], }; const processedSidebar = await testProcessSidebars(unprocessedSidebars); expect(StaticSidebarItemsGenerator).toHaveBeenCalledTimes(3); expect(StaticSidebarItemsGenerator).toHaveBeenCalledWith({ categoriesMetadata: {}, defaultSidebarItemsGenerator: DefaultSidebarItemsGenerator, item: {type: 'autogenerated', dirName: 'dir1'}, docs: params.docs, version: { versionName: version.versionName, }, numberPrefixParser: DefaultNumberPrefixParser, isCategoryIndex, }); expect(StaticSidebarItemsGenerator).toHaveBeenCalledWith({ defaultSidebarItemsGenerator: DefaultSidebarItemsGenerator, categoriesMetadata: {}, item: {type: 'autogenerated', dirName: 'dir2'}, docs: params.docs, version: { versionName: version.versionName, }, numberPrefixParser: DefaultNumberPrefixParser, isCategoryIndex, }); expect(StaticSidebarItemsGenerator).toHaveBeenCalledWith({ defaultSidebarItemsGenerator: DefaultSidebarItemsGenerator, categoriesMetadata: {}, item: {type: 'autogenerated', dirName: 'dir3'}, docs: params.docs, version: { versionName: version.versionName, }, numberPrefixParser: DefaultNumberPrefixParser, isCategoryIndex, }); expect(processedSidebar).toEqual({ someSidebar: [ {type: 'doc', id: 'doc1'}, { type: 'category', label: 'Category', link: { type: 'generated-index', slug: 'category-generated-index-slug', }, items: [{type: 'doc', id: 'doc2'}, ...StaticGeneratedSidebarSlice], }, {type: 'link', href: 'https://facebook.com', label: 'FB'}, ], secondSidebar: [ {type: 'doc', id: 'doc3'}, ...StaticGeneratedSidebarSlice, {type: 'link', href: 'https://instagram.com', label: 'IG'}, ...StaticGeneratedSidebarSlice, { type: 'category', label: 'Category', collapsed: false, collapsible: true, items: [{type: 'doc', id: 'doc4'}], }, ], } as ProcessedSidebars); }); it('ensures generated items are normalized', async () => { const sidebarSliceContainingCategoryGeneratedIndex: NormalizedSidebar = [ { type: 'category', label: 'Generated category', link: { type: 'generated-index', slug: 'generated-cat-index-slug', }, items: [ { type: 'doc', id: 'foo', }, ], }, ]; const unprocessedSidebars: NormalizedSidebars = { someSidebar: [{type: 'autogenerated', dirName: 'dir2'}], }; const processedSidebar = await testProcessSidebars( unprocessedSidebars, {}, { sidebarItemsGenerator: createStaticSidebarItemGenerator( sidebarSliceContainingCategoryGeneratedIndex, ), }, ); expect(processedSidebar).toEqual({ someSidebar: [ { type: 'category', label: 'Generated category', link: { type: 'generated-index', slug: 'generated-cat-index-slug', }, items: [ { type: 'doc', id: 'foo', }, ], }, ], } as ProcessedSidebars); }); });
1,278
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/utils.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { createSidebarsUtils, collectSidebarDocItems, collectSidebarCategories, collectSidebarLinks, transformSidebarItems, collectSidebarsDocIds, toDocNavigationLink, toNavigationLink, } from '../utils'; import type {Sidebar, Sidebars} from '../types'; import type { DocMetadataBase, PropNavigationLink, } from '@docusaurus/plugin-content-docs'; describe('createSidebarsUtils', () => { const sidebar1: Sidebar = [ { type: 'category', collapsed: false, collapsible: true, label: 'S1 Category', items: [ { type: 'category', collapsed: false, collapsible: true, label: 'S1 Subcategory', items: [{type: 'doc', id: 'doc1'}], }, {type: 'doc', id: 'doc2'}, ], }, ]; const sidebar2: Sidebar = [ { type: 'category', collapsed: false, collapsible: true, label: 'S2 Category', items: [ {type: 'doc', id: 'doc3', label: 'Doc 3'}, {type: 'doc', id: 'doc4'}, ], }, ]; const sidebar3: Sidebar = [ { type: 'category', collapsed: false, collapsible: true, label: 'S3 Category', link: { type: 'doc', id: 'doc5', }, items: [ { type: 'category', collapsed: false, collapsible: true, label: 'S3 SubCategory', link: { type: 'generated-index', slug: '/s3-subcategory-index-slug', permalink: '/s3-subcategory-index-permalink', }, items: [ { type: 'category', collapsed: false, collapsible: true, label: 'S3 SubSubCategory', link: { type: 'generated-index', slug: '/s3-subsubcategory-slug', permalink: '/s3-subsubcategory-index-permalink', }, items: [ {type: 'doc', id: 'doc6'}, {type: 'doc', id: 'doc7'}, ], }, ], }, ], }, ]; const sidebar4: Sidebar = [ { type: 'category', collapsed: false, collapsible: true, label: 'Related', items: [ {type: 'link', href: 'https://facebook.com', label: 'Facebook'}, {type: 'link', href: 'https://reactjs.org', label: 'React'}, {type: 'link', href: 'https://docusaurus.io', label: 'Docusaurus'}, ], }, { type: 'category', collapsed: false, collapsible: true, label: 'S4 Category', link: { type: 'generated-index', slug: '/s4-category-slug', permalink: '/s4-category-slug', }, items: [ {type: 'doc', id: 'doc8'}, {type: 'doc', id: 'doc9'}, ], }, ]; const sidebars: Sidebars = {sidebar1, sidebar2, sidebar3, sidebar4}; const { getFirstDocIdOfFirstSidebar, getSidebarNameByDocId, getDocNavigation, getCategoryGeneratedIndexNavigation, getCategoryGeneratedIndexList, getFirstLink, } = createSidebarsUtils(sidebars); it('getFirstDocIdOfFirstSidebar', () => { expect(getFirstDocIdOfFirstSidebar()).toBe('doc1'); }); it('getSidebarNameByDocId', () => { expect(getSidebarNameByDocId('doc1')).toBe('sidebar1'); expect(getSidebarNameByDocId('doc2')).toBe('sidebar1'); expect(getSidebarNameByDocId('doc3')).toBe('sidebar2'); expect(getSidebarNameByDocId('doc4')).toBe('sidebar2'); expect(getSidebarNameByDocId('doc5')).toBe('sidebar3'); expect(getSidebarNameByDocId('doc6')).toBe('sidebar3'); expect(getSidebarNameByDocId('doc7')).toBe('sidebar3'); expect(getSidebarNameByDocId('unknown_id')).toBeUndefined(); }); it('getDocNavigation', () => { expect( getDocNavigation({ docId: 'doc1', displayedSidebar: undefined, unlistedIds: new Set(), }), ).toEqual({ sidebarName: 'sidebar1', previous: undefined, next: { type: 'doc', id: 'doc2', }, }); expect( getDocNavigation({ docId: 'doc2', displayedSidebar: undefined, unlistedIds: new Set(), }), ).toEqual({ sidebarName: 'sidebar1', previous: { type: 'doc', id: 'doc1', }, next: undefined, }); expect( getDocNavigation({ docId: 'doc3', displayedSidebar: undefined, unlistedIds: new Set(), }), ).toEqual({ sidebarName: 'sidebar2', previous: undefined, next: { type: 'doc', id: 'doc4', }, }); expect( getDocNavigation({ docId: 'doc4', displayedSidebar: undefined, unlistedIds: new Set(), }), ).toEqual({ sidebarName: 'sidebar2', previous: { type: 'doc', id: 'doc3', label: 'Doc 3', }, next: undefined, }); expect( getDocNavigation({ docId: 'doc5', displayedSidebar: undefined, unlistedIds: new Set(), }), ).toMatchObject({ sidebarName: 'sidebar3', previous: undefined, next: { type: 'category', label: 'S3 SubCategory', }, }); expect( getDocNavigation({ docId: 'doc6', displayedSidebar: undefined, unlistedIds: new Set(), }), ).toMatchObject({ sidebarName: 'sidebar3', previous: { type: 'category', label: 'S3 SubSubCategory', }, next: { type: 'doc', id: 'doc7', }, }); expect( getDocNavigation({ docId: 'doc7', displayedSidebar: undefined, unlistedIds: new Set(), }), ).toEqual({ sidebarName: 'sidebar3', previous: { type: 'doc', id: 'doc6', }, next: undefined, }); expect( getDocNavigation({ docId: 'doc3', displayedSidebar: null, unlistedIds: new Set(), }), ).toEqual({ sidebarName: undefined, previous: undefined, next: undefined, }); expect(() => getDocNavigation({ docId: 'doc3', displayedSidebar: 'foo', unlistedIds: new Set(), }), ).toThrowErrorMatchingInlineSnapshot( `"Doc with ID doc3 wants to display sidebar foo but a sidebar with this name doesn't exist"`, ); expect( getDocNavigation({ docId: 'doc3', displayedSidebar: 'sidebar1', unlistedIds: new Set(), }), ).toEqual({ sidebarName: 'sidebar1', previous: undefined, next: undefined, }); }); it('getCategoryGeneratedIndexNavigation', () => { expect( getCategoryGeneratedIndexNavigation('/s3-subcategory-index-permalink'), ).toMatchObject({ sidebarName: 'sidebar3', previous: { type: 'category', label: 'S3 Category', }, next: { type: 'category', label: 'S3 SubSubCategory', }, }); expect( getCategoryGeneratedIndexNavigation('/s3-subsubcategory-index-permalink'), ).toMatchObject({ sidebarName: 'sidebar3', previous: { type: 'category', label: 'S3 SubCategory', }, next: { type: 'doc', id: 'doc6', }, }); }); it('getCategoryGeneratedIndexList', () => { expect(getCategoryGeneratedIndexList()).toMatchObject([ { type: 'category', label: 'S3 SubCategory', }, { type: 'category', label: 'S3 SubSubCategory', }, { type: 'category', label: 'S4 Category', }, ]); }); it('getFirstLink', () => { expect(getFirstLink('sidebar1')).toEqual({ id: 'doc1', type: 'doc', label: 'doc1', }); expect(getFirstLink('sidebar2')).toEqual({ id: 'doc3', type: 'doc', label: 'Doc 3', }); expect(getFirstLink('sidebar3')).toEqual({ id: 'doc5', type: 'doc', label: 'S3 Category', }); expect(getFirstLink('sidebar4')).toEqual({ type: 'generated-index', permalink: '/s4-category-slug', label: 'S4 Category', }); }); }); describe('collectSidebarDocItems', () => { it('can collect docs', () => { const sidebar: Sidebar = [ { type: 'category', collapsed: false, collapsible: true, label: 'Category1', items: [ { type: 'category', collapsed: false, collapsible: true, label: 'Subcategory 1', items: [{type: 'doc', id: 'doc1'}], }, { type: 'category', collapsed: false, collapsible: true, label: 'Subcategory 2', items: [ {type: 'doc', id: 'doc2'}, { type: 'category', collapsed: false, collapsible: true, label: 'Sub sub category 1', items: [{type: 'doc', id: 'doc3'}], }, ], }, ], }, { type: 'category', collapsed: false, collapsible: true, label: 'Category2', items: [ {type: 'doc', id: 'doc4'}, {type: 'doc', id: 'doc5'}, ], }, ]; expect(collectSidebarDocItems(sidebar).map((doc) => doc.id)).toEqual([ 'doc1', 'doc2', 'doc3', 'doc4', 'doc5', ]); }); }); describe('collectSidebarCategories', () => { it('can collect categories', () => { const sidebar: Sidebar = [ { type: 'category', collapsed: false, collapsible: true, label: 'Category1', items: [ { type: 'category', collapsed: false, collapsible: true, label: 'Subcategory 1', items: [{type: 'doc', id: 'doc1'}], }, { type: 'category', collapsed: false, collapsible: true, label: 'Subcategory 2', items: [ {type: 'doc', id: 'doc2'}, { type: 'category', collapsed: false, collapsible: true, label: 'Sub sub category 1', items: [{type: 'doc', id: 'doc3'}], }, ], }, ], }, { type: 'category', collapsed: false, collapsible: true, label: 'Category2', items: [ {type: 'doc', id: 'doc4'}, {type: 'doc', id: 'doc5'}, ], }, ]; expect( collectSidebarCategories(sidebar).map((category) => category.label), ).toEqual([ 'Category1', 'Subcategory 1', 'Subcategory 2', 'Sub sub category 1', 'Category2', ]); }); }); describe('collectSidebarLinks', () => { it('can collect links', () => { const sidebar: Sidebar = [ { type: 'category', collapsed: false, collapsible: true, label: 'Category1', items: [ { type: 'link', href: 'https://google.com', label: 'Google', }, { type: 'category', collapsed: false, collapsible: true, label: 'Subcategory 2', items: [ { type: 'link', href: 'https://facebook.com', label: 'Facebook', }, ], }, ], }, ]; expect(collectSidebarLinks(sidebar).map((link) => link.href)).toEqual([ 'https://google.com', 'https://facebook.com', ]); }); }); describe('collectSidebarsDocIds', () => { it('can collect sidebars doc items', () => { const sidebar1: Sidebar = [ { type: 'category', collapsed: false, collapsible: true, label: 'Category1', items: [ { type: 'category', collapsed: false, collapsible: true, label: 'Subcategory 1', items: [{type: 'doc', id: 'doc1'}], }, {type: 'doc', id: 'doc2'}, ], }, ]; const sidebar2: Sidebar = [ { type: 'category', collapsed: false, collapsible: true, label: 'Category2', items: [ {type: 'doc', id: 'doc3'}, {type: 'doc', id: 'doc4'}, ], }, ]; const sidebar3: Sidebar = [ {type: 'doc', id: 'doc5'}, {type: 'doc', id: 'doc6'}, ]; expect(collectSidebarsDocIds({sidebar1, sidebar2, sidebar3})).toEqual({ sidebar1: ['doc1', 'doc2'], sidebar2: ['doc3', 'doc4'], sidebar3: ['doc5', 'doc6'], }); }); }); describe('transformSidebarItems', () => { it('can transform sidebar items', () => { const sidebar: Sidebar = [ { type: 'category', collapsed: false, collapsible: true, label: 'Category1', items: [ { type: 'category', collapsed: false, collapsible: true, label: 'Subcategory 1', items: [{type: 'doc', id: 'doc1'}], customProps: {fakeProp: false}, }, { type: 'category', collapsed: false, collapsible: true, label: 'Subcategory 2', items: [ {type: 'doc', id: 'doc2'}, { type: 'category', collapsed: false, collapsible: true, label: 'Sub sub category 1', items: [ {type: 'doc', id: 'doc3', customProps: {lorem: 'ipsum'}}, ], }, ], }, ], }, { type: 'category', collapsed: false, collapsible: true, label: 'Category2', items: [ {type: 'doc', id: 'doc4'}, {type: 'doc', id: 'doc5'}, ], }, ]; expect( transformSidebarItems(sidebar, (item) => { if (item.type === 'category') { return {...item, label: `MODIFIED LABEL: ${item.label}`}; } return item; }), ).toEqual([ { type: 'category', collapsed: false, collapsible: true, label: 'MODIFIED LABEL: Category1', items: [ { type: 'category', collapsed: false, collapsible: true, label: 'MODIFIED LABEL: Subcategory 1', items: [{type: 'doc', id: 'doc1'}], customProps: {fakeProp: false}, }, { type: 'category', collapsed: false, collapsible: true, label: 'MODIFIED LABEL: Subcategory 2', items: [ {type: 'doc', id: 'doc2'}, { type: 'category', collapsed: false, collapsible: true, label: 'MODIFIED LABEL: Sub sub category 1', items: [ {type: 'doc', id: 'doc3', customProps: {lorem: 'ipsum'}}, ], }, ], }, ], }, { type: 'category', collapsed: false, collapsible: true, label: 'MODIFIED LABEL: Category2', items: [ {type: 'doc', id: 'doc4'}, {type: 'doc', id: 'doc5'}, ], }, ]); }); }); describe('toDocNavigationLink', () => { type TestDoc = Pick<DocMetadataBase, 'permalink' | 'title' | 'frontMatter'>; function testDoc(data: TestDoc) { return data as DocMetadataBase; } it('with no front matter', () => { expect( toDocNavigationLink( testDoc({ title: 'Doc Title', permalink: '/docPermalink', frontMatter: {}, }), ), ).toEqual({ title: 'Doc Title', permalink: '/docPermalink', } as PropNavigationLink); }); it('with pagination_label front matter', () => { expect( toDocNavigationLink( testDoc({ title: 'Doc Title', permalink: '/docPermalink', frontMatter: { pagination_label: 'pagination_label', }, }), ), ).toEqual({ title: 'pagination_label', permalink: '/docPermalink', } as PropNavigationLink); }); it('with sidebar_label front matter', () => { expect( toDocNavigationLink( testDoc({ title: 'Doc Title', permalink: '/docPermalink', frontMatter: { sidebar_label: 'sidebar_label', }, }), ), ).toEqual({ title: 'sidebar_label', permalink: '/docPermalink', } as PropNavigationLink); }); it('with pagination_label + sidebar_label front matter', () => { expect( toDocNavigationLink( testDoc({ title: 'Doc Title', permalink: '/docPermalink', frontMatter: { pagination_label: 'pagination_label', sidebar_label: 'sidebar_label', }, }), ), ).toEqual({ title: 'pagination_label', permalink: '/docPermalink', } as PropNavigationLink); }); }); describe('toNavigationLink', () => { type TestDoc = Pick<DocMetadataBase, 'permalink' | 'title'>; function testDoc(data: TestDoc) { return {...data, frontMatter: {}} as DocMetadataBase; } const docsById: {[docId: string]: DocMetadataBase} = { doc1: testDoc({ title: 'Doc 1', permalink: '/doc1', }), doc2: testDoc({ title: 'Doc 1', permalink: '/doc1', }), }; it('with doc items', () => { expect(toNavigationLink({type: 'doc', id: 'doc1'}, docsById)).toEqual( toDocNavigationLink(docsById.doc1!), ); expect(toNavigationLink({type: 'doc', id: 'doc2'}, docsById)).toEqual( toDocNavigationLink(docsById.doc2!), ); expect(() => toNavigationLink({type: 'doc', id: 'doc3'}, docsById), ).toThrowErrorMatchingInlineSnapshot( `"Can't create navigation link: no doc found with id=doc3"`, ); }); it('with category item and doc link', () => { expect( toNavigationLink( { type: 'category', label: 'Category', items: [], link: { type: 'doc', id: 'doc1', }, collapsed: true, collapsible: true, }, docsById, ), ).toEqual(toDocNavigationLink(docsById.doc1!)); expect(() => toNavigationLink( { type: 'category', label: 'Category', items: [], link: { type: 'doc', id: 'doc3', }, collapsed: true, collapsible: true, }, docsById, ), ).toThrowErrorMatchingInlineSnapshot( `"Can't create navigation link: no doc found with id=doc3"`, ); }); it('with category item and generated-index link', () => { expect( toNavigationLink( { type: 'category', label: 'Category', items: [], link: { type: 'generated-index', slug: 'slug', permalink: 'generated-index-permalink', }, collapsed: true, collapsible: true, }, docsById, ), ).toEqual({title: 'Category', permalink: 'generated-index-permalink'}); }); });
1,279
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/validation.test.ts
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {validateSidebars, validateCategoryMetadataFile} from '../validation'; import type {SidebarsConfig, CategoryMetadataFile} from '../types'; describe('validateSidebars', () => { it('throw for bad value', () => { expect(() => validateSidebars({sidebar: [{type: 42}]})) .toThrowErrorMatchingInlineSnapshot(` "{ "type": 42, "undefined" [1]: -- missing -- } [1] Unknown sidebar item type "42"." `); }); it('accept empty object', () => { const sidebars: SidebarsConfig = {}; validateSidebars(sidebars); }); it('accept valid values', () => { const sidebars: SidebarsConfig = { sidebar1: [ {type: 'doc', id: 'doc1'}, {type: 'doc', id: 'doc2'}, { type: 'category', label: 'Category', items: [{type: 'doc', id: 'doc3'}], }, ], }; validateSidebars(sidebars); }); it('sidebar category wrong label', () => { expect( () => validateSidebars({ docs: [ { type: 'category', label: true, items: [{type: 'doc', id: 'doc1'}], }, ], }), // eslint-disable-next-line jest/no-large-snapshots ).toThrowErrorMatchingInlineSnapshot(` "{ "type": "category", "items": [ { "type": "doc", "id": "doc1" } ], "label" [1]: true } [1] "label" must be a string" `); }); it('sidebars link wrong label', () => { expect(() => validateSidebars({ docs: [ { type: 'link', label: false, href: 'https://github.com', }, ], }), ).toThrowErrorMatchingInlineSnapshot(` "{ "type": "link", "href": "https://github.com", "label" [1]: false } [1] "label" must be a string" `); }); it('sidebars link wrong href', () => { expect(() => validateSidebars({ docs: [ { type: 'link', label: 'GitHub', href: ['example.com'], }, ], }), ).toThrowErrorMatchingInlineSnapshot(` "{ "type": "link", "label": "GitHub", "href" [1]: [ "example.com" ] } [1] "href" contains an invalid value" `); }); it('sidebars with unknown sidebar item type', () => { expect(() => validateSidebars({ docs: [ { type: 'superman', }, ], }), ).toThrowErrorMatchingInlineSnapshot(` "{ "type": "superman", "undefined" [1]: -- missing -- } [1] Unknown sidebar item type "superman"." `); }); it('sidebars category missing items', () => { expect(() => validateSidebars({ docs: [ { type: 'category', label: 'category', }, { type: 'ref', id: 'hello', }, ], }), ).toThrowErrorMatchingInlineSnapshot(` "{ "type": "category", "label": "category", "items" [1]: -- missing -- } [1] "items" is required" `); }); it('sidebars category wrong field', () => { expect(() => validateSidebars({ docs: [ { type: 'category', label: 'category', items: [], href: 'https://google.com', }, { type: 'ref', id: 'hello', }, ], }), ).toThrowErrorMatchingInlineSnapshot(` "{ "type": "category", "label": "category", "items": [], "href" [1]: "https://google.com" } [1] "href" is not allowed" `); }); it('sidebar category wrong items', () => { expect(() => validateSidebars({ docs: { Test: [ { type: 'category', label: 'Category Label', items: 'doc1', }, ], }, }), ).toThrowErrorMatchingInlineSnapshot(`"sidebar.forEach is not a function"`); }); it('sidebars item doc but id is not a string', () => { expect(() => validateSidebars({ docs: [ { type: 'doc', id: ['doc1'], }, ], }), ).toThrowErrorMatchingInlineSnapshot(` "{ "type": "doc", "id" [1]: [ "doc1" ] } [1] "id" must be a string" `); }); it('html type requires a value', () => { const sidebars: SidebarsConfig = { sidebar1: [ { // @ts-expect-error - test missing value type: 'html', }, ], }; expect(() => validateSidebars(sidebars)) .toThrowErrorMatchingInlineSnapshot(` "{ "type": "html", "value" [1]: -- missing -- } [1] "value" is required" `); }); it('html type accepts valid values', () => { const sidebars: SidebarsConfig = { sidebar1: [ { type: 'html', value: '<p>Hello, World!</p>', defaultStyle: true, className: 'foo', }, ], }; validateSidebars(sidebars); }); }); describe('validateCategoryMetadataFile', () => { // TODO add more tests it('throw for bad value', () => { expect(() => validateCategoryMetadataFile(42), ).toThrowErrorMatchingInlineSnapshot(`""value" must be of type object"`); }); it('accept empty object', () => { const content: CategoryMetadataFile = {}; expect(validateCategoryMetadataFile(content)).toEqual(content); }); it('accept valid values', () => { const content: CategoryMetadataFile = { className: 'className', label: 'Category Label', link: { type: 'generated-index', slug: 'slug', title: 'title', description: 'description', }, collapsible: true, collapsed: true, position: 3, }; expect(validateCategoryMetadataFile(content)).toEqual(content); }); it('rejects permalink', () => { const content: CategoryMetadataFile = { className: 'className', label: 'Category Label', link: { type: 'generated-index', slug: 'slug', // @ts-expect-error: rejected on purpose permalink: 'somePermalink', title: 'title', description: 'description', }, collapsible: true, collapsed: true, position: 3, }; expect(() => validateCategoryMetadataFile(content), ).toThrowErrorMatchingInlineSnapshot(`""link.permalink" is not allowed"`); }); });
1,291
0
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__
petrpan-code/facebook/docusaurus/packages/docusaurus-plugin-content-docs/src/sidebars/__tests__/__snapshots__/generator.test.ts.snap
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`DefaultSidebarItemsGenerator generates complex nested sidebar 1`] = ` [ { "id": "intro", "type": "doc", }, { "collapsed": undefined, "collapsible": undefined, "items": [ { "id": "tutorial1", "type": "doc", }, { "id": "tutorial2", "type": "doc", }, ], "label": "Tutorials", "link": { "id": "tutorials-index", "type": "doc", }, "type": "category", }, { "collapsed": false, "collapsible": undefined, "customProps": { "description": "foo", }, "items": [ { "className": "foo", "id": "guide1", "type": "doc", }, { "collapsed": undefined, "collapsible": undefined, "items": [ { "id": "nested-guide", "type": "doc", }, ], "label": "SubGuides (metadata file label)", "link": { "description": "subGuides-description", "slug": "subGuides-generated-index-slug", "title": "subGuides-title", "type": "generated-index", }, "type": "category", }, { "id": "guide2", "type": "doc", }, ], "label": "Guides", "link": { "id": "guides-index", "type": "doc", }, "type": "category", }, { "id": "end", "type": "doc", }, ] `; exports[`DefaultSidebarItemsGenerator generates simple flat sidebar 1`] = ` [ { "id": "doc3", "type": "doc", }, { "id": "doc4", "type": "doc", }, { "customProps": { "custom": "prop", }, "id": "doc1", "label": "doc1 sidebar label", "type": "doc", }, { "id": "doc2", "type": "doc", }, { "id": "doc5", "type": "doc", }, ] `; exports[`DefaultSidebarItemsGenerator generates subfolder sidebar 1`] = ` [ { "collapsed": undefined, "collapsible": undefined, "items": [ { "id": "doc8", "type": "doc", }, { "id": "doc7", "type": "doc", }, ], "label": "Subsubsubfolder category label", "link": { "id": "doc1", "type": "doc", }, "type": "category", }, { "className": "bar", "collapsed": undefined, "collapsible": undefined, "items": [ { "id": "doc6", "type": "doc", }, ], "label": "subsubsubfolder2 (_category_.yml label)", "type": "category", }, { "id": "doc1", "type": "doc", }, { "id": "doc4", "type": "doc", }, { "collapsed": undefined, "collapsible": undefined, "items": [ { "id": "doc5", "type": "doc", }, ], "label": "subsubsubfolder", "type": "category", }, ] `; exports[`DefaultSidebarItemsGenerator respects custom isCategoryIndex 1`] = ` [ { "id": "intro", "type": "doc", }, { "collapsed": undefined, "collapsible": undefined, "items": [ { "id": "tutorial1", "type": "doc", }, { "id": "tutorial2", "type": "doc", }, ], "label": "Tutorials", "link": { "id": "tutorials-index", "type": "doc", }, "type": "category", }, { "collapsed": undefined, "collapsible": undefined, "items": [ { "className": "foo", "id": "guide1", "type": "doc", }, { "id": "guide2", "type": "doc", }, { "id": "not-guides-index", "type": "doc", }, ], "label": "Guides", "type": "category", }, ] `; exports[`DefaultSidebarItemsGenerator uses explicit link over the index/readme.{md,mdx} naming convention 1`] = ` [ { "collapsed": undefined, "collapsible": undefined, "items": [ { "id": "parent/doc2", "type": "doc", }, { "id": "parent/doc1", "type": "doc", }, ], "label": "Category label", "link": { "id": "parent/doc3", "type": "doc", }, "type": "category", }, { "collapsed": undefined, "collapsible": undefined, "items": [ { "id": "parent/doc4", "type": "doc", }, { "id": "parent/doc6", "type": "doc", }, { "id": "parent/doc5", "type": "doc", }, ], "label": "Category 2 label", "type": "category", }, ] `;