diff --git a/packages/adapters/fastify/web/src/resolveOptions.test.ts b/packages/adapters/fastify/web/src/resolveOptions.test.ts index aa1d2bac772b..2026b9f01e57 100644 --- a/packages/adapters/fastify/web/src/resolveOptions.test.ts +++ b/packages/adapters/fastify/web/src/resolveOptions.test.ts @@ -36,9 +36,9 @@ describe('resolveOptions', () => { apiUrl: undefined, apiProxyTarget: '/api', }, - }) + }), ).toThrowErrorMatchingInlineSnapshot( - `[Error: If you provide \`apiProxyTarget\`, it has to be a fully-qualified URL. \`apiProxyTarget\` is '/api']` + `[Error: If you provide \`apiProxyTarget\`, it has to be a fully-qualified URL. \`apiProxyTarget\` is '/api']`, ) }) @@ -49,7 +49,7 @@ describe('resolveOptions', () => { apiUrl: undefined, apiProxyTarget: 'http://api.foo.com', }, - }) + }), ).toMatchInlineSnapshot(` { "flags": { @@ -72,9 +72,9 @@ describe('resolveOptions', () => { apiUrl: '', apiProxyTarget: undefined, }, - }) + }), ).toThrowErrorMatchingInlineSnapshot( - `[Error: \`apiUrl\` cannot be an empty string]` + `[Error: \`apiUrl\` cannot be an empty string]`, ) }) @@ -85,9 +85,9 @@ describe('resolveOptions', () => { apiUrl: '', apiProxyTarget: '', }, - }) + }), ).toThrowErrorMatchingInlineSnapshot( - `[Error: \`apiUrl\` cannot be an empty string]` + `[Error: \`apiUrl\` cannot be an empty string]`, ) }) @@ -98,9 +98,9 @@ describe('resolveOptions', () => { apiUrl: '', apiProxyTarget: '/api', }, - }) + }), ).toThrowErrorMatchingInlineSnapshot( - `[Error: \`apiUrl\` cannot be an empty string]` + `[Error: \`apiUrl\` cannot be an empty string]`, ) }) @@ -111,9 +111,9 @@ describe('resolveOptions', () => { apiUrl: '', apiProxyTarget: 'http://api.foo.com', }, - }) + }), ).toThrowErrorMatchingInlineSnapshot( - `[Error: \`apiUrl\` cannot be an empty string]` + `[Error: \`apiUrl\` cannot be an empty string]`, ) }) }) @@ -126,7 +126,7 @@ describe('resolveOptions', () => { apiUrl: '/api', apiProxyTarget: undefined, }, - }) + }), ).toMatchInlineSnapshot(` { "flags": { @@ -147,7 +147,7 @@ describe('resolveOptions', () => { apiUrl: '/api', apiProxyTarget: '', }, - }) + }), ).toMatchInlineSnapshot(` { "flags": { @@ -168,9 +168,9 @@ describe('resolveOptions', () => { apiUrl: '/api', apiProxyTarget: '/api', }, - }) + }), ).toThrowErrorMatchingInlineSnapshot( - `[Error: If you provide \`apiProxyTarget\`, it has to be a fully-qualified URL. \`apiProxyTarget\` is '/api']` + `[Error: If you provide \`apiProxyTarget\`, it has to be a fully-qualified URL. \`apiProxyTarget\` is '/api']`, ) }) @@ -181,7 +181,7 @@ describe('resolveOptions', () => { apiUrl: '/api', apiProxyTarget: 'http://api.foo.com', }, - }) + }), ).toMatchInlineSnapshot(` { "flags": { @@ -204,7 +204,7 @@ describe('resolveOptions', () => { apiUrl: 'http://api.foo.com', apiProxyTarget: undefined, }, - }) + }), ).toMatchInlineSnapshot(` { "flags": { @@ -225,7 +225,7 @@ describe('resolveOptions', () => { apiUrl: 'http://api.foo.com', apiProxyTarget: '', }, - }) + }), ).toMatchInlineSnapshot(` { "flags": { @@ -246,9 +246,9 @@ describe('resolveOptions', () => { apiUrl: 'http://api.foo.com', apiProxyTarget: '/api', }, - }) + }), ).toThrowErrorMatchingInlineSnapshot( - `[Error: If you provide \`apiProxyTarget\`, it has to be a fully-qualified URL. \`apiProxyTarget\` is '/api']` + `[Error: If you provide \`apiProxyTarget\`, it has to be a fully-qualified URL. \`apiProxyTarget\` is '/api']`, ) }) @@ -259,9 +259,9 @@ describe('resolveOptions', () => { apiUrl: 'http://api.foo.com', apiProxyTarget: 'http://api.foo.com', }, - }) + }), ).toThrowErrorMatchingInlineSnapshot( - `[Error: If you provide \`apiProxyTarget\`, \`apiUrl\` cannot be a fully-qualified URL. \`apiUrl\` is 'http://api.foo.com']` + `[Error: If you provide \`apiProxyTarget\`, \`apiUrl\` cannot be a fully-qualified URL. \`apiUrl\` is 'http://api.foo.com']`, ) }) }) @@ -273,7 +273,7 @@ describe('resolveOptions', () => { redwood: { apiHost: 'http://api.foo.com', }, - }) + }), ).toMatchInlineSnapshot(` { "flags": { diff --git a/packages/adapters/fastify/web/src/resolveOptions.ts b/packages/adapters/fastify/web/src/resolveOptions.ts index 8a7e98929732..d49d27de487d 100644 --- a/packages/adapters/fastify/web/src/resolveOptions.ts +++ b/packages/adapters/fastify/web/src/resolveOptions.ts @@ -26,7 +26,7 @@ export function resolveOptions(options: RedwoodFastifyWebOptions) { !isFullyQualifiedUrl(redwoodOptions.apiProxyTarget) ) { throw new Error( - `If you provide \`apiProxyTarget\`, it has to be a fully-qualified URL. \`apiProxyTarget\` is '${redwoodOptions.apiProxyTarget}'` + `If you provide \`apiProxyTarget\`, it has to be a fully-qualified URL. \`apiProxyTarget\` is '${redwoodOptions.apiProxyTarget}'`, ) } @@ -43,7 +43,7 @@ export function resolveOptions(options: RedwoodFastifyWebOptions) { // This is pretty unlikely because we default `apiUrl` to '/.redwood/functions' if (!redwoodOptions.apiUrl && redwoodOptions.apiProxyTarget) { throw new Error( - `If you provide \`apiProxyTarget\`, \`apiUrl\` has to be a relative URL. \`apiUrl\` is '${redwoodOptions.apiUrl}'` + `If you provide \`apiProxyTarget\`, \`apiUrl\` has to be a relative URL. \`apiUrl\` is '${redwoodOptions.apiUrl}'`, ) } @@ -58,7 +58,7 @@ export function resolveOptions(options: RedwoodFastifyWebOptions) { // ``` if (apiUrlIsFullyQualifiedUrl && redwoodOptions.apiProxyTarget) { throw new Error( - `If you provide \`apiProxyTarget\`, \`apiUrl\` cannot be a fully-qualified URL. \`apiUrl\` is '${redwoodOptions.apiUrl}'` + `If you provide \`apiProxyTarget\`, \`apiUrl\` cannot be a fully-qualified URL. \`apiUrl\` is '${redwoodOptions.apiUrl}'`, ) } diff --git a/packages/adapters/fastify/web/src/web.test.ts b/packages/adapters/fastify/web/src/web.test.ts index 0f3af359396d..6cff6d87adf1 100644 --- a/packages/adapters/fastify/web/src/web.test.ts +++ b/packages/adapters/fastify/web/src/web.test.ts @@ -53,7 +53,7 @@ describe('redwoodFastifyWeb', () => { expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( - fs.readFileSync(path.join(getPaths().web.dist, `${url}.html`), 'utf-8') + fs.readFileSync(path.join(getPaths().web.dist, `${url}.html`), 'utf-8'), ) }) @@ -68,7 +68,7 @@ describe('redwoodFastifyWeb', () => { expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( - fs.readFileSync(path.join(getPaths().web.dist, `${url}.html`), 'utf-8') + fs.readFileSync(path.join(getPaths().web.dist, `${url}.html`), 'utf-8'), ) }) @@ -85,7 +85,7 @@ describe('redwoodFastifyWeb', () => { expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( - fs.readFileSync(path.join(getPaths().web.dist, `${url}.html`), 'utf-8') + fs.readFileSync(path.join(getPaths().web.dist, `${url}.html`), 'utf-8'), ) }) @@ -124,7 +124,7 @@ describe('redwoodFastifyWeb', () => { expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( - fs.readFileSync(path.join(getPaths().web.dist, url), 'utf-8') + fs.readFileSync(path.join(getPaths().web.dist, url), 'utf-8'), ) }) @@ -137,7 +137,7 @@ describe('redwoodFastifyWeb', () => { expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( - fs.readFileSync(path.join(getPaths().web.dist, '200.html'), 'utf-8') + fs.readFileSync(path.join(getPaths().web.dist, '200.html'), 'utf-8'), ) }) }) @@ -153,13 +153,13 @@ describe('redwoodFastifyWeb', () => { expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe( - 'application/javascript; charset=UTF-8' + 'application/javascript; charset=UTF-8', ) expect(res.body).toBe( fs.readFileSync( path.join(getPaths().web.dist, relativeFilePath), - 'utf-8' - ) + 'utf-8', + ), ) }) @@ -176,8 +176,8 @@ describe('redwoodFastifyWeb', () => { expect(res.body).toBe( fs.readFileSync( path.join(getPaths().web.dist, relativeFilePath), - 'utf-8' - ) + 'utf-8', + ), ) }) @@ -191,13 +191,13 @@ describe('redwoodFastifyWeb', () => { expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe( - 'application/json; charset=UTF-8' + 'application/json; charset=UTF-8', ) expect(res.body).toBe( fs.readFileSync( path.join(getPaths().web.dist, relativeFilePath), - 'utf-8' - ) + 'utf-8', + ), ) }) @@ -224,8 +224,8 @@ describe('redwoodFastifyWeb', () => { expect(res.body).toBe( fs.readFileSync( path.join(getPaths().web.dist, relativeFilePath), - 'utf-8' - ) + 'utf-8', + ), ) }) @@ -242,8 +242,8 @@ describe('redwoodFastifyWeb', () => { expect(res.body).toBe( fs.readFileSync( path.join(getPaths().web.dist, relativeFilePath), - 'utf-8' - ) + 'utf-8', + ), ) }) }) @@ -319,10 +319,10 @@ describe('redwoodFastifyWeb', () => { expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe( - 'application/json; charset=utf-8' + 'application/json; charset=utf-8', ) expect(res.body).toMatchInlineSnapshot( - `"{"data":null,"errors":[{"message":"Bad Gateway: you may have misconfigured apiUrl and apiProxyTarget. If apiUrl is a relative URL, you must provide apiProxyTarget.","extensions":{"code":"BAD_GATEWAY","httpStatus":502}}]}"` + `"{"data":null,"errors":[{"message":"Bad Gateway: you may have misconfigured apiUrl and apiProxyTarget. If apiUrl is a relative URL, you must provide apiProxyTarget.","extensions":{"code":"BAD_GATEWAY","httpStatus":502}}]}"`, ) }) @@ -336,10 +336,10 @@ describe('redwoodFastifyWeb', () => { expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe( - 'application/json; charset=utf-8' + 'application/json; charset=utf-8', ) expect(res.body).toMatchInlineSnapshot( - `"{"data":null,"errors":[{"message":"Bad Gateway: you may have misconfigured apiUrl and apiProxyTarget. If apiUrl is a relative URL, you must provide apiProxyTarget.","extensions":{"code":"BAD_GATEWAY","httpStatus":502}}]}"` + `"{"data":null,"errors":[{"message":"Bad Gateway: you may have misconfigured apiUrl and apiProxyTarget. If apiUrl is a relative URL, you must provide apiProxyTarget.","extensions":{"code":"BAD_GATEWAY","httpStatus":502}}]}"`, ) }) }) diff --git a/packages/adapters/fastify/web/src/web.ts b/packages/adapters/fastify/web/src/web.ts index cda8135e86e3..1c2ea3b74938 100644 --- a/packages/adapters/fastify/web/src/web.ts +++ b/packages/adapters/fastify/web/src/web.ts @@ -17,7 +17,7 @@ export { coerceRootPath, RedwoodFastifyWebOptions } export async function redwoodFastifyWeb( fastify: FastifyInstance, - opts: RedwoodFastifyWebOptions + opts: RedwoodFastifyWebOptions, ) { const { redwoodOptions, flags } = resolveOptions(opts) diff --git a/packages/adapters/fastify/web/src/webFallback.test.ts b/packages/adapters/fastify/web/src/webFallback.test.ts index 9129201edc22..671f6014ebf2 100644 --- a/packages/adapters/fastify/web/src/webFallback.test.ts +++ b/packages/adapters/fastify/web/src/webFallback.test.ts @@ -39,7 +39,7 @@ describe('webFallback', () => { expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( - fs.readFileSync(path.join(getPaths().web.dist, url), 'utf-8') + fs.readFileSync(path.join(getPaths().web.dist, url), 'utf-8'), ) await fastify.close() diff --git a/packages/api-server/src/__tests__/api.test.ts b/packages/api-server/src/__tests__/api.test.ts index 5c08e8a74ab0..f21faf1c9640 100644 --- a/packages/api-server/src/__tests__/api.test.ts +++ b/packages/api-server/src/__tests__/api.test.ts @@ -132,7 +132,7 @@ describe('redwoodFastifyAPI', () => { expect(res.statusCode).toEqual(404) expect(res.body).toEqual( - 'Function "deeplyNested" was not found.' + 'Function "deeplyNested" was not found.', ) }) }) diff --git a/packages/api-server/src/__tests__/createServer.test.ts b/packages/api-server/src/__tests__/createServer.test.ts index d58ae2eb6d3c..ed74a42b4484 100644 --- a/packages/api-server/src/__tests__/createServer.test.ts +++ b/packages/api-server/src/__tests__/createServer.test.ts @@ -139,7 +139,7 @@ describe('createServer', () => { const lastCallIndex = consoleLogSpy.mock.calls.length - 1 expect(consoleLogSpy.mock.calls[lastCallIndex][0]).toMatch( - /Server listening at/ + /Server listening at/, ) // `console.warn` will be used if there's a `server.config.js` file. @@ -250,19 +250,19 @@ describe('resolveOptions', () => { expect( resolveOptions({ apiRootPath: 'v1', - }).apiRootPath + }).apiRootPath, ).toEqual(expected) expect( resolveOptions({ apiRootPath: '/v1', - }).apiRootPath + }).apiRootPath, ).toEqual(expected) expect( resolveOptions({ apiRootPath: 'v1/', - }).apiRootPath + }).apiRootPath, ).toEqual(expected) }) @@ -311,7 +311,7 @@ describe('resolveOptions', () => { it('parses `--apiPort`', () => { expect( - resolveOptions({ parseArgs: true }, ['--apiPort', '8930']).apiPort + resolveOptions({ parseArgs: true }, ['--apiPort', '8930']).apiPort, ).toEqual(8930) }) @@ -319,13 +319,13 @@ describe('resolveOptions', () => { expect(() => { resolveOptions({ parseArgs: true }, ['--apiPort', 'eight-nine-ten']) }).toThrowErrorMatchingInlineSnapshot( - `[Error: \`apiPort\` must be an integer]` + `[Error: \`apiPort\` must be an integer]`, ) }) it('parses `--apiRootPath`', () => { expect( - resolveOptions({ parseArgs: true }, ['--apiRootPath', 'foo']).apiRootPath + resolveOptions({ parseArgs: true }, ['--apiRootPath', 'foo']).apiRootPath, ).toEqual('/foo/') }) @@ -334,13 +334,13 @@ describe('resolveOptions', () => { resolveOptions({ parseArgs: true, apiRootPath: 'foo' }, [ '--apiRootPath', 'bar', - ]).apiRootPath + ]).apiRootPath, ).toEqual('/bar/') }) it('parses `--apiHost`', () => { expect( - resolveOptions({ parseArgs: true }, ['--apiHost', '127.0.0.1']).apiHost + resolveOptions({ parseArgs: true }, ['--apiHost', '127.0.0.1']).apiHost, ).toEqual('127.0.0.1') }) }) diff --git a/packages/api-server/src/__tests__/fastify.test.ts b/packages/api-server/src/__tests__/fastify.test.ts index cad36b0ef0ad..6023a2c3f79c 100644 --- a/packages/api-server/src/__tests__/fastify.test.ts +++ b/packages/api-server/src/__tests__/fastify.test.ts @@ -73,7 +73,7 @@ describe('createFastifyInstance', () => { { 'redwood.toml': '', }, - FIXTURE_PATH + FIXTURE_PATH, ) await createFastifyInstance() @@ -88,7 +88,7 @@ describe('createFastifyInstance', () => { 'server.config.js': '', }, }, - FIXTURE_PATH + FIXTURE_PATH, ) await createFastifyInstance() diff --git a/packages/api-server/src/__tests__/lambdaLoader.test.ts b/packages/api-server/src/__tests__/lambdaLoader.test.ts index 3a66e89f385e..eff3a3f8b6f8 100644 --- a/packages/api-server/src/__tests__/lambdaLoader.test.ts +++ b/packages/api-server/src/__tests__/lambdaLoader.test.ts @@ -79,7 +79,7 @@ describe('loadFunctionsFromDist', () => { 'noHandler', 'at', expect.any(String), - 'does not have a function called handler defined.' + 'does not have a function called handler defined.', ) }) }) diff --git a/packages/api-server/src/__tests__/logFormatter.test.ts b/packages/api-server/src/__tests__/logFormatter.test.ts index 6c7e2356129c..a80a0177b72a 100644 --- a/packages/api-server/src/__tests__/logFormatter.test.ts +++ b/packages/api-server/src/__tests__/logFormatter.test.ts @@ -30,13 +30,13 @@ describe('LogFormatter', () => { describe('Formats log messages', () => { it('Formats newline-delimited json data with a message', () => { expect( - logFormatter({ level: 10, message: 'Message in a bottle' }) + logFormatter({ level: 10, message: 'Message in a bottle' }), ).toMatch('Message in a bottle') }) it('Formats newline-delimited json data with a msg', () => { expect(logFormatter({ level: 10, msg: 'Message in a bottle' })).toMatch( - 'Message in a bottle' + 'Message in a bottle', ) }) @@ -69,13 +69,13 @@ describe('LogFormatter', () => { query: { id: 1, }, - }) + }), ).toMatch('"id": 1') }) it('Handles operation name', () => { expect( - logFormatter({ level: 10, operationName: 'GET_BLOG_POST_BY_ID' }) + logFormatter({ level: 10, operationName: 'GET_BLOG_POST_BY_ID' }), ).toMatch('GET_BLOG_POST_BY_ID') }) @@ -84,7 +84,7 @@ describe('LogFormatter', () => { logFormatter({ level: 10, data: { post: { id: 1, title: 'My Blog Post' } }, - }) + }), ).toMatch('My Blog Post') }) @@ -95,7 +95,7 @@ describe('LogFormatter', () => { logFormatter({ level: 10, userAgent, - }) + }), ).toMatch(/Mozilla.*AppleWebKit.*Safari/) }) }) @@ -106,7 +106,7 @@ describe('LogFormatter', () => { logFormatter({ level: 10, custom: 'I should see this custom message text', - }) + }), ).toMatch('I should see this') }) @@ -115,7 +115,7 @@ describe('LogFormatter', () => { logFormatter({ level: 10, custom: 'I should see this custom emoji and label', - }) + }), ).toMatch('🗒 Custom') }) @@ -126,7 +126,7 @@ describe('LogFormatter', () => { custom: { string: 'I should see this custom message in the log', }, - }) + }), ).toMatch('I should see this custom message in the log') }) @@ -138,7 +138,7 @@ describe('LogFormatter', () => { string: 'I should see this custom message and number in the log', number: 100, }, - }) + }), ).toMatch('100') }) @@ -150,7 +150,7 @@ describe('LogFormatter', () => { string: 'I should see this custom object in the log', obj: { foo: 'bar' }, }, - }) + }), ).toMatch('"foo": "bar"') }) @@ -162,7 +162,7 @@ describe('LogFormatter', () => { string: 'I should see this custom object in the log', obj: { foo: 'bar' }, }, - }) + }), ).toMatch('"foo": "bar"') }) @@ -183,7 +183,7 @@ describe('LogFormatter', () => { remotePort: 1, }, }, - }) + }), ).not.toMatch('should not appear') }) }) @@ -197,7 +197,7 @@ describe('LogFormatter', () => { stack: 'A stack trace \n will have \n several lines \n at some line number \n at some code', }, - }) + }), ).toMatch(/at some line number/) }) @@ -211,7 +211,7 @@ describe('LogFormatter', () => { stack: 'A stack trace \n will have \n several lines \n at some line number \n at some code', }, - }) + }), ).toMatch(/GraphQL Error Info/) }) @@ -222,7 +222,7 @@ describe('LogFormatter', () => { level: 10, apiVersion: '4.2.1', environment: 'staging', - }) + }), ).toMatch('"apiVersion": "4.2.1"') expect( @@ -230,7 +230,7 @@ describe('LogFormatter', () => { level: 10, apiVersion: '4.2.1', environment: 'staging', - }) + }), ).toMatch('"environment": "staging"') }) @@ -242,7 +242,7 @@ describe('LogFormatter', () => { environment: 'staging', version: '4.2.1', }, - }) + }), ).toMatch('"deploy"') expect( @@ -252,7 +252,7 @@ describe('LogFormatter', () => { environment: 'staging', version: '4.2.1', }, - }) + }), ).toMatch('"environment": "staging"') logFormatter({ @@ -270,7 +270,7 @@ describe('LogFormatter', () => { environment: 'staging', version: '4.2.1', }, - }) + }), ).toMatch('"version": "4.2.1"') }) }) @@ -279,7 +279,7 @@ describe('LogFormatter', () => { expect( logFormatter({ level: 10, - }) + }), ).not.toContain('undefined') }) }) diff --git a/packages/api-server/src/__tests__/requestHandlers/awsLambdaFastify.test.ts b/packages/api-server/src/__tests__/requestHandlers/awsLambdaFastify.test.ts index 2c2b05667aef..92c869559260 100644 --- a/packages/api-server/src/__tests__/requestHandlers/awsLambdaFastify.test.ts +++ b/packages/api-server/src/__tests__/requestHandlers/awsLambdaFastify.test.ts @@ -60,7 +60,7 @@ describe('Tests AWS Lambda to Fastify request transformation and handling', () = await requestHandler(request, mockedReply, handler) expect(mockedReply.send).toHaveBeenCalledWith( - Buffer.from('this_is_a_test_of_base64Encoding', 'base64') + Buffer.from('this_is_a_test_of_base64Encoding', 'base64'), ) expect(mockedReply.status).toHaveBeenCalledWith(200) }) @@ -120,11 +120,11 @@ describe('Tests AWS Lambda to Fastify request transformation and handling', () = expect(mockedReply.headers).not.toHaveBeenCalled() expect(mockedReply.header).toHaveBeenCalledWith( 'content-type', - 'application/json' + 'application/json', ) expect(mockedReply.header).toHaveBeenCalledWith( 'authorization', - 'Bearer token 123' + 'Bearer token 123', ) }) @@ -158,7 +158,7 @@ describe('Tests AWS Lambda to Fastify request transformation and handling', () = expect(mockedReply.headers).not.toHaveBeenCalled() expect(mockedReply.header).toHaveBeenCalledWith( 'content-type', - 'application/json; text/html' + 'application/json; text/html', ) }) }) diff --git a/packages/api-server/src/apiCLIConfigHandler.ts b/packages/api-server/src/apiCLIConfigHandler.ts index 5808b1f476db..40928044b17c 100644 --- a/packages/api-server/src/apiCLIConfigHandler.ts +++ b/packages/api-server/src/apiCLIConfigHandler.ts @@ -42,7 +42,7 @@ export async function handler(options: APIParsedOptions = {}) { fastify.log.trace( { custom: { ...fastify.initialConfig } }, - 'Fastify server configuration' + 'Fastify server configuration', ) fastify.log.trace(`Registered plugins\n${fastify.printPlugins()}`) diff --git a/packages/api-server/src/bin.ts b/packages/api-server/src/bin.ts index cb30140aa0cd..5655bc3c8241 100644 --- a/packages/api-server/src/bin.ts +++ b/packages/api-server/src/bin.ts @@ -44,20 +44,20 @@ yargs(hideBin(process.argv)) bothDescription, // @ts-expect-error The yargs types seem wrong; it's ok for builder to be a function bothBuilder, - bothHandler + bothHandler, ) .command( 'api', apiDescription, // @ts-expect-error The yargs types seem wrong; it's ok for builder to be a function apiBuilder, - apiHandler + apiHandler, ) .command( 'web', webDescription, // @ts-expect-error The yargs types seem wrong; it's ok for builder to be a function webBuilder, - webHandler + webHandler, ) .parse() diff --git a/packages/api-server/src/bothCLIConfigHandler.ts b/packages/api-server/src/bothCLIConfigHandler.ts index 25a6aea6b17c..1191c80e3008 100644 --- a/packages/api-server/src/bothCLIConfigHandler.ts +++ b/packages/api-server/src/bothCLIConfigHandler.ts @@ -49,7 +49,7 @@ export async function handler(options: BothParsedOptions) { webFastify.log.trace( { custom: { ...webFastify.initialConfig } }, - 'Fastify server configuration' + 'Fastify server configuration', ) webFastify.log.trace(`Registered plugins\n${webFastify.printPlugins()}`) @@ -61,7 +61,7 @@ export async function handler(options: BothParsedOptions) { apiFastify.log.trace( { custom: { ...apiFastify.initialConfig } }, - 'Fastify server configuration' + 'Fastify server configuration', ) apiFastify.log.trace(`Registered plugins\n${apiFastify.printPlugins()}`) @@ -69,7 +69,7 @@ export async function handler(options: BothParsedOptions) { const webServer = chalk.green(webFastify.listeningOrigin) const apiServer = chalk.magenta( - `${apiFastify.listeningOrigin}${options.apiRootPath}` + `${apiFastify.listeningOrigin}${options.apiRootPath}`, ) const graphqlEndpoint = chalk.magenta(`${apiServer}graphql`) diff --git a/packages/api-server/src/createServer.ts b/packages/api-server/src/createServer.ts index 925750bae893..13b9e10706cd 100644 --- a/packages/api-server/src/createServer.ts +++ b/packages/api-server/src/createServer.ts @@ -70,7 +70,7 @@ export async function createServer(options: CreateServerOptions = {}) { // Warn about `api/server.config.js` const serverConfigPath = path.join( getPaths().base, - getConfig().api.serverConfig + getConfig().api.serverConfig, ) if (fs.existsSync(serverConfigPath)) { @@ -91,8 +91,8 @@ export async function createServer(options: CreateServerOptions = {}) { 'server.register(myFastifyPlugin)', '```', '', - ].join('\n') - ) + ].join('\n'), + ), ) } @@ -147,8 +147,8 @@ export async function createServer(options: CreateServerOptions = {}) { server.addHook('onListen', (done) => { console.log( `Server listening at ${chalk.magenta( - `${server.listeningOrigin}${apiRootPath}` - )}` + `${server.listeningOrigin}${apiRootPath}`, + )}`, ) done() }) diff --git a/packages/api-server/src/createServerHelpers.ts b/packages/api-server/src/createServerHelpers.ts index fa6e2602f972..298ccfdf1317 100644 --- a/packages/api-server/src/createServerHelpers.ts +++ b/packages/api-server/src/createServerHelpers.ts @@ -58,7 +58,7 @@ type ResolvedOptions = Required< export function resolveOptions( options: CreateServerOptions = {}, - args?: string[] + args?: string[], ) { options.parseArgs ??= true diff --git a/packages/api-server/src/fastify.ts b/packages/api-server/src/fastify.ts index 0f9ef1f25b55..642dbebaa6b2 100644 --- a/packages/api-server/src/fastify.ts +++ b/packages/api-server/src/fastify.ts @@ -26,7 +26,7 @@ let serverConfigFile: { configureFastify: async (fastify, options) => { fastify.log.trace( options, - `In configureFastify hook for side: ${options?.side}` + `In configureFastify hook for side: ${options?.side}`, ) return fastify }, @@ -37,7 +37,7 @@ export async function loadFastifyConfig() { // do we need to babel first? const serverConfigPath = path.join( getPaths().base, - getConfig().api.serverConfig + getConfig().api.serverConfig, ) // If a server.config.js is not found, use the default @@ -57,7 +57,7 @@ export async function loadFastifyConfig() { } export const createFastifyInstance = async ( - options?: FastifyServerOptions + options?: FastifyServerOptions, ): Promise => { const { config } = await loadFastifyConfig() diff --git a/packages/api-server/src/logFormatter/formatters.ts b/packages/api-server/src/logFormatter/formatters.ts index b0ba0716f0c7..8e36ba5d4373 100644 --- a/packages/api-server/src/logFormatter/formatters.ts +++ b/packages/api-server/src/logFormatter/formatters.ts @@ -57,7 +57,7 @@ export const formatCustom = (query?: Record) => { if (!isEmptyObject(query)) { return chalk.white( - NEWLINE + '🗒 Custom' + NEWLINE + JSON.stringify(query, null, 2) + NEWLINE + '🗒 Custom' + NEWLINE + JSON.stringify(query, null, 2), ) } @@ -67,7 +67,7 @@ export const formatCustom = (query?: Record) => { export const formatData = (data?: Record) => { if (!isEmptyObject(data)) { return chalk.white( - NEWLINE + '📦 Result Data' + NEWLINE + JSON.stringify(data, null, 2) + NEWLINE + '📦 Result Data' + NEWLINE + JSON.stringify(data, null, 2), ) } @@ -97,7 +97,7 @@ export const formatErrorProp = (errorPropValue: Record) => { NEWLINE + NEWLINE + JSON.stringify(errorPropValue, null, 2) + - NEWLINE + NEWLINE, ) } @@ -176,7 +176,7 @@ export const formatOperationName = (operationName: string) => { export const formatQuery = (query?: Record) => { if (!isEmptyObject(query)) { return chalk.white( - NEWLINE + '🔭 Query' + NEWLINE + JSON.stringify(query, null, 2) + NEWLINE + '🔭 Query' + NEWLINE + JSON.stringify(query, null, 2), ) } @@ -184,14 +184,14 @@ export const formatQuery = (query?: Record) => { } export const formatResponseCache = ( - responseCache?: Record + responseCache?: Record, ) => { if (!isEmptyObject(responseCache)) { return chalk.white( NEWLINE + '💾 Response Cache' + NEWLINE + - JSON.stringify(responseCache, null, 2) + JSON.stringify(responseCache, null, 2), ) } @@ -207,14 +207,14 @@ export const formatStack = (stack?: string | Record) => { return chalk.redBright( stack ? NEWLINE + '🥞 Error Stack' + NEWLINE + NEWLINE + stack + NEWLINE - : '' + : '', ) } export const formatTracing = (data?: Record) => { if (!isEmptyObject(data)) { return chalk.white( - NEWLINE + '⏰ Timing' + NEWLINE + JSON.stringify(data, null, 2) + NEWLINE + '⏰ Timing' + NEWLINE + JSON.stringify(data, null, 2), ) } diff --git a/packages/api-server/src/plugins/api.ts b/packages/api-server/src/plugins/api.ts index fe0bc1de24ac..665ff79d82a5 100644 --- a/packages/api-server/src/plugins/api.ts +++ b/packages/api-server/src/plugins/api.ts @@ -21,7 +21,7 @@ export interface RedwoodFastifyAPIOptions { export async function redwoodFastifyAPI( fastify: FastifyInstance, - opts: RedwoodFastifyAPIOptions + opts: RedwoodFastifyAPIOptions, ) { const redwoodOptions = opts.redwood ?? {} redwoodOptions.apiRootPath ??= '/' @@ -41,7 +41,7 @@ export async function redwoodFastifyAPI( fastify.addContentTypeParser( ['application/x-www-form-urlencoded', 'multipart/form-data'], { parseAs: 'string' }, - fastify.defaultTextParser + fastify.defaultTextParser, ) if (redwoodOptions.loadUserConfig) { diff --git a/packages/api-server/src/plugins/graphql.ts b/packages/api-server/src/plugins/graphql.ts index 779bd44385a8..08cdc279e515 100644 --- a/packages/api-server/src/plugins/graphql.ts +++ b/packages/api-server/src/plugins/graphql.ts @@ -27,7 +27,7 @@ export interface RedwoodFastifyGraphQLOptions { export async function redwoodFastifyGraphQLServer( fastify: FastifyInstance, - options: RedwoodFastifyGraphQLOptions + options: RedwoodFastifyGraphQLOptions, ) { const redwoodOptions = options.redwood ?? {} redwoodOptions.apiRootPath ??= '/' @@ -83,7 +83,7 @@ export async function redwoodFastifyGraphQLServer( const graphQLYogaHandler = async ( req: FastifyRequest, - reply: FastifyReply + reply: FastifyReply, ) => { const response = await yoga.handleNodeRequest(req, { req, @@ -116,10 +116,10 @@ export async function redwoodFastifyGraphQLServer( fastify.addHook('onReady', (done) => { console.info(`GraphQL Yoga Server endpoint at ${graphqlEndpoint}`) console.info( - `GraphQL Yoga Server Health Check endpoint at ${graphqlEndpoint}/health` + `GraphQL Yoga Server Health Check endpoint at ${graphqlEndpoint}/health`, ) console.info( - `GraphQL Yoga Server Readiness endpoint at ${graphqlEndpoint}/readiness` + `GraphQL Yoga Server Readiness endpoint at ${graphqlEndpoint}/readiness`, ) done() diff --git a/packages/api-server/src/plugins/lambdaLoader.ts b/packages/api-server/src/plugins/lambdaLoader.ts index 757dce9d2f4d..b51ead976176 100644 --- a/packages/api-server/src/plugins/lambdaLoader.ts +++ b/packages/api-server/src/plugins/lambdaLoader.ts @@ -35,20 +35,20 @@ export const setLambdaFunctions = async (foundFunctions: string[]) => { routeName, 'at', fnPath, - 'does not have a function called handler defined.' + 'does not have a function called handler defined.', ) } // TODO: Use terminal link. console.log( chalk.magenta('/' + routeName), - chalk.dim.italic(Date.now() - ts + ' ms') + chalk.dim.italic(Date.now() - ts + ' ms'), ) }) await Promise.all(imports) console.log( - chalk.dim.italic('...Done importing in ' + (Date.now() - tsImport) + ' ms') + chalk.dim.italic('...Done importing in ' + (Date.now() - tsImport) + ' ms'), ) } @@ -58,11 +58,11 @@ type LoadFunctionsFromDistOptions = { // TODO: Use v8 caching to load these crazy fast. export const loadFunctionsFromDist = async ( - options: LoadFunctionsFromDistOptions = {} + options: LoadFunctionsFromDistOptions = {}, ) => { const serverFunctions = findApiDistFunctions( getPaths().api.base, - options?.fastGlobOptions + options?.fastGlobOptions, ) // Place `GraphQL` serverless function at the start. @@ -78,7 +78,7 @@ export const loadFunctionsFromDist = async ( // import { findApiDistFunctions } from '@redwoodjs/internal/dist/files' function findApiDistFunctions( cwd: string = getPaths().api.base, - options: FastGlobOptions = {} + options: FastGlobOptions = {}, ) { return fg.sync('dist/functions/**/*.{ts,js}', { cwd, @@ -101,7 +101,7 @@ interface LambdaHandlerRequest extends RequestGenericInterface { **/ export const lambdaRequestHandler = async ( req: FastifyRequest, - reply: FastifyReply + reply: FastifyReply, ) => { const { routeName } = req.params diff --git a/packages/api-server/src/requestHandlers/awsLambdaFastify.ts b/packages/api-server/src/requestHandlers/awsLambdaFastify.ts index b68fc38a123c..611ad66d7f21 100644 --- a/packages/api-server/src/requestHandlers/awsLambdaFastify.ts +++ b/packages/api-server/src/requestHandlers/awsLambdaFastify.ts @@ -9,7 +9,7 @@ import qs from 'qs' import { mergeMultiValueHeaders, parseBody } from './utils' export const lambdaEventForFastifyRequest = ( - request: FastifyRequest + request: FastifyRequest, ): APIGatewayProxyEvent => { return { httpMethod: request.method, @@ -28,7 +28,7 @@ export const lambdaEventForFastifyRequest = ( const fastifyResponseForLambdaResult = ( reply: FastifyReply, - lambdaResult: APIGatewayProxyResult + lambdaResult: APIGatewayProxyResult, ) => { const { statusCode = 200, @@ -38,7 +38,7 @@ const fastifyResponseForLambdaResult = ( } = lambdaResult const mergedHeaders = mergeMultiValueHeaders(headers, multiValueHeaders) Object.entries(mergedHeaders).forEach(([name, values]) => - values.forEach((value) => reply.header(name, value)) + values.forEach((value) => reply.header(name, value)), ) reply.status(statusCode) @@ -54,7 +54,7 @@ const fastifyResponseForLambdaResult = ( const fastifyResponseForLambdaError = ( req: FastifyRequest, reply: FastifyReply, - error: Error + error: Error, ) => { req.log.error(error) reply.status(500).send() @@ -63,7 +63,7 @@ const fastifyResponseForLambdaError = ( export const requestHandler = async ( req: FastifyRequest, reply: FastifyReply, - handler: Handler + handler: Handler, ) => { // We take the fastify request object and convert it into a lambda function event. const event = lambdaEventForFastifyRequest(req) @@ -85,7 +85,7 @@ export const requestHandler = async ( event, // @ts-expect-error - Add support for context: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/0bb210867d16170c4a08d9ce5d132817651a0f80/types/aws-lambda/index.d.ts#L443-L467 {}, - handlerCallback(reply) + handlerCallback(reply), ) // In this case the handlerCallback should not be called. diff --git a/packages/api-server/src/requestHandlers/utils.ts b/packages/api-server/src/requestHandlers/utils.ts index dfd3e0a41b04..8ed97edeb3f7 100644 --- a/packages/api-server/src/requestHandlers/utils.ts +++ b/packages/api-server/src/requestHandlers/utils.ts @@ -34,10 +34,10 @@ export const parseBody = (rawBody: string | Buffer): ParseBodyResult => { */ export const mergeMultiValueHeaders = ( headers: FastifyLambdaHeaders, - multiValueHeaders: FastifyLambdaMultiValueHeaders + multiValueHeaders: FastifyLambdaMultiValueHeaders, ) => { const mergedHeaders = Object.entries( - headers || {} + headers || {}, ).reduce((acc, [name, value]) => { acc[name.toLowerCase()] = [value] diff --git a/packages/api-server/src/types.ts b/packages/api-server/src/types.ts index 55b350ab59a4..cf17b978ba82 100644 --- a/packages/api-server/src/types.ts +++ b/packages/api-server/src/types.ts @@ -10,7 +10,7 @@ export type FastifySideConfigFnOptions = { export type FastifySideConfigFn = ( fastify: FastifyInstance, options?: FastifySideConfigFnOptions & - Pick + Pick, ) => Promise | void export type APIParsedOptions = { diff --git a/packages/api-server/src/watch.ts b/packages/api-server/src/watch.ts index bad8c36b43e9..c96de6027cb0 100644 --- a/packages/api-server/src/watch.ts +++ b/packages/api-server/src/watch.ts @@ -63,7 +63,7 @@ const validate = async () => { } catch (e: any) { killApiServer() console.error( - chalk.redBright(`[GQL Server Error] - Schema validation failed`) + chalk.redBright(`[GQL Server Error] - Schema validation failed`), ) console.error(chalk.red(e?.message)) console.error(chalk.redBright('-'.repeat(40))) @@ -105,14 +105,14 @@ const buildAndRestart = async ({ // We expect the OpenTelemetry SDK setup file to be in a specific location const opentelemetrySDKScriptPath = path.join( rwjsPaths.api.dist, - 'opentelemetry.js' + 'opentelemetry.js', ) const opentelemetrySDKScriptPathRelative = path.relative( rwjsPaths.base, - opentelemetrySDKScriptPath + opentelemetrySDKScriptPath, ) console.log( - `Setting up OpenTelemetry using the setup file: ${opentelemetrySDKScriptPathRelative}` + `Setting up OpenTelemetry using the setup file: ${opentelemetrySDKScriptPathRelative}`, ) if (fs.existsSync(opentelemetrySDKScriptPath)) { forkOpts.execArgv = forkOpts.execArgv.concat([ @@ -120,7 +120,7 @@ const buildAndRestart = async ({ ]) } else { console.error( - `OpenTelemetry setup file does not exist at ${opentelemetrySDKScriptPathRelative}` + `OpenTelemetry setup file does not exist at ${opentelemetrySDKScriptPathRelative}`, ) } } @@ -139,13 +139,13 @@ const buildAndRestart = async ({ httpServerProcess = fork( serverFile, ['--apiPort', port.toString()], - forkOpts + forkOpts, ) } else { httpServerProcess = fork( path.join(__dirname, 'bin.js'), ['api', '--port', port.toString()], - forkOpts + forkOpts, ) } } catch (e) { @@ -161,14 +161,14 @@ const debouncedRebuild = debounce( () => buildAndRestart({ rebuild: true }), process.env.RWJS_DELAY_RESTART ? parseInt(process.env.RWJS_DELAY_RESTART, 10) - : 500 + : 500, ) const debouncedBuild = debounce( () => buildAndRestart({ rebuild: false }), process.env.RWJS_DELAY_RESTART ? parseInt(process.env.RWJS_DELAY_RESTART, 10) - : 500 + : 500, ) // NOTE: the file comes through as a unix path, even on windows @@ -234,7 +234,7 @@ chokidar } console.log( - chalk.dim(`[${eventName}] ${filePath.replace(rwjsPaths.api.base, '')}`) + chalk.dim(`[${eventName}] ${filePath.replace(rwjsPaths.api.base, '')}`), ) if (eventName === 'add' || eventName === 'unlink') { diff --git a/packages/api/src/__tests__/normalizeRequest.test.ts b/packages/api/src/__tests__/normalizeRequest.test.ts index c39e316eceda..98ad6306858f 100644 --- a/packages/api/src/__tests__/normalizeRequest.test.ts +++ b/packages/api/src/__tests__/normalizeRequest.test.ts @@ -7,7 +7,7 @@ import { normalizeRequest } from '../transforms' export const createMockedLambdaEvent = ( httpMethod = 'POST', body: any = undefined, - isBase64Encoded = false + isBase64Encoded = false, ): APIGatewayProxyEvent => { return { body, @@ -59,9 +59,9 @@ describe('Lambda Request', () => { const corsEventB64 = createMockedLambdaEvent( 'POST', Buffer.from(JSON.stringify({ bazinga: 'hello_world' }), 'utf8').toString( - 'base64' + 'base64', ), - true + true, ) expect(await normalizeRequest(corsEventB64)).toEqual({ @@ -87,7 +87,7 @@ describe('Lambda Request', () => { const corsEventWithoutB64 = createMockedLambdaEvent( 'OPTIONS', undefined, - false + false, ) expect(await normalizeRequest(corsEventWithoutB64)).toEqual({ @@ -109,7 +109,7 @@ describe('Fetch API Request', () => { 'content-type': 'application/json', }, body: JSON.stringify({ bazinga: 'kittens_purr_purr' }), - } + }, ) const partial = await normalizeRequest(fetchEvent) @@ -141,7 +141,7 @@ describe('Fetch API Request', () => { method: 'PUT', headers, body: '', - } + }, ) const partial = await normalizeRequest(fetchEvent) diff --git a/packages/api/src/auth/index.ts b/packages/api/src/auth/index.ts index 77fd6e7789f4..b93eebaa584e 100644 --- a/packages/api/src/auth/index.ts +++ b/packages/api/src/auth/index.ts @@ -11,10 +11,10 @@ export type { Decoded } const AUTH_PROVIDER_HEADER = 'auth-provider' export const getAuthProviderHeader = ( - event: APIGatewayProxyEvent | Request + event: APIGatewayProxyEvent | Request, ) => { const authProviderKey = Object.keys(event?.headers ?? {}).find( - (key) => key.toLowerCase() === AUTH_PROVIDER_HEADER + (key) => key.toLowerCase() === AUTH_PROVIDER_HEADER, ) if (authProviderKey) { return getEventHeader(event, authProviderKey) @@ -31,7 +31,7 @@ export interface AuthorizationHeader { * Split the `Authorization` header into a schema and token part. */ export const parseAuthorizationHeader = ( - event: APIGatewayProxyEvent | Request + event: APIGatewayProxyEvent | Request, ): AuthorizationHeader => { const parts = getEventHeader(event, 'authorization')?.split(' ') if (parts?.length !== 2) { @@ -55,13 +55,13 @@ export const parseAuthorizationHeader = ( export type AuthContextPayload = [ Decoded, { type: string } & AuthorizationHeader, - { event: APIGatewayProxyEvent | Request; context: LambdaContext } + { event: APIGatewayProxyEvent | Request; context: LambdaContext }, ] export type Decoder = ( token: string, type: string, - req: { event: APIGatewayProxyEvent | Request; context: LambdaContext } + req: { event: APIGatewayProxyEvent | Request; context: LambdaContext }, ) => Promise /** diff --git a/packages/api/src/auth/verifiers/__tests__/jwtVerifier.test.ts b/packages/api/src/auth/verifiers/__tests__/jwtVerifier.test.ts index 985c9d37ffb9..ff686de2d000 100644 --- a/packages/api/src/auth/verifiers/__tests__/jwtVerifier.test.ts +++ b/packages/api/src/auth/verifiers/__tests__/jwtVerifier.test.ts @@ -15,7 +15,7 @@ describe('jwtVerifier verifier', () => { const { sign } = createVerifier('jwtVerifier') const signature = sign({ payload, secret }) expect(signature).toMatch( - /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/ + /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/, ) }) }) diff --git a/packages/api/src/auth/verifiers/base64Sha1Verifier.ts b/packages/api/src/auth/verifiers/base64Sha1Verifier.ts index 54a29a08ac83..847d1a8216ec 100644 --- a/packages/api/src/auth/verifiers/base64Sha1Verifier.ts +++ b/packages/api/src/auth/verifiers/base64Sha1Verifier.ts @@ -66,7 +66,7 @@ export const verifySignature = ({ throw new WebhookVerificationError() } catch (error: any) { throw new WebhookVerificationError( - `${VERIFICATION_ERROR_MESSAGE}: ${error.message}` + `${VERIFICATION_ERROR_MESSAGE}: ${error.message}`, ) } } diff --git a/packages/api/src/auth/verifiers/base64Sha256Verifier.ts b/packages/api/src/auth/verifiers/base64Sha256Verifier.ts index 913bde6fd050..1ae71ea114b3 100644 --- a/packages/api/src/auth/verifiers/base64Sha256Verifier.ts +++ b/packages/api/src/auth/verifiers/base64Sha256Verifier.ts @@ -66,7 +66,7 @@ export const verifySignature = ({ throw new WebhookVerificationError() } catch (error: any) { throw new WebhookVerificationError( - `${VERIFICATION_ERROR_MESSAGE}: ${error.message}` + `${VERIFICATION_ERROR_MESSAGE}: ${error.message}`, ) } } @@ -79,7 +79,7 @@ export const verifySignature = ({ * @see https://github.com/svix/svix-webhooks/blob/main/javascript/src/index.ts */ const base64Sha256Verifier = ( - _options?: VerifyOptions + _options?: VerifyOptions, ): Base64Sha256Verifier => { return { sign: ({ payload, secret }) => { diff --git a/packages/api/src/auth/verifiers/index.ts b/packages/api/src/auth/verifiers/index.ts index da124bc99c30..e720c7c9d359 100644 --- a/packages/api/src/auth/verifiers/index.ts +++ b/packages/api/src/auth/verifiers/index.ts @@ -11,7 +11,7 @@ import type { */ export const createVerifier = ( type: SupportedVerifierTypes, - options?: VerifyOptions + options?: VerifyOptions, ): WebhookVerifier => { if (options) { return verifierLookup[type](options) diff --git a/packages/api/src/auth/verifiers/sha1Verifier.ts b/packages/api/src/auth/verifiers/sha1Verifier.ts index d64b6fc9db6e..90fdd9329900 100644 --- a/packages/api/src/auth/verifiers/sha1Verifier.ts +++ b/packages/api/src/auth/verifiers/sha1Verifier.ts @@ -37,7 +37,7 @@ const createSignature = ({ const digest = Buffer.from( algorithm + '=' + hmac.update(payload).digest('hex'), - 'utf8' + 'utf8', ) return digest.toString() @@ -67,7 +67,7 @@ export const verifySignature = ({ const digest = Buffer.from( algorithm + '=' + hmac.update(payload).digest('hex'), - 'utf8' + 'utf8', ) // constant time comparison to prevent timing attacks @@ -84,7 +84,7 @@ export const verifySignature = ({ throw new WebhookVerificationError() } catch (error: any) { throw new WebhookVerificationError( - `${VERIFICATION_ERROR_MESSAGE}: ${error.message}` + `${VERIFICATION_ERROR_MESSAGE}: ${error.message}`, ) } } diff --git a/packages/api/src/auth/verifiers/sha256Verifier.ts b/packages/api/src/auth/verifiers/sha256Verifier.ts index 2c4be0cc3d68..4cbbbca53ff6 100644 --- a/packages/api/src/auth/verifiers/sha256Verifier.ts +++ b/packages/api/src/auth/verifiers/sha256Verifier.ts @@ -37,7 +37,7 @@ const createSignature = ({ const digest = Buffer.from( algorithm + '=' + hmac.update(payload).digest('hex'), - 'utf8' + 'utf8', ) return digest.toString() @@ -67,7 +67,7 @@ export const verifySignature = ({ const digest = Buffer.from( algorithm + '=' + hmac.update(payload).digest('hex'), - 'utf8' + 'utf8', ) // constant time comparison to prevent timing attacks @@ -84,7 +84,7 @@ export const verifySignature = ({ throw new WebhookVerificationError() } catch (error: any) { throw new WebhookVerificationError( - `${VERIFICATION_ERROR_MESSAGE}: ${error.message}` + `${VERIFICATION_ERROR_MESSAGE}: ${error.message}`, ) } } diff --git a/packages/api/src/auth/verifiers/timestampSchemeVerifier.ts b/packages/api/src/auth/verifiers/timestampSchemeVerifier.ts index e5b3b72fd067..d96d2618f918 100644 --- a/packages/api/src/auth/verifiers/timestampSchemeVerifier.ts +++ b/packages/api/src/auth/verifiers/timestampSchemeVerifier.ts @@ -139,7 +139,7 @@ const verifySignature = ({ * */ const timestampSchemeVerifier = ( - options?: VerifyOptions + options?: VerifyOptions, ): TimestampSchemeVerifier => { return { sign: ({ payload, secret }) => { diff --git a/packages/api/src/bins/redwood.ts b/packages/api/src/bins/redwood.ts index 7c3de49808df..7b8ed6c86426 100644 --- a/packages/api/src/bins/redwood.ts +++ b/packages/api/src/bins/redwood.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromCli = createRequire( - require.resolve('@redwoodjs/cli/package.json') + require.resolve('@redwoodjs/cli/package.json'), ) const bins = requireFromCli('./package.json')['bin'] diff --git a/packages/api/src/bins/rwfw.ts b/packages/api/src/bins/rwfw.ts index 31c3e0e8b40f..c7585af03983 100644 --- a/packages/api/src/bins/rwfw.ts +++ b/packages/api/src/bins/rwfw.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromCli = createRequire( - require.resolve('@redwoodjs/cli/package.json') + require.resolve('@redwoodjs/cli/package.json'), ) const bins = requireFromCli('./package.json')['bin'] diff --git a/packages/api/src/bins/tsc.ts b/packages/api/src/bins/tsc.ts index 22c9992cec31..d447f04f5a1b 100644 --- a/packages/api/src/bins/tsc.ts +++ b/packages/api/src/bins/tsc.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromTypeScript = createRequire( - require.resolve('typescript/package.json') + require.resolve('typescript/package.json'), ) const bins = requireFromTypeScript('./package.json')['bin'] diff --git a/packages/api/src/cache/__tests__/cacheFindMany.test.ts b/packages/api/src/cache/__tests__/cacheFindMany.test.ts index 0eb8008daa08..c114dd929653 100644 --- a/packages/api/src/cache/__tests__/cacheFindMany.test.ts +++ b/packages/api/src/cache/__tests__/cacheFindMany.test.ts @@ -42,7 +42,7 @@ describe('cacheFindMany', () => { expect(spy).toHaveBeenCalled() expect(client.storage[`test-1-${now.getTime()}`].value).toEqual( - JSON.stringify([user]) + JSON.stringify([user]), ) }) @@ -76,11 +76,11 @@ describe('cacheFindMany', () => { expect(spy).toHaveBeenCalled() // the `now` cache still exists expect( - JSON.parse(client.storage[`test-1-${now.getTime()}`].value)[0].id + JSON.parse(client.storage[`test-1-${now.getTime()}`].value)[0].id, ).toEqual(1) // the `future` cache should have been created expect(client.storage[`test-1-${future.getTime()}`].value).toEqual( - JSON.stringify([user]) + JSON.stringify([user]), ) }) diff --git a/packages/api/src/cache/clients/BaseClient.ts b/packages/api/src/cache/clients/BaseClient.ts index 9cf6d3382ee0..e2642a3f09d3 100644 --- a/packages/api/src/cache/clients/BaseClient.ts +++ b/packages/api/src/cache/clients/BaseClient.ts @@ -14,7 +14,7 @@ export default abstract class BaseClient { abstract set( key: string, value: unknown, - options: { expires?: number } + options: { expires?: number }, ): Promise | any // types are tightened in the child classes // Removes a value by its key diff --git a/packages/api/src/cache/clients/InMemoryClient.ts b/packages/api/src/cache/clients/InMemoryClient.ts index 0668ff7f0e15..2b3ad256ef7d 100644 --- a/packages/api/src/cache/clients/InMemoryClient.ts +++ b/packages/api/src/cache/clients/InMemoryClient.ts @@ -23,7 +23,7 @@ export default class InMemoryClient extends BaseClient { */ get contents() { return Object.values(this.storage).map((cacheObj) => - JSON.parse(cacheObj.value) + JSON.parse(cacheObj.value), ) } diff --git a/packages/api/src/cache/clients/RedisClient.ts b/packages/api/src/cache/clients/RedisClient.ts index 04cd102a3552..a6211fad87bb 100644 --- a/packages/api/src/cache/clients/RedisClient.ts +++ b/packages/api/src/cache/clients/RedisClient.ts @@ -33,7 +33,7 @@ export default class RedisClient extends BaseClient { this.client = createClient(this.redisOptions) as RedisClientType this.client.on( 'error', - (err: Error) => this.logger?.error(err) || console.error(err) + (err: Error) => this.logger?.error(err) || console.error(err), ) return this.client.connect() diff --git a/packages/api/src/cache/index.ts b/packages/api/src/cache/index.ts index bc32e37cfe83..f10fe78aeee4 100644 --- a/packages/api/src/cache/index.ts +++ b/packages/api/src/cache/index.ts @@ -22,7 +22,7 @@ export interface CacheOptions { } export interface CacheFindManyOptions< - TFindManyArgs extends Record + TFindManyArgs extends Record, > extends CacheOptions { conditions?: TFindManyArgs } @@ -69,7 +69,7 @@ const serialize = (input: any) => { export const createCache = ( cacheClient: BaseClient, - options?: CreateCacheOptions + options?: CreateCacheOptions, ) => { const client = cacheClient const logger = options?.logger @@ -80,7 +80,7 @@ export const createCache = ( const cache = async ( key: CacheKey, input: () => TResult | Promise, - options?: CacheOptions + options?: CacheOptions, ): Promise => { const cacheKey = formatCacheKey(key, prefix) @@ -125,7 +125,7 @@ export const createCache = ( ]) logger?.debug( - `[Cache] MISS '${cacheKey}', SET ${JSON.stringify(data).length} bytes` + `[Cache] MISS '${cacheKey}', SET ${JSON.stringify(data).length} bytes`, ) return serialize(data) } catch (e: any) { @@ -137,7 +137,7 @@ export const createCache = ( const cacheFindMany = async ( key: CacheKey, model: TDelegate, - options: CacheFindManyOptions[0]> = {} + options: CacheFindManyOptions[0]> = {}, ) => { const { conditions, ...rest } = options const cacheKey = formatCacheKey(key, prefix) @@ -158,7 +158,7 @@ export const createCache = ( } catch (e: any) { if (e instanceof PrismaClientValidationError) { logger?.error( - `[Cache] cacheFindMany error: model does not contain \`${fields.id}\` or \`${fields.updatedAt}\` fields` + `[Cache] cacheFindMany error: model does not contain \`${fields.id}\` or \`${fields.updatedAt}\` fields`, ) } else { logger?.error(`[Cache] cacheFindMany error: ${e.message}`) @@ -175,7 +175,7 @@ export const createCache = ( }${cacheKeySeparator}${latest[fields.updatedAt].getTime()}` } else { logger?.debug( - `[Cache] cacheFindMany: No data to cache for key \`${key}\`, skipping` + `[Cache] cacheFindMany: No data to cache for key \`${key}\`, skipping`, ) return serialize(await model.findMany(conditions)) diff --git a/packages/api/src/cors.ts b/packages/api/src/cors.ts index 7a33d55e0c14..6ab493845367 100644 --- a/packages/api/src/cors.ts +++ b/packages/api/src/cors.ts @@ -34,7 +34,7 @@ export function createCorsContext(cors: CorsConfig | undefined) { } else if (Array.isArray(cors.allowedHeaders)) { corsHeaders.set( 'access-control-allow-headers', - cors.allowedHeaders.join(',') + cors.allowedHeaders.join(','), ) } } @@ -45,7 +45,7 @@ export function createCorsContext(cors: CorsConfig | undefined) { } else if (Array.isArray(cors.exposedHeaders)) { corsHeaders.set( 'access-control-expose-headers', - cors.exposedHeaders.join(',') + cors.exposedHeaders.join(','), ) } } @@ -81,12 +81,12 @@ export function createCorsContext(cors: CorsConfig | undefined) { } const requestAccessControlRequestHeaders = eventHeaders.get( - 'access-control-request-headers' + 'access-control-request-headers', ) if (!cors.allowedHeaders && requestAccessControlRequestHeaders) { requestCorsHeaders.set( 'access-control-allow-headers', - requestAccessControlRequestHeaders + requestAccessControlRequestHeaders, ) } } diff --git a/packages/api/src/event.ts b/packages/api/src/event.ts index 90b7e8fa8bbc..68b0a0402caa 100644 --- a/packages/api/src/event.ts +++ b/packages/api/src/event.ts @@ -5,7 +5,7 @@ import { isFetchApiRequest } from './transforms' // Extracts the header from an event, handling lower and upper case header names. export const getEventHeader = ( event: APIGatewayProxyEvent | Request, - headerName: string + headerName: string, ) => { if (isFetchApiRequest(event)) { return event.headers.get(headerName) diff --git a/packages/api/src/logger/index.ts b/packages/api/src/logger/index.ts index 421f20b18841..819c88fc373b 100644 --- a/packages/api/src/logger/index.ts +++ b/packages/api/src/logger/index.ts @@ -224,7 +224,7 @@ export const createLogger = ({ if (isFile) { if (isProduction) { console.warn( - 'Please make certain that file system access is available when logging to a file in a production environment.' + 'Please make certain that file system access is available when logging to a file in a production environment.', ) } @@ -232,7 +232,7 @@ export const createLogger = ({ } else { if (isStream && isDevelopment && !isTest) { console.warn( - 'Logs will be sent to the transport stream in the current development environment.' + 'Logs will be sent to the transport stream in the current development environment.', ) } @@ -321,12 +321,12 @@ export const handlePrismaLogging = (config: PrismaLoggingConfig): void => { if (queryEvent.duration >= slowQueryThreshold) { logger.warn( { ...queryEvent }, - `Slow Query performed in ${queryEvent.duration} msec` + `Slow Query performed in ${queryEvent.duration} msec`, ) } else { logger.debug( { ...queryEvent }, - `Query performed in ${queryEvent.duration} msec` + `Query performed in ${queryEvent.duration} msec`, ) } }) diff --git a/packages/api/src/logger/logger.test.ts b/packages/api/src/logger/logger.test.ts index 5663f9e235f4..dbc6025e8063 100644 --- a/packages/api/src/logger/logger.test.ts +++ b/packages/api/src/logger/logger.test.ts @@ -61,7 +61,7 @@ const watchFileCreated = (filename) => { const setupLogger = ( loggerOptions?: LoggerOptions, destination?: string, - showConfig?: boolean + showConfig?: boolean, ): { logger: BaseLogger logSinkData?: Promise @@ -190,7 +190,7 @@ describe('logger', () => { expect(logStatement).toHaveProperty('event') expect(logStatement['event']['headers']['authorization']).toEqual( - '[Redacted]' + '[Redacted]', ) }) @@ -215,7 +215,7 @@ describe('logger', () => { { jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', }, - 'test of a redacted JWT' + 'test of a redacted JWT', ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted JWT') @@ -231,7 +231,7 @@ describe('logger', () => { { password: '123456', }, - 'test of a redacted password' + 'test of a redacted password', ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted password') @@ -247,7 +247,7 @@ describe('logger', () => { { hashedPassword: 'c0RnBEEF####', }, - 'test of a redacted hashed password' + 'test of a redacted hashed password', ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted hashed password') @@ -265,11 +265,11 @@ describe('logger', () => { hashedPassword: 'c0RnBEEF####', }, }, - 'test of a redacted data hashed password' + 'test of a redacted data hashed password', ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual( - 'test of a redacted data hashed password' + 'test of a redacted data hashed password', ) expect(logStatement).toHaveProperty('data.hashedPassword') @@ -287,16 +287,16 @@ describe('logger', () => { }, }, }, - 'test of a redacted user data hashed password' + 'test of a redacted user data hashed password', ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual( - 'test of a redacted user data hashed password' + 'test of a redacted user data hashed password', ) expect(logStatement).toHaveProperty('data.user.hashedPassword') expect(logStatement['data']['user']['hashedPassword']).toEqual( - '[Redacted]' + '[Redacted]', ) }) @@ -307,7 +307,7 @@ describe('logger', () => { { salt: 'npeppa', }, - 'test of a redacted salt' + 'test of a redacted salt', ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted salt') @@ -325,7 +325,7 @@ describe('logger', () => { salt: 'npeppa', }, }, - 'test of a redacted data salt' + 'test of a redacted data salt', ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted data salt') @@ -345,7 +345,7 @@ describe('logger', () => { }, }, }, - 'test of a redacted user data salt' + 'test of a redacted user data salt', ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted user data salt') @@ -361,7 +361,7 @@ describe('logger', () => { { email: 'alice@example.com', }, - 'test of a redacted email' + 'test of a redacted email', ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted email') @@ -375,7 +375,7 @@ describe('logger', () => { test('it creates a log file with a statement', async () => { const tmp = join( os.tmpdir(), - '_' + Math.random().toString(36).substr(2, 9) + '_' + Math.random().toString(36).substr(2, 9), ) const { logger } = setupLogger({ level: 'trace' }, tmp) diff --git a/packages/api/src/transforms.ts b/packages/api/src/transforms.ts index 3fb7eb010f86..908f82b5273a 100644 --- a/packages/api/src/transforms.ts +++ b/packages/api/src/transforms.ts @@ -44,7 +44,7 @@ export const parseFetchEventBody = async (event: Request) => { } export const isFetchApiRequest = ( - event: Request | APIGatewayProxyEvent + event: Request | APIGatewayProxyEvent, ): event is Request => { if ( event.constructor.name === 'Request' || @@ -80,7 +80,7 @@ function getQueryStringParams(reqUrl: string) { * NOTE: It does NOT return a full Request object! */ export async function normalizeRequest( - event: APIGatewayProxyEvent | Request + event: APIGatewayProxyEvent | Request, ): Promise { if (isFetchApiRequest(event)) { return { diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index 3217855f3cfe..9ccfc95599ee 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -17,13 +17,13 @@ type SdlOnlyFields = Omit // Object with all the optional keys, so that we can make them nullable type PrismaTypeWithOptionalKeysFromSdl< TPrisma extends AnyObject, - TSdl extends AnyObject + TSdl extends AnyObject, > = Pick> // Make the optional values nullable type PrismaTypeWithOptionalKeysAndNullableValues< TPrisma extends AnyObject, - TSdl extends AnyObject + TSdl extends AnyObject, > = { [k in keyof PrismaTypeWithOptionalKeysFromSdl]?: | PrismaTypeWithOptionalKeysFromSdl[k] @@ -33,13 +33,13 @@ type PrismaTypeWithOptionalKeysAndNullableValues< // Object with all the required keys type PrismaTypeWithRequiredKeysFromSdl< TPrisma extends AnyObject, - TSdl extends AnyObject + TSdl extends AnyObject, > = Pick> // To replace the unknowns with types from Sdl on SDL-only fields type OptionalsAndSdlOnly< TPrisma extends AnyObject, - TSdl extends AnyObject + TSdl extends AnyObject, > = PrismaTypeWithOptionalKeysAndNullableValues & SdlOnlyFields @@ -58,7 +58,7 @@ export type MakeRelationsOptional = { export type MergePrismaWithSdlTypes< TPrisma extends AnyObject, TSdl extends AnyObject, - TAllMappedModels + TAllMappedModels, > = A.Compute< OptionalsAndSdlOnly> & PrismaTypeWithRequiredKeysFromSdl< diff --git a/packages/api/src/validations/__tests__/validations.test.js b/packages/api/src/validations/__tests__/validations.test.js index a411a8c4a3d3..146ced0f0917 100644 --- a/packages/api/src/validations/__tests__/validations.test.js +++ b/packages/api/src/validations/__tests__/validations.test.js @@ -11,19 +11,19 @@ import { describe('validate absence', () => { it('checks if value is null or undefined', () => { expect(() => - validate('rob@redwoodjs.com', 'email', { absence: true }) + validate('rob@redwoodjs.com', 'email', { absence: true }), ).toThrow(ValidationErrors.AbsenceValidationError) expect(() => validate('', 'email', { absence: true })).toThrow( - ValidationErrors.AbsenceValidationError + ValidationErrors.AbsenceValidationError, ) expect(() => - validate('', 'email', { absence: { allowEmptyString: false } }) + validate('', 'email', { absence: { allowEmptyString: false } }), ).toThrow(ValidationErrors.AbsenceValidationError) expect(() => validate(null, 'email', { absence: true })).not.toThrow() expect(() => validate(undefined, 'email', { absence: true })).not.toThrow() expect(() => - validate('', 'email', { absence: { allowEmptyString: true } }) + validate('', 'email', { absence: { allowEmptyString: true } }), ).not.toThrow() }) @@ -70,22 +70,22 @@ describe('validate acceptance', () => { it('checks for truthiness', () => { ;[null, undefined, 0, 1, '1', 'true'].forEach((val) => { expect(() => validate(val, 'terms', { acceptance: true })).toThrow( - ValidationErrors.AcceptanceValidationError + ValidationErrors.AcceptanceValidationError, ) }) expect(() => - validate('terms', 'true', { acceptance: { in: ['1'] } }) + validate('terms', 'true', { acceptance: { in: ['1'] } }), ).toThrow(ValidationErrors.AcceptanceValidationError) expect(() => validate(1, 'terms', { acceptance: { in: ['1'] } })).toThrow( - ValidationErrors.AcceptanceValidationError + ValidationErrors.AcceptanceValidationError, ) expect(() => validate(true, 'terms', { acceptance: true })).not.toThrow() expect(() => - validate('true', 'terms', { acceptance: { in: ['true'] } }) + validate('true', 'terms', { acceptance: { in: ['true'] } }), ).not.toThrow() expect(() => - validate(1, 'terms', { acceptance: { in: [1] } }) + validate(1, 'terms', { acceptance: { in: [1] } }), ).not.toThrow() }) @@ -139,7 +139,7 @@ describe('validate email', () => { ' dt@redwoodjs.com', ].forEach((val) => { expect(() => validate(val, 'email', { email: true })).toThrow( - ValidationErrors.EmailValidationError + ValidationErrors.EmailValidationError, ) }) ;[ @@ -150,7 +150,7 @@ describe('validate email', () => { expect(() => validate(val, 'email', { email: true, - }) + }), ).not.toThrow() }) }) @@ -179,27 +179,27 @@ describe('validate email', () => { describe('validate exclusion', () => { it('checks for exclusion', () => { expect(() => - validate('foo', 'selection', { exclusion: ['foo', 'bar'] }) + validate('foo', 'selection', { exclusion: ['foo', 'bar'] }), ).toThrow(ValidationErrors.ExclusionValidationError) expect(() => - validate('bar', 'selection', { exclusion: { in: ['foo', 'bar'] } }) + validate('bar', 'selection', { exclusion: { in: ['foo', 'bar'] } }), ).toThrow(ValidationErrors.ExclusionValidationError) expect(() => validate('bar', 'selection', { exclusion: { in: ['foo', 'bar'], caseSensitive: true }, - }) + }), ).toThrow(ValidationErrors.ExclusionValidationError) expect(() => - validate('qux', 'selection', { exclusion: ['foo', 'bar'] }) + validate('qux', 'selection', { exclusion: ['foo', 'bar'] }), ).not.toThrow() expect(() => - validate('qux', 'selection', { exclusion: { in: ['foo', 'bar'] } }) + validate('qux', 'selection', { exclusion: { in: ['foo', 'bar'] } }), ).not.toThrow() expect(() => validate('qux', 'selection', { exclusion: { in: ['foo', 'bar'], caseSensitive: true }, - }) + }), ).not.toThrow() }) @@ -207,18 +207,18 @@ describe('validate exclusion', () => { expect(() => validate('Bar', 'selection', { exclusion: { in: ['foo', 'bar'], caseSensitive: false }, - }) + }), ).toThrow(ValidationErrors.ExclusionValidationError) expect(() => validate('bar', 'selection', { exclusion: { in: ['foo', 'Bar'], caseSensitive: false }, - }) + }), ).toThrow(ValidationErrors.ExclusionValidationError) expect(() => validate('qux', 'selection', { exclusion: { in: ['foo', 'bar'], caseSensitive: false }, - }) + }), ).not.toThrow() }) @@ -272,21 +272,21 @@ describe('validate exclusion', () => { describe('validate format', () => { it('checks for valid format', () => { expect(() => validate('foobar', 'text', { format: /baz/ })).toThrow( - ValidationErrors.FormatValidationError + ValidationErrors.FormatValidationError, ) expect(() => validate('foobar', 'text', { format: /baz/ })).toThrow( - ValidationErrors.FormatValidationError + ValidationErrors.FormatValidationError, ) // inline regex ;[/foo/, /^foo/].forEach((pattern) => { expect(() => - validate('foobar', 'text', { format: pattern }) + validate('foobar', 'text', { format: pattern }), ).not.toThrow() }) // options format ;[/foo/, /^foo/].forEach((pattern) => { expect(() => - validate('foobar', 'text', { format: { pattern } }) + validate('foobar', 'text', { format: { pattern } }), ).not.toThrow() }) }) @@ -356,27 +356,27 @@ describe('validate format', () => { describe('validate inclusion', () => { it('checks for inclusion', () => { expect(() => - validate('qux', 'selection', { inclusion: ['foo', 'bar'] }) + validate('qux', 'selection', { inclusion: ['foo', 'bar'] }), ).toThrow(ValidationErrors.InclusionValidationError) expect(() => - validate('quux', 'selection', { inclusion: { in: ['foo', 'bar'] } }) + validate('quux', 'selection', { inclusion: { in: ['foo', 'bar'] } }), ).toThrow(ValidationErrors.InclusionValidationError) expect(() => validate('QUUX', 'selection', { inclusion: { in: ['foo', 'bar'], caseSensitive: true }, - }) + }), ).toThrow(ValidationErrors.InclusionValidationError) expect(() => - validate('foo', 'selection', { inclusion: ['foo', 'bar'] }) + validate('foo', 'selection', { inclusion: ['foo', 'bar'] }), ).not.toThrow() expect(() => - validate('foo', 'selection', { inclusion: { in: ['foo', 'bar'] } }) + validate('foo', 'selection', { inclusion: { in: ['foo', 'bar'] } }), ).not.toThrow() expect(() => validate('foo', 'selection', { inclusion: { in: ['foo', 'bar'], caseSensitive: true }, - }) + }), ).not.toThrow() }) @@ -384,18 +384,18 @@ describe('validate inclusion', () => { expect(() => validate('quux', 'selection', { inclusion: { in: ['foo', 'bar'], caseSensitive: false }, - }) + }), ).toThrow(ValidationErrors.InclusionValidationError) expect(() => validate('Foo', 'selection', { inclusion: { in: ['foo', 'bar'], caseSensitive: false }, - }) + }), ).not.toThrow() expect(() => validate('foo', 'selection', { inclusion: { in: ['FOO', 'bar'], caseSensitive: false }, - }) + }), ).not.toThrow() }) @@ -425,7 +425,7 @@ describe('validate inclusion', () => { describe('validate length', () => { it('checks for minimum length', () => { expect(() => validate('a', 'username', { length: { min: 2 } })).toThrow( - ValidationErrors.MinLengthValidationError + ValidationErrors.MinLengthValidationError, ) // default error @@ -444,16 +444,16 @@ describe('validate length', () => { // valid expect(() => - validate('foobar', 'username', { length: { min: 4 } }) + validate('foobar', 'username', { length: { min: 4 } }), ).not.toThrow() expect(() => - validate('foobar', 'username', { length: { min: 4, max: 8 } }) + validate('foobar', 'username', { length: { min: 4, max: 8 } }), ).not.toThrow() }) it('checks for maximum length', () => { expect(() => - validate('johndoeesquirethethird', 'username', { length: { max: 10 } }) + validate('johndoeesquirethethird', 'username', { length: { max: 10 } }), ).toThrow(ValidationErrors.MaxLengthValidationError) // default error @@ -474,19 +474,19 @@ describe('validate length', () => { // valid expect(() => - validate('foobar', 'username', { length: { max: 8 } }) + validate('foobar', 'username', { length: { max: 8 } }), ).not.toThrow() }) it('throws an error if the field does not equal a given number', () => { // too short expect(() => - validate('foobar', 'username', { length: { equal: 7 } }) + validate('foobar', 'username', { length: { equal: 7 } }), ).toThrow(ValidationErrors.EqualLengthValidationError) // too long expect(() => - validate('foobarbaz', 'username', { length: { equal: 7 } }) + validate('foobarbaz', 'username', { length: { equal: 7 } }), ).toThrow(ValidationErrors.EqualLengthValidationError) // default error @@ -507,19 +507,19 @@ describe('validate length', () => { // valid expect(() => - validate('foobar', 'username', { length: { equal: 6 } }) + validate('foobar', 'username', { length: { equal: 6 } }), ).not.toThrow() }) it('throws an error if the field is not within a range', () => { // too short expect(() => - validate('foobar', 'username', { length: { between: [10, 20] } }) + validate('foobar', 'username', { length: { between: [10, 20] } }), ).toThrow(ValidationErrors.BetweenLengthValidationError) // too long expect(() => - validate('foobar', 'username', { length: { between: [2, 4] } }) + validate('foobar', 'username', { length: { between: [2, 4] } }), ).toThrow(ValidationErrors.BetweenLengthValidationError) // default error @@ -540,7 +540,7 @@ describe('validate length', () => { // valid expect(() => - validate('foobar', 'username', { length: { between: [2, 10] } }) + validate('foobar', 'username', { length: { between: [2, 10] } }), ).not.toThrow() }) @@ -552,13 +552,13 @@ describe('validate length', () => { describe('validate numericality', () => { it('checks if value is a number', () => { expect(() => validate('a', 'number', { numericality: true })).toThrow( - ValidationErrors.TypeNumericalityValidationError + ValidationErrors.TypeNumericalityValidationError, ) expect(() => validate([1], 'number', { numericality: true })).toThrow( - ValidationErrors.TypeNumericalityValidationError + ValidationErrors.TypeNumericalityValidationError, ) expect(() => - validate({ foo: 1 }, 'number', { numericality: true }) + validate({ foo: 1 }, 'number', { numericality: true }), ).toThrow(ValidationErrors.TypeNumericalityValidationError) expect(() => validate(42, 'number', { numericality: true })).not.toThrow() @@ -567,11 +567,11 @@ describe('validate numericality', () => { it('checks if value is an integer', () => { expect(() => - validate(1.2, 'number', { numericality: { integer: true } }) + validate(1.2, 'number', { numericality: { integer: true } }), ).toThrow(ValidationErrors.IntegerNumericalityValidationError) expect(() => - validate(3, 'number', { numericality: { integer: true } }) + validate(3, 'number', { numericality: { integer: true } }), ).not.toThrow(ValidationErrors.IntegerNumericalityValidationError) // default error @@ -584,26 +584,26 @@ describe('validate numericality', () => { it('checks if value is less than required number', () => { expect(() => - validate(2, 'number', { numericality: { lessThan: 1 } }) + validate(2, 'number', { numericality: { lessThan: 1 } }), ).toThrow(ValidationErrors.LessThanNumericalityValidationError) expect(() => - validate(2, 'number', { numericality: { lessThan: 2 } }) + validate(2, 'number', { numericality: { lessThan: 2 } }), ).toThrow(ValidationErrors.LessThanNumericalityValidationError) expect(() => - validate(2.1, 'number', { numericality: { lessThan: 2.1 } }) + validate(2.1, 'number', { numericality: { lessThan: 2.1 } }), ).toThrow(ValidationErrors.LessThanNumericalityValidationError) expect(() => - validate(2.2, 'number', { numericality: { lessThan: 2.1 } }) + validate(2.2, 'number', { numericality: { lessThan: 2.1 } }), ).toThrow(ValidationErrors.LessThanNumericalityValidationError) expect(() => - validate(2, 'number', { numericality: { lessThan: 0 } }) + validate(2, 'number', { numericality: { lessThan: 0 } }), ).toThrow(ValidationErrors.LessThanNumericalityValidationError) expect(() => - validate(2, 'number', { numericality: { lessThan: 3 } }) + validate(2, 'number', { numericality: { lessThan: 3 } }), ).not.toThrow(ValidationErrors.LessThanNumericalityValidationError) expect(() => - validate(3.1, 'number', { numericality: { lessThan: 3.2 } }) + validate(3.1, 'number', { numericality: { lessThan: 3.2 } }), ).not.toThrow(ValidationErrors.LessThanNumericalityValidationError) // default error @@ -617,26 +617,26 @@ describe('validate numericality', () => { it('checks if value is less than or equal to required number', () => { expect(() => - validate(2, 'number', { numericality: { lessThanOrEqual: 1 } }) + validate(2, 'number', { numericality: { lessThanOrEqual: 1 } }), ).toThrow(ValidationErrors.LessThanOrEqualNumericalityValidationError) expect(() => - validate(2, 'number', { numericality: { lessThanOrEqual: 1.5 } }) + validate(2, 'number', { numericality: { lessThanOrEqual: 1.5 } }), ).toThrow(ValidationErrors.LessThanOrEqualNumericalityValidationError) expect(() => - validate(2.2, 'number', { numericality: { lessThanOrEqual: 2.1 } }) + validate(2.2, 'number', { numericality: { lessThanOrEqual: 2.1 } }), ).toThrow(ValidationErrors.LessThanOrEqualNumericalityValidationError) expect(() => - validate(2.2, 'number', { numericality: { lessThanOrEqual: 2 } }) + validate(2.2, 'number', { numericality: { lessThanOrEqual: 2 } }), ).toThrow(ValidationErrors.LessThanOrEqualNumericalityValidationError) expect(() => - validate(2, 'number', { numericality: { lessThanOrEqual: 0 } }) + validate(2, 'number', { numericality: { lessThanOrEqual: 0 } }), ).toThrow(ValidationErrors.LessThanOrEqualNumericalityValidationError) expect(() => - validate(2.2, 'number', { numericality: { lessThanOrEqual: 2.3 } }) + validate(2.2, 'number', { numericality: { lessThanOrEqual: 2.3 } }), ).not.toThrow(ValidationErrors.LessThanOrEqualNumericalityValidationError) expect(() => - validate(2.2, 'number', { numericality: { lessThanOrEqual: 2.2 } }) + validate(2.2, 'number', { numericality: { lessThanOrEqual: 2.2 } }), ).not.toThrow(ValidationErrors.LessThanOrEqualNumericalityValidationError) // default error @@ -650,29 +650,29 @@ describe('validate numericality', () => { it('checks if value is greater than required number', () => { expect(() => - validate(2, 'number', { numericality: { greaterThan: 3 } }) + validate(2, 'number', { numericality: { greaterThan: 3 } }), ).toThrow(ValidationErrors.GreaterThanNumericalityValidationError) expect(() => - validate(2, 'number', { numericality: { greaterThan: 2 } }) + validate(2, 'number', { numericality: { greaterThan: 2 } }), ).toThrow(ValidationErrors.GreaterThanNumericalityValidationError) expect(() => - validate(2.1, 'number', { numericality: { greaterThan: 3 } }) + validate(2.1, 'number', { numericality: { greaterThan: 3 } }), ).toThrow(ValidationErrors.GreaterThanNumericalityValidationError) expect(() => - validate(3.0, 'number', { numericality: { greaterThan: 3.1 } }) + validate(3.0, 'number', { numericality: { greaterThan: 3.1 } }), ).toThrow(ValidationErrors.GreaterThanNumericalityValidationError) expect(() => - validate(3.0, 'number', { numericality: { greaterThan: 3 } }) + validate(3.0, 'number', { numericality: { greaterThan: 3 } }), ).toThrow(ValidationErrors.GreaterThanNumericalityValidationError) expect(() => - validate(-1, 'number', { numericality: { greaterThan: 0 } }) + validate(-1, 'number', { numericality: { greaterThan: 0 } }), ).toThrow(ValidationErrors.GreaterThanNumericalityValidationError) expect(() => - validate(3, 'number', { numericality: { greaterThan: 2 } }) + validate(3, 'number', { numericality: { greaterThan: 2 } }), ).not.toThrow(ValidationErrors.GreaterThanNumericalityValidationError) expect(() => - validate(3.1, 'number', { numericality: { greaterThan: 3.0 } }) + validate(3.1, 'number', { numericality: { greaterThan: 3.0 } }), ).not.toThrow(ValidationErrors.GreaterThanNumericalityValidationError) // default error @@ -686,30 +686,30 @@ describe('validate numericality', () => { it('checks if value is greater than or equal to required number', () => { expect(() => - validate(2, 'number', { numericality: { greaterThanOrEqual: 3 } }) + validate(2, 'number', { numericality: { greaterThanOrEqual: 3 } }), ).toThrow(ValidationErrors.GreaterThanOrEqualNumericalityValidationError) expect(() => - validate(3.0, 'number', { numericality: { greaterThanOrEqual: 3.1 } }) + validate(3.0, 'number', { numericality: { greaterThanOrEqual: 3.1 } }), ).toThrow(ValidationErrors.GreaterThanOrEqualNumericalityValidationError) expect(() => - validate(-1, 'number', { numericality: { greaterThanOrEqual: 0 } }) + validate(-1, 'number', { numericality: { greaterThanOrEqual: 0 } }), ).toThrow(ValidationErrors.GreaterThanOrEqualNumericalityValidationError) expect(() => - validate(3, 'number', { numericality: { greaterThan: 2 } }) + validate(3, 'number', { numericality: { greaterThan: 2 } }), ).not.toThrow(ValidationErrors.GreaterThanNumericalityValidationError) expect(() => - validate(3.1, 'number', { numericality: { greaterThan: 3.0 } }) + validate(3.1, 'number', { numericality: { greaterThan: 3.0 } }), ).not.toThrow(ValidationErrors.GreaterThanNumericalityValidationError) expect(() => - validate(2, 'number', { numericality: { greaterThanOrEqual: 2 } }) + validate(2, 'number', { numericality: { greaterThanOrEqual: 2 } }), ).not.toThrow( - ValidationErrors.GreaterThanOrEqualNumericalityValidationError + ValidationErrors.GreaterThanOrEqualNumericalityValidationError, ) expect(() => - validate(2.5, 'number', { numericality: { greaterThanOrEqual: 2.5 } }) + validate(2.5, 'number', { numericality: { greaterThanOrEqual: 2.5 } }), ).not.toThrow( - ValidationErrors.GreaterThanOrEqualNumericalityValidationError + ValidationErrors.GreaterThanOrEqualNumericalityValidationError, ) // default error @@ -723,32 +723,32 @@ describe('validate numericality', () => { it('checks if value is not equal to required number', () => { expect(() => validate(2, 'number', { numericality: { equal: 3 } })).toThrow( - ValidationErrors.EqualNumericalityValidationError + ValidationErrors.EqualNumericalityValidationError, ) expect(() => - validate(2.0, 'number', { numericality: { equal: 3 } }) + validate(2.0, 'number', { numericality: { equal: 3 } }), ).toThrow(ValidationErrors.EqualNumericalityValidationError) expect(() => - validate(2.9, 'number', { numericality: { equal: 3.1 } }) + validate(2.9, 'number', { numericality: { equal: 3.1 } }), ).toThrow(ValidationErrors.EqualNumericalityValidationError) expect(() => - validate(2.9, 'number', { numericality: { equal: 3 } }) + validate(2.9, 'number', { numericality: { equal: 3 } }), ).toThrow(ValidationErrors.EqualNumericalityValidationError) expect(() => validate(2, 'number', { numericality: { equal: 0 } })).toThrow( - ValidationErrors.EqualNumericalityValidationError + ValidationErrors.EqualNumericalityValidationError, ) expect(() => - validate(2, 'number', { numericality: { equal: 2 } }) + validate(2, 'number', { numericality: { equal: 2 } }), ).not.toThrow(ValidationErrors.EqualNumericalityValidationError) expect(() => - validate(2.0, 'number', { numericality: { equal: 2.0 } }) + validate(2.0, 'number', { numericality: { equal: 2.0 } }), ).not.toThrow(ValidationErrors.EqualNumericalityValidationError) expect(() => - validate(2, 'number', { numericality: { equal: 2.0 } }) + validate(2, 'number', { numericality: { equal: 2.0 } }), ).not.toThrow(ValidationErrors.EqualNumericalityValidationError) expect(() => - validate(2.0, 'number', { numericality: { equal: 2 } }) + validate(2.0, 'number', { numericality: { equal: 2 } }), ).not.toThrow(ValidationErrors.EqualNumericalityValidationError) // default error @@ -762,26 +762,26 @@ describe('validate numericality', () => { it('checks if not equal to required number', () => { expect(() => - validate(3, 'number', { numericality: { otherThan: 3 } }) + validate(3, 'number', { numericality: { otherThan: 3 } }), ).toThrow(ValidationErrors.OtherThanNumericalityValidationError) expect(() => - validate(2.9, 'number', { numericality: { otherThan: 2.9 } }) + validate(2.9, 'number', { numericality: { otherThan: 2.9 } }), ).toThrow(ValidationErrors.OtherThanNumericalityValidationError) expect(() => - validate(3.0, 'number', { numericality: { otherThan: 3 } }) + validate(3.0, 'number', { numericality: { otherThan: 3 } }), ).toThrow(ValidationErrors.OtherThanNumericalityValidationError) expect(() => - validate(0, 'number', { numericality: { otherThan: 0 } }) + validate(0, 'number', { numericality: { otherThan: 0 } }), ).toThrow(ValidationErrors.OtherThanNumericalityValidationError) expect(() => - validate(2, 'number', { numericality: { otherThan: 3 } }) + validate(2, 'number', { numericality: { otherThan: 3 } }), ).not.toThrow(ValidationErrors.OtherThanNumericalityValidationError) expect(() => - validate(2.1, 'number', { numericality: { otherThan: 3.1 } }) + validate(2.1, 'number', { numericality: { otherThan: 3.1 } }), ).not.toThrow(ValidationErrors.OtherThanNumericalityValidationError) expect(() => - validate(3.0, 'number', { numericality: { otherThan: 4 } }) + validate(3.0, 'number', { numericality: { otherThan: 4 } }), ).not.toThrow(ValidationErrors.OtherThanNumericalityValidationError) // default error @@ -795,17 +795,17 @@ describe('validate numericality', () => { it('checks for a value being even', () => { expect(() => - validate(3, 'number', { numericality: { even: true } }) + validate(3, 'number', { numericality: { even: true } }), ).toThrow(ValidationErrors.EvenNumericalityValidationError) expect(() => - validate(3.0, 'number', { numericality: { even: true } }) + validate(3.0, 'number', { numericality: { even: true } }), ).toThrow(ValidationErrors.EvenNumericalityValidationError) expect(() => - validate(2, 'number', { numericality: { even: true } }) + validate(2, 'number', { numericality: { even: true } }), ).not.toThrow(ValidationErrors.EvenNumericalityValidationError) expect(() => - validate(2.0, 'number', { numericality: { even: true } }) + validate(2.0, 'number', { numericality: { even: true } }), ).not.toThrow(ValidationErrors.EvenNumericalityValidationError) // default error @@ -819,17 +819,17 @@ describe('validate numericality', () => { it('checks for a value being odd', () => { expect(() => - validate(2, 'number', { numericality: { odd: true } }) + validate(2, 'number', { numericality: { odd: true } }), ).toThrow(ValidationErrors.OddNumericalityValidationError) expect(() => - validate(2.0, 'number', { numericality: { odd: true } }) + validate(2.0, 'number', { numericality: { odd: true } }), ).toThrow(ValidationErrors.OddNumericalityValidationError) expect(() => - validate(3, 'number', { numericality: { odd: true } }) + validate(3, 'number', { numericality: { odd: true } }), ).not.toThrow(ValidationErrors.OddNumericalityValidationError) expect(() => - validate(3.0, 'number', { numericality: { odd: true } }) + validate(3.0, 'number', { numericality: { odd: true } }), ).not.toThrow(ValidationErrors.OddNumericalityValidationError) // default error @@ -843,20 +843,20 @@ describe('validate numericality', () => { it('checks for a value being positive', () => { expect(() => - validate(-1, 'number', { numericality: { positive: true } }) + validate(-1, 'number', { numericality: { positive: true } }), ).toThrow(ValidationErrors.PositiveNumericalityValidationError) expect(() => - validate(-2.0, 'number', { numericality: { positive: true } }) + validate(-2.0, 'number', { numericality: { positive: true } }), ).toThrow(ValidationErrors.PositiveNumericalityValidationError) expect(() => - validate(0, 'number', { numericality: { positive: true } }) + validate(0, 'number', { numericality: { positive: true } }), ).toThrow(ValidationErrors.PositiveNumericalityValidationError) expect(() => - validate(3, 'number', { numericality: { positive: true } }) + validate(3, 'number', { numericality: { positive: true } }), ).not.toThrow(ValidationErrors.PositiveNumericalityValidationError) expect(() => - validate(3.0, 'number', { numericality: { positive: true } }) + validate(3.0, 'number', { numericality: { positive: true } }), ).not.toThrow(ValidationErrors.PositiveNumericalityValidationError) // default error @@ -870,20 +870,20 @@ describe('validate numericality', () => { it('checks for a value being negative', () => { expect(() => - validate(1, 'number', { numericality: { negative: true } }) + validate(1, 'number', { numericality: { negative: true } }), ).toThrow(ValidationErrors.NegativeNumericalityValidationError) expect(() => - validate(2.0, 'number', { numericality: { negative: true } }) + validate(2.0, 'number', { numericality: { negative: true } }), ).toThrow(ValidationErrors.NegativeNumericalityValidationError) expect(() => - validate(0, 'number', { numericality: { negative: true } }) + validate(0, 'number', { numericality: { negative: true } }), ).toThrow(ValidationErrors.NegativeNumericalityValidationError) expect(() => - validate(-3, 'number', { numericality: { negative: true } }) + validate(-3, 'number', { numericality: { negative: true } }), ).not.toThrow(ValidationErrors.NegativeNumericalityValidationError) expect(() => - validate(-3.0, 'number', { numericality: { negative: true } }) + validate(-3.0, 'number', { numericality: { negative: true } }), ).not.toThrow(ValidationErrors.NegativeNumericalityValidationError) // default error @@ -903,47 +903,47 @@ describe('validate numericality', () => { describe('validate presence', () => { it('checks for a field being null', () => { expect(() => validate(null, 'email', { presence: true })).toThrow( - ValidationErrors.PresenceValidationError + ValidationErrors.PresenceValidationError, ) expect(() => - validate(null, 'email', { presence: { allowNull: false } }) + validate(null, 'email', { presence: { allowNull: false } }), ).toThrow(ValidationErrors.PresenceValidationError) expect(() => - validate(undefined, 'email', { presence: { allowUndefined: true } }) + validate(undefined, 'email', { presence: { allowUndefined: true } }), ).not.toThrow() expect(() => - validate(null, 'email', { presence: { allowNull: true } }) + validate(null, 'email', { presence: { allowNull: true } }), ).not.toThrow() expect(() => validate('', 'email', { presence: true })).not.toThrow() }) it('checks for a field being undefined', () => { expect(() => validate(undefined, 'email', { presence: true })).toThrow( - ValidationErrors.PresenceValidationError + ValidationErrors.PresenceValidationError, ) expect(() => - validate(undefined, 'email', { presence: { allowUndefined: false } }) + validate(undefined, 'email', { presence: { allowUndefined: false } }), ).toThrow(ValidationErrors.PresenceValidationError) expect(() => - validate(null, 'email', { presence: { allowNull: true } }) + validate(null, 'email', { presence: { allowNull: true } }), ).not.toThrow() expect(() => - validate(undefined, 'email', { presence: { allowUndefined: true } }) + validate(undefined, 'email', { presence: { allowUndefined: true } }), ).not.toThrow() }) it('checks for a field being an empty string', () => { expect(() => - validate('', 'email', { presence: { allowEmptyString: false } }) + validate('', 'email', { presence: { allowEmptyString: false } }), ).toThrow(ValidationErrors.PresenceValidationError) expect(() => validate('', 'email', { presence: true })).not.toThrow() expect(() => validate('', 'email', { presence: { allowNull: true, allowUndefined: true }, - }) + }), ).not.toThrow() }) @@ -993,7 +993,7 @@ describe('validate custom', () => { throw new Error('foo') }, }, - }) + }), ).toThrow(ValidationErrors.CustomValidationError) expect(() => @@ -1001,7 +1001,7 @@ describe('validate custom', () => { custom: { with: () => {}, }, - }) + }), ).not.toThrow(ValidationErrors.CustomValidationError) }) @@ -1126,7 +1126,7 @@ describe('validate', () => { validate(null, 'email', { presence: true, format: /^\d+$/, - }) + }), ).toThrow(ValidationErrors.PresenceValidationError) // fails second validator @@ -1134,7 +1134,7 @@ describe('validate', () => { validate('rob@redwoodjs.com', 'email', { presence: true, format: /^\d+$/, - }) + }), ).toThrow(ValidationErrors.FormatValidationError) // passes all validators @@ -1142,7 +1142,7 @@ describe('validate', () => { validate(12345, 'number', { presence: true, format: /^\d+$/, - }) + }), ).not.toThrow() }) @@ -1281,7 +1281,7 @@ describe('validateUniqueness', () => { await validateUniqueness( 'user', { name: 'Rob', email: 'rob@redwoodjs.com' }, - () => {} + () => {}, ) } catch (e) { expect(e.message).toEqual('name, email must be unique') @@ -1302,7 +1302,7 @@ describe('validateUniqueness', () => { { message: 'Email already taken', }, - () => {} + () => {}, ) } catch (e) { expect(e.message).toEqual('Email already taken') @@ -1332,8 +1332,8 @@ describe('validateUniqueness', () => { 'user', { email: 'rob@redwoodjs.com' }, { db: mockPrismaClient }, - () => {} - ) + () => {}, + ), ).rejects.toThrowError('email must be unique') expect(mockFindFirstOther).toBeCalled() diff --git a/packages/api/src/validations/errors.ts b/packages/api/src/validations/errors.ts index f32aa9f7cfee..7b75433d7003 100644 --- a/packages/api/src/validations/errors.ts +++ b/packages/api/src/validations/errors.ts @@ -13,7 +13,7 @@ export class ServiceValidationError extends RedwoodError { for (const [key, value] of Object.entries(substitutions)) { errorMessage = errorMessage.replaceAll( `\${${key}}`, - titleCase(humanize(String(value))) + titleCase(humanize(String(value))), ) // this mimics the Apollo Server use of error codes and extensions needed @@ -41,7 +41,7 @@ export class AbsenceValidationError extends ServiceValidationError { constructor( name: string, message = '${name} is not absent', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'AbsenceValidationError' @@ -54,7 +54,7 @@ export class AcceptanceValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must be accepted', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'AcceptanceValidationError' @@ -67,7 +67,7 @@ export class EmailValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must be formatted like an email address', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'EmailValidationError' @@ -79,7 +79,7 @@ export class ExclusionValidationError extends ServiceValidationError { constructor( name: string, message = '${name} is reserved', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'ExclusionValidationError' @@ -92,7 +92,7 @@ export class FormatValidationError extends ServiceValidationError { constructor( name: string, message = '${name} is not formatted correctly', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'FormatValidationError' @@ -105,7 +105,7 @@ export class InclusionValidationError extends ServiceValidationError { constructor( name: string, message = '${name} is reserved', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'InclusionValidationError' @@ -118,7 +118,7 @@ export class MinLengthValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must have at least ${min} characters', - substitutions: { min?: number } = {} + substitutions: { min?: number } = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'MinLengthValidationError' @@ -131,7 +131,7 @@ export class MaxLengthValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must have no more than ${max} characters', - substitutions: { max?: number } = {} + substitutions: { max?: number } = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'MaxLengthValidationError' @@ -144,7 +144,7 @@ export class EqualLengthValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must have exactly ${equal} characters', - substitutions: { equal?: number } = {} + substitutions: { equal?: number } = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'EqualLengthValidationError' @@ -157,7 +157,7 @@ export class BetweenLengthValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must be between ${min} and ${max} characters', - substitutions: { min?: number; max?: number } = {} + substitutions: { min?: number; max?: number } = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'BetweenLengthValidationError' @@ -170,7 +170,7 @@ export class PresenceValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must be present', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'PresenceValidationError' @@ -183,7 +183,7 @@ export class TypeNumericalityValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must by a number', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'TypeNumericalityValidationError' @@ -196,7 +196,7 @@ export class IntegerNumericalityValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must be an integer', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'IntegerNumericalityValidationError' @@ -209,7 +209,7 @@ export class LessThanNumericalityValidationError extends ServiceValidationError constructor( name: string, message = '${name} must be less than ${lessThan}', - substitutions: { lessThan?: number } = {} + substitutions: { lessThan?: number } = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'LessThanNumericalityValidationError' @@ -222,13 +222,13 @@ export class LessThanOrEqualNumericalityValidationError extends ServiceValidatio constructor( name: string, message = '${name} must be less than or equal to ${lessThanOrEqual}', - substitutions: { lessThanOrEqual?: number } = {} + substitutions: { lessThanOrEqual?: number } = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'LessThanOrEqualNumericalityValidationError' Object.setPrototypeOf( this, - LessThanOrEqualNumericalityValidationError.prototype + LessThanOrEqualNumericalityValidationError.prototype, ) } } @@ -237,13 +237,13 @@ export class GreaterThanNumericalityValidationError extends ServiceValidationErr constructor( name: string, message = '${name} must be greater than ${greaterThan}', - substitutions: { greaterThan?: number } = {} + substitutions: { greaterThan?: number } = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'GreaterThanNumericalityValidationError' Object.setPrototypeOf( this, - GreaterThanNumericalityValidationError.prototype + GreaterThanNumericalityValidationError.prototype, ) } } @@ -252,13 +252,13 @@ export class GreaterThanOrEqualNumericalityValidationError extends ServiceValida constructor( name: string, message = '${name} must be greater than or equal to ${greaterThanOrEqual}', - substitutions: { greaterThanOrEqual?: number } = {} + substitutions: { greaterThanOrEqual?: number } = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'GreaterThanOrEqualNumericalityValidationError' Object.setPrototypeOf( this, - GreaterThanOrEqualNumericalityValidationError.prototype + GreaterThanOrEqualNumericalityValidationError.prototype, ) } } @@ -267,7 +267,7 @@ export class EqualNumericalityValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must equal ${equal}', - substitutions: { equal?: number } = {} + substitutions: { equal?: number } = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'EqualNumericalityValidationError' @@ -280,7 +280,7 @@ export class OtherThanNumericalityValidationError extends ServiceValidationError constructor( name: string, message = '${name} must not equal ${otherThan}', - substitutions: { otherThan?: number } = {} + substitutions: { otherThan?: number } = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'OtherThanNumericalityValidationError' @@ -293,7 +293,7 @@ export class EvenNumericalityValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must be even', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'EvenNumericalityValidationError' @@ -306,7 +306,7 @@ export class OddNumericalityValidationError extends ServiceValidationError { constructor( name: string, message = '${name} must be odd', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'OddNumericalityValidationError' @@ -319,7 +319,7 @@ export class PositiveNumericalityValidationError extends ServiceValidationError constructor( name: string, message = '${name} must be positive', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'PositiveNumericalityValidationError' @@ -332,7 +332,7 @@ export class NegativeNumericalityValidationError extends ServiceValidationError constructor( name: string, message = '${name} must be negative', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'NegativeNumericalityValidationError' @@ -347,7 +347,7 @@ export class CustomValidationError extends ServiceValidationError { // Since CustomValidationError is derived from either a raised error or a string, the message is always passed. // but for the sake of consistency, we'll keep the message optional. message = '', - substitutions = {} + substitutions = {}, ) { super(message, Object.assign(substitutions, { name })) this.name = 'CustomValidationError' diff --git a/packages/api/src/validations/validations.ts b/packages/api/src/validations/validations.ts index 3fc9f41c6719..c1c6e4b87f30 100644 --- a/packages/api/src/validations/validations.ts +++ b/packages/api/src/validations/validations.ts @@ -246,7 +246,7 @@ const VALIDATORS = { absence: ( value: unknown, name: string, - options: boolean | AbsenceValidatorOptions + options: boolean | AbsenceValidatorOptions, ) => { const absenceOptions = { allowEmptyString: false } Object.assign(absenceOptions, options) @@ -268,7 +268,7 @@ const VALIDATORS = { acceptance: ( value: unknown, name: string, - options: boolean | AcceptanceValidatorOptions + options: boolean | AcceptanceValidatorOptions, ) => { let acceptedValues: Array @@ -293,7 +293,7 @@ const VALIDATORS = { email: ( value: unknown, name: string, - options: boolean | EmailValidatorOptions + options: boolean | EmailValidatorOptions, ) => { const pattern = /^[^@\s]+@[^.\s]+\.[^\s]+$/ @@ -309,7 +309,7 @@ const VALIDATORS = { exclusion: ( value: unknown, name: string, - options: Array | ExclusionValidatorOptions + options: Array | ExclusionValidatorOptions, ) => { const [exclusionList, val] = prepareExclusionInclusion(value, options) @@ -325,14 +325,14 @@ const VALIDATORS = { format: ( value: unknown, name: string, - options: RegExp | FormatValidatorOptions + options: RegExp | FormatValidatorOptions, ) => { const pattern = options instanceof RegExp ? options : options.pattern if (pattern == null) { throw new ValidationErrors.FormatValidationError( name, - 'No pattern for format validation' + 'No pattern for format validation', ) } @@ -348,7 +348,7 @@ const VALIDATORS = { inclusion: ( value: unknown, name: string, - options: Array | InclusionValidatorOptions + options: Array | InclusionValidatorOptions, ) => { const [inclusionList, val] = prepareExclusionInclusion(value, options) @@ -410,7 +410,7 @@ const VALIDATORS = { numericality: ( value: unknown, name: string, - options: boolean | NumericalityValidatorOptions + options: boolean | NumericalityValidatorOptions, ) => { if (typeof value !== 'number') { validationError('typeNumericality', name, options) @@ -492,7 +492,7 @@ const VALIDATORS = { presence: ( value: unknown, name: string, - options: boolean | PresenceValidatorOptions + options: boolean | PresenceValidatorOptions, ) => { const presenceOptions = { allowNull: false, @@ -537,10 +537,10 @@ const validationError = ( type: string, name: string, options: any, - substitutions = {} + substitutions = {}, ) => { const errorClassName = `${pascalcase( - type + type, )}ValidationError` as keyof typeof ValidationErrors const ErrorClass = ValidationErrors[errorClassName] const errorMessage = @@ -557,7 +557,7 @@ const prepareExclusionInclusion = ( options: | Array | InclusionValidatorOptions - | ExclusionValidatorOptions + | ExclusionValidatorOptions, ): [Array, unknown] => { const inputList = (Array.isArray(options) && options) || options.in || [] @@ -581,17 +581,17 @@ const prepareExclusionInclusion = ( export function validate( value: unknown, labelOrRecipe: ValidationWithMessagesRecipe, - recipe?: never + recipe?: never, ): void export function validate( value: unknown, labelOrRecipe: string, - recipe: ValidationRecipe + recipe: ValidationRecipe, ): void export function validate( value: unknown, labelOrRecipe: string | ValidationWithMessagesRecipe, - recipe?: ValidationRecipe + recipe?: ValidationRecipe, ): void { let label, validationRecipe @@ -684,13 +684,13 @@ export async function validateUniqueness( model: string, fields: Record, optionsOrCallback: (tx: PrismaClient) => Promise, - callback: never + callback: never, ): Promise export async function validateUniqueness( model: string, fields: Record, optionsOrCallback: UniquenessValidatorOptions, - callback?: (tx: PrismaClient) => Promise + callback?: (tx: PrismaClient) => Promise, ): Promise export async function validateUniqueness( model: string, @@ -698,7 +698,7 @@ export async function validateUniqueness( optionsOrCallback: | UniquenessValidatorOptions | ((tx: PrismaClient) => Promise), - callback?: (tx: PrismaClient) => Promise + callback?: (tx: PrismaClient) => Promise, ): Promise { const { $self, $scope, ...rest } = fields let options: UniquenessValidatorOptions = {} diff --git a/packages/api/src/webhooks/index.ts b/packages/api/src/webhooks/index.ts index 341795828245..36181bdfc99b 100644 --- a/packages/api/src/webhooks/index.ts +++ b/packages/api/src/webhooks/index.ts @@ -76,7 +76,7 @@ export const verifyEvent = ( payload?: string secret?: string options?: VerifyOptions | undefined - } + }, ): boolean | WebhookVerificationError => { let body = '' @@ -136,7 +136,7 @@ export const verifySignature = ( secret: string signature: string options?: VerifyOptions | undefined - } + }, ): boolean | WebhookVerificationError => { const { verify } = createVerifier(type, options) @@ -165,7 +165,7 @@ export const signPayload = ( payload: string secret: string options?: VerifyOptions | undefined - } + }, ): string => { const { sign } = createVerifier(type, options) diff --git a/packages/api/src/webhooks/webhooks.test.ts b/packages/api/src/webhooks/webhooks.test.ts index 2e479b4d7d6c..37fc19be7637 100644 --- a/packages/api/src/webhooks/webhooks.test.ts +++ b/packages/api/src/webhooks/webhooks.test.ts @@ -75,7 +75,7 @@ describe('webhooks', () => { payload, secret, signature, - }) + }), ).toBeTruthy() }) }) @@ -103,7 +103,7 @@ describe('webhooks', () => { payload, secret, signature, - }) + }), ).toBeTruthy() }) }) @@ -131,7 +131,7 @@ describe('webhooks', () => { payload, secret, signature, - }) + }), ).toBeTruthy() }) }) @@ -159,7 +159,7 @@ describe('webhooks', () => { payload, secret, signature, - }) + }), ).toBeTruthy() }) }) @@ -174,7 +174,7 @@ describe('webhooks', () => { }) expect(signature).toEqual( - 'eyJhbGciOiJIUzI1NiJ9.Tm8gbW9yZSBzZWNyZXRzLCBNYXJ0eS4.LBqlEwDa4bWxzrv_Y1_Y7S6_7czhzLZuF17d5c6YjXI' + 'eyJhbGciOiJIUzI1NiJ9.Tm8gbW9yZSBzZWNyZXRzLCBNYXJ0eS4.LBqlEwDa4bWxzrv_Y1_Y7S6_7czhzLZuF17d5c6YjXI', ) }) @@ -189,7 +189,7 @@ describe('webhooks', () => { payload, secret, signature, - }) + }), ).toBeTruthy() }) }) @@ -208,7 +208,7 @@ describe('webhooks', () => { payload, secret, signature, - }) + }), ).toBeTruthy() }) }) @@ -235,7 +235,7 @@ describe('webhooks', () => { }) expect(signature).toMatch( - 'AaP4EgcpPC5oE3eppI/s6EMtQCZ4Ap34wNHPoxBoikI=' + 'AaP4EgcpPC5oE3eppI/s6EMtQCZ4Ap34wNHPoxBoikI=', ) }) @@ -250,7 +250,7 @@ describe('webhooks', () => { payload, secret, signature, - }) + }), ).toBeTruthy() }) }) @@ -271,7 +271,7 @@ describe('webhooks', () => { }) expect( - verifyEvent('timestampSchemeVerifier', { event, secret }) + verifyEvent('timestampSchemeVerifier', { event, secret }), ).toBeTruthy() }) @@ -289,7 +289,7 @@ describe('webhooks', () => { }) expect( - verifyEvent('timestampSchemeVerifier', { event, secret }) + verifyEvent('timestampSchemeVerifier', { event, secret }), ).toBeTruthy() }) @@ -310,7 +310,7 @@ describe('webhooks', () => { event, payload, secret, - }) + }), ).toBeTruthy() }) @@ -453,7 +453,7 @@ describe('webhooks', () => { currentTimestampOverride: parseInt(svix_timestamp, 10) * 1000 - ONE_MINUTE, }, - }) + }), ).toBeTruthy() }) }) diff --git a/packages/auth-providers/auth0/api/src/decoder.ts b/packages/auth-providers/auth0/api/src/decoder.ts index 1ffb391713e5..c1b8a85c43c0 100644 --- a/packages/auth-providers/auth0/api/src/decoder.ts +++ b/packages/auth-providers/auth0/api/src/decoder.ts @@ -25,13 +25,13 @@ import type { Decoder } from '@redwoodjs/api' * */ export const verifyAuth0Token = ( - bearerToken: string + bearerToken: string, ): Promise> => { return new Promise((resolve, reject) => { const { AUTH0_DOMAIN, AUTH0_AUDIENCE } = process.env if (!AUTH0_DOMAIN || !AUTH0_AUDIENCE) { throw new Error( - '`AUTH0_DOMAIN` or `AUTH0_AUDIENCE` env vars are not set.' + '`AUTH0_DOMAIN` or `AUTH0_AUDIENCE` env vars are not set.', ) } @@ -58,9 +58,9 @@ export const verifyAuth0Token = ( resolve( typeof decoded === 'undefined' ? null - : (decoded as Record) + : (decoded as Record), ) - } + }, ) }) } diff --git a/packages/auth-providers/auth0/setup/src/setupHandler.ts b/packages/auth-providers/auth0/setup/src/setupHandler.ts index ff8323e2f463..d589bb2ba9f8 100644 --- a/packages/auth-providers/auth0/setup/src/setupHandler.ts +++ b/packages/auth-providers/auth0/setup/src/setupHandler.ts @@ -6,7 +6,7 @@ import { standardAuthHandler } from '@redwoodjs/cli-helpers' import type { Args } from './setup' const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8'), ) export async function handler({ force: forceArg }: Args) { diff --git a/packages/auth-providers/auth0/web/src/__tests__/auth0.test.tsx b/packages/auth-providers/auth0/web/src/__tests__/auth0.test.tsx index 62f821cafbab..aab7df2c6836 100644 --- a/packages/auth-providers/auth0/web/src/__tests__/auth0.test.tsx +++ b/packages/auth-providers/auth0/web/src/__tests__/auth0.test.tsx @@ -28,10 +28,10 @@ const adminUser: User = { let loggedInUser: User | undefined async function getTokenSilently( - options: GetTokenSilentlyOptions & { detailedResponse: true } + options: GetTokenSilentlyOptions & { detailedResponse: true }, ): Promise async function getTokenSilently( - options?: GetTokenSilentlyOptions + options?: GetTokenSilentlyOptions, ): Promise async function getTokenSilently(): Promise< string | GetTokenSilentlyVerboseResponse @@ -83,12 +83,12 @@ beforeEach(() => { function getAuth0Auth(customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( auth0MockClient as Auth0Client, - customProviderHooks + customProviderHooks, ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, diff --git a/packages/auth-providers/auth0/web/src/auth0.ts b/packages/auth-providers/auth0/web/src/auth0.ts index 54cb1a5fe787..9a880e52e2df 100644 --- a/packages/auth-providers/auth0/web/src/auth0.ts +++ b/packages/auth-providers/auth0/web/src/auth0.ts @@ -15,9 +15,9 @@ export function createAuth( customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean - } + }, ) { const authImplementation = createAuthImplementation(auth0Client) diff --git a/packages/auth-providers/azureActiveDirectory/api/src/__tests__/azureActiveDirectory.test.ts b/packages/auth-providers/azureActiveDirectory/api/src/__tests__/azureActiveDirectory.test.ts index f58e3c9ee3e9..a7303e5767dc 100644 --- a/packages/auth-providers/azureActiveDirectory/api/src/__tests__/azureActiveDirectory.test.ts +++ b/packages/auth-providers/azureActiveDirectory/api/src/__tests__/azureActiveDirectory.test.ts @@ -38,7 +38,7 @@ test('throws if AZURE_ACTIVE_DIRECTORY_AUTHORITY env var is not set', async () = process.env.AZURE_ACTIVE_DIRECTORY_JTW_ISSUER = 'jwt-issuer' await expect( - authDecoder('token', 'azureActiveDirectory', req) + authDecoder('token', 'azureActiveDirectory', req), ).rejects.toThrow('AZURE_ACTIVE_DIRECTORY_AUTHORITY env var is not set') }) diff --git a/packages/auth-providers/azureActiveDirectory/api/src/decoder.ts b/packages/auth-providers/azureActiveDirectory/api/src/decoder.ts index 447233db4611..1c82f09f5111 100644 --- a/packages/auth-providers/azureActiveDirectory/api/src/decoder.ts +++ b/packages/auth-providers/azureActiveDirectory/api/src/decoder.ts @@ -43,7 +43,7 @@ export const authDecoder: Decoder = async (token: string, type: string) => { 'Azure Active Directory. This might be a result of an ' + 'outage. See https://status.azure.com/en-us/status for ' + 'current status.', - err + err, ) } }) @@ -63,9 +63,9 @@ export const authDecoder: Decoder = async (token: string, type: string) => { resolve( typeof decoded === 'undefined' ? null - : (decoded as Record) + : (decoded as Record), ) - } + }, ) }) } diff --git a/packages/auth-providers/azureActiveDirectory/setup/src/setupHandler.ts b/packages/auth-providers/azureActiveDirectory/setup/src/setupHandler.ts index 1cb20c87a605..c6a1dc0c5dc8 100644 --- a/packages/auth-providers/azureActiveDirectory/setup/src/setupHandler.ts +++ b/packages/auth-providers/azureActiveDirectory/setup/src/setupHandler.ts @@ -6,7 +6,7 @@ import { standardAuthHandler } from '@redwoodjs/cli-helpers' import type { Args } from './setup' const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8'), ) export async function handler({ force: forceArg }: Args) { diff --git a/packages/auth-providers/azureActiveDirectory/web/src/__tests__/azureActiveDirectory.test.tsx b/packages/auth-providers/azureActiveDirectory/web/src/__tests__/azureActiveDirectory.test.tsx index ef8032bfa58d..adc839800bb4 100644 --- a/packages/auth-providers/azureActiveDirectory/web/src/__tests__/azureActiveDirectory.test.tsx +++ b/packages/auth-providers/azureActiveDirectory/web/src/__tests__/azureActiveDirectory.test.tsx @@ -119,12 +119,12 @@ beforeEach(() => { function getAzureActiveDirectoryAuth(customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( azureActiveDirectoryMockClient as AzureActiveDirectoryClient, - customProviderHooks + customProviderHooks, ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, diff --git a/packages/auth-providers/azureActiveDirectory/web/src/azureActiveDirectory.ts b/packages/auth-providers/azureActiveDirectory/web/src/azureActiveDirectory.ts index bbf37be373aa..82dcf0ed2291 100644 --- a/packages/auth-providers/azureActiveDirectory/web/src/azureActiveDirectory.ts +++ b/packages/auth-providers/azureActiveDirectory/web/src/azureActiveDirectory.ts @@ -14,19 +14,19 @@ export function createAuth( customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean - } + }, ) { const authImplementation = createAuthImplementation( - azureActiveDirectoryClient + azureActiveDirectoryClient, ) return createAuthentication(authImplementation, customProviderHooks) } function createAuthImplementation( - azureActiveDirectoryClient: AzureActiveDirectoryClient + azureActiveDirectoryClient: AzureActiveDirectoryClient, ) { return { type: 'azureActiveDirectory', @@ -48,9 +48,8 @@ function createAuthImplementation( // InteractionRequiredAuthError, call acquireTokenRedirect // https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/acquire-token.md try { - const token = await azureActiveDirectoryClient.acquireTokenSilent( - request - ) + const token = + await azureActiveDirectoryClient.acquireTokenSilent(request) return token.idToken } catch (error) { if (error instanceof InteractionRequiredAuthError) { diff --git a/packages/auth-providers/clerk/api/src/__tests__/clerk.test.ts b/packages/auth-providers/clerk/api/src/__tests__/clerk.test.ts index 1ccea2ef70a4..b169915b963b 100644 --- a/packages/auth-providers/clerk/api/src/__tests__/clerk.test.ts +++ b/packages/auth-providers/clerk/api/src/__tests__/clerk.test.ts @@ -44,7 +44,7 @@ describe('clerkAuthDecoder', () => { process.env.CLERK_JWT_KEY = 'jwt-key' await expect( - clerkAuthDecoder('invalid-token', 'clerk', req) + clerkAuthDecoder('invalid-token', 'clerk', req), ).rejects.toThrow() }) }) diff --git a/packages/auth-providers/clerk/api/src/decoder.ts b/packages/auth-providers/clerk/api/src/decoder.ts index 28f2c5dab15e..abd0d52b5798 100644 --- a/packages/auth-providers/clerk/api/src/decoder.ts +++ b/packages/auth-providers/clerk/api/src/decoder.ts @@ -40,7 +40,7 @@ export const authDecoder: Decoder = async (token: string, type: string) => { export const clerkAuthDecoder: Decoder = async ( token: string, - type: string + type: string, ) => { if (type !== 'clerk') { return null diff --git a/packages/auth-providers/clerk/setup/src/setupHandler.ts b/packages/auth-providers/clerk/setup/src/setupHandler.ts index d990fb20c9d6..ec0a258e6463 100644 --- a/packages/auth-providers/clerk/setup/src/setupHandler.ts +++ b/packages/auth-providers/clerk/setup/src/setupHandler.ts @@ -6,7 +6,7 @@ import { standardAuthHandler } from '@redwoodjs/cli-helpers' import type { Args } from './setup' const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8'), ) export const handler = async ({ force: forceArg }: Args) => { diff --git a/packages/auth-providers/clerk/web/src/__tests__/clerk.test.tsx b/packages/auth-providers/clerk/web/src/__tests__/clerk.test.tsx index 2ddaa1974573..7a5334f5d82a 100644 --- a/packages/auth-providers/clerk/web/src/__tests__/clerk.test.tsx +++ b/packages/auth-providers/clerk/web/src/__tests__/clerk.test.tsx @@ -104,7 +104,7 @@ beforeEach(() => { function getClerkAuth(customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth(customProviderHooks) @@ -191,7 +191,7 @@ describe('Clerk', () => { if ( rolesToCheck === 'admin' && (currentUser.emailAddresses as any).some( - (email) => email.emailAddress === 'admin@example.com' + (email) => email.emailAddress === 'admin@example.com', ) ) { return true diff --git a/packages/auth-providers/clerk/web/src/clerk.tsx b/packages/auth-providers/clerk/web/src/clerk.tsx index f23ac13718d7..2e3e2fb8cc7a 100644 --- a/packages/auth-providers/clerk/web/src/clerk.tsx +++ b/packages/auth-providers/clerk/web/src/clerk.tsx @@ -20,10 +20,10 @@ export function createAuth( customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean }, - authImplementationOptions?: AuthImplementationOptions + authImplementationOptions?: AuthImplementationOptions, ) { const authImplementation = createAuthImplementation(authImplementationOptions) @@ -48,7 +48,7 @@ function createAuthImplementation({ }, logout: async ( callbackOrOptions?: SignOutCallback | SignOutOptions, - options?: SignOutOptions + options?: SignOutOptions, ) => { const clerk = (window as any).Clerk as Clerk return clerk?.signOut(callbackOrOptions as any, options) diff --git a/packages/auth-providers/custom/setup/src/setupHandler.ts b/packages/auth-providers/custom/setup/src/setupHandler.ts index a055e0924662..9833e837bd9b 100644 --- a/packages/auth-providers/custom/setup/src/setupHandler.ts +++ b/packages/auth-providers/custom/setup/src/setupHandler.ts @@ -9,7 +9,7 @@ import { import type { Args } from './setup' const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8'), ) export async function handler({ force: forceArg }: Args) { diff --git a/packages/auth-providers/dbAuth/api/src/DbAuthHandler.ts b/packages/auth-providers/dbAuth/api/src/DbAuthHandler.ts index bbdb52b55c2d..c276f127548c 100644 --- a/packages/auth-providers/dbAuth/api/src/DbAuthHandler.ts +++ b/packages/auth-providers/dbAuth/api/src/DbAuthHandler.ts @@ -170,7 +170,7 @@ export type UserType = Record export interface DbAuthHandlerOptions< TUser = UserType, - TUserAttributes = Record + TUserAttributes = Record, > { /** * Provide prisma db client @@ -301,7 +301,7 @@ const DEFAULT_ALLOWED_USER_FIELDS = ['id', 'email'] export class DbAuthHandler< TUser extends UserType, - TUserAttributes = Record + TUserAttributes = Record, > { event: Request | APIGatewayProxyEvent _normalizedRequest: PartialRequest | undefined @@ -324,7 +324,7 @@ export class DbAuthHandler< if (!this._normalizedRequest) { // This is a dev time error, no need to throw a specialized error throw new Error( - 'dbAuthHandler has not been initialised. Either await dbAuthHandler.invoke() or call await dbAuth.init()' + 'dbAuthHandler has not been initialised. Either await dbAuthHandler.invoke() or call await dbAuth.init()', ) } return this._normalizedRequest @@ -401,7 +401,7 @@ export class DbAuthHandler< constructor( event: APIGatewayProxyEvent | Request, _context: LambdaContext, // @TODO: - options: DbAuthHandlerOptions + options: DbAuthHandlerOptions, ) { this.options = options this.event = event @@ -423,14 +423,14 @@ export class DbAuthHandler< const sessionExpiresAt = new Date() sessionExpiresAt.setSeconds( sessionExpiresAt.getSeconds() + - (this.options.login as LoginFlowOptions).expires + (this.options.login as LoginFlowOptions).expires, ) this.sessionExpiresDate = sessionExpiresAt.toUTCString() const webAuthnExpiresAt = new Date() webAuthnExpiresAt.setSeconds( webAuthnExpiresAt.getSeconds() + - ((this.options?.webAuthn as WebAuthnFlowOptions)?.expires || 0) + ((this.options?.webAuthn as WebAuthnFlowOptions)?.expires || 0), ) this.webAuthnExpiresDate = webAuthnExpiresAt.toUTCString() @@ -463,7 +463,7 @@ export class DbAuthHandler< async init() { if (!this._normalizedRequest) { this._normalizedRequest = (await normalizeRequest( - this.event + this.event, )) as PartialRequest } } @@ -479,7 +479,7 @@ export class DbAuthHandler< if (this.corsContext.shouldHandleCors(this.normalizedRequest)) { return this._buildResponseWithCorsHeaders( { body: '', statusCode: 200 }, - corsHeaders + corsHeaders, ) } } @@ -489,7 +489,7 @@ export class DbAuthHandler< if (this.hasInvalidSession) { return this._buildResponseWithCorsHeaders( this._ok(...this._logoutResponse()), - corsHeaders + corsHeaders, ) } @@ -507,13 +507,12 @@ export class DbAuthHandler< } // call whatever auth method was requested and return the body and headers - const [body, headers, options = { statusCode: 200 }] = await this[ - method - ]() + const [body, headers, options = { statusCode: 200 }] = + await this[method]() return this._buildResponseWithCorsHeaders( this._ok(body, headers, options), - corsHeaders + corsHeaders, ) } catch (e: any) { if (e instanceof DbAuthError.WrongVerbError) { @@ -521,7 +520,7 @@ export class DbAuthHandler< } else { return this._buildResponseWithCorsHeaders( this._badRequest(e.message || e), - corsHeaders + corsHeaders, ) } } @@ -533,7 +532,7 @@ export class DbAuthHandler< if (!enabled) { throw new DbAuthError.FlowNotEnabledError( (this.options.forgotPassword as ForgotPasswordFlowOptions)?.errors - ?.flowNotEnabled || `Forgot password flow is not enabled` + ?.flowNotEnabled || `Forgot password flow is not enabled`, ) } @@ -542,7 +541,7 @@ export class DbAuthHandler< if (!username || username.trim() === '') { throw new DbAuthError.UsernameRequiredError( (this.options.forgotPassword as ForgotPasswordFlowOptions)?.errors - ?.usernameRequired || `Username is required` + ?.usernameRequired || `Username is required`, ) } let user @@ -559,7 +558,7 @@ export class DbAuthHandler< const tokenExpires = new Date() tokenExpires.setSeconds( tokenExpires.getSeconds() + - (this.options.forgotPassword as ForgotPasswordFlowOptions).expires + (this.options.forgotPassword as ForgotPasswordFlowOptions).expires, ) // generate a token @@ -599,7 +598,7 @@ export class DbAuthHandler< } else { throw new DbAuthError.UsernameNotFoundError( (this.options.forgotPassword as ForgotPasswordFlowOptions)?.errors - ?.usernameNotFound || `Username '${username} not found` + ?.usernameNotFound || `Username '${username} not found`, ) } } @@ -631,14 +630,14 @@ export class DbAuthHandler< if (!enabled) { throw new DbAuthError.FlowNotEnabledError( (this.options.login as LoginFlowOptions)?.errors?.flowNotEnabled || - `Login flow is not enabled` + `Login flow is not enabled`, ) } const { username, password } = this.normalizedRequest.jsonBody || {} const dbUser = await this._verifyUser(username, password) const handlerUser = await (this.options.login as LoginFlowOptions).handler( - dbUser + dbUser, ) if ( @@ -660,7 +659,7 @@ export class DbAuthHandler< if (!enabled) { throw new DbAuthError.FlowNotEnabledError( (this.options.resetPassword as ResetPasswordFlowOptions)?.errors - ?.flowNotEnabled || `Reset password flow is not enabled` + ?.flowNotEnabled || `Reset password flow is not enabled`, ) } @@ -671,7 +670,7 @@ export class DbAuthHandler< throw new DbAuthError.ResetTokenRequiredError( ( this.options.resetPassword as ResetPasswordFlowOptions - )?.errors?.resetTokenRequired + )?.errors?.resetTokenRequired, ) } @@ -695,7 +694,7 @@ export class DbAuthHandler< throw new DbAuthError.ReusedPasswordError( ( this.options.resetPassword as ResetPasswordFlowOptions - )?.errors?.reusedPassword + )?.errors?.reusedPassword, ) } @@ -733,14 +732,14 @@ export class DbAuthHandler< if (!enabled) { throw new DbAuthError.FlowNotEnabledError( (this.options.signup as SignupFlowOptions)?.errors?.flowNotEnabled || - `Signup flow is not enabled` + `Signup flow is not enabled`, ) } // check if password is valid const { password } = this.normalizedRequest.jsonBody || {} ;(this.options.signup as SignupFlowOptions).passwordValidation?.( - password as string + password as string, ) const userOrMessage = await this._createUser() @@ -764,7 +763,7 @@ export class DbAuthHandler< throw new DbAuthError.ResetTokenRequiredError( ( this.options.resetPassword as ResetPasswordFlowOptions - )?.errors?.resetTokenRequired + )?.errors?.resetTokenRequired, ) } @@ -818,14 +817,14 @@ export class DbAuthHandler< expectedRPID: webAuthnOptions.domain, authenticator: { credentialID: base64url.toBuffer( - credential[webAuthnOptions.credentialFields.id] + credential[webAuthnOptions.credentialFields.id], ), credentialPublicKey: credential[webAuthnOptions.credentialFields.publicKey], counter: credential[webAuthnOptions.credentialFields.counter], transports: credential[webAuthnOptions.credentialFields.transports] ? JSON.parse( - credential[webAuthnOptions.credentialFields.transports] + credential[webAuthnOptions.credentialFields.transports], ) : DbAuthHandler.AVAILABLE_WEBAUTHN_TRANSPORTS, }, @@ -927,7 +926,7 @@ export class DbAuthHandler< await this._saveChallenge( user[this.options.authFields.id], - authOptions.challenge + authOptions.challenge, ) return [authOptions] @@ -963,7 +962,7 @@ export class DbAuthHandler< if (webAuthnOptions.type && webAuthnOptions.type !== 'any') { options.authenticatorSelection = Object.assign( options.authenticatorSelection || {}, - { authenticatorAttachment: webAuthnOptions.type } + { authenticatorAttachment: webAuthnOptions.type }, ) } @@ -971,7 +970,7 @@ export class DbAuthHandler< await this._saveChallenge( user[this.options.authFields.id], - regOptions.challenge + regOptions.challenge, ) return [regOptions] @@ -1044,7 +1043,7 @@ export class DbAuthHandler< { 'set-cookie': this._webAuthnCookie( plainCredentialId, - this.webAuthnExpiresDate + this.webAuthnExpiresDate, ), }, ] @@ -1207,7 +1206,7 @@ export class DbAuthHandler< // creates the session) _createSessionHeader( data: DbAuthSession, - csrfToken: string + csrfToken: string, ): SetCookieHeader { const session = JSON.stringify(data) + ';' + csrfToken const encrypted = encryptSession(session) @@ -1236,7 +1235,7 @@ export class DbAuthHandler< const tokenExpires = new Date() tokenExpires.setSeconds( tokenExpires.getSeconds() - - (this.options.forgotPassword as ForgotPasswordFlowOptions).expires + (this.options.forgotPassword as ForgotPasswordFlowOptions).expires, ) const tokenHash = hashToken(token) @@ -1252,7 +1251,7 @@ export class DbAuthHandler< throw new DbAuthError.ResetTokenInvalidError( ( this.options.resetPassword as ResetPasswordFlowOptions - )?.errors?.resetTokenInvalid + )?.errors?.resetTokenInvalid, ) } @@ -1262,7 +1261,7 @@ export class DbAuthHandler< throw new DbAuthError.ResetTokenExpiredError( ( this.options.resetPassword as ResetPasswordFlowOptions - )?.errors?.resetTokenExpired + )?.errors?.resetTokenExpired, ) } @@ -1289,7 +1288,7 @@ export class DbAuthHandler< // verifies that a username and password are correct, and returns the user if so async _verifyUser( username: string | undefined, - password: string | undefined + password: string | undefined, ) { // do we have all the query params we need to check the user? if ( @@ -1301,7 +1300,7 @@ export class DbAuthHandler< throw new DbAuthError.UsernameAndPasswordRequiredError( ( this.options.login as LoginFlowOptions - )?.errors?.usernameOrPasswordMissing + )?.errors?.usernameOrPasswordMissing, ) } @@ -1323,7 +1322,7 @@ export class DbAuthHandler< if (!user) { throw new DbAuthError.UserNotFoundError( username, - (this.options.login as LoginFlowOptions)?.errors?.usernameNotFound + (this.options.login as LoginFlowOptions)?.errors?.usernameNotFound, ) } @@ -1337,7 +1336,7 @@ export class DbAuthHandler< // if no options are present. async _verifyPassword(user: Record, password: string) { const options = extractHashingOptions( - user[this.options.authFields.hashedPassword] as string + user[this.options.authFields.hashedPassword] as string, ) if (Object.keys(options).length) { @@ -1354,7 +1353,7 @@ export class DbAuthHandler< // fallback to old CryptoJS hashing const [legacyHashedPassword] = legacyHashPassword( password, - user[this.options.authFields.salt] as string + user[this.options.authFields.salt] as string, ) if ( @@ -1375,7 +1374,7 @@ export class DbAuthHandler< throw new DbAuthError.IncorrectPasswordError( user[this.options.authFields.username] as string, - (this.options.login as LoginFlowOptions)?.errors?.incorrectPassword + (this.options.login as LoginFlowOptions)?.errors?.incorrectPassword, ) } @@ -1436,7 +1435,7 @@ export class DbAuthHandler< if (user) { throw new DbAuthError.DuplicateUsernameError( username, - (this.options.signup as SignupFlowOptions)?.errors?.usernameTaken + (this.options.signup as SignupFlowOptions)?.errors?.usernameTaken, ) } @@ -1480,7 +1479,7 @@ export class DbAuthHandler< if (!value || value.trim() === '') { throw new DbAuthError.FieldRequiredError( name, - (this.options.signup as SignupFlowOptions)?.errors?.fieldMissing + (this.options.signup as SignupFlowOptions)?.errors?.fieldMissing, ) } else { return true @@ -1489,11 +1488,11 @@ export class DbAuthHandler< _loginResponse( user: Record, - statusCode = 200 + statusCode = 200, ): [ { id: string }, SetCookieHeader & CsrfTokenHeader, - { statusCode: number } + { statusCode: number }, ] { const sessionData = this._sanitizeUser(user) @@ -1513,7 +1512,7 @@ export class DbAuthHandler< } _logoutResponse( - response?: Record + response?: Record, ): [string, SetCookieHeader] { return [ response ? JSON.stringify(response) : '', @@ -1552,7 +1551,7 @@ export class DbAuthHandler< statusCode: number headers?: Record }, - corsHeaders: CorsHeaders + corsHeaders: CorsHeaders, ) { return { ...response, @@ -1565,7 +1564,7 @@ export class DbAuthHandler< _getUserMatchCriteriaOptions( username: string, - usernameMatchFlowOption: string | undefined + usernameMatchFlowOption: string | undefined, ) { // Each db provider has it owns rules for case insensitive comparison. // We are checking if you have defined one for your db choice here diff --git a/packages/auth-providers/dbAuth/api/src/__tests__/DbAuthHandler.fetch.test.js b/packages/auth-providers/dbAuth/api/src/__tests__/DbAuthHandler.fetch.test.js index 82116c9f2eb6..4004327419bc 100644 --- a/packages/auth-providers/dbAuth/api/src/__tests__/DbAuthHandler.fetch.test.js +++ b/packages/auth-providers/dbAuth/api/src/__tests__/DbAuthHandler.fetch.test.js @@ -59,7 +59,7 @@ const TableMock = class { let matchingRecords = this.records keys.forEach((key) => { matchingRecords = matchingRecords.filter( - (record) => record[key] === where[key] + (record) => record[key] === where[key], ) }) return matchingRecords[0] @@ -97,7 +97,7 @@ const LOGOUT_COOKIE = 'session=;Expires=Thu, 01 Jan 1970 00:00:00 GMT' const SESSION_SECRET = '540d03ebb00b441f8f7442cbc39958ad' const FIXTURE_PATH = path.resolve( __dirname, - '../../../../../../__fixtures__/example-todo-main' + '../../../../../../__fixtures__/example-todo-main', ) beforeAll(() => { @@ -134,7 +134,7 @@ const encryptToCookie = (data) => { const cipher = crypto.createCipheriv( 'aes-256-cbc', SESSION_SECRET.substring(0, 32), - iv + iv, ) let encryptedSession = cipher.update(data, 'utf-8', 'base64') encryptedSession += cipher.final('base64') @@ -255,7 +255,7 @@ describe('dbAuth', () => { describe('PAST_EXPIRES_DATE', () => { it('returns the start of epoch as a UTCString', () => { expect(DbAuthHandler.PAST_EXPIRES_DATE).toEqual( - new Date('1970-01-01T00:00:00.000+00:00').toUTCString() + new Date('1970-01-01T00:00:00.000+00:00').toUTCString(), ) }) }) @@ -351,7 +351,7 @@ describe('dbAuth', () => { signup: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoForgotPasswordHandler) expect( @@ -368,7 +368,7 @@ describe('dbAuth', () => { signup: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoForgotPasswordHandler) }) @@ -390,7 +390,7 @@ describe('dbAuth', () => { forgotPassword: { enabled: false, }, - }) + }), ).not.toThrow(dbAuthError.NoForgotPasswordHandler) }) @@ -408,7 +408,7 @@ describe('dbAuth', () => { signup: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoSessionExpirationError) // login object exists, but not `expires` key expect( @@ -426,7 +426,7 @@ describe('dbAuth', () => { signup: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoSessionExpirationError) }) @@ -446,7 +446,7 @@ describe('dbAuth', () => { signup: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoLoginHandlerError) }) @@ -466,7 +466,7 @@ describe('dbAuth', () => { forgotPassword: { handler: () => {}, }, - }) + }), ).not.toThrow(dbAuthError.NoLoginHandlerError) }) @@ -484,7 +484,7 @@ describe('dbAuth', () => { resetPassword: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoSignupHandler) expect( @@ -501,7 +501,7 @@ describe('dbAuth', () => { handler: () => {}, }, signup: {}, - }) + }), ).toThrow(dbAuthError.NoSignupHandler) }) @@ -523,7 +523,7 @@ describe('dbAuth', () => { forgotPassword: { handler: () => {}, }, - }) + }), ).not.toThrow(dbAuthError.NoSignupHandler) }) @@ -574,7 +574,7 @@ describe('dbAuth', () => { await dbAuth.init() await dbAuth.init() expect(dbAuth.normalizedRequest.headers.get('csrf-token')).toEqual( - 'qwerty' + 'qwerty', ) }) @@ -605,7 +605,7 @@ describe('dbAuth', () => { delete process.env.SESSION_SECRET expect(() => new DbAuthHandler(req, context, options)).toThrow( - dbAuthError.NoSessionSecretError + dbAuthError.NoSessionSecretError, ) }) }) @@ -706,7 +706,7 @@ describe('dbAuth', () => { expect(response.statusCode).toEqual(200) expect(response.headers['access-control-allow-credentials']).toBe('true') expect(response.headers['access-control-allow-origin']).toBe( - 'https://www.myRedwoodWebSide.com' + 'https://www.myRedwoodWebSide.com', ) }) @@ -1468,7 +1468,7 @@ describe('dbAuth', () => { it('throws an error if resetToken is expired', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires - 1 + tokenExpires.getSeconds() - options.forgotPassword.expires - 1, ) await createDbUser({ resetToken: hashToken('1234'), @@ -1495,7 +1495,7 @@ describe('dbAuth', () => { it('clears out resetToken and resetTokenExpiresAt if expired', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires - 1 + tokenExpires.getSeconds() - options.forgotPassword.expires - 1, ) const user = await createDbUser({ resetToken: hashToken('1234'), @@ -1529,7 +1529,7 @@ describe('dbAuth', () => { it('throws allowReusedPassword is false and new password is same as old', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) await createDbUser({ resetToken: hashToken('1234'), @@ -1550,14 +1550,14 @@ describe('dbAuth', () => { await dbAuth.init() await expect(dbAuth.resetPassword()).rejects.toThrow( - dbAuthError.ReusedPasswordError + dbAuthError.ReusedPasswordError, ) }) it('does not throw if allowReusedPassword is true and new password is same as old', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) await createDbUser({ resetToken: hashToken('1234'), @@ -1583,7 +1583,7 @@ describe('dbAuth', () => { it('updates the users password', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) const user = await createDbUser({ resetToken: hashToken('1234'), @@ -1615,7 +1615,7 @@ describe('dbAuth', () => { it('clears resetToken and resetTokenExpiresAt', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) const user = await createDbUser({ resetToken: hashToken('1234'), @@ -1646,7 +1646,7 @@ describe('dbAuth', () => { it('invokes resetPassword.handler() with the user', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) const user = await createDbUser({ resetToken: hashToken('1234'), @@ -1674,7 +1674,7 @@ describe('dbAuth', () => { it('returns a logout response if handler returns falsy', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) await createDbUser({ resetToken: hashToken('1234'), @@ -1701,7 +1701,7 @@ describe('dbAuth', () => { it('returns a login response if handler returns falsy', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) await createDbUser({ resetToken: hashToken('1234'), @@ -1923,7 +1923,7 @@ describe('dbAuth', () => { it('returns the ID of the logged in user', async () => { const user = await createDbUser() const cookie = encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ) const headers = { @@ -1955,7 +1955,7 @@ describe('dbAuth', () => { req = { headers: { cookie: encryptToCookie( - JSON.stringify({ id: 9999999999 }) + ';' + 'token' + JSON.stringify({ id: 9999999999 }) + ';' + 'token', ), }, } @@ -2011,7 +2011,7 @@ describe('dbAuth', () => { const headers = { 'auth-provider': 'dbAuth', 'rw-studio-impersonation-cookie': encryptToCookie( - JSON.stringify({ id: dbUser.id }) + JSON.stringify({ id: dbUser.id }), ), } @@ -2039,7 +2039,7 @@ describe('dbAuth', () => { cookie: encryptToCookie(JSON.stringify({ id: 9999999999 })), // The "real" cookie with an invalid userId // 👇 The impersonated header takes precendence 'rw-studio-impersonation-cookie': encryptToCookie( - JSON.stringify({ id: dbUser.id }) + JSON.stringify({ id: dbUser.id }), ), }, }) @@ -2062,7 +2062,7 @@ describe('dbAuth', () => { headers: { 'auth-provider': 'dbAuth', 'rw-studio-impersonation-cookie': encryptToCookie( - JSON.stringify({ id: dbUserId }) + JSON.stringify({ id: dbUserId }), ), authorization: 'Bearer ' + dbUserId, }, @@ -2074,7 +2074,7 @@ describe('dbAuth', () => { await dbAuth._getCurrentUser() } catch (e) { expect(e.message).toEqual( - 'Cannot retrieve user details without being logged in' + 'Cannot retrieve user details without being logged in', ) } }) @@ -2108,7 +2108,7 @@ describe('dbAuth', () => { expect.assertions(1) await expect(dbAuth.webAuthnAuthenticate()).rejects.toThrow( - dbAuthError.WebAuthnError + dbAuthError.WebAuthnError, ) }) @@ -2127,7 +2127,7 @@ describe('dbAuth', () => { expect.assertions(1) await expect(dbAuth.webAuthnAuthenticate()).rejects.toThrow( - 'Credentials not found' + 'Credentials not found', ) }) @@ -2155,7 +2155,7 @@ describe('dbAuth', () => { expect.assertions(1) await expect(dbAuth.webAuthnAuthenticate()).rejects.toThrow( - 'Unexpected authentication response challenge' + 'Unexpected authentication response challenge', ) }) @@ -2224,7 +2224,7 @@ describe('dbAuth', () => { expect(body).toEqual(false) expect(headers['set-cookie'][0]).toMatch( - 'webAuthn=CxMJqILwYufSaEQsJX6rKHw_LkMXAGU64PaKU55l6ejZ4FNO5kBLiA' + 'webAuthn=CxMJqILwYufSaEQsJX6rKHw_LkMXAGU64PaKU55l6ejZ4FNO5kBLiA', ) }) }) @@ -2267,7 +2267,7 @@ describe('dbAuth', () => { req = { headers: { cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), }, } @@ -2295,7 +2295,7 @@ describe('dbAuth', () => { req = { headers: { cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), }, } @@ -2354,7 +2354,7 @@ describe('dbAuth', () => { const user = await createDbUser() const headers = { cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), } @@ -2370,7 +2370,7 @@ describe('dbAuth', () => { expect(regOptions.attestation).toEqual('none') expect(regOptions.authenticatorSelection.authenticatorAttachment).toEqual( - options.webAuthn.type + options.webAuthn.type, ) expect(regOptions.excludeCredentials).toEqual([]) expect(regOptions.rp.name).toEqual(options.webAuthn.name) @@ -2385,7 +2385,7 @@ describe('dbAuth', () => { const user = await createDbUser() const headers = { cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), } @@ -2406,7 +2406,7 @@ describe('dbAuth', () => { let user = await createDbUser() const headers = { cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), } @@ -2433,7 +2433,7 @@ describe('dbAuth', () => { headers: { 'Content-Type': 'application/json', cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), }, body: '{"method":"webAuthnRegister","id":"GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg","rawId":"GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg","response":{"attestationObject":"o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVisSZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NFAAAAAK3OAAI1vMYKZIsLJfHwVQMAKBqo2TrmGKaTmwQ3lZJ263AS5GmvYpkuRCScLQle-NGrFM9uLHQJhhalAQIDJiABIVggGIipTQt-gcoDPOpW6Zje_Av9C0-jWb2R2PBmXJJL-c8iWCC76wxo3uzG8cPqb0A8Vij-dqMbrEytEHjuFOtiQ2dt8A","clientDataJSON":"eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiSHVHUHJRcUs3ZjUzTkx3TVpNc3RfREw5RGlnMkJCaXZEWVdXcGF3SVBWTSIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODkxMCIsImNyb3NzT3JpZ2luIjpmYWxzZSwib3RoZXJfa2V5c19jYW5fYmVfYWRkZWRfaGVyZSI6ImRvIG5vdCBjb21wYXJlIGNsaWVudERhdGFKU09OIGFnYWluc3QgYSB0ZW1wbGF0ZS4gU2VlIGh0dHBzOi8vZ29vLmdsL3lhYlBleCJ9"},"type":"public-key","clientExtensionResults":{},"transports":["internal"]}', @@ -2448,7 +2448,7 @@ describe('dbAuth', () => { }) expect(credential.id).toEqual( - 'GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg' + 'GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg', ) expect(credential.transports).toEqual('["internal"]') expect(credential.counter).toEqual(0) @@ -2462,12 +2462,12 @@ describe('dbAuth', () => { headers: { 'Content-Type': 'application/json', cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), }, body: Buffer.from( `{"method":"webAuthnRegister","id":"GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg","rawId":"GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg","response":{"attestationObject":"o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVisSZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NFAAAAAK3OAAI1vMYKZIsLJfHwVQMAKBqo2TrmGKaTmwQ3lZJ263AS5GmvYpkuRCScLQle-NGrFM9uLHQJhhalAQIDJiABIVggGIipTQt-gcoDPOpW6Zje_Av9C0-jWb2R2PBmXJJL-c8iWCC76wxo3uzG8cPqb0A8Vij-dqMbrEytEHjuFOtiQ2dt8A","clientDataJSON":"eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiSHVHUHJRcUs3ZjUzTkx3TVpNc3RfREw5RGlnMkJCaXZEWVdXcGF3SVBWTSIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODkxMCIsImNyb3NzT3JpZ2luIjpmYWxzZSwib3RoZXJfa2V5c19jYW5fYmVfYWRkZWRfaGVyZSI6ImRvIG5vdCBjb21wYXJlIGNsaWVudERhdGFKU09OIGFnYWluc3QgYSB0ZW1wbGF0ZS4gU2VlIGh0dHBzOi8vZ29vLmdsL3lhYlBleCJ9"},"type":"public-key","clientExtensionResults":{},"transports":["internal"]}`, - 'utf8' + 'utf8', ), } const dbAuth = new DbAuthHandler(req, context, options) @@ -2480,7 +2480,7 @@ describe('dbAuth', () => { }) expect(credential.id).toEqual( - 'GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg' + 'GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg', ) }) }) @@ -2518,7 +2518,7 @@ describe('dbAuth', () => { const dbAuth = new DbAuthHandler({ headers: {} }, context, options) expect(dbAuth._webAuthnCookie('1234', 'now')).toMatch( - 'webAuthn=1234;Expires=Thu, 01 Jan 1970 00:00:00 GMT' + 'webAuthn=1234;Expires=Thu, 01 Jan 1970 00:00:00 GMT', ) }) }) @@ -2539,7 +2539,7 @@ describe('dbAuth', () => { Domain: 'example.com', }, }, - } + }, ) const attributes = dbAuth._cookieAttributes({}) @@ -2612,7 +2612,7 @@ describe('dbAuth', () => { expect(Object.keys(headers).length).toEqual(1) expect(headers['set-cookie']).toMatch( - `Expires=${dbAuth.sessionExpiresDate}` + `Expires=${dbAuth.sessionExpiresDate}`, ) // can't really match on the session value since it will change on every render, // due to CSRF token generation but we can check that it contains only the @@ -2854,7 +2854,7 @@ describe('dbAuth', () => { // password now hashed by node:crypto expect(user.hashedPassword).toEqual( - 'f20d69d478fa1afc85057384e21bd457a76b23b23e2a94f5bd982976f700a552|16384|8|1' + 'f20d69d478fa1afc85057384e21bd457a76b23b23e2a94f5bd982976f700a552|16384|8|1', ) // salt should remain the same expect(user.salt).toEqual('2ef27f4073c603ba8b7807c6de6d6a89') @@ -2902,7 +2902,7 @@ describe('dbAuth', () => { const dbUser = await createDbUser() const headers = { cookie: encryptToCookie( - JSON.stringify({ id: dbUser.id }) + ';' + 'token' + JSON.stringify({ id: dbUser.id }) + ';' + 'token', ), } @@ -2929,7 +2929,7 @@ describe('dbAuth', () => { const dbUser = await createDbUser() const headers = { cookie: encryptToCookie( - JSON.stringify({ id: dbUser.id }) + ';' + 'token' + JSON.stringify({ id: dbUser.id }) + ';' + 'token', ), } @@ -2970,7 +2970,7 @@ describe('dbAuth', () => { } const headers = { cookie: encryptToCookie( - JSON.stringify({ userId: dbUser.userId }) + ';' + 'token' + JSON.stringify({ userId: dbUser.userId }) + ';' + 'token', ), } @@ -3012,7 +3012,7 @@ describe('dbAuth', () => { } catch (e) { expect(e).toBeInstanceOf(dbAuthError.DuplicateUsernameError) expect(e.message).toEqual( - defaultMessage.replace(/\$\{username\}/, dbUser.email) + defaultMessage.replace(/\$\{username\}/, dbUser.email), ) } @@ -3096,7 +3096,7 @@ describe('dbAuth', () => { } catch (e) { expect(e).toBeInstanceOf(dbAuthError.DuplicateUsernameError) expect(e.message).toEqual( - defaultMessage.replace(/\$\{username\}/, dbUser.email) + defaultMessage.replace(/\$\{username\}/, dbUser.email), ) } @@ -3128,7 +3128,7 @@ describe('dbAuth', () => { } catch (e) { expect(e).toBeInstanceOf(dbAuthError.FieldRequiredError) expect(e.message).toEqual( - defaultMessage.replace(/\$\{field\}/, 'username') + defaultMessage.replace(/\$\{field\}/, 'username'), ) } @@ -3178,7 +3178,7 @@ describe('dbAuth', () => { } catch (e) { expect(e).toBeInstanceOf(dbAuthError.FieldRequiredError) expect(e.message).toEqual( - defaultMessage.replace(/\$\{field\}/, 'password') + defaultMessage.replace(/\$\{field\}/, 'password'), ) } diff --git a/packages/auth-providers/dbAuth/api/src/__tests__/DbAuthHandler.test.js b/packages/auth-providers/dbAuth/api/src/__tests__/DbAuthHandler.test.js index 4eb2c75dd6da..79806fb8703a 100644 --- a/packages/auth-providers/dbAuth/api/src/__tests__/DbAuthHandler.test.js +++ b/packages/auth-providers/dbAuth/api/src/__tests__/DbAuthHandler.test.js @@ -59,7 +59,7 @@ const TableMock = class { let matchingRecords = this.records keys.forEach((key) => { matchingRecords = matchingRecords.filter( - (record) => record[key] === where[key] + (record) => record[key] === where[key], ) }) return matchingRecords[0] @@ -97,7 +97,7 @@ const LOGOUT_COOKIE = 'session=;Expires=Thu, 01 Jan 1970 00:00:00 GMT' const SESSION_SECRET = '540d03ebb00b441f8f7442cbc39958ad' const FIXTURE_PATH = path.resolve( __dirname, - '../../../../../../__fixtures__/example-todo-main' + '../../../../../../__fixtures__/example-todo-main', ) beforeAll(() => { @@ -134,7 +134,7 @@ const encryptToCookie = (data) => { const cipher = crypto.createCipheriv( 'aes-256-cbc', SESSION_SECRET.substring(0, 32), - iv + iv, ) let encryptedSession = cipher.update(data, 'utf-8', 'base64') encryptedSession += cipher.final('base64') @@ -255,7 +255,7 @@ describe('dbAuth', () => { describe('PAST_EXPIRES_DATE', () => { it('returns the start of epoch as a UTCString', () => { expect(DbAuthHandler.PAST_EXPIRES_DATE).toEqual( - new Date('1970-01-01T00:00:00.000+00:00').toUTCString() + new Date('1970-01-01T00:00:00.000+00:00').toUTCString(), ) }) }) @@ -351,7 +351,7 @@ describe('dbAuth', () => { signup: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoForgotPasswordHandler) expect( @@ -368,7 +368,7 @@ describe('dbAuth', () => { signup: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoForgotPasswordHandler) }) @@ -390,7 +390,7 @@ describe('dbAuth', () => { forgotPassword: { enabled: false, }, - }) + }), ).not.toThrow(dbAuthError.NoForgotPasswordHandler) }) @@ -408,7 +408,7 @@ describe('dbAuth', () => { signup: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoSessionExpirationError) // login object exists, but not `expires` key expect( @@ -426,7 +426,7 @@ describe('dbAuth', () => { signup: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoSessionExpirationError) }) @@ -446,7 +446,7 @@ describe('dbAuth', () => { signup: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoLoginHandlerError) }) @@ -466,7 +466,7 @@ describe('dbAuth', () => { forgotPassword: { handler: () => {}, }, - }) + }), ).not.toThrow(dbAuthError.NoLoginHandlerError) }) @@ -484,7 +484,7 @@ describe('dbAuth', () => { resetPassword: { handler: () => {}, }, - }) + }), ).toThrow(dbAuthError.NoSignupHandler) expect( @@ -501,7 +501,7 @@ describe('dbAuth', () => { handler: () => {}, }, signup: {}, - }) + }), ).toThrow(dbAuthError.NoSignupHandler) }) @@ -523,7 +523,7 @@ describe('dbAuth', () => { forgotPassword: { handler: () => {}, }, - }) + }), ).not.toThrow(dbAuthError.NoSignupHandler) }) @@ -612,7 +612,7 @@ describe('dbAuth', () => { const dbAuth = new DbAuthHandler(event, context, options) await dbAuth.init() expect(dbAuth.normalizedRequest.headers.get('csrf-token')).toEqual( - 'qwerty' + 'qwerty', ) }) @@ -643,7 +643,7 @@ describe('dbAuth', () => { delete process.env.SESSION_SECRET expect(() => new DbAuthHandler(event, context, options)).toThrow( - dbAuthError.NoSessionSecretError + dbAuthError.NoSessionSecretError, ) }) }) @@ -721,7 +721,7 @@ describe('dbAuth', () => { expect(response.statusCode).toEqual(200) expect(response.headers['access-control-allow-credentials']).toBe('true') expect(response.headers['access-control-allow-origin']).toBe( - 'https://www.myRedwoodWebSide.com' + 'https://www.myRedwoodWebSide.com', ) }) @@ -1321,7 +1321,7 @@ describe('dbAuth', () => { it('throws an error if resetToken is expired', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires - 1 + tokenExpires.getSeconds() - options.forgotPassword.expires - 1, ) await createDbUser({ resetToken: hashToken('1234'), @@ -1343,7 +1343,7 @@ describe('dbAuth', () => { it('clears out resetToken and resetTokenExpiresAt if expired', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires - 1 + tokenExpires.getSeconds() - options.forgotPassword.expires - 1, ) const user = await createDbUser({ resetToken: hashToken('1234'), @@ -1372,7 +1372,7 @@ describe('dbAuth', () => { it('throws allowReusedPassword is false and new password is same as old', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) await createDbUser({ resetToken: hashToken('1234'), @@ -1388,14 +1388,14 @@ describe('dbAuth', () => { await dbAuth.init() await expect(dbAuth.resetPassword()).rejects.toThrow( - dbAuthError.ReusedPasswordError + dbAuthError.ReusedPasswordError, ) }) it('does not throw if allowReusedPassword is true and new password is same as old', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) await createDbUser({ resetToken: hashToken('1234'), @@ -1416,7 +1416,7 @@ describe('dbAuth', () => { it('updates the users password', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) const user = await createDbUser({ resetToken: hashToken('1234'), @@ -1443,7 +1443,7 @@ describe('dbAuth', () => { it('clears resetToken and resetTokenExpiresAt', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) const user = await createDbUser({ resetToken: hashToken('1234'), @@ -1469,7 +1469,7 @@ describe('dbAuth', () => { it('invokes resetPassword.handler() with the user', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) const user = await createDbUser({ resetToken: hashToken('1234'), @@ -1492,7 +1492,7 @@ describe('dbAuth', () => { it('returns a logout response if handler returns falsy', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) await createDbUser({ resetToken: hashToken('1234'), @@ -1514,7 +1514,7 @@ describe('dbAuth', () => { it('returns a login response if handler returns falsy', async () => { const tokenExpires = new Date() tokenExpires.setSeconds( - tokenExpires.getSeconds() - options.forgotPassword.expires + 1 + tokenExpires.getSeconds() - options.forgotPassword.expires + 1, ) await createDbUser({ resetToken: hashToken('1234'), @@ -1690,7 +1690,7 @@ describe('dbAuth', () => { it('returns the token from the cookie', async () => { const user = await createDbUser() const cookie = encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ) event = { @@ -1717,7 +1717,7 @@ describe('dbAuth', () => { event = { headers: { cookie: encryptToCookie( - JSON.stringify({ id: 9999999999 }) + ';' + 'token' + JSON.stringify({ id: 9999999999 }) + ';' + 'token', ), }, } @@ -1802,7 +1802,7 @@ describe('dbAuth', () => { // create session cookie in event header event.headers.cookie = encryptToCookie( - JSON.stringify({ id: 9999999999 }) + JSON.stringify({ id: 9999999999 }), ) // should read session from graphiQL header, not from cookie @@ -1834,7 +1834,7 @@ describe('dbAuth', () => { await dbAuth._getCurrentUser() } catch (e) { expect(e.message).toEqual( - 'Cannot retrieve user details without being logged in' + 'Cannot retrieve user details without being logged in', ) } }) @@ -1866,7 +1866,7 @@ describe('dbAuth', () => { expect.assertions(1) await expect(dbAuth.webAuthnAuthenticate()).rejects.toThrow( - dbAuthError.WebAuthnError + dbAuthError.WebAuthnError, ) }) @@ -1880,7 +1880,7 @@ describe('dbAuth', () => { expect.assertions(1) await expect(dbAuth.webAuthnAuthenticate()).rejects.toThrow( - 'Credentials not found' + 'Credentials not found', ) }) @@ -1905,7 +1905,7 @@ describe('dbAuth', () => { expect.assertions(1) await expect(dbAuth.webAuthnAuthenticate()).rejects.toThrow( - 'Unexpected authentication response challenge' + 'Unexpected authentication response challenge', ) }) @@ -1969,7 +1969,7 @@ describe('dbAuth', () => { expect(body).toEqual(false) expect(headers['set-cookie'][0]).toMatch( - 'webAuthn=CxMJqILwYufSaEQsJX6rKHw_LkMXAGU64PaKU55l6ejZ4FNO5kBLiA' + 'webAuthn=CxMJqILwYufSaEQsJX6rKHw_LkMXAGU64PaKU55l6ejZ4FNO5kBLiA', ) }) }) @@ -2011,7 +2011,7 @@ describe('dbAuth', () => { event = { headers: { cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), }, } @@ -2039,7 +2039,7 @@ describe('dbAuth', () => { event = { headers: { cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), }, } @@ -2096,7 +2096,7 @@ describe('dbAuth', () => { event = { headers: { cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), }, } @@ -2107,7 +2107,7 @@ describe('dbAuth', () => { expect(regOptions.attestation).toEqual('none') expect(regOptions.authenticatorSelection.authenticatorAttachment).toEqual( - options.webAuthn.type + options.webAuthn.type, ) expect(regOptions.excludeCredentials).toEqual([]) expect(regOptions.rp.name).toEqual(options.webAuthn.name) @@ -2123,7 +2123,7 @@ describe('dbAuth', () => { event = { headers: { cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), }, } @@ -2140,7 +2140,7 @@ describe('dbAuth', () => { event = { headers: { cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), }, } @@ -2162,7 +2162,7 @@ describe('dbAuth', () => { headers: { 'Content-Type': 'application/json', cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), }, body: '{"method":"webAuthnRegister","id":"GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg","rawId":"GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg","response":{"attestationObject":"o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVisSZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NFAAAAAK3OAAI1vMYKZIsLJfHwVQMAKBqo2TrmGKaTmwQ3lZJ263AS5GmvYpkuRCScLQle-NGrFM9uLHQJhhalAQIDJiABIVggGIipTQt-gcoDPOpW6Zje_Av9C0-jWb2R2PBmXJJL-c8iWCC76wxo3uzG8cPqb0A8Vij-dqMbrEytEHjuFOtiQ2dt8A","clientDataJSON":"eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiSHVHUHJRcUs3ZjUzTkx3TVpNc3RfREw5RGlnMkJCaXZEWVdXcGF3SVBWTSIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODkxMCIsImNyb3NzT3JpZ2luIjpmYWxzZSwib3RoZXJfa2V5c19jYW5fYmVfYWRkZWRfaGVyZSI6ImRvIG5vdCBjb21wYXJlIGNsaWVudERhdGFKU09OIGFnYWluc3QgYSB0ZW1wbGF0ZS4gU2VlIGh0dHBzOi8vZ29vLmdsL3lhYlBleCJ9"},"type":"public-key","clientExtensionResults":{},"transports":["internal"]}', @@ -2177,7 +2177,7 @@ describe('dbAuth', () => { }) expect(credential.id).toEqual( - 'GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg' + 'GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg', ) expect(credential.transports).toEqual('["internal"]') expect(credential.counter).toEqual(0) @@ -2191,12 +2191,12 @@ describe('dbAuth', () => { headers: { 'Content-Type': 'application/json', cookie: encryptToCookie( - JSON.stringify({ id: user.id }) + ';' + 'token' + JSON.stringify({ id: user.id }) + ';' + 'token', ), }, body: Buffer.from( `{"method":"webAuthnRegister","id":"GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg","rawId":"GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg","response":{"attestationObject":"o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVisSZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NFAAAAAK3OAAI1vMYKZIsLJfHwVQMAKBqo2TrmGKaTmwQ3lZJ263AS5GmvYpkuRCScLQle-NGrFM9uLHQJhhalAQIDJiABIVggGIipTQt-gcoDPOpW6Zje_Av9C0-jWb2R2PBmXJJL-c8iWCC76wxo3uzG8cPqb0A8Vij-dqMbrEytEHjuFOtiQ2dt8A","clientDataJSON":"eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiSHVHUHJRcUs3ZjUzTkx3TVpNc3RfREw5RGlnMkJCaXZEWVdXcGF3SVBWTSIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODkxMCIsImNyb3NzT3JpZ2luIjpmYWxzZSwib3RoZXJfa2V5c19jYW5fYmVfYWRkZWRfaGVyZSI6ImRvIG5vdCBjb21wYXJlIGNsaWVudERhdGFKU09OIGFnYWluc3QgYSB0ZW1wbGF0ZS4gU2VlIGh0dHBzOi8vZ29vLmdsL3lhYlBleCJ9"},"type":"public-key","clientExtensionResults":{},"transports":["internal"]}`, - 'utf8' + 'utf8', ), } const dbAuth = new DbAuthHandler(event, context, options) @@ -2209,7 +2209,7 @@ describe('dbAuth', () => { }) expect(credential.id).toEqual( - 'GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg' + 'GqjZOuYYppObBDeVknbrcBLkaa9imS5EJJwtCV740asUz24sdAmGFg', ) }) }) @@ -2249,7 +2249,7 @@ describe('dbAuth', () => { await dbAuth.init() expect(dbAuth._webAuthnCookie('1234', 'now')).toMatch( - 'webAuthn=1234;Expires=Thu, 01 Jan 1970 00:00:00 GMT' + 'webAuthn=1234;Expires=Thu, 01 Jan 1970 00:00:00 GMT', ) }) }) @@ -2270,7 +2270,7 @@ describe('dbAuth', () => { Domain: 'example.com', }, }, - } + }, ) const attributes = dbAuth._cookieAttributes({}) @@ -2343,7 +2343,7 @@ describe('dbAuth', () => { expect(Object.keys(headers).length).toEqual(1) expect(headers['set-cookie']).toMatch( - `Expires=${dbAuth.sessionExpiresDate}` + `Expires=${dbAuth.sessionExpiresDate}`, ) // can't really match on the session value since it will change on every render, // due to CSRF token generation but we can check that it contains only the @@ -2577,7 +2577,7 @@ describe('dbAuth', () => { // password now hashed by node:crypto expect(user.hashedPassword).toEqual( - 'f20d69d478fa1afc85057384e21bd457a76b23b23e2a94f5bd982976f700a552|16384|8|1' + 'f20d69d478fa1afc85057384e21bd457a76b23b23e2a94f5bd982976f700a552|16384|8|1', ) // salt should remain the same expect(user.salt).toEqual('2ef27f4073c603ba8b7807c6de6d6a89') @@ -2620,7 +2620,7 @@ describe('dbAuth', () => { event = { headers: { cookie: encryptToCookie( - JSON.stringify({ id: dbUser.id }) + ';' + 'token' + JSON.stringify({ id: dbUser.id }) + ';' + 'token', ), }, } @@ -2641,7 +2641,7 @@ describe('dbAuth', () => { event = { headers: { cookie: encryptToCookie( - JSON.stringify({ id: dbUser.id }) + ';' + 'token' + JSON.stringify({ id: dbUser.id }) + ';' + 'token', ), }, } @@ -2659,7 +2659,7 @@ describe('dbAuth', () => { const event = { headers: { cookie: encryptToCookie( - JSON.stringify({ userId: dbUser.userId }) + ';' + 'token' + JSON.stringify({ userId: dbUser.userId }) + ';' + 'token', ), }, } @@ -2710,7 +2710,7 @@ describe('dbAuth', () => { } catch (e) { expect(e).toBeInstanceOf(dbAuthError.DuplicateUsernameError) expect(e.message).toEqual( - defaultMessage.replace(/\$\{username\}/, dbUser.email) + defaultMessage.replace(/\$\{username\}/, dbUser.email), ) } @@ -2779,7 +2779,7 @@ describe('dbAuth', () => { } catch (e) { expect(e).toBeInstanceOf(dbAuthError.DuplicateUsernameError) expect(e.message).toEqual( - defaultMessage.replace(/\$\{username\}/, dbUser.email) + defaultMessage.replace(/\$\{username\}/, dbUser.email), ) } @@ -2805,7 +2805,7 @@ describe('dbAuth', () => { } catch (e) { expect(e).toBeInstanceOf(dbAuthError.FieldRequiredError) expect(e.message).toEqual( - defaultMessage.replace(/\$\{field\}/, 'username') + defaultMessage.replace(/\$\{field\}/, 'username'), ) } @@ -2843,7 +2843,7 @@ describe('dbAuth', () => { } catch (e) { expect(e).toBeInstanceOf(dbAuthError.FieldRequiredError) expect(e.message).toEqual( - defaultMessage.replace(/\$\{field\}/, 'password') + defaultMessage.replace(/\$\{field\}/, 'password'), ) } diff --git a/packages/auth-providers/dbAuth/api/src/__tests__/shared.test.ts b/packages/auth-providers/dbAuth/api/src/__tests__/shared.test.ts index 094a59e83dc3..a58f1aa1740f 100644 --- a/packages/auth-providers/dbAuth/api/src/__tests__/shared.test.ts +++ b/packages/auth-providers/dbAuth/api/src/__tests__/shared.test.ts @@ -20,7 +20,7 @@ import { const FIXTURE_PATH = path.resolve( __dirname, - '../../../../../../__fixtures__/example-todo-main' + '../../../../../../__fixtures__/example-todo-main', ) const SESSION_SECRET = '540d03ebb00b441f8f7442cbc39958ad' @@ -29,7 +29,7 @@ const encrypt = (data) => { const cipher = crypto.createCipheriv( 'aes-256-cbc', SESSION_SECRET.substring(0, 32), - iv + iv, ) let encryptedSession = cipher.update(data, 'utf-8', 'base64') encryptedSession += cipher.final('base64') @@ -64,7 +64,7 @@ describe('getSession()', () => { it('returns the value of the session cookie', () => { expect(getSession('session_8911=qwerty', 'session_%port%')).toEqual( - 'qwerty' + 'qwerty', ) }) @@ -96,15 +96,15 @@ describe('cookieName()', () => { describe('isLegacySession()', () => { it('returns `true` if the session cookie appears to be encrypted with CryptoJS', () => { expect( - isLegacySession('U2FsdGVkX1+s7seQJnVgGgInxuXm13l8VvzA3Mg2fYg=') + isLegacySession('U2FsdGVkX1+s7seQJnVgGgInxuXm13l8VvzA3Mg2fYg='), ).toEqual(true) }) it('returns `false` if the session cookie appears to be encrypted with node:crypto', () => { expect( isLegacySession( - 'ko6iXKV11DSjb6kFJ4iwcf1FEqa5wPpbL1sdtKiV51Y=|cQaYkOPG/r3ILxWiFiz90w==' - ) + 'ko6iXKV11DSjb6kFJ4iwcf1FEqa5wPpbL1sdtKiV51Y=|cQaYkOPG/r3ILxWiFiz90w==', + ), ).toEqual(false) }) }) @@ -125,7 +125,7 @@ describe('decryptSession()', () => { it('throws an error if decryption errors out', () => { expect(() => decryptSession('session=qwerty')).toThrow( - error.SessionDecryptionError + error.SessionDecryptionError, ) }) @@ -141,7 +141,7 @@ describe('decryptSession()', () => { process.env.SESSION_SECRET = 'QKxN2vFSHAf94XYynK8LUALfDuDSdFowG6evfkFX8uszh4YZqhTiqEdshrhWbwbw' const [json] = decryptSession( - 'U2FsdGVkX1+s7seQJnVgGgInxuXm13l8VvzA3Mg2fYg=' + 'U2FsdGVkX1+s7seQJnVgGgInxuXm13l8VvzA3Mg2fYg=', ) expect(json).toEqual({ id: 7 }) @@ -174,7 +174,7 @@ describe('webAuthnSession', () => { it('returns the webAuthn cookie data', () => { const output = webAuthnSession( - dummyEvent('session=abcd1234;webAuthn=zyxw9876') + dummyEvent('session=abcd1234;webAuthn=zyxw9876'), ) expect(output).toEqual('zyxw9876') @@ -188,7 +188,7 @@ describe('hashPassword', () => { }) expect(hash).toEqual( - '230847bea5154b6c7d281d09593ad1be26fa03a93c04a73bcc2b608c073a8213|16384|8|1' + '230847bea5154b6c7d281d09593ad1be26fa03a93c04a73bcc2b608c073a8213|16384|8|1', ) expect(salt).toEqual('ba8b7807c6de6d6a892ef27f4073c603') }) @@ -230,11 +230,11 @@ describe('legacyHashPassword', () => { it('hashes a password with CryptoJS given a salt and returns both', () => { const [hash, salt] = legacyHashPassword( 'password', - '2ef27f4073c603ba8b7807c6de6d6a89' + '2ef27f4073c603ba8b7807c6de6d6a89', ) expect(hash).toEqual( - '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba' + '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba', ) expect(salt).toEqual('2ef27f4073c603ba8b7807c6de6d6a89') }) @@ -266,7 +266,7 @@ describe('session cookie extraction', () => { it('extracts from the event', () => { const cookie = encryptToCookie( - JSON.stringify({ id: 9999999999 }) + ';' + 'token' + JSON.stringify({ id: 9999999999 }) + ';' + 'token', ) event = { @@ -325,7 +325,7 @@ describe('session cookie extraction', () => { const dbUserId = 42 const impersonatedCookie = encryptToCookie( - JSON.stringify({ id: dbUserId }) + JSON.stringify({ id: dbUserId }), ) const req = new Request('http://localhost:8910/_rw_mw', { @@ -342,13 +342,13 @@ describe('session cookie extraction', () => { it('impersonation cookie takes precendence', () => { const sessionCookie = encryptToCookie( - JSON.stringify({ id: 9999999999 }) + ';' + 'token' + JSON.stringify({ id: 9999999999 }) + ';' + 'token', ) const dbUserId = 42 const impersonatedCookie = encryptToCookie( - JSON.stringify({ id: dbUserId }) + JSON.stringify({ id: dbUserId }), ) event = { @@ -370,26 +370,26 @@ describe('extractHashingOptions()', () => { expect(extractHashingOptions('')).toEqual({}) expect( extractHashingOptions( - '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba' - ) + '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba', + ), ).toEqual({}) expect( extractHashingOptions( - '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba|1' - ) + '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba|1', + ), ).toEqual({}) expect( extractHashingOptions( - '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba|1|2' - ) + '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba|1|2', + ), ).toEqual({}) }) it('returns an object with scrypt options', () => { expect( extractHashingOptions( - '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba|16384|8|1' - ) + '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba|16384|8|1', + ), ).toEqual({ cost: 16384, blockSize: 8, diff --git a/packages/auth-providers/dbAuth/api/src/decoder.ts b/packages/auth-providers/dbAuth/api/src/decoder.ts index d479f64025b8..4e1d6780bb2a 100644 --- a/packages/auth-providers/dbAuth/api/src/decoder.ts +++ b/packages/auth-providers/dbAuth/api/src/decoder.ts @@ -21,7 +21,7 @@ export const createAuthDecoder = (cookieNameOption: string): Decoder => { export const authDecoder: Decoder = async ( _authHeaderValue: string, type: string, - req: { event: APIGatewayProxyEvent | Request } + req: { event: APIGatewayProxyEvent | Request }, ) => { if (type !== 'dbAuth') { return null diff --git a/packages/auth-providers/dbAuth/api/src/errors.ts b/packages/auth-providers/dbAuth/api/src/errors.ts index 0d5012465c5d..da972aecf1b6 100644 --- a/packages/auth-providers/dbAuth/api/src/errors.ts +++ b/packages/auth-providers/dbAuth/api/src/errors.ts @@ -1,7 +1,7 @@ export class NoSessionSecretError extends Error { constructor() { super( - 'dbAuth requires a SESSION_SECRET environment variable that is used to encrypt session cookies. Use `yarn rw g secret` to create one, then add to your `.env` file. DO NOT check this variable in your version control system!!' + 'dbAuth requires a SESSION_SECRET environment variable that is used to encrypt session cookies. Use `yarn rw g secret` to create one, then add to your `.env` file. DO NOT check this variable in your version control system!!', ) this.name = 'NoSessionSecretError' } @@ -45,7 +45,7 @@ export class NoResetPasswordHandlerError extends Error { export class NoWebAuthnConfigError extends Error { constructor() { super( - 'To use Webauthn you need both `webauthn` and `credentialModelAccessor` config options, see https://redwoodjs.com/docs/auth/dbAuth#webauthn' + 'To use Webauthn you need both `webauthn` and `credentialModelAccessor` config options, see https://redwoodjs.com/docs/auth/dbAuth#webauthn', ) this.name = 'NoWebAuthnConfigError' } @@ -54,7 +54,7 @@ export class NoWebAuthnConfigError extends Error { export class MissingWebAuthnConfigError extends Error { constructor() { super( - 'You are missing one or more WebAuthn config options, see https://redwoodjs.com/docs/auth/dbAuth#webauthn' + 'You are missing one or more WebAuthn config options, see https://redwoodjs.com/docs/auth/dbAuth#webauthn', ) this.name = 'MissingWebAuthnConfigError' } @@ -84,7 +84,7 @@ export class NotLoggedInError extends Error { export class UserNotFoundError extends Error { constructor( username: string | undefined = undefined, - message: string | undefined = 'Username ${username} not found' + message: string | undefined = 'Username ${username} not found', ) { if (username) { super(message.replace(/\$\{username\}/g, username)) @@ -98,7 +98,7 @@ export class UserNotFoundError extends Error { export class UsernameAndPasswordRequiredError extends Error { constructor( - message: string | undefined = 'Both username and password are required' + message: string | undefined = 'Both username and password are required', ) { super(message) this.name = 'UsernameAndPasswordRequiredError' @@ -108,7 +108,7 @@ export class UsernameAndPasswordRequiredError extends Error { export class NoUserIdError extends Error { constructor() { super( - 'loginHandler() must return an object with an `id` field as set in `authFields.id`' + 'loginHandler() must return an object with an `id` field as set in `authFields.id`', ) this.name = 'NoUserIdError' } @@ -117,7 +117,7 @@ export class NoUserIdError extends Error { export class FieldRequiredError extends Error { constructor( name: string, - message: string | undefined = '${field} is required' + message: string | undefined = '${field} is required', ) { super(message.replace(/\$\{field\}/g, name)) this.name = 'FieldRequiredError' @@ -127,7 +127,7 @@ export class FieldRequiredError extends Error { export class DuplicateUsernameError extends Error { constructor( username: string, - message: string | undefined = 'Username `${username}` already in use' + message: string | undefined = 'Username `${username}` already in use', ) { super(message.replace(/\$\{username\}/g, username)) this.name = 'DuplicateUsernameError' @@ -137,7 +137,7 @@ export class DuplicateUsernameError extends Error { export class IncorrectPasswordError extends Error { constructor( username: string, - message: string | undefined = 'Incorrect password for ${username}' + message: string | undefined = 'Incorrect password for ${username}', ) { super(message.replace(/\$\{username\}/g, username)) this.name = 'IncorrectPasswordError' @@ -237,7 +237,7 @@ export class WebAuthnError extends Error { export class NoWebAuthnSessionError extends WebAuthnError { constructor( - message = 'Log in with username and password to enable WebAuthn' + message = 'Log in with username and password to enable WebAuthn', ) { super(message) this.name = 'NoWebAuthnSessionError' diff --git a/packages/auth-providers/dbAuth/api/src/shared.ts b/packages/auth-providers/dbAuth/api/src/shared.ts index cf2cfef29e03..e2ce9634073b 100644 --- a/packages/auth-providers/dbAuth/api/src/shared.ts +++ b/packages/auth-providers/dbAuth/api/src/shared.ts @@ -42,7 +42,7 @@ const eventGraphiQLHeadersCookie = (event: APIGatewayProxyEvent | Request) => { if (process.env.NODE_ENV === 'development') { const impersationationHeader = getEventHeader( event, - 'rw-studio-impersonation-cookie' + 'rw-studio-impersonation-cookie', ) if (impersationationHeader) { @@ -124,7 +124,7 @@ export const decryptSession = (text: string | null) => { const decipher = crypto.createDecipheriv( 'aes-256-cbc', (process.env.SESSION_SECRET as string).substring(0, 32), - Buffer.from(iv, 'base64') + Buffer.from(iv, 'base64'), ) decoded = decipher.update(encryptedText, 'base64', 'utf-8') + @@ -147,7 +147,7 @@ export const encryptSession = (dataString: string) => { const cipher = crypto.createCipheriv( 'aes-256-cbc', (process.env.SESSION_SECRET as string).substring(0, 32), - iv + iv, ) let encryptedData = cipher.update(dataString, 'utf-8', 'base64') encryptedData += cipher.final('base64') @@ -158,7 +158,7 @@ export const encryptSession = (dataString: string) => { // returns the actual value of the session cookie export const getSession = ( text: string | undefined, - cookieNameOption: string | undefined + cookieNameOption: string | undefined, ) => { if (typeof text === 'undefined' || text === null) { return null @@ -181,14 +181,14 @@ export const getSession = ( // name of the dbAuth session cookie export const dbAuthSession = ( event: APIGatewayProxyEvent | Request, - cookieNameOption: string | undefined + cookieNameOption: string | undefined, ) => { const sessionCookie = extractCookie(event) if (sessionCookie) { // i.e. Browser making a request const [session, _csrfToken] = decryptSession( - getSession(sessionCookie, cookieNameOption) + getSession(sessionCookie, cookieNameOption), ) return session } else { @@ -227,7 +227,7 @@ export const hashPassword = ( { salt = crypto.randomBytes(32).toString('hex'), options = DEFAULT_SCRYPT_OPTIONS, - }: { salt?: string; options?: ScryptOptions } = {} + }: { salt?: string; options?: ScryptOptions } = {}, ) => { const encryptedString = crypto .scryptSync(text.normalize('NFC'), salt, 32, options) diff --git a/packages/auth-providers/dbAuth/setup/src/setup.ts b/packages/auth-providers/dbAuth/setup/src/setup.ts index b43454f10436..c7a971cb8250 100644 --- a/packages/auth-providers/dbAuth/setup/src/setup.ts +++ b/packages/auth-providers/dbAuth/setup/src/setup.ts @@ -21,8 +21,8 @@ export function builder(yargs: yargs.Argv) { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#setup-auth' - )}` + 'https://redwoodjs.com/docs/cli-commands#setup-auth', + )}`, ) } diff --git a/packages/auth-providers/dbAuth/setup/src/setupData.ts b/packages/auth-providers/dbAuth/setup/src/setupData.ts index 82bdf2d88dab..d2cec497d136 100644 --- a/packages/auth-providers/dbAuth/setup/src/setupData.ts +++ b/packages/auth-providers/dbAuth/setup/src/setupData.ts @@ -6,7 +6,7 @@ import { getPaths, colors, addEnvVarTask } from '@redwoodjs/cli-helpers' export const libPath = getPaths().api.lib.replace(getPaths().base, '') export const functionsPath = getPaths().api.functions.replace( getPaths().base, - '' + '', ) const secret = crypto.randomBytes(32).toString('base64') @@ -14,7 +14,7 @@ const secret = crypto.randomBytes(32).toString('base64') export const extraTask = addEnvVarTask( 'SESSION_SECRET', secret, - 'Used to encrypt/decrypt session cookies. Change this value and re-deploy to log out all users of your app at once.' + 'Used to encrypt/decrypt session cookies. Change this value and re-deploy to log out all users of your app at once.', ) // any notes to print out when the job is done diff --git a/packages/auth-providers/dbAuth/setup/src/setupHandler.ts b/packages/auth-providers/dbAuth/setup/src/setupHandler.ts index 813cb23f83bd..d2cb6143f727 100644 --- a/packages/auth-providers/dbAuth/setup/src/setupHandler.ts +++ b/packages/auth-providers/dbAuth/setup/src/setupHandler.ts @@ -15,7 +15,7 @@ import { } from './webAuthn.setupData' const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8'), ) export async function handler({ webauthn, force: forceArg }: Args) { @@ -77,12 +77,12 @@ export const createAuthDecoderFunction = { const newContent = content .replace( 'import { getCurrentUser } from', - 'import { cookieName, getCurrentUser } from' + 'import { cookieName, getCurrentUser } from', ) .replace( 'export const handler = createGraphQLHandler({', 'const authDecoder = createAuthDecoder(cookieName)\n\n' + - 'export const handler = createGraphQLHandler({' + 'export const handler = createGraphQLHandler({', ) if (!newContent.includes('import { cookieName')) { diff --git a/packages/auth-providers/dbAuth/web/src/__tests__/dbAuth.test.ts b/packages/auth-providers/dbAuth/web/src/__tests__/dbAuth.test.ts index f6aa2f01b350..9f21253de96c 100644 --- a/packages/auth-providers/dbAuth/web/src/__tests__/dbAuth.test.ts +++ b/packages/auth-providers/dbAuth/web/src/__tests__/dbAuth.test.ts @@ -82,7 +82,7 @@ beforeEach(() => { const defaultArgs: DbAuthClientArgs & { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean } = { fetchConfig: { credentials: 'include' }, @@ -117,7 +117,7 @@ describe('dbAuth', () => { `${globalThis.RWJS_API_URL}/auth?method=getToken`, { credentials: 'same-origin', - } + }, ) }) @@ -130,7 +130,7 @@ describe('dbAuth', () => { `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', - }) + }), ) }) @@ -147,7 +147,7 @@ describe('dbAuth', () => { `${globalThis.RWJS_API_URL}/auth?method=getToken`, { credentials: 'include', - } + }, ) }) @@ -156,21 +156,21 @@ describe('dbAuth', () => { await act( async () => - await auth.logIn({ username: 'username', password: 'password' }) + await auth.logIn({ username: 'username', password: 'password' }), ) expect(globalThis.fetch).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', - }) + }), ) expect(globalThis.fetch).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', - }) + }), ) }) @@ -184,7 +184,7 @@ describe('dbAuth', () => { `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', - }) + }), ) }) @@ -195,14 +195,14 @@ describe('dbAuth', () => { await auth.resetPassword({ resetToken: 'reset-token', password: 'password', - }) + }), ) expect(globalThis.fetch).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', - }) + }), ) }) @@ -213,14 +213,14 @@ describe('dbAuth', () => { await auth.signUp({ username: 'username', password: 'password', - }) + }), ) expect(globalThis.fetch).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', - }) + }), ) }) @@ -232,7 +232,7 @@ describe('dbAuth', () => { `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', - }) + }), ) }) @@ -245,7 +245,7 @@ describe('dbAuth', () => { '/.redwood/functions/dbauth', expect.objectContaining({ credentials: 'same-origin', - }) + }), ) }) diff --git a/packages/auth-providers/dbAuth/web/src/__tests__/webAuthn.test.ts b/packages/auth-providers/dbAuth/web/src/__tests__/webAuthn.test.ts index e5d09ecafdd7..51cab7624afd 100644 --- a/packages/auth-providers/dbAuth/web/src/__tests__/webAuthn.test.ts +++ b/packages/auth-providers/dbAuth/web/src/__tests__/webAuthn.test.ts @@ -82,15 +82,15 @@ describe('webAuthn', () => { expect(mockOpen).toBeCalledWith( 'GET', `${globalThis.RWJS_API_URL}/auth?method=webAuthnAuthOptions`, - false + false, ) expect(mockOpen).toBeCalledWith( 'POST', `${globalThis.RWJS_API_URL}/auth`, - false + false, ) expect(mockSend).toBeCalledWith( - expect.stringMatching(/"method":"webAuthnAuthenticate"/) + expect.stringMatching(/"method":"webAuthnAuthenticate"/), ) expect(mockOpen).toHaveBeenCalledTimes(2) }) @@ -103,15 +103,15 @@ describe('webAuthn', () => { expect(mockOpen).toBeCalledWith( 'GET', '/.redwood/functions/webauthn?method=webAuthnAuthOptions', - false + false, ) expect(mockOpen).toBeCalledWith( 'POST', '/.redwood/functions/webauthn', - false + false, ) expect(mockSend).toBeCalledWith( - expect.stringMatching(/"method":"webAuthnAuthenticate"/) + expect.stringMatching(/"method":"webAuthnAuthenticate"/), ) expect(mockOpen).toHaveBeenCalledTimes(2) }) @@ -123,15 +123,15 @@ describe('webAuthn', () => { expect(mockOpen).toBeCalledWith( 'GET', `${globalThis.RWJS_API_URL}/auth?method=webAuthnRegOptions`, - false + false, ) expect(mockOpen).toBeCalledWith( 'POST', `${globalThis.RWJS_API_URL}/auth`, - false + false, ) expect(mockSend).toBeCalledWith( - expect.stringMatching(/"method":"webAuthnRegister"/) + expect.stringMatching(/"method":"webAuthnRegister"/), ) expect(mockOpen).toHaveBeenCalledTimes(2) }) @@ -144,15 +144,15 @@ describe('webAuthn', () => { expect(mockOpen).toBeCalledWith( 'GET', '/.redwood/functions/webauthn?method=webAuthnRegOptions', - false + false, ) expect(mockOpen).toBeCalledWith( 'POST', '/.redwood/functions/webauthn', - false + false, ) expect(mockSend).toBeCalledWith( - expect.stringMatching(/"method":"webAuthnRegister"/) + expect.stringMatching(/"method":"webAuthnRegister"/), ) expect(mockOpen).toHaveBeenCalledTimes(2) }) diff --git a/packages/auth-providers/dbAuth/web/src/dbAuth.ts b/packages/auth-providers/dbAuth/web/src/dbAuth.ts index 4f53ebdd026f..510f2930c1de 100644 --- a/packages/auth-providers/dbAuth/web/src/dbAuth.ts +++ b/packages/auth-providers/dbAuth/web/src/dbAuth.ts @@ -22,9 +22,9 @@ export function createAuth( customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean - } + }, ) { return createAuthentication(dbAuthClient, customProviderHooks) } diff --git a/packages/auth-providers/dbAuth/web/src/webAuthn.ts b/packages/auth-providers/dbAuth/web/src/webAuthn.ts index 259c5a67b67f..5c4d3606b94e 100644 --- a/packages/auth-providers/dbAuth/web/src/webAuthn.ts +++ b/packages/auth-providers/dbAuth/web/src/webAuthn.ts @@ -35,7 +35,7 @@ class WebAuthnDeviceNotFoundError extends WebAuthnAuthenticationError { class WebAuthnNoAuthenticatorError extends WebAuthnAuthenticationError { constructor() { super( - "This device was not recognized. Use username/password login, or if you're using iOS you can try reloading this page" + "This device was not recognized. Use username/password login, or if you're using iOS you can try reloading this page", ) this.name = 'WebAuthnNoAuthenticatorError' } @@ -71,7 +71,7 @@ export default class WebAuthnClient { xhr.open( 'GET', `${this.getAuthApiUrl()}?method=webAuthnAuthOptions`, - false + false, ) xhr.setRequestHeader('content-type', 'application/json') xhr.send(null) @@ -83,14 +83,14 @@ export default class WebAuthnClient { throw new WebAuthnDeviceNotFoundError() } else { throw new WebAuthnAuthenticationError( - `Could not start authentication: ${options.error}` + `Could not start authentication: ${options.error}`, ) } } } catch (e: any) { console.error(e.message) throw new WebAuthnAuthenticationError( - `Could not start authentication: ${e.message}` + `Could not start authentication: ${e.message}`, ) } @@ -111,26 +111,26 @@ export default class WebAuthnClient { JSON.stringify({ method: 'webAuthnAuthenticate', ...browserResponse, - }) + }), ) const options = JSON.parse(xhr.responseText) if (xhr.status !== 200) { throw new WebAuthnAuthenticationError( - `Could not complete authentication: ${options.error}` + `Could not complete authentication: ${options.error}`, ) } } catch (e: any) { if ( e.message.match( - /No available authenticator recognized any of the allowed credentials/ + /No available authenticator recognized any of the allowed credentials/, ) ) { throw new WebAuthnNoAuthenticatorError() } else { throw new WebAuthnAuthenticationError( - `Error while authenticating: ${e.message}` + `Error while authenticating: ${e.message}`, ) } } @@ -147,7 +147,7 @@ export default class WebAuthnClient { xhr.open( 'GET', `${this.getAuthApiUrl()}?method=webAuthnRegOptions`, - false + false, ) xhr.setRequestHeader('content-type', 'application/json') xhr.send(null) @@ -156,13 +156,13 @@ export default class WebAuthnClient { if (xhr.status !== 200) { throw new WebAuthnRegistrationError( - `Could not start registration: ${options.error}` + `Could not start registration: ${options.error}`, ) } } catch (e: any) { console.error(e) throw new WebAuthnRegistrationError( - `Could not start registration: ${e.message}` + `Could not start registration: ${e.message}`, ) } @@ -180,7 +180,7 @@ export default class WebAuthnClient { throw new WebAuthnAlreadyRegisteredError() } else { throw new WebAuthnRegistrationError( - `Error while registering: ${e.message}` + `Error while registering: ${e.message}`, ) } } @@ -196,12 +196,12 @@ export default class WebAuthnClient { if (xhr.status !== 200) { throw new WebAuthnRegistrationError( - `Could not complete registration: ${options.error}` + `Could not complete registration: ${options.error}`, ) } } catch (e: any) { throw new WebAuthnRegistrationError( - `Error while registering: ${e.message}` + `Error while registering: ${e.message}`, ) } diff --git a/packages/auth-providers/firebase/setup/src/setupHandler.ts b/packages/auth-providers/firebase/setup/src/setupHandler.ts index 83ab3d7a31ac..a048a54751e7 100644 --- a/packages/auth-providers/firebase/setup/src/setupHandler.ts +++ b/packages/auth-providers/firebase/setup/src/setupHandler.ts @@ -6,7 +6,7 @@ import { standardAuthHandler } from '@redwoodjs/cli-helpers' import type { Args } from './setup' const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8'), ) export async function handler({ force: forceArg }: Args) { diff --git a/packages/auth-providers/firebase/web/src/__tests__/firebase.test.tsx b/packages/auth-providers/firebase/web/src/__tests__/firebase.test.tsx index b1e9d4ed0a9a..e3c2612cffa0 100644 --- a/packages/auth-providers/firebase/web/src/__tests__/firebase.test.tsx +++ b/packages/auth-providers/firebase/web/src/__tests__/firebase.test.tsx @@ -97,7 +97,7 @@ const firebaseAuth: Partial = { signInWithEmailAndPassword: async ( _auth: Auth, email: string, - _password: string + _password: string, ) => { if (email.startsWith('admin')) { loggedInUser = adminUser @@ -147,12 +147,12 @@ beforeEach(() => { function getFirebaseAuth(customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( firebaseMockClient as FirebaseClient, - customProviderHooks + customProviderHooks, ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, diff --git a/packages/auth-providers/firebase/web/src/firebase.ts b/packages/auth-providers/firebase/web/src/firebase.ts index 9081c523a9d5..065d9bdc8ffd 100644 --- a/packages/auth-providers/firebase/web/src/firebase.ts +++ b/packages/auth-providers/firebase/web/src/firebase.ts @@ -49,7 +49,7 @@ interface EmailLinkOptions { } const hasPasswordCredentials = ( - options: Options + options: Options, ): options is PasswordOptions => { return options.email !== undefined && options.password !== undefined } @@ -64,7 +64,7 @@ const isEmailLinkOptions = (options: Options): options is EmailLinkOptions => { const applyProviderOptions = ( provider: OAuthProvider, - options: Options + options: Options, ): OAuthProvider => { if (options.customParameters) { provider.setCustomParameters(options.customParameters) @@ -80,9 +80,9 @@ export function createAuth( customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean - } + }, ) { const authImplementation = createAuthImplementation(firebaseClient) @@ -128,7 +128,7 @@ function createAuthImplementation({ }) }, login: async ( - options: oAuthProvider | Options = { providerId: 'google.com' } + options: oAuthProvider | Options = { providerId: 'google.com' }, ) => { // If argument provided is a string, it should be the oAuth Provider // Cast the provider string into the options object @@ -140,7 +140,7 @@ function createAuthImplementation({ return firebaseAuth.signInWithEmailAndPassword( auth, options.email, - options.password + options.password, ) } @@ -163,7 +163,7 @@ function createAuthImplementation({ }, logout: () => auth.signOut(), signup: async ( - options: oAuthProvider | Options = { providerId: 'google.com' } + options: oAuthProvider | Options = { providerId: 'google.com' }, ) => { if (typeof options === 'string') { options = { providerId: options } @@ -173,7 +173,7 @@ function createAuthImplementation({ return firebaseAuth.createUserWithEmailAndPassword( auth, options.email, - options.password + options.password, ) } diff --git a/packages/auth-providers/netlify/api/src/__tests__/netlify.test.ts b/packages/auth-providers/netlify/api/src/__tests__/netlify.test.ts index 1e769d53a6ad..cfa76587b60b 100644 --- a/packages/auth-providers/netlify/api/src/__tests__/netlify.test.ts +++ b/packages/auth-providers/netlify/api/src/__tests__/netlify.test.ts @@ -80,6 +80,6 @@ test('throws on expired token', async () => { authDecoder('expired-token', 'netlify', { ...req.event, context: { clientContext: { user: { sub: 'abc123' } } }, - } as any) + } as any), ).rejects.toThrow('jwt expired') }) diff --git a/packages/auth-providers/netlify/api/src/decoder.ts b/packages/auth-providers/netlify/api/src/decoder.ts index 58dbf4d21226..73d3cf8ee006 100644 --- a/packages/auth-providers/netlify/api/src/decoder.ts +++ b/packages/auth-providers/netlify/api/src/decoder.ts @@ -18,7 +18,7 @@ interface NetlifyTokenPayload extends Record { export const authDecoder: Decoder = async ( token: string, type: string, - req: { context: LambdaContext } + req: { context: LambdaContext }, ) => { if (type !== 'netlify') { return null @@ -41,7 +41,7 @@ export const authDecoder: Decoder = async ( if (nowTimestamp >= decodedToken.exp) { throw new TokenExpiredError( 'jwt expired', - new Date(decodedToken.exp * 1000) + new Date(decodedToken.exp * 1000), ) } diff --git a/packages/auth-providers/netlify/setup/src/setupHandler.ts b/packages/auth-providers/netlify/setup/src/setupHandler.ts index b857fd093cd2..bc2adbd09d16 100644 --- a/packages/auth-providers/netlify/setup/src/setupHandler.ts +++ b/packages/auth-providers/netlify/setup/src/setupHandler.ts @@ -6,7 +6,7 @@ import { standardAuthHandler } from '@redwoodjs/cli-helpers' import type { Args } from './setup' const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8'), ) export async function handler({ force: forceArg }: Args) { diff --git a/packages/auth-providers/netlify/web/src/__tests__/netlify.test.tsx b/packages/auth-providers/netlify/web/src/__tests__/netlify.test.tsx index f8b692d5f761..8852faebf8ea 100644 --- a/packages/auth-providers/netlify/web/src/__tests__/netlify.test.tsx +++ b/packages/auth-providers/netlify/web/src/__tests__/netlify.test.tsx @@ -96,12 +96,12 @@ beforeEach(() => { function getNetlifyAuth(customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( netlifyIdentityMockClient as NetlifyIdentity, - customProviderHooks + customProviderHooks, ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, diff --git a/packages/auth-providers/netlify/web/src/netlify.ts b/packages/auth-providers/netlify/web/src/netlify.ts index 580b758e5334..e487f19e8d4b 100644 --- a/packages/auth-providers/netlify/web/src/netlify.ts +++ b/packages/auth-providers/netlify/web/src/netlify.ts @@ -16,9 +16,9 @@ export function createAuth( customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean - } + }, ) { const authImplementation = createAuthImplementation(netlifyIdentity) diff --git a/packages/auth-providers/supabase/api/src/__tests__/supabase.test.ts b/packages/auth-providers/supabase/api/src/__tests__/supabase.test.ts index dc15eef8dc05..31e522f823df 100644 --- a/packages/auth-providers/supabase/api/src/__tests__/supabase.test.ts +++ b/packages/auth-providers/supabase/api/src/__tests__/supabase.test.ts @@ -43,7 +43,7 @@ test('throws if SUPABASE_JWT_SECRET env var is not set', async () => { delete process.env.SUPABASE_JWT_SECRET await expect(authDecoder('token', 'supabase', req)).rejects.toThrow( - 'SUPABASE_JWT_SECRET env var is not set' + 'SUPABASE_JWT_SECRET env var is not set', ) }) diff --git a/packages/auth-providers/supabase/setup/src/setupHandler.ts b/packages/auth-providers/supabase/setup/src/setupHandler.ts index 4a7b1d1396a6..e6bb8002ca46 100644 --- a/packages/auth-providers/supabase/setup/src/setupHandler.ts +++ b/packages/auth-providers/supabase/setup/src/setupHandler.ts @@ -6,7 +6,7 @@ import { standardAuthHandler } from '@redwoodjs/cli-helpers' import type { Args } from './setup' const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8'), ) export const handler = async ({ force: forceArg }: Args) => { diff --git a/packages/auth-providers/supabase/web/src/__tests__/supabase.test.tsx b/packages/auth-providers/supabase/web/src/__tests__/supabase.test.tsx index 096e3692307d..0c4c158e73e2 100644 --- a/packages/auth-providers/supabase/web/src/__tests__/supabase.test.tsx +++ b/packages/auth-providers/supabase/web/src/__tests__/supabase.test.tsx @@ -66,7 +66,7 @@ let loggedInUser: User | undefined const mockSupabaseAuthClient: Partial = { signInWithPassword: async ( - credentials: SignInWithPasswordCredentials + credentials: SignInWithPasswordCredentials, ): Promise => { const { email } = credentials as { email: string } @@ -83,7 +83,7 @@ const mockSupabaseAuthClient: Partial = { } }, signInWithOAuth: async ( - credentials: SignInWithOAuthCredentials + credentials: SignInWithOAuthCredentials, ): Promise => { loggedInUser = oAuthUser @@ -96,7 +96,7 @@ const mockSupabaseAuthClient: Partial = { } }, signInWithOtp: async ( - credentials: SignInWithPasswordlessCredentials + credentials: SignInWithPasswordlessCredentials, ): Promise => { loggedInUser = user loggedInUser.email = credentials['email'] @@ -111,7 +111,7 @@ const mockSupabaseAuthClient: Partial = { }, signInWithIdToken: async ( - credentials: SignInWithIdTokenCredentials + credentials: SignInWithIdTokenCredentials, ): Promise => { loggedInUser = user @@ -158,7 +158,7 @@ const mockSupabaseAuthClient: Partial = { return { error: null } }, signUp: async ( - credentials: SignUpWithPasswordCredentials + credentials: SignUpWithPasswordCredentials, ): Promise => { const { email } = credentials as { email: string @@ -290,12 +290,12 @@ beforeEach(() => { function getSupabaseAuth(customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( supabaseMockClient as SupabaseClient, - customProviderHooks + customProviderHooks, ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, diff --git a/packages/auth-providers/supabase/web/src/supabase.ts b/packages/auth-providers/supabase/web/src/supabase.ts index 8d4406124b06..6c5ddf057467 100644 --- a/packages/auth-providers/supabase/web/src/supabase.ts +++ b/packages/auth-providers/supabase/web/src/supabase.ts @@ -41,9 +41,9 @@ export function createAuth( customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean - } + }, ) { const authImplementation = createAuthImplementation(supabaseClient) @@ -63,7 +63,7 @@ function createAuthImplementation(supabaseClient: SupabaseClient) { | SignInWithOAuthOptions | SignInWithIdTokenOptions | SignInWithPasswordlessOptions - | SignInWithSSOOptions + | SignInWithSSOOptions, ): Promise => { /** * Log in an existing user with an email and password or phone and password. @@ -163,7 +163,7 @@ function createAuthImplementation(supabaseClient: SupabaseClient) { * @returns A user if the server has "autoconfirm" OFF */ signup: async ( - credentials: SignUpWithPasswordCredentials + credentials: SignUpWithPasswordCredentials, ): Promise => { return await supabaseClient.auth.signUp(credentials) }, @@ -208,7 +208,7 @@ function createAuthImplementation(supabaseClient: SupabaseClient) { window.history.replaceState( {}, document.title, - window.location.pathname + window.location.pathname, ) } catch (error) { console.error(error) diff --git a/packages/auth-providers/supertokens/api/src/__tests__/supertokens.test.ts b/packages/auth-providers/supertokens/api/src/__tests__/supertokens.test.ts index d30873686b08..ae68a9c3f71b 100644 --- a/packages/auth-providers/supertokens/api/src/__tests__/supertokens.test.ts +++ b/packages/auth-providers/supertokens/api/src/__tests__/supertokens.test.ts @@ -39,7 +39,7 @@ test('throws if SUPERTOKENS_JWKS_URL env var is not set', async () => { delete process.env.SUPERTOKENS_JWKS_URL await expect(authDecoder('token', 'supertokens', req)).rejects.toThrow( - 'SUPERTOKENS_JWKS_URL env var is not set' + 'SUPERTOKENS_JWKS_URL env var is not set', ) }) diff --git a/packages/auth-providers/supertokens/api/src/decoder.ts b/packages/auth-providers/supertokens/api/src/decoder.ts index 400f81b9f7bb..a04ec719ff42 100644 --- a/packages/auth-providers/supertokens/api/src/decoder.ts +++ b/packages/auth-providers/supertokens/api/src/decoder.ts @@ -26,7 +26,7 @@ export const authDecoder: Decoder = async (token: string, type: string) => { function (err: Error | null, key?: SigningKey) { const signingKey = key?.getPublicKey() callback(err, signingKey) - } + }, ) } diff --git a/packages/auth-providers/supertokens/setup/src/setupHandler.ts b/packages/auth-providers/supertokens/setup/src/setupHandler.ts index d58fd648b8d6..a8058cc48b67 100644 --- a/packages/auth-providers/supertokens/setup/src/setupHandler.ts +++ b/packages/auth-providers/supertokens/setup/src/setupHandler.ts @@ -7,7 +7,7 @@ import type { Args } from './setup' export async function handler({ force: forceArg }: Args) { const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8'), ) standardAuthHandler({ @@ -62,7 +62,7 @@ export const addRoutingLogic = { line.includes('@redwoodjs') ) { acc.push( - "import { canHandleRoute, getRoutingComponent } from 'supertokens-auth-react/ui'" + "import { canHandleRoute, getRoutingComponent } from 'supertokens-auth-react/ui'", ) acc.push('') @@ -76,7 +76,7 @@ export const addRoutingLogic = { .join('\n') content = content.replace( "import { useAuth } from './auth'", - "import { useAuth, PreBuiltUI } from './auth'" + "import { useAuth, PreBuiltUI } from './auth'", ) content = content.replace( @@ -84,7 +84,7 @@ export const addRoutingLogic = { 'const Routes = () => {\n' + ' if (canHandleRoute(PreBuiltUI)) {\n' + ' return getRoutingComponent(PreBuiltUI)\n' + - ' }\n\n' + ' }\n\n', ) fs.writeFileSync(routesPath, content) diff --git a/packages/auth-providers/supertokens/web/src/__tests__/supertokens.test.tsx b/packages/auth-providers/supertokens/web/src/__tests__/supertokens.test.tsx index d20fdb9df410..159328b8c8e7 100644 --- a/packages/auth-providers/supertokens/web/src/__tests__/supertokens.test.tsx +++ b/packages/auth-providers/supertokens/web/src/__tests__/supertokens.test.tsx @@ -80,12 +80,12 @@ beforeEach(() => { function getSuperTokensAuth(customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( superTokensMockClient as SuperTokensAuth, - customProviderHooks + customProviderHooks, ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, diff --git a/packages/auth-providers/supertokens/web/src/supertokens.ts b/packages/auth-providers/supertokens/web/src/supertokens.ts index e20c1e7904ff..8adac4c33438 100644 --- a/packages/auth-providers/supertokens/web/src/supertokens.ts +++ b/packages/auth-providers/supertokens/web/src/supertokens.ts @@ -21,9 +21,9 @@ export function createAuth( customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean - } + }, ) { const authImplementation = createAuthImplementation(superTokens) diff --git a/packages/auth/src/AuthContext.ts b/packages/auth/src/AuthContext.ts index 0cf37e9fd982..6d3a567349df 100644 --- a/packages/auth/src/AuthContext.ts +++ b/packages/auth/src/AuthContext.ts @@ -16,7 +16,7 @@ export interface AuthContextInterface< TResetPasswordOptions, TResetPassword, TValidateResetToken, - TClient + TClient, > { /** Determining your current authentication state */ loading: boolean @@ -93,7 +93,7 @@ export function createAuthContext< TResetPasswordOptions, TResetPassword, TValidateResetToken, - TClient + TClient, >() { return React.createContext< | AuthContextInterface< diff --git a/packages/auth/src/AuthImplementation.ts b/packages/auth/src/AuthImplementation.ts index 94842e6c62ad..0bb3642416e8 100644 --- a/packages/auth/src/AuthImplementation.ts +++ b/packages/auth/src/AuthImplementation.ts @@ -11,7 +11,7 @@ export interface AuthImplementation< TResetPasswordOptions = unknown, TResetPassword = unknown, TValidateResetToken = unknown, - TClient = unknown + TClient = unknown, > { type: string client?: TClient diff --git a/packages/auth/src/AuthProvider/AuthProvider.tsx b/packages/auth/src/AuthProvider/AuthProvider.tsx index 22c16f1fa7fb..1a0b17fe99d8 100644 --- a/packages/auth/src/AuthProvider/AuthProvider.tsx +++ b/packages/auth/src/AuthProvider/AuthProvider.tsx @@ -36,7 +36,7 @@ export function createAuthProvider< TResetPasswordOptions, TResetPassword, TValidateResetToken, - TClient + TClient, >( AuthContext: React.Context< | AuthContextInterface< @@ -73,9 +73,9 @@ export function createAuthProvider< customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean - } + }, ) { const AuthProvider = ({ children, @@ -104,7 +104,7 @@ export function createAuthProvider< authImplementation, setAuthProviderState, getCurrentUser, - skipFetchCurrentUser + skipFetchCurrentUser, ) const hasRole = customProviderHooks?.useHasRole @@ -115,13 +115,13 @@ export function createAuthProvider< authImplementation, setAuthProviderState, getCurrentUser, - skipFetchCurrentUser + skipFetchCurrentUser, ) const logIn = useLogIn( authImplementation, setAuthProviderState, getCurrentUser, - skipFetchCurrentUser + skipFetchCurrentUser, ) const logOut = useLogOut(authImplementation, setAuthProviderState) const forgotPassword = useForgotPassword(authImplementation) diff --git a/packages/auth/src/AuthProvider/ServerAuthProvider.tsx b/packages/auth/src/AuthProvider/ServerAuthProvider.tsx index 162597b21db3..b9ca2e8364a2 100644 --- a/packages/auth/src/AuthProvider/ServerAuthProvider.tsx +++ b/packages/auth/src/AuthProvider/ServerAuthProvider.tsx @@ -30,7 +30,7 @@ const getAuthInitialStateFromServer = () => { * On the client it restores from the initial server state injected in the ServerAuthProvider */ export const ServerAuthContext = React.createContext( - getAuthInitialStateFromServer() + getAuthInitialStateFromServer(), ) /** @@ -49,7 +49,7 @@ export const ServerAuthProvider = ({ // not totally necessary, but it's nice to not have them in the DOM // @MARK: needs discussion! const stringifiedAuthState = `__REDWOOD__SERVER__AUTH_STATE__ = ${JSON.stringify( - sanitizeServerAuthState(value) + sanitizeServerAuthState(value), )};` return ( diff --git a/packages/auth/src/AuthProvider/useCurrentUser.ts b/packages/auth/src/AuthProvider/useCurrentUser.ts index 9a523ed87172..bd385c9bc1cb 100644 --- a/packages/auth/src/AuthProvider/useCurrentUser.ts +++ b/packages/auth/src/AuthProvider/useCurrentUser.ts @@ -29,7 +29,7 @@ export const useCurrentUser = (authImplementation: AuthImplementation) => { return data?.redwood?.currentUser } else { throw new Error( - `Could not fetch current user: ${response.statusText} (${response.status})` + `Could not fetch current user: ${response.statusText} (${response.status})`, ) } }, [authImplementation, getToken]) diff --git a/packages/auth/src/AuthProvider/useForgotPassword.ts b/packages/auth/src/AuthProvider/useForgotPassword.ts index 19102e2acb74..7589648c735f 100644 --- a/packages/auth/src/AuthProvider/useForgotPassword.ts +++ b/packages/auth/src/AuthProvider/useForgotPassword.ts @@ -15,7 +15,7 @@ export const useForgotPassword = < TResetPasswordOptions, TResetPassword, TValidateResetToken, - TClient + TClient, >( authImplementation: AuthImplementation< TUser, @@ -31,7 +31,7 @@ export const useForgotPassword = < TResetPassword, TValidateResetToken, TClient - > + >, ) => { return useCallback( async (username: string) => { @@ -39,10 +39,10 @@ export const useForgotPassword = < return await authImplementation.forgotPassword(username) } else { throw new Error( - `Auth client ${authImplementation.type} does not implement this function` + `Auth client ${authImplementation.type} does not implement this function`, ) } }, - [authImplementation] + [authImplementation], ) } diff --git a/packages/auth/src/AuthProvider/useHasRole.ts b/packages/auth/src/AuthProvider/useHasRole.ts index bda4cbe0e3c3..fd324c40bf1c 100644 --- a/packages/auth/src/AuthProvider/useHasRole.ts +++ b/packages/auth/src/AuthProvider/useHasRole.ts @@ -26,7 +26,7 @@ export const useHasRole = (currentUser: CurrentUser | null) => { } else if (Array.isArray(currentUser.roles)) { // rolesToCheck is a string, currentUser.roles is an array return currentUser.roles?.some( - (allowedRole) => rolesToCheck === allowedRole + (allowedRole) => rolesToCheck === allowedRole, ) } } @@ -35,12 +35,12 @@ export const useHasRole = (currentUser: CurrentUser | null) => { if (Array.isArray(currentUser.roles)) { // rolesToCheck is an array, currentUser.roles is an array return currentUser.roles?.some((allowedRole) => - rolesToCheck.includes(allowedRole) + rolesToCheck.includes(allowedRole), ) } else if (typeof currentUser.roles === 'string') { // rolesToCheck is an array, currentUser.roles is a string return rolesToCheck.some( - (allowedRole) => currentUser?.roles === allowedRole + (allowedRole) => currentUser?.roles === allowedRole, ) } } @@ -48,6 +48,6 @@ export const useHasRole = (currentUser: CurrentUser | null) => { return false }, - [currentUser] + [currentUser], ) } diff --git a/packages/auth/src/AuthProvider/useLogIn.ts b/packages/auth/src/AuthProvider/useLogIn.ts index 5ffbafb84442..9e9515b6b0a0 100644 --- a/packages/auth/src/AuthProvider/useLogIn.ts +++ b/packages/auth/src/AuthProvider/useLogIn.ts @@ -20,7 +20,7 @@ export const useLogIn = < TResetPasswordOptions, TResetPassword, TValidateResetToken, - TClient + TClient, >( authImplementation: AuthImplementation< TUser, @@ -41,13 +41,13 @@ export const useLogIn = < React.SetStateAction> >, getCurrentUser: ReturnType, - skipFetchCurrentUser: boolean | undefined + skipFetchCurrentUser: boolean | undefined, ) => { const reauthenticate = useReauthenticate( authImplementation, setAuthProviderState, getCurrentUser, - skipFetchCurrentUser + skipFetchCurrentUser, ) return useCallback( @@ -58,6 +58,6 @@ export const useLogIn = < return loginResult }, - [authImplementation, reauthenticate, setAuthProviderState] + [authImplementation, reauthenticate, setAuthProviderState], ) } diff --git a/packages/auth/src/AuthProvider/useLogOut.ts b/packages/auth/src/AuthProvider/useLogOut.ts index e11bb41ffa42..a5d0b942db23 100644 --- a/packages/auth/src/AuthProvider/useLogOut.ts +++ b/packages/auth/src/AuthProvider/useLogOut.ts @@ -17,7 +17,7 @@ export const useLogOut = < TResetPasswordOptions, TResetPassword, TValidateResetToken, - TClient + TClient, >( authImplementation: AuthImplementation< TUser, @@ -36,7 +36,7 @@ export const useLogOut = < >, setAuthProviderState: React.Dispatch< React.SetStateAction> - > + >, ) => { return useCallback( async (options?: TLogOutOptions) => { @@ -53,6 +53,6 @@ export const useLogOut = < return logoutOutput }, - [authImplementation, setAuthProviderState] + [authImplementation, setAuthProviderState], ) } diff --git a/packages/auth/src/AuthProvider/useReauthenticate.ts b/packages/auth/src/AuthProvider/useReauthenticate.ts index ffca5fe63384..11de939fa017 100644 --- a/packages/auth/src/AuthProvider/useReauthenticate.ts +++ b/packages/auth/src/AuthProvider/useReauthenticate.ts @@ -20,7 +20,7 @@ export const useReauthenticate = ( React.SetStateAction> >, getCurrentUser: ReturnType, - skipFetchCurrentUser: boolean | undefined + skipFetchCurrentUser: boolean | undefined, ) => { const getToken = useToken(authImplementation) diff --git a/packages/auth/src/AuthProvider/useResetPassword.ts b/packages/auth/src/AuthProvider/useResetPassword.ts index 1c255b5b99d9..9ce8c4587f3c 100644 --- a/packages/auth/src/AuthProvider/useResetPassword.ts +++ b/packages/auth/src/AuthProvider/useResetPassword.ts @@ -15,7 +15,7 @@ export const useResetPassword = < TResetPasswordOptions, TResetPassword, TValidateResetToken, - TClient + TClient, >( authImplementation: AuthImplementation< TUser, @@ -31,7 +31,7 @@ export const useResetPassword = < TResetPassword, TValidateResetToken, TClient - > + >, ) => { return useCallback( async (options?: TResetPasswordOptions) => { @@ -39,10 +39,10 @@ export const useResetPassword = < return await authImplementation.resetPassword(options) } else { throw new Error( - `Auth client ${authImplementation.type} does not implement this function` + `Auth client ${authImplementation.type} does not implement this function`, ) } }, - [authImplementation] + [authImplementation], ) } diff --git a/packages/auth/src/AuthProvider/useSignUp.ts b/packages/auth/src/AuthProvider/useSignUp.ts index e1d729e3a090..596cd8155f05 100644 --- a/packages/auth/src/AuthProvider/useSignUp.ts +++ b/packages/auth/src/AuthProvider/useSignUp.ts @@ -19,7 +19,7 @@ export const useSignUp = < TResetPasswordOptions, TResetPassword, TValidateResetToken, - TClient + TClient, >( authImplementation: AuthImplementation< TUser, @@ -40,13 +40,13 @@ export const useSignUp = < React.SetStateAction> >, getCurrentUser: ReturnType, - skipFetchCurrentUser: boolean | undefined + skipFetchCurrentUser: boolean | undefined, ) => { const reauthenticate = useReauthenticate( authImplementation, setAuthProviderState, getCurrentUser, - skipFetchCurrentUser + skipFetchCurrentUser, ) return useCallback( @@ -55,6 +55,6 @@ export const useSignUp = < await reauthenticate() return signupOutput }, - [authImplementation, reauthenticate] + [authImplementation, reauthenticate], ) } diff --git a/packages/auth/src/AuthProvider/useValidateResetToken.ts b/packages/auth/src/AuthProvider/useValidateResetToken.ts index 85715c6a48a4..f7ea795f3d86 100644 --- a/packages/auth/src/AuthProvider/useValidateResetToken.ts +++ b/packages/auth/src/AuthProvider/useValidateResetToken.ts @@ -15,7 +15,7 @@ export const useValidateResetToken = < TResetPasswordOptions, TResetPassword, TValidateResetToken, - TClient + TClient, >( authImplementation: AuthImplementation< TUser, @@ -31,7 +31,7 @@ export const useValidateResetToken = < TResetPassword, TValidateResetToken, TClient - > + >, ) => { return useCallback( async (resetToken: string | null) => { @@ -39,10 +39,10 @@ export const useValidateResetToken = < return await authImplementation.validateResetToken(resetToken) } else { throw new Error( - `Auth client ${authImplementation.type} does not implement this function` + `Auth client ${authImplementation.type} does not implement this function`, ) } }, - [authImplementation] + [authImplementation], ) } diff --git a/packages/auth/src/__tests__/AuthProvider.test.tsx b/packages/auth/src/__tests__/AuthProvider.test.tsx index ea0e601a3973..bad662ad8235 100644 --- a/packages/auth/src/__tests__/AuthProvider.test.tsx +++ b/packages/auth/src/__tests__/AuthProvider.test.tsx @@ -39,9 +39,9 @@ const server = setupServer( redwood: { currentUser: CURRENT_USER_DATA, }, - }) + }), ) - }) + }), ) const consoleError = console.error @@ -165,7 +165,7 @@ describe('Custom auth provider', () => { render( - + , ) // We're booting up! @@ -189,13 +189,13 @@ describe('Custom auth provider', () => { expect(mockAuthClient.getUserMetadata).toBeCalledTimes(1) expect( screen.getByText( - 'userMetadata: {"sub":"abcdefg|123456","username":"peterp"}' - ) + 'userMetadata: {"sub":"abcdefg|123456","username":"peterp"}', + ), ).toBeInTheDocument() expect( screen.getByText( - 'currentUser: {"name":"Peter Pistorius","email":"nospam@example.net"}' - ) + 'currentUser: {"name":"Peter Pistorius","email":"nospam@example.net"}', + ), ).toBeInTheDocument() expect(screen.getByText('authToken: hunter2')).toBeInTheDocument() @@ -210,7 +210,7 @@ describe('Custom auth provider', () => { render( - + , ) // We're booting up! @@ -248,7 +248,7 @@ describe('Custom auth provider', () => { render( - + , ) // The user is not authenticated @@ -271,8 +271,8 @@ describe('Custom auth provider', () => { // The original current user data is fetched. expect( screen.getByText( - 'currentUser: {"name":"Peter Pistorius","email":"nospam@example.net"}' - ) + 'currentUser: {"name":"Peter Pistorius","email":"nospam@example.net"}', + ), ).toBeInTheDocument() CURRENT_USER_DATA = { ...CURRENT_USER_DATA, name: 'Rambo' } @@ -280,8 +280,8 @@ describe('Custom auth provider', () => { await waitFor(() => screen.getByText( - 'currentUser: {"name":"Rambo","email":"nospam@example.net"}' - ) + 'currentUser: {"name":"Rambo","email":"nospam@example.net"}', + ), ) }) @@ -289,7 +289,7 @@ describe('Custom auth provider', () => { server.use( graphql.query('__REDWOOD__AUTH_GET_CURRENT_USER', (_req, res, ctx) => { return res(ctx.status(404)) - }) + }), ) const mockAuthClient = customTestAuth @@ -303,14 +303,14 @@ describe('Custom auth provider', () => { render( - + , ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() await waitFor(() => - screen.getByText('Could not fetch current user: Not Found (404)') + screen.getByText('Could not fetch current user: Not Found (404)'), ) }) @@ -329,7 +329,7 @@ describe('Custom auth provider', () => { render( - + , ) // We're booting up! @@ -376,7 +376,7 @@ describe('Custom auth provider', () => { render( - + , ) // We're booting up! @@ -423,7 +423,7 @@ describe('Custom auth provider', () => { render( - + , ) // We're booting up! @@ -470,7 +470,7 @@ describe('Custom auth provider', () => { render( - + , ) // We're booting up! @@ -516,7 +516,7 @@ describe('Custom auth provider', () => { render( - + , ) // We're booting up! @@ -559,7 +559,7 @@ describe('Custom auth provider', () => { render( - + , ) // We're booting up! @@ -606,7 +606,7 @@ describe('Custom auth provider', () => { render( - + , ) // We're booting up! @@ -652,7 +652,7 @@ describe('Custom auth provider', () => { render( - + , ) // We're booting up! @@ -706,7 +706,7 @@ describe('Custom auth provider', () => { render( - + , ) await waitFor(() => expect(mockedForgotPassword).toBeCalledWith('username')) diff --git a/packages/auth/src/authFactory.ts b/packages/auth/src/authFactory.ts index 256ce56ae8ef..33c00aa5732d 100644 --- a/packages/auth/src/authFactory.ts +++ b/packages/auth/src/authFactory.ts @@ -17,7 +17,7 @@ export function createAuthentication< TResetPasswordOptions, TResetPassword, TValidateResetToken, - TClient + TClient, >( authImplementation: AuthImplementation< TUser, @@ -37,9 +37,9 @@ export function createAuthentication< customProviderHooks?: { useCurrentUser?: () => Promise useHasRole?: ( - currentUser: CurrentUser | null + currentUser: CurrentUser | null, ) => (rolesToCheck: string | string[]) => boolean - } + }, ) { const AuthContext = createAuthContext< TUser, @@ -59,7 +59,7 @@ export function createAuthentication< const AuthProvider = createAuthProvider( AuthContext, authImplementation, - customProviderHooks + customProviderHooks, ) return { AuthContext, AuthProvider, useAuth } diff --git a/packages/auth/src/useAuth.ts b/packages/auth/src/useAuth.ts index a28ce79c3922..301aa66877b8 100644 --- a/packages/auth/src/useAuth.ts +++ b/packages/auth/src/useAuth.ts @@ -14,7 +14,7 @@ export function createUseAuth< TResetPasswordOptions, TResetPassword, TValidateResetToken, - TClient + TClient, >( AuthContext: React.Context< | AuthContextInterface< @@ -32,7 +32,7 @@ export function createUseAuth< TClient > | undefined - > + >, ) { const useAuth = (): AuthContextInterface< TUser, diff --git a/packages/babel-config/src/__tests__/api.test.ts b/packages/babel-config/src/__tests__/api.test.ts index 7a40e3798481..1a86db2e9703 100644 --- a/packages/babel-config/src/__tests__/api.test.ts +++ b/packages/babel-config/src/__tests__/api.test.ts @@ -84,12 +84,12 @@ describe('api', () => { 'babel.config.js': '', }, }, - redwoodProjectPath + redwoodProjectPath, ) const apiSideBabelConfigPath = getApiSideBabelConfigPath() expect(ensurePosixPath(apiSideBabelConfigPath || '')).toMatch( - '/redwood-app/api/babel.config.js' + '/redwood-app/api/babel.config.js', ) }) @@ -99,7 +99,7 @@ describe('api', () => { 'redwood.toml': '', api: {}, }, - redwoodProjectPath + redwoodProjectPath, ) const apiSideBabelConfigPath = getApiSideBabelConfigPath() @@ -114,7 +114,7 @@ describe('api', () => { 'redwood.toml': '', api: {}, }, - redwoodProjectPath + redwoodProjectPath, ) const apiSideBabelPlugins = getApiSideBabelPlugins() @@ -195,7 +195,7 @@ describe('api', () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const [_, babelPluginModuleResolverConfig] = apiSideBabelPlugins.find( - (plugin) => plugin[0] === 'babel-plugin-module-resolver' + (plugin) => plugin[0] === 'babel-plugin-module-resolver', )! as [any, ModuleResolverConfig, any] expect(babelPluginModuleResolverConfig).toMatchObject({ @@ -208,7 +208,7 @@ describe('api', () => { }) expect(babelPluginModuleResolverConfig.root[0]).toMatch( - getPaths().api.base + getPaths().api.base, ) expect(apiSideBabelPlugins).toContainEqual([ @@ -235,7 +235,7 @@ describe('api', () => { 'redwood.toml': '', api: {}, }, - redwoodProjectPath + redwoodProjectPath, ) const apiSideBabelPlugins = getApiSideBabelPlugins({ diff --git a/packages/babel-config/src/__tests__/prebuildApiFile.test.ts b/packages/babel-config/src/__tests__/prebuildApiFile.test.ts index 24fd5126f0c3..f54ef048d6e6 100644 --- a/packages/babel-config/src/__tests__/prebuildApiFile.test.ts +++ b/packages/babel-config/src/__tests__/prebuildApiFile.test.ts @@ -27,7 +27,7 @@ describe('api prebuild ', () => { describe('Node.js 13', () => { it('polyfills Math.hypot', () => { expect(code).toContain( - `import _Math$hypot from "@babel/runtime-corejs3/core-js/math/hypot"` + `import _Math$hypot from "@babel/runtime-corejs3/core-js/math/hypot"`, ) }) }) @@ -35,7 +35,7 @@ describe('api prebuild ', () => { describe('Node.js 14', () => { it('polyfills String.matchAll', () => { expect(code).toContain( - `import _matchAllInstanceProperty from "@babel/runtime-corejs3/core-js/instance/match-all"` + `import _matchAllInstanceProperty from "@babel/runtime-corejs3/core-js/instance/match-all"`, ) }) }) @@ -43,7 +43,7 @@ describe('api prebuild ', () => { describe('Node.js 15', () => { it('polyfills AggregateError', () => { expect(code).toContain( - `import _AggregateError from "@babel/runtime-corejs3/core-js/aggregate-error"` + `import _AggregateError from "@babel/runtime-corejs3/core-js/aggregate-error"`, ) }) @@ -83,7 +83,7 @@ describe('api prebuild ', () => { // ``` it('polyfills Promise.any', () => { expect(code).toContain( - `import _Promise from "@babel/runtime-corejs3/core-js/promise"` + `import _Promise from "@babel/runtime-corejs3/core-js/promise"`, ) const _Promise = require('@babel/runtime-corejs3/core-js/promise') expect(_Promise).toHaveProperty('any') @@ -91,7 +91,7 @@ describe('api prebuild ', () => { it('polyfills String.replaceAll', () => { expect(code).toContain( - `import _replaceAllInstanceProperty from "@babel/runtime-corejs3/core-js/instance/replace-all"` + `import _replaceAllInstanceProperty from "@babel/runtime-corejs3/core-js/instance/replace-all"`, ) }) }) @@ -104,7 +104,7 @@ describe('api prebuild ', () => { `const buffer = new ArrayBuffer(8);`, `const uint8 = new Uint8Array(buffer);`, `uint8.set([1, 2, 3], 3);`, - ].join('\n') + ].join('\n'), ) }) }) @@ -116,31 +116,31 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#reflect-metadata it('polyfills Reflect methods', () => { expect(code).toContain( - `import _Reflect$defineMetadata from "@babel/runtime-corejs3/core-js/reflect/define-metadata"` + `import _Reflect$defineMetadata from "@babel/runtime-corejs3/core-js/reflect/define-metadata"`, ) expect(code).toContain( - `import _Reflect$deleteMetadata from "@babel/runtime-corejs3/core-js/reflect/delete-metadata"` + `import _Reflect$deleteMetadata from "@babel/runtime-corejs3/core-js/reflect/delete-metadata"`, ) expect(code).toContain( - `import _Reflect$getMetadata from "@babel/runtime-corejs3/core-js/reflect/get-metadata"` + `import _Reflect$getMetadata from "@babel/runtime-corejs3/core-js/reflect/get-metadata"`, ) expect(code).toContain( - `import _Reflect$getMetadataKeys from "@babel/runtime-corejs3/core-js/reflect/get-metadata-keys"` + `import _Reflect$getMetadataKeys from "@babel/runtime-corejs3/core-js/reflect/get-metadata-keys"`, ) expect(code).toContain( - `import _Reflect$getOwnMetadata from "@babel/runtime-corejs3/core-js/reflect/get-own-metadata"` + `import _Reflect$getOwnMetadata from "@babel/runtime-corejs3/core-js/reflect/get-own-metadata"`, ) expect(code).toContain( - `import _Reflect$getOwnMetadataKeys from "@babel/runtime-corejs3/core-js/reflect/get-own-metadata-keys"` + `import _Reflect$getOwnMetadataKeys from "@babel/runtime-corejs3/core-js/reflect/get-own-metadata-keys"`, ) expect(code).toContain( - `import _Reflect$hasMetadata from "@babel/runtime-corejs3/core-js/reflect/has-metadata"` + `import _Reflect$hasMetadata from "@babel/runtime-corejs3/core-js/reflect/has-metadata"`, ) expect(code).toContain( - `import _Reflect$hasOwnMetadata from "@babel/runtime-corejs3/core-js/reflect/has-own-metadata"` + `import _Reflect$hasOwnMetadata from "@babel/runtime-corejs3/core-js/reflect/has-own-metadata"`, ) expect(code).toContain( - `import _Reflect$metadata from "@babel/runtime-corejs3/core-js/reflect/metadata"` + `import _Reflect$metadata from "@babel/runtime-corejs3/core-js/reflect/metadata"`, ) }) }) @@ -161,7 +161,7 @@ describe('api prebuild ', () => { `array.lastItem = 4;`, `new Array(1, 2, 3).lastIndex;`, `new Array(1, 2, 3).lastItem;`, - ].join('\n') + ].join('\n'), ) }) @@ -169,10 +169,10 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#compositekey-and-compositesymbol it('polyfills compositeKey and compositeSymbol', () => { expect(code).toContain( - `import _compositeKey from "@babel/runtime-corejs3/core-js/composite-key"` + `import _compositeKey from "@babel/runtime-corejs3/core-js/composite-key"`, ) expect(code).toContain( - `import _compositeSymbol from "@babel/runtime-corejs3/core-js/composite-symbol"` + `import _compositeSymbol from "@babel/runtime-corejs3/core-js/composite-symbol"`, ) }) @@ -180,7 +180,7 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#new-collections-methods it('polyfills New collections methods', () => { expect(code).toContain( - `import _Map from "@babel/runtime-corejs3/core-js/map"` + `import _Map from "@babel/runtime-corejs3/core-js/map"`, ) // See the comments on Promise.any above for more of an explanation // of why we're testing for properties. @@ -204,7 +204,7 @@ describe('api prebuild ', () => { expect(_Map).toHaveProperty('update') expect(code).toContain( - `import _Set from "@babel/runtime-corejs3/core-js/set"` + `import _Set from "@babel/runtime-corejs3/core-js/set"`, ) const _Set = require('@babel/runtime-corejs3/core-js/set') expect(_Set).toHaveProperty('addAll') @@ -227,7 +227,7 @@ describe('api prebuild ', () => { expect(_Set).toHaveProperty('union') expect(code).toContain( - `import _WeakMap from "@babel/runtime-corejs3/core-js/weak-map"` + `import _WeakMap from "@babel/runtime-corejs3/core-js/weak-map"`, ) const _WeakMap = require('@babel/runtime-corejs3/core-js/weak-map') expect(_WeakMap).toHaveProperty('deleteAll') @@ -235,7 +235,7 @@ describe('api prebuild ', () => { expect(_WeakMap).toHaveProperty('of') expect(code).toContain( - `import _WeakSet from "@babel/runtime-corejs3/core-js/weak-set"` + `import _WeakSet from "@babel/runtime-corejs3/core-js/weak-set"`, ) const _WeakSet = require('@babel/runtime-corejs3/core-js/weak-set') expect(_WeakSet).toHaveProperty('addAll') @@ -248,25 +248,25 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#math-extensions it('polyfills Math extensions', () => { expect(code).toContain( - `import _Math$clamp from "@babel/runtime-corejs3/core-js/math/clamp"` + `import _Math$clamp from "@babel/runtime-corejs3/core-js/math/clamp"`, ) expect(code).toContain( - `import _Math$DEG_PER_RAD from "@babel/runtime-corejs3/core-js/math/deg-per-rad"` + `import _Math$DEG_PER_RAD from "@babel/runtime-corejs3/core-js/math/deg-per-rad"`, ) expect(code).toContain( - `import _Math$degrees from "@babel/runtime-corejs3/core-js/math/degrees"` + `import _Math$degrees from "@babel/runtime-corejs3/core-js/math/degrees"`, ) expect(code).toContain( - `import _Math$fscale from "@babel/runtime-corejs3/core-js/math/fscale"` + `import _Math$fscale from "@babel/runtime-corejs3/core-js/math/fscale"`, ) expect(code).toContain( - `import _Math$RAD_PER_DEG from "@babel/runtime-corejs3/core-js/math/rad-per-deg"` + `import _Math$RAD_PER_DEG from "@babel/runtime-corejs3/core-js/math/rad-per-deg"`, ) expect(code).toContain( - `import _Math$radians from "@babel/runtime-corejs3/core-js/math/radians"` + `import _Math$radians from "@babel/runtime-corejs3/core-js/math/radians"`, ) expect(code).toContain( - `import _Math$scale from "@babel/runtime-corejs3/core-js/math/scale"` + `import _Math$scale from "@babel/runtime-corejs3/core-js/math/scale"`, ) }) @@ -274,7 +274,7 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#mathsignbit it('polyfills Math.signbit', () => { expect(code).toContain( - `import _Math$signbit from "@babel/runtime-corejs3/core-js/math/signbit"` + `import _Math$signbit from "@babel/runtime-corejs3/core-js/math/signbit"`, ) }) @@ -282,7 +282,7 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#numberfromstring it('polyfills Number.fromString', () => { expect(code).toContain( - `import _Number$fromString from "@babel/runtime-corejs3/core-js/number/from-string"` + `import _Number$fromString from "@babel/runtime-corejs3/core-js/number/from-string"`, ) }) @@ -290,10 +290,10 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#observable it('polyfills Observable', () => { expect(code).toContain( - `import _Observable from "@babel/runtime-corejs3/core-js/observable"` + `import _Observable from "@babel/runtime-corejs3/core-js/observable"`, ) expect(code).toContain( - `import _Symbol$observable from "@babel/runtime-corejs3/core-js/symbol/observable"` + `import _Symbol$observable from "@babel/runtime-corejs3/core-js/symbol/observable"`, ) }) @@ -301,7 +301,7 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#stringprototypecodepoints it('polyfills String.prototype.codePoints', () => { expect(code).toContain( - `import _codePointsInstanceProperty from "@babel/runtime-corejs3/core-js/instance/code-points"` + `import _codePointsInstanceProperty from "@babel/runtime-corejs3/core-js/instance/code-points"`, ) }) @@ -310,7 +310,7 @@ describe('api prebuild ', () => { // This one's been renamed to Symbol.matcher since core-js v3.0.0. But Symbol.patternMatch still works it('polyfills Symbol.matcher', () => { expect(code).toContain( - `import _Symbol$patternMatch from "@babel/runtime-corejs3/core-js/symbol/pattern-match"` + `import _Symbol$patternMatch from "@babel/runtime-corejs3/core-js/symbol/pattern-match"`, ) }) }) @@ -320,7 +320,7 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#symbol-asyncdispose-dispose--for-using-statement it('polyfills Symbol.{ asyncDispose, dispose } for using statement', () => { expect(code).toContain( - `import _Symbol$dispose from "@babel/runtime-corejs3/core-js/symbol/dispose"` + `import _Symbol$dispose from "@babel/runtime-corejs3/core-js/symbol/dispose"`, ) }) }) @@ -331,16 +331,16 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#efficient-64-bit-arithmetic it('polyfills efficient 64 bit arithmetic', () => { expect(code).toContain( - `import _Math$iaddh from "@babel/runtime-corejs3/core-js/math/iaddh"` + `import _Math$iaddh from "@babel/runtime-corejs3/core-js/math/iaddh"`, ) expect(code).toContain( - `import _Math$imulh from "@babel/runtime-corejs3/core-js/math/imulh"` + `import _Math$imulh from "@babel/runtime-corejs3/core-js/math/imulh"`, ) expect(code).toContain( - `import _Math$isubh from "@babel/runtime-corejs3/core-js/math/isubh"` + `import _Math$isubh from "@babel/runtime-corejs3/core-js/math/isubh"`, ) expect(code).toContain( - `import _Math$umulh from "@babel/runtime-corejs3/core-js/math/umulh"` + `import _Math$umulh from "@babel/runtime-corejs3/core-js/math/umulh"`, ) }) @@ -355,7 +355,7 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#stringat it('polyfills String#at', () => { expect(code).toContain( - `import _atInstanceProperty from "@babel/runtime-corejs3/core-js/instance/at"` + `import _atInstanceProperty from "@babel/runtime-corejs3/core-js/instance/at"`, ) }) }) @@ -365,7 +365,7 @@ describe('api prebuild ', () => { // See https://github.com/zloirock/core-js#seeded-pseudo-random-numbers it('polyfills Seeded pseudo-random numbers', () => { expect(code).toContain( - `import _Math$seededPRNG from "@babel/runtime-corejs3/core-js/math/seeded-prng"` + `import _Math$seededPRNG from "@babel/runtime-corejs3/core-js/math/seeded-prng"`, ) }) }) @@ -381,7 +381,7 @@ describe('api prebuild ', () => { const [_, base64EncodedFile] = sourceMaps.split(sourceMapsMatcher) const { sources } = JSON.parse( - Buffer.from(base64EncodedFile, 'base64').toString('utf-8') + Buffer.from(base64EncodedFile, 'base64').toString('utf-8'), ) expect(sources).toMatchInlineSnapshot(` @@ -404,22 +404,22 @@ describe('api prebuild ', () => { // Polyfill for Symbol expect(code).toContain( - `import _Symbol from "@babel/runtime-corejs3/core-js/symbol"` + `import _Symbol from "@babel/runtime-corejs3/core-js/symbol"`, ) // Polyfill for Promise expect(code).toContain( - `import _Promise from "@babel/runtime-corejs3/core-js/promise"` + `import _Promise from "@babel/runtime-corejs3/core-js/promise"`, ) // Polyfill for .includes expect(code).toContain( - 'import _includesInstanceProperty from "@babel/runtime-corejs3/core-js/instance/includes"' + 'import _includesInstanceProperty from "@babel/runtime-corejs3/core-js/instance/includes"', ) // Polyfill for .iterator expect(code).toContain( - `import _getIterator from "@babel/runtime-corejs3/core-js/get-iterator"` + `import _getIterator from "@babel/runtime-corejs3/core-js/get-iterator"`, ) }) }) diff --git a/packages/babel-config/src/__tests__/tsconfigParsing.test.ts b/packages/babel-config/src/__tests__/tsconfigParsing.test.ts index 3ca80f58fa43..9747c3d5c8a4 100644 --- a/packages/babel-config/src/__tests__/tsconfigParsing.test.ts +++ b/packages/babel-config/src/__tests__/tsconfigParsing.test.ts @@ -24,7 +24,7 @@ describe('TypeScript config file parsing', () => { api: {}, web: {}, }, - redwoodProjectPath + redwoodProjectPath, ) const typeScriptConfig = parseTypeScriptConfigFiles() @@ -46,7 +46,7 @@ describe('TypeScript config file parsing', () => { 'tsconfig.json': webTSConfig, }, }, - redwoodProjectPath + redwoodProjectPath, ) const typeScriptConfig = parseTypeScriptConfigFiles() @@ -68,7 +68,7 @@ describe('TypeScript config file parsing', () => { 'jsconfig.json': webJSConfig, }, }, - redwoodProjectPath + redwoodProjectPath, ) const typeScriptConfig = parseTypeScriptConfigFiles() @@ -92,7 +92,7 @@ describe('TypeScript config file parsing', () => { 'tsconfig.json': webTSConfig, }, }, - redwoodProjectPath + redwoodProjectPath, ) expect(parseTypeScriptConfigFiles).not.toThrow() @@ -112,20 +112,20 @@ describe('getPathsFromTypeScriptConfig', () => { api: {}, web: {}, }, - redwoodProjectPath + redwoodProjectPath, ) const typeScriptConfig = parseTypeScriptConfigFiles() const apiPaths = getPathsFromTypeScriptConfig( typeScriptConfig.api, - FAKE_API_ROOT + FAKE_API_ROOT, ) expect(apiPaths).toMatchObject({}) const webPaths = getPathsFromTypeScriptConfig( typeScriptConfig.web, - FAKE_WEB_ROOT + FAKE_WEB_ROOT, ) expect(webPaths).toMatchObject({}) }) @@ -144,20 +144,20 @@ describe('getPathsFromTypeScriptConfig', () => { 'tsconfig.json': webTSConfig, }, }, - redwoodProjectPath + redwoodProjectPath, ) const typeScriptConfig = parseTypeScriptConfigFiles() const apiPaths = getPathsFromTypeScriptConfig( typeScriptConfig.api, - FAKE_API_ROOT + FAKE_API_ROOT, ) expect(apiPaths).toMatchInlineSnapshot(`{}`) const webPaths = getPathsFromTypeScriptConfig( typeScriptConfig.web, - FAKE_WEB_ROOT + FAKE_WEB_ROOT, ) expect(webPaths).toMatchInlineSnapshot(`{}`) }) @@ -178,20 +178,20 @@ describe('getPathsFromTypeScriptConfig', () => { 'tsconfig.json': webTSConfig, }, }, - redwoodProjectPath + redwoodProjectPath, ) const typeScriptConfig = parseTypeScriptConfigFiles() const apiPaths = getPathsFromTypeScriptConfig( typeScriptConfig.api, - FAKE_API_ROOT + FAKE_API_ROOT, ) expect(apiPaths).toMatchInlineSnapshot(`{}`) const webPaths = getPathsFromTypeScriptConfig( typeScriptConfig.web, - FAKE_WEB_ROOT + FAKE_WEB_ROOT, ) expect(webPaths).toMatchInlineSnapshot(`{}`) }) @@ -212,26 +212,26 @@ describe('getPathsFromTypeScriptConfig', () => { 'tsconfig.json': webTSConfig, }, }, - redwoodProjectPath + redwoodProjectPath, ) const typeScriptConfig = parseTypeScriptConfigFiles() const apiPaths = getPathsFromTypeScriptConfig( typeScriptConfig.api, - FAKE_API_ROOT + FAKE_API_ROOT, ) expect(ensurePosixPath(apiPaths['@services'])).toEqual( - ensurePosixPath(`${FAKE_API_ROOT}/src/services`) + ensurePosixPath(`${FAKE_API_ROOT}/src/services`), ) const webPaths = getPathsFromTypeScriptConfig( typeScriptConfig.web, - FAKE_WEB_ROOT + FAKE_WEB_ROOT, ) expect(ensurePosixPath(webPaths['@ui'])).toEqual( - ensurePosixPath(`${FAKE_WEB_ROOT}/src/ui`) + ensurePosixPath(`${FAKE_WEB_ROOT}/src/ui`), ) }) }) diff --git a/packages/babel-config/src/api.ts b/packages/babel-config/src/api.ts index 337beede36f1..a210b38d942e 100644 --- a/packages/babel-config/src/api.ts +++ b/packages/babel-config/src/api.ts @@ -20,7 +20,7 @@ import { export const TARGETS_NODE = '20.10' export const getApiSideBabelPresets = ( - { presetEnv } = { presetEnv: false } + { presetEnv } = { presetEnv: false }, ) => { return [ [ @@ -214,7 +214,7 @@ export const registerApiSideBabelHook = ({ export const transformWithBabel = async ( srcPath: string, - plugins: TransformOptions['plugins'] + plugins: TransformOptions['plugins'], ) => { const code = await fs.readFile(srcPath, 'utf-8') const defaultOptions = getApiSideDefaultBabelConfig({ diff --git a/packages/babel-config/src/common.ts b/packages/babel-config/src/common.ts index 5aeb57b5ad49..b55a2d336f14 100644 --- a/packages/babel-config/src/common.ts +++ b/packages/babel-config/src/common.ts @@ -48,7 +48,7 @@ export const CORE_JS_VERSION = pkgJson.dependencies['core-js'] if (!CORE_JS_VERSION) { throw new Error( - 'RedwoodJS Project Babel: Could not determine core-js version.' + 'RedwoodJS Project Babel: Could not determine core-js version.', ) } @@ -57,7 +57,7 @@ export const RUNTIME_CORE_JS_VERSION = if (!RUNTIME_CORE_JS_VERSION) { throw new Error( - 'RedwoodJS Project Babel: Could not determine core-js runtime version' + 'RedwoodJS Project Babel: Could not determine core-js runtime version', ) } @@ -111,7 +111,7 @@ export const parseTypeScriptConfigFiles = () => { } return parseConfigFileTextToJson( configPath, - fs.readFileSync(configPath, 'utf-8') + fs.readFileSync(configPath, 'utf-8'), ) } const apiConfig = parseConfigFile(rwPaths.api.base) @@ -134,7 +134,7 @@ type CompilerOptionsForPaths = { */ export const getPathsFromTypeScriptConfig = ( config: CompilerOptionsForPaths, - rootDir: string + rootDir: string, ): Record => { if (!config) { return {} @@ -164,7 +164,7 @@ export const getPathsFromTypeScriptConfig = ( const aliasKey = key.replace('/*', '') const aliasValue = path.join( absoluteBase, - (value as string)[0].replace('/*', '') + (value as string)[0].replace('/*', ''), ) pathsObj[aliasKey] = aliasValue diff --git a/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-mock-cell-data.test.ts b/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-mock-cell-data.test.ts index 1a63e132f863..b02d6c15e657 100644 --- a/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-mock-cell-data.test.ts +++ b/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-mock-cell-data.test.ts @@ -14,31 +14,31 @@ describe('babel plugin redwood mock cell data', () => { 'cell with afterQuery': { fixture: path.join( __fixtures__, - 'example-todo-main/web/src/components/TodoListCell/TodoListCell.mock.js' + 'example-todo-main/web/src/components/TodoListCell/TodoListCell.mock.js', ), outputFixture: path.join( __dirname, - '__fixtures__/mock-cell-data/output_TodoListCell.mock.js' + '__fixtures__/mock-cell-data/output_TodoListCell.mock.js', ), }, 'cell without afterQuery': { fixture: path.join( __fixtures__, - 'example-todo-main/web/src/components/NumTodosCell/NumTodosCell.mock.js' + 'example-todo-main/web/src/components/NumTodosCell/NumTodosCell.mock.js', ), outputFixture: path.join( __dirname, - '__fixtures__/mock-cell-data/output_NumTodosCell.mock.js' + '__fixtures__/mock-cell-data/output_NumTodosCell.mock.js', ), }, 'exporting a function declaration': { fixture: path.join( __fixtures__, - 'example-todo-main/web/src/components/NumTodosTwoCell/NumTodosTwoCell.mock.js' + 'example-todo-main/web/src/components/NumTodosTwoCell/NumTodosTwoCell.mock.js', ), outputFixture: path.join( __dirname, - '__fixtures__/mock-cell-data/output_NumTodosTwoCell.mock.js' + '__fixtures__/mock-cell-data/output_NumTodosTwoCell.mock.js', ), }, }, diff --git a/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-routes-auto-loader.test.ts b/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-routes-auto-loader.test.ts index be625d841ffc..d4403ba3b7cb 100644 --- a/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-routes-auto-loader.test.ts +++ b/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-routes-auto-loader.test.ts @@ -10,7 +10,7 @@ import type { PluginOptions as RoutesAutoLoaderOptions } from '../babel-plugin-r const transform = ( filename: string, - pluginOptions?: RoutesAutoLoaderOptions + pluginOptions?: RoutesAutoLoaderOptions, ) => { const code = fs.readFileSync(filename, 'utf-8') return babel.transform(code, { @@ -23,7 +23,7 @@ const transform = ( describe('mulitiple files ending in Page.{js,jsx,ts,tsx}', () => { const FAILURE_FIXTURE_PATH = path.resolve( __dirname, - './__fixtures__/route-auto-loader/failure' + './__fixtures__/route-auto-loader/failure', ) beforeAll(() => { @@ -38,7 +38,7 @@ describe('mulitiple files ending in Page.{js,jsx,ts,tsx}', () => { expect(() => { transform(getPaths().web.routes) }).toThrowError( - "Unable to find only a single file ending in 'Page.{js,jsx,ts,tsx}' in the follow page directories: 'HomePage" + "Unable to find only a single file ending in 'Page.{js,jsx,ts,tsx}' in the follow page directories: 'HomePage", ) }) }) @@ -46,7 +46,7 @@ describe('mulitiple files ending in Page.{js,jsx,ts,tsx}', () => { describe('page auto loader correctly imports pages', () => { const FIXTURE_PATH = path.resolve( __dirname, - '../../../../../__fixtures__/example-todo-main/' + '../../../../../__fixtures__/example-todo-main/', ) let result: babel.BabelFileResult | null @@ -74,7 +74,7 @@ describe('page auto loader correctly imports pages', () => { test('RSC specific code should not be added', () => { expect(result?.code).not.toContain( - 'import { renderFromRscServer } from "@redwoodjs/vite/client"' + 'import { renderFromRscServer } from "@redwoodjs/vite/client"', ) }) }) @@ -82,7 +82,7 @@ describe('page auto loader correctly imports pages', () => { describe('page auto loader handles imports for RSC', () => { const FIXTURE_PATH = path.resolve( __dirname, - '../../../../../__fixtures__/example-todo-main/' + '../../../../../__fixtures__/example-todo-main/', ) let result: babel.BabelFileResult | null @@ -105,20 +105,20 @@ describe('page auto loader handles imports for RSC', () => { `) expect(codeOutput).toContain( - 'import { renderFromRscServer } from "@redwoodjs/vite/client"' + 'import { renderFromRscServer } from "@redwoodjs/vite/client"', ) expect(codeOutput).toContain( - 'const HomePage = renderFromRscServer("HomePage")' + 'const HomePage = renderFromRscServer("HomePage")', ) // Un-imported pages get added with renderFromRscServer // so it calls the RSC worker to get a flight response expect(codeOutput).toContain( - 'const HomePage = renderFromRscServer("HomePage")' + 'const HomePage = renderFromRscServer("HomePage")', ) expect(codeOutput).toContain( - 'const BarPage = renderFromRscServer("BarPage")' + 'const BarPage = renderFromRscServer("BarPage")', ) }) diff --git a/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-src-alias.test.ts b/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-src-alias.test.ts index 7323831e49ca..a4e50641bcb7 100644 --- a/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-src-alias.test.ts +++ b/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-src-alias.test.ts @@ -6,7 +6,7 @@ import plugin from '../babel-plugin-redwood-src-alias' const FIXTURE_PATH = path.resolve( __dirname, - '../../../../../__fixtures__/empty-project' + '../../../../../__fixtures__/empty-project', ) describe('babel plugin redwood import dir - graphql function', () => { diff --git a/packages/babel-config/src/plugins/babel-plugin-redwood-cell.ts b/packages/babel-config/src/plugins/babel-plugin-redwood-cell.ts index 9b160d29dfb4..70e46493c0a2 100644 --- a/packages/babel-config/src/plugins/babel-plugin-redwood-cell.ts +++ b/packages/babel-config/src/plugins/babel-plugin-redwood-cell.ts @@ -104,11 +104,11 @@ export default function ({ types: t }: { types: typeof types }): PluginObj { [ t.importSpecifier( t.identifier(createCellHookName), - t.identifier(createCellHookName) + t.identifier(createCellHookName), ), ], - t.stringLiteral(importFrom) - ) + t.stringLiteral(importFrom), + ), ) // Insert at the bottom of the file: @@ -122,22 +122,22 @@ export default function ({ types: t }: { types: typeof types }): PluginObj { t.identifier(name), t.identifier(name), false, - true - ) + true, + ), ), // Add the `displayName` property so we can name the Cell // after the filename. t.objectProperty( t.identifier('displayName'), t.stringLiteral( - parse(this.file.opts.filename as string).name + parse(this.file.opts.filename as string).name, ), false, - true + true, ), ]), - ]) - ) + ]), + ), ) }, }, diff --git a/packages/babel-config/src/plugins/babel-plugin-redwood-context-wrapping.ts b/packages/babel-config/src/plugins/babel-plugin-redwood-context-wrapping.ts index 683e2395efde..4b5b958d18d7 100644 --- a/packages/babel-config/src/plugins/babel-plugin-redwood-context-wrapping.ts +++ b/packages/babel-config/src/plugins/babel-plugin-redwood-context-wrapping.ts @@ -11,17 +11,17 @@ function generateWrappedHandler(t: typeof types, isAsync: boolean) { t.callExpression( t.memberExpression( t.callExpression(t.identifier('__rw_getAsyncStoreInstance'), []), - t.identifier('getStore') + t.identifier('getStore'), ), - [] - ) + [], + ), ), ]) t.addComment( contextStoreVariableDeclaration, 'leading', ' The store will be undefined if no context isolation has been performed yet', - true + true, ) return t.arrowFunctionExpression( [t.identifier('__rw_event'), t.identifier('__rw__context')], @@ -31,7 +31,7 @@ function generateWrappedHandler(t: typeof types, isAsync: boolean) { t.binaryExpression( '===', t.identifier('__rw_contextStore'), - t.identifier('undefined') + t.identifier('undefined'), ), t.blockStatement([ t.returnStatement( @@ -39,34 +39,34 @@ function generateWrappedHandler(t: typeof types, isAsync: boolean) { t.memberExpression( t.callExpression( t.identifier('__rw_getAsyncStoreInstance'), - [] + [], ), - t.identifier('run') + t.identifier('run'), ), [ t.newExpression(t.identifier('Map'), []), t.identifier('__rw_handler'), t.identifier('__rw_event'), t.identifier('__rw__context'), - ] - ) + ], + ), ), - ]) + ]), ), t.returnStatement( t.callExpression(t.identifier('__rw_handler'), [ t.identifier('__rw_event'), t.identifier('__rw__context'), - ]) + ]), ), ]), - isAsync + isAsync, ) } export default function ( { types: t }: { types: typeof types }, - { projectIsEsm = false }: { projectIsEsm?: boolean } = {} + { projectIsEsm = false }: { projectIsEsm?: boolean } = {}, ): PluginObj { return { name: 'babel-plugin-redwood-context-wrapping', @@ -97,15 +97,15 @@ export default function ( [ t.importSpecifier( t.identifier('__rw_getAsyncStoreInstance'), - t.identifier('getAsyncStoreInstance') + t.identifier('getAsyncStoreInstance'), ), ], t.stringLiteral( projectIsEsm ? '@redwoodjs/context/dist/store.js' - : '@redwoodjs/context/dist/store' - ) - ) + : '@redwoodjs/context/dist/store', + ), + ), ) // Copy the original handler function to a new renamed function @@ -113,9 +113,9 @@ export default function ( t.variableDeclaration('const', [ t.variableDeclarator( t.identifier('__rw_handler'), - declaration.declarations[0].init + declaration.declarations[0].init, ), - ]) + ]), ) // Attempt to determine if we should mark the handler as async diff --git a/packages/babel-config/src/plugins/babel-plugin-redwood-graphql-options-extract.ts b/packages/babel-config/src/plugins/babel-plugin-redwood-graphql-options-extract.ts index 34e39c7aa276..ee88bfa47cae 100644 --- a/packages/babel-config/src/plugins/babel-plugin-redwood-graphql-options-extract.ts +++ b/packages/babel-config/src/plugins/babel-plugin-redwood-graphql-options-extract.ts @@ -12,7 +12,7 @@ function optionsConstNode( | types.JSXNamespacedName | types.SpreadElement | types.Expression, - state: PluginPass + state: PluginPass, ) { if ( t.isIdentifier(value) || @@ -23,11 +23,11 @@ function optionsConstNode( return t.exportNamedDeclaration( t.variableDeclaration('const', [ t.variableDeclarator(t.identifier(exportVariableName), value), - ]) + ]), ) } else { throw new Error( - `Unable to parse graphql function options in '${state.file.opts.filename}'` + `Unable to parse graphql function options in '${state.file.opts.filename}'`, ) } } diff --git a/packages/babel-config/src/plugins/babel-plugin-redwood-import-dir.ts b/packages/babel-config/src/plugins/babel-plugin-redwood-import-dir.ts index cf523405b7ec..357af7c5f7f2 100644 --- a/packages/babel-config/src/plugins/babel-plugin-redwood-import-dir.ts +++ b/packages/babel-config/src/plugins/babel-plugin-redwood-import-dir.ts @@ -23,7 +23,7 @@ import { importStatementPath } from '@redwoodjs/project-config' */ export default function ( { types: t }: { types: typeof types }, - { projectIsEsm = false }: { projectIsEsm?: boolean } = {} + { projectIsEsm = false }: { projectIsEsm?: boolean } = {}, ): PluginObj { return { name: 'babel-plugin-redwood-import-dir', @@ -42,9 +42,9 @@ export default function ( t.variableDeclaration('let', [ t.variableDeclarator( t.identifier(importName), - t.objectExpression([]) + t.objectExpression([]), ), - ]) + ]), ) const importGlob = importStatementPath(p.node.source.value) @@ -74,15 +74,15 @@ export default function ( t.importDeclaration( [ t.importNamespaceSpecifier( - t.identifier(importName + '_' + fpVarName) + t.identifier(importName + '_' + fpVarName), ), ], t.stringLiteral( projectIsEsm ? `${filePathWithoutExtension}.js` - : filePathWithoutExtension - ) - ) + : filePathWithoutExtension, + ), + ), ) // + . = @@ -93,11 +93,11 @@ export default function ( '=', t.memberExpression( t.identifier(importName), - t.identifier(fpVarName) + t.identifier(fpVarName), ), - t.identifier(importName + '_' + fpVarName) - ) - ) + t.identifier(importName + '_' + fpVarName), + ), + ), ) } diff --git a/packages/babel-config/src/plugins/babel-plugin-redwood-mock-cell-data.ts b/packages/babel-config/src/plugins/babel-plugin-redwood-mock-cell-data.ts index 861154c8e83c..04443082ae03 100644 --- a/packages/babel-config/src/plugins/babel-plugin-redwood-mock-cell-data.ts +++ b/packages/babel-config/src/plugins/babel-plugin-redwood-mock-cell-data.ts @@ -15,12 +15,12 @@ export default function ({ types: t }: { types: typeof types }): PluginObj { // export const standard = ${ex} const createExportStandard = ( - ex: types.CallExpression | types.ArrowFunctionExpression + ex: types.CallExpression | types.ArrowFunctionExpression, ) => t.exportNamedDeclaration( t.variableDeclaration('const', [ t.variableDeclarator(t.identifier('standard'), ex), - ]) + ]), ) return { @@ -81,7 +81,7 @@ export default function ({ types: t }: { types: typeof types }): PluginObj { mockFunctionMaybe.type !== 'FunctionExpression' ) { throw new Error( - `\n \n Mock Error: You must export your standard mock as a function \n \n` + `\n \n Mock Error: You must export your standard mock as a function \n \n`, ) } @@ -131,7 +131,7 @@ export default function ({ types: t }: { types: typeof types }): PluginObj { // mockGraphQLQuery(, ) const mockGraphQLCall = t.callExpression( t.identifier('mockGraphQLQuery'), - [t.stringLiteral(cellMetadata.operationName), mockFunction] + [t.stringLiteral(cellMetadata.operationName), mockFunction], ) // Delete original "export const standard" @@ -144,10 +144,10 @@ export default function ({ types: t }: { types: typeof types }): PluginObj { [ t.importSpecifier( t.identifier('afterQuery'), - t.identifier('afterQuery') + t.identifier('afterQuery'), ), ], - t.stringLiteral(`./${path.basename(cellPath)}`) + t.stringLiteral(`./${path.basename(cellPath)}`), ) nodesToInsert = [ @@ -158,8 +158,8 @@ export default function ({ types: t }: { types: typeof types }): PluginObj { [], t.callExpression(t.identifier('afterQuery'), [ t.callExpression(mockGraphQLCall, []), - ]) - ) + ]), + ), ), ] } else { @@ -239,7 +239,7 @@ export const getCellMetadata = (p: string) => { const hasQueryExport = namedExports.find(({ name }) => name === 'QUERY') const hasAfterQueryExport = namedExports.find( - ({ name }) => name === 'afterQuery' + ({ name }) => name === 'afterQuery', ) let operationName = '' diff --git a/packages/babel-config/src/plugins/babel-plugin-redwood-otel-wrapping.ts b/packages/babel-config/src/plugins/babel-plugin-redwood-otel-wrapping.ts index 7b1ab73644aa..eef7a9b07e6b 100644 --- a/packages/babel-config/src/plugins/babel-plugin-redwood-otel-wrapping.ts +++ b/packages/babel-config/src/plugins/babel-plugin-redwood-otel-wrapping.ts @@ -8,7 +8,7 @@ import { getBaseDirFromFile } from '@redwoodjs/project-config' function addOpenTelemetryImport( path: NodePath, - t: typeof types + t: typeof types, ) { // We need to have access to the `trace` from `@opentelemetry/api` in order to add the // automatic instrumentation. We will import it and alias it to something highly specific @@ -18,11 +18,11 @@ function addOpenTelemetryImport( [ t.importSpecifier( t.identifier('RW_OTEL_WRAPPER_TRACE'), - t.identifier('trace') + t.identifier('trace'), ), ], - t.stringLiteral('@opentelemetry/api') - ) + t.stringLiteral('@opentelemetry/api'), + ), ) } @@ -47,7 +47,7 @@ function getRedwoodPaths(state: PluginPass): { ? filename.substring( filenameOffset, filename.substring(filenameOffset).indexOf(nodejsPath.sep) + - filenameOffset + filenameOffset, ) : '?' @@ -60,7 +60,7 @@ function getRedwoodPaths(state: PluginPass): { function wrapExportNamedDeclaration( path: NodePath, state: PluginPass, - t: typeof types + t: typeof types, ) { const declaration = path.node.declaration const declarationIsSupported = @@ -101,7 +101,7 @@ function wrapExportNamedDeclaration( if (param.type === 'ObjectPattern') { const objectProperties = param.properties.filter( - (p) => p.type === 'ObjectProperty' + (p) => p.type === 'ObjectProperty', ) as types.ObjectProperty[] originalFunctionArgumentsWithoutDefaults.push( t.objectExpression( @@ -110,8 +110,8 @@ function wrapExportNamedDeclaration( return t.objectProperty(p.key, p.value.left) } return p - }) - ) + }), + ), ) continue @@ -122,7 +122,7 @@ function wrapExportNamedDeclaration( originalFunctionArgumentsWithoutDefaults.push(param.left) } else if (param.left.type === 'ObjectPattern') { const objectProperties = param.left.properties.filter( - (p) => p.type === 'ObjectProperty' + (p) => p.type === 'ObjectProperty', ) as types.ObjectProperty[] originalFunctionArgumentsWithoutDefaults.push( t.objectExpression( @@ -131,8 +131,8 @@ function wrapExportNamedDeclaration( return t.objectProperty(p.key, p.value.left) } return p - }) - ) + }), + ), ) } else { // TODO: Implement others, bail out for now @@ -151,7 +151,7 @@ function wrapExportNamedDeclaration( const activeSpanBlock = t.callExpression( t.memberExpression( t.identifier('RW_OTEL_WRAPPER_TRACER'), - t.identifier('startActiveSpan') + t.identifier('startActiveSpan'), ), [ t.stringLiteral(`redwoodjs:api:${apiFolder}:${originalFunctionName}`), @@ -162,25 +162,25 @@ function wrapExportNamedDeclaration( t.callExpression( t.memberExpression( t.identifier('span'), - t.identifier('setAttribute') + t.identifier('setAttribute'), ), [ t.stringLiteral('code.function'), t.stringLiteral(originalFunctionName), - ] - ) + ], + ), ), t.expressionStatement( t.callExpression( t.memberExpression( t.identifier('span'), - t.identifier('setAttribute') + t.identifier('setAttribute'), ), [ t.stringLiteral('code.filepath'), t.stringLiteral(filename || '?'), - ] - ) + ], + ), ), t.tryStatement( t.blockStatement([ @@ -191,20 +191,20 @@ function wrapExportNamedDeclaration( ? t.awaitExpression( t.callExpression( t.identifier(wrappedFunctionName), - originalFunctionArgumentsWithoutDefaults - ) + originalFunctionArgumentsWithoutDefaults, + ), ) : t.callExpression( t.identifier(wrappedFunctionName), - originalFunctionArgumentsWithoutDefaults - ) + originalFunctionArgumentsWithoutDefaults, + ), ), ]), t.expressionStatement( t.callExpression( t.memberExpression(t.identifier('span'), t.identifier('end')), - [] - ) + [], + ), ), t.returnStatement(t.identifier('RW_OTEL_WRAPPER_INNER_RESULT')), ]), @@ -215,22 +215,22 @@ function wrapExportNamedDeclaration( t.callExpression( t.memberExpression( t.identifier('span'), - t.identifier('recordException') + t.identifier('recordException'), ), - [t.identifier('error')] - ) + [t.identifier('error')], + ), ), t.expressionStatement( t.callExpression( t.memberExpression( t.identifier('span'), - t.identifier('setStatus') + t.identifier('setStatus'), ), [ t.objectExpression([ t.objectProperty( t.identifier('code'), - t.numericLiteral(2) + t.numericLiteral(2), ), t.objectProperty( t.identifier('message'), @@ -243,18 +243,18 @@ function wrapExportNamedDeclaration( t.identifier('error'), t.identifier('message'), false, - true + true, ), t.identifier('split'), false, - true + true, ), [t.stringLiteral('\n')], - false + false, ), t.numericLiteral(0), true, - false + false, ), t.optionalMemberExpression( t.optionalCallExpression( @@ -264,45 +264,45 @@ function wrapExportNamedDeclaration( t.identifier('error'), t.identifier('toString'), false, - true + true, ), [], - false + false, ), t.identifier('split'), false, - true + true, ), [t.stringLiteral('\n')], - false + false, ), t.numericLiteral(0), true, - false - ) - ) + false, + ), + ), ), ]), - ] - ) + ], + ), ), t.expressionStatement( t.callExpression( t.memberExpression( t.identifier('span'), - t.identifier('end') + t.identifier('end'), ), - [] - ) + [], + ), ), t.throwStatement(t.identifier('error')), - ]) - ) + ]), + ), ), ]), - originalFunction.async + originalFunction.async, ), - ] + ], ) const wrapper = t.arrowFunctionExpression( @@ -312,7 +312,7 @@ function wrapExportNamedDeclaration( t.variableDeclaration('const', [ t.variableDeclarator( t.identifier(wrappedFunctionName), - originalFunction + originalFunction, ), ]), t.variableDeclaration('const', [ @@ -321,10 +321,10 @@ function wrapExportNamedDeclaration( t.callExpression( t.memberExpression( t.identifier('RW_OTEL_WRAPPER_TRACE'), - t.identifier('getTracer') + t.identifier('getTracer'), ), - [t.stringLiteral('redwoodjs')] - ) + [t.stringLiteral('redwoodjs')], + ), ), ]), t.variableDeclaration('const', [ @@ -332,16 +332,16 @@ function wrapExportNamedDeclaration( t.identifier('RW_OTEL_WRAPPER_RESULT'), originalFunction.async ? t.awaitExpression(activeSpanBlock) - : activeSpanBlock + : activeSpanBlock, ), ]), t.returnStatement(t.identifier('RW_OTEL_WRAPPER_RESULT')), ], originalFunction.body.type === 'BlockStatement' ? originalFunction.body.directives - : undefined + : undefined, ), - originalFunction.async + originalFunction.async, ) // Replace the original function with the wrapped version diff --git a/packages/babel-config/src/plugins/babel-plugin-redwood-remove-dev-fatal-error-page.ts b/packages/babel-config/src/plugins/babel-plugin-redwood-remove-dev-fatal-error-page.ts index 12108e7b671a..29a9a22cc800 100644 --- a/packages/babel-config/src/plugins/babel-plugin-redwood-remove-dev-fatal-error-page.ts +++ b/packages/babel-config/src/plugins/babel-plugin-redwood-remove-dev-fatal-error-page.ts @@ -19,7 +19,7 @@ export default function ({ types: t }: { types: typeof types }): PluginObj { const variableDeclaration = t.variableDeclaration('const', [ t.variableDeclarator( t.identifier('DevFatalErrorPage'), - t.identifier('undefined') + t.identifier('undefined'), ), ]) diff --git a/packages/babel-config/src/plugins/babel-plugin-redwood-routes-auto-loader.ts b/packages/babel-config/src/plugins/babel-plugin-redwood-routes-auto-loader.ts index bd31b9b914b4..fc342f2fd317 100644 --- a/packages/babel-config/src/plugins/babel-plugin-redwood-routes-auto-loader.ts +++ b/packages/babel-config/src/plugins/babel-plugin-redwood-routes-auto-loader.ts @@ -39,7 +39,11 @@ const withRelativeImports = (page: PagesDependency) => { export default function ( { types: t }: { types: typeof types }, - { forPrerender = false, forVite = false, forRscClient = false }: PluginOptions + { + forPrerender = false, + forVite = false, + forRscClient = false, + }: PluginOptions, ): PluginObj { // @NOTE: This var gets mutated inside the visitors let pages = processPagesDir().map(withRelativeImports) @@ -57,10 +61,10 @@ export default function ( if (duplicatePageImportNames.size > 0) { throw new Error( `Unable to find only a single file ending in 'Page.{js,jsx,ts,tsx}' in the follow page directories: ${Array.from( - duplicatePageImportNames + duplicatePageImportNames, ) .map((name) => `'${name}'`) - .join(', ')}` + .join(', ')}`, ) } @@ -76,11 +80,11 @@ export default function ( } const userImportRelativePath = getPathRelativeToSrc( - importStatementPath(p.node.source?.value) + importStatementPath(p.node.source?.value), ) const defaultSpecifier = p.node.specifiers.filter((specifiers) => - t.isImportDefaultSpecifier(specifiers) + t.isImportDefaultSpecifier(specifiers), )[0] // Remove Page imports in prerender mode (see babel-preset) @@ -110,7 +114,7 @@ export default function ( // Remove the default import for the page and leave all the others p.node.specifiers = p.node.specifiers.filter( - (specifier) => !t.isImportDefaultSpecifier(specifier) + (specifier) => !t.isImportDefaultSpecifier(specifier), ) } @@ -122,7 +126,9 @@ export default function ( // We use the path & defaultSpecifier because the const name could be anything pages = pages.filter( (page) => - !(page.relativeImport === ensurePosixPath(userImportRelativePath)) + !( + page.relativeImport === ensurePosixPath(userImportRelativePath) + ), ) } }, @@ -140,8 +146,8 @@ export default function ( nodes.unshift( t.importDeclaration( [t.importSpecifier(t.identifier('lazy'), t.identifier('lazy'))], - t.stringLiteral('react') - ) + t.stringLiteral('react'), + ), ) // For RSC Client builds add @@ -152,11 +158,11 @@ export default function ( [ t.importSpecifier( t.identifier('renderFromRscServer'), - t.identifier('renderFromRscServer') + t.identifier('renderFromRscServer'), ), ], - t.stringLiteral('@redwoodjs/vite/client') - ) + t.stringLiteral('@redwoodjs/vite/client'), + ), ) } @@ -174,9 +180,9 @@ export default function ( t.identifier(importName), t.callExpression(t.identifier('renderFromRscServer'), [ t.stringLiteral(importName), - ]) + ]), ), - ]) + ]), ) } else { // const = { @@ -207,7 +213,7 @@ export default function ( t.objectExpression([ t.objectProperty( t.identifier('name'), - t.stringLiteral(importName) + t.stringLiteral(importName), ), // prerenderLoader for ssr/prerender and first load of // prerendered pages in browser (csr) @@ -220,9 +226,9 @@ export default function ( forPrerender, forVite, relativeImport, - t - ) - ) + t, + ), + ), ), t.objectProperty( t.identifier('LazyComponent'), @@ -231,13 +237,13 @@ export default function ( [], t.callExpression(t.identifier('import'), [ importArgument, - ]) + ]), ), - ]) + ]), ), - ]) + ]), ), - ]) + ]), ) } } @@ -254,7 +260,7 @@ function prerenderLoaderImpl( forPrerender: boolean, forVite: boolean, relativeImport: string, - t: typeof types + t: typeof types, ) { if (forPrerender) { // This works for both vite and webpack @@ -277,8 +283,8 @@ function prerenderLoaderImpl( t.memberExpression( t.identifier('globalThis.__REDWOOD__PRERENDER_PAGES'), t.identifier('name'), - true - ) + true, + ), ), ]) } else { diff --git a/packages/babel-config/src/plugins/babel-plugin-redwood-src-alias.ts b/packages/babel-config/src/plugins/babel-plugin-redwood-src-alias.ts index 472aa6b7a9b7..5fe60706f12e 100644 --- a/packages/babel-config/src/plugins/babel-plugin-redwood-src-alias.ts +++ b/packages/babel-config/src/plugins/babel-plugin-redwood-src-alias.ts @@ -7,7 +7,7 @@ export default function ( options: { /** absolute path to the `src` directory */ srcAbsPath: string - } + }, ): PluginObj { return { name: 'babel-plugin-redwood-src-alias', diff --git a/packages/babel-config/src/web.ts b/packages/babel-config/src/web.ts index 87924e84f01f..a739fc577286 100644 --- a/packages/babel-config/src/web.ts +++ b/packages/babel-config/src/web.ts @@ -26,7 +26,7 @@ export interface Flags { } export const getWebSideBabelPlugins = ( - { forJest, forVite }: Flags = { forJest: false, forVite: false } + { forJest, forVite }: Flags = { forJest: false, forVite: false }, ) => { // Need the project config to know if trusted graphql documents is being used and decide to use // the gql tag import or the trusted document gql function generated by code gen client preset @@ -113,7 +113,7 @@ export const getWebSideOverrides = ( forPrerender: false, forVite: false, forRscClient: false, - } + }, ): Array => { // Have to use a readonly array here because of a limitation in TS // See https://stackoverflow.com/a/70763406/88106 @@ -153,7 +153,7 @@ export const getWebSideOverrides = ( return overrides.filter( (override: false | TransformOptions): override is TransformOptions => { return !!override - } + }, ) } @@ -180,7 +180,7 @@ export const getWebSideBabelPresets = (options: Flags) => { if (presetName === '@babel/preset-react') { reactPresetConfig = presetConfig } - } + }, ) } return [ diff --git a/packages/cli-helpers/src/auth/__tests__/authFiles.test.ts b/packages/cli-helpers/src/auth/__tests__/authFiles.test.ts index 6107f663a0c3..929ff033b32f 100644 --- a/packages/cli-helpers/src/auth/__tests__/authFiles.test.ts +++ b/packages/cli-helpers/src/auth/__tests__/authFiles.test.ts @@ -44,7 +44,7 @@ it('generates a record of TS files', async () => { await apiSideFiles({ basedir: path.join(__dirname, 'fixtures/supertokensSetup'), webAuthn: false, - }) + }), ).sort() expect(filePaths).toEqual([ @@ -61,7 +61,7 @@ it('generates a record of JS files', async () => { await apiSideFiles({ basedir: path.join(__dirname, 'fixtures/supertokensSetup'), webAuthn: false, - }) + }), ).sort() expect(filePaths).toEqual([ @@ -80,13 +80,13 @@ it('generates a record of webAuthn files', async () => { expect(Object.keys(filesRecord)).toHaveLength(2) expect( Object.values(filesRecord).some((content) => - content.toLowerCase().includes('webauthn') - ) + content.toLowerCase().includes('webauthn'), + ), ).toBeTruthy() expect( Object.values(filesRecord).some( - (content) => !content.toLowerCase().includes('webauthn') - ) + (content) => !content.toLowerCase().includes('webauthn'), + ), ).toBeTruthy() }) @@ -104,7 +104,7 @@ it('generates new filenames to avoid overwriting existing files', () => { const filesRecord = generateUniqueFileNames( conflictingFilesRecord, - 'supertokens' + 'supertokens', ) const filePaths = Object.keys(filesRecord).sort() diff --git a/packages/cli-helpers/src/auth/__tests__/authTasks.test.ts b/packages/cli-helpers/src/auth/__tests__/authTasks.test.ts index 1b4a04d9c404..25a96399f168 100644 --- a/packages/cli-helpers/src/auth/__tests__/authTasks.test.ts +++ b/packages/cli-helpers/src/auth/__tests__/authTasks.test.ts @@ -97,13 +97,13 @@ beforeEach(() => { vi.mocked(isTypeScriptProject).mockReturnValue(true) vi.mocked(getPaths).mockReturnValue( // @ts-expect-error - We are not returning a full set of mock paths here - mockedPathGenerator('App.tsx', 'Routes.tsx') + mockedPathGenerator('App.tsx', 'Routes.tsx'), ) vol.fromJSON({ [path.join( getPaths().base, - platformPath('/templates/web/auth.ts.template') + platformPath('/templates/web/auth.ts.template'), )]: '// web auth template', [getPaths().web.app]: webAppTsx, [getPaths().api.graphql]: graphqlTs, @@ -115,7 +115,7 @@ describe('authTasks', () => { it('Should update App.{jsx,tsx}, Routes.{jsx,tsx} and add auth.ts (Auth0)', () => { const templatePath = path.join( getPaths().base, - platformPath('/templates/web/auth.ts.template') + platformPath('/templates/web/auth.ts.template'), ) vol.fromJSON({ @@ -142,7 +142,7 @@ describe('authTasks', () => { it('Should update App.{jsx,tsx}, Routes.{jsx,tsx} and add auth.ts (Clerk)', () => { const templatePath = path.join( getPaths().base, - platformPath('/templates/web/auth.tsx.template') + platformPath('/templates/web/auth.tsx.template'), ) // NOTE: We reset here because we had to remove the `auth.ts.template` @@ -313,8 +313,8 @@ describe('authTasks', () => { expect(hasAuthProvider('')).toBeTruthy() expect( hasAuthProvider( - '' - ) + '', + ), ).toBeTruthy() expect(hasAuthProvider('')).toBeFalsy() @@ -456,7 +456,7 @@ describe('authTasks', () => { ) - `.replace(/\n/g, '\r\n') + `.replace(/\n/g, '\r\n'), ) }) @@ -538,7 +538,7 @@ describe('authTasks', () => { ) - `.replace(/\n/g, '\r\n') + `.replace(/\n/g, '\r\n'), ) }) @@ -596,7 +596,7 @@ describe('authTasks', () => { ) - `.replace(/\n/g, '\r\n') + `.replace(/\n/g, '\r\n'), ) }) @@ -640,7 +640,7 @@ describe('authTasks', () => { createWebAuth(getPaths().base, false).task(ctx) expect( - fs.readFileSync(path.join(getPaths().web.src, 'auth.ts'), 'utf-8') + fs.readFileSync(path.join(getPaths().web.src, 'auth.ts'), 'utf-8'), ).toMatchSnapshot() }) @@ -659,7 +659,7 @@ describe('authTasks', () => { await createWebAuth(getPaths().base, false).task(ctx) expect( - fs.readFileSync(path.join(getPaths().web.src, 'auth.js'), 'utf-8') + fs.readFileSync(path.join(getPaths().web.src, 'auth.js'), 'utf-8'), ).toMatchSnapshot() }) }) diff --git a/packages/cli-helpers/src/auth/__tests__/setupHelpers.test.ts b/packages/cli-helpers/src/auth/__tests__/setupHelpers.test.ts index 07e04b1437f4..068059935b46 100644 --- a/packages/cli-helpers/src/auth/__tests__/setupHelpers.test.ts +++ b/packages/cli-helpers/src/auth/__tests__/setupHelpers.test.ts @@ -18,7 +18,7 @@ vi.mock('../../lib/paths', () => { src: path.join(__dirname, '../create-redwood-app/template/api/src'), functions: path.join( __dirname, - '../create-redwood-app/template/api/src/functions' + '../create-redwood-app/template/api/src/functions', ), lib: path.join(__dirname, '../create-redwood-app/template/api/src/lib'), }, diff --git a/packages/cli-helpers/src/auth/authFiles.ts b/packages/cli-helpers/src/auth/authFiles.ts index 28ce77d1ef53..8d2f33d98d9b 100644 --- a/packages/cli-helpers/src/auth/authFiles.ts +++ b/packages/cli-helpers/src/auth/authFiles.ts @@ -71,7 +71,7 @@ export const apiSideFiles = async ({ basedir, webAuthn }: FilesArgs) => { const templateFilePath = path.join( apiBaseTemplatePath, dir, - f.templateFileName + f.templateFileName, ) const outputFilePath = path.join(apiSrcPath, dir, f.outputFileName) @@ -119,7 +119,7 @@ export const apiSideFiles = async ({ basedir, webAuthn }: FilesArgs) => { */ export function generateUniqueFileNames( filesRecord: Record, - provider: string + provider: string, ) { const newFilesRecord: Record = {} diff --git a/packages/cli-helpers/src/auth/authTasks.ts b/packages/cli-helpers/src/auth/authTasks.ts index 8c90351d4a93..145172daab79 100644 --- a/packages/cli-helpers/src/auth/authTasks.ts +++ b/packages/cli-helpers/src/auth/authTasks.ts @@ -40,12 +40,12 @@ function addAuthDecoderToCreateGraphQLHandler(content: string) { // emulate an atomic group. if ( !new RegExp('(?=(^.*?createGraphQLHandler))\\1.*\\bauthDecoder', 's').test( - content + content, ) ) { return content.replace( /^(?\s*)(loggerConfig:)(.*)$/m, - `$authDecoder,\n$$2$3` + `$authDecoder,\n$$2$3`, ) } @@ -110,20 +110,20 @@ export const addApiConfig = ({ const hasCurrentUserImport = /(^import {.*?getCurrentUser(?!getCurrentUser).*?} from 'src\/lib\/auth')/s.test( - newContent + newContent, ) if (!hasCurrentUserImport) { // add import statement newContent = newContent.replace( /^(import { db } from 'src\/lib\/db')$/m, - `import { getCurrentUser } from 'src/lib/auth'\n$1` + `import { getCurrentUser } from 'src/lib/auth'\n$1`, ) // add object to handler newContent = newContent.replace( /^(\s*)(loggerConfig:)(.*)$/m, - `$1getCurrentUser,\n$1$2$3` + `$1getCurrentUser,\n$1$2$3`, ) } @@ -140,7 +140,7 @@ const addAuthImportToApp = (content: string) => { const contentLines = content.split('\n') // Find the last import line that's not a .css or .scss import const importIndex = contentLines.findLastIndex((line: string) => - /^\s*import (?!.*(?:.css'|.scss'))/.test(line) + /^\s*import (?!.*(?:.css'|.scss'))/.test(line), ) // After the import found above, insert a blank line followed by the @@ -154,7 +154,7 @@ const addAuthImportToRoutes = (content: string) => { const contentLines = content.split('\n') // Find the last import line that's not a .css or .scss import const importIndex = contentLines.findLastIndex((line: string) => - /^\s*import (?!.*(?:.css'|.scss'))/.test(line) + /^\s*import (?!.*(?:.css'|.scss'))/.test(line), ) // After the import found above, insert a blank line followed by the @@ -229,7 +229,7 @@ const addAuthProviderToApp = (content: string, setupMode: AuthSetupMode) => { } const match = content.match( - /(\s+)()(.*)(<\/RedwoodProvider>)/s + /(\s+)()(.*)(<\/RedwoodProvider>)/s, ) if (!match) { @@ -270,21 +270,21 @@ const addAuthProviderToApp = (content: string, setupMode: AuthSetupMode) => { return content.replace( /\s+.*<\/RedwoodProvider>/s, - renderContent + renderContent, ) } const hasUseAuthHook = (componentName: string, content: string) => { return new RegExp( `<${componentName}.*useAuth={.*?}.*?>.*<\/${componentName}>`, - 's' + 's', ).test(content) } const addUseAuthHook = (componentName: string, content: string) => { return content.replace( `<${componentName}`, - `<${componentName} useAuth={useAuth}` + `<${componentName} useAuth={useAuth}`, ) } @@ -293,7 +293,7 @@ const addUseAuthHook = (componentName: string, content: string) => { * Exported for testing */ export const addConfigToWebApp = < - Renderer extends typeof ListrRenderer + Renderer extends typeof ListrRenderer, >(): ListrTask => { return { title: 'Updating web/src/App.{jsx,tsx}', @@ -315,7 +315,7 @@ export const addConfigToWebApp = < // Remove legacy AuthProvider import content = content.replace( "import { AuthProvider } from '@redwoodjs/auth'\n", - '' + '', ) } @@ -329,7 +329,7 @@ export const addConfigToWebApp = < task.output = colors.warning( 'Could not find .\nIf you are using a custom ' + 'GraphQL Client you will have to make sure it gets access to your ' + - '`useAuth`, if it needs it.' + '`useAuth`, if it needs it.', ) } @@ -383,7 +383,7 @@ export const createWebAuth = (basedir: string, webAuthn: boolean) => { authFileName = path.join( getPaths().web.src, - ctx.provider + 'Auth' + count + ctx.provider + 'Auth' + count, ) i++ @@ -394,7 +394,7 @@ export const createWebAuth = (basedir: string, webAuthn: boolean) => { let template: string | undefined = fs.readFileSync( path.join(templatesBaseDir, templateFileName), - 'utf-8' + 'utf-8', ) template = isTSProject @@ -435,14 +435,14 @@ export const addConfigToRoutes = () => { */ export const generateAuthApiFiles = ( basedir: string, - webAuthn: boolean + webAuthn: boolean, ): ListrTask => { return { title: 'Generating auth api side files...', task: async (ctx, task) => { if (!apiSrcDoesExist()) { return new Error( - 'Could not find api/src directory. Cannot continue setup!' + 'Could not find api/src directory. Cannot continue setup!', ) } @@ -469,7 +469,7 @@ export const generateAuthApiFiles = ( } else if (ctx.setupMode === 'COMBINE') { const uniqueFilesRecord = generateUniqueFileNames( filesRecord, - ctx.provider + ctx.provider, ) filesRecord = uniqueFilesRecord @@ -494,12 +494,12 @@ function findExistingFiles(filesMap: Record) { } export const addAuthConfigToGqlApi = ( - authDecoderImport?: string + authDecoderImport?: string, ) => ({ title: 'Adding auth config to GraphQL API...', task: ( ctx: AuthGeneratorCtx, - _task: ListrTaskWrapper + _task: ListrTaskWrapper, ) => { if (graphFunctionDoesExist()) { addApiConfig({ @@ -509,7 +509,7 @@ export const addAuthConfigToGqlApi = ( }) } else { throw new Error( - 'GraphQL function not found. You will need to pass the decoder to the createGraphQLHandler function.' + 'GraphQL function not found. You will need to pass the decoder to the createGraphQLHandler function.', ) } }, @@ -527,13 +527,13 @@ export interface AuthGeneratorCtx { } export const setAuthSetupMode = ( - force: boolean + force: boolean, ) => { return { title: 'Checking project for existing auth...', task: async ( ctx: AuthGeneratorCtx, - task: ListrTaskWrapper + task: ListrTaskWrapper, ) => { if (force) { ctx.setupMode = 'FORCE' diff --git a/packages/cli-helpers/src/auth/setupHelpers.ts b/packages/cli-helpers/src/auth/setupHelpers.ts index 0daaeae51e3a..bd5df134eeaf 100644 --- a/packages/cli-helpers/src/auth/setupHelpers.ts +++ b/packages/cli-helpers/src/auth/setupHelpers.ts @@ -39,8 +39,8 @@ export const standardAuthBuilder = (yargs: Argv) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#setup-auth' - )}` + 'https://redwoodjs.com/docs/cli-commands#setup-auth', + )}`, ) } @@ -110,11 +110,11 @@ export const standardAuthHandler = async ({ ...[ '', `${colors.warning( - 'Your existing auth provider has been replaced!' + 'Your existing auth provider has been replaced!', )}`, "You'll still need to manually remove your old auth provider's config,", "functions, and dependencies (in your web and api package.json's).", - ] + ], ) } @@ -125,8 +125,8 @@ export const standardAuthHandler = async ({ 'names for the newly generated files. This probably means ' + `${ctx.provider} auth doesn't work out of the box. You'll most ` + 'likely have to manually merge some of the generated files ' + - 'with your existing auth files' - ) + 'with your existing auth files', + ), ) } }, @@ -139,7 +139,7 @@ export const standardAuthHandler = async ({ setupMode: 'UNKNOWN', provider, // provider name passed from CLI }, - } + }, ) try { diff --git a/packages/cli-helpers/src/lib/__tests__/index.test.ts b/packages/cli-helpers/src/lib/__tests__/index.test.ts index e3974872a26f..ef1aeb28ecb4 100644 --- a/packages/cli-helpers/src/lib/__tests__/index.test.ts +++ b/packages/cli-helpers/src/lib/__tests__/index.test.ts @@ -10,7 +10,7 @@ vi.mock('../paths', () => { return { base: path.resolve( __dirname, - '../../../../../__fixtures__/example-todo-main' + '../../../../../__fixtures__/example-todo-main', ), } }, @@ -36,6 +36,6 @@ test('prettify formats tsx content', async () => { return <>{foo}, {bar}}` expect( - await prettify('FooBarComponent.template.tsx', content) + await prettify('FooBarComponent.template.tsx', content), ).toMatchSnapshot() }) diff --git a/packages/cli-helpers/src/lib/__tests__/project.addTomlSetting.test.ts b/packages/cli-helpers/src/lib/__tests__/project.addTomlSetting.test.ts index 16b52678357b..a2e1b0c7c95d 100644 --- a/packages/cli-helpers/src/lib/__tests__/project.addTomlSetting.test.ts +++ b/packages/cli-helpers/src/lib/__tests__/project.addTomlSetting.test.ts @@ -33,7 +33,7 @@ it('should add `fragments = true` to empty redwood.toml', () => { setTomlSetting('graphql', 'fragments', 'true') expect(vol.toJSON()[FIXTURE_PATH + '/redwood.toml']).toMatch( - /fragments = true/ + /fragments = true/, ) }) @@ -78,7 +78,7 @@ it('should update redwood.toml even if `fragments = true` exists for other secti setTomlSetting('graphql', 'fragments', true) expect(vol.toJSON()[FIXTURE_PATH + '/redwood.toml']).toEqual( - toml + '\n[graphql]\n fragments = true' + toml + '\n[graphql]\n fragments = true', ) }) @@ -138,7 +138,7 @@ it('should handle when [graphql] is last section in redwood.toml', async () => { setTomlSetting('graphql', 'fragments', true) expect(vol.toJSON()[FIXTURE_PATH + '/redwood.toml']).toEqual( - toml + '\n fragments = true' + toml + '\n fragments = true', ) }) @@ -185,7 +185,7 @@ it("should add to end of existing section, also when it's the last section", asy setTomlSetting('graphql', 'fragments', true) expect(vol.toJSON()[FIXTURE_PATH + '/redwood.toml']).toEqual( - toml + ' fragments = true\n' + toml + ' fragments = true\n', ) }) @@ -255,7 +255,7 @@ it('should update existing setting if available, with no spaces', async () => { setTomlSetting('graphql', 'fragments', true) expect(vol.toJSON()[FIXTURE_PATH + '/redwood.toml']).toEqual( - '[graphql]\nfragments = true' + '[graphql]\nfragments = true', ) }) diff --git a/packages/cli-helpers/src/lib/__tests__/project.test.ts b/packages/cli-helpers/src/lib/__tests__/project.test.ts index a82a29acafc6..c423ecff3bc9 100644 --- a/packages/cli-helpers/src/lib/__tests__/project.test.ts +++ b/packages/cli-helpers/src/lib/__tests__/project.test.ts @@ -92,7 +92,7 @@ describe('addEnvVar', () => { const file = addEnvVar( 'EXISTING_VAR', 'new_value', - 'Updated existing variable Comment' + 'Updated existing variable Comment', ) expect(file).toMatchSnapshot() @@ -117,7 +117,7 @@ describe('addEnvVar', () => { const file = addEnvVar( 'EXISTING_VAR', 'new_value', - 'New Variable Comment' + 'New Variable Comment', ) expect(file).toMatchSnapshot() @@ -148,7 +148,7 @@ describe('updateTomlConfig', () => { it('adds when experimental cli is not configured', () => { const file = updateTomlConfig( - '@example/test-package-when-cli-not-configured' + '@example/test-package-when-cli-not-configured', ) expect(file).toMatchSnapshot() }) @@ -178,7 +178,7 @@ describe('updateTomlConfig', () => { } const file = updateTomlConfig( - '@example/test-package-when-no-plugins-configured' + '@example/test-package-when-no-plugins-configured', ) expect(file).toMatchSnapshot() @@ -192,7 +192,7 @@ describe('updateTomlConfig', () => { } const file = updateTomlConfig( - '@example/test-package-when-autoInstall-false' + '@example/test-package-when-autoInstall-false', ) expect(file).toMatchSnapshot() @@ -211,7 +211,7 @@ describe('updateTomlConfig', () => { } const file = updateTomlConfig( - '@existing-example/some-package-name-already-exists' + '@existing-example/some-package-name-already-exists', ) expect(file).toMatchSnapshot() diff --git a/packages/cli-helpers/src/lib/__tests__/version.test.ts b/packages/cli-helpers/src/lib/__tests__/version.test.ts index 69ae65d13aa1..5570c8d959dd 100644 --- a/packages/cli-helpers/src/lib/__tests__/version.test.ts +++ b/packages/cli-helpers/src/lib/__tests__/version.test.ts @@ -212,9 +212,9 @@ describe('version compatibility detection', () => { throw new Error('Some fetch related error') }) await expect( - getCompatibilityData('some-package', 'latest') + getCompatibilityData('some-package', 'latest'), ).rejects.toThrowErrorMatchingInlineSnapshot( - `[Error: Some fetch related error]` + `[Error: Some fetch related error]`, ) // Mock the json parsing to throw an error @@ -227,9 +227,9 @@ describe('version compatibility detection', () => { }) await expect( - getCompatibilityData('some-package', 'latest') + getCompatibilityData('some-package', 'latest'), ).rejects.toThrowErrorMatchingInlineSnapshot( - `[Error: Some json parsing error]` + `[Error: Some json parsing error]`, ) }) @@ -245,25 +245,25 @@ describe('version compatibility detection', () => { }) await expect( - getCompatibilityData('some-package', 'latest') + getCompatibilityData('some-package', 'latest'), ).rejects.toThrowErrorMatchingInlineSnapshot( - `[Error: Some packument related error]` + `[Error: Some packument related error]`, ) }) test('throws if preferred version is not found', async () => { await expect( - getCompatibilityData('@scope/package-name', '0.0.4') + getCompatibilityData('@scope/package-name', '0.0.4'), ).rejects.toThrowErrorMatchingInlineSnapshot( - `[Error: The package '@scope/package-name' does not have a version '0.0.4']` + `[Error: The package '@scope/package-name' does not have a version '0.0.4']`, ) }) test('throws if preferred tag is not found', async () => { await expect( - getCompatibilityData('@scope/package-name', 'next') + getCompatibilityData('@scope/package-name', 'next'), ).rejects.toThrowErrorMatchingInlineSnapshot( - `[Error: The package '@scope/package-name' does not have a tag 'next']` + `[Error: The package '@scope/package-name' does not have a tag 'next']`, ) }) @@ -280,9 +280,9 @@ describe('version compatibility detection', () => { }) await expect( - getCompatibilityData('@scope/package-name', 'latest') + getCompatibilityData('@scope/package-name', 'latest'), ).rejects.toThrowErrorMatchingInlineSnapshot( - `[Error: The package '@scope/package-name' does not have a tag 'latest']` + `[Error: The package '@scope/package-name' does not have a tag 'latest']`, ) }) @@ -323,7 +323,7 @@ describe('version compatibility detection', () => { tag: 'latest', version: '0.0.3', }, - } + }, ) vi.spyOn(fs, 'readFileSync').mockImplementation(() => { @@ -344,7 +344,7 @@ describe('version compatibility detection', () => { tag: undefined, version: '0.0.2', }, - } + }, ) }) @@ -358,9 +358,9 @@ describe('version compatibility detection', () => { }) expect( - getCompatibilityData('@scope/package-name', 'latest') + getCompatibilityData('@scope/package-name', 'latest'), ).rejects.toThrowErrorMatchingInlineSnapshot( - `[Error: No compatible version of '@scope/package-name' was found]` + `[Error: No compatible version of '@scope/package-name' was found]`, ) }) }) diff --git a/packages/cli-helpers/src/lib/index.ts b/packages/cli-helpers/src/lib/index.ts index a9676cd33a1a..d0529e9136d9 100644 --- a/packages/cli-helpers/src/lib/index.ts +++ b/packages/cli-helpers/src/lib/index.ts @@ -62,7 +62,7 @@ export const getPrettierOptions = async () => { // Make this work with --cwd options.tailwindConfig = path.join( process.env.RWJS_CWD ?? process.cwd(), - options.tailwindConfig + options.tailwindConfig, ) } @@ -74,7 +74,7 @@ export const getPrettierOptions = async () => { export const prettify = async ( templateFilename: string, - renderedTemplate: string + renderedTemplate: string, ): Promise => { // We format .js and .css templates, we need to tell prettier which parser // we're using. @@ -109,7 +109,7 @@ export const writeFile = ( task: ListrTaskWrapper = {} as ListrTaskWrapper< never, Renderer - > + >, ) => { const { base } = getPaths() task.title = `Writing \`./${path.relative(base, target)}\`` @@ -138,7 +138,7 @@ export const writeFile = ( */ export const writeFilesTask = ( files: Record, - options: { existingFiles: ExistingFiles } + options: { existingFiles: ExistingFiles }, ) => { const { base } = getPaths() @@ -153,11 +153,11 @@ export const writeFilesTask = ( task: ListrTaskWrapper< never, ListrGetRendererClassFromValue - > + >, ) => { return writeFile(file, contents, options, task) }, } - }) + }), ) } diff --git a/packages/cli-helpers/src/lib/project.ts b/packages/cli-helpers/src/lib/project.ts index 8c79ffff5d29..88a29412c584 100644 --- a/packages/cli-helpers/src/lib/project.ts +++ b/packages/cli-helpers/src/lib/project.ts @@ -72,7 +72,7 @@ export const updateTomlConfig = (packageName: string) => { } } else if (cliSection.plugins) { const packageExists = cliSection.plugins.some( - (plugin) => plugin.package === packageName + (plugin) => plugin.package === packageName, ) if (!packageExists) { @@ -180,7 +180,7 @@ export const setRedwoodCWD = (cwd?: string) => { const redwoodTOMLPath = findUp('redwood.toml', process.cwd()) if (!redwoodTOMLPath) { throw new Error( - `Couldn't find up a "redwood.toml" file from ${process.cwd()}` + `Couldn't find up a "redwood.toml" file from ${process.cwd()}`, ) } if (redwoodTOMLPath) { @@ -202,7 +202,7 @@ export const setRedwoodCWD = (cwd?: string) => { export function setTomlSetting( section: keyof Config, setting: string, - value: string | boolean | number + value: string | boolean | number, ) { const redwoodTomlPath = getConfigPath() const originalTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8') @@ -260,7 +260,7 @@ export function setTomlSetting( if (inSection && !updateExistingValue) { for (const existingSectionSetting of existingSectionSettings) { const matches = line.match( - new RegExp(`^(\\s*)${existingSectionSetting}\\s*=`, 'i') + new RegExp(`^(\\s*)${existingSectionSetting}\\s*=`, 'i'), ) if (!updateExistingValue && matches) { @@ -291,7 +291,7 @@ export function setTomlSetting( // find a commented value instead if (!updateExistingValue) { const matchesComment = line.match( - new RegExp(`^(\\s*)#(\\s*)${setting}\\s*=`, 'i') + new RegExp(`^(\\s*)#(\\s*)${setting}\\s*=`, 'i'), ) if (matchesComment) { @@ -315,7 +315,7 @@ export function setTomlSetting( tomlLines.splice( insertionIndex, updateExistingValue || updateExistingCommentedValue ? 1 : 0, - `${indentation}${setting} = ${value}` + `${indentation}${setting} = ${value}`, ) newTomlContent = tomlLines.join('\n') diff --git a/packages/cli-helpers/src/lib/version.ts b/packages/cli-helpers/src/lib/version.ts index a0ec4fec0ed2..6f6059a26f38 100644 --- a/packages/cli-helpers/src/lib/version.ts +++ b/packages/cli-helpers/src/lib/version.ts @@ -7,7 +7,7 @@ import { getPaths } from '@redwoodjs/project-config' function getCorrespondingTag( version: string, - distTags: Record + distTags: Record, ) { return Object.entries(distTags).find(([_, v]) => v === version)?.[0] } @@ -22,13 +22,13 @@ function getCorrespondingTag( */ export async function getCompatibilityData( packageName: string, - preferredVersionOrTag: string + preferredVersionOrTag: string, ) { // Get the project's version of RedwoodJS from the root package.json's @redwoodjs/core dev dependency const projectPackageJson = JSON.parse( fs.readFileSync(path.join(getPaths().base, 'package.json'), { encoding: 'utf8', - }) + }), ) const projectRedwoodVersion = projectPackageJson.devDependencies['@redwoodjs/core'] @@ -51,13 +51,13 @@ export async function getCompatibilityData( if (isUsingTag) { if (packument['dist-tags'][preferredVersionOrTag] === undefined) { throw new Error( - `The package '${packageName}' does not have a tag '${preferredVersionOrTag}'` + `The package '${packageName}' does not have a tag '${preferredVersionOrTag}'`, ) } } else { if (packument.versions[preferredVersionOrTag] === undefined) { throw new Error( - `The package '${packageName}' does not have a version '${preferredVersionOrTag}'` + `The package '${packageName}' does not have a version '${preferredVersionOrTag}'`, ) } } diff --git a/packages/cli-helpers/src/telemetry/index.ts b/packages/cli-helpers/src/telemetry/index.ts index 6e32cd251887..3adbadca2aa3 100644 --- a/packages/cli-helpers/src/telemetry/index.ts +++ b/packages/cli-helpers/src/telemetry/index.ts @@ -13,7 +13,7 @@ type TelemetryAttributes = { */ export function recordTelemetryAttributes( attributes: TelemetryAttributes, - span?: Span + span?: Span, ) { const spanToRecord = span ?? opentelemetry.trace.getActiveSpan() if (spanToRecord === undefined) { diff --git a/packages/cli-packages/dataMigrate/dist.test.ts b/packages/cli-packages/dataMigrate/dist.test.ts index 10a98623da00..63ac315739b9 100644 --- a/packages/cli-packages/dataMigrate/dist.test.ts +++ b/packages/cli-packages/dataMigrate/dist.test.ts @@ -22,7 +22,7 @@ describe('dist', () => { it('starts with shebang', () => { const binFileContent = fs.readFileSync( path.join(distPath, 'bin.js'), - 'utf-8' + 'utf-8', ) binFileContent.startsWith('#!/usr/bin/env node') }) diff --git a/packages/cli-packages/dataMigrate/src/__tests__/install.test.ts b/packages/cli-packages/dataMigrate/src/__tests__/install.test.ts index 378cb0eef95e..7ec340af1d5a 100644 --- a/packages/cli-packages/dataMigrate/src/__tests__/install.test.ts +++ b/packages/cli-packages/dataMigrate/src/__tests__/install.test.ts @@ -8,7 +8,7 @@ jest.mock( () => ({ handler: jest.fn(), }), - { virtual: true } + { virtual: true }, ) describe('install', () => { @@ -21,7 +21,7 @@ describe('install', () => { it("`command` and `description` haven't unintentionally changed", () => { expect(installCommand.command).toMatchInlineSnapshot(`"install"`) expect(installCommand.description).toMatchInlineSnapshot( - `"Add the RW_DataMigration model to your schema"` + `"Add the RW_DataMigration model to your schema"`, ) }) @@ -38,12 +38,12 @@ describe('install', () => { // to avoid having to match control characters that might not even always // be there expect(yargs.epilogue).toHaveBeenCalledWith( - expect.stringMatching(/Also see the .*Redwood CLI Reference.*/) + expect.stringMatching(/Also see the .*Redwood CLI Reference.*/), ) expect(yargs.epilogue).toHaveBeenCalledWith( expect.stringMatching( - /https:\/\/redwoodjs\.com\/docs\/cli-commands#datamigrate-install/ - ) + /https:\/\/redwoodjs\.com\/docs\/cli-commands#datamigrate-install/, + ), ) }) diff --git a/packages/cli-packages/dataMigrate/src/__tests__/installHandler.test.ts b/packages/cli-packages/dataMigrate/src/__tests__/installHandler.test.ts index 089c4ce984a2..7f2968eef075 100644 --- a/packages/cli-packages/dataMigrate/src/__tests__/installHandler.test.ts +++ b/packages/cli-packages/dataMigrate/src/__tests__/installHandler.test.ts @@ -38,7 +38,7 @@ describe('installHandler', () => { it("the `createDatabaseMigrationCommand` hasn't unintentionally changed", () => { expect(createDatabaseMigrationCommand).toMatchInlineSnapshot( - `"yarn rw prisma migrate dev --name create_data_migrations --create-only"` + `"yarn rw prisma migrate dev --name create_data_migrations --create-only"`, ) }) @@ -55,7 +55,7 @@ describe('installHandler', () => { }, }, }, - redwoodProjectPath + redwoodProjectPath, ) console.log = jest.fn() @@ -66,7 +66,7 @@ describe('installHandler', () => { expect(fs.readdirSync(dataMigrationsPath)).toEqual(['.keep']) expect(fs.readFileSync(getPaths().api.dbSchema, 'utf-8')).toMatch( - RW_DATA_MIGRATION_MODEL + RW_DATA_MIGRATION_MODEL, ) expect(execa.command).toHaveBeenCalledWith(createDatabaseMigrationCommand, { cwd: getPaths().base, diff --git a/packages/cli-packages/dataMigrate/src/__tests__/up.test.ts b/packages/cli-packages/dataMigrate/src/__tests__/up.test.ts index 06ad05baa883..b010371b608c 100644 --- a/packages/cli-packages/dataMigrate/src/__tests__/up.test.ts +++ b/packages/cli-packages/dataMigrate/src/__tests__/up.test.ts @@ -12,7 +12,7 @@ jest.mock( () => ({ handler: jest.fn(), }), - { virtual: true } + { virtual: true }, ) describe('up', () => { @@ -20,7 +20,7 @@ describe('up', () => { expect(upCommand).toHaveProperty('command', 'up') expect(upCommand).toHaveProperty( 'description', - 'Run any outstanding Data Migrations against the database' + 'Run any outstanding Data Migrations against the database', ) expect(upCommand).toHaveProperty('builder') expect(upCommand).toHaveProperty('handler') @@ -34,7 +34,7 @@ describe('up', () => { dist: {}, }, }, - '/redwood-app' + '/redwood-app', ) process.env.RWJS_CWD = '/redwood-app' diff --git a/packages/cli-packages/dataMigrate/src/__tests__/upHandler.test.ts b/packages/cli-packages/dataMigrate/src/__tests__/upHandler.test.ts index db19cf845c78..8701bed8689d 100644 --- a/packages/cli-packages/dataMigrate/src/__tests__/upHandler.test.ts +++ b/packages/cli-packages/dataMigrate/src/__tests__/upHandler.test.ts @@ -48,7 +48,7 @@ jest.mock( }, } }, - { virtual: true } + { virtual: true }, ) jest.mock( @@ -68,7 +68,7 @@ jest.mock( }, } }, - { virtual: true } + { virtual: true }, ) jest.mock( @@ -78,7 +78,7 @@ jest.mock( }, { virtual: true, - } + }, ) jest.mock( @@ -88,7 +88,7 @@ jest.mock( }, { virtual: true, - } + }, ) jest.mock( @@ -102,7 +102,7 @@ jest.mock( }, { virtual: true, - } + }, ) jest.mock( @@ -116,7 +116,7 @@ jest.mock( }, { virtual: true, - } + }, ) jest.mock( @@ -126,7 +126,7 @@ jest.mock( }, { virtual: true, - } + }, ) jest.mock( @@ -136,7 +136,7 @@ jest.mock( }, { virtual: true, - } + }, ) const RWJS_CWD = process.env.RWJS_CWD @@ -183,7 +183,7 @@ describe('upHandler', () => { }, }, }, - redwoodProjectPath + redwoodProjectPath, ) await handler({ @@ -192,7 +192,7 @@ describe('upHandler', () => { }) expect(consoleInfoMock.mock.calls[0][0]).toMatch( - NO_PENDING_MIGRATIONS_MESSAGE + NO_PENDING_MIGRATIONS_MESSAGE, ) }) @@ -215,7 +215,7 @@ describe('upHandler', () => { }, }, }, - redwoodProjectPath + redwoodProjectPath, ) await handler({ @@ -224,7 +224,7 @@ describe('upHandler', () => { }) expect(consoleInfoMock.mock.calls[0][0]).toMatch( - NO_PENDING_MIGRATIONS_MESSAGE + NO_PENDING_MIGRATIONS_MESSAGE, ) }) @@ -257,7 +257,7 @@ describe('upHandler', () => { }, }, }, - redwoodProjectPath + redwoodProjectPath, ) await handler({ @@ -270,13 +270,13 @@ describe('upHandler', () => { process.exitCode = 0 expect(consoleInfoMock.mock.calls[0][0]).toMatch( - '1 data migration(s) completed successfully.' + '1 data migration(s) completed successfully.', ) expect(consoleErrorMock.mock.calls[1][0]).toMatch( - '1 data migration(s) exited with errors.' + '1 data migration(s) exited with errors.', ) expect(consoleWarnMock.mock.calls[0][0]).toMatch( - '1 data migration(s) skipped due to previous error' + '1 data migration(s) skipped due to previous error', ) }) }) diff --git a/packages/cli-packages/dataMigrate/src/commands/install.ts b/packages/cli-packages/dataMigrate/src/commands/install.ts index 001245a3406d..31ce69dfc8e5 100644 --- a/packages/cli-packages/dataMigrate/src/commands/install.ts +++ b/packages/cli-packages/dataMigrate/src/commands/install.ts @@ -8,8 +8,8 @@ export function builder(yargs: Argv): Argv { return yargs.epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#datamigrate-install' - )}` + 'https://redwoodjs.com/docs/cli-commands#datamigrate-install', + )}`, ) } diff --git a/packages/cli-packages/dataMigrate/src/commands/installHandler.ts b/packages/cli-packages/dataMigrate/src/commands/installHandler.ts index 5bdda934716a..e274a641c1a4 100644 --- a/packages/cli-packages/dataMigrate/src/commands/installHandler.ts +++ b/packages/cli-packages/dataMigrate/src/commands/installHandler.ts @@ -18,7 +18,7 @@ export async function handler() { task() { fs.outputFileSync( path.join(redwoodProjectPaths.api.dataMigrations, '.keep'), - '' + '', ) }, }, @@ -31,8 +31,8 @@ export async function handler() { fs.writeFileSync( dbSchemaFilePath, [dbSchemaFileContent.trim(), '', RW_DATA_MIGRATION_MODEL, ''].join( - '\n' - ) + '\n', + ), ) }, }, @@ -49,7 +49,7 @@ export async function handler() { // is the only one I've found to work. So we set it just during testing. { renderer: process.env.NODE_ENV === 'test' ? 'verbose' : 'default', - } + }, ) try { diff --git a/packages/cli-packages/dataMigrate/src/commands/up.ts b/packages/cli-packages/dataMigrate/src/commands/up.ts index 314082e0eb52..d20d8d004bb3 100644 --- a/packages/cli-packages/dataMigrate/src/commands/up.ts +++ b/packages/cli-packages/dataMigrate/src/commands/up.ts @@ -26,8 +26,8 @@ export function builder(yargs: Argv): Argv { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#datamigrate-up' - )}` + 'https://redwoodjs.com/docs/cli-commands#datamigrate-up', + )}`, ) } diff --git a/packages/cli-packages/dataMigrate/src/commands/upHandler.ts b/packages/cli-packages/dataMigrate/src/commands/upHandler.ts index 732648ec4257..b7a8f874911d 100644 --- a/packages/cli-packages/dataMigrate/src/commands/upHandler.ts +++ b/packages/cli-packages/dataMigrate/src/commands/upHandler.ts @@ -20,7 +20,7 @@ export async function handler({ if (importDbClientFromDist) { if (!fs.existsSync(distPath)) { console.warn( - `Can't find api dist at ${distPath}. You may need to build first: yarn rw build api` + `Can't find api dist at ${distPath}. You may need to build first: yarn rw build api`, ) process.exitCode = 1 return @@ -32,8 +32,8 @@ export async function handler({ console.error( `Can't find db.js at ${distLibDbPath}. Redwood expects the db.js file to be in the ${path.join( distPath, - 'lib' - )} directory` + 'lib', + )} directory`, ) process.exitCode = 1 return @@ -78,7 +78,7 @@ export async function handler({ try { const { startedAt, finishedAt } = await runDataMigration( db, - dataMigration.path + dataMigration.path, ) counters.run++ await recordDataMigration(db, { @@ -90,7 +90,7 @@ export async function handler({ } catch (e) { counters.error++ console.error( - c.error(`Error in data migration: ${(e as Error).message}`) + c.error(`Error in data migration: ${(e as Error).message}`), ) } }, @@ -137,8 +137,8 @@ async function getPendingDataMigrations(db: PrismaClient) { // There may be a `.keep` file in the data migrations directory. .filter((dataMigrationFileName) => ['js', '.ts'].some((extension) => - dataMigrationFileName.endsWith(extension) - ) + dataMigrationFileName.endsWith(extension), + ), ) .map((dataMigrationFileName) => { const [version] = dataMigrationFileName.split('-') @@ -152,10 +152,10 @@ async function getPendingDataMigrations(db: PrismaClient) { const ranDataMigrations: DataMigration[] = await db.rW_DataMigration.findMany( { orderBy: { version: 'asc' }, - } + }, ) const ranDataMigrationVersions = ranDataMigrations.map((dataMigration) => - dataMigration.version.toString() + dataMigration.version.toString(), ) const pendingDataMigrations = dataMigrations @@ -172,7 +172,7 @@ async function getPendingDataMigrations(db: PrismaClient) { */ function sortDataMigrationsByVersion( dataMigrationA: { version: string }, - dataMigrationB: { version: string } + dataMigrationB: { version: string }, ) { const aVersion = parseInt(dataMigrationA.version) const bVersion = parseInt(dataMigrationB.version) @@ -204,7 +204,7 @@ export const NO_PENDING_MIGRATIONS_MESSAGE = */ async function recordDataMigration( db: PrismaClient, - { version, name, startedAt, finishedAt }: DataMigration + { version, name, startedAt, finishedAt }: DataMigration, ) { await db.rW_DataMigration.create({ data: { version, name, startedAt, finishedAt }, @@ -221,19 +221,19 @@ function reportDataMigrations(counters: { }) { if (counters.run) { console.info( - c.green(`${counters.run} data migration(s) completed successfully.`) + c.green(`${counters.run} data migration(s) completed successfully.`), ) } if (counters.error) { console.error( - c.error(`${counters.error} data migration(s) exited with errors.`) + c.error(`${counters.error} data migration(s) exited with errors.`), ) } if (counters.skipped) { console.warn( c.warning( - `${counters.skipped} data migration(s) skipped due to previous error.` - ) + `${counters.skipped} data migration(s) skipped due to previous error.`, + ), ) } } diff --git a/packages/cli-packages/dataMigrate/src/index.ts b/packages/cli-packages/dataMigrate/src/index.ts index b01fcdc32622..d49e6272984a 100644 --- a/packages/cli-packages/dataMigrate/src/index.ts +++ b/packages/cli-packages/dataMigrate/src/index.ts @@ -26,8 +26,8 @@ function builder(yargs: Argv) { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#datamigrate' - )}` + 'https://redwoodjs.com/docs/cli-commands#datamigrate', + )}`, ) } diff --git a/packages/cli-packages/storybook/src/commands/storybook.ts b/packages/cli-packages/storybook/src/commands/storybook.ts index 50a6285ccb68..50a3da337439 100644 --- a/packages/cli-packages/storybook/src/commands/storybook.ts +++ b/packages/cli-packages/storybook/src/commands/storybook.ts @@ -20,7 +20,7 @@ export const defaultOptions: StorybookYargsOptions = { } export function builder( - yargs: Argv + yargs: Argv, ): Argv { return yargs .option('build', { @@ -58,8 +58,8 @@ export function builder( .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#storybook' - )}` + 'https://redwoodjs.com/docs/cli-commands#storybook', + )}`, ) } diff --git a/packages/cli-packages/storybook/src/commands/storybookHandler.ts b/packages/cli-packages/storybook/src/commands/storybookHandler.ts index 9433cb62080a..31deb4773958 100644 --- a/packages/cli-packages/storybook/src/commands/storybookHandler.ts +++ b/packages/cli-packages/storybook/src/commands/storybookHandler.ts @@ -26,7 +26,7 @@ export async function handler({ // they install Storybook so that the real types come through. fs.rmSync( path.join(getPaths().generated.types.includes, 'web-storybook.d.ts'), - { force: true } + { force: true }, ) // Check for conflicting options @@ -37,8 +37,8 @@ export async function handler({ if (build && open) { console.warn( c.warning( - 'Warning: --open option has no effect when running Storybook build' - ) + 'Warning: --open option has no effect when running Storybook build', + ), ) } @@ -53,11 +53,11 @@ export async function handler({ // Create the `MockServiceWorker.js` file. See https://mswjs.io/docs/cli/init. await execa.command( `yarn msw init "${staticAssetsFolder}" --no-save`, - execaOptions + execaOptions, ) const storybookConfigPath = path.dirname( - require.resolve('@redwoodjs/testing/config/storybook/main.js') + require.resolve('@redwoodjs/testing/config/storybook/main.js'), ) let command = '' diff --git a/packages/cli/src/__tests__/cwd.test.js b/packages/cli/src/__tests__/cwd.test.js index 0c9347877030..0915b1589969 100644 --- a/packages/cli/src/__tests__/cwd.test.js +++ b/packages/cli/src/__tests__/cwd.test.js @@ -27,7 +27,7 @@ describe('The CLI sets `cwd` correctly', () => { expect(status).toBe(1) expect(stdout).toBe('') expect(stderr).toMatchInlineSnapshot( - `"Couldn't find a "redwood.toml" file in __fixtures__"` + `"Couldn't find a "redwood.toml" file in __fixtures__"`, ) }) }) @@ -57,7 +57,7 @@ describe('The CLI sets `cwd` correctly', () => { expect(status).toBe(1) expect(stdout).toBe('') expect(stderr).toMatchInlineSnapshot( - `"Couldn't find a "redwood.toml" file in __fixtures__"` + `"Couldn't find a "redwood.toml" file in __fixtures__"`, ) }) }) @@ -71,7 +71,7 @@ describe('The CLI sets `cwd` correctly', () => { ...process.env, RWJS_CWD: '/ignored/path', }, - } + }, ) expect(status).toBe(0) @@ -87,13 +87,13 @@ describe('The CLI sets `cwd` correctly', () => { ...process.env, RWJS_CWD: path.join('__fixtures__', 'test-project'), }, - } + }, ) expect(status).toBe(1) expect(stdout).toBe('') expect(stderr).toMatchInlineSnapshot( - `"Couldn't find a "redwood.toml" file in __fixtures__"` + `"Couldn't find a "redwood.toml" file in __fixtures__"`, ) }) }) diff --git a/packages/cli/src/__tests__/loadEnvFiles.test.js b/packages/cli/src/__tests__/loadEnvFiles.test.js index 07c8542d93c1..0628758cfcbd 100644 --- a/packages/cli/src/__tests__/loadEnvFiles.test.js +++ b/packages/cli/src/__tests__/loadEnvFiles.test.js @@ -45,7 +45,7 @@ describe('loadEnvFiles', () => { expect(process.env).toHaveProperty( 'PROD_DATABASE_URL', - 'postgresql://user:password@localhost:5432/myproddb' + 'postgresql://user:password@localhost:5432/myproddb', ) }) @@ -64,11 +64,11 @@ describe('loadEnvFiles', () => { expect(process.env).toHaveProperty( 'DEV_DATABASE_URL', - 'postgresql://user:password@localhost:5432/mydevdb' + 'postgresql://user:password@localhost:5432/mydevdb', ) expect(process.env).toHaveProperty( 'PROD_DATABASE_URL', - 'postgresql://user:password@localhost:5432/myproddb' + 'postgresql://user:password@localhost:5432/myproddb', ) }) @@ -84,7 +84,7 @@ describe('loadEnvFiles', () => { expect(process.env).toHaveProperty( 'DATABASE_URL', - 'postgresql://user:password@localhost:5432/mycollisiondb' + 'postgresql://user:password@localhost:5432/mycollisiondb', ) expect(process.env).toHaveProperty('TEST_BASE', '1') expect(process.env).toHaveProperty('TEST_COLLISION', '1') @@ -102,7 +102,7 @@ describe('loadEnvFiles', () => { expect(process.env).toHaveProperty( 'PROD_DATABASE_URL', - 'postgresql://user:password@localhost:5432/bazinga' + 'postgresql://user:password@localhost:5432/bazinga', ) expect(process.env).toHaveProperty('BAZINGA', '1') }) @@ -119,7 +119,7 @@ describe('loadEnvFiles', () => { expect(process.env).toHaveProperty( 'PROD_DATABASE_URL', - 'postgresql://user:password@localhost:5432/myproddb' + 'postgresql://user:password@localhost:5432/myproddb', ) expect(process.env).toHaveProperty('BAZINGA', '1') }) diff --git a/packages/cli/src/__tests__/plugin.test.js b/packages/cli/src/__tests__/plugin.test.js index c11b4fff73a3..e1638acf6f7b 100644 --- a/packages/cli/src/__tests__/plugin.test.js +++ b/packages/cli/src/__tests__/plugin.test.js @@ -63,7 +63,7 @@ describe('command information caching', () => { test('returns the correct cache when a local cache exists', () => { const anExistingDefaultCacheEntryKey = Object.keys( - pluginLib.PLUGIN_CACHE_DEFAULT + pluginLib.PLUGIN_CACHE_DEFAULT, )[0] const anExistingDefaultCacheEntry = { [anExistingDefaultCacheEntryKey]: { @@ -204,7 +204,7 @@ describe('plugin loading', () => { ], } }, - { virtual: true } + { virtual: true }, ) vol.fromJSON({ ['commandCache.json']: JSON.stringify({ @@ -234,17 +234,17 @@ describe('plugin loading', () => { expect(pluginLib.loadPluginPackage).toHaveBeenCalledWith( '@redwoodjs/cli-some-package-not-in-cache', undefined, - true + true, ) // Should have saved the cache with the new package expect(pluginLib.saveCommandCache).toHaveBeenCalledTimes(1) const knownPlugins = getConfig.mock.results[0].value.experimental.cli.plugins.map( - (plugin) => plugin.package + (plugin) => plugin.package, ) const saveCommandCacheArg = Object.entries( - pluginLib.saveCommandCache.mock.calls[0][0] + pluginLib.saveCommandCache.mock.calls[0][0], ).filter(([key]) => knownPlugins.includes(key)) expect(saveCommandCacheArg).toMatchSnapshot() @@ -264,7 +264,7 @@ describe('plugin loading', () => { getConfig.mockRestore() process.argv = originalArgv - } + }, ) test.each([['--help'], ['-h'], ['']])( @@ -304,7 +304,7 @@ describe('plugin loading', () => { ], } }, - { virtual: true } + { virtual: true }, ) vol.fromJSON({ ['commandCache.json']: JSON.stringify({ @@ -334,17 +334,17 @@ describe('plugin loading', () => { expect(pluginLib.loadPluginPackage).toHaveBeenCalledWith( '@redwoodjs/cli-some-package-not-in-cache', undefined, - true + true, ) // Should have saved the cache with the new package expect(pluginLib.saveCommandCache).toHaveBeenCalledTimes(1) const knownPlugins = getConfig.mock.results[0].value.experimental.cli.plugins.map( - (plugin) => plugin.package + (plugin) => plugin.package, ) const saveCommandCacheArg = Object.entries( - pluginLib.saveCommandCache.mock.calls[0][0] + pluginLib.saveCommandCache.mock.calls[0][0], ).filter(([key]) => knownPlugins.includes(key)) expect(saveCommandCacheArg).toMatchSnapshot() @@ -364,7 +364,7 @@ describe('plugin loading', () => { getConfig.mockRestore() process.argv = originalArgv - } + }, ) test.each([['--help'], ['-h'], ['']])( @@ -404,7 +404,7 @@ describe('plugin loading', () => { ], } }, - { virtual: true } + { virtual: true }, ) vol.fromJSON({ ['commandCache.json']: JSON.stringify({ @@ -437,10 +437,10 @@ describe('plugin loading', () => { expect(pluginLib.saveCommandCache).toHaveBeenCalledTimes(1) const knownPlugins = getConfig.mock.results[0].value.experimental.cli.plugins.map( - (plugin) => plugin.package + (plugin) => plugin.package, ) const saveCommandCacheArg = Object.entries( - pluginLib.saveCommandCache.mock.calls[0][0] + pluginLib.saveCommandCache.mock.calls[0][0], ).filter(([key]) => knownPlugins.includes(key)) expect(saveCommandCacheArg).toMatchSnapshot() @@ -454,7 +454,7 @@ describe('plugin loading', () => { getConfig.mockRestore() process.argv = originalArgv - } + }, ) test('correct loading for unknown namespace (no command)', async () => { @@ -492,7 +492,7 @@ describe('plugin loading', () => { ], } }, - { virtual: true } + { virtual: true }, ) vol.fromJSON({ ['commandCache.json']: JSON.stringify({ @@ -522,17 +522,17 @@ describe('plugin loading', () => { expect(pluginLib.loadPluginPackage).toHaveBeenCalledWith( '@redwoodjs/cli-some-package-not-in-cache', undefined, - true + true, ) // Should have saved the cache with the new package expect(pluginLib.saveCommandCache).toHaveBeenCalledTimes(1) const knownPlugins = getConfig.mock.results[0].value.experimental.cli.plugins.map( - (plugin) => plugin.package + (plugin) => plugin.package, ) const saveCommandCacheArg = Object.entries( - pluginLib.saveCommandCache.mock.calls[0][0] + pluginLib.saveCommandCache.mock.calls[0][0], ).filter(([key]) => knownPlugins.includes(key)) expect(saveCommandCacheArg).toMatchSnapshot() @@ -588,7 +588,7 @@ describe('plugin loading', () => { ], } }, - { virtual: true } + { virtual: true }, ) vol.fromJSON({ ['commandCache.json']: JSON.stringify({ @@ -618,17 +618,17 @@ describe('plugin loading', () => { expect(pluginLib.loadPluginPackage).toHaveBeenCalledWith( '@redwoodjs/cli-some-package-not-in-cache', undefined, - true + true, ) // Should have saved the cache with the new package expect(pluginLib.saveCommandCache).toHaveBeenCalledTimes(1) const knownPlugins = getConfig.mock.results[0].value.experimental.cli.plugins.map( - (plugin) => plugin.package + (plugin) => plugin.package, ) const saveCommandCacheArg = Object.entries( - pluginLib.saveCommandCache.mock.calls[0][0] + pluginLib.saveCommandCache.mock.calls[0][0], ).filter(([key]) => knownPlugins.includes(key)) expect(saveCommandCacheArg).toMatchSnapshot() @@ -685,7 +685,7 @@ describe('plugin loading', () => { ], } }, - { virtual: true } + { virtual: true }, ) vol.fromJSON({ ['commandCache.json']: JSON.stringify({ @@ -734,17 +734,17 @@ describe('plugin loading', () => { expect(pluginLib.loadPluginPackage).toHaveBeenCalledWith( '@redwoodjs/cli-some-package', undefined, - true + true, ) // Should have saved the cache with the new package expect(pluginLib.saveCommandCache).toHaveBeenCalledTimes(1) const knownPlugins = getConfig.mock.results[0].value.experimental.cli.plugins.map( - (plugin) => plugin.package + (plugin) => plugin.package, ) const saveCommandCacheArg = Object.entries( - pluginLib.saveCommandCache.mock.calls[0][0] + pluginLib.saveCommandCache.mock.calls[0][0], ).filter(([key]) => knownPlugins.includes(key)) expect(saveCommandCacheArg).toMatchSnapshot() @@ -790,7 +790,7 @@ describe('plugin loading', () => { ], } }, - { virtual: true } + { virtual: true }, ) vi.mock( '@redwoodjs/cli-some-package', @@ -805,7 +805,7 @@ describe('plugin loading', () => { ], } }, - { virtual: true } + { virtual: true }, ) vol.fromJSON({ ['commandCache.json']: JSON.stringify({}), @@ -856,22 +856,22 @@ describe('plugin loading', () => { expect(pluginLib.loadPluginPackage).toHaveBeenCalledWith( '@redwoodjs/cli-some-package', undefined, - true + true, ) expect(pluginLib.loadPluginPackage).toHaveBeenCalledWith( '@redwoodjs/cli-some-package-not-in-cache', undefined, - true + true, ) // Should have saved the cache with the new package expect(pluginLib.saveCommandCache).toHaveBeenCalledTimes(1) const knownPlugins = getConfig.mock.results[0].value.experimental.cli.plugins.map( - (plugin) => plugin.package + (plugin) => plugin.package, ) const saveCommandCacheArg = Object.entries( - pluginLib.saveCommandCache.mock.calls[0][0] + pluginLib.saveCommandCache.mock.calls[0][0], ).filter(([key]) => knownPlugins.includes(key)) expect(saveCommandCacheArg).toMatchSnapshot() @@ -918,7 +918,7 @@ describe('plugin loading', () => { ], } }, - { virtual: true } + { virtual: true }, ) vol.fromJSON({ ['commandCache.json']: JSON.stringify({ @@ -982,17 +982,17 @@ describe('plugin loading', () => { expect(pluginLib.loadPluginPackage).toHaveBeenCalledWith( '@redwoodjs/cli-some-package-not-in-cache', undefined, - true + true, ) // Should have saved the cache with the new package expect(pluginLib.saveCommandCache).toHaveBeenCalledTimes(1) const knownPlugins = getConfig.mock.results[0].value.experimental.cli.plugins.map( - (plugin) => plugin.package + (plugin) => plugin.package, ) const saveCommandCacheArg = Object.entries( - pluginLib.saveCommandCache.mock.calls[0][0] + pluginLib.saveCommandCache.mock.calls[0][0], ).filter(([key]) => knownPlugins.includes(key)) expect(saveCommandCacheArg).toMatchSnapshot() @@ -1054,7 +1054,7 @@ describe('plugin loading', () => { ], } }, - { virtual: true } + { virtual: true }, ) vol.fromJSON({ ['commandCache.json']: JSON.stringify({ @@ -1103,17 +1103,17 @@ describe('plugin loading', () => { expect(pluginLib.loadPluginPackage).toHaveBeenCalledWith( '@bluewoodjs/cli-some-package', undefined, - true + true, ) // Should have saved the cache with the new package expect(pluginLib.saveCommandCache).toHaveBeenCalledTimes(1) const knownPlugins = getConfig.mock.results[0].value.experimental.cli.plugins.map( - (plugin) => plugin.package + (plugin) => plugin.package, ) const saveCommandCacheArg = Object.entries( - pluginLib.saveCommandCache.mock.calls[0][0] + pluginLib.saveCommandCache.mock.calls[0][0], ).filter(([key]) => knownPlugins.includes(key)) expect(saveCommandCacheArg).toMatchSnapshot() @@ -1198,22 +1198,22 @@ describe('plugin loading', () => { expect(pluginLib.loadPluginPackage).toHaveBeenCalledWith( '@bluewoodjs/cli-some-package', undefined, - true + true, ) expect(pluginLib.loadPluginPackage).toHaveBeenCalledWith( '@bluewoodjs/cli-some-package-second-example', undefined, - true + true, ) // Should have saved the cache with the new package expect(pluginLib.saveCommandCache).toHaveBeenCalledTimes(1) const knownPlugins = getConfig.mock.results[0].value.experimental.cli.plugins.map( - (plugin) => plugin.package + (plugin) => plugin.package, ) const saveCommandCacheArg = Object.entries( - pluginLib.saveCommandCache.mock.calls[0][0] + pluginLib.saveCommandCache.mock.calls[0][0], ).filter(([key]) => knownPlugins.includes(key)) expect(saveCommandCacheArg).toMatchSnapshot() @@ -1296,10 +1296,10 @@ describe('plugin loading', () => { expect(pluginLib.saveCommandCache).toHaveBeenCalledTimes(1) const knownPlugins = getConfig.mock.results[0].value.experimental.cli.plugins.map( - (plugin) => plugin.package + (plugin) => plugin.package, ) const saveCommandCacheArg = Object.entries( - pluginLib.saveCommandCache.mock.calls[0][0] + pluginLib.saveCommandCache.mock.calls[0][0], ).filter(([key]) => knownPlugins.includes(key)) expect(saveCommandCacheArg).toMatchSnapshot() diff --git a/packages/cli/src/commands/__tests__/build.test.js b/packages/cli/src/commands/__tests__/build.test.js index 8c257288207a..74736a2a52a0 100644 --- a/packages/cli/src/commands/__tests__/build.test.js +++ b/packages/cli/src/commands/__tests__/build.test.js @@ -74,6 +74,6 @@ test('Should run prerender for web', async () => { // because `detectPrerenderRoutes` is empty. expect(consoleSpy.mock.calls[0][0]).toBe('Starting prerendering...') expect(consoleSpy.mock.calls[1][0]).toMatch( - /You have not marked any routes to "prerender"/ + /You have not marked any routes to "prerender"/, ) }) diff --git a/packages/cli/src/commands/__tests__/dev.test.js b/packages/cli/src/commands/__tests__/dev.test.js index 8de1625bc3fe..e14ac9023546 100644 --- a/packages/cli/src/commands/__tests__/dev.test.js +++ b/packages/cli/src/commands/__tests__/dev.test.js @@ -111,11 +111,11 @@ describe('yarn rw dev', () => { // Uses absolute path, so not doing a snapshot expect(webCommand.command).toContain( - 'yarn cross-env NODE_ENV=development rw-vite-dev' + 'yarn cross-env NODE_ENV=development rw-vite-dev', ) expect(apiCommand.command.replace(/\s+/g, ' ')).toEqual( - 'yarn cross-env NODE_ENV=development NODE_OPTIONS="--enable-source-maps" yarn nodemon --quiet --watch "/mocked/project/redwood.toml" --exec "yarn rw-api-server-watch --port 8911 --debug-port 18911 | rw-log-formatter"' + 'yarn cross-env NODE_ENV=development NODE_OPTIONS="--enable-source-maps" yarn nodemon --quiet --watch "/mocked/project/redwood.toml" --exec "yarn rw-api-server-watch --port 8911 --debug-port 18911 | rw-log-formatter"', ) expect(generateCommand.command).toEqual('yarn rw-gen-watch') @@ -150,11 +150,11 @@ describe('yarn rw dev', () => { // Uses absolute path, so not doing a snapshot expect(webCommand.command).toContain( - 'yarn cross-env NODE_ENV=development rw-dev-fe' + 'yarn cross-env NODE_ENV=development rw-dev-fe', ) expect(apiCommand.command.replace(/\s+/g, ' ')).toEqual( - 'yarn cross-env NODE_ENV=development NODE_OPTIONS="--enable-source-maps" yarn nodemon --quiet --watch "/mocked/project/redwood.toml" --exec "yarn rw-api-server-watch --port 8911 --debug-port 18911 | rw-log-formatter"' + 'yarn cross-env NODE_ENV=development NODE_OPTIONS="--enable-source-maps" yarn nodemon --quiet --watch "/mocked/project/redwood.toml" --exec "yarn rw-api-server-watch --port 8911 --debug-port 18911 | rw-log-formatter"', ) expect(generateCommand.command).toEqual('yarn rw-gen-watch') @@ -186,7 +186,7 @@ describe('yarn rw dev', () => { const apiCommand = find(concurrentlyArgs, { name: 'api' }) expect(apiCommand.command.replace(/\s+/g, ' ')).toContain( - 'yarn rw-api-server-watch --port 8911 --debug-port 90909090' + 'yarn rw-api-server-watch --port 8911 --debug-port 90909090', ) }) @@ -242,7 +242,7 @@ describe('yarn rw dev', () => { const webCommand = find(concurrentlyArgs, { name: 'web' }) expect(webCommand.command).toContain( - 'yarn cross-env NODE_ENV=development rw-vite-dev' + 'yarn cross-env NODE_ENV=development rw-vite-dev', ) }) }) diff --git a/packages/cli/src/commands/__tests__/serve.test.js b/packages/cli/src/commands/__tests__/serve.test.js index 33bbefa8468b..0c7f342c1994 100644 --- a/packages/cli/src/commands/__tests__/serve.test.js +++ b/packages/cli/src/commands/__tests__/serve.test.js @@ -87,7 +87,7 @@ describe('yarn rw serve', () => { expect.objectContaining({ port: 5555, apiRootPath: expect.stringMatching(/^\/?funkyFunctions\/?$/), - }) + }), ) }) @@ -95,14 +95,14 @@ describe('yarn rw serve', () => { const parser = yargs().command('serve [side]', false, builder) await parser.parse( - 'serve api --port 5555 --rootPath funkyFunctions/nested/' + 'serve api --port 5555 --rootPath funkyFunctions/nested/', ) expect(apiServerCLIConfig.handler).toHaveBeenCalledWith( expect.objectContaining({ port: 5555, rootPath: expect.stringMatching(/^\/?funkyFunctions\/nested\/$/), - }) + }), ) }) @@ -115,7 +115,7 @@ describe('yarn rw serve', () => { expect.objectContaining({ port: 9898, socket: 'abc', - }) + }), ) }) }) diff --git a/packages/cli/src/commands/__tests__/test.test.js b/packages/cli/src/commands/__tests__/test.test.js index 3a3cef335395..e63ebb68cdf1 100644 --- a/packages/cli/src/commands/__tests__/test.test.js +++ b/packages/cli/src/commands/__tests__/test.test.js @@ -132,10 +132,10 @@ test('Passes values of other flags to jest', async () => { // Note that these below tests aren't the best, since they don't check for order // But I'm making sure only 2 extra params get passed expect(execa.mock.results[0].value.params).toEqual( - expect.arrayContaining(['--bazinga', false]) + expect.arrayContaining(['--bazinga', false]), ) expect(execa.mock.results[0].value.params).toEqual( - expect.arrayContaining(['--hello', 'world']) + expect.arrayContaining(['--hello', 'world']), ) }) diff --git a/packages/cli/src/commands/__tests__/type-check.test.js b/packages/cli/src/commands/__tests__/type-check.test.js index 8caa836b94d5..6306a1d2bb7e 100644 --- a/packages/cli/src/commands/__tests__/type-check.test.js +++ b/packages/cli/src/commands/__tests__/type-check.test.js @@ -111,6 +111,6 @@ test('Should generate prisma client', async () => { command: 'yarn tsc --noEmit --skipLibCheck', }) expect(runCommandTask.mock.results[0].value[0]).toMatch( - /.+(\\|\/)prisma(\\|\/)build(\\|\/)index.js.+/ + /.+(\\|\/)prisma(\\|\/)build(\\|\/)index.js.+/, ) }) diff --git a/packages/cli/src/commands/build.js b/packages/cli/src/commands/build.js index d38568f6ba96..445ea13ca63a 100644 --- a/packages/cli/src/commands/build.js +++ b/packages/cli/src/commands/build.js @@ -22,7 +22,7 @@ export const builder = (yargs) => { default: false, description: `Use ${terminalLink( 'Webpack Bundle Analyzer', - 'https://github.com/webpack-contrib/webpack-bundle-analyzer' + 'https://github.com/webpack-contrib/webpack-bundle-analyzer', )}`, type: 'boolean', }) @@ -64,8 +64,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#build' - )}` + 'https://redwoodjs.com/docs/cli-commands#build', + )}`, ) } diff --git a/packages/cli/src/commands/buildHandler.js b/packages/cli/src/commands/buildHandler.js index 9d3367d11ade..72e4ae8a599b 100644 --- a/packages/cli/src/commands/buildHandler.js +++ b/packages/cli/src/commands/buildHandler.js @@ -43,9 +43,9 @@ export const handler = async ({ console.log('Measuring Web Build Performance...') execa.sync( `yarn cross-env NODE_ENV=production webpack --config ${require.resolve( - '@redwoodjs/core/config/webpack.perf.js' + '@redwoodjs/core/config/webpack.perf.js', )}`, - { stdio: 'inherit', shell: true, cwd: rwjsPaths.web.base } + { stdio: 'inherit', shell: true, cwd: rwjsPaths.web.base }, ) // We do not want to continue building... return @@ -55,9 +55,9 @@ export const handler = async ({ console.log('Building Web Stats...') execa.sync( `yarn cross-env NODE_ENV=production webpack --config ${require.resolve( - '@redwoodjs/core/config/webpack.stats.js' + '@redwoodjs/core/config/webpack.stats.js', )}`, - { stdio: 'inherit', shell: true, cwd: rwjsPaths.web.base } + { stdio: 'inherit', shell: true, cwd: rwjsPaths.web.base }, ) // We do not want to continue building... return @@ -136,7 +136,7 @@ export const handler = async ({ // one in the future as a performance optimization. await execa( `node ${require.resolve( - '@redwoodjs/vite/bins/rw-vite-build.mjs' + '@redwoodjs/vite/bins/rw-vite-build.mjs', )} --webDir="${rwjsPaths.web.base}" --verbose=${verbose}`, { stdio: verbose ? 'inherit' : 'pipe', @@ -145,18 +145,18 @@ export const handler = async ({ // It won't change process.cwd for anything else here, in this // process cwd: rwjsPaths.web.base, - } + }, ) } else { await execa( `yarn cross-env NODE_ENV=production webpack --config ${require.resolve( - '@redwoodjs/core/config/webpack.production.js' + '@redwoodjs/core/config/webpack.production.js', )}`, { stdio: verbose ? 'inherit' : 'pipe', shell: true, cwd: rwjsPaths.web.base, - } + }, ) } @@ -168,7 +168,7 @@ export const handler = async ({ fs.copyFileSync( indexHtmlPath, - path.join(getPaths().web.dist, '200.html') + path.join(getPaths().web.dist, '200.html'), ) } }, @@ -181,8 +181,8 @@ export const handler = async ({ console.log( `You have not marked any routes to "prerender" in your ${terminalLink( 'Routes', - 'file://' + rwjsPaths.web.routes - )}.` + 'file://' + rwjsPaths.web.routes, + )}.`, ) return diff --git a/packages/cli/src/commands/consoleHandler.js b/packages/cli/src/commands/consoleHandler.js index 038e9d2f3c08..d6dd5abc17ee 100644 --- a/packages/cli/src/commands/consoleHandler.js +++ b/packages/cli/src/commands/consoleHandler.js @@ -22,7 +22,7 @@ const persistConsoleHistory = (r) => { fs.appendFileSync( consoleHistoryFile, r.lines.filter((line) => line.trim()).join('\n') + '\n', - 'utf8' + 'utf8', ) } diff --git a/packages/cli/src/commands/deploy.js b/packages/cli/src/commands/deploy.js index a57a99e755fe..62f377184f69 100644 --- a/packages/cli/src/commands/deploy.js +++ b/packages/cli/src/commands/deploy.js @@ -9,6 +9,6 @@ export const builder = (yargs) => .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#deploy' - )}\n` + 'https://redwoodjs.com/docs/cli-commands#deploy', + )}\n`, ) diff --git a/packages/cli/src/commands/deploy/__tests__/baremetal.test.js b/packages/cli/src/commands/deploy/__tests__/baremetal.test.js index 01b1a6dd98af..8db2dec678a1 100644 --- a/packages/cli/src/commands/deploy/__tests__/baremetal.test.js +++ b/packages/cli/src/commands/deploy/__tests__/baremetal.test.js @@ -18,8 +18,8 @@ describe('verifyConfig', () => { expect(() => baremetal.verifyConfig( { production: { servers: [{ host: 'prod.server.com' }] } }, - {} - ) + {}, + ), ).toThrow('Must specify an environment to deploy to') }) @@ -27,8 +27,8 @@ describe('verifyConfig', () => { expect(() => baremetal.verifyConfig( { production: { servers: [{ host: 'prod.server.com' }] } }, - { environment: 'staging' } - ) + { environment: 'staging' }, + ), ).toThrow('No servers found for environment "staging"') }) }) @@ -39,9 +39,9 @@ describe('verifyServerConfig', () => { baremetal.verifyServerConfig({ path: '/var/www/app', repo: 'git://github.com', - }) + }), ).toThrow( - '"host" config option not set. See https://redwoodjs.com/docs/deployment/baremetal#deploytoml' + '"host" config option not set. See https://redwoodjs.com/docs/deployment/baremetal#deploytoml', ) }) @@ -50,9 +50,9 @@ describe('verifyServerConfig', () => { baremetal.verifyServerConfig({ host: 'host.test', repo: 'git://github.com', - }) + }), ).toThrow( - '"path" config option not set. See https://redwoodjs.com/docs/deployment/baremetal#deploytoml' + '"path" config option not set. See https://redwoodjs.com/docs/deployment/baremetal#deploytoml', ) }) @@ -61,9 +61,9 @@ describe('verifyServerConfig', () => { baremetal.verifyServerConfig({ host: 'host.test', path: '/var/www/app', - }) + }), ).toThrow( - '"repo" config option not set. See https://redwoodjs.com/docs/deployment/baremetal#deploytoml' + '"repo" config option not set. See https://redwoodjs.com/docs/deployment/baremetal#deploytoml', ) }) @@ -73,7 +73,7 @@ describe('verifyServerConfig', () => { host: 'host.test', path: '/var/www/app', repo: 'git://github.com', - }) + }), ).toEqual(true) }) }) @@ -83,7 +83,7 @@ describe('maintenanceTasks', () => { const tasks = baremetal.maintenanceTasks( 'up', {}, - { path: '/var/www/app', processNames: ['api'] } + { path: '/var/www/app', processNames: ['api'] }, ) expect(tasks.length).toEqual(2) @@ -95,7 +95,7 @@ describe('maintenanceTasks', () => { const tasks = baremetal.maintenanceTasks( 'down', {}, - { path: '/var/www/app', processNames: ['api'] } + { path: '/var/www/app', processNames: ['api'] }, ) expect(tasks.length).toEqual(2) @@ -109,7 +109,7 @@ describe('rollbackTasks', () => { const tasks1 = baremetal.rollbackTasks( 1, {}, - { path: '/var/www/app', processNames: ['api'] } + { path: '/var/www/app', processNames: ['api'] }, ) expect(tasks1.length).toEqual(2) @@ -119,7 +119,7 @@ describe('rollbackTasks', () => { const tasks2 = baremetal.rollbackTasks( 5, {}, - { path: '/var/www/app', processNames: ['api'] } + { path: '/var/www/app', processNames: ['api'] }, ) expect(tasks2[0].title).toMatch('Rolling back 5') @@ -163,7 +163,7 @@ describe('serverConfigWithDefaults', () => { it('overrides branch name from yargs no matter what', () => { const config = baremetal.serverConfigWithDefaults( { branch: 'earth' }, - { branch: 'moon' } + { branch: 'moon' }, ) expect(config.branch).toEqual('moon') }) @@ -176,7 +176,7 @@ describe('parseConfig', () => { ` [[production.servers]] host = 'server.com' - ` + `, ) expect(envConfig).toEqual({ servers: [{ host: 'server.com' }] }) @@ -191,7 +191,7 @@ describe('parseConfig', () => { [[staging.servers]] host = 'staging.server.com' - ` + `, ) expect(envConfig).toEqual({ servers: [{ host: 'staging.server.com' }] }) @@ -203,7 +203,7 @@ describe('parseConfig', () => { ` [[production.servers]] host = 'server.com' - ` + `, ) expect(envLifecycle.before).toEqual({}) @@ -219,7 +219,7 @@ describe('parseConfig', () => { [[production.servers]] host = 'server.com' - ` + `, ) expect(envLifecycle.before).toEqual({ install: ['yarn global'] }) @@ -236,7 +236,7 @@ describe('parseConfig', () => { [[production.servers]] host = 'server.com' - ` + `, ) expect(envLifecycle.before).toEqual({ @@ -255,7 +255,7 @@ describe('parseConfig', () => { [[production.servers]] host = 'server.com' - ` + `, ) expect(envLifecycle.before).toEqual({ @@ -273,7 +273,7 @@ describe('parseConfig', () => { [production.before] install = 'yarn env' - ` + `, ) expect(envLifecycle.before).toEqual({ install: ['yarn env'] }) @@ -293,7 +293,7 @@ describe('parseConfig', () => { [production.before] install = 'yarn env one' update = 'yarn env two' - ` + `, ) expect(envLifecycle.before).toEqual({ @@ -316,7 +316,7 @@ describe('parseConfig', () => { repo = '\${TEST_VAR_REPO:git://github.com}' path = '\${TEST_VAR_PATH:/var/www/app}' privateKeyPath = '/Users/me/.ssh/id_rsa' - ` + `, ) const server = servers[0] expect(server.host).toEqual('staging.server.com') @@ -528,7 +528,7 @@ describe('deployTasks', () => { defaultYargs, {}, // ssh defaultServerConfig, - {} // lifecycle + {}, // lifecycle ) expect(Object.keys(tasks).length).toEqual(8) @@ -555,7 +555,7 @@ describe('deployTasks', () => { defaultYargs, {}, // ssh { ...defaultServerConfig, sides: ['api', 'web'] }, - {} // lifecycle + {}, // lifecycle ) expect(Object.keys(tasks).length).toEqual(9) @@ -568,7 +568,7 @@ describe('deployTasks', () => { defaultYargs, {}, // ssh { ...defaultServerConfig, migrate: false }, - {} // lifecycle + {}, // lifecycle ) expect(Object.keys(tasks).length).toEqual(8) @@ -580,7 +580,7 @@ describe('deployTasks', () => { { ...defaultYargs, firstRun: true }, {}, // ssh defaultServerConfig, - {} // lifecycle + {}, // lifecycle ) expect(Object.keys(tasks).length).toEqual(9) @@ -593,7 +593,7 @@ describe('deployTasks', () => { { ...defaultYargs, update: false }, {}, // ssh defaultServerConfig, - {} // lifecycle + {}, // lifecycle ) expect(tasks[0].skip()).toEqual(true) @@ -606,7 +606,7 @@ describe('deployTasks', () => { { ...defaultYargs, install: false }, {}, // ssh defaultServerConfig, - {} // lifecycle + {}, // lifecycle ) expect(tasks[2].skip()).toEqual(true) @@ -617,7 +617,7 @@ describe('deployTasks', () => { { ...defaultYargs, migrate: false }, {}, // ssh defaultServerConfig, - {} // lifecycle + {}, // lifecycle ) expect(tasks[3].skip()).toEqual(true) @@ -628,7 +628,7 @@ describe('deployTasks', () => { { ...defaultYargs, build: false }, {}, // ssh defaultServerConfig, - {} // lifecycle + {}, // lifecycle ) expect(tasks[4].skip()).toEqual(true) @@ -639,7 +639,7 @@ describe('deployTasks', () => { { ...defaultYargs, restart: false }, {}, // ssh defaultServerConfig, - {} // lifecycle + {}, // lifecycle ) expect(tasks[6].skip()).toEqual(true) @@ -650,7 +650,7 @@ describe('deployTasks', () => { { ...defaultYargs, cleanup: false }, {}, // ssh defaultServerConfig, - {} // lifecycle + {}, // lifecycle ) expect(tasks[7].skip()).toEqual(true) @@ -661,7 +661,7 @@ describe('deployTasks', () => { defaultYargs, {}, // ssh defaultServerConfig, - { before: { update: ['touch before-update.txt'] } } + { before: { update: ['touch before-update.txt'] } }, ) expect(Object.keys(tasks).length).toEqual(9) @@ -674,7 +674,7 @@ describe('deployTasks', () => { defaultYargs, {}, // ssh defaultServerConfig, - { before: { install: ['touch before-install.txt'] } } + { before: { install: ['touch before-install.txt'] } }, ) expect(Object.keys(tasks).length).toEqual(9) @@ -687,7 +687,7 @@ describe('deployTasks', () => { defaultYargs, {}, // ssh defaultServerConfig, - { before: { migrate: ['touch before-migrate.txt'] } } + { before: { migrate: ['touch before-migrate.txt'] } }, ) expect(Object.keys(tasks).length).toEqual(9) @@ -700,7 +700,7 @@ describe('deployTasks', () => { defaultYargs, {}, // ssh defaultServerConfig, - { before: { build: ['touch before-build.txt'] } } + { before: { build: ['touch before-build.txt'] } }, ) expect(Object.keys(tasks).length).toEqual(9) @@ -713,7 +713,7 @@ describe('deployTasks', () => { defaultYargs, {}, // ssh defaultServerConfig, - { before: { restart: ['touch before-restart.txt'] } } + { before: { restart: ['touch before-restart.txt'] } }, ) expect(Object.keys(tasks).length).toEqual(9) @@ -726,7 +726,7 @@ describe('deployTasks', () => { defaultYargs, {}, // ssh defaultServerConfig, - { before: { cleanup: ['touch before-cleanup.txt'] } } + { before: { cleanup: ['touch before-cleanup.txt'] } }, ) expect(Object.keys(tasks).length).toEqual(9) @@ -739,11 +739,11 @@ describe('commands', () => { it('contains a top-level task for each server in an environment', () => { const prodServers = baremetal.commands( { environment: 'production', releaseDir: '2022051120000' }, - {} + {}, ) const stagingServers = baremetal.commands( { environment: 'staging', releaseDir: '2022051120000' }, - {} + {}, ) expect(prodServers.length).toEqual(2) @@ -757,7 +757,7 @@ describe('commands', () => { it('a single server contains nested deploy tasks', () => { const servers = baremetal.commands( { environment: 'staging', releaseDir: '2022051120000' }, - {} + {}, ) expect(servers[0].task()).toBeInstanceOf(Listr) @@ -766,7 +766,7 @@ describe('commands', () => { it('contains connection and disconnection tasks', () => { const servers = baremetal.commands( { environment: 'staging', releaseDir: '2022051120000' }, - {} + {}, ) const tasks = servers[0].task().tasks @@ -777,7 +777,7 @@ describe('commands', () => { it('contains deploy tasks by default', () => { const servers = baremetal.commands( { environment: 'staging', releaseDir: '2022051120000' }, - {} + {}, ) const tasks = servers[0].task().tasks @@ -791,7 +791,7 @@ describe('commands', () => { releaseDir: '2022051120000', maintenance: 'up', }, - {} + {}, ) const tasks = servers[0].task().tasks @@ -806,7 +806,7 @@ describe('commands', () => { releaseDir: '2022051120000', rollback: 2, }, - {} + {}, ) const tasks = servers[0].task().tasks @@ -820,7 +820,7 @@ describe('commands', () => { environment: 'test', releaseDir: '2022051120000', }, - {} + {}, ) const tasks = servers[0].task().tasks diff --git a/packages/cli/src/commands/deploy/__tests__/nftPack.test.js b/packages/cli/src/commands/deploy/__tests__/nftPack.test.js index dc081e00889f..aebd55e0bab0 100644 --- a/packages/cli/src/commands/deploy/__tests__/nftPack.test.js +++ b/packages/cli/src/commands/deploy/__tests__/nftPack.test.js @@ -49,32 +49,32 @@ test('Check packager detects all functions', () => { test('Creates entry file for nested functions correctly', () => { const nestedFunction = findApiDistFunctions().find((fPath) => - fPath.includes('nested') + fPath.includes('nested'), ) const [outputPath, content] = nftPacker.generateEntryFile( nestedFunction, - 'nested' + 'nested', ) expect(outputPath).toBe('./api/dist/zipball/nested/nested.js') expect(content).toMatchInlineSnapshot( - `"module.exports = require('./api/dist/functions/nested/nested.js')"` + `"module.exports = require('./api/dist/functions/nested/nested.js')"`, ) }) test('Creates entry file for top level functions correctly', () => { const graphqlFunction = findApiDistFunctions().find((fPath) => - fPath.includes('graphql') + fPath.includes('graphql'), ) const [outputPath, content] = nftPacker.generateEntryFile( graphqlFunction, - 'graphql' + 'graphql', ) expect(outputPath).toBe('./api/dist/zipball/graphql/graphql.js') expect(content).toMatchInlineSnapshot( - `"module.exports = require('./api/dist/functions/graphql.js')"` + `"module.exports = require('./api/dist/functions/graphql.js')"`, ) }) diff --git a/packages/cli/src/commands/deploy/baremetal.js b/packages/cli/src/commands/deploy/baremetal.js index 52f3945a2b18..90daf79a5fd3 100644 --- a/packages/cli/src/commands/deploy/baremetal.js +++ b/packages/cli/src/commands/deploy/baremetal.js @@ -126,8 +126,8 @@ export const builder = (yargs) => { yargs.epilogue( `Also see the ${terminalLink( 'Redwood Baremetal Deploy Reference', - 'https://redwoodjs.com/docs/cli-commands#deploy' - )}\n` + 'https://redwoodjs.com/docs/cli-commands#deploy', + )}\n`, ) } @@ -146,7 +146,7 @@ const sshExec = async (ssh, path, command, args) => { if (result.code !== 0) { const error = new Error( - `Error while running command \`${command} ${args.join(' ')}\`` + `Error while running command \`${command} ${args.join(' ')}\``, ) error.exitCode = result.code throw error @@ -157,14 +157,14 @@ const sshExec = async (ssh, path, command, args) => { export const throwMissingConfig = (name) => { throw new Error( - `"${name}" config option not set. See https://redwoodjs.com/docs/deployment/baremetal#deploytoml` + `"${name}" config option not set. See https://redwoodjs.com/docs/deployment/baremetal#deploytoml`, ) } export const verifyConfig = (config, yargs) => { if (!yargs.environment) { throw new Error( - 'Must specify an environment to deploy to, ex: `yarn rw deploy baremetal production`' + 'Must specify an environment to deploy to, ex: `yarn rw deploy baremetal production`', ) } @@ -305,13 +305,13 @@ export const rollbackTasks = (count, ssh, serverConfig) => { await symlinkCurrentCommand( dirs[rollbackIndex], ssh, - serverConfig.path + serverConfig.path, ) } else { throw new Error( `Cannot rollback ${rollbackCount} release(s): ${ dirs.length - dirs.indexOf(currentLink) - 1 - } previous release(s) available` + } previous release(s) available`, ) } }, @@ -327,7 +327,7 @@ export const rollbackTasks = (count, ssh, serverConfig) => { processName, ssh, serverConfig, - serverConfig.path + serverConfig.path, ) }, }) @@ -341,7 +341,7 @@ export const lifecycleTask = ( lifecycle, task, skip, - { serverLifecycle, ssh, cmdPath } + { serverLifecycle, ssh, cmdPath }, ) => { if (serverLifecycle[lifecycle]?.[task]) { const tasks = [] @@ -393,7 +393,7 @@ export const deployTasks = (yargs, ssh, serverConfig, serverLifecycle) => { ]) }, }, - }) + }), ) tasks.push( @@ -407,7 +407,7 @@ export const deployTasks = (yargs, ssh, serverConfig, serverLifecycle) => { await sshExec(ssh, cmdPath, 'ln', [SYMLINK_FLAGS, '../.env', '.env']) }, }, - }) + }), ) tasks.push( @@ -423,7 +423,7 @@ export const deployTasks = (yargs, ssh, serverConfig, serverLifecycle) => { ]) }, }, - }) + }), ) tasks.push( @@ -452,7 +452,7 @@ export const deployTasks = (yargs, ssh, serverConfig, serverLifecycle) => { ]) }, }, - }) + }), ) for (const side of serverConfig.sides) { @@ -471,7 +471,7 @@ export const deployTasks = (yargs, ssh, serverConfig, serverLifecycle) => { ]) }, }, - }) + }), ) } @@ -487,7 +487,7 @@ export const deployTasks = (yargs, ssh, serverConfig, serverLifecycle) => { }, skip: () => !yargs.update, }, - }) + }), ) if (serverConfig.processNames) { @@ -509,15 +509,15 @@ export const deployTasks = (yargs, ssh, serverConfig, serverLifecycle) => { 'start', pathJoin( CURRENT_RELEASE_SYMLINK_NAME, - 'ecosystem.config.js' + 'ecosystem.config.js', ), '--only', processName, - ] + ], ) }, }, - }) + }), ) tasks.push({ title: `Saving ${processName} state for future startup...`, @@ -541,11 +541,11 @@ export const deployTasks = (yargs, ssh, serverConfig, serverLifecycle) => { processName, ssh, serverConfig, - serverConfig.path + serverConfig.path, ) }, }, - }) + }), ) } } @@ -565,11 +565,11 @@ export const deployTasks = (yargs, ssh, serverConfig, serverLifecycle) => { await sshExec( ssh, serverConfig.path, - `ls -t | tail -n +${fileStartIndex} | xargs rm -rf` + `ls -t | tail -n +${fileStartIndex} | xargs rm -rf`, ) }, }, - }) + }), ) return tasks.flat().filter((e) => e) @@ -582,7 +582,7 @@ const mergeLifecycleEvents = (lifecycle, other) => { for (const hook of LIFECYCLE_HOOKS) { for (const key in other[hook]) { lifecycleCopy[hook][key] = (lifecycleCopy[hook][key] || []).concat( - other[hook][key] + other[hook][key], ) } } @@ -650,13 +650,13 @@ export const commands = (yargs, ssh) => { if (yargs.maintenance) { tasks = tasks.concat( - maintenanceTasks(yargs.maintenance, ssh, serverConfig) + maintenanceTasks(yargs.maintenance, ssh, serverConfig), ) } else if (yargs.rollback) { tasks = tasks.concat(rollbackTasks(yargs.rollback, ssh, serverConfig)) } else { tasks = tasks.concat( - deployTasks(yargs, ssh, serverConfig, serverLifecycle) + deployTasks(yargs, ssh, serverConfig, serverLifecycle), ) } @@ -710,7 +710,7 @@ export const handler = async (yargs) => { padding: { top: 0, bottom: 0, right: 1, left: 1 }, margin: 0, borderColor: 'red', - }) + }), ) process.exit(e?.exitCode || 1) diff --git a/packages/cli/src/commands/deploy/edgio.js b/packages/cli/src/commands/deploy/edgio.js index 9cfc80f793fc..e74f04e21584 100644 --- a/packages/cli/src/commands/deploy/edgio.js +++ b/packages/cli/src/commands/deploy/edgio.js @@ -34,7 +34,7 @@ export const builder = async (yargs) => { .options(edgioBuilder) .group( Object.keys(omit(edgioBuilder, ['skip-init'])), - 'Edgio deploy options:' + 'Edgio deploy options:', ) } @@ -114,7 +114,7 @@ export const ERR_MESSAGE_MISSING_CLI = buildErrorMessage( 'It looks like Edgio is not configured for your project.', 'Run the following to add Edgio to your project:', ` ${c.info('yarn add -D @edgio/cli')}`, - ].join('\n') + ].join('\n'), ) export const ERR_MESSAGE_NOT_INITIALIZED = buildErrorMessage( @@ -123,7 +123,7 @@ export const ERR_MESSAGE_NOT_INITIALIZED = buildErrorMessage( 'It looks like Edgio is not configured for your project.', 'Run the following to initialize Edgio on your project:', ` ${c.info('yarn edgio init')}`, - ].join('\n') + ].join('\n'), ) export function buildErrorMessage(title, message) { @@ -134,7 +134,7 @@ export function buildErrorMessage(title, message) { '', `Also see the ${terminalLink( 'RedwoodJS on Edgio Guide', - 'https://docs.edg.io/guides/redwoodjs' + 'https://docs.edg.io/guides/redwoodjs', )} for additional resources.`, '', ].join('\n') diff --git a/packages/cli/src/commands/deploy/flightcontrol.js b/packages/cli/src/commands/deploy/flightcontrol.js index 03b879f353b5..7f05b55c455c 100644 --- a/packages/cli/src/commands/deploy/flightcontrol.js +++ b/packages/cli/src/commands/deploy/flightcontrol.js @@ -38,8 +38,8 @@ export const builder = (yargs) => { .epilogue( `For more commands, options, and examples, see ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#deploy' - )}` + 'https://redwoodjs.com/docs/cli-commands#deploy', + )}`, ) } @@ -68,7 +68,7 @@ export const handler = async ({ side, serve, prisma, dm: dataMigrate }) => { console.log('Running database migrations...') execa.commandSync( `node_modules/.bin/prisma migrate deploy --schema "${rwjsPaths.api.dbSchema}"`, - execaConfig + execaConfig, ) } diff --git a/packages/cli/src/commands/deploy/helpers/helpers.js b/packages/cli/src/commands/deploy/helpers/helpers.js index 9918873ae3e2..234dba6fb325 100644 --- a/packages/cli/src/commands/deploy/helpers/helpers.js +++ b/packages/cli/src/commands/deploy/helpers/helpers.js @@ -26,8 +26,8 @@ export const deployBuilder = (yargs) => { .epilogue( `For more commands, options, and examples, see ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#deploy' - )}` + 'https://redwoodjs.com/docs/cli-commands#deploy', + )}`, ) } diff --git a/packages/cli/src/commands/deploy/packing/nft.js b/packages/cli/src/commands/deploy/packing/nft.js index 7c9cb979be5a..db9f3f528b5f 100644 --- a/packages/cli/src/commands/deploy/packing/nft.js +++ b/packages/cli/src/commands/deploy/packing/nft.js @@ -27,7 +27,7 @@ export function zipDirectory(source, out) { // returns a tuple of [filePath, fileContent] export function generateEntryFile(functionAbsolutePath, name) { const relativeImport = ensurePosixPath( - path.relative(getPaths().base, functionAbsolutePath) + path.relative(getPaths().base, functionAbsolutePath), ) return [ `${ZIPBALL_DIR}/${name}/${name}.js`, @@ -46,8 +46,8 @@ export async function packageSingleFunction(functionFile) { copyPromises.push( fse.copy( './' + singleDependencyPath, - `${ZIPBALL_DIR}/${functionName}/${singleDependencyPath}` - ) + `${ZIPBALL_DIR}/${functionName}/${singleDependencyPath}`, + ), ) } @@ -61,7 +61,7 @@ export async function packageSingleFunction(functionFile) { await Promise.all(copyPromises) await exports.zipDirectory( `${ZIPBALL_DIR}/${functionName}`, - `${ZIPBALL_DIR}/${functionName}.zip` + `${ZIPBALL_DIR}/${functionName}.zip`, ) await fse.remove(`${ZIPBALL_DIR}/${functionName}`) return diff --git a/packages/cli/src/commands/deploy/render.js b/packages/cli/src/commands/deploy/render.js index 37b3c0b7ce6a..66d940c75adb 100644 --- a/packages/cli/src/commands/deploy/render.js +++ b/packages/cli/src/commands/deploy/render.js @@ -38,8 +38,8 @@ export const builder = (yargs) => { .epilogue( `For more commands, options, and examples, see ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#deploy' - )}` + 'https://redwoodjs.com/docs/cli-commands#deploy', + )}`, ) } @@ -64,14 +64,14 @@ export const handler = async ({ side, prisma, dataMigrate }) => { console.log('Running database migrations...') execa.commandSync( `node_modules/.bin/prisma migrate deploy --schema "${rwjsPaths.api.dbSchema}"`, - execaConfig + execaConfig, ) } if (dataMigrate) { console.log('Running data migrations...') const packageJson = fs.readJsonSync( - path.join(rwjsPaths.base, 'package.json') + path.join(rwjsPaths.base, 'package.json'), ) const hasDataMigratePackage = !!packageJson.devDependencies['@redwoodjs/cli-data-migrate'] @@ -86,7 +86,7 @@ export const handler = async ({ side, prisma, dataMigrate }) => { '```', 'yarn add -D @redwoodjs/cli-data-migrate', '```', - ].join('\n') + ].join('\n'), ) } else { execa.commandSync('yarn rw dataMigrate up', execaConfig) diff --git a/packages/cli/src/commands/deploy/serverless.js b/packages/cli/src/commands/deploy/serverless.js index c3fc24ab0c77..d94ffc4aa6ae 100644 --- a/packages/cli/src/commands/deploy/serverless.js +++ b/packages/cli/src/commands/deploy/serverless.js @@ -56,8 +56,8 @@ export const builder = (yargs) => { yargs.epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#deploy' - )}\n` + 'https://redwoodjs.com/docs/cli-commands#deploy', + )}\n`, ) } @@ -152,7 +152,7 @@ export const handler = async (yargs) => { { exitOnError: true, renderer: yargs.verbose && 'verbose', - } + }, ) try { await tasks.run() @@ -168,7 +168,7 @@ export const handler = async (yargs) => { { shell: true, cwd: getPaths().api.base, - } + }, ) const deployedApiUrl = slsInfo.match(/HttpApiUrl: (https:\/\/.*)/)[1] @@ -196,7 +196,7 @@ export const handler = async (yargs) => { console.log( SETUP_MARKER, - 'First deploys can take a good few minutes...' + 'First deploys can take a good few minutes...', ) console.log() @@ -204,7 +204,7 @@ export const handler = async (yargs) => { [ // Rebuild web with the new API_URL ...buildCommands({ ...yargs, sides: ['web'], firstRun: false }).map( - mapCommandsToListr + mapCommandsToListr, ), ...deployCommands({ ...yargs, @@ -215,7 +215,7 @@ export const handler = async (yargs) => { { exitOnError: true, renderer: yargs.verbose && 'verbose', - } + }, ) // Deploy the web side now that the API_URL has been configured @@ -226,7 +226,7 @@ export const handler = async (yargs) => { { shell: true, cwd: getPaths().web.base, - } + }, ) const deployedWebUrl = slsInfo.match(/url: (https:\/\/.*)/)[1] @@ -248,7 +248,7 @@ export const handler = async (yargs) => { padding: { top: 0, bottom: 0, right: 1, left: 1 }, margin: 1, borderColor: 'gray', - }) + }), ) } } diff --git a/packages/cli/src/commands/destroy.js b/packages/cli/src/commands/destroy.js index 32e26f8c018d..215259dea162 100644 --- a/packages/cli/src/commands/destroy.js +++ b/packages/cli/src/commands/destroy.js @@ -10,6 +10,6 @@ export const builder = (yargs) => .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#destroy-alias-d' - )}` + 'https://redwoodjs.com/docs/cli-commands#destroy-alias-d', + )}`, ) diff --git a/packages/cli/src/commands/destroy/cell/__tests__/cell.test.js b/packages/cli/src/commands/destroy/cell/__tests__/cell.test.js index c9e772ef60ef..ea98206054bd 100644 --- a/packages/cli/src/commands/destroy/cell/__tests__/cell.test.js +++ b/packages/cli/src/commands/destroy/cell/__tests__/cell.test.js @@ -69,7 +69,7 @@ test('destroys cell files with stories and tests', async () => { await t.run() const generatedFiles = Object.keys( - await files({ name: 'User', stories: true, tests: true }) + await files({ name: 'User', stories: true, tests: true }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) diff --git a/packages/cli/src/commands/destroy/component/__tests__/component.test.js b/packages/cli/src/commands/destroy/component/__tests__/component.test.js index d236a6622c4f..4b84fdf3b72c 100644 --- a/packages/cli/src/commands/destroy/component/__tests__/component.test.js +++ b/packages/cli/src/commands/destroy/component/__tests__/component.test.js @@ -56,7 +56,7 @@ test('destroys component files including stories and tests', async () => { return t.run().then(async () => { const generatedFiles = Object.keys( - await files({ name: 'About', stories: true, tests: true }) + await files({ name: 'About', stories: true, tests: true }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) diff --git a/packages/cli/src/commands/destroy/directive/__tests__/directive.test.js b/packages/cli/src/commands/destroy/directive/__tests__/directive.test.js index 2531b9b5a94d..fc1d17dbe744 100644 --- a/packages/cli/src/commands/destroy/directive/__tests__/directive.test.js +++ b/packages/cli/src/commands/destroy/directive/__tests__/directive.test.js @@ -42,7 +42,7 @@ test('destroys directive files', async () => { return t.run().then(() => { const generatedFiles = Object.keys( - files({ name: 'require-admin', type: 'validator', tests: true }) + files({ name: 'require-admin', type: 'validator', tests: true }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) diff --git a/packages/cli/src/commands/destroy/helpers.js b/packages/cli/src/commands/destroy/helpers.js index 792b4f4f632e..5ffc4ed574a8 100644 --- a/packages/cli/src/commands/destroy/helpers.js +++ b/packages/cli/src/commands/destroy/helpers.js @@ -15,7 +15,7 @@ const tasks = ({ componentName, filesFn, name }) => }, }, ], - { rendererOptions: { collapseSubtasks: false }, exitOnError: true } + { rendererOptions: { collapseSubtasks: false }, exitOnError: true }, ) export const createYargsForComponentDestroy = ({ diff --git a/packages/cli/src/commands/destroy/layout/__tests__/layout.test.js b/packages/cli/src/commands/destroy/layout/__tests__/layout.test.js index e43e6530a223..59f25a85c2cf 100644 --- a/packages/cli/src/commands/destroy/layout/__tests__/layout.test.js +++ b/packages/cli/src/commands/destroy/layout/__tests__/layout.test.js @@ -56,7 +56,7 @@ test('destroys layout files with stories and tests', async () => { return t.run().then(() => { const generatedFiles = Object.keys( - files({ name: 'Blog', stories: true, tests: true }) + files({ name: 'Blog', stories: true, tests: true }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) diff --git a/packages/cli/src/commands/destroy/page/__tests__/page.test.js b/packages/cli/src/commands/destroy/page/__tests__/page.test.js index 6c32c7d0b0f2..125901a592df 100644 --- a/packages/cli/src/commands/destroy/page/__tests__/page.test.js +++ b/packages/cli/src/commands/destroy/page/__tests__/page.test.js @@ -86,7 +86,7 @@ test('cleans up route from Routes.js', async () => { ' ', ' ', '', - ].join('\n') + ].join('\n'), ) }) }) @@ -103,7 +103,7 @@ test('cleans up route with a custom path from Routes.js', async () => { ' ', ' ', '', - ].join('\n') + ].join('\n'), ) }) }) diff --git a/packages/cli/src/commands/destroy/page/page.js b/packages/cli/src/commands/destroy/page/page.js index 4613e783f048..ef2d8c891c9b 100644 --- a/packages/cli/src/commands/destroy/page/page.js +++ b/packages/cli/src/commands/destroy/page/page.js @@ -46,7 +46,7 @@ export const tasks = ({ name, path }) => task: async () => removeRoutesFromRouterTask([camelcase(name)]), }, ], - { rendererOptions: { collapseSubtasks: false }, exitOnError: true } + { rendererOptions: { collapseSubtasks: false }, exitOnError: true }, ) export const handler = async ({ name, path }) => { diff --git a/packages/cli/src/commands/destroy/scaffold/__tests__/scaffold.test.js b/packages/cli/src/commands/destroy/scaffold/__tests__/scaffold.test.js index e2921314b724..85a2cc1e9dd7 100644 --- a/packages/cli/src/commands/destroy/scaffold/__tests__/scaffold.test.js +++ b/packages/cli/src/commands/destroy/scaffold/__tests__/scaffold.test.js @@ -115,7 +115,7 @@ describe('rw destroy scaffold', () => { model: 'Post', tests: false, nestScaffoldByModel: true, - }) + }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) @@ -166,11 +166,11 @@ describe('rw destroy scaffold', () => { model: 'Post', tests: false, nestScaffoldByModel: true, - }) + }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => - expect(unlinkSpy).toHaveBeenCalledWith(f) + expect(unlinkSpy).toHaveBeenCalledWith(f), ) }) }) @@ -192,7 +192,7 @@ describe('rw destroy scaffold', () => { ' ', ' ', '', - ].join('\n') + ].join('\n'), ) }) }) @@ -246,7 +246,7 @@ describe('rw destroy scaffold', () => { path: 'admin', tests: false, nestScaffoldByModel: true, - }) + }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) @@ -296,11 +296,11 @@ describe('rw destroy scaffold', () => { path: 'admin', tests: false, nestScaffoldByModel: true, - }) + }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => - expect(unlinkSpy).toHaveBeenCalledWith(f) + expect(unlinkSpy).toHaveBeenCalledWith(f), ) }) }) @@ -323,7 +323,7 @@ describe('rw destroy scaffold', () => { ' ', ' ', '', - ].join('\n') + ].join('\n'), ) }) }) diff --git a/packages/cli/src/commands/destroy/scaffold/__tests__/scaffoldNoNest.test.js b/packages/cli/src/commands/destroy/scaffold/__tests__/scaffoldNoNest.test.js index 60b5ce9065a7..95f6d6c4a928 100644 --- a/packages/cli/src/commands/destroy/scaffold/__tests__/scaffoldNoNest.test.js +++ b/packages/cli/src/commands/destroy/scaffold/__tests__/scaffoldNoNest.test.js @@ -91,7 +91,7 @@ describe('rw destroy scaffold', () => { '', ].join('\n'), }, - '/' + '/', ) }) @@ -116,7 +116,7 @@ describe('rw destroy scaffold', () => { model: 'Post', tests: false, nestScaffoldByModel: false, - }) + }), ) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) @@ -166,11 +166,11 @@ describe('rw destroy scaffold', () => { model: 'Post', tests: false, nestScaffoldByModel: false, - }) + }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => - expect(unlinkSpy).toHaveBeenCalledWith(f) + expect(unlinkSpy).toHaveBeenCalledWith(f), ) }) }) @@ -192,7 +192,7 @@ describe('rw destroy scaffold', () => { ' ', ' ', '', - ].join('\n') + ].join('\n'), ) }) }) @@ -245,7 +245,7 @@ describe('rw destroy scaffold', () => { path: 'admin', tests: false, nestScaffoldByModel: false, - }) + }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) @@ -293,11 +293,11 @@ describe('rw destroy scaffold', () => { path: 'admin', tests: false, nestScaffoldByModel: false, - }) + }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => - expect(unlinkSpy).toHaveBeenCalledWith(f) + expect(unlinkSpy).toHaveBeenCalledWith(f), ) }) }) @@ -320,7 +320,7 @@ describe('rw destroy scaffold', () => { ' ', ' ', '', - ].join('\n') + ].join('\n'), ) }) }) diff --git a/packages/cli/src/commands/destroy/scaffold/scaffold.js b/packages/cli/src/commands/destroy/scaffold/scaffold.js index 7b6ef8194fcf..62703aadf282 100644 --- a/packages/cli/src/commands/destroy/scaffold/scaffold.js +++ b/packages/cli/src/commands/destroy/scaffold/scaffold.js @@ -39,12 +39,12 @@ const removeSetImport = () => { } const [redwoodRouterImport] = routesContent.match( - /import {[^]*} from '@redwoodjs\/router'/ + /import {[^]*} from '@redwoodjs\/router'/, ) const removedSetImport = redwoodRouterImport.replace(/,*\s*Set,*/, '') const newRoutesContent = routesContent.replace( redwoodRouterImport, - removedSetImport + removedSetImport, ) writeFile(routesPath, newRoutesContent, { overwriteExisting: true }) @@ -64,7 +64,7 @@ const removeLayoutImport = ({ model: name, path: scaffoldPath = '' }) => { const newRoutesContent = routesContent.replace( new RegExp(`\\s*${importLayout}`), - '' + '', ) writeFile(routesPath, newRoutesContent, { overwriteExisting: true }) @@ -109,7 +109,7 @@ export const tasks = ({ model, path, tests, nestScaffoldByModel }) => task: () => removeLayoutImport({ model, path }), }, ], - { rendererOptions: { collapseSubtasks: false }, exitOnError: true } + { rendererOptions: { collapseSubtasks: false }, exitOnError: true }, ) export const handler = async ({ model: modelArg }) => { diff --git a/packages/cli/src/commands/destroy/sdl/__tests__/sdl.test.js b/packages/cli/src/commands/destroy/sdl/__tests__/sdl.test.js index 8d2fec9f9058..f15cfc463fdf 100644 --- a/packages/cli/src/commands/destroy/sdl/__tests__/sdl.test.js +++ b/packages/cli/src/commands/destroy/sdl/__tests__/sdl.test.js @@ -48,7 +48,7 @@ describe('rw destroy sdl', () => { return t.tasks[0].run().then(async () => { const generatedFiles = Object.keys( - await files({ ...getDefaultArgs(builder), name: 'Post' }) + await files({ ...getDefaultArgs(builder), name: 'Post' }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) @@ -63,7 +63,7 @@ describe('rw destroy sdl', () => { ...getDefaultArgs(builder), typescript: true, name: 'Post', - }) + }), ) }) @@ -78,7 +78,7 @@ describe('rw destroy sdl', () => { ...getDefaultArgs(builder), typescript: true, name: 'Post', - }) + }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) diff --git a/packages/cli/src/commands/destroy/sdl/sdl.js b/packages/cli/src/commands/destroy/sdl/sdl.js index e52320fb3bd6..a4ac0810e36e 100644 --- a/packages/cli/src/commands/destroy/sdl/sdl.js +++ b/packages/cli/src/commands/destroy/sdl/sdl.js @@ -29,7 +29,7 @@ export const tasks = ({ model }) => }, }, ], - { rendererOptions: { collapseSubtasks: false }, exitOnError: true } + { rendererOptions: { collapseSubtasks: false }, exitOnError: true }, ) export const handler = async ({ model }) => { diff --git a/packages/cli/src/commands/destroy/service/__tests__/service.test.js b/packages/cli/src/commands/destroy/service/__tests__/service.test.js index 3e9db329c0c1..65c088cb2f72 100644 --- a/packages/cli/src/commands/destroy/service/__tests__/service.test.js +++ b/packages/cli/src/commands/destroy/service/__tests__/service.test.js @@ -57,7 +57,7 @@ describe('rw destroy service', () => { return t.run().then(async () => { const generatedFiles = Object.keys( - await files({ ...getDefaultArgs(builder), name: 'User' }) + await files({ ...getDefaultArgs(builder), name: 'User' }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) @@ -72,7 +72,7 @@ describe('rw destroy service', () => { ...getDefaultArgs(builder), typescript: true, name: 'User', - }) + }), ) }) @@ -91,7 +91,7 @@ describe('rw destroy service', () => { ...getDefaultArgs(builder), typescript: true, name: 'User', - }) + }), ) expect(generatedFiles.length).toEqual(unlinkSpy.mock.calls.length) generatedFiles.forEach((f) => expect(unlinkSpy).toHaveBeenCalledWith(f)) diff --git a/packages/cli/src/commands/dev.js b/packages/cli/src/commands/dev.js index de9b2946bb22..f9b726c7fa70 100644 --- a/packages/cli/src/commands/dev.js +++ b/packages/cli/src/commands/dev.js @@ -46,8 +46,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#dev' - )}` + 'https://redwoodjs.com/docs/cli-commands#dev', + )}`, ) } diff --git a/packages/cli/src/commands/devHandler.js b/packages/cli/src/commands/devHandler.js index bd1df26ff710..f98833a46da6 100644 --- a/packages/cli/src/commands/devHandler.js +++ b/packages/cli/src/commands/devHandler.js @@ -110,7 +110,7 @@ export const handler = async ({ } catch (e) { errorTelemetry( process.argv, - `Error generating prisma client: ${e.message}` + `Error generating prisma client: ${e.message}`, ) console.error(c.error(e.message)) } @@ -123,7 +123,7 @@ export const handler = async ({ } catch (e) { errorTelemetry(process.argv, `Error shutting down "api": ${e.message}`) console.error( - `Error whilst shutting down "api" port: ${c.error(e.message)}` + `Error whilst shutting down "api" port: ${c.error(e.message)}`, ) } } @@ -135,13 +135,13 @@ export const handler = async ({ } catch (e) { errorTelemetry(process.argv, `Error shutting down "web": ${e.message}`) console.error( - `Error whilst shutting down "web" port: ${c.error(e.message)}` + `Error whilst shutting down "web" port: ${c.error(e.message)}`, ) } } const webpackDevConfig = require.resolve( - '@redwoodjs/core/config/webpack.development.js' + '@redwoodjs/core/config/webpack.development.js', ) const getApiDebugFlag = () => { @@ -180,7 +180,7 @@ export const handler = async ({ if (getConfig().web.bundler === 'webpack') { if (streamingSsrEnabled) { throw new Error( - 'Webpack does not support SSR. Please switch your bundler to Vite in redwood.toml first' + 'Webpack does not support SSR. Please switch your bundler to Vite in redwood.toml first', ) } else { webCommand = `yarn cross-env NODE_ENV=development RWJS_WATCH_NODE_MODULES=${ @@ -234,13 +234,13 @@ export const handler = async ({ prefix: '{name} |', timestampFormat: 'HH:mm:ss', handleInput: true, - } + }, ) result.catch((e) => { if (typeof e?.message !== 'undefined') { errorTelemetry( process.argv, - `Error concurrently starting sides: ${e.message}` + `Error concurrently starting sides: ${e.message}`, ) exitWithError(e) } diff --git a/packages/cli/src/commands/exec.js b/packages/cli/src/commands/exec.js index c171ed9974b6..47e6c4837437 100644 --- a/packages/cli/src/commands/exec.js +++ b/packages/cli/src/commands/exec.js @@ -23,8 +23,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#up' - )}` + 'https://redwoodjs.com/docs/cli-commands#up', + )}`, ) } diff --git a/packages/cli/src/commands/execHandler.js b/packages/cli/src/commands/execHandler.js index 09b0511499f2..1de907100a64 100644 --- a/packages/cli/src/commands/execHandler.js +++ b/packages/cli/src/commands/execHandler.js @@ -103,7 +103,7 @@ export const handler = async (args) => { require.resolve(scriptPath) } catch { console.error( - c.error(`\nNo script called ${c.underline(name)} in ./scripts folder.\n`) + c.error(`\nNo script called ${c.underline(name)} in ./scripts folder.\n`), ) printAvailableScriptsToConsole() diff --git a/packages/cli/src/commands/experimental.js b/packages/cli/src/commands/experimental.js index 32e235b31282..0bcc75cddf9a 100644 --- a/packages/cli/src/commands/experimental.js +++ b/packages/cli/src/commands/experimental.js @@ -24,6 +24,6 @@ export const builder = (yargs) => .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#experimental' - )}` + 'https://redwoodjs.com/docs/cli-commands#experimental', + )}`, ) diff --git a/packages/cli/src/commands/experimental/__tests__/setupDocker.test.js b/packages/cli/src/commands/experimental/__tests__/setupDocker.test.js index 7c96f33c050a..0b7500e66bb3 100644 --- a/packages/cli/src/commands/experimental/__tests__/setupDocker.test.js +++ b/packages/cli/src/commands/experimental/__tests__/setupDocker.test.js @@ -19,7 +19,7 @@ describe('setupDocker', () => { test("description didn't change unintentionally", () => { expect(description).toMatchInlineSnapshot( - `"Setup the experimental Dockerfile"` + `"Setup the experimental Dockerfile"`, ) }) diff --git a/packages/cli/src/commands/experimental/setupDockerHandler.js b/packages/cli/src/commands/experimental/setupDockerHandler.js index c4f9170aea67..b97850403695 100644 --- a/packages/cli/src/commands/experimental/setupDockerHandler.js +++ b/packages/cli/src/commands/experimental/setupDockerHandler.js @@ -15,29 +15,29 @@ export async function handler({ force }) { let dockerfileTemplateContent = fs.readFileSync( path.resolve(TEMPLATE_DIR, 'Dockerfile'), - 'utf-8' + 'utf-8', ) const dockerComposeDevTemplateContent = fs.readFileSync( path.resolve(TEMPLATE_DIR, 'docker-compose.dev.yml'), - 'utf-8' + 'utf-8', ) const dockerComposeProdTemplateContent = fs.readFileSync( path.resolve(TEMPLATE_DIR, 'docker-compose.prod.yml'), - 'utf-8' + 'utf-8', ) const dockerignoreTemplateContent = fs.readFileSync( path.resolve(TEMPLATE_DIR, 'dockerignore'), - 'utf-8' + 'utf-8', ) const dockerfilePath = path.join(getPaths().base, 'Dockerfile') const dockerComposeDevFilePath = path.join( getPaths().base, - 'docker-compose.dev.yml' + 'docker-compose.dev.yml', ) const dockerComposeProdFilePath = path.join( getPaths().base, - 'docker-compose.prod.yml' + 'docker-compose.prod.yml', ) const dockerignoreFilePath = path.join(getPaths().base, '.dockerignore') @@ -73,7 +73,7 @@ export async function handler({ force }) { if (hasWorkspaceToolsPlugin) { task.skip( - 'The official yarn workspace-tools plugin is already installed' + 'The official yarn workspace-tools plugin is already installed', ) return } @@ -89,21 +89,21 @@ export async function handler({ force }) { task: async (_ctx, task) => { const apiServerPackageName = '@redwoodjs/api-server' const { dependencies: apiDependencies } = fs.readJSONSync( - path.join(getPaths().api.base, 'package.json') + path.join(getPaths().api.base, 'package.json'), ) const hasApiServerPackage = Object.keys(apiDependencies).includes(apiServerPackageName) const webServerPackageName = '@redwoodjs/web-server' const { dependencies: webDependencies } = fs.readJSONSync( - path.join(getPaths().web.base, 'package.json') + path.join(getPaths().web.base, 'package.json'), ) const hasWebServerPackage = Object.keys(webDependencies).includes(webServerPackageName) if (hasApiServerPackage && hasWebServerPackage) { task.skip( - `${apiServerPackageName} and ${webServerPackageName} are already installed` + `${apiServerPackageName} and ${webServerPackageName} are already installed`, ) return } @@ -116,7 +116,7 @@ export async function handler({ force }) { `yarn workspace api add ${apiServerPackageName}@${apiServerPackageVersion}`, { cwd: getPaths().base, - } + }, ) } @@ -128,7 +128,7 @@ export async function handler({ force }) { `yarn workspace web add ${webServerPackageName}@${webServerPackageVersion}`, { cwd: getPaths().base, - } + }, ) } @@ -165,12 +165,12 @@ export async function handler({ force }) { beforeWebBuildWithPrerenderStageDelimeter, afterWebBuildWithPrerenderStageDelimeter, ] = dockerfileTemplateContent.split( - webBuildWithPrerenderStageDelimeter + webBuildWithPrerenderStageDelimeter, ) const [beforeWebBuildStageDelimeter, afterWebBuildStageDelimeter] = afterWebBuildWithPrerenderStageDelimeter.split( - webBuildStageDelimeter + webBuildStageDelimeter, ) dockerfileTemplateContent = [ @@ -191,7 +191,7 @@ export async function handler({ force }) { { existingFiles: force ? 'OVERWRITE' : 'SKIP', }, - task + task, ) writeFile( dockerComposeDevFilePath, @@ -199,13 +199,13 @@ export async function handler({ force }) { { existingFiles: force ? 'OVERWRITE' : 'SKIP', }, - task + task, ) writeFile( dockerComposeProdFilePath, dockerComposeProdTemplateContent, { existingFiles: force ? 'OVERWRITE' : 'SKIP' }, - task + task, ) writeFile( dockerignoreFilePath, @@ -213,7 +213,7 @@ export async function handler({ force }) { { existingFiles: force ? 'OVERWRITE' : 'SKIP', }, - task + task, ) }, }, @@ -224,7 +224,7 @@ export async function handler({ force }) { const gitignoreFilePath = path.join(getPaths().base, '.gitignore') const gitignoreFileContent = fs.readFileSync( gitignoreFilePath, - 'utf-8' + 'utf-8', ) if (gitignoreFileContent.includes('postgres')) { @@ -235,7 +235,7 @@ export async function handler({ force }) { writeFile( gitignoreFilePath, gitignoreFileContent.concat('\npostgres\n'), - { existingFiles: 'OVERWRITE' } + { existingFiles: 'OVERWRITE' }, ) }, }, @@ -250,12 +250,12 @@ export async function handler({ force }) { const hasOpenSetToTrue = browserOpenRegExp.test(configContent) const hasExperimentalDockerfileConfig = configContent.includes( - '[experimental.dockerfile]' + '[experimental.dockerfile]', ) if (!hasOpenSetToTrue && hasExperimentalDockerfileConfig) { task.skip( - `The [experimental.dockerfile] config block already exists in your 'redwood.toml' file` + `The [experimental.dockerfile] config block already exists in your 'redwood.toml' file`, ) return } @@ -263,13 +263,13 @@ export async function handler({ force }) { if (hasOpenSetToTrue) { configContent = configContent.replace( /open\s*=\s*true/, - 'open = false' + 'open = false', ) } if (!hasExperimentalDockerfileConfig) { configContent = configContent.concat( - `\n[experimental.dockerfile]\n\tenabled = true\n` + `\n[experimental.dockerfile]\n\tenabled = true\n`, ) } @@ -283,7 +283,7 @@ export async function handler({ force }) { { renderer: process.env.NODE_ENV === 'test' ? 'verbose' : 'default', - } + }, ) try { @@ -312,7 +312,7 @@ export async function handler({ force }) { '', "There's a lot in the Dockerfile and there's a reason for every line.", 'Be sure to check out the docs: https://redwoodjs.com/docs/docker', - ].join('\n') + ].join('\n'), ) } catch (e) { errorTelemetry(process.argv, e.message) diff --git a/packages/cli/src/commands/experimental/setupOpentelemetryHandler.js b/packages/cli/src/commands/experimental/setupOpentelemetryHandler.js index 2ddf42fb7206..381a8cb06c56 100644 --- a/packages/cli/src/commands/experimental/setupOpentelemetryHandler.js +++ b/packages/cli/src/commands/experimental/setupOpentelemetryHandler.js @@ -46,7 +46,7 @@ export const handler = async ({ force, verbose }) => { task: () => { const setupTemplateContent = fs.readFileSync( path.resolve(__dirname, 'templates', 'opentelemetry.ts.template'), - 'utf-8' + 'utf-8', ) const setupScriptContent = ts ? setupTemplateContent @@ -69,15 +69,15 @@ export const handler = async ({ force, verbose }) => { writeFile( redwoodTomlPath, configContent.concat( - `\n[experimental.opentelemetry]\n\tenabled = true\n\twrapApi = true` + `\n[experimental.opentelemetry]\n\tenabled = true\n\twrapApi = true`, ), { overwriteExisting: true, // redwood.toml always exists - } + }, ) } else { task.skip( - `The [experimental.opentelemetry] config block already exists in your 'redwood.toml' file.` + `The [experimental.opentelemetry] config block already exists in your 'redwood.toml' file.`, ) } }, @@ -86,7 +86,7 @@ export const handler = async ({ force, verbose }) => { title: 'Notice: GraphQL function update...', enabled: () => { return fs.existsSync( - resolveFile(path.join(getPaths().api.functions, 'graphql')) + resolveFile(path.join(getPaths().api.functions, 'graphql')), ) }, task: (_ctx, task) => { @@ -99,7 +99,7 @@ export const handler = async ({ force, verbose }) => { '}', '', `Which can found at ${c.info( - path.join(getPaths().api.functions, 'graphql') + path.join(getPaths().api.functions, 'graphql'), )}`, ].join('\n') }, @@ -109,7 +109,7 @@ export const handler = async ({ force, verbose }) => { title: 'Notice: GraphQL function update (server file)...', enabled: () => { return fs.existsSync( - resolveFile(path.join(getPaths().api.src, 'server')) + resolveFile(path.join(getPaths().api.src, 'server')), ) }, task: (_ctx, task) => { @@ -122,7 +122,7 @@ export const handler = async ({ force, verbose }) => { '}', '', `Which can found at ${c.info( - path.join(getPaths().api.src, 'server') + path.join(getPaths().api.src, 'server'), )}`, ].join('\n') }, @@ -147,8 +147,8 @@ export const handler = async ({ force, verbose }) => { 'generator client'.length, schemaContent.indexOf( '}', - schemaContent.indexOf('generator client') - ) + 1 + schemaContent.indexOf('generator client'), + ) + 1, ) .trim() @@ -156,18 +156,18 @@ export const handler = async ({ force, verbose }) => { let newSchemaContents = schemaContent if (previewLineExists) { task.skip( - 'Please add "tracing" to your previewFeatures in prisma.schema' + 'Please add "tracing" to your previewFeatures in prisma.schema', ) } else { const newClientConfig = clientConfig.trim().split('\n') newClientConfig.splice( newClientConfig.length - 1, 0, - 'previewFeatures = ["tracing"]' + 'previewFeatures = ["tracing"]', ) newSchemaContents = newSchemaContents.replace( clientConfig, - newClientConfig.join('\n') + newClientConfig.join('\n'), ) } @@ -214,7 +214,7 @@ export const handler = async ({ force, verbose }) => { { rendererOptions: { collapseSubtasks: false, persistentOutput: true }, renderer: verbose ? 'verbose' : 'default', - } + }, ) try { diff --git a/packages/cli/src/commands/experimental/setupRscHandler.js b/packages/cli/src/commands/experimental/setupRscHandler.js index 2dbddc3eb0ce..d1935ebe264d 100644 --- a/packages/cli/src/commands/experimental/setupRscHandler.js +++ b/packages/cli/src/commands/experimental/setupRscHandler.js @@ -30,13 +30,13 @@ export const handler = async ({ force, verbose }) => { if (!getConfig().experimental?.streamingSsr?.enabled) { throw new Error( - 'The Streaming SSR experimental feature must be enabled before you can enable RSCs' + 'The Streaming SSR experimental feature must be enabled before you can enable RSCs', ) } if (!isTypeScriptProject()) { throw new Error( - 'RSCs are only supported in TypeScript projects at this time' + 'RSCs are only supported in TypeScript projects at this time', ) } }, @@ -50,7 +50,7 @@ export const handler = async ({ force, verbose }) => { configContent.concat('\n[experimental.rsc]\n enabled = true\n'), { overwriteExisting: true, // redwood.toml always exists - } + }, ) } else { if (force) { @@ -61,15 +61,15 @@ export const handler = async ({ force, verbose }) => { configContent.replace( // Enable if it's currently disabled '\n[experimental.rsc]\n enabled = false\n', - '\n[experimental.rsc]\n enabled = true\n' + '\n[experimental.rsc]\n enabled = true\n', ), { overwriteExisting: true, // redwood.toml always exists - } + }, ) } else { task.skip( - 'The [experimental.rsc] config block already exists in your `redwood.toml` file.' + 'The [experimental.rsc] config block already exists in your `redwood.toml` file.', ) } } @@ -81,7 +81,7 @@ export const handler = async ({ force, verbose }) => { task: async () => { const entriesTemplate = fs.readFileSync( path.resolve(__dirname, 'templates', 'rsc', 'entries.ts.template'), - 'utf-8' + 'utf-8', ) // Can't use rwPaths.web.entries because it's not created yet @@ -98,14 +98,14 @@ export const handler = async ({ force, verbose }) => { __dirname, 'templates', 'rsc', - 'HomePage.tsx.template' + 'HomePage.tsx.template', ), - 'utf-8' + 'utf-8', ) const homePagePath = path.join( rwPaths.web.pages, 'HomePage', - 'HomePage.tsx' + 'HomePage.tsx', ) writeFile(homePagePath, homePageTemplate, { @@ -117,14 +117,14 @@ export const handler = async ({ force, verbose }) => { __dirname, 'templates', 'rsc', - 'AboutPage.tsx.template' + 'AboutPage.tsx.template', ), - 'utf-8' + 'utf-8', ) const aboutPagePath = path.join( rwPaths.web.pages, 'AboutPage', - 'AboutPage.tsx' + 'AboutPage.tsx', ) writeFile(aboutPagePath, aboutPageTemplate, { @@ -137,12 +137,12 @@ export const handler = async ({ force, verbose }) => { task: async () => { const counterTemplate = fs.readFileSync( path.resolve(__dirname, 'templates', 'rsc', 'Counter.tsx.template'), - 'utf-8' + 'utf-8', ) const counterPath = path.join( rwPaths.web.components, 'Counter', - 'Counter.tsx' + 'Counter.tsx', ) writeFile(counterPath, counterTemplate, { @@ -158,14 +158,14 @@ export const handler = async ({ force, verbose }) => { __dirname, 'templates', 'rsc', - 'AboutCounter.tsx.template' + 'AboutCounter.tsx.template', ), - 'utf-8' + 'utf-8', ) const counterPath = path.join( rwPaths.web.components, 'Counter', - 'AboutCounter.tsx' + 'AboutCounter.tsx', ) writeFile(counterPath, counterTemplate, { @@ -202,7 +202,7 @@ export const handler = async ({ force, verbose }) => { files.forEach((file) => { const template = fs.readFileSync( path.resolve(__dirname, 'templates', 'rsc', file.template), - 'utf-8' + 'utf-8', ) const filePath = path.join(rwPaths.web.src, ...file.path) @@ -220,14 +220,14 @@ export const handler = async ({ force, verbose }) => { __dirname, 'templates', 'rsc', - 'NavigationLayout.tsx.template' + 'NavigationLayout.tsx.template', ), - 'utf-8' + 'utf-8', ) const layoutPath = path.join( rwPaths.web.layouts, 'NavigationLayout', - 'NavigationLayout.tsx' + 'NavigationLayout.tsx', ) writeFile(layoutPath, layoutTemplate, { overwriteExisting: force }) @@ -237,14 +237,14 @@ export const handler = async ({ force, verbose }) => { __dirname, 'templates', 'rsc', - 'NavigationLayout.css.template' + 'NavigationLayout.css.template', ), - 'utf-8' + 'utf-8', ) const cssPath = path.join( rwPaths.web.layouts, 'NavigationLayout', - 'NavigationLayout.css' + 'NavigationLayout.css', ) writeFile(cssPath, cssTemplate, { overwriteExisting: force }) @@ -257,7 +257,7 @@ export const handler = async ({ force, verbose }) => { if ( /\n\s*' + ' ', ) writeFile(rwPaths.web.html, indexHtml, { @@ -280,7 +280,7 @@ export const handler = async ({ force, verbose }) => { task: async () => { const template = fs.readFileSync( path.resolve(__dirname, 'templates', 'rsc', 'index.css.template'), - 'utf-8' + 'utf-8', ) const filePath = path.join(rwPaths.web.src, 'index.css') @@ -306,7 +306,7 @@ export const handler = async ({ force, verbose }) => { await prettify('tsconfig.json', JSON.stringify(tsconfig, null, 2)), { overwriteExisting: true, - } + }, ) }, }, @@ -315,7 +315,7 @@ export const handler = async ({ force, verbose }) => { task: async () => { const routesTemplate = fs.readFileSync( path.resolve(__dirname, 'templates', 'rsc', 'Routes.tsx.template'), - 'utf-8' + 'utf-8', ) writeFile(rwPaths.web.routes, routesTemplate, { @@ -332,7 +332,7 @@ export const handler = async ({ force, verbose }) => { { rendererOptions: { collapseSubtasks: false, persistentOutput: true }, renderer: verbose ? 'verbose' : 'default', - } + }, ) try { diff --git a/packages/cli/src/commands/experimental/setupStreamingSsrHandler.js b/packages/cli/src/commands/experimental/setupStreamingSsrHandler.js index 28f8e658f982..aa0ba298218e 100644 --- a/packages/cli/src/commands/experimental/setupStreamingSsrHandler.js +++ b/packages/cli/src/commands/experimental/setupStreamingSsrHandler.js @@ -32,7 +32,7 @@ export const handler = async ({ force, verbose }) => { task: () => { if (!rwPaths.web.entryClient || !rwPaths.web.viteConfig) { throw new Error( - 'Vite needs to be setup before you can enable Streaming SSR' + 'Vite needs to be setup before you can enable Streaming SSR', ) } }, @@ -44,11 +44,11 @@ export const handler = async ({ force, verbose }) => { writeFile( redwoodTomlPath, configContent.concat( - `\n[experimental.streamingSsr]\n enabled = true\n` + `\n[experimental.streamingSsr]\n enabled = true\n`, ), { overwriteExisting: true, // redwood.toml always exists - } + }, ) } else { if (force) { @@ -59,15 +59,15 @@ export const handler = async ({ force, verbose }) => { configContent.replace( // Enable if it's currently disabled `\n[experimental.streamingSsr]\n enabled = false\n`, - `\n[experimental.streamingSsr]\n enabled = true\n` + `\n[experimental.streamingSsr]\n enabled = true\n`, ), { overwriteExisting: true, // redwood.toml always exists - } + }, ) } else { task.skip( - `The [experimental.streamingSsr] config block already exists in your 'redwood.toml' file.` + `The [experimental.streamingSsr] config block already exists in your 'redwood.toml' file.`, ) } } @@ -82,9 +82,9 @@ export const handler = async ({ force, verbose }) => { __dirname, 'templates', 'streamingSsr', - 'entry.client.tsx.template' + 'entry.client.tsx.template', ), - 'utf-8' + 'utf-8', ) let entryClientPath = rwPaths.web.entryClient const entryClientContent = ts @@ -119,14 +119,14 @@ export const handler = async ({ force, verbose }) => { __dirname, 'templates', 'streamingSsr', - 'entry.server.tsx.template' + 'entry.server.tsx.template', ), - 'utf-8' + 'utf-8', ) // Can't use rwPaths.web.entryServer because it might not be not created yet const entryServerPath = path.join( rwPaths.web.src, - `entry.server${ext}` + `entry.server${ext}`, ) const entryServerContent = ts ? entryServerTemplate @@ -145,9 +145,9 @@ export const handler = async ({ force, verbose }) => { __dirname, 'templates', 'streamingSsr', - 'Document.tsx.template' + 'Document.tsx.template', ), - 'utf-8' + 'utf-8', ) const documentPath = path.join(rwPaths.web.src, `Document${ext}`) const documentContent = ts @@ -171,7 +171,7 @@ export const handler = async ({ force, verbose }) => { { rendererOptions: { collapseSubtasks: false, persistentOutput: true }, renderer: verbose ? 'verbose' : 'default', - } + }, ) try { diff --git a/packages/cli/src/commands/experimental/util.js b/packages/cli/src/commands/experimental/util.js index fd30e670851a..b52c72e68528 100644 --- a/packages/cli/src/commands/experimental/util.js +++ b/packages/cli/src/commands/experimental/util.js @@ -20,34 +20,34 @@ export const getEpilogue = ( command, description, topicId, - isTerminal = false + isTerminal = false, ) => `This is an experimental feature to: ${description}.\n\nPlease find documentation and links to provide feedback for ${command} at:\n -> ${link( topicId, - isTerminal + isTerminal, )}` export const printTaskEpilogue = (command, description, topicId) => { console.log( `${chalk.hex('#ff845e')( `------------------------------------------------------------------\n 🧪 ${chalk.green( - 'Experimental Feature' - )} 🧪\n------------------------------------------------------------------` - )}` + 'Experimental Feature', + )} 🧪\n------------------------------------------------------------------`, + )}`, ) console.log(getEpilogue(command, description, topicId, false)) console.log( `${chalk.hex('#ff845e')( - '------------------------------------------------------------------' - )}\n` + '------------------------------------------------------------------', + )}\n`, ) } export const isServerFileSetup = () => { if (!serverFileExists()) { throw new Error( - 'RedwoodJS Realtime requires a serverful environment. Please run `yarn rw setup server-file` first.' + 'RedwoodJS Realtime requires a serverful environment. Please run `yarn rw setup server-file` first.', ) } @@ -57,7 +57,7 @@ export const isServerFileSetup = () => { export const realtimeExists = () => { const realtimePath = path.join( getPaths().api.lib, - `realtime.${isTypeScriptProject() ? 'ts' : 'js'}` + `realtime.${isTypeScriptProject() ? 'ts' : 'js'}`, ) return fs.existsSync(realtimePath) } @@ -65,7 +65,7 @@ export const realtimeExists = () => { export const isRealtimeSetup = () => { if (!realtimeExists) { throw new Error( - 'Adding realtime events requires that RedwoodJS Realtime be setup. Please run `yarn setup realtime` first.' + 'Adding realtime events requires that RedwoodJS Realtime be setup. Please run `yarn setup realtime` first.', ) } diff --git a/packages/cli/src/commands/generate.js b/packages/cli/src/commands/generate.js index d42c8a5f6f4d..d9cabbcc5236 100644 --- a/packages/cli/src/commands/generate.js +++ b/packages/cli/src/commands/generate.js @@ -36,6 +36,6 @@ export const builder = (yargs) => .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#generate-alias-g' - )}` + 'https://redwoodjs.com/docs/cli-commands#generate-alias-g', + )}`, ) diff --git a/packages/cli/src/commands/generate/__tests__/createYargsForComponentGeneration.test.js b/packages/cli/src/commands/generate/__tests__/createYargsForComponentGeneration.test.js index ef247cdc283f..bf5749ec7d47 100644 --- a/packages/cli/src/commands/generate/__tests__/createYargsForComponentGeneration.test.js +++ b/packages/cli/src/commands/generate/__tests__/createYargsForComponentGeneration.test.js @@ -45,6 +45,6 @@ test('createYargsForComponentGeneration generates a yargs handler as expected', expect.objectContaining({ title: 'Cool beans, with rad sauce', }), - ]) + ]), ) }) diff --git a/packages/cli/src/commands/generate/__tests__/helpers.test.js b/packages/cli/src/commands/generate/__tests__/helpers.test.js index f9a86508de90..684cbb6c0250 100644 --- a/packages/cli/src/commands/generate/__tests__/helpers.test.js +++ b/packages/cli/src/commands/generate/__tests__/helpers.test.js @@ -42,8 +42,8 @@ test('customOrDefaultTemplatePath returns the default path if no custom template expect(output).toMatch( path.normalize( - '/packages/cli/src/commands/generate/page/templates/page.tsx.template' - ) + '/packages/cli/src/commands/generate/page/templates/page.tsx.template', + ), ) }) @@ -58,7 +58,7 @@ test('customOrDefaultTemplatePath returns the app path if a custom template exis }) expect(output).toEqual( - path.normalize('/path/to/project/web/generators/page/page.tsx.template') + path.normalize('/path/to/project/web/generators/page/page.tsx.template'), ) }) @@ -74,8 +74,8 @@ test('customOrDefaultTemplatePath returns the app path with proper side, generat expect(output).toEqual( path.normalize( - '/path/to/project/api/generators/cell/component.tsx.template' - ) + '/path/to/project/api/generators/cell/component.tsx.template', + ), ) }) @@ -93,7 +93,7 @@ test('templateForComponentFile creates a proper output path for files', async () }) expect(output[0]).toEqual( - path.normalize('/path/to/project/web/src/pages/FooBarPage/FooBarPage.js') + path.normalize('/path/to/project/web/src/pages/FooBarPage/FooBarPage.js'), ) } }) @@ -112,7 +112,7 @@ test('templateForComponentFile creates a proper output path for files with all c }) expect(output[0]).toEqual( - path.normalize('/path/to/project/web/src/pages/FOOBARPage/FOOBARPage.js') + path.normalize('/path/to/project/web/src/pages/FOOBARPage/FOOBARPage.js'), ) } }) @@ -131,7 +131,7 @@ test('templateForComponentFile creates a proper output path for files for starti }) expect(output[0]).toEqual( - path.normalize('/path/to/project/web/src/pages/FOOBarPage/FOOBarPage.js') + path.normalize('/path/to/project/web/src/pages/FOOBarPage/FOOBarPage.js'), ) } }) @@ -150,7 +150,7 @@ test('templateForComponentFile creates a proper output path for files with upper }) expect(output[0]).toEqual( - path.normalize('/path/to/project/web/src/pages/ABtestPage/ABtestPage.js') + path.normalize('/path/to/project/web/src/pages/ABtestPage/ABtestPage.js'), ) } }) @@ -166,7 +166,7 @@ test('templateForComponentFile can create a path in /web', async () => { }) expect(output[0]).toEqual( - path.normalize('/path/to/project/web/src/pages/HomePage/HomePage.js') + path.normalize('/path/to/project/web/src/pages/HomePage/HomePage.js'), ) }) @@ -181,7 +181,7 @@ test('templateForComponentFile can create a path in /api', async () => { }) expect(output[0]).toEqual( - path.normalize('/path/to/project/api/src/services/HomePage/HomePage.js') + path.normalize('/path/to/project/api/src/services/HomePage/HomePage.js'), ) }) @@ -196,7 +196,7 @@ test('templateForComponentFile can override generated component name', async () }) expect(output[0]).toEqual( - path.normalize('/path/to/project/web/src/pages/Hobbiton/Hobbiton.js') + path.normalize('/path/to/project/web/src/pages/Hobbiton/Hobbiton.js'), ) }) @@ -212,7 +212,7 @@ test('templateForComponentFile can override file extension', async () => { }) expect(output[0]).toEqual( - path.normalize('/path/to/project/web/src/pages/HomePage/HomePage.txt') + path.normalize('/path/to/project/web/src/pages/HomePage/HomePage.txt'), ) }) @@ -227,7 +227,7 @@ test('templateForComponentFile can override output path', async () => { }) expect(output[0]).toEqual( - path.normalize('/path/to/project/api/src/functions/func.ts') + path.normalize('/path/to/project/api/src/functions/func.ts'), ) }) @@ -267,7 +267,7 @@ test('pathName creates path based on name if path is just a route parameter', () test('pathName supports paths with route params', () => { expect(helpers.pathName('/post/{id:Int}/edit', 'EditPost')).toEqual( - '/post/{id:Int}/edit' + '/post/{id:Int}/edit', ) }) diff --git a/packages/cli/src/commands/generate/cell/__tests__/cell.test.js b/packages/cli/src/commands/generate/cell/__tests__/cell.test.js index f77f53e160c9..0f940d3fd646 100644 --- a/packages/cli/src/commands/generate/cell/__tests__/cell.test.js +++ b/packages/cli/src/commands/generate/cell/__tests__/cell.test.js @@ -35,9 +35,9 @@ describe('Single word files', () => { expect( singleWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserCell/UserCell.jsx' + '/path/to/project/web/src/components/UserCell/UserCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -45,9 +45,9 @@ describe('Single word files', () => { expect( singleWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserCell/UserCell.test.jsx' + '/path/to/project/web/src/components/UserCell/UserCell.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -55,9 +55,9 @@ describe('Single word files', () => { expect( singleWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserCell/UserCell.stories.jsx' + '/path/to/project/web/src/components/UserCell/UserCell.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -65,9 +65,9 @@ describe('Single word files', () => { expect( singleWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserCell/UserCell.mock.js' + '/path/to/project/web/src/components/UserCell/UserCell.mock.js', ) - ] + ], ).toMatchSnapshot() }) }) @@ -84,13 +84,13 @@ test('trims Cell from end of name', async () => { const cellCode = files[ path.normalize( - '/path/to/project/web/src/components/BazingaCell/BazingaCell.jsx' + '/path/to/project/web/src/components/BazingaCell/BazingaCell.jsx', ) ] expect(cellCode).not.toBeUndefined() expect( - cellCode.split('\n').includes('export const Success = ({ bazinga }) => {') + cellCode.split('\n').includes('export const Success = ({ bazinga }) => {'), ).toBeTruthy() }) @@ -111,9 +111,9 @@ describe('Multiword files', () => { expect( multiWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -121,9 +121,9 @@ describe('Multiword files', () => { expect( multiWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.test.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -131,9 +131,9 @@ describe('Multiword files', () => { expect( multiWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.stories.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -141,9 +141,9 @@ describe('Multiword files', () => { expect( multiWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.mock.js' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.mock.js', ) - ] + ], ).toMatchSnapshot() }) }) @@ -165,9 +165,9 @@ describe('Snake case words', () => { expect( snakeCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -175,9 +175,9 @@ describe('Snake case words', () => { expect( snakeCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.test.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -185,9 +185,9 @@ describe('Snake case words', () => { expect( snakeCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.stories.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -195,9 +195,9 @@ describe('Snake case words', () => { expect( snakeCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.mock.js' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.mock.js', ) - ] + ], ).toMatchSnapshot() }) }) @@ -218,9 +218,9 @@ describe('Kebab case words', () => { expect( kebabCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -228,9 +228,9 @@ describe('Kebab case words', () => { expect( kebabCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.test.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -238,9 +238,9 @@ describe('Kebab case words', () => { expect( kebabCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.stories.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -248,9 +248,9 @@ describe('Kebab case words', () => { expect( kebabCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.mock.js' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.mock.js', ) - ] + ], ).toMatchSnapshot() }) }) @@ -272,9 +272,9 @@ describe('camelCase words', () => { expect( camelCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -282,9 +282,9 @@ describe('camelCase words', () => { expect( camelCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.test.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -292,9 +292,9 @@ describe('camelCase words', () => { expect( camelCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.stories.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -302,9 +302,9 @@ describe('camelCase words', () => { expect( camelCaseWordFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.mock.js' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.mock.js', ) - ] + ], ).toMatchSnapshot() }) }) @@ -319,10 +319,10 @@ test("doesn't include test file when --tests is set to false", async () => { expect(Object.keys(withoutTestFiles)).toEqual([ path.normalize( - '/path/to/project/web/src/components/UserCell/UserCell.mock.js' + '/path/to/project/web/src/components/UserCell/UserCell.mock.js', ), path.normalize( - '/path/to/project/web/src/components/UserCell/UserCell.stories.jsx' + '/path/to/project/web/src/components/UserCell/UserCell.stories.jsx', ), path.normalize('/path/to/project/web/src/components/UserCell/UserCell.jsx'), ]) @@ -338,10 +338,10 @@ test("doesn't include storybook file when --stories is set to false", async () = expect(Object.keys(withoutStoryFiles)).toEqual([ path.normalize( - '/path/to/project/web/src/components/UserCell/UserCell.mock.js' + '/path/to/project/web/src/components/UserCell/UserCell.mock.js', ), path.normalize( - '/path/to/project/web/src/components/UserCell/UserCell.test.jsx' + '/path/to/project/web/src/components/UserCell/UserCell.test.jsx', ), path.normalize('/path/to/project/web/src/components/UserCell/UserCell.jsx'), ]) @@ -369,19 +369,19 @@ test('generates list cells if list flag passed in', async () => { }) const CELL_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.jsx' + '/path/to/project/web/src/components/MembersCell/MembersCell.jsx', ) const TEST_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.test.jsx' + '/path/to/project/web/src/components/MembersCell/MembersCell.test.jsx', ) const STORY_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.stories.jsx' + '/path/to/project/web/src/components/MembersCell/MembersCell.stories.jsx', ) const MOCK_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.mock.js' + '/path/to/project/web/src/components/MembersCell/MembersCell.mock.js', ) // Check the file names @@ -407,19 +407,19 @@ test('generates list cells if name is plural', async () => { }) const CELL_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.jsx' + '/path/to/project/web/src/components/MembersCell/MembersCell.jsx', ) const TEST_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.test.jsx' + '/path/to/project/web/src/components/MembersCell/MembersCell.test.jsx', ) const STORY_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.stories.jsx' + '/path/to/project/web/src/components/MembersCell/MembersCell.stories.jsx', ) const MOCK_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.mock.js' + '/path/to/project/web/src/components/MembersCell/MembersCell.mock.js', ) // Check the file names @@ -443,19 +443,19 @@ test('TypeScript: generates list cells if list flag passed in', async () => { }) const CELL_PATH = path.normalize( - '/path/to/project/web/src/components/BazingaCell/BazingaCell.tsx' + '/path/to/project/web/src/components/BazingaCell/BazingaCell.tsx', ) const TEST_PATH = path.normalize( - '/path/to/project/web/src/components/BazingaCell/BazingaCell.test.tsx' + '/path/to/project/web/src/components/BazingaCell/BazingaCell.test.tsx', ) const STORY_PATH = path.normalize( - '/path/to/project/web/src/components/BazingaCell/BazingaCell.stories.tsx' + '/path/to/project/web/src/components/BazingaCell/BazingaCell.stories.tsx', ) const MOCK_PATH = path.normalize( - '/path/to/project/web/src/components/BazingaCell/BazingaCell.mock.ts' + '/path/to/project/web/src/components/BazingaCell/BazingaCell.mock.ts', ) // Check the file names @@ -482,19 +482,19 @@ test('TypeScript: generates list cells if name is plural', async () => { }) const CELL_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.tsx' + '/path/to/project/web/src/components/MembersCell/MembersCell.tsx', ) const TEST_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.test.tsx' + '/path/to/project/web/src/components/MembersCell/MembersCell.test.tsx', ) const STORY_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.stories.tsx' + '/path/to/project/web/src/components/MembersCell/MembersCell.stories.tsx', ) const MOCK_PATH = path.normalize( - '/path/to/project/web/src/components/MembersCell/MembersCell.mock.ts' + '/path/to/project/web/src/components/MembersCell/MembersCell.mock.ts', ) // Check the file names @@ -518,19 +518,19 @@ test('"equipment" with list flag', async () => { }) const CELL_PATH = path.normalize( - '/path/to/project/web/src/components/EquipmentListCell/EquipmentListCell.jsx' + '/path/to/project/web/src/components/EquipmentListCell/EquipmentListCell.jsx', ) const TEST_PATH = path.normalize( - '/path/to/project/web/src/components/EquipmentListCell/EquipmentListCell.test.jsx' + '/path/to/project/web/src/components/EquipmentListCell/EquipmentListCell.test.jsx', ) const STORY_PATH = path.normalize( - '/path/to/project/web/src/components/EquipmentListCell/EquipmentListCell.stories.jsx' + '/path/to/project/web/src/components/EquipmentListCell/EquipmentListCell.stories.jsx', ) const MOCK_PATH = path.normalize( - '/path/to/project/web/src/components/EquipmentListCell/EquipmentListCell.mock.js' + '/path/to/project/web/src/components/EquipmentListCell/EquipmentListCell.mock.js', ) // Check the file names @@ -554,19 +554,19 @@ test('"equipment" withOUT list flag should find equipment by id', async () => { }) const CELL_PATH = path.normalize( - '/path/to/project/web/src/components/EquipmentCell/EquipmentCell.jsx' + '/path/to/project/web/src/components/EquipmentCell/EquipmentCell.jsx', ) const TEST_PATH = path.normalize( - '/path/to/project/web/src/components/EquipmentCell/EquipmentCell.test.jsx' + '/path/to/project/web/src/components/EquipmentCell/EquipmentCell.test.jsx', ) const STORY_PATH = path.normalize( - '/path/to/project/web/src/components/EquipmentCell/EquipmentCell.stories.jsx' + '/path/to/project/web/src/components/EquipmentCell/EquipmentCell.stories.jsx', ) const MOCK_PATH = path.normalize( - '/path/to/project/web/src/components/EquipmentCell/EquipmentCell.mock.js' + '/path/to/project/web/src/components/EquipmentCell/EquipmentCell.mock.js', ) // Check the file names @@ -590,19 +590,19 @@ test('generates a cell with a string primary id key', async () => { }) const CELL_PATH = path.normalize( - '/path/to/project/web/src/components/AddressCell/AddressCell.jsx' + '/path/to/project/web/src/components/AddressCell/AddressCell.jsx', ) const TEST_PATH = path.normalize( - '/path/to/project/web/src/components/AddressCell/AddressCell.test.jsx' + '/path/to/project/web/src/components/AddressCell/AddressCell.test.jsx', ) const STORY_PATH = path.normalize( - '/path/to/project/web/src/components/AddressCell/AddressCell.stories.jsx' + '/path/to/project/web/src/components/AddressCell/AddressCell.stories.jsx', ) const MOCK_PATH = path.normalize( - '/path/to/project/web/src/components/AddressCell/AddressCell.mock.js' + '/path/to/project/web/src/components/AddressCell/AddressCell.mock.js', ) // Check the file names @@ -629,19 +629,19 @@ test('generates list a cell with a string primary id keys', async () => { }) const CELL_PATH = path.normalize( - '/path/to/project/web/src/components/AddressesCell/AddressesCell.jsx' + '/path/to/project/web/src/components/AddressesCell/AddressesCell.jsx', ) const TEST_PATH = path.normalize( - '/path/to/project/web/src/components/AddressesCell/AddressesCell.test.jsx' + '/path/to/project/web/src/components/AddressesCell/AddressesCell.test.jsx', ) const STORY_PATH = path.normalize( - '/path/to/project/web/src/components/AddressesCell/AddressesCell.stories.jsx' + '/path/to/project/web/src/components/AddressesCell/AddressesCell.stories.jsx', ) const MOCK_PATH = path.normalize( - '/path/to/project/web/src/components/AddressesCell/AddressesCell.mock.js' + '/path/to/project/web/src/components/AddressesCell/AddressesCell.mock.js', ) // Check the file names @@ -669,7 +669,7 @@ describe('Custom query names', () => { }) const CELL_PATH = path.normalize( - '/path/to/project/web/src/components/CluesCell/CluesCell.jsx' + '/path/to/project/web/src/components/CluesCell/CluesCell.jsx', ) expect(generatedFiles[CELL_PATH]).toContain('query FindBluesClues {') @@ -682,9 +682,9 @@ describe('Custom query names', () => { tests: false, stories: false, query: 'AlreadyDefinedQueryName', - }) + }), ).rejects.toThrow( - 'Specified query name: "AlreadyDefinedQueryName" is not unique' + 'Specified query name: "AlreadyDefinedQueryName" is not unique', ) }) }) @@ -711,9 +711,9 @@ describe('Custom Id Field files', () => { expect( customIdFieldFiles[ path.normalize( - '/path/to/project/web/src/components/CustomIdFieldCell/CustomIdFieldCell.jsx' + '/path/to/project/web/src/components/CustomIdFieldCell/CustomIdFieldCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -721,9 +721,9 @@ describe('Custom Id Field files', () => { expect( customIdFieldFiles[ path.normalize( - '/path/to/project/web/src/components/CustomIdFieldCell/CustomIdFieldCell.test.jsx' + '/path/to/project/web/src/components/CustomIdFieldCell/CustomIdFieldCell.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -731,9 +731,9 @@ describe('Custom Id Field files', () => { expect( customIdFieldFiles[ path.normalize( - '/path/to/project/web/src/components/CustomIdFieldCell/CustomIdFieldCell.stories.jsx' + '/path/to/project/web/src/components/CustomIdFieldCell/CustomIdFieldCell.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -741,9 +741,9 @@ describe('Custom Id Field files', () => { expect( customIdFieldFiles[ path.normalize( - '/path/to/project/web/src/components/CustomIdFieldCell/CustomIdFieldCell.mock.js' + '/path/to/project/web/src/components/CustomIdFieldCell/CustomIdFieldCell.mock.js', ) - ] + ], ).toMatchSnapshot() }) }) @@ -766,9 +766,9 @@ describe('Custom Id Field files', () => { expect( customIdFieldListFiles[ path.normalize( - '/path/to/project/web/src/components/CustomIdFieldsCell/CustomIdFieldsCell.jsx' + '/path/to/project/web/src/components/CustomIdFieldsCell/CustomIdFieldsCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -776,9 +776,9 @@ describe('Custom Id Field files', () => { expect( customIdFieldListFiles[ path.normalize( - '/path/to/project/web/src/components/CustomIdFieldsCell/CustomIdFieldsCell.test.jsx' + '/path/to/project/web/src/components/CustomIdFieldsCell/CustomIdFieldsCell.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -786,9 +786,9 @@ describe('Custom Id Field files', () => { expect( customIdFieldListFiles[ path.normalize( - '/path/to/project/web/src/components/CustomIdFieldsCell/CustomIdFieldsCell.stories.jsx' + '/path/to/project/web/src/components/CustomIdFieldsCell/CustomIdFieldsCell.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -796,9 +796,9 @@ describe('Custom Id Field files', () => { expect( customIdFieldListFiles[ path.normalize( - '/path/to/project/web/src/components/CustomIdFieldsCell/CustomIdFieldsCell.mock.js' + '/path/to/project/web/src/components/CustomIdFieldsCell/CustomIdFieldsCell.mock.js', ) - ] + ], ).toMatchSnapshot() }) }) diff --git a/packages/cli/src/commands/generate/cell/cell.js b/packages/cli/src/commands/generate/cell/cell.js index 4adc7f6c1608..dc9dc42b1ba0 100644 --- a/packages/cli/src/commands/generate/cell/cell.js +++ b/packages/cli/src/commands/generate/cell/cell.js @@ -65,9 +65,8 @@ export const files = async ({ name, typescript, ...options }) => { let operationName = options.query if (operationName) { - const userSpecifiedOperationNameIsUnique = await operationNameIsUnique( - operationName - ) + const userSpecifiedOperationNameIsUnique = + await operationNameIsUnique(operationName) if (!userSpecifiedOperationNameIsUnique) { throw new Error(`Specified query name: "${operationName}" is not unique!`) } @@ -182,11 +181,10 @@ export const { command, description, builder, handler } = title: `Generating types ...`, task: async (_ctx, task) => { const queryFieldName = nameVariants( - removeGeneratorName(cellName, 'cell') + removeGeneratorName(cellName, 'cell'), ).camelName - const projectHasSdl = await checkProjectForQueryField( - queryFieldName - ) + const projectHasSdl = + await checkProjectForQueryField(queryFieldName) if (projectHasSdl) { const { errors } = await generateTypes() @@ -201,7 +199,7 @@ export const { command, description, builder, handler } = addFunctionToRollback(generateTypes, true) } else { task.skip( - `Skipping type generation: no SDL defined for "${queryFieldName}". To generate types, run 'yarn rw g sdl ${queryFieldName}'.` + `Skipping type generation: no SDL defined for "${queryFieldName}". To generate types, run 'yarn rw g sdl ${queryFieldName}'.`, ) } }, diff --git a/packages/cli/src/commands/generate/cell/utils/utils.js b/packages/cli/src/commands/generate/cell/utils/utils.js index efca1d8f5bcd..1ad9da3371a7 100644 --- a/packages/cli/src/commands/generate/cell/utils/utils.js +++ b/packages/cli/src/commands/generate/cell/utils/utils.js @@ -14,10 +14,10 @@ export const getCellOperationNames = async () => { export const uniqueOperationName = async ( name, - { index = 1, list = false } + { index = 1, list = false }, ) => { let operationName = pascalcase( - index <= 1 ? `find_${name}_query` : `find_${name}_query_${index}` + index <= 1 ? `find_${name}_query` : `find_${name}_query_${index}`, ) if (list) { diff --git a/packages/cli/src/commands/generate/component/__tests__/component.test.ts b/packages/cli/src/commands/generate/component/__tests__/component.test.ts index 582fef4ed5a3..bda71aca55be 100644 --- a/packages/cli/src/commands/generate/component/__tests__/component.test.ts +++ b/packages/cli/src/commands/generate/component/__tests__/component.test.ts @@ -69,7 +69,7 @@ test('creates a single word component', () => { expect( singleWordDefaultFiles[ path.normalize('/path/to/project/web/src/components/User/User.jsx') - ] + ], ).toMatchSnapshot() }) @@ -77,7 +77,7 @@ test('creates a single word component test', () => { expect( singleWordDefaultFiles[ path.normalize('/path/to/project/web/src/components/User/User.test.jsx') - ] + ], ).toMatchSnapshot() }) @@ -85,9 +85,9 @@ test('creates a single word component story', () => { expect( singleWordDefaultFiles[ path.normalize( - '/path/to/project/web/src/components/User/User.stories.jsx' + '/path/to/project/web/src/components/User/User.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -95,9 +95,9 @@ test('creates a multi word component', () => { expect( multiWordDefaultFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/UserProfile.jsx' + '/path/to/project/web/src/components/UserProfile/UserProfile.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -105,16 +105,16 @@ test('creates a TS component and test', () => { expect( typescriptFiles[ path.normalize( - '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.tsx' + '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.tsx', ) - ] + ], ).toMatchSnapshot() expect( typescriptFiles[ path.normalize( - '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.test.tsx' + '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.test.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -122,9 +122,9 @@ test('creates a multi word component test', () => { expect( multiWordDefaultFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/UserProfile.test.jsx' + '/path/to/project/web/src/components/UserProfile/UserProfile.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -132,9 +132,9 @@ test('creates a multi word component story', () => { expect( multiWordDefaultFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/UserProfile.stories.jsx' + '/path/to/project/web/src/components/UserProfile/UserProfile.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -142,16 +142,16 @@ test('creates JS component files if typescript = false', () => { expect( javascriptFiles[ path.normalize( - '/path/to/project/web/src/components/JavascriptUser/JavascriptUser.jsx' + '/path/to/project/web/src/components/JavascriptUser/JavascriptUser.jsx', ) - ] + ], ).not.toBeUndefined() expect( javascriptFiles[ path.normalize( - '/path/to/project/web/src/components/JavascriptUser/JavascriptUser.test.jsx' + '/path/to/project/web/src/components/JavascriptUser/JavascriptUser.test.jsx', ) - ] + ], ).not.toBeUndefined() }) @@ -159,26 +159,26 @@ test('creates TS component files if typescript = true', () => { expect( typescriptFiles[ path.normalize( - '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.tsx' + '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.tsx', ) - ] + ], ).not.toBeUndefined() expect( typescriptFiles[ path.normalize( - '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.test.tsx' + '/path/to/project/web/src/components/TypescriptUser/TypescriptUser.test.tsx', ) - ] + ], ).not.toBeUndefined() }) test("doesn't include storybook file when --stories is set to false", () => { expect(Object.keys(withoutStoryFiles)).toEqual([ path.normalize( - '/path/to/project/web/src/components/WithoutStories/WithoutStories.test.jsx' + '/path/to/project/web/src/components/WithoutStories/WithoutStories.test.jsx', ), path.normalize( - '/path/to/project/web/src/components/WithoutStories/WithoutStories.jsx' + '/path/to/project/web/src/components/WithoutStories/WithoutStories.jsx', ), ]) }) @@ -186,10 +186,10 @@ test("doesn't include storybook file when --stories is set to false", () => { test("doesn't include test file when --tests is set to false", () => { expect(Object.keys(withoutTestFiles)).toEqual([ path.normalize( - '/path/to/project/web/src/components/WithoutTests/WithoutTests.stories.jsx' + '/path/to/project/web/src/components/WithoutTests/WithoutTests.stories.jsx', ), path.normalize( - '/path/to/project/web/src/components/WithoutTests/WithoutTests.jsx' + '/path/to/project/web/src/components/WithoutTests/WithoutTests.jsx', ), ]) }) diff --git a/packages/cli/src/commands/generate/dataMigration/dataMigration.js b/packages/cli/src/commands/generate/dataMigration/dataMigration.js index 719272e17bcc..4b71365ea575 100644 --- a/packages/cli/src/commands/generate/dataMigration/dataMigration.js +++ b/packages/cli/src/commands/generate/dataMigration/dataMigration.js @@ -13,7 +13,7 @@ import { prepareForRollback } from '../../../lib/rollback' import { validateName, yargsDefaults } from '../helpers' const POST_RUN_INSTRUCTIONS = `Next steps...\n\n ${c.warning( - 'After writing your migration, you can run it with:' + 'After writing your migration, you can run it with:', )} yarn rw dataMigrate up @@ -54,8 +54,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#generate-datamigration' - )}` + 'https://redwoodjs.com/docs/cli-commands#generate-datamigration', + )}`, ) // Merge generator defaults in @@ -88,7 +88,7 @@ export const handler = async (args) => { }, }, ].filter(Boolean), - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/generate/dbAuth/__tests__/dbAuth.test.js b/packages/cli/src/commands/generate/dbAuth/__tests__/dbAuth.test.js index a1e3e621b144..cf7a9a492737 100644 --- a/packages/cli/src/commands/generate/dbAuth/__tests__/dbAuth.test.js +++ b/packages/cli/src/commands/generate/dbAuth/__tests__/dbAuth.test.js @@ -38,8 +38,8 @@ mockFiles[ .readFileSync( path.join( __dirname, - `../../scaffold/templates/assets/scaffold.css.template` - ) + `../../scaffold/templates/assets/scaffold.css.template`, + ), ) .toString() @@ -47,8 +47,8 @@ mockFiles[getPaths().web.routes] = realfs .readFileSync( path.join( __dirname, - `../../../../../../../__fixtures__/example-todo-main/web/src/Routes.js` - ) + `../../../../../../../__fixtures__/example-todo-main/web/src/Routes.js`, + ), ) .toString() @@ -56,8 +56,8 @@ mockFiles[getPaths().web.app] = realfs .readFileSync( path.join( __dirname, - `../../../../../../../__fixtures__/example-todo-main/web/src/App.js` - ) + `../../../../../../../__fixtures__/example-todo-main/web/src/App.js`, + ), ) .toString() @@ -76,7 +76,7 @@ describe('dbAuth', () => { it('creates a signup page', async () => { expect(await dbAuth.files(true, false)).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx' + '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx', ), ]) }) @@ -235,8 +235,8 @@ describe('dbAuth', () => { const forgotPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx', + ), ) .toString() expect(forgotPasswordPage).toMatchSnapshot() @@ -244,8 +244,8 @@ describe('dbAuth', () => { const loginPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx' - ) + '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx', + ), ) .toString() expect(loginPage).toMatchSnapshot() @@ -253,8 +253,8 @@ describe('dbAuth', () => { const resetPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx', + ), ) .toString() expect(resetPasswordPage).toMatchSnapshot() @@ -262,8 +262,8 @@ describe('dbAuth', () => { const signupPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx' - ) + '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx', + ), ) .toString() expect(signupPage).toMatchSnapshot() @@ -284,8 +284,8 @@ describe('dbAuth', () => { const forgotPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx', + ), ) .toString() expect(forgotPasswordPage).toMatchSnapshot() @@ -293,8 +293,8 @@ describe('dbAuth', () => { const loginPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx' - ) + '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx', + ), ) .toString() expect(loginPage).toMatchSnapshot() @@ -302,8 +302,8 @@ describe('dbAuth', () => { const resetPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx', + ), ) .toString() expect(resetPasswordPage).toMatchSnapshot() @@ -311,8 +311,8 @@ describe('dbAuth', () => { const signupPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx' - ) + '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx', + ), ) .toString() expect(signupPage).toMatchSnapshot() @@ -335,8 +335,8 @@ describe('dbAuth', () => { const forgotPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx', + ), ) .toString() expect(forgotPasswordPage).toMatchSnapshot() @@ -344,8 +344,8 @@ describe('dbAuth', () => { const loginPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx' - ) + '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx', + ), ) .toString() expect(loginPage).toMatchSnapshot() @@ -353,8 +353,8 @@ describe('dbAuth', () => { const resetPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx', + ), ) .toString() expect(resetPasswordPage).toMatchSnapshot() @@ -362,8 +362,8 @@ describe('dbAuth', () => { const signupPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx' - ) + '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx', + ), ) .toString() expect(signupPage).toMatchSnapshot() @@ -384,8 +384,8 @@ describe('dbAuth', () => { const forgotPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx', + ), ) .toString() expect(forgotPasswordPage).toMatchSnapshot() @@ -393,8 +393,8 @@ describe('dbAuth', () => { const loginPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx' - ) + '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx', + ), ) .toString() expect(loginPage).toMatchSnapshot() @@ -402,8 +402,8 @@ describe('dbAuth', () => { const resetPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx', + ), ) .toString() expect(resetPasswordPage).toMatchSnapshot() @@ -411,8 +411,8 @@ describe('dbAuth', () => { const signupPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx' - ) + '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx', + ), ) .toString() expect(signupPage).toMatchSnapshot() @@ -435,8 +435,8 @@ describe('dbAuth', () => { const forgotPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx', + ), ) .toString() expect(forgotPasswordPage).toMatchSnapshot() @@ -444,8 +444,8 @@ describe('dbAuth', () => { const loginPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx' - ) + '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx', + ), ) .toString() expect(loginPage).toMatchSnapshot() @@ -453,8 +453,8 @@ describe('dbAuth', () => { const resetPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx', + ), ) .toString() expect(resetPasswordPage).toMatchSnapshot() @@ -462,8 +462,8 @@ describe('dbAuth', () => { const signupPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx' - ) + '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx', + ), ) .toString() expect(signupPage).toMatchSnapshot() @@ -485,8 +485,8 @@ describe('dbAuth', () => { const forgotPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx', + ), ) .toString() expect(forgotPasswordPage).toMatchSnapshot() @@ -494,8 +494,8 @@ describe('dbAuth', () => { const loginPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx' - ) + '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx', + ), ) .toString() expect(loginPage).toMatchSnapshot() @@ -503,8 +503,8 @@ describe('dbAuth', () => { const resetPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx', + ), ) .toString() expect(resetPasswordPage).toMatchSnapshot() @@ -512,8 +512,8 @@ describe('dbAuth', () => { const signupPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx' - ) + '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx', + ), ) .toString() expect(signupPage).toMatchSnapshot() @@ -539,8 +539,8 @@ describe('dbAuth', () => { const forgotPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx', + ), ) .toString() expect(forgotPasswordPage).toMatchSnapshot() @@ -548,8 +548,8 @@ describe('dbAuth', () => { const loginPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx' - ) + '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx', + ), ) .toString() expect(loginPage).toMatchSnapshot() @@ -557,8 +557,8 @@ describe('dbAuth', () => { const resetPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx', + ), ) .toString() expect(resetPasswordPage).toMatchSnapshot() @@ -566,8 +566,8 @@ describe('dbAuth', () => { const signupPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx' - ) + '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx', + ), ) .toString() expect(signupPage).toMatchSnapshot() @@ -594,8 +594,8 @@ describe('dbAuth', () => { const forgotPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx', + ), ) .toString() expect(forgotPasswordPage).toMatchSnapshot() @@ -603,8 +603,8 @@ describe('dbAuth', () => { const loginPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx' - ) + '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx', + ), ) .toString() expect(loginPage).toMatchSnapshot() @@ -612,8 +612,8 @@ describe('dbAuth', () => { const resetPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx', + ), ) .toString() expect(resetPasswordPage).toMatchSnapshot() @@ -621,8 +621,8 @@ describe('dbAuth', () => { const signupPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx' - ) + '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx', + ), ) .toString() expect(signupPage).toMatchSnapshot() @@ -651,8 +651,8 @@ describe('dbAuth', () => { const forgotPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ForgotPasswordPage/ForgotPasswordPage.jsx', + ), ) .toString() expect(forgotPasswordPage).toMatchSnapshot() @@ -660,8 +660,8 @@ describe('dbAuth', () => { const loginPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx' - ) + '/path/to/project/web/src/pages/LoginPage/LoginPage.jsx', + ), ) .toString() expect(loginPage).toMatchSnapshot() @@ -669,8 +669,8 @@ describe('dbAuth', () => { const resetPasswordPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx' - ) + '/path/to/project/web/src/pages/ResetPasswordPage/ResetPasswordPage.jsx', + ), ) .toString() expect(resetPasswordPage).toMatchSnapshot() @@ -678,8 +678,8 @@ describe('dbAuth', () => { const signupPage = fs .readFileSync( path.normalize( - '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx' - ) + '/path/to/project/web/src/pages/SignupPage/SignupPage.jsx', + ), ) .toString() expect(signupPage).toMatchSnapshot() diff --git a/packages/cli/src/commands/generate/dbAuth/dbAuth.js b/packages/cli/src/commands/generate/dbAuth/dbAuth.js index 94581d256932..734a1bc20adc 100644 --- a/packages/cli/src/commands/generate/dbAuth/dbAuth.js +++ b/packages/cli/src/commands/generate/dbAuth/dbAuth.js @@ -113,8 +113,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/authentication#self-hosted-auth-installation-and-setup' - )}` + 'https://redwoodjs.com/docs/authentication#self-hosted-auth-installation-and-setup', + )}`, ) // Merge generator defaults in @@ -158,7 +158,7 @@ export const files = async ({ generator: 'dbAuth', templatePath: 'forgotPassword.tsx.template', templateVars, - }) + }), ) } @@ -174,7 +174,7 @@ export const files = async ({ ? 'login.webAuthn.tsx.template' : 'login.tsx.template', templateVars, - }) + }), ) } @@ -188,7 +188,7 @@ export const files = async ({ generator: 'dbAuth', templatePath: 'resetPassword.tsx.template', templateVars, - }) + }), ) } @@ -202,7 +202,7 @@ export const files = async ({ generator: 'dbAuth', templatePath: 'signup.tsx.template', templateVars, - }) + }), ) } @@ -217,9 +217,9 @@ export const files = async ({ const scaffoldTemplate = await generateTemplate( path.join( __dirname, - '../scaffold/templates/assets/scaffold.css.template' + '../scaffold/templates/assets/scaffold.css.template', ), - { name: 'scaffold' } + { name: 'scaffold' }, ) files.push([scaffoldOutputPath, scaffoldTemplate]) @@ -269,7 +269,7 @@ const tasks = ({ task: async (subctx, subtask) => { if (usernameLabel) { subtask.skip( - `Argument username-label is set, using: "${usernameLabel}"` + `Argument username-label is set, using: "${usernameLabel}"`, ) return } @@ -287,7 +287,7 @@ const tasks = ({ task: async (subctx, subtask) => { if (passwordLabel) { subtask.skip( - `Argument password-label passed, using: "${passwordLabel}"` + `Argument password-label passed, using: "${passwordLabel}"`, ) return } @@ -310,7 +310,7 @@ const tasks = ({ task.skip( `Querying WebAuthn addition: argument webauthn passed, WebAuthn ${ webauthn ? '' : 'not' - } included` + } included`, ) return } @@ -370,7 +370,7 @@ const tasks = ({ rendererOptions: { collapseSubtasks: false }, injectWrapper: { enquirer: enquirer || new Enquirer() }, exitOnError: true, - } + }, ) } diff --git a/packages/cli/src/commands/generate/directive/__tests__/directive.test.ts b/packages/cli/src/commands/generate/directive/__tests__/directive.test.ts index 4d835ca36732..df783a8ac747 100644 --- a/packages/cli/src/commands/generate/directive/__tests__/directive.test.ts +++ b/packages/cli/src/commands/generate/directive/__tests__/directive.test.ts @@ -18,10 +18,10 @@ test('creates a JavaScript validator directive', async () => { }) const expectedOutputPath = path.normalize( - '/path/to/project/api/src/directives/requireAdmin/requireAdmin.js' + '/path/to/project/api/src/directives/requireAdmin/requireAdmin.js', ) const expectedTestOutputPath = path.normalize( - '/path/to/project/api/src/directives/requireAdmin/requireAdmin.test.js' + '/path/to/project/api/src/directives/requireAdmin/requireAdmin.test.js', ) expect(Object.keys(output)).toContainEqual(expectedOutputPath) @@ -39,10 +39,10 @@ test('creates a TypeScript transformer directive', async () => { }) const expectedOutputPath = path.normalize( - '/path/to/project/api/src/directives/bazingaFooBar/bazingaFooBar.ts' + '/path/to/project/api/src/directives/bazingaFooBar/bazingaFooBar.ts', ) const expectedTestOutputPath = path.normalize( - '/path/to/project/api/src/directives/bazingaFooBar/bazingaFooBar.test.ts' + '/path/to/project/api/src/directives/bazingaFooBar/bazingaFooBar.test.ts', ) expect(Object.keys(output)).toContainEqual(expectedOutputPath) diff --git a/packages/cli/src/commands/generate/directive/directive.js b/packages/cli/src/commands/generate/directive/directive.js index 9fd98d5a84d3..0a48273c900e 100644 --- a/packages/cli/src/commands/generate/directive/directive.js +++ b/packages/cli/src/commands/generate/directive/directive.js @@ -58,7 +58,7 @@ export const files = async ({ name, typescript = false, type, tests }) => { outputPath: path.join( getPaths().api.directives, camelName, - testOutputFilename + testOutputFilename, ), templateVars: { camelName }, }) @@ -115,7 +115,7 @@ export const handler = async (args) => { }) const POST_RUN_INSTRUCTIONS = `Next steps...\n\n ${c.warning( - 'After modifying your directive, you can add it to your SDLs e.g.:' + 'After modifying your directive, you can add it to your SDLs e.g.:', )} ${c.info('// example todo.sdl.js')} ${c.info('# Option A: Add it to a field')} @@ -191,7 +191,7 @@ export const handler = async (args) => { }, }, ].filter(Boolean), - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/generate/function/__tests__/function.test.ts b/packages/cli/src/commands/generate/function/__tests__/function.test.ts index 442b8aa5f1a9..f46f130c6f56 100644 --- a/packages/cli/src/commands/generate/function/__tests__/function.test.ts +++ b/packages/cli/src/commands/generate/function/__tests__/function.test.ts @@ -27,7 +27,7 @@ describe('Single word default files', async () => { expect.stringContaining('foo.js'), expect.stringContaining('foo.test.js'), expect.stringContaining('foo.scenarios.js'), - ]) + ]), ) }) @@ -35,21 +35,21 @@ describe('Single word default files', async () => { expect( singleWordDefaultFiles[ path.normalize('/path/to/project/api/src/functions/foo/foo.js') - ] + ], ).toMatchSnapshot() expect( singleWordDefaultFiles[ path.normalize('/path/to/project/api/src/functions/foo/foo.test.js') - ] + ], ).toMatchSnapshot('Test snapshot') expect( singleWordDefaultFiles[ path.normalize( - '/path/to/project/api/src/functions/foo/foo.scenarios.js' + '/path/to/project/api/src/functions/foo/foo.scenarios.js', ) - ] + ], ).toMatchSnapshot('Scenario snapshot') }) }) @@ -71,7 +71,7 @@ test('creates a multi word function file', async () => { expect( multiWordDefaultFiles[ path.normalize('/path/to/project/api/src/functions/sendMail/sendMail.js') - ] + ], ).toMatchSnapshot() }) @@ -83,9 +83,9 @@ test('creates a .js file if --javascript=true', async () => { expect( javascriptFiles[ path.normalize( - '/path/to/project/api/src/functions/javascriptFunction/javascriptFunction.js' + '/path/to/project/api/src/functions/javascriptFunction/javascriptFunction.js', ) - ] + ], ).toMatchSnapshot() // ^ JS-function-args should be stripped of their types and consequently the unused 'aws-lamda' import removed. // https://babeljs.io/docs/en/babel-plugin-transform-typescript @@ -105,15 +105,15 @@ test('creates a .ts file if --typescript=true', async () => { expect.stringContaining('typescriptFunction.ts'), expect.stringContaining('typescriptFunction.test.ts'), expect.stringContaining('typescriptFunction.scenarios.ts'), - ]) + ]), ) expect( typescriptFiles[ path.normalize( - '/path/to/project/api/src/functions/typescriptFunction/typescriptFunction.ts' + '/path/to/project/api/src/functions/typescriptFunction/typescriptFunction.ts', ) - ] + ], ).toMatchSnapshot() // ^ TS-functions, on the other hand, retain the 'aws-lamda' import and type-declartions. }) diff --git a/packages/cli/src/commands/generate/function/function.js b/packages/cli/src/commands/generate/function/function.js index eba8a117b596..c0b9f2afb499 100644 --- a/packages/cli/src/commands/generate/function/function.js +++ b/packages/cli/src/commands/generate/function/function.js @@ -36,7 +36,7 @@ export const files = async ({ outputPath: path.join( getPaths().api.functions, functionName, - `${functionName}${extension}` + `${functionName}${extension}`, ), }) @@ -54,7 +54,7 @@ export const files = async ({ outputPath: path.join( getPaths().api.functions, functionName, - `${functionName}.test${extension}` + `${functionName}.test${extension}`, ), }) @@ -69,7 +69,7 @@ export const files = async ({ outputPath: path.join( getPaths().api.functions, functionName, - `${functionName}.scenarios${extension}` + `${functionName}.scenarios${extension}`, ), }) @@ -112,8 +112,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#generate-function' - )}` + 'https://redwoodjs.com/docs/cli-commands#generate-function', + )}`, ) // Add default options, includes '--typescript', '--javascript', '--force', ... @@ -144,7 +144,7 @@ export const handler = async ({ name, force, ...rest }) => { }, }, ], - { rendererOptions: { collapseSubtasks: false }, exitOnError: true } + { rendererOptions: { collapseSubtasks: false }, exitOnError: true }, ) try { @@ -160,16 +160,16 @@ export const handler = async ({ name, force, ...rest }) => { console.info( c.bold( 'When deployed, a custom serverless function is an open API endpoint and ' + - 'is your responsibility to secure appropriately.' - ) + 'is your responsibility to secure appropriately.', + ), ) console.info('') console.info( `Please consult the ${terminalLink( 'Serverless Function Considerations', - 'https://redwoodjs.com/docs/serverless-functions#security-considerations' - )} in the RedwoodJS documentation for more information.` + 'https://redwoodjs.com/docs/serverless-functions#security-considerations', + )} in the RedwoodJS documentation for more information.`, ) console.info('') } catch (e) { diff --git a/packages/cli/src/commands/generate/helpers.js b/packages/cli/src/commands/generate/helpers.js index 0b8ad76e3518..3ac8e2e43c92 100644 --- a/packages/cli/src/commands/generate/helpers.js +++ b/packages/cli/src/commands/generate/helpers.js @@ -32,7 +32,7 @@ export const customOrDefaultTemplatePath = ({ const customPath = path.join( getPaths()[side].generators, generator, - templatePath + templatePath, ) if (fs.existsSync(customPath)) { @@ -75,7 +75,7 @@ export const templateForComponentFile = async ({ const content = await generateTemplate(fullTemplatePath, { name, outputPath: ensurePosixPath( - `./${path.relative(getPaths().base, componentOutputPath)}` + `./${path.relative(getPaths().base, componentOutputPath)}`, ), ...templateVars, }) @@ -144,7 +144,7 @@ export const yargsDefaults = { export const validateName = (name) => { if (name.match(/^\W/)) { throw new Error( - 'The argument must start with a letter, number or underscore.' + 'The argument must start with a letter, number or underscore.', ) } } @@ -175,8 +175,8 @@ export const createYargsForComponentGeneration = ({ .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - `https://redwoodjs.com/docs/cli-commands#generate-${componentName}` - )}` + `https://redwoodjs.com/docs/cli-commands#generate-${componentName}`, + )}`, ) .option('tests', { description: 'Generate test files', @@ -243,7 +243,7 @@ export const createYargsForComponentGeneration = ({ rendererOptions: { collapseSubtasks: false }, exitOnError: true, renderer: options.verbose && 'verbose', - } + }, ) if (options.rollback && !options.force) { diff --git a/packages/cli/src/commands/generate/layout/__tests__/layout.test.ts b/packages/cli/src/commands/generate/layout/__tests__/layout.test.ts index a7d81477a233..8e8436c75040 100644 --- a/packages/cli/src/commands/generate/layout/__tests__/layout.test.ts +++ b/packages/cli/src/commands/generate/layout/__tests__/layout.test.ts @@ -23,9 +23,9 @@ describe('Single Word default files', async () => { expect( singleWordDefaultFiles[ path.normalize( - '/path/to/project/web/src/layouts/AppLayout/AppLayout.jsx' + '/path/to/project/web/src/layouts/AppLayout/AppLayout.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -33,9 +33,9 @@ describe('Single Word default files', async () => { expect( singleWordDefaultFiles[ path.normalize( - '/path/to/project/web/src/layouts/AppLayout/AppLayout.test.jsx' + '/path/to/project/web/src/layouts/AppLayout/AppLayout.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -43,9 +43,9 @@ describe('Single Word default files', async () => { expect( singleWordDefaultFiles[ path.normalize( - '/path/to/project/web/src/layouts/AppLayout/AppLayout.stories.jsx' + '/path/to/project/web/src/layouts/AppLayout/AppLayout.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) }) @@ -61,9 +61,9 @@ describe('Multi word default files', async () => { expect( multiWordDefaultFiles[ path.normalize( - '/path/to/project/web/src/layouts/SinglePageLayout/SinglePageLayout.jsx' + '/path/to/project/web/src/layouts/SinglePageLayout/SinglePageLayout.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -71,9 +71,9 @@ describe('Multi word default files', async () => { expect( multiWordDefaultFiles[ path.normalize( - '/path/to/project/web/src/layouts/SinglePageLayout/SinglePageLayout.test.jsx' + '/path/to/project/web/src/layouts/SinglePageLayout/SinglePageLayout.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -81,9 +81,9 @@ describe('Multi word default files', async () => { expect( multiWordDefaultFiles[ path.normalize( - '/path/to/project/web/src/layouts/SinglePageLayout/SinglePageLayout.stories.jsx' + '/path/to/project/web/src/layouts/SinglePageLayout/SinglePageLayout.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) }) @@ -100,16 +100,16 @@ describe('JS Files', async () => { expect( javascriptFiles[ path.normalize( - '/path/to/project/web/src/layouts/JavascriptPageLayout/JavascriptPageLayout.jsx' + '/path/to/project/web/src/layouts/JavascriptPageLayout/JavascriptPageLayout.jsx', ) - ] + ], ).not.toBeUndefined() expect( javascriptFiles[ path.normalize( - '/path/to/project/web/src/layouts/JavascriptPageLayout/JavascriptPageLayout.test.jsx' + '/path/to/project/web/src/layouts/JavascriptPageLayout/JavascriptPageLayout.test.jsx', ) - ] + ], ).not.toBeUndefined() }) }) @@ -124,13 +124,13 @@ test('trims Layout from end of name', async () => { const layoutCode = files[ path.normalize( - '/path/to/project/web/src/layouts/BazingaLayout/BazingaLayout.jsx' + '/path/to/project/web/src/layouts/BazingaLayout/BazingaLayout.jsx', ) ] expect(layoutCode).not.toBeUndefined() expect( - layoutCode.split('\n').includes('export default BazingaLayout') + layoutCode.split('\n').includes('export default BazingaLayout'), ).toBeTruthy() }) @@ -144,13 +144,13 @@ test('Does not trim Layout from beginning of name', async () => { const layoutCode = files[ path.normalize( - '/path/to/project/web/src/layouts/LayoutForBazingaLayout/LayoutForBazingaLayout.jsx' + '/path/to/project/web/src/layouts/LayoutForBazingaLayout/LayoutForBazingaLayout.jsx', ) ] expect(layoutCode).not.toBeUndefined() expect( - layoutCode.split('\n').includes('export default LayoutForBazingaLayout') + layoutCode.split('\n').includes('export default LayoutForBazingaLayout'), ).toBeTruthy() }) @@ -164,13 +164,13 @@ test('Does not trim Layout from middle of name', async () => { const layoutCode = files[ path.normalize( - '/path/to/project/web/src/layouts/MyLayoutForBazingaLayout/MyLayoutForBazingaLayout.jsx' + '/path/to/project/web/src/layouts/MyLayoutForBazingaLayout/MyLayoutForBazingaLayout.jsx', ) ] expect(layoutCode).not.toBeUndefined() expect( - layoutCode.split('\n').includes('export default MyLayoutForBazingaLayout') + layoutCode.split('\n').includes('export default MyLayoutForBazingaLayout'), ).toBeTruthy() }) @@ -184,13 +184,13 @@ test('Only trims Layout once', async () => { const layoutCode = files[ path.normalize( - '/path/to/project/web/src/layouts/BazingaLayoutLayout/BazingaLayoutLayout.jsx' + '/path/to/project/web/src/layouts/BazingaLayoutLayout/BazingaLayoutLayout.jsx', ) ] expect(layoutCode).not.toBeUndefined() expect( - layoutCode.split('\n').includes('export default BazingaLayoutLayout') + layoutCode.split('\n').includes('export default BazingaLayoutLayout'), ).toBeTruthy() }) @@ -206,16 +206,16 @@ describe('TS files', async () => { expect( typescriptFiles[ path.normalize( - '/path/to/project/web/src/layouts/TypescriptPageLayout/TypescriptPageLayout.tsx' + '/path/to/project/web/src/layouts/TypescriptPageLayout/TypescriptPageLayout.tsx', ) - ] + ], ).not.toBeUndefined() expect( typescriptFiles[ path.normalize( - '/path/to/project/web/src/layouts/TypescriptPageLayout/TypescriptPageLayout.test.tsx' + '/path/to/project/web/src/layouts/TypescriptPageLayout/TypescriptPageLayout.test.tsx', ) - ] + ], ).not.toBeUndefined() }) }) @@ -230,10 +230,10 @@ test("doesn't include storybook file when --stories is set to false", async () = expect(Object.keys(withoutStoryFiles)).toEqual([ path.normalize( - '/path/to/project/web/src/layouts/WithoutStoriesLayout/WithoutStoriesLayout.test.jsx' + '/path/to/project/web/src/layouts/WithoutStoriesLayout/WithoutStoriesLayout.test.jsx', ), path.normalize( - '/path/to/project/web/src/layouts/WithoutStoriesLayout/WithoutStoriesLayout.jsx' + '/path/to/project/web/src/layouts/WithoutStoriesLayout/WithoutStoriesLayout.jsx', ), ]) }) @@ -247,10 +247,10 @@ test("doesn't include test file when --tests is set to false", async () => { expect(Object.keys(withoutTestFiles)).toEqual([ path.normalize( - '/path/to/project/web/src/layouts/WithoutTestsLayout/WithoutTestsLayout.stories.jsx' + '/path/to/project/web/src/layouts/WithoutTestsLayout/WithoutTestsLayout.stories.jsx', ), path.normalize( - '/path/to/project/web/src/layouts/WithoutTestsLayout/WithoutTestsLayout.jsx' + '/path/to/project/web/src/layouts/WithoutTestsLayout/WithoutTestsLayout.jsx', ), ]) }) @@ -264,9 +264,9 @@ test('JavaScript: includes skip link when --skipLink is set to true', async () = expect( withSkipLinkFilesJS[ path.normalize( - '/path/to/project/web/src/layouts/A11yLayout/A11yLayout.jsx' + '/path/to/project/web/src/layouts/A11yLayout/A11yLayout.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -280,8 +280,8 @@ test('TypeScript: includes skip link when --skipLink is set to true', async () = expect( withSkipLinkFilesTS[ path.normalize( - '/path/to/project/web/src/layouts/A11yLayout/A11yLayout.tsx' + '/path/to/project/web/src/layouts/A11yLayout/A11yLayout.tsx', ) - ] + ], ).toMatchSnapshot() }) diff --git a/packages/cli/src/commands/generate/model/model.js b/packages/cli/src/commands/generate/model/model.js index 16930a33f0fd..0b19bc348a38 100644 --- a/packages/cli/src/commands/generate/model/model.js +++ b/packages/cli/src/commands/generate/model/model.js @@ -37,8 +37,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'RedwoodRecord Reference', - 'https://redwoodjs.com/docs/redwoodrecord' - )}` + 'https://redwoodjs.com/docs/redwoodrecord', + )}`, ) Object.entries(yargsDefaults).forEach(([option, config]) => { @@ -71,7 +71,7 @@ export const handler = async ({ force, ...args }) => { }, }, ].filter(Boolean), - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/generate/page/__tests__/page.test.js b/packages/cli/src/commands/generate/page/__tests__/page.test.js index 4d0c5341d8a0..de893d4f6eca 100644 --- a/packages/cli/src/commands/generate/page/__tests__/page.test.js +++ b/packages/cli/src/commands/generate/page/__tests__/page.test.js @@ -68,7 +68,7 @@ describe('Single world files', async () => { expect( singleWordFiles[ path.normalize('/path/to/project/web/src/pages/HomePage/HomePage.jsx') - ] + ], ).toMatchSnapshot() }) @@ -76,9 +76,9 @@ describe('Single world files', async () => { expect( singleWordFiles[ path.normalize( - '/path/to/project/web/src/pages/HomePage/HomePage.test.jsx' + '/path/to/project/web/src/pages/HomePage/HomePage.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -86,9 +86,9 @@ describe('Single world files', async () => { expect( singleWordFiles[ path.normalize( - '/path/to/project/web/src/pages/HomePage/HomePage.stories.jsx' + '/path/to/project/web/src/pages/HomePage/HomePage.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) }) @@ -105,9 +105,9 @@ describe('multiWorldFiles', async () => { expect( multiWordFiles[ path.normalize( - '/path/to/project/web/src/pages/ContactUsPage/ContactUsPage.jsx' + '/path/to/project/web/src/pages/ContactUsPage/ContactUsPage.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -115,9 +115,9 @@ describe('multiWorldFiles', async () => { expect( multiWordFiles[ path.normalize( - '/path/to/project/web/src/pages/ContactUsPage/ContactUsPage.test.jsx' + '/path/to/project/web/src/pages/ContactUsPage/ContactUsPage.test.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -125,9 +125,9 @@ describe('multiWorldFiles', async () => { expect( multiWordFiles[ path.normalize( - '/path/to/project/web/src/pages/ContactUsPage/ContactUsPage.stories.jsx' + '/path/to/project/web/src/pages/ContactUsPage/ContactUsPage.stories.jsx', ) - ] + ], ).toMatchSnapshot() }) }) @@ -144,7 +144,7 @@ describe('Plural word files', async () => { expect( pluralWordFiles[ path.normalize('/path/to/project/web/src/pages/CatsPage/CatsPage.jsx') - ] + ], ).toMatchSnapshot() }) }) @@ -161,7 +161,7 @@ describe('paramFiles', async () => { expect( paramFiles[ path.normalize('/path/to/project/web/src/pages/PostPage/PostPage.jsx') - ] + ], ).toMatchSnapshot() }) @@ -169,9 +169,9 @@ describe('paramFiles', async () => { expect( paramFiles[ path.normalize( - '/path/to/project/web/src/pages/PostPage/PostPage.test.jsx' + '/path/to/project/web/src/pages/PostPage/PostPage.test.jsx', ) - ] + ], ).toMatchSnapshot() }) }) @@ -187,10 +187,10 @@ describe('No test files', async () => { it('doesnt create a test for page component when tests=false', () => { expect(Object.keys(noTestsFiles)).toEqual([ path.normalize( - '/path/to/project/web/src/pages/NoTestsPage/NoTestsPage.stories.jsx' + '/path/to/project/web/src/pages/NoTestsPage/NoTestsPage.stories.jsx', ), path.normalize( - '/path/to/project/web/src/pages/NoTestsPage/NoTestsPage.jsx' + '/path/to/project/web/src/pages/NoTestsPage/NoTestsPage.jsx', ), ]) }) @@ -207,10 +207,10 @@ describe('No stories files', async () => { it('doesnt create a story for page component when stories=false', () => { expect(Object.keys(noStoriesFiles)).toEqual([ path.normalize( - '/path/to/project/web/src/pages/NoStoriesPage/NoStoriesPage.test.jsx' + '/path/to/project/web/src/pages/NoStoriesPage/NoStoriesPage.test.jsx', ), path.normalize( - '/path/to/project/web/src/pages/NoStoriesPage/NoStoriesPage.jsx' + '/path/to/project/web/src/pages/NoStoriesPage/NoStoriesPage.jsx', ), ]) }) @@ -453,25 +453,25 @@ describe('TS Files', async () => { expect( typescriptFiles[ path.normalize( - '/path/to/project/web/src/pages/TSFilesPage/TSFilesPage.tsx' + '/path/to/project/web/src/pages/TSFilesPage/TSFilesPage.tsx', ) - ] + ], ).toMatchSnapshot() expect( typescriptFiles[ path.normalize( - '/path/to/project/web/src/pages/TSFilesPage/TSFilesPage.stories.tsx' + '/path/to/project/web/src/pages/TSFilesPage/TSFilesPage.stories.tsx', ) - ] + ], ).toMatchSnapshot() expect( typescriptFiles[ path.normalize( - '/path/to/project/web/src/pages/TSFilesPage/TSFilesPage.test.tsx' + '/path/to/project/web/src/pages/TSFilesPage/TSFilesPage.test.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -487,9 +487,9 @@ describe('TS Files', async () => { expect( typescriptParamFiles[ path.normalize( - '/path/to/project/web/src/pages/TSParamFilesPage/TSParamFilesPage.tsx' + '/path/to/project/web/src/pages/TSParamFilesPage/TSParamFilesPage.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -500,16 +500,16 @@ describe('TS Files', async () => { tests: false, stories: false, ...page.paramVariants( - pathName('/bazinga-ts/{id:Int}', 'typescript-param-with-type') + pathName('/bazinga-ts/{id:Int}', 'typescript-param-with-type'), ), }) expect( typescriptParamTypeFiles[ path.normalize( - '/path/to/project/web/src/pages/TSParamTypeFilesPage/TSParamTypeFilesPage.tsx' + '/path/to/project/web/src/pages/TSParamTypeFilesPage/TSParamTypeFilesPage.tsx', ) - ] + ], ).toMatchSnapshot() }) }) diff --git a/packages/cli/src/commands/generate/page/page.js b/packages/cli/src/commands/generate/page/page.js index 15a9abfac52d..dcb2d93f843b 100644 --- a/packages/cli/src/commands/generate/page/page.js +++ b/packages/cli/src/commands/generate/page/page.js @@ -152,7 +152,7 @@ export const files = async ({ name, tests, stories, typescript, ...rest }) => { export const routes = ({ name, path }) => { return [ ``, ] } @@ -245,7 +245,7 @@ export const handler = async ({ title: 'Updating routes file...', task: async () => { addRoutesToRouterTask( - routes({ name: pageName, path: pathName(path, pageName) }) + routes({ name: pageName, path: pathName(path, pageName) }), ) }, }, @@ -276,7 +276,7 @@ export const handler = async ({ }, }, ].filter(Boolean), - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/generate/realtime/realtimeHandler.js b/packages/cli/src/commands/generate/realtime/realtimeHandler.js index 1ce7f8a7ae56..cb49daedfa30 100644 --- a/packages/cli/src/commands/generate/realtime/realtimeHandler.js +++ b/packages/cli/src/commands/generate/realtime/realtimeHandler.js @@ -90,12 +90,12 @@ export async function handler({ name, type, force, verbose }) { 'templates', 'subscriptions', 'blank', - `blank.sdl.ts.template` + `blank.sdl.ts.template`, ) const sdlFile = path.join( redwoodPaths.api.graphql, - `${name}.sdl.${isTypeScriptProject() ? 'ts' : 'js'}` + `${name}.sdl.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const sdlContent = ts @@ -109,12 +109,12 @@ export async function handler({ name, type, force, verbose }) { 'templates', 'subscriptions', 'blank', - `blank.service.ts.template` + `blank.service.ts.template`, ) const serviceFile = path.join( redwoodPaths.api.services, `${name}`, - `${name}.${isTypeScriptProject() ? 'ts' : 'js'}` + `${name}.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const serviceContent = ts @@ -128,13 +128,13 @@ export async function handler({ name, type, force, verbose }) { 'templates', 'subscriptions', 'blank', - `blank.ts.template` + `blank.ts.template`, ) const exampleFile = path.join( redwoodPaths.api.subscriptions, `${name}`, - `${name}.${isTypeScriptProject() ? 'ts' : 'js'}` + `${name}.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const setupScriptContent = ts @@ -148,21 +148,21 @@ export async function handler({ name, type, force, verbose }) { generateTemplate(sdlContent, templateVariables(name)), { overwriteExisting: force, - } + }, ), writeFile( serviceFile, generateTemplate(serviceContent, templateVariables(name)), { overwriteExisting: force, - } + }, ), writeFile( exampleFile, generateTemplate(setupScriptContent, templateVariables(name)), { overwriteExisting: force, - } + }, ), ] }, @@ -177,11 +177,11 @@ export async function handler({ name, type, force, verbose }) { 'templates', 'liveQueries', 'blank', - `blank.sdl.ts.template` + `blank.sdl.ts.template`, ) const sdlFile = path.join( redwoodPaths.api.graphql, - `${name}.sdl.${isTypeScriptProject() ? 'ts' : 'js'}` + `${name}.sdl.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const sdlContent = ts ? exampleSdlTemplateContent @@ -193,13 +193,13 @@ export async function handler({ name, type, force, verbose }) { 'templates', 'liveQueries', 'blank', - 'blank.service.ts.template' + 'blank.service.ts.template', ) const serviceFile = path.join( redwoodPaths.api.services, `${name}`, - `${name}.${isTypeScriptProject() ? 'ts' : 'js'}` + `${name}.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const serviceContent = ts ? exampleServiceTemplateContent @@ -212,14 +212,14 @@ export async function handler({ name, type, force, verbose }) { generateTemplate(sdlContent, templateVariables(name)), { overwriteExisting: force, - } + }, ), writeFile( serviceFile, generateTemplate(serviceContent, templateVariables(name)), { overwriteExisting: force, - } + }, ), ] }, @@ -229,7 +229,7 @@ export async function handler({ name, type, force, verbose }) { task: async () => { await generateTypes() console.log( - 'Note: You may need to manually restart GraphQL in VSCode to see the new types take effect.\n\n' + 'Note: You may need to manually restart GraphQL in VSCode to see the new types take effect.\n\n', ) }, }, @@ -237,7 +237,7 @@ export async function handler({ name, type, force, verbose }) { { rendererOptions: { collapseSubtasks: false, persistentOutput: true }, renderer: verbose ? 'verbose' : 'default', - } + }, ) try { diff --git a/packages/cli/src/commands/generate/scaffold/__tests__/editableColumns.test.js b/packages/cli/src/commands/generate/scaffold/__tests__/editableColumns.test.js index 261662106a89..830bb42ee1e3 100644 --- a/packages/cli/src/commands/generate/scaffold/__tests__/editableColumns.test.js +++ b/packages/cli/src/commands/generate/scaffold/__tests__/editableColumns.test.js @@ -30,7 +30,7 @@ describe('editable columns', () => { form = files[ path.normalize( - '/path/to/project/web/src/components/ExcludeDefault/ExcludeDefaultForm/ExcludeDefaultForm.jsx' + '/path/to/project/web/src/components/ExcludeDefault/ExcludeDefaultForm/ExcludeDefaultForm.jsx', ) ] }) diff --git a/packages/cli/src/commands/generate/scaffold/__tests__/scaffold.test.js b/packages/cli/src/commands/generate/scaffold/__tests__/scaffold.test.js index c40c5dcc5634..2d636dc9e010 100644 --- a/packages/cli/src/commands/generate/scaffold/__tests__/scaffold.test.js +++ b/packages/cli/src/commands/generate/scaffold/__tests__/scaffold.test.js @@ -59,7 +59,7 @@ describe('in javascript (default) mode', () => { test('creates a stylesheet', () => { expect( - files[path.normalize('/path/to/project/web/src/scaffold.css')] + files[path.normalize('/path/to/project/web/src/scaffold.css')], ).toMatchSnapshot() }) @@ -69,9 +69,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -81,9 +81,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/pages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Post/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -91,9 +91,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/pages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Post/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch(`import EditPostCell from 'src/components/Post/EditPostCell'`) }) @@ -101,9 +101,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/pages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Post/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -111,9 +111,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/pages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Post/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch(`import PostsCell from 'src/components/Post/PostsCell'`) }) @@ -121,9 +121,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/pages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Post/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -131,9 +131,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/pages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Post/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/Post/NewPost'`) }) @@ -141,9 +141,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/pages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Post/PostPage/PostPage.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -151,9 +151,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/pages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Post/PostPage/PostPage.jsx', ) - ] + ], ).toMatch(`import PostCell from 'src/components/Post/PostCell'`) }) @@ -163,9 +163,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/PostEditCell/PostEditCell.jsx' + '/path/to/project/web/src/components/Post/PostEditCell/PostEditCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -173,9 +173,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Post/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Post/PostForm'`) }) @@ -183,9 +183,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Post/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -193,9 +193,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Post/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/Post/Posts'`) }) @@ -203,9 +203,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Post/PostCell/PostCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -213,9 +213,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Post/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/Post/Post'`) }) @@ -225,9 +225,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/Post/PostForm/PostForm.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -235,9 +235,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/Posts/Posts.jsx' + '/path/to/project/web/src/components/Post/Posts/Posts.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -245,9 +245,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/Posts/Posts.jsx' + '/path/to/project/web/src/components/Post/Posts/Posts.jsx', ) - ] + ], ).toMatch(`import { QUERY } from 'src/components/Post/PostsCell'`) }) @@ -255,9 +255,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Post/NewPost/NewPost.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -265,9 +265,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Post/NewPost/NewPost.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Post/PostForm'`) }) @@ -275,7 +275,7 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize('/path/to/project/web/src/components/Post/Post/Post.jsx') - ] + ], ).toMatchSnapshot() }) @@ -286,9 +286,9 @@ describe('in javascript (default) mode', () => { model: 'NoEditableField', tests: true, nestScaffoldByModel: true, - }) + }), ).rejects.toThrow( - 'There are no editable fields in the NoEditableField model' + 'There are no editable fields in the NoEditableField model', ) }) @@ -296,7 +296,7 @@ describe('in javascript (default) mode', () => { test('creates a single-word name routes', async () => { expect( - await scaffold.routes({ model: 'Post', nestScaffoldByModel: true }) + await scaffold.routes({ model: 'Post', nestScaffoldByModel: true }), ).toEqual([ '', '', @@ -307,7 +307,10 @@ describe('in javascript (default) mode', () => { test('creates a multi-word name routes', async () => { expect( - await scaffold.routes({ model: 'UserProfile', nestScaffoldByModel: true }) + await scaffold.routes({ + model: 'UserProfile', + nestScaffoldByModel: true, + }), ).toEqual([ '', '', @@ -327,7 +330,7 @@ describe('in javascript (default) mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/UserProfile/UserProfilesCell/UserProfilesCell.jsx', ) ] const query = cell.match(/(userProfiles.*?\})/s)[1] @@ -344,7 +347,7 @@ describe('in javascript (default) mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/UserProfile/UserProfileCell/UserProfileCell.jsx', ) ] const query = cell.match(/(userProfile.*?\})/s)[1] @@ -361,7 +364,7 @@ describe('in javascript (default) mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ) ] const query = cell.match(/(userProfile.*?\})/s)[1] @@ -381,9 +384,9 @@ describe('in javascript (default) mode', () => { expect( foreignKeyFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/UserProfile/NewUserProfile/NewUserProfile.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -397,9 +400,9 @@ describe('in javascript (default) mode', () => { expect( foreignKeyFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -407,13 +410,13 @@ describe('in javascript (default) mode', () => { test('creates a formatters function file', () => { expect( - files[path.normalize('/path/to/project/web/src/lib/formatters.jsx')] + files[path.normalize('/path/to/project/web/src/lib/formatters.jsx')], ).toMatchSnapshot() }) test('creates a formatters function test file', () => { expect( - files[path.normalize('/path/to/project/web/src/lib/formatters.test.jsx')] + files[path.normalize('/path/to/project/web/src/lib/formatters.test.jsx')], ).toMatchSnapshot() }) }) @@ -461,7 +464,7 @@ describe('in typescript mode', () => { test('creates a stylesheet', () => { expect( - tsFiles[path.normalize('/path/to/project/web/src/scaffold.css')] + tsFiles[path.normalize('/path/to/project/web/src/scaffold.css')], ).toMatchSnapshot() }) @@ -471,9 +474,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.tsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -483,9 +486,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/pages/Post/EditPostPage/EditPostPage.tsx' + '/path/to/project/web/src/pages/Post/EditPostPage/EditPostPage.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -493,9 +496,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/pages/Post/PostsPage/PostsPage.tsx' + '/path/to/project/web/src/pages/Post/PostsPage/PostsPage.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -503,9 +506,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/pages/Post/NewPostPage/NewPostPage.tsx' + '/path/to/project/web/src/pages/Post/NewPostPage/NewPostPage.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -513,9 +516,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/pages/Post/PostPage/PostPage.tsx' + '/path/to/project/web/src/pages/Post/PostPage/PostPage.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -525,9 +528,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/components/Post/EditPostCell/EditPostCell.tsx' + '/path/to/project/web/src/components/Post/EditPostCell/EditPostCell.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -535,9 +538,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/components/Post/PostsCell/PostsCell.tsx' + '/path/to/project/web/src/components/Post/PostsCell/PostsCell.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -545,9 +548,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/components/Post/PostCell/PostCell.tsx' + '/path/to/project/web/src/components/Post/PostCell/PostCell.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -557,9 +560,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/components/Post/PostForm/PostForm.tsx' + '/path/to/project/web/src/components/Post/PostForm/PostForm.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -567,9 +570,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/components/Post/Posts/Posts.tsx' + '/path/to/project/web/src/components/Post/Posts/Posts.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -577,9 +580,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/components/Post/NewPost/NewPost.tsx' + '/path/to/project/web/src/components/Post/NewPost/NewPost.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -587,7 +590,7 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize('/path/to/project/web/src/components/Post/Post/Post.tsx') - ] + ], ).toMatchSnapshot() }) @@ -595,7 +598,7 @@ describe('in typescript mode', () => { test('creates a single-word name routes', async () => { expect( - await scaffold.routes({ model: 'Post', nestScaffoldByModel: true }) + await scaffold.routes({ model: 'Post', nestScaffoldByModel: true }), ).toEqual([ '', '', @@ -606,7 +609,10 @@ describe('in typescript mode', () => { test('creates a multi-word name routes', async () => { expect( - await scaffold.routes({ model: 'UserProfile', nestScaffoldByModel: true }) + await scaffold.routes({ + model: 'UserProfile', + nestScaffoldByModel: true, + }), ).toEqual([ '', '', @@ -626,7 +632,7 @@ describe('in typescript mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/UserProfile/UserProfilesCell/UserProfilesCell.jsx', ) ] const query = cell.match(/(userProfiles.*?\})/s)[1] @@ -643,7 +649,7 @@ describe('in typescript mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/UserProfile/UserProfileCell/UserProfileCell.jsx', ) ] const query = cell.match(/(userProfile.*?\})/s)[1] @@ -661,7 +667,7 @@ describe('in typescript mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/EditUserProfileCell/EditUserProfileCell.tsx' + '/path/to/project/web/src/components/UserProfile/EditUserProfileCell/EditUserProfileCell.tsx', ) ] const query = cell.match(/(userProfile.*?\})/s)[1] @@ -682,9 +688,9 @@ describe('in typescript mode', () => { expect( foreignKeyFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/NewUserProfile/NewUserProfile.tsx' + '/path/to/project/web/src/components/UserProfile/NewUserProfile/NewUserProfile.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -699,9 +705,9 @@ describe('in typescript mode', () => { expect( foreignKeyFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfile/EditUserProfileCell/EditUserProfileCell.tsx' + '/path/to/project/web/src/components/UserProfile/EditUserProfileCell/EditUserProfileCell.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -709,7 +715,7 @@ describe('in typescript mode', () => { test('creates a formatters function file', () => { expect( - tsFiles[path.normalize('/path/to/project/web/src/lib/formatters.tsx')] + tsFiles[path.normalize('/path/to/project/web/src/lib/formatters.tsx')], ).toMatchSnapshot() }) @@ -717,7 +723,7 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize('/path/to/project/web/src/lib/formatters.test.tsx') - ] + ], ).toMatchSnapshot() }) }) @@ -732,7 +738,7 @@ describe('tailwind flag', () => { }) expect( - files[path.normalize('/path/to/project/web/src/scaffold.css')] + files[path.normalize('/path/to/project/web/src/scaffold.css')], ).toMatchSnapshot() }) @@ -745,7 +751,7 @@ describe('tailwind flag', () => { }) expect( - files[path.normalize('/path/to/project/web/src/scaffold.css')] + files[path.normalize('/path/to/project/web/src/scaffold.css')], ).toMatchSnapshot() }) }) @@ -756,7 +762,7 @@ describe("'use client' directive", () => { beforeAll(async () => { vol.fromJSON( { 'redwood.toml': '[experimental.rsc]\n enabled = true' }, - '/' + '/', ) files = await scaffold.files({ @@ -770,9 +776,9 @@ describe("'use client' directive", () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Post/NewPost/NewPost.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -780,9 +786,9 @@ describe("'use client' directive", () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Post/PostCell/PostCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -790,9 +796,9 @@ describe("'use client' directive", () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Post/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -800,9 +806,9 @@ describe("'use client' directive", () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Post/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatchSnapshot() }) }) diff --git a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldNoNest.test.js b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldNoNest.test.js index 4e84cef4e8fa..abbfb05f6fba 100644 --- a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldNoNest.test.js +++ b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldNoNest.test.js @@ -56,7 +56,7 @@ describe('in javascript (default) mode', () => { test('creates a stylesheet', () => { expect( - files[path.normalize('/path/to/project/web/src/scaffold.css')] + files[path.normalize('/path/to/project/web/src/scaffold.css')], ).toMatchSnapshot() }) @@ -66,9 +66,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -78,9 +78,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/pages/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -88,7 +88,7 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize('/path/to/project/web/src/pages/PostsPage/PostsPage.jsx') - ] + ], ).toMatchSnapshot() }) @@ -96,9 +96,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/pages/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -106,7 +106,7 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize('/path/to/project/web/src/pages/PostPage/PostPage.jsx') - ] + ], ).toMatchSnapshot() }) @@ -116,9 +116,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/PostEditCell/PostEditCell.jsx' + '/path/to/project/web/src/components/PostEditCell/PostEditCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -126,9 +126,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -136,9 +136,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/PostCell/PostCell.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -148,9 +148,9 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/PostForm/PostForm.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -158,7 +158,7 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize('/path/to/project/web/src/components/Posts/Posts.jsx') - ] + ], ).toMatchSnapshot() }) @@ -166,15 +166,17 @@ describe('in javascript (default) mode', () => { expect( files[ path.normalize( - '/path/to/project/web/src/components/PostNew/PostNew.jsx' + '/path/to/project/web/src/components/PostNew/PostNew.jsx', ) - ] + ], ).toMatchSnapshot() }) test('creates a show component', async () => { expect( - files[path.normalize('/path/to/project/web/src/components/Post/Post.jsx')] + files[ + path.normalize('/path/to/project/web/src/components/Post/Post.jsx') + ], ).toMatchSnapshot() }) @@ -182,7 +184,7 @@ describe('in javascript (default) mode', () => { test('creates a single-word name routes', async () => { expect( - await scaffold.routes({ model: 'Post', nestScaffoldByModel: false }) + await scaffold.routes({ model: 'Post', nestScaffoldByModel: false }), ).toEqual([ '', '', @@ -196,7 +198,7 @@ describe('in javascript (default) mode', () => { await scaffold.routes({ model: 'UserProfile', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -216,7 +218,7 @@ describe('in javascript (default) mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/UserProfilesCell/UserProfilesCell.jsx', ) ] const query = cell.match(/(userProfiles.*?\})/s)[1] @@ -233,7 +235,7 @@ describe('in javascript (default) mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx', ) ] const query = cell.match(/(userProfile.*?\})/s)[1] @@ -250,7 +252,7 @@ describe('in javascript (default) mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/EditUserProfileCell/EditUserProfileCell.jsx', ) ] const query = cell.match(/(userProfile.*?\})/s)[1] @@ -270,9 +272,9 @@ describe('in javascript (default) mode', () => { expect( foreignKeyFiles[ path.normalize( - '/path/to/project/web/src/components/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/NewUserProfile/NewUserProfile.jsx', ) - ] + ], ).toMatchSnapshot() }) @@ -286,9 +288,9 @@ describe('in javascript (default) mode', () => { expect( foreignKeyFiles[ path.normalize( - '/path/to/project/web/src/components/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/EditUserProfileCell/EditUserProfileCell.jsx', ) - ] + ], ).toMatchSnapshot() }) }) @@ -336,7 +338,7 @@ describe('in typescript mode', () => { test('creates a stylesheet', () => { expect( - tsFiles[path.normalize('/path/to/project/web/src/scaffold.css')] + tsFiles[path.normalize('/path/to/project/web/src/scaffold.css')], ).toMatchSnapshot() }) @@ -346,9 +348,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.tsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -358,9 +360,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/pages/EditPostPage/EditPostPage.tsx' + '/path/to/project/web/src/pages/EditPostPage/EditPostPage.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -368,7 +370,7 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize('/path/to/project/web/src/pages/PostsPage/PostsPage.tsx') - ] + ], ).toMatchSnapshot() }) @@ -376,9 +378,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/pages/NewPostPage/NewPostPage.tsx' + '/path/to/project/web/src/pages/NewPostPage/NewPostPage.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -386,7 +388,7 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize('/path/to/project/web/src/pages/PostPage/PostPage.tsx') - ] + ], ).toMatchSnapshot() }) @@ -396,9 +398,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/components/EditPostCell/EditPostCell.tsx' + '/path/to/project/web/src/components/EditPostCell/EditPostCell.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -406,9 +408,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/components/PostsCell/PostsCell.tsx' + '/path/to/project/web/src/components/PostsCell/PostsCell.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -416,9 +418,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/components/PostCell/PostCell.tsx' + '/path/to/project/web/src/components/PostCell/PostCell.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -428,9 +430,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/components/PostForm/PostForm.tsx' + '/path/to/project/web/src/components/PostForm/PostForm.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -438,7 +440,7 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize('/path/to/project/web/src/components/Posts/Posts.tsx') - ] + ], ).toMatchSnapshot() }) @@ -446,9 +448,9 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize( - '/path/to/project/web/src/components/PostNew/PostNew.tsx' + '/path/to/project/web/src/components/PostNew/PostNew.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -456,7 +458,7 @@ describe('in typescript mode', () => { expect( tsFiles[ path.normalize('/path/to/project/web/src/components/Post/Post.tsx') - ] + ], ).toMatchSnapshot() }) @@ -464,7 +466,7 @@ describe('in typescript mode', () => { test('creates a single-word name routes', async () => { expect( - await scaffold.routes({ model: 'Post', nestScaffoldByModel: false }) + await scaffold.routes({ model: 'Post', nestScaffoldByModel: false }), ).toEqual([ '', '', @@ -478,7 +480,7 @@ describe('in typescript mode', () => { await scaffold.routes({ model: 'UserProfile', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -498,7 +500,7 @@ describe('in typescript mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/UserProfilesCell/UserProfilesCell.jsx', ) ] const query = cell.match(/(userProfiles.*?\})/s)[1] @@ -515,7 +517,7 @@ describe('in typescript mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/UserProfileCell/UserProfileCell.jsx', ) ] const query = cell.match(/(userProfile.*?\})/s)[1] @@ -533,7 +535,7 @@ describe('in typescript mode', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/EditUserProfileCell/EditUserProfileCell.tsx' + '/path/to/project/web/src/components/EditUserProfileCell/EditUserProfileCell.tsx', ) ] const query = cell.match(/(userProfile.*?\})/s)[1] @@ -554,9 +556,9 @@ describe('in typescript mode', () => { expect( foreignKeyFiles[ path.normalize( - '/path/to/project/web/src/components/NewUserProfile/NewUserProfile.tsx' + '/path/to/project/web/src/components/NewUserProfile/NewUserProfile.tsx', ) - ] + ], ).toMatchSnapshot() }) @@ -571,9 +573,9 @@ describe('in typescript mode', () => { expect( foreignKeyFiles[ path.normalize( - '/path/to/project/web/src/components/EditUserProfileCell/EditUserProfileCell.tsx' + '/path/to/project/web/src/components/EditUserProfileCell/EditUserProfileCell.tsx', ) - ] + ], ).toMatchSnapshot() }) }) diff --git a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPath.test.js b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPath.test.js index 828600a73fe9..be52063bcaaf 100644 --- a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPath.test.js +++ b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPath.test.js @@ -36,7 +36,7 @@ describe('admin/post', () => { it('creates a layout', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -46,7 +46,7 @@ describe('admin/post', () => { it('creates a edit page', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -55,18 +55,18 @@ describe('admin/post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/Admin/Post/EditPostCell'` + `import EditPostCell from 'src/components/Admin/Post/EditPostCell'`, ) }) it('creates a index page', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/PostsPage/PostsPage.jsx', ), ]) }) @@ -75,16 +75,16 @@ describe('admin/post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch(`import PostsCell from 'src/components/Admin/Post/PostsCell'`) }) it('creates a new page', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -93,16 +93,16 @@ describe('admin/post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/Admin/Post/NewPost'`) }) it('creates a show page', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/PostPage/PostPage.jsx', ), ]) }) @@ -111,9 +111,9 @@ describe('admin/post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/PostPage/PostPage.jsx', ) - ] + ], ).toMatch(`import PostCell from 'src/components/Admin/Post/PostCell'`) }) @@ -122,7 +122,7 @@ describe('admin/post', () => { it('creates an edit cell', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Post/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -131,16 +131,16 @@ describe('admin/post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Post/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/Post/PostForm'`) }) it('creates an index cell', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Post/PostsCell/PostsCell.jsx', ), ]) }) @@ -149,16 +149,16 @@ describe('admin/post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Post/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/Admin/Post/Posts'`) }) it('creates a show cell', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Post/PostCell/PostCell.jsx', ), ]) }) @@ -167,9 +167,9 @@ describe('admin/post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Post/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/Admin/Post/Post'`) }) @@ -178,7 +178,7 @@ describe('admin/post', () => { it('creates a form component', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/Admin/Post/PostForm/PostForm.jsx', ), ]) }) @@ -186,7 +186,7 @@ describe('admin/post', () => { it('creates an index component', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/Posts/Posts.jsx' + '/path/to/project/web/src/components/Admin/Post/Posts/Posts.jsx', ), ]) }) @@ -194,7 +194,7 @@ describe('admin/post', () => { it('creates a new component', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Post/NewPost/NewPost.jsx', ), ]) }) @@ -203,16 +203,16 @@ describe('admin/post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Post/NewPost/NewPost.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/Post/PostForm'`) }) it('creates a show component', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/Post/Post.jsx' + '/path/to/project/web/src/components/Admin/Post/Post/Post.jsx', ), ]) }) @@ -227,7 +227,7 @@ describe('admin/post', () => { model: 'Post', path: 'admin', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -242,7 +242,7 @@ describe('admin/post', () => { model: 'UserProfile', path: 'admin', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -264,7 +264,7 @@ describe('admin/post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfile/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfile/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -284,7 +284,7 @@ describe('admin/post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfile/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfile/UserProfileCell/UserProfileCell.jsx', ) ] @@ -304,7 +304,7 @@ describe('admin/post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -325,7 +325,7 @@ describe('admin/post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfile/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/Admin/UserProfile/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -340,7 +340,7 @@ describe('admin/post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) @@ -368,7 +368,7 @@ describe('Admin/Post', () => { it('creates a layout', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -378,7 +378,7 @@ describe('Admin/Post', () => { it('creates a edit page', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -387,18 +387,18 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/Admin/Post/EditPostCell'` + `import EditPostCell from 'src/components/Admin/Post/EditPostCell'`, ) }) it('creates a index page', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/PostsPage/PostsPage.jsx', ), ]) }) @@ -407,16 +407,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch(`import PostsCell from 'src/components/Admin/Post/PostsCell'`) }) it('creates a new page', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -425,16 +425,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/Admin/Post/NewPost'`) }) it('creates a show page', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/PostPage/PostPage.jsx', ), ]) }) @@ -443,9 +443,9 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Post/PostPage/PostPage.jsx', ) - ] + ], ).toMatch(`import PostCell from 'src/components/Admin/Post/PostCell'`) }) @@ -454,7 +454,7 @@ describe('Admin/Post', () => { it('creates an edit cell', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Post/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -463,16 +463,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Post/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/Post/PostForm'`) }) it('creates an index cell', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Post/PostsCell/PostsCell.jsx', ), ]) }) @@ -481,16 +481,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Post/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/Admin/Post/Posts'`) }) it('creates a show cell', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Post/PostCell/PostCell.jsx', ), ]) }) @@ -499,9 +499,9 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Post/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/Admin/Post/Post'`) }) @@ -510,7 +510,7 @@ describe('Admin/Post', () => { it('creates a form component', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/Admin/Post/PostForm/PostForm.jsx', ), ]) }) @@ -518,7 +518,7 @@ describe('Admin/Post', () => { it('creates an index component', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/Posts/Posts.jsx' + '/path/to/project/web/src/components/Admin/Post/Posts/Posts.jsx', ), ]) }) @@ -527,9 +527,9 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Post/Posts/Posts.jsx' + '/path/to/project/web/src/components/Admin/Post/Posts/Posts.jsx', ) - ] + ], ).toMatch(`import { QUERY } from 'src/components/Admin/Post/PostsCell'`) }) @@ -537,16 +537,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Post/NewPost/NewPost.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/Post/PostForm'`) }) it('creates a new component', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Post/NewPost/NewPost.jsx', ), ]) }) @@ -555,16 +555,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Post/NewPost/NewPost.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/Post/PostForm'`) }) it('creates a show component', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/Post/Post.jsx' + '/path/to/project/web/src/components/Admin/Post/Post/Post.jsx', ), ]) }) @@ -579,7 +579,7 @@ describe('Admin/Post', () => { model: 'Post', path: 'Admin', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -594,7 +594,7 @@ describe('Admin/Post', () => { model: 'UserProfile', path: 'Admin', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -616,7 +616,7 @@ describe('Admin/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfile/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfile/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -636,7 +636,7 @@ describe('Admin/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfile/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfile/UserProfileCell/UserProfileCell.jsx', ) ] @@ -656,7 +656,7 @@ describe('Admin/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -677,7 +677,7 @@ describe('Admin/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfile/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/Admin/UserProfile/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -692,7 +692,7 @@ describe('Admin/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) diff --git a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMulti.test.js b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMulti.test.js index c278cac77b8e..2f65d0a0a645 100644 --- a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMulti.test.js +++ b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMulti.test.js @@ -37,7 +37,7 @@ describe('admin/pages/post', () => { test('creates a layout', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -47,7 +47,7 @@ describe('admin/pages/post', () => { test('creates a edit page', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -56,18 +56,18 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/Admin/Pages/Post/EditPostCell'` + `import EditPostCell from 'src/components/Admin/Pages/Post/EditPostCell'`, ) }) test('creates a index page', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/PostsPage/PostsPage.jsx', ), ]) }) @@ -76,18 +76,18 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch( - `import PostsCell from 'src/components/Admin/Pages/Post/PostsCell'` + `import PostsCell from 'src/components/Admin/Pages/Post/PostsCell'`, ) }) test('creates a new page', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -96,16 +96,16 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/Admin/Pages/Post/NewPost'`) }) test('creates a show page', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/PostPage/PostPage.jsx', ), ]) }) @@ -114,11 +114,11 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/PostPage/PostPage.jsx', ) - ] + ], ).toMatch( - `import PostCell from 'src/components/Admin/Pages/Post/PostCell'` + `import PostCell from 'src/components/Admin/Pages/Post/PostCell'`, ) }) @@ -127,7 +127,7 @@ describe('admin/pages/post', () => { test('creates an edit cell', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -136,18 +136,18 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch( - `import PostForm from 'src/components/Admin/Pages/Post/PostForm'` + `import PostForm from 'src/components/Admin/Pages/Post/PostForm'`, ) }) test('creates an index cell', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/PostsCell/PostsCell.jsx', ), ]) }) @@ -156,16 +156,16 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/Admin/Pages/Post/Posts'`) }) test('creates a show cell', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/PostCell/PostCell.jsx', ), ]) }) @@ -174,9 +174,9 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/Admin/Pages/Post/Post'`) }) @@ -185,7 +185,7 @@ describe('admin/pages/post', () => { test('creates a form component', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/PostForm/PostForm.jsx', ), ]) }) @@ -193,7 +193,7 @@ describe('admin/pages/post', () => { test('creates an index component', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/Posts/Posts.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/Posts/Posts.jsx', ), ]) }) @@ -201,7 +201,7 @@ describe('admin/pages/post', () => { test('creates a new component', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/NewPost/NewPost.jsx', ), ]) }) @@ -210,18 +210,18 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/NewPost/NewPost.jsx', ) - ] + ], ).toMatch( - `import PostForm from 'src/components/Admin/Pages/Post/PostForm'` + `import PostForm from 'src/components/Admin/Pages/Post/PostForm'`, ) }) test('creates a show component', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/Post/Post.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/Post/Post.jsx', ), ]) }) @@ -236,7 +236,7 @@ describe('admin/pages/post', () => { model: 'Post', path: 'admin/pages', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -251,7 +251,7 @@ describe('admin/pages/post', () => { model: 'UserProfile', path: 'admin/pages', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -273,7 +273,7 @@ describe('admin/pages/post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfile/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfile/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -293,7 +293,7 @@ describe('admin/pages/post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfile/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfile/UserProfileCell/UserProfileCell.jsx', ) ] @@ -313,7 +313,7 @@ describe('admin/pages/post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -334,7 +334,7 @@ describe('admin/pages/post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfile/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfile/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -349,7 +349,7 @@ describe('admin/pages/post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) @@ -378,7 +378,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates a layout', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -388,7 +388,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates a edit page', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -397,18 +397,18 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/Admin/Pages/Post/EditPostCell'` + `import EditPostCell from 'src/components/Admin/Pages/Post/EditPostCell'`, ) }) test('creates a index page', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/PostsPage/PostsPage.jsx', ), ]) }) @@ -417,18 +417,18 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch( - `import PostsCell from 'src/components/Admin/Pages/Post/PostsCell'` + `import PostsCell from 'src/components/Admin/Pages/Post/PostsCell'`, ) }) test('creates a new page', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -437,16 +437,16 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/Admin/Pages/Post/NewPost'`) }) test('creates a show page', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/PostPage/PostPage.jsx', ), ]) }) @@ -455,11 +455,11 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/Post/PostPage/PostPage.jsx', ) - ] + ], ).toMatch( - `import PostCell from 'src/components/Admin/Pages/Post/PostCell'` + `import PostCell from 'src/components/Admin/Pages/Post/PostCell'`, ) }) @@ -468,7 +468,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates an edit cell', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -477,18 +477,18 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch( - `import PostForm from 'src/components/Admin/Pages/Post/PostForm'` + `import PostForm from 'src/components/Admin/Pages/Post/PostForm'`, ) }) test('creates an index cell', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/PostsCell/PostsCell.jsx', ), ]) }) @@ -497,16 +497,16 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/Admin/Pages/Post/Posts'`) }) test('creates a show cell', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/PostCell/PostCell.jsx', ), ]) }) @@ -515,9 +515,9 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/Admin/Pages/Post/Post'`) }) @@ -526,7 +526,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates a form component', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/PostForm/PostForm.jsx', ), ]) }) @@ -534,7 +534,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates an index component', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/Posts/Posts.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/Posts/Posts.jsx', ), ]) }) @@ -542,7 +542,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates a new component', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/NewPost/NewPost.jsx', ), ]) }) @@ -551,18 +551,18 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/NewPost/NewPost.jsx', ) - ] + ], ).toMatch( - `import PostForm from 'src/components/Admin/Pages/Post/PostForm'` + `import PostForm from 'src/components/Admin/Pages/Post/PostForm'`, ) }) test('creates a show component', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/Post/Post.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/Post/Post.jsx', ), ]) }) @@ -577,7 +577,7 @@ describe('Admin/Pages/Post/Post', () => { model: 'Post', path: 'Admin/Pages', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -592,7 +592,7 @@ describe('Admin/Pages/Post/Post', () => { model: 'UserProfile', path: 'Admin/Pages', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -614,7 +614,7 @@ describe('Admin/Pages/Post/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfile/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfile/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -634,7 +634,7 @@ describe('Admin/Pages/Post/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfile/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfile/UserProfileCell/UserProfileCell.jsx', ) ] @@ -654,7 +654,7 @@ describe('Admin/Pages/Post/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -675,7 +675,7 @@ describe('Admin/Pages/Post/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfile/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfile/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -690,7 +690,7 @@ describe('Admin/Pages/Post/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) diff --git a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiNoNest.test.js b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiNoNest.test.js index 49cde654245c..538995b4aaa2 100644 --- a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiNoNest.test.js +++ b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiNoNest.test.js @@ -37,7 +37,7 @@ describe('admin/pages/post', () => { test('creates a layout', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -47,7 +47,7 @@ describe('admin/pages/post', () => { test('creates a edit page', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -56,18 +56,18 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/Admin/Pages/EditPostCell'` + `import EditPostCell from 'src/components/Admin/Pages/EditPostCell'`, ) }) test('creates a index page', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/PostsPage/PostsPage.jsx', ), ]) }) @@ -76,16 +76,16 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch(`import PostsCell from 'src/components/Admin/Pages/PostsCell'`) }) test('creates a new page', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -94,16 +94,16 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/Admin/Pages/NewPost'`) }) test('creates a show page', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/PostPage/PostPage.jsx', ), ]) }) @@ -112,9 +112,9 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/PostPage/PostPage.jsx', ) - ] + ], ).toMatch(`import PostCell from 'src/components/Admin/Pages/PostCell'`) }) @@ -123,7 +123,7 @@ describe('admin/pages/post', () => { test('creates an edit cell', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -132,16 +132,16 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/Pages/PostForm'`) }) test('creates an index cell', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/PostsCell/PostsCell.jsx', ), ]) }) @@ -150,16 +150,16 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/Admin/Pages/Posts'`) }) test('creates a show cell', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/PostCell/PostCell.jsx', ), ]) }) @@ -168,9 +168,9 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/Admin/Pages/Post'`) }) @@ -179,7 +179,7 @@ describe('admin/pages/post', () => { test('creates a form component', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/Admin/Pages/PostForm/PostForm.jsx', ), ]) }) @@ -187,7 +187,7 @@ describe('admin/pages/post', () => { test('creates an index component', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Posts/Posts.jsx' + '/path/to/project/web/src/components/Admin/Pages/Posts/Posts.jsx', ), ]) }) @@ -195,7 +195,7 @@ describe('admin/pages/post', () => { test('creates a new component', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Pages/NewPost/NewPost.jsx', ), ]) }) @@ -204,16 +204,16 @@ describe('admin/pages/post', () => { expect( filesNestedLower[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Pages/NewPost/NewPost.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/Pages/PostForm'`) }) test('creates a show component', async () => { expect(filesNestedLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/Post.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/Post.jsx', ), ]) }) @@ -228,7 +228,7 @@ describe('admin/pages/post', () => { model: 'Post', path: 'admin/pages', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -243,7 +243,7 @@ describe('admin/pages/post', () => { model: 'UserProfile', path: 'admin/pages', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -265,7 +265,7 @@ describe('admin/pages/post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -285,7 +285,7 @@ describe('admin/pages/post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfileCell/UserProfileCell.jsx', ) ] @@ -305,7 +305,7 @@ describe('admin/pages/post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -326,7 +326,7 @@ describe('admin/pages/post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/Admin/Pages/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -341,7 +341,7 @@ describe('admin/pages/post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) @@ -369,7 +369,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates a layout', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -379,7 +379,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates a edit page', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -388,18 +388,18 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/Admin/Pages/EditPostCell'` + `import EditPostCell from 'src/components/Admin/Pages/EditPostCell'`, ) }) test('creates a index page', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/PostsPage/PostsPage.jsx', ), ]) }) @@ -408,16 +408,16 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch(`import PostsCell from 'src/components/Admin/Pages/PostsCell'`) }) test('creates a new page', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -426,16 +426,16 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/Admin/Pages/NewPost'`) }) test('creates a show page', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/PostPage/PostPage.jsx', ), ]) }) @@ -444,9 +444,9 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/Pages/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/Pages/PostPage/PostPage.jsx', ) - ] + ], ).toMatch(`import PostCell from 'src/components/Admin/Pages/PostCell'`) }) @@ -455,7 +455,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates an edit cell', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -464,16 +464,16 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/Pages/PostForm'`) }) test('creates an index cell', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/PostsCell/PostsCell.jsx', ), ]) }) @@ -482,16 +482,16 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/Admin/Pages/Posts'`) }) test('creates a show cell', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/PostCell/PostCell.jsx', ), ]) }) @@ -500,9 +500,9 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/Admin/Pages/Post'`) }) @@ -511,7 +511,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates a form component', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/Admin/Pages/PostForm/PostForm.jsx', ), ]) }) @@ -519,7 +519,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates an index component', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Posts/Posts.jsx' + '/path/to/project/web/src/components/Admin/Pages/Posts/Posts.jsx', ), ]) }) @@ -527,7 +527,7 @@ describe('Admin/Pages/Post/Post', () => { test('creates a new component', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Pages/NewPost/NewPost.jsx', ), ]) }) @@ -536,16 +536,16 @@ describe('Admin/Pages/Post/Post', () => { expect( filesNestedUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/Pages/NewPost/NewPost.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/Pages/PostForm'`) }) test('creates a show component', async () => { expect(filesNestedUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/Post/Post.jsx' + '/path/to/project/web/src/components/Admin/Pages/Post/Post.jsx', ), ]) }) @@ -560,7 +560,7 @@ describe('Admin/Pages/Post/Post', () => { model: 'Post', path: 'Admin/Pages', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -575,7 +575,7 @@ describe('Admin/Pages/Post/Post', () => { model: 'UserProfile', path: 'Admin/Pages', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -597,7 +597,7 @@ describe('Admin/Pages/Post/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -617,7 +617,7 @@ describe('Admin/Pages/Post/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/UserProfileCell/UserProfileCell.jsx', ) ] @@ -637,7 +637,7 @@ describe('Admin/Pages/Post/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -658,7 +658,7 @@ describe('Admin/Pages/Post/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/Admin/Pages/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -673,7 +673,7 @@ describe('Admin/Pages/Post/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Pages/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/Pages/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) diff --git a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiword.test.js b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiword.test.js index aad59d3ec567..0d79faa24e19 100644 --- a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiword.test.js +++ b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiword.test.js @@ -37,7 +37,7 @@ describe('AdminPages/Post', () => { test('creates a layout', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -47,7 +47,7 @@ describe('AdminPages/Post', () => { test('creates a edit page', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -56,18 +56,18 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/AdminPages/Post/EditPostCell'` + `import EditPostCell from 'src/components/AdminPages/Post/EditPostCell'`, ) }) test('creates a index page', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx', ), ]) }) @@ -76,18 +76,18 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch( - `import PostsCell from 'src/components/AdminPages/Post/PostsCell'` + `import PostsCell from 'src/components/AdminPages/Post/PostsCell'`, ) }) test('creates a new page', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -96,16 +96,16 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/AdminPages/Post/NewPost'`) }) test('creates a show page', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx', ), ]) }) @@ -114,11 +114,11 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx', ) - ] + ], ).toMatch( - `import PostCell from 'src/components/AdminPages/Post/PostCell'` + `import PostCell from 'src/components/AdminPages/Post/PostCell'`, ) }) @@ -127,7 +127,7 @@ describe('AdminPages/Post', () => { test('creates an edit cell', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -136,18 +136,18 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch( - `import PostForm from 'src/components/AdminPages/Post/PostForm'` + `import PostForm from 'src/components/AdminPages/Post/PostForm'`, ) }) test('creates an index cell', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx', ), ]) }) @@ -156,16 +156,16 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/AdminPages/Post/Posts'`) }) test('creates a show cell', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx', ), ]) }) @@ -174,9 +174,9 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/AdminPages/Post/Post'`) }) @@ -185,7 +185,7 @@ describe('AdminPages/Post', () => { test('creates a form component', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostForm/PostForm.jsx', ), ]) }) @@ -193,7 +193,7 @@ describe('AdminPages/Post', () => { test('creates an index component', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/Posts/Posts.jsx' + '/path/to/project/web/src/components/AdminPages/Post/Posts/Posts.jsx', ), ]) }) @@ -201,7 +201,7 @@ describe('AdminPages/Post', () => { test('creates a new component', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx', ), ]) }) @@ -210,18 +210,18 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx', ) - ] + ], ).toMatch( - `import PostForm from 'src/components/AdminPages/Post/PostForm'` + `import PostForm from 'src/components/AdminPages/Post/PostForm'`, ) }) test('creates a show component', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/Post/Post.jsx' + '/path/to/project/web/src/components/AdminPages/Post/Post/Post.jsx', ), ]) }) @@ -236,7 +236,7 @@ describe('AdminPages/Post', () => { model: 'Post', path: 'AdminPages', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -251,7 +251,7 @@ describe('AdminPages/Post', () => { model: 'UserProfile', path: 'AdminPages', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -273,7 +273,7 @@ describe('AdminPages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -293,7 +293,7 @@ describe('AdminPages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfileCell/UserProfileCell.jsx', ) ] @@ -313,7 +313,7 @@ describe('AdminPages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -334,7 +334,7 @@ describe('AdminPages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -349,7 +349,7 @@ describe('AdminPages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) @@ -378,7 +378,7 @@ describe('admin-pages/Post', () => { test('creates a layout', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -388,7 +388,7 @@ describe('admin-pages/Post', () => { test('creates a edit page', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -397,18 +397,18 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/AdminPages/Post/EditPostCell'` + `import EditPostCell from 'src/components/AdminPages/Post/EditPostCell'`, ) }) test('creates a index page', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx', ), ]) }) @@ -417,18 +417,18 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch( - `import PostsCell from 'src/components/AdminPages/Post/PostsCell'` + `import PostsCell from 'src/components/AdminPages/Post/PostsCell'`, ) }) test('creates a new page', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -437,16 +437,16 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/AdminPages/Post/NewPost'`) }) test('creates a show page', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx', ), ]) }) @@ -455,11 +455,11 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx', ) - ] + ], ).toMatch( - `import PostCell from 'src/components/AdminPages/Post/PostCell'` + `import PostCell from 'src/components/AdminPages/Post/PostCell'`, ) }) @@ -468,7 +468,7 @@ describe('admin-pages/Post', () => { test('creates an edit cell', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -477,18 +477,18 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch( - `import PostForm from 'src/components/AdminPages/Post/PostForm'` + `import PostForm from 'src/components/AdminPages/Post/PostForm'`, ) }) test('creates an index cell', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx', ), ]) }) @@ -497,16 +497,16 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/AdminPages/Post/Posts'`) }) test('creates a show cell', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx', ), ]) }) @@ -515,9 +515,9 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/AdminPages/Post/Post'`) }) @@ -526,7 +526,7 @@ describe('admin-pages/Post', () => { test('creates a form component', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostForm/PostForm.jsx', ), ]) }) @@ -534,7 +534,7 @@ describe('admin-pages/Post', () => { test('creates an index component', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/Posts/Posts.jsx' + '/path/to/project/web/src/components/AdminPages/Post/Posts/Posts.jsx', ), ]) }) @@ -542,7 +542,7 @@ describe('admin-pages/Post', () => { test('creates a new component', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx', ), ]) }) @@ -551,18 +551,18 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx', ) - ] + ], ).toMatch( - `import PostForm from 'src/components/AdminPages/Post/PostForm'` + `import PostForm from 'src/components/AdminPages/Post/PostForm'`, ) }) test('creates a show component', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/Post/Post.jsx' + '/path/to/project/web/src/components/AdminPages/Post/Post/Post.jsx', ), ]) }) @@ -577,7 +577,7 @@ describe('admin-pages/Post', () => { model: 'post', path: 'admin-pages', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -592,7 +592,7 @@ describe('admin-pages/Post', () => { model: 'userProfile', path: 'admin-pages', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -614,7 +614,7 @@ describe('admin-pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -634,7 +634,7 @@ describe('admin-pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfileCell/UserProfileCell.jsx', ) ] @@ -654,7 +654,7 @@ describe('admin-pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -675,7 +675,7 @@ describe('admin-pages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -690,7 +690,7 @@ describe('admin-pages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) @@ -719,7 +719,7 @@ describe('admin_pages/Post', () => { test('creates a layout', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -729,7 +729,7 @@ describe('admin_pages/Post', () => { test('creates a edit page', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -738,18 +738,18 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/AdminPages/Post/EditPostCell'` + `import EditPostCell from 'src/components/AdminPages/Post/EditPostCell'`, ) }) test('creates a index page', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx', ), ]) }) @@ -758,18 +758,18 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch( - `import PostsCell from 'src/components/AdminPages/Post/PostsCell'` + `import PostsCell from 'src/components/AdminPages/Post/PostsCell'`, ) }) test('creates a new page', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -778,16 +778,16 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/AdminPages/Post/NewPost'`) }) test('creates a show page', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx', ), ]) }) @@ -796,11 +796,11 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/Post/PostPage/PostPage.jsx', ) - ] + ], ).toMatch( - `import PostCell from 'src/components/AdminPages/Post/PostCell'` + `import PostCell from 'src/components/AdminPages/Post/PostCell'`, ) }) @@ -809,7 +809,7 @@ describe('admin_pages/Post', () => { test('creates an edit cell', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -818,18 +818,18 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch( - `import PostForm from 'src/components/AdminPages/Post/PostForm'` + `import PostForm from 'src/components/AdminPages/Post/PostForm'`, ) }) test('creates an index cell', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx', ), ]) }) @@ -838,16 +838,16 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/AdminPages/Post/Posts'`) }) test('creates a show cell', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx', ), ]) }) @@ -856,9 +856,9 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/AdminPages/Post/Post'`) }) @@ -867,7 +867,7 @@ describe('admin_pages/Post', () => { test('creates a form component', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/AdminPages/Post/PostForm/PostForm.jsx', ), ]) }) @@ -875,7 +875,7 @@ describe('admin_pages/Post', () => { test('creates an index component', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/Posts/Posts.jsx' + '/path/to/project/web/src/components/AdminPages/Post/Posts/Posts.jsx', ), ]) }) @@ -883,7 +883,7 @@ describe('admin_pages/Post', () => { test('creates a new component', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx', ), ]) }) @@ -892,18 +892,18 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/Post/NewPost/NewPost.jsx', ) - ] + ], ).toMatch( - `import PostForm from 'src/components/AdminPages/Post/PostForm'` + `import PostForm from 'src/components/AdminPages/Post/PostForm'`, ) }) test('creates a show component', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/Post/Post.jsx' + '/path/to/project/web/src/components/AdminPages/Post/Post/Post.jsx', ), ]) }) @@ -918,7 +918,7 @@ describe('admin_pages/Post', () => { model: 'Post', path: 'admin_pages', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -933,7 +933,7 @@ describe('admin_pages/Post', () => { model: 'UserProfile', path: 'admin_pages', nestScaffoldByModel: true, - }) + }), ).toEqual([ '', '', @@ -955,7 +955,7 @@ describe('admin_pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -975,7 +975,7 @@ describe('admin_pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/UserProfileCell/UserProfileCell.jsx', ) ] @@ -995,7 +995,7 @@ describe('admin_pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -1016,7 +1016,7 @@ describe('admin_pages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -1031,7 +1031,7 @@ describe('admin_pages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfile/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) diff --git a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiwordNoNest.test.js b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiwordNoNest.test.js index a49b379946d4..fe0d4c7b7c82 100644 --- a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiwordNoNest.test.js +++ b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathMultiwordNoNest.test.js @@ -37,7 +37,7 @@ describe('AdminPages/Post', () => { test('creates a layout', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -47,7 +47,7 @@ describe('AdminPages/Post', () => { test('creates a edit page', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -56,18 +56,18 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/AdminPages/EditPostCell'` + `import EditPostCell from 'src/components/AdminPages/EditPostCell'`, ) }) test('creates a index page', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx', ), ]) }) @@ -76,16 +76,16 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch(`import PostsCell from 'src/components/AdminPages/PostsCell'`) }) test('creates a new page', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -94,16 +94,16 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/AdminPages/NewPost'`) }) test('creates a show page', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx', ), ]) }) @@ -112,9 +112,9 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx', ) - ] + ], ).toMatch(`import PostCell from 'src/components/AdminPages/PostCell'`) }) @@ -123,7 +123,7 @@ describe('AdminPages/Post', () => { test('creates an edit cell', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -132,16 +132,16 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/AdminPages/PostForm'`) }) test('creates an index cell', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx', ), ]) }) @@ -150,16 +150,16 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/AdminPages/Posts'`) }) test('creates a show cell', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx', ), ]) }) @@ -168,9 +168,9 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/AdminPages/Post'`) }) @@ -179,7 +179,7 @@ describe('AdminPages/Post', () => { test('creates a form component', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/AdminPages/PostForm/PostForm.jsx', ), ]) }) @@ -187,7 +187,7 @@ describe('AdminPages/Post', () => { test('creates an index component', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Posts/Posts.jsx' + '/path/to/project/web/src/components/AdminPages/Posts/Posts.jsx', ), ]) }) @@ -195,7 +195,7 @@ describe('AdminPages/Post', () => { test('creates a new component', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx', ), ]) }) @@ -204,16 +204,16 @@ describe('AdminPages/Post', () => { expect( filesMultiwordUpper[ path.normalize( - '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/AdminPages/PostForm'`) }) test('creates a show component', async () => { expect(filesMultiwordUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/Post.jsx' + '/path/to/project/web/src/components/AdminPages/Post/Post.jsx', ), ]) }) @@ -228,7 +228,7 @@ describe('AdminPages/Post', () => { model: 'Post', path: 'AdminPages', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -243,7 +243,7 @@ describe('AdminPages/Post', () => { model: 'UserProfile', path: 'AdminPages', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -265,7 +265,7 @@ describe('AdminPages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -285,7 +285,7 @@ describe('AdminPages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfileCell/UserProfileCell.jsx', ) ] @@ -305,7 +305,7 @@ describe('AdminPages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -326,7 +326,7 @@ describe('AdminPages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/AdminPages/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -341,7 +341,7 @@ describe('AdminPages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) @@ -370,7 +370,7 @@ describe('admin-pages/Post', () => { test('creates a layout', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -380,7 +380,7 @@ describe('admin-pages/Post', () => { test('creates a edit page', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -389,18 +389,18 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/AdminPages/EditPostCell'` + `import EditPostCell from 'src/components/AdminPages/EditPostCell'`, ) }) test('creates a index page', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx', ), ]) }) @@ -409,16 +409,16 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch(`import PostsCell from 'src/components/AdminPages/PostsCell'`) }) test('creates a new page', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -427,16 +427,16 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/AdminPages/NewPost'`) }) test('creates a show page', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx', ), ]) }) @@ -445,9 +445,9 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx', ) - ] + ], ).toMatch(`import PostCell from 'src/components/AdminPages/PostCell'`) }) @@ -456,7 +456,7 @@ describe('admin-pages/Post', () => { test('creates an edit cell', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -465,16 +465,16 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/AdminPages/PostForm'`) }) test('creates an index cell', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx', ), ]) }) @@ -483,16 +483,16 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/AdminPages/Posts'`) }) test('creates a show cell', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx', ), ]) }) @@ -501,9 +501,9 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/AdminPages/Post'`) }) @@ -512,7 +512,7 @@ describe('admin-pages/Post', () => { test('creates a form component', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/AdminPages/PostForm/PostForm.jsx', ), ]) }) @@ -520,7 +520,7 @@ describe('admin-pages/Post', () => { test('creates an index component', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Posts/Posts.jsx' + '/path/to/project/web/src/components/AdminPages/Posts/Posts.jsx', ), ]) }) @@ -528,7 +528,7 @@ describe('admin-pages/Post', () => { test('creates a new component', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx', ), ]) }) @@ -537,16 +537,16 @@ describe('admin-pages/Post', () => { expect( filesMultiwordDash[ path.normalize( - '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/AdminPages/PostForm'`) }) test('creates a show component', async () => { expect(filesMultiwordDash).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/Post.jsx' + '/path/to/project/web/src/components/AdminPages/Post/Post.jsx', ), ]) }) @@ -561,7 +561,7 @@ describe('admin-pages/Post', () => { model: 'Post', path: 'admin-pages', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -576,7 +576,7 @@ describe('admin-pages/Post', () => { model: 'UserProfile', path: 'admin-pages', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -598,7 +598,7 @@ describe('admin-pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -618,7 +618,7 @@ describe('admin-pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfileCell/UserProfileCell.jsx', ) ] @@ -638,7 +638,7 @@ describe('admin-pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -659,7 +659,7 @@ describe('admin-pages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/AdminPages/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -674,7 +674,7 @@ describe('admin-pages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) @@ -703,7 +703,7 @@ describe('admin_pages/Post', () => { test('creates a layout', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -713,7 +713,7 @@ describe('admin_pages/Post', () => { test('creates a edit page', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -722,18 +722,18 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch( - `import EditPostCell from 'src/components/AdminPages/EditPostCell'` + `import EditPostCell from 'src/components/AdminPages/EditPostCell'`, ) }) test('creates a index page', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx', ), ]) }) @@ -742,16 +742,16 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch(`import PostsCell from 'src/components/AdminPages/PostsCell'`) }) test('creates a new page', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -760,16 +760,16 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/AdminPages/NewPost'`) }) test('creates a show page', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx', ), ]) }) @@ -778,9 +778,9 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/AdminPages/PostPage/PostPage.jsx', ) - ] + ], ).toMatch(`import PostCell from 'src/components/AdminPages/PostCell'`) }) @@ -789,7 +789,7 @@ describe('admin_pages/Post', () => { test('creates an edit cell', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -798,16 +798,16 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/AdminPages/PostForm'`) }) test('creates an index cell', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx', ), ]) }) @@ -816,16 +816,16 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/AdminPages/Posts'`) }) test('creates a show cell', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx', ), ]) }) @@ -834,9 +834,9 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/AdminPages/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/AdminPages/Post'`) }) @@ -845,7 +845,7 @@ describe('admin_pages/Post', () => { test('creates a form component', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/AdminPages/PostForm/PostForm.jsx', ), ]) }) @@ -853,7 +853,7 @@ describe('admin_pages/Post', () => { test('creates an index component', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Posts/Posts.jsx' + '/path/to/project/web/src/components/AdminPages/Posts/Posts.jsx', ), ]) }) @@ -861,7 +861,7 @@ describe('admin_pages/Post', () => { test('creates a new component', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx', ), ]) }) @@ -870,16 +870,16 @@ describe('admin_pages/Post', () => { expect( filesMultiwordUnderscore[ path.normalize( - '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/AdminPages/NewPost/NewPost.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/AdminPages/PostForm'`) }) test('creates a show component', async () => { expect(filesMultiwordUnderscore).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/Post/Post.jsx' + '/path/to/project/web/src/components/AdminPages/Post/Post.jsx', ), ]) }) @@ -894,7 +894,7 @@ describe('admin_pages/Post', () => { model: 'Post', path: 'admin_pages', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -909,7 +909,7 @@ describe('admin_pages/Post', () => { model: 'UserProfile', path: 'admin_pages', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -931,7 +931,7 @@ describe('admin_pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -951,7 +951,7 @@ describe('admin_pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/UserProfileCell/UserProfileCell.jsx', ) ] @@ -971,7 +971,7 @@ describe('admin_pages/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -992,7 +992,7 @@ describe('admin_pages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/AdminPages/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -1007,7 +1007,7 @@ describe('admin_pages/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/AdminPages/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) diff --git a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathNoNest.test.js b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathNoNest.test.js index 7001ec3c92c3..c246c191b291 100644 --- a/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathNoNest.test.js +++ b/packages/cli/src/commands/generate/scaffold/__tests__/scaffoldPathNoNest.test.js @@ -36,7 +36,7 @@ describe('admin/Post', () => { test('creates a layout', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -46,7 +46,7 @@ describe('admin/Post', () => { test('creates a edit page', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -55,16 +55,16 @@ describe('admin/Post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch(`import EditPostCell from 'src/components/Admin/EditPostCell'`) }) test('creates a index page', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/PostsPage/PostsPage.jsx', ), ]) }) @@ -73,16 +73,16 @@ describe('admin/Post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch(`import PostsCell from 'src/components/Admin/PostsCell'`) }) test('creates a new page', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -91,16 +91,16 @@ describe('admin/Post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/Admin/NewPost'`) }) test('creates a show page', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/PostPage/PostPage.jsx', ), ]) }) @@ -109,9 +109,9 @@ describe('admin/Post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/pages/Admin/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/PostPage/PostPage.jsx', ) - ] + ], ).toMatch(`import PostCell from 'src/components/Admin/PostCell'`) }) @@ -120,7 +120,7 @@ describe('admin/Post', () => { test('creates an edit cell', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -129,16 +129,16 @@ describe('admin/Post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/components/Admin/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/PostForm'`) }) test('creates an index cell', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/PostsCell/PostsCell.jsx', ), ]) }) @@ -147,16 +147,16 @@ describe('admin/Post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/components/Admin/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/Admin/Posts'`) }) test('creates a show cell', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/PostCell/PostCell.jsx', ), ]) }) @@ -165,9 +165,9 @@ describe('admin/Post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/components/Admin/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/Admin/Post'`) }) @@ -176,7 +176,7 @@ describe('admin/Post', () => { test('creates a form component', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/Admin/PostForm/PostForm.jsx', ), ]) }) @@ -184,7 +184,7 @@ describe('admin/Post', () => { test('creates an index component', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Posts/Posts.jsx' + '/path/to/project/web/src/components/Admin/Posts/Posts.jsx', ), ]) }) @@ -192,7 +192,7 @@ describe('admin/Post', () => { test('creates a new component', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/NewPost/NewPost.jsx', ), ]) }) @@ -201,16 +201,16 @@ describe('admin/Post', () => { expect( filesLower[ path.normalize( - '/path/to/project/web/src/components/Admin/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/NewPost/NewPost.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/PostForm'`) }) test('creates a show component', async () => { expect(filesLower).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/Post.jsx' + '/path/to/project/web/src/components/Admin/Post/Post.jsx', ), ]) }) @@ -224,7 +224,7 @@ describe('admin/Post', () => { model: 'Post', path: 'admin', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -239,7 +239,7 @@ describe('admin/Post', () => { model: 'UserProfile', path: 'admin', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -261,7 +261,7 @@ describe('admin/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -281,7 +281,7 @@ describe('admin/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfileCell/UserProfileCell.jsx', ) ] @@ -301,7 +301,7 @@ describe('admin/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -322,7 +322,7 @@ describe('admin/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/Admin/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -337,7 +337,7 @@ describe('admin/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) @@ -366,7 +366,7 @@ describe('Admin/Post', () => { test('creates a layout', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx' + '/path/to/project/web/src/layouts/ScaffoldLayout/ScaffoldLayout.jsx', ), ]) }) @@ -376,7 +376,7 @@ describe('Admin/Post', () => { test('creates a edit page', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/EditPostPage/EditPostPage.jsx', ), ]) }) @@ -385,16 +385,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/EditPostPage/EditPostPage.jsx' + '/path/to/project/web/src/pages/Admin/EditPostPage/EditPostPage.jsx', ) - ] + ], ).toMatch(`import EditPostCell from 'src/components/Admin/EditPostCell'`) }) test('creates a index page', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/PostsPage/PostsPage.jsx', ), ]) }) @@ -403,16 +403,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/PostsPage/PostsPage.jsx' + '/path/to/project/web/src/pages/Admin/PostsPage/PostsPage.jsx', ) - ] + ], ).toMatch(`import PostsCell from 'src/components/Admin/PostsCell'`) }) test('creates a new page', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/NewPostPage/NewPostPage.jsx', ), ]) }) @@ -421,16 +421,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/NewPostPage/NewPostPage.jsx' + '/path/to/project/web/src/pages/Admin/NewPostPage/NewPostPage.jsx', ) - ] + ], ).toMatch(`import NewPost from 'src/components/Admin/NewPost'`) }) test('creates a show page', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/pages/Admin/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/PostPage/PostPage.jsx', ), ]) }) @@ -439,9 +439,9 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/pages/Admin/PostPage/PostPage.jsx' + '/path/to/project/web/src/pages/Admin/PostPage/PostPage.jsx', ) - ] + ], ).toMatch(`import PostCell from 'src/components/Admin/PostCell'`) }) @@ -450,7 +450,7 @@ describe('Admin/Post', () => { test('creates an edit cell', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/EditPostCell/EditPostCell.jsx', ), ]) }) @@ -459,16 +459,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/EditPostCell/EditPostCell.jsx' + '/path/to/project/web/src/components/Admin/EditPostCell/EditPostCell.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/PostForm'`) }) test('creates an index cell', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/PostsCell/PostsCell.jsx', ), ]) }) @@ -477,16 +477,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/PostsCell/PostsCell.jsx' + '/path/to/project/web/src/components/Admin/PostsCell/PostsCell.jsx', ) - ] + ], ).toMatch(`import Posts from 'src/components/Admin/Posts'`) }) test('creates a show cell', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/PostCell/PostCell.jsx', ), ]) }) @@ -495,9 +495,9 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/PostCell/PostCell.jsx' + '/path/to/project/web/src/components/Admin/PostCell/PostCell.jsx', ) - ] + ], ).toMatch(`import Post from 'src/components/Admin/Post'`) }) @@ -506,7 +506,7 @@ describe('Admin/Post', () => { test('creates a form component', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/PostForm/PostForm.jsx' + '/path/to/project/web/src/components/Admin/PostForm/PostForm.jsx', ), ]) }) @@ -514,7 +514,7 @@ describe('Admin/Post', () => { test('creates an index component', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Posts/Posts.jsx' + '/path/to/project/web/src/components/Admin/Posts/Posts.jsx', ), ]) }) @@ -522,7 +522,7 @@ describe('Admin/Post', () => { test('creates a new component', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/NewPost/NewPost.jsx', ), ]) }) @@ -531,16 +531,16 @@ describe('Admin/Post', () => { expect( filesUpper[ path.normalize( - '/path/to/project/web/src/components/Admin/NewPost/NewPost.jsx' + '/path/to/project/web/src/components/Admin/NewPost/NewPost.jsx', ) - ] + ], ).toMatch(`import PostForm from 'src/components/Admin/PostForm'`) }) test('creates a show component', async () => { expect(filesUpper).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/Post/Post.jsx' + '/path/to/project/web/src/components/Admin/Post/Post.jsx', ), ]) }) @@ -555,7 +555,7 @@ describe('Admin/Post', () => { model: 'Post', path: 'Admin', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -570,7 +570,7 @@ describe('Admin/Post', () => { model: 'UserProfile', path: 'Admin', nestScaffoldByModel: false, - }) + }), ).toEqual([ '', '', @@ -592,7 +592,7 @@ describe('Admin/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfilesCell/UserProfilesCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfilesCell/UserProfilesCell.jsx', ) ] @@ -612,7 +612,7 @@ describe('Admin/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/UserProfileCell/UserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/UserProfileCell/UserProfileCell.jsx', ) ] @@ -632,7 +632,7 @@ describe('Admin/Post', () => { const cell = userProfileFiles[ path.normalize( - '/path/to/project/web/src/components/Admin/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/EditUserProfileCell/EditUserProfileCell.jsx', ) ] @@ -653,7 +653,7 @@ describe('Admin/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/NewUserProfile/NewUserProfile.jsx' + '/path/to/project/web/src/components/Admin/NewUserProfile/NewUserProfile.jsx', ), ]) }) @@ -668,7 +668,7 @@ describe('Admin/Post', () => { expect(foreignKeyFiles).toHaveProperty([ path.normalize( - '/path/to/project/web/src/components/Admin/EditUserProfileCell/EditUserProfileCell.jsx' + '/path/to/project/web/src/components/Admin/EditUserProfileCell/EditUserProfileCell.jsx', ), ]) }) diff --git a/packages/cli/src/commands/generate/scaffold/scaffold.js b/packages/cli/src/commands/generate/scaffold/scaffold.js index f9a8d85bae51..2efacd0ecfab 100644 --- a/packages/cli/src/commands/generate/scaffold/scaffold.js +++ b/packages/cli/src/commands/generate/scaffold/scaffold.js @@ -71,7 +71,7 @@ const filterAutoGeneratedColumnsForScaffold = (column) => { const getImportComponentNames = ( name, scaffoldPath, - nestScaffoldByModel = true + nestScaffoldByModel = true, ) => { const pluralName = pascalcase(pluralize(name)) const singularName = pascalcase(singularize(name)) @@ -155,7 +155,7 @@ export const files = async ({ const templateStrings = getTemplateStrings( name, scaffoldPath, - nestScaffoldByModel + nestScaffoldByModel, ) const pascalScaffoldPath = scaffoldPath === '' @@ -168,7 +168,7 @@ export const files = async ({ pascalScaffoldPath, typescript, nestScaffoldByModel, - templateStrings + templateStrings, )), ...(await sdlFiles({ ...getDefaultArgs(sdlBuilder), @@ -192,7 +192,7 @@ export const files = async ({ pascalScaffoldPath, typescript, nestScaffoldByModel, - templateStrings + templateStrings, )), } } @@ -204,7 +204,7 @@ const assetFiles = async (name, tailwind) => { side: 'web', generator: 'scaffold', templatePath: 'assets', - }) + }), ) for (const asset of assets) { @@ -231,7 +231,7 @@ const assetFiles = async (name, tailwind) => { }), { name, - } + }, ) fileList[outputPath] = template } @@ -245,12 +245,12 @@ const formatters = async (name, isTypescript) => { const outputPath = path.join( getPaths().web.src, 'lib', - isTypescript ? 'formatters.tsx' : 'formatters.jsx' + isTypescript ? 'formatters.tsx' : 'formatters.jsx', ) const outputPathTest = path.join( getPaths().web.src, 'lib', - isTypescript ? 'formatters.test.tsx' : 'formatters.test.jsx' + isTypescript ? 'formatters.test.tsx' : 'formatters.test.jsx', ) // skip files that already exist on disk, never worry about overwriting @@ -266,7 +266,7 @@ const formatters = async (name, isTypescript) => { }), { name, - } + }, ) const templateTest = await generateTemplate( @@ -277,7 +277,7 @@ const formatters = async (name, isTypescript) => { }), { name, - } + }, ) return { @@ -357,7 +357,7 @@ const modelRelatedVariables = (model) => { if (componentMetadata[column.type]?.validation) { validation = componentMetadata[column.type]?.validation( - column?.isRequired + column?.isRequired, ) } else { validation = column?.isRequired @@ -409,7 +409,7 @@ const modelRelatedVariables = (model) => { editableColumns.reduce((accumulator, column) => { accumulator[column.component] = true return accumulator - }, {}) + }, {}), ) if (!fieldsToImport.length) { @@ -443,7 +443,7 @@ const layoutFiles = async ( name, force, generateTypescript, - templateStrings + templateStrings, ) => { let fileList = {} @@ -452,19 +452,19 @@ const layoutFiles = async ( side: 'web', generator: 'scaffold', templatePath: 'layouts', - }) + }), ) for (const layout of layouts) { const outputLayoutName = layout.replace( /\.tsx\.template/, - generateTypescript ? '.tsx' : '.jsx' + generateTypescript ? '.tsx' : '.jsx', ) const outputPath = path.join( getPaths().web.layouts, 'ScaffoldLayout', - outputLayoutName + outputLayoutName, ) // Since the ScaffoldLayout is shared, don't overwrite by default @@ -479,7 +479,7 @@ const layoutFiles = async ( name, pascalScaffoldPath: '', ...templateStrings, - } + }, ) fileList[outputPath] = generateTypescript @@ -496,7 +496,7 @@ const pageFiles = async ( pascalScaffoldPath = '', generateTypescript, nestScaffoldByModel = true, - templateStrings + templateStrings, ) => { const pluralName = pascalcase(pluralize(name)) const singularName = pascalcase(singularize(name)) @@ -512,7 +512,7 @@ const pageFiles = async ( side: 'web', generator: 'scaffold', templatePath: 'pages', - }) + }), ) for (const page of pages) { @@ -530,7 +530,7 @@ const pageFiles = async ( getPaths().web.pages, pascalScaffoldPath, finalFolder, - outputPageName + outputPageName, ) const template = await generateTemplate( customOrDefaultTemplatePath({ @@ -545,7 +545,7 @@ const pageFiles = async ( pascalScaffoldPath, ...templateStrings, ...modelRelatedVariables(model), - } + }, ) fileList[outputPath] = generateTypescript @@ -561,7 +561,7 @@ const componentFiles = async ( pascalScaffoldPath = '', generateTypescript, nestScaffoldByModel = true, - templateStrings + templateStrings, ) => { const pluralName = pascalcase(pluralize(name)) const singularName = pascalcase(singularize(name)) @@ -577,7 +577,7 @@ const componentFiles = async ( side: 'web', generator: 'scaffold', templatePath: 'components', - }) + }), ) for (const component of components) { @@ -594,7 +594,7 @@ const componentFiles = async ( getPaths().web.components, pascalScaffoldPath, finalFolder, - outputComponentName + outputComponentName, ) const useClientDirective = getConfig().experimental?.rsc?.enabled @@ -617,7 +617,7 @@ const componentFiles = async ( useClientDirective, ...templateStrings, ...modelRelatedVariables(model), - } + }, ) fileList[outputPath] = generateTypescript @@ -674,7 +674,7 @@ const addLayoutImport = () => { if (!routesContent.match(importLayout)) { const newRoutesContent = routesContent.replace( /['"]@redwoodjs\/router['"](\s*)/, - `'@redwoodjs/router'\n\n${importLayout}$1` + `'@redwoodjs/router'\n\n${importLayout}$1`, ) writeFile(routesPath, newRoutesContent, { overwriteExisting: true }) @@ -707,12 +707,12 @@ const addSetImport = (task) => { const routesContent = readFile(routesPath).toString() const [redwoodRouterImport, importStart, spacing, importContent, importEnd] = routesContent.match( - /(import {)(\s*)([^]*)(} from ['"]@redwoodjs\/router['"])/ + /(import {)(\s*)([^]*)(} from ['"]@redwoodjs\/router['"])/, ) || [] if (!redwoodRouterImport) { task.skip( - "Couldn't add Set import from @redwoodjs/router to Routes.{jsx,tsx}" + "Couldn't add Set import from @redwoodjs/router to Routes.{jsx,tsx}", ) return undefined } @@ -729,7 +729,7 @@ const addSetImport = (task) => { `,` + spacing + importContent + - importEnd + importEnd, ) writeFile(routesPath, newRoutesContent, { overwriteExisting: true }) @@ -748,7 +748,7 @@ const addScaffoldSetToRouter = async (model, path) => { return addRoutesToRouterTask( await routes({ model, path }), 'ScaffoldLayout', - { title, titleTo, buttonLabel, buttonTo } + { title, titleTo, buttonLabel, buttonTo }, ) } @@ -783,8 +783,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#generate-scaffold' - )}` + 'https://redwoodjs.com/docs/cli-commands#generate-scaffold', + )}`, ) // Merge generator defaults in @@ -857,7 +857,7 @@ export const tasks = ({ }, }, ], - { rendererOptions: { collapseSubtasks: false }, exitOnError: true } + { rendererOptions: { collapseSubtasks: false }, exitOnError: true }, ) } diff --git a/packages/cli/src/commands/generate/script/__tests__/script.test.ts b/packages/cli/src/commands/generate/script/__tests__/script.test.ts index 5ecf120af207..a17dde05ed99 100644 --- a/packages/cli/src/commands/generate/script/__tests__/script.test.ts +++ b/packages/cli/src/commands/generate/script/__tests__/script.test.ts @@ -16,7 +16,7 @@ test('creates a JavaScript function to execute', () => { }) const expectedOutputPath = path.normalize( - '/path/to/project/scripts/scriptyMcScript.js' + '/path/to/project/scripts/scriptyMcScript.js', ) expect(Object.keys(output)).toContainEqual(expectedOutputPath) @@ -30,7 +30,7 @@ test('creates a TypeScript function to execute', () => { }) const expectedOutputPath = path.normalize( - '/path/to/project/scripts/typescriptyTypescript.ts' + '/path/to/project/scripts/typescriptyTypescript.ts', ) const tsconfigPath = path.normalize('/path/to/project/scripts/tsconfig.json') diff --git a/packages/cli/src/commands/generate/script/script.js b/packages/cli/src/commands/generate/script/script.js index 459ec5470580..efa429bf5101 100644 --- a/packages/cli/src/commands/generate/script/script.js +++ b/packages/cli/src/commands/generate/script/script.js @@ -16,7 +16,7 @@ const TEMPLATE_PATH = path.resolve(__dirname, 'templates', 'script.js.template') const TSCONFIG_TEMPLATE = path.resolve( __dirname, 'templates', - 'tsconfig.json.template' + 'tsconfig.json.template', ) export const files = ({ name, typescript = false }) => { @@ -52,8 +52,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#generate-script' - )}` + 'https://redwoodjs.com/docs/cli-commands#generate-script', + )}`, ) Object.entries(yargsDefaults).forEach(([option, config]) => { @@ -69,7 +69,7 @@ export const handler = async ({ force, ...args }) => { }) const POST_RUN_INSTRUCTIONS = `Next steps...\n\n ${c.warning( - 'After modifying your script, you can invoke it like:' + 'After modifying your script, you can invoke it like:', )} yarn rw exec ${args.name} @@ -94,7 +94,7 @@ export const handler = async ({ force, ...args }) => { }, }, ].filter(Boolean), - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/generate/sdl/__tests__/sdl.test.js b/packages/cli/src/commands/generate/sdl/__tests__/sdl.test.js index fccd76153bb4..56c86490b432 100644 --- a/packages/cli/src/commands/generate/sdl/__tests__/sdl.test.js +++ b/packages/cli/src/commands/generate/sdl/__tests__/sdl.test.js @@ -80,17 +80,17 @@ const itCreatesAService = (baseArgs = {}) => { expect(files).toHaveProperty([ path.normalize( - `/path/to/project/api/src/services/users/users.${extension}` + `/path/to/project/api/src/services/users/users.${extension}`, ), ]) expect(files).toHaveProperty([ path.normalize( - `/path/to/project/api/src/services/users/users.test.${extension}` + `/path/to/project/api/src/services/users/users.test.${extension}`, ), ]) expect(files).toHaveProperty([ path.normalize( - `/path/to/project/api/src/services/users/users.scenarios.${extension}` + `/path/to/project/api/src/services/users/users.scenarios.${extension}`, ), ]) }) @@ -104,9 +104,9 @@ const itCreatesASingleWordSDLFile = (baseArgs = {}) => { expect( files[ path.normalize( - `/path/to/project/api/src/graphql/users.sdl.${extension}` + `/path/to/project/api/src/graphql/users.sdl.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -122,9 +122,9 @@ const itCreatesAMultiWordSDLFile = (baseArgs = {}) => { expect( files[ path.normalize( - `/path/to/project/api/src/graphql/userProfiles.sdl.${extension}` + `/path/to/project/api/src/graphql/userProfiles.sdl.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -137,9 +137,9 @@ const itCreatesASingleWordSDLFileWithCRUD = (baseArgs = {}) => { expect( files[ path.normalize( - `/path/to/project/api/src/graphql/posts.sdl.${extension}` + `/path/to/project/api/src/graphql/posts.sdl.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -156,33 +156,33 @@ const itCreateAMultiWordSDLFileWithCRUD = (baseArgs = {}) => { // Service files expect(files).toHaveProperty([ path.normalize( - `/path/to/project/api/src/services/userProfiles/userProfiles.${extension}` + `/path/to/project/api/src/services/userProfiles/userProfiles.${extension}`, ), ]) expect(files).toHaveProperty([ path.normalize( - `/path/to/project/api/src/services/userProfiles/userProfiles.test.${extension}` + `/path/to/project/api/src/services/userProfiles/userProfiles.test.${extension}`, ), ]) expect(files).toHaveProperty([ path.normalize( - `/path/to/project/api/src/services/userProfiles/userProfiles.scenarios.${extension}` + `/path/to/project/api/src/services/userProfiles/userProfiles.scenarios.${extension}`, ), ]) //sdl file expect(files).toHaveProperty([ path.normalize( - `/path/to/project/api/src/graphql/userProfiles.sdl.${extension}` + `/path/to/project/api/src/graphql/userProfiles.sdl.${extension}`, ), ]) expect( files[ path.normalize( - `/path/to/project/api/src/graphql/userProfiles.sdl.${extension}` + `/path/to/project/api/src/graphql/userProfiles.sdl.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -199,9 +199,9 @@ const itCreatesAnSDLFileWithEnumDefinitions = (baseArgs = {}) => { expect( files[ path.normalize( - `/path/to/project/api/src/graphql/shoes.sdl.${extension}` + `/path/to/project/api/src/graphql/shoes.sdl.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -214,9 +214,9 @@ const itCreatesAnSDLFileWithJsonDefinitions = (baseArgs = {}) => { expect( files[ path.normalize( - `/path/to/project/api/src/graphql/photos.sdl.${extension}` + `/path/to/project/api/src/graphql/photos.sdl.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -231,7 +231,7 @@ const itCreatesAnSDLFileWithByteDefinitions = (baseArgs = {}) => { const ext = extensionForBaseArgs(baseArgs) expect( - files[path.normalize(`/path/to/project/api/src/graphql/keys.sdl.${ext}`)] + files[path.normalize(`/path/to/project/api/src/graphql/keys.sdl.${ext}`)], ).toMatchSnapshot() }) } diff --git a/packages/cli/src/commands/generate/sdl/sdl.js b/packages/cli/src/commands/generate/sdl/sdl.js index f3baf1f25c54..ff7d7521c61d 100644 --- a/packages/cli/src/commands/generate/sdl/sdl.js +++ b/packages/cli/src/commands/generate/sdl/sdl.js @@ -38,7 +38,7 @@ const missingIdConsoleMessage = () => { const line3 = "you'll need to update your schema definition to include" const line4 = 'an `@id` column. Read more here: ' const line5 = chalk.underline.blue( - 'https://redwoodjs.com/docs/schema-relations' + 'https://redwoodjs.com/docs/schema-relations', ) console.error( @@ -46,7 +46,7 @@ const missingIdConsoleMessage = () => { padding: 1, margin: { top: 1, bottom: 3, right: 1, left: 2 }, borderStyle: 'single', - }) + }), ) } @@ -154,7 +154,7 @@ const sdlFromSchemaModel = async (name, crud, docs = false) => { .map(async (field) => { const model = await getSchema(field.type) return model - }) + }), ) ).reduce((acc, cur) => ({ ...acc, [cur.name]: cur }), {}) @@ -166,7 +166,7 @@ const sdlFromSchemaModel = async (name, crud, docs = false) => { .map(async (field) => { const enumDef = await getEnum(field.type) return enumDef - }) + }), ) ).reduce((acc, curr) => acc.concat(curr), []) @@ -229,7 +229,7 @@ export const files = async ({ const extension = typescript ? 'ts' : 'js' let outputPath = path.join( getPaths().api.graphql, - `${camelcase(pluralize(name))}.sdl.${extension}` + `${camelcase(pluralize(name))}.sdl.${extension}`, ) if (typescript) { @@ -284,8 +284,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#generate-sdl' - )}` + 'https://redwoodjs.com/docs/cli-commands#generate-sdl', + )}`, ) // Merge default options in @@ -349,7 +349,7 @@ export const handler = async ({ rendererOptions: { collapseSubtasks: false }, exitOnError: true, silentRendererCondition: process.env.NODE_ENV === 'test', - } + }, ) if (rollback && !force) { diff --git a/packages/cli/src/commands/generate/secret/secret.js b/packages/cli/src/commands/generate/secret/secret.js index a012efe5e227..705832b109ab 100644 --- a/packages/cli/src/commands/generate/secret/secret.js +++ b/packages/cli/src/commands/generate/secret/secret.js @@ -31,8 +31,8 @@ export const builder = (yargs) => .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#generate-secret' - )}` + 'https://redwoodjs.com/docs/cli-commands#generate-secret', + )}`, ) export const handler = ({ length, raw }) => { @@ -51,7 +51,7 @@ export const handler = ({ length, raw }) => { console.info(` ${generateSecret(length)}`) console.info('') console.info( - "If you're using this with dbAuth, set a SESSION_SECRET environment variable to this value." + "If you're using this with dbAuth, set a SESSION_SECRET environment variable to this value.", ) console.info('') console.info('Keep it secret, keep it safe!') diff --git a/packages/cli/src/commands/generate/service/__tests__/scenario.test.js b/packages/cli/src/commands/generate/service/__tests__/scenario.test.js index 46f94e6f0831..1507a5057ebb 100644 --- a/packages/cli/src/commands/generate/service/__tests__/scenario.test.js +++ b/packages/cli/src/commands/generate/service/__tests__/scenario.test.js @@ -213,14 +213,13 @@ describe('the scenario generator', () => { }) test('fieldsToScenario returns scenario data for nested relations', async () => { - const { scalarFields, relations, foreignKeys } = await service.parseSchema( - 'UserProfile' - ) + const { scalarFields, relations, foreignKeys } = + await service.parseSchema('UserProfile') const scenario = await service.fieldsToScenario( scalarFields, relations, - foreignKeys + foreignKeys, ) expect(scenario.user).toEqual( @@ -228,7 +227,7 @@ describe('the scenario generator', () => { create: expect.objectContaining({ email: expect.any(String), }), - }) + }), ) }) }) diff --git a/packages/cli/src/commands/generate/service/__tests__/service.test.js b/packages/cli/src/commands/generate/service/__tests__/service.test.js index 87175e775bb9..1ef03fe1e515 100644 --- a/packages/cli/src/commands/generate/service/__tests__/service.test.js +++ b/packages/cli/src/commands/generate/service/__tests__/service.test.js @@ -43,9 +43,9 @@ const itCreatesASingleWordServiceFile = (baseArgs) => { expect( files[ path.normalize( - `/path/to/project/api/src/services/users/users.${extension}` + `/path/to/project/api/src/services/users/users.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -60,9 +60,9 @@ const itCreatesASingleWordServiceTestFile = (baseArgs) => { expect( files[ path.normalize( - `/path/to/project/api/src/services/users/users.test.${extension}` + `/path/to/project/api/src/services/users/users.test.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -75,7 +75,7 @@ const itCreatesASingleWordServiceScenarioFile = (baseArgs) => { }) const extension = extensionForBaseArgs(baseArgs) const filePath = path.normalize( - `/path/to/project/api/src/services/users/users.scenarios.${extension}` + `/path/to/project/api/src/services/users/users.scenarios.${extension}`, ) expect(Object.keys(files)).toContain(filePath) @@ -95,9 +95,9 @@ const itCreatesAMultiWordServiceFile = (baseArgs) => { expect( files[ path.normalize( - `/path/to/project/api/src/services/userProfiles/userProfiles.${extension}` + `/path/to/project/api/src/services/userProfiles/userProfiles.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -114,9 +114,9 @@ const itCreatesAMultiWordServiceTestFile = (baseArgs) => { expect( files[ path.normalize( - `/path/to/project/api/src/services/userProfiles/userProfiles.test.${extension}` + `/path/to/project/api/src/services/userProfiles/userProfiles.test.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -133,9 +133,9 @@ const itCreatesASingleWordServiceFileWithCRUDActions = (baseArgs) => { expect( files[ path.normalize( - `/path/to/project/api/src/services/posts/posts.${extension}` + `/path/to/project/api/src/services/posts/posts.${extension}`, ) - ] + ], ).toMatchSnapshot() // TODO @@ -152,7 +152,7 @@ const itCreatesASingleWordServiceTestFileWithCRUDActions = (baseArgs) => { }) const extension = extensionForBaseArgs(baseArgs) const filePath = path.normalize( - `/path/to/project/api/src/services/posts/posts.test.${extension}` + `/path/to/project/api/src/services/posts/posts.test.${extension}`, ) expect(Object.keys(files)).toContain(filePath) @@ -168,7 +168,7 @@ const itCreatesAMultiWordServiceFileWithCRUDActions = (baseArgs) => { }) const extension = extensionForBaseArgs(baseArgs) const filePath = path.normalize( - `/path/to/project/api/src/services/userProfiles/userProfiles.${extension}` + `/path/to/project/api/src/services/userProfiles/userProfiles.${extension}`, ) expect(Object.keys(files)).toContain(filePath) @@ -184,7 +184,7 @@ const itCreatesAMultiWordServiceTestFileWithCRUDActions = (baseArgs) => { }) const extension = extensionForBaseArgs(baseArgs) const filePath = path.normalize( - `/path/to/project/api/src/services/userProfiles/userProfiles.test.${extension}` + `/path/to/project/api/src/services/userProfiles/userProfiles.test.${extension}`, ) expect(Object.keys(files)).toContain(filePath) @@ -192,7 +192,7 @@ const itCreatesAMultiWordServiceTestFileWithCRUDActions = (baseArgs) => { } const itCreatesAMultiWordServiceTestFileWithMultipleScalarTypes = ( - baseArgs + baseArgs, ) => { test('creates a multi word service test file with multiple scalar types', async () => { const files = await service.files({ @@ -205,9 +205,9 @@ const itCreatesAMultiWordServiceTestFileWithMultipleScalarTypes = ( expect( files[ path.normalize( - `/path/to/project/api/src/services/scalarTypes/scalarTypes.test.${extension}` + `/path/to/project/api/src/services/scalarTypes/scalarTypes.test.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -225,9 +225,9 @@ const itCreatesASingleWordServiceFileWithAHasManyRelation = (baseArgs) => { expect( files[ path.normalize( - `/path/to/project/api/src/services/users/users.${extension}` + `/path/to/project/api/src/services/users/users.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -245,9 +245,9 @@ const itCreatesASingleWordServiceFileWithABelongsToRelation = (baseArgs) => { expect( files[ path.normalize( - `/path/to/project/api/src/services/users/users.${extension}` + `/path/to/project/api/src/services/users/users.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -265,15 +265,15 @@ const itCreatesASingleWordServiceFileWithMultipleRelations = (baseArgs) => { expect( files[ path.normalize( - `/path/to/project/api/src/services/users/users.${extension}` + `/path/to/project/api/src/services/users/users.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } const itCreatesAMultiWordServiceTestFileWithCRUDAndOnlyForeignKeyRequired = ( - baseArgs + baseArgs, ) => { test('creates a multi word service test file with crud actions and only foreign as mandatory field', async () => { const files = await service.files({ @@ -286,9 +286,9 @@ const itCreatesAMultiWordServiceTestFileWithCRUDAndOnlyForeignKeyRequired = ( expect( files[ path.normalize( - `/path/to/project/api/src/services/transactions/transactions.test.${extension}` + `/path/to/project/api/src/services/transactions/transactions.test.${extension}`, ) - ] + ], ).toMatchSnapshot() }) } @@ -356,7 +356,7 @@ describe('parseSchema', () => { const { scalarFields } = await service.parseSchema('User') expect( - scalarFields.find((field) => field.name === 'email') + scalarFields.find((field) => field.name === 'email'), ).not.toBeUndefined() }) @@ -370,7 +370,7 @@ describe('parseSchema', () => { const { scalarFields } = await service.parseSchema('User') expect( - scalarFields.find((field) => field.name === 'isAdmin') + scalarFields.find((field) => field.name === 'isAdmin'), ).toBeUndefined() }) @@ -378,7 +378,7 @@ describe('parseSchema', () => { const { scalarFields } = await service.parseSchema('UserProfile') expect( - scalarFields.find((field) => field.name === 'userId') + scalarFields.find((field) => field.name === 'userId'), ).not.toBeUndefined() }) @@ -443,7 +443,7 @@ describe('fieldsToScenario', () => { { name: 'boolean', type: 'Boolean' }, ], {}, - [] + [], ) expect(output.email).toEqual('String') @@ -469,7 +469,7 @@ describe('fieldsToScenario', () => { { name: 'userId', type: 'Integer' }, ], { user: { foreignKey: 'userId', type: 'User' } }, - ['userId'] + ['userId'], ) expect(Object.keys(output)).toEqual(['title', 'user']) @@ -486,7 +486,7 @@ describe('fieldsToScenario', () => { ], // note that relationship name is "author" but datatype is "User" { author: { foreignKey: 'authorId', type: 'User' } }, - ['userId'] + ['userId'], ) expect(Object.keys(output)).toEqual(['title', 'author']) diff --git a/packages/cli/src/commands/generate/service/service.js b/packages/cli/src/commands/generate/service/service.js index 0576182e155e..051c25da3764 100644 --- a/packages/cli/src/commands/generate/service/service.js +++ b/packages/cli/src/commands/generate/service/service.js @@ -79,7 +79,7 @@ export const scenarioFieldValue = (field) => { export const fieldsToScenario = async ( scalarFields, relations, - foreignKeys + foreignKeys, ) => { const data = {} @@ -103,7 +103,7 @@ export const fieldsToScenario = async ( create: await fieldsToScenario( relScalarFields, relRelations, - relForeignKeys + relForeignKeys, ), } } @@ -126,7 +126,7 @@ export const buildScenario = async (model) => { const scenarioData = await fieldsToScenario( scalarFields, relations, - foreignKeys + foreignKeys, ) Object.keys(scenarioData).forEach((key) => { @@ -326,9 +326,9 @@ export const files = async ({ create: await fieldsToInput(model), update: await fieldsToUpdate(model), types: await fieldTypes(model), - prismaImport: ( - await parseSchema(model) - ).scalarFields.some((field) => field.type === 'Decimal'), + prismaImport: (await parseSchema(model)).scalarFields.some( + (field) => field.type === 'Decimal', + ), prismaModel: model, idName, ...rest, @@ -404,8 +404,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#generate-service' - )}` + 'https://redwoodjs.com/docs/cli-commands#generate-service', + )}`, ) Object.entries(defaults).forEach(([option, config]) => { yargs.option(option, config) diff --git a/packages/cli/src/commands/info.js b/packages/cli/src/commands/info.js index 5593e03760c8..e0bf8af50020 100644 --- a/packages/cli/src/commands/info.js +++ b/packages/cli/src/commands/info.js @@ -11,8 +11,8 @@ export const builder = (yargs) => { yargs.epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#info' - )}` + 'https://redwoodjs.com/docs/cli-commands#info', + )}`, ) } export const handler = async () => { diff --git a/packages/cli/src/commands/lint.js b/packages/cli/src/commands/lint.js index c24bab90224b..7857429de11c 100644 --- a/packages/cli/src/commands/lint.js +++ b/packages/cli/src/commands/lint.js @@ -23,8 +23,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#lint' - )}` + 'https://redwoodjs.com/docs/cli-commands#lint', + )}`, ) } @@ -50,7 +50,7 @@ export const handler = async ({ path, fix }) => { cwd: getPaths().base, shell: true, stdio: 'inherit', - } + }, ) process.exitCode = result.exitCode diff --git a/packages/cli/src/commands/prerenderHandler.js b/packages/cli/src/commands/prerenderHandler.js index 45fdb405ac30..9a4f12564176 100644 --- a/packages/cli/src/commands/prerenderHandler.js +++ b/packages/cli/src/commands/prerenderHandler.js @@ -25,7 +25,7 @@ const mapRouterPathToHtml = (routerPath) => { function getRouteHooksFilePath(routeFilePath) { const routeHooksFilePathTs = routeFilePath.replace( /\.[jt]sx?$/, - '.routeHooks.ts' + '.routeHooks.ts', ) if (fs.existsSync(routeHooksFilePathTs)) { @@ -34,7 +34,7 @@ function getRouteHooksFilePath(routeFilePath) { const routeHooksFilePathJs = routeFilePath.replace( /\.[jt]sx?$/, - '.routeHooks.js' + '.routeHooks.js', ) if (fs.existsSync(routeHooksFilePathJs)) { @@ -101,7 +101,7 @@ async function expandRouteParameters(route) { Object.entries(pathParamValues).forEach(([paramName, paramValue]) => { newPath = newPath.replace( new RegExp(`{${paramName}:?[^}]*}`), - paramValue + paramValue, ) }) @@ -124,8 +124,8 @@ export const getTasks = async (dryrun, routerPathFilter = null) => { console.log('\nSkipping prerender...') console.log( c.warning( - 'You have not marked any routes with a path as `prerender` in `Routes.{jsx,tsx}` \n' - ) + 'You have not marked any routes with a path as `prerender` in `Routes.{jsx,tsx}` \n', + ), ) // Don't error out @@ -134,7 +134,7 @@ export const getTasks = async (dryrun, routerPathFilter = null) => { if (!fs.existsSync(indexHtmlPath)) { console.error( - 'You must run `yarn rw build web` before trying to prerender.' + 'You must run `yarn rw build web` before trying to prerender.', ) process.exit(1) // TODO: Run this automatically at this point. @@ -143,7 +143,7 @@ export const getTasks = async (dryrun, routerPathFilter = null) => { configureBabel() const expandedRouteParameters = await Promise.all( - prerenderRoutes.map((route) => expandRouteParameters(route)) + prerenderRoutes.map((route) => expandRouteParameters(route)), ) const listrTasks = expandedRouteParameters @@ -172,7 +172,7 @@ export const getTasks = async (dryrun, routerPathFilter = null) => { // Check if route param templates in e.g. /path/{param1} have been replaced if (/\{.*}/.test(routeToPrerender.path)) { throw new PathParamError( - `Could not retrieve route parameters for ${routeToPrerender.path}` + `Could not retrieve route parameters for ${routeToPrerender.path}`, ) } @@ -188,14 +188,14 @@ export const getTasks = async (dryrun, routerPathFilter = null) => { } catch (e) { console.log() console.log( - c.warning('You can use `yarn rw prerender --dry-run` to debug') + c.warning('You can use `yarn rw prerender --dry-run` to debug'), ) console.log() console.log( `${c.info('-'.repeat(10))} Error rendering path "${ routeToPrerender.path - }" ${c.info('-'.repeat(10))}` + }" ${c.info('-'.repeat(10))}`, ) errorTelemetry(process.argv, `Error prerendering: ${e.message}`) @@ -218,25 +218,25 @@ const diagnosticCheck = () => { { message: 'Duplicate React version found in web/node_modules', failure: fs.existsSync( - path.join(getPaths().web.base, 'node_modules/react') + path.join(getPaths().web.base, 'node_modules/react'), ), }, { message: 'Duplicate react-dom version found in web/node_modules', failure: fs.existsSync( - path.join(getPaths().web.base, 'node_modules/react-dom') + path.join(getPaths().web.base, 'node_modules/react-dom'), ), }, { message: 'Duplicate core-js version found in web/node_modules', failure: fs.existsSync( - path.join(getPaths().web.base, 'node_modules/core-js') + path.join(getPaths().web.base, 'node_modules/core-js'), ), }, { message: 'Duplicate @redwoodjs/web version found in web/node_modules', failure: fs.existsSync( - path.join(getPaths().web.base, 'node_modules/@redwoodjs/web') + path.join(getPaths().web.base, 'node_modules/@redwoodjs/web'), ), }, ] @@ -256,13 +256,13 @@ const diagnosticCheck = () => { console.log('-'.repeat(50)) console.log( - 'Diagnostic check found issues. See the Redwood Forum link below for help:' + 'Diagnostic check found issues. See the Redwood Forum link below for help:', ) console.log( c.underline( - 'https://community.redwoodjs.com/search?q=duplicate%20package%20found' - ) + 'https://community.redwoodjs.com/search?q=duplicate%20package%20found', + ), ) console.log() @@ -278,8 +278,8 @@ export const handler = async ({ path: routerPath, dryRun, verbose }) => { if (getConfig().experimental?.streamingSsr?.enabled) { console.log( c.warning( - 'Prerendering is not yet supported with Streaming SSR. Skipping prerender...' - ) + 'Prerendering is not yet supported with Streaming SSR. Skipping prerender...', + ), ) return @@ -314,25 +314,25 @@ export const handler = async ({ path: routerPath, dryRun, verbose }) => { if (e instanceof PathParamError) { console.log( c.info( - "- You most likely need to add or update a *.routeHooks.{js,ts} file next to the Page you're trying to prerender" - ) + "- You most likely need to add or update a *.routeHooks.{js,ts} file next to the Page you're trying to prerender", + ), ) } else { console.log( c.info( - `- This could mean that a library you're using does not support SSR.` - ) + `- This could mean that a library you're using does not support SSR.`, + ), ) console.log( c.info( - '- Avoid using `window` in the initial render path through your React components without checks. \n See https://redwoodjs.com/docs/prerender#prerender-utils' - ) + '- Avoid using `window` in the initial render path through your React components without checks. \n See https://redwoodjs.com/docs/prerender#prerender-utils', + ), ) console.log( c.info( - '- Avoid prerendering Cells with authenticated queries, by conditionally rendering them.\n See https://redwoodjs.com/docs/prerender#common-warnings--errors' - ) + '- Avoid prerendering Cells with authenticated queries, by conditionally rendering them.\n See https://redwoodjs.com/docs/prerender#common-warnings--errors', + ), ) } diff --git a/packages/cli/src/commands/prismaHandler.js b/packages/cli/src/commands/prismaHandler.js index e4b6bcf0da82..f513c91e3412 100644 --- a/packages/cli/src/commands/prismaHandler.js +++ b/packages/cli/src/commands/prismaHandler.js @@ -30,7 +30,7 @@ export const handler = async ({ _, $0, commands = [], ...options }) => { if (!hasHelpOption) { if ( ['generate', 'introspect', 'db', 'migrate', 'studio', 'format'].includes( - commands[0] + commands[0], ) ) { if (!fs.existsSync(rwjsPaths.api.dbSchema)) { @@ -74,7 +74,7 @@ export const handler = async ({ _, $0, commands = [], ...options }) => { cwd: rwjsPaths.base, stdio: 'inherit', cleanup: true, - } + }, ) if (hasHelpOption || commands.length === 0) { @@ -102,6 +102,6 @@ const printWrapInfo = () => { padding: { top: 0, bottom: 0, right: 1, left: 1 }, margin: 1, borderColor: 'gray', - }) + }), ) } diff --git a/packages/cli/src/commands/record.js b/packages/cli/src/commands/record.js index 933c1b9dbef0..f33822ecdf0f 100644 --- a/packages/cli/src/commands/record.js +++ b/packages/cli/src/commands/record.js @@ -10,6 +10,6 @@ export const builder = (yargs) => .epilogue( `Also see the ${terminalLink( 'RedwoodRecord Docs', - 'https://redwoodjs.com/docs/redwoodrecord' - )}\n` + 'https://redwoodjs.com/docs/redwoodrecord', + )}\n`, ) diff --git a/packages/cli/src/commands/serve.js b/packages/cli/src/commands/serve.js index 168b84558cd0..89b5e27bff7f 100644 --- a/packages/cli/src/commands/serve.js +++ b/packages/cli/src/commands/serve.js @@ -107,8 +107,8 @@ export const builder = async (yargs) => { ) { console.error( c.error( - '\n Please run `yarn rw build web` before trying to serve web. \n' - ) + '\n Please run `yarn rw build web` before trying to serve web. \n', + ), ) process.exit(1) } @@ -119,8 +119,8 @@ export const builder = async (yargs) => { ) { console.error( c.error( - '\n Please run `yarn rw build api` before trying to serve api. \n' - ) + '\n Please run `yarn rw build api` before trying to serve api. \n', + ), ) process.exit(1) } @@ -133,8 +133,8 @@ export const builder = async (yargs) => { ) { console.error( c.error( - '\n Please run `yarn rw build` before trying to serve your redwood app. \n' - ) + '\n Please run `yarn rw build` before trying to serve your redwood app. \n', + ), ) process.exit(1) } @@ -147,7 +147,7 @@ export const builder = async (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#serve' - )}` + 'https://redwoodjs.com/docs/cli-commands#serve', + )}`, ) } diff --git a/packages/cli/src/commands/serveBothHandler.js b/packages/cli/src/commands/serveBothHandler.js index 8fdc57c7e88d..71bad8b1a052 100644 --- a/packages/cli/src/commands/serveBothHandler.js +++ b/packages/cli/src/commands/serveBothHandler.js @@ -62,7 +62,7 @@ export const bothServerFileHandler = async (argv) => { prefix: '{name} |', timestampFormat: 'HH:mm:ss', handleInput: true, - } + }, ) try { @@ -71,7 +71,7 @@ export const bothServerFileHandler = async (argv) => { if (typeof error?.message !== 'undefined') { errorTelemetry( process.argv, - `Error concurrently starting sides: ${error.message}` + `Error concurrently starting sides: ${error.message}`, ) exitWithError(error) } diff --git a/packages/cli/src/commands/setup.js b/packages/cli/src/commands/setup.js index 111a98d2682c..22c1f16e0fca 100644 --- a/packages/cli/src/commands/setup.js +++ b/packages/cli/src/commands/setup.js @@ -23,6 +23,6 @@ export const builder = (yargs) => .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#setup' - )}` + 'https://redwoodjs.com/docs/cli-commands#setup', + )}`, ) diff --git a/packages/cli/src/commands/setup/auth/auth.js b/packages/cli/src/commands/setup/auth/auth.js index 287037d2b5a7..9e14cd6465ce 100644 --- a/packages/cli/src/commands/setup/auth/auth.js +++ b/packages/cli/src/commands/setup/auth/auth.js @@ -21,8 +21,8 @@ export async function builder(yargs) { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#setup-auth' - )}` + 'https://redwoodjs.com/docs/cli-commands#setup-auth', + )}`, ) // Command "redirects" for auth providers we used to support .command(...redirectCommand('ethereum')) @@ -44,7 +44,7 @@ export async function builder(yargs) { const handler = await getAuthHandler('@redwoodjs/auth-auth0-setup') console.log() handler(args) - } + }, ) .command( ['azure-active-directory', 'azureActiveDirectory'], @@ -57,11 +57,11 @@ export async function builder(yargs) { verbose: args.verbose, }) const handler = await getAuthHandler( - '@redwoodjs/auth-azure-active-directory-setup' + '@redwoodjs/auth-azure-active-directory-setup', ) console.log() handler(args) - } + }, ) .command( 'clerk', @@ -76,7 +76,7 @@ export async function builder(yargs) { const handler = await getAuthHandler('@redwoodjs/auth-clerk-setup') console.log() handler(args) - } + }, ) .command( 'custom', @@ -91,7 +91,7 @@ export async function builder(yargs) { const handler = await getAuthHandler('@redwoodjs/auth-custom-setup') console.log() handler(args) - } + }, ) .command( 'dbAuth', @@ -114,7 +114,7 @@ export async function builder(yargs) { const handler = await getAuthHandler('@redwoodjs/auth-dbauth-setup') console.log() handler(args) - } + }, ) .command( 'firebase', @@ -129,7 +129,7 @@ export async function builder(yargs) { const handler = await getAuthHandler('@redwoodjs/auth-firebase-setup') console.log() handler(args) - } + }, ) .command( 'netlify', @@ -144,7 +144,7 @@ export async function builder(yargs) { const handler = await getAuthHandler('@redwoodjs/auth-netlify-setup') console.log() handler(args) - } + }, ) .command( 'supabase', @@ -159,7 +159,7 @@ export async function builder(yargs) { const handler = await getAuthHandler('@redwoodjs/auth-supabase-setup') console.log() handler(args) - } + }, ) .command( 'supertokens', @@ -172,11 +172,11 @@ export async function builder(yargs) { verbose: args.verbose, }) const handler = await getAuthHandler( - '@redwoodjs/auth-supertokens-setup' + '@redwoodjs/auth-supertokens-setup', ) console.log() handler(args) - } + }, ) } @@ -207,7 +207,7 @@ function redirectCommand(provider) { function getRedirectMessage(provider) { return `${provider} is no longer supported out of the box. But you can still integrate it yourself with ${terminalLink( 'Custom Auth', - 'https://redwoodjs.com/docs/canary/auth/custom' + 'https://redwoodjs.com/docs/canary/auth/custom', )}` } @@ -229,7 +229,7 @@ async function getAuthHandler(module) { try { const packumentResponse = await fetch( - `https://registry.npmjs.org/${module}` + `https://registry.npmjs.org/${module}`, ) packument = await packumentResponse.json() @@ -239,7 +239,7 @@ async function getAuthHandler(module) { } } catch (error) { throw new Error( - `Couldn't fetch packument for ${module}: ${error.message}` + `Couldn't fetch packument for ${module}: ${error.message}`, ) } @@ -271,7 +271,7 @@ async function getAuthHandler(module) { */ function isInstalled(module) { const { dependencies, devDependencies } = fs.readJSONSync( - path.join(getPaths().base, 'package.json') + path.join(getPaths().base, 'package.json'), ) const deps = { diff --git a/packages/cli/src/commands/setup/cache/cache.js b/packages/cli/src/commands/setup/cache/cache.js index 3f7350159074..ac99a308f276 100644 --- a/packages/cli/src/commands/setup/cache/cache.js +++ b/packages/cli/src/commands/setup/cache/cache.js @@ -23,8 +23,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#setup-cache' - )}` + 'https://redwoodjs.com/docs/cli-commands#setup-cache', + )}`, ) } diff --git a/packages/cli/src/commands/setup/cache/cacheHandler.js b/packages/cli/src/commands/setup/cache/cacheHandler.js index 7ba40160adb5..81f9305e7bb3 100644 --- a/packages/cli/src/commands/setup/cache/cacheHandler.js +++ b/packages/cli/src/commands/setup/cache/cacheHandler.js @@ -34,7 +34,7 @@ export const handler = async ({ client, force }) => { task: () => { const template = fs .readFileSync( - path.join(__dirname, 'templates', `${client}.ts.template`) + path.join(__dirname, 'templates', `${client}.ts.template`), ) .toString() @@ -43,14 +43,14 @@ export const handler = async ({ client, force }) => { template, { overwriteExisting: force, - } + }, ) }, }, addEnvVarTask( 'CACHE_HOST', CLIENT_HOST_MAP[client], - `Where your ${client} server lives for service caching` + `Where your ${client} server lives for service caching`, ), { title: 'One more thing...', diff --git a/packages/cli/src/commands/setup/custom-web-index/custom-web-index-handler.js b/packages/cli/src/commands/setup/custom-web-index/custom-web-index-handler.js index 5d360dc2d7b7..5386a4132d16 100644 --- a/packages/cli/src/commands/setup/custom-web-index/custom-web-index-handler.js +++ b/packages/cli/src/commands/setup/custom-web-index/custom-web-index-handler.js @@ -12,7 +12,7 @@ import c from '../../../lib/colors' export const handler = async ({ force }) => { if (getPaths().web.viteConfig) { console.warn( - c.warning('Warning: This command only applies to projects using webpack') + c.warning('Warning: This command only applies to projects using webpack'), ) return } @@ -35,12 +35,12 @@ export const handler = async ({ force }) => { path.join( getPaths().base, // NOTE we're copying over the index.js before babel transform - 'node_modules/@redwoodjs/web/src/entry/index.js' - ) + 'node_modules/@redwoodjs/web/src/entry/index.js', + ), ) .toString() .replace('~redwood-app-root', './App'), - { overwriteExisting: force } + { overwriteExisting: force }, ) }, }, @@ -49,14 +49,14 @@ export const handler = async ({ force }) => { task: (_ctx, task) => { task.title = `One more thing...\n ${c.green( - 'Quick link to the docs on configuring a custom entry point for your RW app' + 'Quick link to the docs on configuring a custom entry point for your RW app', )} ${chalk.hex('#e8e8e8')('https://redwoodjs.com/docs/custom-web-index')} ` }, }, ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/setup/deploy/__tests__/netlify.test.js b/packages/cli/src/commands/setup/deploy/__tests__/netlify.test.js index 10203da45d80..0120611a87bc 100644 --- a/packages/cli/src/commands/setup/deploy/__tests__/netlify.test.js +++ b/packages/cli/src/commands/setup/deploy/__tests__/netlify.test.js @@ -21,8 +21,8 @@ vi.mock('../../../../lib', async (importOriginal) => { base: path.resolve( path.join( __dirname, - '../../../../../../../__fixtures__/example-todo-main' - ) + '../../../../../../../__fixtures__/example-todo-main', + ), ), } }, @@ -76,7 +76,7 @@ describe('netlify', () => { expect(error).toBeUndefined() const filesystem = vol.toJSON() const netlifyTomlPath = Object.keys(filesystem).find((path) => - path.endsWith('netlify.toml') + path.endsWith('netlify.toml'), ) expect(netlifyTomlPath).toBeDefined() expect(filesystem[netlifyTomlPath]).toMatchSnapshot() @@ -86,7 +86,7 @@ describe('netlify', () => { updateApiURLTask('/.netlify/functions').task() expect(fs.readFileSync(REDWOOD_TOML_PATH)).toMatch( - /apiUrl = "\/.netlify\/functions"/ + /apiUrl = "\/.netlify\/functions"/, ) }) @@ -96,7 +96,7 @@ describe('netlify', () => { const filesystem = vol.toJSON() const netlifyTomlPath = Object.keys(filesystem).find((path) => - path.endsWith('netlify.toml') + path.endsWith('netlify.toml'), ) expect(netlifyTomlPath).toBeDefined() expect(filesystem[netlifyTomlPath]).toMatchSnapshot() diff --git a/packages/cli/src/commands/setup/deploy/deploy.js b/packages/cli/src/commands/setup/deploy/deploy.js index 705c8ae93edb..7f0e05e7b2db 100644 --- a/packages/cli/src/commands/setup/deploy/deploy.js +++ b/packages/cli/src/commands/setup/deploy/deploy.js @@ -15,6 +15,6 @@ export const builder = (yargs) => .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#setup-deploy-config' - )}` + 'https://redwoodjs.com/docs/cli-commands#setup-deploy-config', + )}`, ) diff --git a/packages/cli/src/commands/setup/deploy/helpers/index.js b/packages/cli/src/commands/setup/deploy/helpers/index.js index 957ef661aef4..e2268602f6d2 100644 --- a/packages/cli/src/commands/setup/deploy/helpers/index.js +++ b/packages/cli/src/commands/setup/deploy/helpers/index.js @@ -18,12 +18,12 @@ export const updateApiURLTask = (apiUrl) => { if (redwoodToml.match(/apiUrl/)) { newRedwoodToml = newRedwoodToml.replace( /apiUrl.*/g, - `apiUrl = "${apiUrl}"` + `apiUrl = "${apiUrl}"`, ) } else if (redwoodToml.match(/\[web\]/)) { newRedwoodToml = newRedwoodToml.replace( /\[web\]/, - `[web]\n apiUrl = "${apiUrl}"` + `[web]\n apiUrl = "${apiUrl}"`, ) } else { newRedwoodToml += `[web]\n apiUrl = "${apiUrl}"` @@ -66,7 +66,7 @@ export const preRequisiteCheckTask = (preRequisites) => { } }, } - }) + }), ), } } diff --git a/packages/cli/src/commands/setup/deploy/providers/baremetal.js b/packages/cli/src/commands/setup/deploy/providers/baremetal.js index 7d3ce5a0f6d4..2ec5ab6b9034 100644 --- a/packages/cli/src/commands/setup/deploy/providers/baremetal.js +++ b/packages/cli/src/commands/setup/deploy/providers/baremetal.js @@ -54,7 +54,7 @@ export const handler = async ({ force }) => { }), printSetupNotes(notes), ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { await tasks.run() diff --git a/packages/cli/src/commands/setup/deploy/providers/coherenceHandler.js b/packages/cli/src/commands/setup/deploy/providers/coherenceHandler.js index 97ee306d6e81..f86317371031 100644 --- a/packages/cli/src/commands/setup/deploy/providers/coherenceHandler.js +++ b/packages/cli/src/commands/setup/deploy/providers/coherenceHandler.js @@ -35,7 +35,7 @@ export async function handler({ force }) { "Reach out to redwood@withcoherence.com with any questions! We're here to support you.", ]), ], - { rendererOptions: { collapse: false } } + { rendererOptions: { collapse: false } }, ) await tasks.run() @@ -97,9 +97,9 @@ async function getCoherenceConfigFileContent() { [ `Coherence doesn't support the "${db}" provider in your Prisma schema.`, `To proceed, switch to one of the following: ${SUPPORTED_DATABASES.join( - ', ' + ', ', )}.`, - ].join('\n') + ].join('\n'), ) } @@ -113,7 +113,7 @@ async function getCoherenceConfigFileContent() { 'yarn', 'node', 'api/dist/server.js', - '--apiRootPath=/api' + '--apiRootPath=/api', ) } else { apiProdCommand.push('yarn', 'rw', 'serve', 'api', '--apiRootPath=/api') @@ -138,7 +138,7 @@ function updateRedwoodTOMLTask() { task: () => { const redwoodTOMLPath = path.join( redwoodProjectPaths.base, - 'redwood.toml' + 'redwood.toml', ) let redwoodTOMLContent = fs.readFileSync(redwoodTOMLPath, 'utf-8') const redwoodTOMLObject = toml.parse(redwoodTOMLContent) @@ -167,8 +167,8 @@ function updateRedwoodTOMLTask() { HOST_REGEXP, (match, spaceBeforeAssign, spaceAfterAssign) => ['host', spaceBeforeAssign, '=', spaceAfterAssign, '"0.0.0.0"'].join( - '' - ) + '', + ), ) // Replace the apiUrl @@ -176,8 +176,8 @@ function updateRedwoodTOMLTask() { API_URL_REGEXP, (match, spaceBeforeAssign, spaceAfterAssign) => ['apiUrl', spaceBeforeAssign, '=', spaceAfterAssign, '"/api"'].join( - '' - ) + '', + ), ) // Replace the web and api ports. @@ -190,7 +190,7 @@ function updateRedwoodTOMLTask() { '=', spaceAfterAssign, `"\${PORT:${port}}"`, - ].join('') + ].join(''), ) fs.writeFileSync(redwoodTOMLPath, redwoodTOMLContent) diff --git a/packages/cli/src/commands/setup/deploy/providers/edgio.js b/packages/cli/src/commands/setup/deploy/providers/edgio.js index c7e4038db751..dc59f42dec3c 100644 --- a/packages/cli/src/commands/setup/deploy/providers/edgio.js +++ b/packages/cli/src/commands/setup/deploy/providers/edgio.js @@ -28,7 +28,7 @@ const prismaBinaryTargetAdditions = () => { if (!content.includes('rhel-openssl-1.0.x')) { const result = content.replace( /binaryTargets =.*\n/, - `binaryTargets = ["native", "rhel-openssl-1.0.x"]\n` + `binaryTargets = ["native", "rhel-openssl-1.0.x"]\n`, ) fs.writeFileSync(getPaths().api.dbSchema, result) @@ -63,7 +63,7 @@ export const handler = async () => { }, printSetupNotes(notes), ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { await tasks.run() diff --git a/packages/cli/src/commands/setup/deploy/providers/flightcontrol.js b/packages/cli/src/commands/setup/deploy/providers/flightcontrol.js index 17bd304dc766..a8038725031a 100644 --- a/packages/cli/src/commands/setup/deploy/providers/flightcontrol.js +++ b/packages/cli/src/commands/setup/deploy/providers/flightcontrol.js @@ -35,7 +35,7 @@ export const getFlightcontrolJson = async (database) => { } const schema = await getSchema( - path.join(getPaths().base, 'api/db/schema.prisma') + path.join(getPaths().base, 'api/db/schema.prisma'), ) const config = await getConfig({ datamodel: schema }) const detectedDatabase = config.datasources[0].activeProvider @@ -96,11 +96,11 @@ const updateGraphQLFunction = () => { task: (_ctx) => { const graphqlTsPath = path.join( getPaths().base, - 'api/src/functions/graphql.ts' + 'api/src/functions/graphql.ts', ) const graphqlJsPath = path.join( getPaths().base, - 'api/src/functions/graphql.js' + 'api/src/functions/graphql.js', ) let graphqlFunctionsPath @@ -122,7 +122,7 @@ const updateGraphQLFunction = () => { .readFileSync(graphqlFunctionsPath, 'utf8') .split(EOL) const graphqlHanderIndex = graphqlContent.findIndex((line) => - line.includes('createGraphQLHandler({') + line.includes('createGraphQLHandler({'), ) if (graphqlHanderIndex === -1) { @@ -138,7 +138,7 @@ const updateGraphQLFunction = () => { graphqlContent.splice( graphqlHanderIndex + 1, 0, - ' cors: { origin: process.env.REDWOOD_WEB_URL, credentials: true },' + ' cors: { origin: process.env.REDWOOD_WEB_URL, credentials: true },', ) fs.writeFileSync(graphqlFunctionsPath, graphqlContent.join(EOL)) @@ -165,7 +165,7 @@ const updateDbAuth = () => { const authContent = fs.readFileSync(authFnPath, 'utf8').split(EOL) const sameSiteLineIndex = authContent.findIndex((line) => - line.match(/SameSite:.*,/) + line.match(/SameSite:.*,/), ) if (sameSiteLineIndex === -1) { console.log(` @@ -175,12 +175,11 @@ const updateDbAuth = () => { `) return } - authContent[ - sameSiteLineIndex - ] = ` SameSite: process.env.NODE_ENV === 'development' ? 'Strict' : 'None',` + authContent[sameSiteLineIndex] = + ` SameSite: process.env.NODE_ENV === 'development' ? 'Strict' : 'None',` const dbHandlerIndex = authContent.findIndex((line) => - line.includes('new DbAuthHandler(') + line.includes('new DbAuthHandler('), ) if (dbHandlerIndex === -1) { console.log(` @@ -194,7 +193,7 @@ const updateDbAuth = () => { authContent.splice( dbHandlerIndex + 1, 0, - ' cors: { origin: process.env.REDWOOD_WEB_URL, credentials: true },' + ' cors: { origin: process.env.REDWOOD_WEB_URL, credentials: true },', ) fs.writeFileSync(authFnPath, authContent.join(EOL)) @@ -223,7 +222,7 @@ const updateApp = () => { const appContent = fs.readFileSync(appPath, 'utf8').split(EOL) const authLineIndex = appContent.findIndex((line) => - line.includes(' { `) // This is CORS config for cookies, which is currently only dbAuth Currently only dbAuth uses cookies and would require this config } else if (appContent.toString().match(/dbAuth/)) { - appContent[ - authLineIndex - ] = ` + appContent[authLineIndex] = + ` ` } const gqlLineIndex = appContent.findIndex((line) => - line.includes(' { `) // This is CORS config for cookies, which is currently only dbAuth Currently only dbAuth uses cookies and would require this config } else if (appContent.toString().match(/dbAuth/)) { - appContent[ - gqlLineIndex - ] = ` + appContent[gqlLineIndex] = + ` ` } @@ -328,7 +325,7 @@ export const handler = async ({ force, database }) => { addToDotEnvDefaultTask(), printSetupNotes(notes), ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/setup/deploy/providers/netlify.js b/packages/cli/src/commands/setup/deploy/providers/netlify.js index 929fdc7e44e9..bce82c1853c8 100644 --- a/packages/cli/src/commands/setup/deploy/providers/netlify.js +++ b/packages/cli/src/commands/setup/deploy/providers/netlify.js @@ -37,7 +37,7 @@ export const handler = async ({ force }) => { addFilesTask({ files, force }), printSetupNotes(notes), ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { await tasks.run() diff --git a/packages/cli/src/commands/setup/deploy/providers/render.js b/packages/cli/src/commands/setup/deploy/providers/render.js index e54fac390183..3b6dbccd3277 100644 --- a/packages/cli/src/commands/setup/deploy/providers/render.js +++ b/packages/cli/src/commands/setup/deploy/providers/render.js @@ -114,7 +114,7 @@ export const handler = async ({ force, database }) => { }), printSetupNotes(notes), ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/setup/deploy/providers/serverless.js b/packages/cli/src/commands/setup/deploy/providers/serverless.js index 825a4d75ea54..f46a8d10d03e 100644 --- a/packages/cli/src/commands/setup/deploy/providers/serverless.js +++ b/packages/cli/src/commands/setup/deploy/providers/serverless.js @@ -71,7 +71,7 @@ const prismaBinaryTargetAdditions = () => { if (!content.includes('rhel-openssl-1.0.x')) { const result = content.replace( /binaryTargets =.*\n/, - `binaryTargets = ["native", "rhel-openssl-1.0.x"]\n` + `binaryTargets = ["native", "rhel-openssl-1.0.x"]\n`, ) fs.writeFileSync(getPaths().api.dbSchema, result) @@ -88,7 +88,7 @@ const updateRedwoodTomlTask = () => { const newContent = content.replace( /apiUrl.*?\n/m, - 'apiUrl = "${API_URL:/api}" # Set API_URL in production to the Serverless deploy endpoint of your api service, see https://redwoodjs.com/docs/deploy/serverless-deploy\n' + 'apiUrl = "${API_URL:/api}" # Set API_URL in production to the Serverless deploy endpoint of your api service, see https://redwoodjs.com/docs/deploy/serverless-deploy\n', ) fs.writeFileSync(configPath, newContent) }, @@ -141,7 +141,7 @@ export const handler = async ({ force }) => { { exitOnError: true, rendererOptions: { collapseSubtasks: false }, - } + }, ) try { await tasks.run() diff --git a/packages/cli/src/commands/setup/generator/generator.js b/packages/cli/src/commands/setup/generator/generator.js index 0d97b5ea0503..1f2d31476eac 100644 --- a/packages/cli/src/commands/setup/generator/generator.js +++ b/packages/cli/src/commands/setup/generator/generator.js @@ -33,7 +33,7 @@ export const builder = (yargs) => { .positional('name', { description: 'Name of the generator to copy templates from', choices: availableGenerators.filter( - (dir) => !EXCLUDE_GENERATORS.includes(dir) + (dir) => !EXCLUDE_GENERATORS.includes(dir), ), }) .option('force', { @@ -45,8 +45,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#setup-generator' - )}` + 'https://redwoodjs.com/docs/cli-commands#setup-generator', + )}`, ) } diff --git a/packages/cli/src/commands/setup/generator/generatorHandler.js b/packages/cli/src/commands/setup/generator/generatorHandler.js index 79b17554ca2a..2accad34b9da 100644 --- a/packages/cli/src/commands/setup/generator/generatorHandler.js +++ b/packages/cli/src/commands/setup/generator/generatorHandler.js @@ -38,12 +38,12 @@ const tasks = ({ name, force }) => { task: (ctx, task) => { task.title = ` Wrote templates to ${destination.replace( getPaths().base, - '' + '', )}` }, }, ], - { rendererOptions: { collapseSubtasks: false }, errorOnExist: true } + { rendererOptions: { collapseSubtasks: false }, errorOnExist: true }, ) } diff --git a/packages/cli/src/commands/setup/graphql/features/fragments/__codemod_tests__/appGqlConfigTransform.test.ts b/packages/cli/src/commands/setup/graphql/features/fragments/__codemod_tests__/appGqlConfigTransform.test.ts index 0c2e81deb83f..d64bfe438b55 100644 --- a/packages/cli/src/commands/setup/graphql/features/fragments/__codemod_tests__/appGqlConfigTransform.test.ts +++ b/packages/cli/src/commands/setup/graphql/features/fragments/__codemod_tests__/appGqlConfigTransform.test.ts @@ -24,7 +24,7 @@ describe('fragments graphQLClientConfig', () => { 'existingPropVariable', { useJsCodeshift: true, - } + }, ) }) @@ -34,7 +34,7 @@ describe('fragments graphQLClientConfig', () => { 'existingPropVariableNoCacheConfig', { useJsCodeshift: true, - } + }, ) }) @@ -44,7 +44,7 @@ describe('fragments graphQLClientConfig', () => { 'existingPropVariableCustomName', { useJsCodeshift: true, - } + }, ) }) @@ -57,9 +57,9 @@ describe('fragments graphQLClientConfig', () => { 'test-project', 'web', 'src', - 'App.tsx' + 'App.tsx', ), - 'utf-8' + 'utf-8', ) await matchInlineTransformSnapshot( 'appGqlConfigTransform', @@ -97,7 +97,7 @@ describe('fragments graphQLClientConfig', () => { ); export default App; - ` + `, ) }) }) diff --git a/packages/cli/src/commands/setup/graphql/features/fragments/__tests__/fragmentsHandler.test.ts b/packages/cli/src/commands/setup/graphql/features/fragments/__tests__/fragmentsHandler.test.ts index 1055456fcdbc..413b95f277b7 100644 --- a/packages/cli/src/commands/setup/graphql/features/fragments/__tests__/fragmentsHandler.test.ts +++ b/packages/cli/src/commands/setup/graphql/features/fragments/__tests__/fragmentsHandler.test.ts @@ -96,7 +96,7 @@ test('redwood.toml update is skipped if fragments are already enabled', async () 'redwood.toml': '[graphql]\nfragments = true', 'web/src/App.tsx': '', }, - FIXTURE_PATH + FIXTURE_PATH, ) await handler({ force: false }) @@ -145,7 +145,7 @@ test('redwood.toml is updated even if `fragments = true` exists for other sectio await handler({ force: false }) expect(vol.toJSON()[FIXTURE_PATH + '/redwood.toml']).toEqual( - toml + '\n[graphql]\n fragments = true' + toml + '\n[graphql]\n fragments = true', ) }) @@ -205,6 +205,6 @@ test('[graphql] is last section in redwood.toml', async () => { await handler({ force: false }) expect(vol.toJSON()[FIXTURE_PATH + '/redwood.toml']).toEqual( - toml + '\n fragments = true' + toml + '\n fragments = true', ) }) diff --git a/packages/cli/src/commands/setup/graphql/features/fragments/appGqlConfigTransform.ts b/packages/cli/src/commands/setup/graphql/features/fragments/appGqlConfigTransform.ts index 10ae99afc799..8cdc34711c6e 100644 --- a/packages/cli/src/commands/setup/graphql/features/fragments/appGqlConfigTransform.ts +++ b/packages/cli/src/commands/setup/graphql/features/fragments/appGqlConfigTransform.ts @@ -43,7 +43,7 @@ export default function transform(file: FileInfo, api: API) { j.JSXAttribute, { name: { name: 'graphQLClientConfig' }, - } + }, ) let graphQLClientConfig: ReturnType @@ -53,7 +53,7 @@ export default function transform(file: FileInfo, api: API) { // Creating `graphQLClientConfig={{}}` graphQLClientConfig = j.jsxAttribute( j.jsxIdentifier('graphQLClientConfig'), - j.jsxExpressionContainer(j.objectExpression([])) + j.jsxExpressionContainer(j.objectExpression([])), ) } else { graphQLClientConfig = graphQLClientConfigCollection.get(0).node @@ -68,7 +68,7 @@ export default function transform(file: FileInfo, api: API) { // graphQLClientConfig={graphQLClientConfig} const graphQLClientConfigExpression = isJsxExpressionContainer( - graphQLClientConfig.value + graphQLClientConfig.value, ) ? graphQLClientConfig.value.expression : j.jsxEmptyExpression() @@ -90,7 +90,7 @@ export default function transform(file: FileInfo, api: API) { "Error configuring possibleTypes. You'll have to do it manually. " + "(Could not find a graphQLClientConfigExpression of the correct type, it's a " + graphQLClientConfigExpression.type + - ')' + ')', ) } @@ -119,9 +119,9 @@ export default function transform(file: FileInfo, api: API) { j.variableDeclaration('const', [ j.variableDeclarator( j.identifier(graphQLClientConfigVariableName), - graphQLClientConfigExpression + graphQLClientConfigExpression, ), - ]) + ]), ) } @@ -129,7 +129,7 @@ export default function transform(file: FileInfo, api: API) { // one we just created above, or the one the user already had, with the name // we found in the `graphQLClientConfig prop expression. const configVariableDeclarators = root.findVariableDeclarators( - graphQLClientConfigVariableName + graphQLClientConfigVariableName, ) const configExpression = configVariableDeclarators.get(0)?.node.init @@ -137,7 +137,7 @@ export default function transform(file: FileInfo, api: API) { if (!isObjectExpression(configExpression)) { throw new Error( "Error configuring possibleTypes. You'll have to do it manually. " + - '(Could not find a graphQLClientConfig variable ObjectExpression)' + '(Could not find a graphQLClientConfig variable ObjectExpression)', ) } @@ -145,14 +145,14 @@ export default function transform(file: FileInfo, api: API) { // an object. Let's see if the object has a `cacheConfig` property. let cacheConfig = configExpression.properties.find((prop) => - isPropertyWithName(prop, 'cacheConfig') + isPropertyWithName(prop, 'cacheConfig'), ) if (!cacheConfig) { // No `cacheConfig` property. Let's insert one! cacheConfig = j.objectProperty( j.identifier('cacheConfig'), - j.objectExpression([]) + j.objectExpression([]), ) configExpression.properties.push(cacheConfig) } @@ -160,7 +160,7 @@ export default function transform(file: FileInfo, api: API) { if (!isObjectProperty(cacheConfig)) { throw new Error( "Error configuring possibleTypes. You'll have to do it manually. " + - '(cacheConfig is not an ObjectProperty)' + '(cacheConfig is not an ObjectProperty)', ) } @@ -169,7 +169,7 @@ export default function transform(file: FileInfo, api: API) { if (!isObjectExpression(cacheConfigValue)) { throw new Error( "Error configuring possibleTypes. You'll have to do it manually. " + - '(cacheConfigValue is not an ObjectExpression)' + '(cacheConfigValue is not an ObjectExpression)', ) } @@ -178,14 +178,14 @@ export default function transform(file: FileInfo, api: API) { // If it doesn't we'll insert one, with the correct value const possibleTypes = cacheConfigValue.properties.find((prop) => - isPropertyWithName(prop, 'possibleTypes') + isPropertyWithName(prop, 'possibleTypes'), ) if (!possibleTypes) { const property = j.property( 'init', j.identifier('possibleTypes'), - j.identifier('possibleTypes.possibleTypes') + j.identifier('possibleTypes.possibleTypes'), ) // property.shorthand = true cacheConfigValue.properties.push(property) @@ -203,8 +203,8 @@ export default function transform(file: FileInfo, api: API) { .node.openingElement.attributes.push( j.jsxAttribute( j.jsxIdentifier('graphQLClientConfig'), - j.jsxExpressionContainer(j.identifier(graphQLClientConfigVariableName)) - ) + j.jsxExpressionContainer(j.identifier(graphQLClientConfigVariableName)), + ), ) return root.toSource() diff --git a/packages/cli/src/commands/setup/graphql/features/fragments/appImportTransform.ts b/packages/cli/src/commands/setup/graphql/features/fragments/appImportTransform.ts index 8cec36fc41de..1e506a39853f 100644 --- a/packages/cli/src/commands/setup/graphql/features/fragments/appImportTransform.ts +++ b/packages/cli/src/commands/setup/graphql/features/fragments/appImportTransform.ts @@ -19,8 +19,8 @@ export default function transform(file: FileInfo, api: API) { .insertAfter( j.importDeclaration( [j.importDefaultSpecifier(j.identifier('possibleTypes'))], - j.literal('src/graphql/possibleTypes') - ) + j.literal('src/graphql/possibleTypes'), + ), ) } diff --git a/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts b/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts index fc7ec0b03670..57e9652f6980 100644 --- a/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts +++ b/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts @@ -82,7 +82,7 @@ export async function handler({ force }: Args) { }, }, ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts index cb74dae3eeee..c1182342f560 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts @@ -56,37 +56,37 @@ beforeAll(async () => { tomlFixtures.default = actualFs.readFileSync( path.join(tomlFixturesPath, 'default.toml'), - 'utf-8' + 'utf-8', ) tomlFixtures.fragments = actualFs.readFileSync( path.join(tomlFixturesPath, 'fragments.toml'), - 'utf-8' + 'utf-8', ) tomlFixtures.fragmentsNoSpaceEquals = actualFs.readFileSync( path.join(tomlFixturesPath, 'fragments_no_space_equals.toml'), - 'utf-8' + 'utf-8', ) tomlFixtures.trustedDocsAlreadySetup = actualFs.readFileSync( path.join(tomlFixturesPath, 'trusted_docs_already_setup.toml'), - 'utf-8' + 'utf-8', ) tomlFixtures.trustedDocsNoSpaceEquals = actualFs.readFileSync( path.join(tomlFixturesPath, 'trusted_docs_no_space_equals.toml'), - 'utf-8' + 'utf-8', ) tomlFixtures.trustedDocsFragmentsAlreadySetup = actualFs.readFileSync( path.join(tomlFixturesPath, 'trusted_docs_fragments_already_setup.toml'), - 'utf-8' + 'utf-8', ) tomlFixtures.trustedDocsCommentedGraphql = actualFs.readFileSync( path.join(tomlFixturesPath, 'trusted_docs_commented_graphql.toml'), - 'utf-8' + 'utf-8', ) }) @@ -103,7 +103,7 @@ describe('Trusted documents setup', () => { it('runs all tasks', async () => { vol.fromJSON( { 'redwood.toml': '', 'api/src/functions/graphql.js': '' }, - APP_PATH + APP_PATH, ) await handler({ force: false }) @@ -125,7 +125,7 @@ describe('Trusted documents setup', () => { 'redwood.toml': tomlFixtures.default, 'api/src/functions/graphql.js': '', }, - APP_PATH + APP_PATH, ) await handler({ force: false }) @@ -140,7 +140,7 @@ describe('Trusted documents setup', () => { 'redwood.toml': tomlFixtures.fragments, 'api/src/functions/graphql.ts': '', }, - APP_PATH + APP_PATH, ) await handler({ force: false }) @@ -155,7 +155,7 @@ describe('Trusted documents setup', () => { 'redwood.toml': tomlFixtures.fragmentsNoSpaceEquals, 'api/src/functions/graphql.js': '', }, - APP_PATH + APP_PATH, ) await handler({ force: false }) @@ -170,13 +170,13 @@ describe('Trusted documents setup', () => { 'redwood.toml': tomlFixtures.trustedDocsAlreadySetup, 'api/src/functions/graphql.js': '', }, - APP_PATH + APP_PATH, ) await handler({ force: false }) expect(vol.toJSON()[APP_PATH + '/redwood.toml']).toEqual( - tomlFixtures.trustedDocsAlreadySetup + tomlFixtures.trustedDocsAlreadySetup, ) }) }) @@ -187,13 +187,13 @@ describe('Trusted documents setup', () => { 'redwood.toml': tomlFixtures.trustedDocsNoSpaceEquals, 'api/src/functions/graphql.js': '', }, - APP_PATH + APP_PATH, ) await handler({ force: false }) expect(vol.toJSON()[APP_PATH + '/redwood.toml']).toEqual( - tomlFixtures.trustedDocsNoSpaceEquals + tomlFixtures.trustedDocsNoSpaceEquals, ) }) }) @@ -204,13 +204,13 @@ describe('Trusted documents setup', () => { 'redwood.toml': tomlFixtures.trustedDocsFragmentsAlreadySetup, 'api/src/functions/graphql.js': '', }, - APP_PATH + APP_PATH, ) await handler({ force: false }) expect(vol.toJSON()[APP_PATH + '/redwood.toml']).toEqual( - tomlFixtures.trustedDocsFragmentsAlreadySetup + tomlFixtures.trustedDocsFragmentsAlreadySetup, ) }) }) @@ -221,7 +221,7 @@ describe('Trusted documents setup', () => { 'redwood.toml': tomlFixtures.trustedDocsCommentedGraphql, 'api/src/functions/graphql.js': '', }, - APP_PATH + APP_PATH, ) await handler({ force: false }) diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts index 7a3e636d75fb..568b0d2974f4 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts @@ -16,8 +16,8 @@ export default function transform(file: FileInfo, api: API) { .insertAfter( j.importDeclaration( [j.importSpecifier(j.identifier('store'))], - j.literal('src/lib/trustedDocumentsStore') - ) + j.literal('src/lib/trustedDocumentsStore'), + ), ) } @@ -30,7 +30,7 @@ export default function transform(file: FileInfo, api: API) { if (createGraphQLHandlerCalls.length === 0) { throw new Error( "Error updating your graphql handler function. You'll have to do it manually. " + - "(Couldn't find a call to `createGraphQLHandler`)" + "(Couldn't find a call to `createGraphQLHandler`)", ) } @@ -40,13 +40,13 @@ export default function transform(file: FileInfo, api: API) { key: { name: 'trustedDocuments', }, - } + }, ) if (existingTrustedDocumentsProperty.length === 0) { const storeProperty = j.objectProperty( j.identifier('store'), - j.identifier('store') + j.identifier('store'), ) storeProperty.shorthand = true @@ -55,8 +55,8 @@ export default function transform(file: FileInfo, api: API) { .node.arguments[0].properties.push( j.objectProperty( j.identifier('trustedDocuments'), - j.objectExpression([storeProperty]) - ) + j.objectExpression([storeProperty]), + ), ) } diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts index c9c185469630..b9a7616ac865 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts @@ -44,7 +44,7 @@ export async function handler({ force }: { force: boolean }) { 'Configuring the GraphQL Handler to use a Trusted Documents store ...', task: async () => { const graphqlPath = resolveFile( - path.join(getPaths().api.functions, 'graphql') + path.join(getPaths().api.functions, 'graphql'), ) if (!graphqlPath) { @@ -73,7 +73,7 @@ export async function handler({ force }: { force: boolean }) { }, }, ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/setup/graphql/graphql.ts b/packages/cli/src/commands/setup/graphql/graphql.ts index 2a4c810bd703..ec17578b4d0e 100644 --- a/packages/cli/src/commands/setup/graphql/graphql.ts +++ b/packages/cli/src/commands/setup/graphql/graphql.ts @@ -13,7 +13,7 @@ export function builder(yargs: Argv) { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#setup-graphql' - )}` + 'https://redwoodjs.com/docs/cli-commands#setup-graphql', + )}`, ) } diff --git a/packages/cli/src/commands/setup/i18n/i18nHandler.js b/packages/cli/src/commands/setup/i18n/i18nHandler.js index 0f87b015d16a..737ff65d5963 100644 --- a/packages/cli/src/commands/setup/i18n/i18nHandler.js +++ b/packages/cli/src/commands/setup/i18n/i18nHandler.js @@ -63,7 +63,7 @@ export const handler = async ({ force }) => { }, }, ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) }, }, @@ -78,17 +78,17 @@ export const handler = async ({ force }) => { */ if (!force && i18nConfigExists()) { throw new Error( - 'i18n config already exists.\nUse --force to override existing config.' + 'i18n config already exists.\nUse --force to override existing config.', ) } else { return writeFile( path.join(getPaths().web.src, 'i18n.js'), fs .readFileSync( - path.resolve(__dirname, 'templates', 'i18n.js.template') + path.resolve(__dirname, 'templates', 'i18n.js.template'), ) .toString(), - { overwriteExisting: force } + { overwriteExisting: force }, ) } }, @@ -106,17 +106,17 @@ export const handler = async ({ force }) => { if (!force && localesExists('fr')) { throw new Error( - 'fr.json config already exists.\nUse --force to override existing config.' + 'fr.json config already exists.\nUse --force to override existing config.', ) } else { return writeFile( path.join(getPaths().web.src, '/locales/fr.json'), fs .readFileSync( - path.resolve(__dirname, 'templates', 'fr.json.template') + path.resolve(__dirname, 'templates', 'fr.json.template'), ) .toString(), - { overwriteExisting: force } + { overwriteExisting: force }, ) } }, @@ -133,17 +133,17 @@ export const handler = async ({ force }) => { */ if (!force && localesExists('en')) { throw new Error( - 'en.json already exists.\nUse --force to override existing config.' + 'en.json already exists.\nUse --force to override existing config.', ) } else { return writeFile( path.join(getPaths().web.src, '/locales/en.json'), fs .readFileSync( - path.resolve(__dirname, 'templates', 'en.json.template') + path.resolve(__dirname, 'templates', 'en.json.template'), ) .toString(), - { overwriteExisting: force } + { overwriteExisting: force }, ) } }, @@ -171,7 +171,7 @@ export const handler = async ({ force }) => { skip: () => fileIncludes(rwPaths.web.storybookConfig, 'withI18n'), task: async () => extendStorybookConfiguration( - path.join(__dirname, 'templates', 'storybook.preview.tsx.template') + path.join(__dirname, 'templates', 'storybook.preview.tsx.template'), ), }, { @@ -180,13 +180,13 @@ export const handler = async ({ force }) => { task.title = `One more thing...\n ${c.green('Quick link to the docs:')}\n ${chalk.hex('#e8e8e8')( - 'https://react.i18next.com/guides/quick-start/' + 'https://react.i18next.com/guides/quick-start/', )} ` }, }, ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/setup/mailer/mailerHandler.js b/packages/cli/src/commands/setup/mailer/mailerHandler.js index 7d8fcb556dc9..65be94a68922 100644 --- a/packages/cli/src/commands/setup/mailer/mailerHandler.js +++ b/packages/cli/src/commands/setup/mailer/mailerHandler.js @@ -27,7 +27,7 @@ export const handler = async ({ force, skipExamples }) => { const templatePath = path.resolve( __dirname, 'templates', - 'mailer.ts.template' + 'mailer.ts.template', ) const templateContent = fs.readFileSync(templatePath, { encoding: 'utf8', @@ -36,7 +36,7 @@ export const handler = async ({ force, skipExamples }) => { const mailerPath = path.join( getPaths().api.lib, - `mailer.${projectIsTypescript ? 'ts' : 'js'}` + `mailer.${projectIsTypescript ? 'ts' : 'js'}`, ) const mailerContent = projectIsTypescript ? templateContent @@ -63,7 +63,7 @@ export const handler = async ({ force, skipExamples }) => { const templatePath = path.resolve( __dirname, 'templates', - 're-example.tsx.template' + 're-example.tsx.template', ) const templateContent = fs.readFileSync(templatePath, { encoding: 'utf8', @@ -73,7 +73,7 @@ export const handler = async ({ force, skipExamples }) => { const exampleTemplatePath = path.join( getPaths().api.mail, 'Example', - `Example.${projectIsTypescript ? 'tsx' : 'jsx'}` + `Example.${projectIsTypescript ? 'tsx' : 'jsx'}`, ) const exampleTemplateContent = projectIsTypescript ? templateContent @@ -106,7 +106,7 @@ export const handler = async ({ force, skipExamples }) => { ], { rendererOptions: { collapseSubtasks: false }, - } + }, ) try { diff --git a/packages/cli/src/commands/setup/monitoring/monitoring.ts b/packages/cli/src/commands/setup/monitoring/monitoring.ts index 56d875ab50c2..bc4fc2cb388a 100644 --- a/packages/cli/src/commands/setup/monitoring/monitoring.ts +++ b/packages/cli/src/commands/setup/monitoring/monitoring.ts @@ -11,7 +11,7 @@ export function builder(yargs: Argv) { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#setup-graphql' - )}` + 'https://redwoodjs.com/docs/cli-commands#setup-graphql', + )}`, ) } diff --git a/packages/cli/src/commands/setup/monitoring/sentry/sentryHandler.ts b/packages/cli/src/commands/setup/monitoring/sentry/sentryHandler.ts index f0db2436f939..f36e62c4cb1f 100644 --- a/packages/cli/src/commands/setup/monitoring/sentry/sentryHandler.ts +++ b/packages/cli/src/commands/setup/monitoring/sentry/sentryHandler.ts @@ -30,7 +30,7 @@ export const handler = async ({ force }: Args) => { addEnvVarTask( 'SENTRY_DSN', '', - 'https://docs.sentry.io/product/sentry-basics/dsn-explainer/' + 'https://docs.sentry.io/product/sentry-basics/dsn-explainer/', ), { title: 'Setting up Sentry on the API and web sides', @@ -39,16 +39,16 @@ export const handler = async ({ force }: Args) => { { [path.join(rwPaths.api.lib, `sentry.${extension}`)]: fs .readFileSync( - path.join(__dirname, 'templates/sentryApi.ts.template') + path.join(__dirname, 'templates/sentryApi.ts.template'), ) .toString(), [path.join(rwPaths.web.src, 'lib', `sentry.${extension}`)]: fs .readFileSync( - path.join(__dirname, 'templates/sentryWeb.ts.template') + path.join(__dirname, 'templates/sentryWeb.ts.template'), ) .toString(), }, - { existingFiles: force ? 'OVERWRITE' : 'SKIP' } + { existingFiles: force ? 'OVERWRITE' : 'SKIP' }, ) }, }, @@ -57,7 +57,7 @@ export const handler = async ({ force }: Args) => { task: async (ctx) => { const graphqlHandlerPath = path.join( rwPaths.api.functions, - `graphql.${extension}` + `graphql.${extension}`, ) const contentLines = fs @@ -66,11 +66,11 @@ export const handler = async ({ force }: Args) => { .split('\n') const handlerIndex = contentLines.findLastIndex((line) => - /^export const handler = createGraphQLHandler\({/.test(line) + /^export const handler = createGraphQLHandler\({/.test(line), ) const pluginsIndex = contentLines.findLastIndex((line) => - /extraPlugins:/.test(line) + /extraPlugins:/.test(line), ) if (handlerIndex === -1 || pluginsIndex !== -1) { @@ -88,14 +88,14 @@ export const handler = async ({ force }: Args) => { ' includeRawResult: true,', ' includeResolverArgs: true,', ' includeExecuteVariables: true,', - '})],' + '})],', ) contentLines.splice(0, 0, "import { useSentry } from '@envelop/sentry'") fs.writeFileSync( graphqlHandlerPath, - await prettify('graphql.ts', contentLines.join('\n')) + await prettify('graphql.ts', contentLines.join('\n')), ) }, }, @@ -109,26 +109,26 @@ export const handler = async ({ force }: Args) => { const webImportIndex = contentLines.findLastIndex((line) => /^import { FatalErrorBoundary, RedwoodProvider } from '@redwoodjs\/web'$/.test( - line - ) + line, + ), ) contentLines.splice( webImportIndex, 1, - "import { RedwoodProvider } from '@redwoodjs/web'" + "import { RedwoodProvider } from '@redwoodjs/web'", ) const boundaryOpenIndex = contentLines.findLastIndex((line) => - //.test(line) + //.test(line), ) contentLines.splice( boundaryOpenIndex, 1, - '' + '', ) const boundaryCloseIndex = contentLines.findLastIndex((line) => - /<\/FatalErrorBoundary>/.test(line) + /<\/FatalErrorBoundary>/.test(line), ) contentLines.splice(boundaryCloseIndex, 1, '') @@ -136,7 +136,7 @@ export const handler = async ({ force }: Args) => { fs.writeFileSync( rwPaths.web.app, - await prettify('App.tsx', contentLines.join('\n')) + await prettify('App.tsx', contentLines.join('\n')), ) }, }, @@ -145,19 +145,19 @@ export const handler = async ({ force }: Args) => { task: (ctx) => { notes.push( colors.green( - 'You will need to add `SENTRY_DSN` to `includeEnvironmentVariables` in redwood.toml.' - ) + 'You will need to add `SENTRY_DSN` to `includeEnvironmentVariables` in redwood.toml.', + ), ) if (ctx.addEnvelopPluginSkipped) { notes.push( `${colors.underline( - 'Make sure you implement the Sentry Envelop plugin:' - )} https://redwoodjs.com/docs/cli-commands#sentry-envelop-plugin` + 'Make sure you implement the Sentry Envelop plugin:', + )} https://redwoodjs.com/docs/cli-commands#sentry-envelop-plugin`, ) } else { notes.push( - 'Check out the RedwoodJS forums for more: https://community.redwoodjs.com/t/sentry-error-and-performance-monitoring-experimental/4880' + 'Check out the RedwoodJS forums for more: https://community.redwoodjs.com/t/sentry-error-and-performance-monitoring-experimental/4880', ) } }, diff --git a/packages/cli/src/commands/setup/package/__tests__/packageHandler.test.js b/packages/cli/src/commands/setup/package/__tests__/packageHandler.test.js index 7112f736f6ba..4448536aa1e0 100644 --- a/packages/cli/src/commands/setup/package/__tests__/packageHandler.test.js +++ b/packages/cli/src/commands/setup/package/__tests__/packageHandler.test.js @@ -75,7 +75,7 @@ describe('packageHandler', () => { }) expect(console.log).toHaveBeenCalledWith( - 'No compatibility check will be performed because you used the --force flag.' + 'No compatibility check will be performed because you used the --force flag.', ) expect(getCompatibilityData).not.toHaveBeenCalled() }) @@ -92,7 +92,7 @@ describe('packageHandler', () => { _: ['setup', 'package'], }) expect(console.log).not.toHaveBeenCalledWith( - 'Be aware that this package is under version 1.0.0 and so should be considered experimental.' + 'Be aware that this package is under version 1.0.0 and so should be considered experimental.', ) await handler({ @@ -101,7 +101,7 @@ describe('packageHandler', () => { _: ['setup', 'package'], }) expect(console.log).toHaveBeenCalledWith( - 'Be aware that this package is under version 1.0.0 and so should be considered experimental.' + 'Be aware that this package is under version 1.0.0 and so should be considered experimental.', ) }) @@ -193,7 +193,7 @@ describe('packageHandler', () => { expect(getCompatibilityData).toHaveBeenNthCalledWith( 1, 'some-package', - 'latest' + 'latest', ) expect(enq.Select).toHaveBeenCalledTimes(1) expect(execa).toHaveBeenNthCalledWith( @@ -203,7 +203,7 @@ describe('packageHandler', () => { { stdio: 'inherit', cwd: path.join('mocked', 'project'), - } + }, ) enq.Select.mockImplementation(() => { @@ -219,7 +219,7 @@ describe('packageHandler', () => { expect(getCompatibilityData).toHaveBeenNthCalledWith( 2, 'some-package', - 'latest' + 'latest', ) expect(enq.Select).toHaveBeenCalledTimes(2) expect(execa).toHaveBeenNthCalledWith( @@ -229,7 +229,7 @@ describe('packageHandler', () => { { stdio: 'inherit', cwd: path.join('mocked', 'project'), - } + }, ) enq.Select.mockImplementation(() => { @@ -245,7 +245,7 @@ describe('packageHandler', () => { expect(getCompatibilityData).toHaveBeenNthCalledWith( 3, 'some-package', - 'latest' + 'latest', ) expect(enq.Select).toHaveBeenCalledTimes(3) expect(execa).toBeCalledTimes(2) // Only called for the previous two select options @@ -305,7 +305,7 @@ describe('packageHandler', () => { expect(getCompatibilityData).toHaveBeenNthCalledWith( 1, 'some-package', - 'stable' + 'stable', ) expect(enq.Select).toHaveBeenCalledTimes(1) expect(execa).toHaveBeenNthCalledWith( @@ -315,7 +315,7 @@ describe('packageHandler', () => { { stdio: 'inherit', cwd: path.join('mocked', 'project'), - } + }, ) enq.Select.mockImplementation(() => { @@ -331,7 +331,7 @@ describe('packageHandler', () => { expect(getCompatibilityData).toHaveBeenNthCalledWith( 2, 'some-package', - 'stable' + 'stable', ) expect(enq.Select).toHaveBeenCalledTimes(2) expect(execa).toHaveBeenNthCalledWith( @@ -341,7 +341,7 @@ describe('packageHandler', () => { { stdio: 'inherit', cwd: path.join('mocked', 'project'), - } + }, ) enq.Select.mockImplementation(() => { @@ -357,7 +357,7 @@ describe('packageHandler', () => { expect(getCompatibilityData).toHaveBeenNthCalledWith( 3, 'some-package', - 'stable' + 'stable', ) expect(enq.Select).toHaveBeenCalledTimes(3) expect(execa).toBeCalledTimes(2) // Only called for the previous two select options @@ -416,7 +416,7 @@ describe('packageHandler', () => { expect(getCompatibilityData).toHaveBeenNthCalledWith( 1, 'some-package', - '1.0.0' + '1.0.0', ) expect(enq.Select).toHaveBeenCalledTimes(1) expect(execa).toHaveBeenNthCalledWith( @@ -426,7 +426,7 @@ describe('packageHandler', () => { { stdio: 'inherit', cwd: path.join('mocked', 'project'), - } + }, ) enq.Select.mockImplementation(() => { @@ -442,7 +442,7 @@ describe('packageHandler', () => { expect(getCompatibilityData).toHaveBeenNthCalledWith( 2, 'some-package', - '1.0.0' + '1.0.0', ) expect(enq.Select).toHaveBeenCalledTimes(2) expect(execa).toHaveBeenNthCalledWith( @@ -452,7 +452,7 @@ describe('packageHandler', () => { { stdio: 'inherit', cwd: path.join('mocked', 'project'), - } + }, ) enq.Select.mockImplementation(() => { @@ -468,7 +468,7 @@ describe('packageHandler', () => { expect(getCompatibilityData).toHaveBeenNthCalledWith( 3, 'some-package', - '1.0.0' + '1.0.0', ) expect(enq.Select).toHaveBeenCalledTimes(3) expect(execa).toBeCalledTimes(2) // Only called for the previous two select options @@ -495,7 +495,7 @@ describe('packageHandler', () => { _: ['setup', 'package'], }) expect(console.log).toHaveBeenCalledWith( - 'Be aware that this package is under version 1.0.0 and so should be considered experimental.' + 'Be aware that this package is under version 1.0.0 and so should be considered experimental.', ) // No force should prompt @@ -512,7 +512,7 @@ describe('packageHandler', () => { expect(getCompatibilityData).toHaveBeenNthCalledWith( 1, 'some-package', - '0.0.1' + '0.0.1', ) expect(enq.Select).toHaveBeenCalledTimes(1) expect(execa).toHaveBeenNthCalledWith( @@ -522,7 +522,7 @@ describe('packageHandler', () => { { stdio: 'inherit', cwd: path.join('mocked', 'project'), - } + }, ) }) }) diff --git a/packages/cli/src/commands/setup/package/package.js b/packages/cli/src/commands/setup/package/package.js index 3736a31c41d6..e0818c6373bb 100644 --- a/packages/cli/src/commands/setup/package/package.js +++ b/packages/cli/src/commands/setup/package/package.js @@ -23,8 +23,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#lint' - )}` + 'https://redwoodjs.com/docs/cli-commands#lint', + )}`, ) } diff --git a/packages/cli/src/commands/setup/package/packageHandler.js b/packages/cli/src/commands/setup/package/packageHandler.js index 0b5e032cb9df..6877bca351dd 100644 --- a/packages/cli/src/commands/setup/package/packageHandler.js +++ b/packages/cli/src/commands/setup/package/packageHandler.js @@ -19,14 +19,14 @@ export async function handler({ npmPackage, force, _: _args }) { // If we're using force don't attempt anything fancy, just run the package after some messaging if (force) { console.log( - 'No compatibility check will be performed because you used the --force flag.' + 'No compatibility check will be performed because you used the --force flag.', ) if ( semver.parse(packageVersion) !== null && semver.lt(packageVersion, '1.0.0') ) { console.log( - 'Be aware that this package is under version 1.0.0 and so should be considered experimental.' + 'Be aware that this package is under version 1.0.0 and so should be considered experimental.', ) } await runPackage(packageName, packageVersion, additionalOptionsToForward) @@ -82,7 +82,7 @@ export async function handler({ npmPackage, force, _: _args }) { compatible.tag ? ` (${compatible.tag})` : '' }` console.log( - `The version ${preferredVersionText} of '${packageName}' is not compatible with your RedwoodJS project version.\nThe latest version compatible with your project is ${latestCompatibleVersionText}.` + `The version ${preferredVersionText} of '${packageName}' is not compatible with your RedwoodJS project version.\nThe latest version compatible with your project is ${latestCompatibleVersionText}.`, ) const decision = await promptWithChoices('What would you like to do?', [ @@ -132,7 +132,7 @@ async function showExperimentalWarning(version) { name: 'no', message: 'No', }, - ] + ], ) if (decision === 'no') { process.exit() diff --git a/packages/cli/src/commands/setup/realtime/realtimeHandler.js b/packages/cli/src/commands/setup/realtime/realtimeHandler.js index 606d8dcee429..c6b3a2d67213 100644 --- a/packages/cli/src/commands/setup/realtime/realtimeHandler.js +++ b/packages/cli/src/commands/setup/realtime/realtimeHandler.js @@ -13,7 +13,7 @@ import { isTypeScriptProject, serverFileExists } from '../../../lib/project' import { setupServerFileTasks } from '../server-file/serverFileHandler' const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../../../../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../../../../package.json'), 'utf-8'), ) export async function handler({ force, includeExamples, verbose }) { @@ -22,7 +22,7 @@ export async function handler({ force, includeExamples, verbose }) { const realtimeLibFilePath = path.join( redwoodPaths.api.lib, - `realtime.${isTypeScriptProject() ? 'ts' : 'js'}` + `realtime.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const tasks = new Listr( @@ -33,7 +33,7 @@ export async function handler({ force, includeExamples, verbose }) { task: () => { const serverFileTemplateContent = fs.readFileSync( path.resolve(__dirname, 'templates', 'realtime.ts.template'), - 'utf-8' + 'utf-8', ) const setupScriptContent = ts @@ -57,15 +57,15 @@ export async function handler({ force, includeExamples, verbose }) { 'templates', 'subscriptions', 'countdown', - `countdown.ts.template` + `countdown.ts.template`, ), - 'utf-8' + 'utf-8', ) const exampleFile = path.join( redwoodPaths.api.subscriptions, 'countdown', - `countdown.${isTypeScriptProject() ? 'ts' : 'js'}` + `countdown.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const setupScriptContent = ts @@ -91,14 +91,14 @@ export async function handler({ force, includeExamples, verbose }) { 'templates', 'subscriptions', 'newMessage', - `rooms.sdl.ts.template` + `rooms.sdl.ts.template`, ), - 'utf-8' + 'utf-8', ) const sdlFile = path.join( redwoodPaths.api.graphql, - `rooms.sdl.${isTypeScriptProject() ? 'ts' : 'js'}` + `rooms.sdl.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const sdlContent = ts @@ -113,14 +113,14 @@ export async function handler({ force, includeExamples, verbose }) { 'templates', 'subscriptions', 'newMessage', - `rooms.ts.template` + `rooms.ts.template`, ), - 'utf-8' + 'utf-8', ) const serviceFile = path.join( redwoodPaths.api.services, 'rooms', - `rooms.${isTypeScriptProject() ? 'ts' : 'js'}` + `rooms.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const serviceContent = ts @@ -135,15 +135,15 @@ export async function handler({ force, includeExamples, verbose }) { 'templates', 'subscriptions', 'newMessage', - `newMessage.ts.template` + `newMessage.ts.template`, ), - 'utf-8' + 'utf-8', ) const exampleFile = path.join( redwoodPaths.api.subscriptions, 'newMessage', - `newMessage.${isTypeScriptProject() ? 'ts' : 'js'}` + `newMessage.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const setupScriptContent = ts @@ -176,14 +176,14 @@ export async function handler({ force, includeExamples, verbose }) { 'templates', 'liveQueries', 'auctions', - `auctions.sdl.ts.template` + `auctions.sdl.ts.template`, ), - 'utf-8' + 'utf-8', ) const sdlFile = path.join( redwoodPaths.api.graphql, - `auctions.sdl.${isTypeScriptProject() ? 'ts' : 'js'}` + `auctions.sdl.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const sdlContent = ts @@ -198,14 +198,14 @@ export async function handler({ force, includeExamples, verbose }) { 'templates', 'liveQueries', 'auctions', - `auctions.ts.template` + `auctions.ts.template`, ), - 'utf-8' + 'utf-8', ) const serviceFile = path.join( redwoodPaths.api.services, 'auctions', - `auctions.${isTypeScriptProject() ? 'ts' : 'js'}` + `auctions.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const serviceContent = ts @@ -236,14 +236,14 @@ export async function handler({ force, includeExamples, verbose }) { 'templates', 'defer', 'fastAndSlowFields', - `fastAndSlowFields.sdl.template` + `fastAndSlowFields.sdl.template`, ), - 'utf-8' + 'utf-8', ) const sdlFile = path.join( redwoodPaths.api.graphql, - `fastAndSlowFields.sdl.${isTypeScriptProject() ? 'ts' : 'js'}` + `fastAndSlowFields.sdl.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const sdlContent = ts @@ -258,14 +258,14 @@ export async function handler({ force, includeExamples, verbose }) { 'templates', 'defer', 'fastAndSlowFields', - `fastAndSlowFields.ts.template` + `fastAndSlowFields.ts.template`, ), - 'utf-8' + 'utf-8', ) const serviceFile = path.join( redwoodPaths.api.services, 'fastAndSlowFields', - `fastAndSlowFields.${isTypeScriptProject() ? 'ts' : 'js'}` + `fastAndSlowFields.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const serviceContent = ts @@ -296,14 +296,14 @@ export async function handler({ force, includeExamples, verbose }) { 'templates', 'stream', 'alphabet', - `alphabet.sdl.template` + `alphabet.sdl.template`, ), - 'utf-8' + 'utf-8', ) const sdlFile = path.join( redwoodPaths.api.graphql, - `alphabet.sdl.${isTypeScriptProject() ? 'ts' : 'js'}` + `alphabet.sdl.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const sdlContent = ts @@ -318,14 +318,14 @@ export async function handler({ force, includeExamples, verbose }) { 'templates', 'stream', 'alphabet', - `alphabet.ts.template` + `alphabet.ts.template`, ), - 'utf-8' + 'utf-8', ) const serviceFile = path.join( redwoodPaths.api.services, 'alphabet', - `alphabet.${isTypeScriptProject() ? 'ts' : 'js'}` + `alphabet.${isTypeScriptProject() ? 'ts' : 'js'}`, ) const serviceContent = ts @@ -348,7 +348,7 @@ export async function handler({ force, includeExamples, verbose }) { task: async () => { await generateTypes() console.log( - 'Note: You may need to manually restart GraphQL in VSCode to see the new types take effect.\n\n' + 'Note: You may need to manually restart GraphQL in VSCode to see the new types take effect.\n\n', ) }, }, @@ -356,7 +356,7 @@ export async function handler({ force, includeExamples, verbose }) { { rendererOptions: { collapseSubtasks: false, persistentOutput: true }, renderer: verbose ? 'verbose' : 'default', - } + }, ) try { diff --git a/packages/cli/src/commands/setup/server-file/serverFileHandler.js b/packages/cli/src/commands/setup/server-file/serverFileHandler.js index 6fb68e544ca6..726659054fc2 100644 --- a/packages/cli/src/commands/setup/server-file/serverFileHandler.js +++ b/packages/cli/src/commands/setup/server-file/serverFileHandler.js @@ -11,7 +11,7 @@ import c from '../../../lib/colors' import { isTypeScriptProject } from '../../../lib/project' const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../../../../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../../../../package.json'), 'utf-8'), ) export function setupServerFileTasks({ force = false } = {}) { @@ -23,12 +23,12 @@ export function setupServerFileTasks({ force = false } = {}) { const serverFilePath = path.join( getPaths().api.src, - `server.${ts ? 'ts' : 'js'}` + `server.${ts ? 'ts' : 'js'}`, ) const serverFileTemplateContent = fs.readFileSync( path.join(__dirname, 'templates', 'server.ts.template'), - 'utf-8' + 'utf-8', ) const setupScriptContent = ts diff --git a/packages/cli/src/commands/setup/tsconfig/tsconfigHandler.js b/packages/cli/src/commands/setup/tsconfig/tsconfigHandler.js index 12be8b901f0f..29ec2c5b4f29 100644 --- a/packages/cli/src/commands/setup/tsconfig/tsconfigHandler.js +++ b/packages/cli/src/commands/setup/tsconfig/tsconfigHandler.js @@ -56,7 +56,7 @@ export const handler = async ({ force }) => { }, }, ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/setup/ui/libraries/chakra-ui.js b/packages/cli/src/commands/setup/ui/libraries/chakra-ui.js index b34ea1a3fb57..6420834a7831 100644 --- a/packages/cli/src/commands/setup/ui/libraries/chakra-ui.js +++ b/packages/cli/src/commands/setup/ui/libraries/chakra-ui.js @@ -66,7 +66,7 @@ export async function handler({ force, install }) { }, }, ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) }, }, @@ -94,7 +94,7 @@ export async function handler({ force, install }) { writeFile( path.join(rwPaths.web.config, 'chakra.config.js'), CHAKRA_THEME_AND_COMMENTS, - { overwriteExisting: force } + { overwriteExisting: force }, ) }, }, @@ -108,12 +108,12 @@ export async function handler({ force, install }) { __dirname, '..', 'templates', - 'chakra.storybook.preview.tsx.template' - ) + 'chakra.storybook.preview.tsx.template', + ), ), }, ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/setup/ui/libraries/mantine.js b/packages/cli/src/commands/setup/ui/libraries/mantine.js index c77466d9bd66..1badad92ee4f 100644 --- a/packages/cli/src/commands/setup/ui/libraries/mantine.js +++ b/packages/cli/src/commands/setup/ui/libraries/mantine.js @@ -101,7 +101,7 @@ export async function handler({ force, install, packages }) { }, }, ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) }, }, @@ -133,15 +133,15 @@ export async function handler({ force, install, packages }) { if (!force && fse.existsSync(postCSSConfigPath)) { throw new Error( - 'PostCSS config already exists.\nUse --force to override existing config.' + 'PostCSS config already exists.\nUse --force to override existing config.', ) } else { const postCSSConfig = fse.readFileSync( path.join( __dirname, - '../templates/mantine-postcss.config.js.template' + '../templates/mantine-postcss.config.js.template', ), - 'utf-8' + 'utf-8', ) return fse.outputFileSync(postCSSConfigPath, postCSSConfig) @@ -166,12 +166,12 @@ export async function handler({ force, install, packages }) { __dirname, '..', 'templates', - 'mantine.storybook.preview.tsx.template' - ) + 'mantine.storybook.preview.tsx.template', + ), ), }, ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/setup/ui/ui.js b/packages/cli/src/commands/setup/ui/ui.js index b98a629d0233..320aaa5919e2 100644 --- a/packages/cli/src/commands/setup/ui/ui.js +++ b/packages/cli/src/commands/setup/ui/ui.js @@ -9,6 +9,6 @@ export const builder = (yargs) => .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#setup-ui' - )}` + 'https://redwoodjs.com/docs/cli-commands#setup-ui', + )}`, ) diff --git a/packages/cli/src/commands/setup/vite/viteHandler.js b/packages/cli/src/commands/setup/vite/viteHandler.js index 81c1f27637fa..a3a3ffbe6b09 100644 --- a/packages/cli/src/commands/setup/vite/viteHandler.js +++ b/packages/cli/src/commands/setup/vite/viteHandler.js @@ -12,7 +12,7 @@ import c from '../../../lib/colors' import { isTypeScriptProject } from '../../../lib/project' const { version } = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../../../../package.json'), 'utf-8') + fs.readFileSync(path.resolve(__dirname, '../../../../package.json'), 'utf-8'), ) export const handler = async ({ force, verbose, addPackage }) => { @@ -30,7 +30,7 @@ export const handler = async ({ force, verbose, addPackage }) => { const templateContent = fs.readFileSync( path.resolve(__dirname, 'templates', 'vite.config.ts.template'), - 'utf-8' + 'utf-8', ) const viteConfigContent = ts @@ -50,7 +50,7 @@ export const handler = async ({ force, verbose, addPackage }) => { if (configContent.includes('bundler = "webpack"')) { throw new Error( - 'You have the bundler set to webpack in your redwood.toml. Remove this line, or change it to "vite" and try again.' + 'You have the bundler set to webpack in your redwood.toml. Remove this line, or change it to "vite" and try again.', ) } else { task.skip('Vite already configured as the bundler') @@ -63,7 +63,7 @@ export const handler = async ({ force, verbose, addPackage }) => { task: () => { const entryPointFile = path.join( getPaths().web.src, - `entry.client.${ts ? 'tsx' : 'jsx'}` + `entry.client.${ts ? 'tsx' : 'jsx'}`, ) const content = fs @@ -71,9 +71,9 @@ export const handler = async ({ force, verbose, addPackage }) => { path.join( getPaths().base, // NOTE we're copying over the index.js before babel transform - 'node_modules/@redwoodjs/web/src/entry/index.js' + 'node_modules/@redwoodjs/web/src/entry/index.js', ), - 'utf-8' + 'utf-8', ) .replace('~redwood-app-root', './App') @@ -96,7 +96,7 @@ export const handler = async ({ force, verbose, addPackage }) => { { rendererOptions: { collapseSubtasks: false }, renderer: verbose ? 'verbose' : 'default', - } + }, ) try { diff --git a/packages/cli/src/commands/setup/webpack/webpackHandler.js b/packages/cli/src/commands/setup/webpack/webpackHandler.js index 50d146c7ad6f..85d8e09e5c0e 100644 --- a/packages/cli/src/commands/setup/webpack/webpackHandler.js +++ b/packages/cli/src/commands/setup/webpack/webpackHandler.js @@ -24,11 +24,11 @@ export const handler = async ({ force }) => { path.resolve( __dirname, 'templates', - 'webpack.config.js.template' - ) + 'webpack.config.js.template', + ), ) .toString(), - { overwriteExisting: force } + { overwriteExisting: force }, ) }, }, @@ -37,16 +37,16 @@ export const handler = async ({ force }) => { task: (_ctx, task) => { task.title = `One more thing...\n ${c.green( - 'Quick link to the docs on configuring custom webpack config:' + 'Quick link to the docs on configuring custom webpack config:', )} ${chalk.hex('#e8e8e8')( - 'https://redwoodjs.com/docs/webpack-configuration#configuring-webpack' + 'https://redwoodjs.com/docs/webpack-configuration#configuring-webpack', )} ` }, }, ], - { rendererOptions: { collapseSubtasks: false } } + { rendererOptions: { collapseSubtasks: false } }, ) try { diff --git a/packages/cli/src/commands/studioHandler.js b/packages/cli/src/commands/studioHandler.js index a947ce1e3eb2..9f8eef730377 100644 --- a/packages/cli/src/commands/studioHandler.js +++ b/packages/cli/src/commands/studioHandler.js @@ -15,7 +15,7 @@ export const handler = async (options) => { assertRedwoodVersion(minVersions) console.log( - 'The studio package is not installed, installing it for you, this may take a moment...' + 'The studio package is not installed, installing it for you, this may take a moment...', ) await installModule('@redwoodjs/studio', '11') console.log('Studio package installed successfully.') @@ -23,14 +23,14 @@ export const handler = async (options) => { const installedRealtime = await installModule('@redwoodjs/realtime') if (installedRealtime) { console.log( - "Added @redwoodjs/realtime to your project, as it's used by Studio" + "Added @redwoodjs/realtime to your project, as it's used by Studio", ) } const installedApiServer = await installModule('@redwoodjs/api-server') if (installedApiServer) { console.log( - "Added @redwoodjs/api-server to your project, as it's used by Studio" + "Added @redwoodjs/api-server to your project, as it's used by Studio", ) } } @@ -79,7 +79,7 @@ export function assertRedwoodVersion(minVersions) { console.error( `The studio command requires Redwood version ${minVersions[0]} or ` + - `greater, you are using ${rwVersion}.` + `greater, you are using ${rwVersion}.`, ) process.exit(1) @@ -87,7 +87,7 @@ export function assertRedwoodVersion(minVersions) { function getProjectRedwoodVersion() { const { devDependencies } = fs.readJSONSync( - path.join(getPaths().base, 'package.json') + path.join(getPaths().base, 'package.json'), ) return devDependencies['@redwoodjs/core'] diff --git a/packages/cli/src/commands/test.js b/packages/cli/src/commands/test.js index 6ddd87895bee..c7efba2ea862 100644 --- a/packages/cli/src/commands/test.js +++ b/packages/cli/src/commands/test.js @@ -34,11 +34,11 @@ export const builder = (yargs) => { }) .epilogue( `For all available flags, run jest cli directly ${c.green( - 'yarn jest --help' + 'yarn jest --help', )}\n\nAlso see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#test' - )}\n` + 'https://redwoodjs.com/docs/cli-commands#test', + )}\n`, ) } diff --git a/packages/cli/src/commands/testHandler.js b/packages/cli/src/commands/testHandler.js index 64088af120be..3c2803507017 100644 --- a/packages/cli/src/commands/testHandler.js +++ b/packages/cli/src/commands/testHandler.js @@ -42,8 +42,8 @@ function isJestConfigFile(sides) { console.error( c.error( `\nError: Missing Jest config file ${side}/jest.config.js` + - '\nTo add this file, run `npx @redwoodjs/codemods update-jest-config`\n' - ) + '\nTo add this file, run `npx @redwoodjs/codemods update-jest-config`\n', + ), ) throw new Error(`Error: Jest config file not found in ${side} side`) } @@ -96,13 +96,13 @@ export const handler = async ({ // Only the side params const sides = filterParams.filter((filterString) => - project.sides().includes(filterString) + project.sides().includes(filterString), ) // All the other params, apart from sides const jestFilterArgs = [ ...filterParams.filter( - (filterString) => !project.sides().includes(filterString) + (filterString) => !project.sides().includes(filterString), ), ] @@ -134,7 +134,7 @@ export const handler = async ({ try { const cacheDirDb = `file:${ensurePosixPath( - rwjsPaths.generated.base + rwjsPaths.generated.base, )}/test.db` const DATABASE_URL = process.env.TEST_DATABASE_URL || cacheDirDb diff --git a/packages/cli/src/commands/type-check.js b/packages/cli/src/commands/type-check.js index 4efec3af8bd9..dacd85efb054 100644 --- a/packages/cli/src/commands/type-check.js +++ b/packages/cli/src/commands/type-check.js @@ -32,8 +32,8 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#type-check' - )}` + 'https://redwoodjs.com/docs/cli-commands#type-check', + )}`, ) } diff --git a/packages/cli/src/commands/type-checkHandler.js b/packages/cli/src/commands/type-checkHandler.js index 32d9ba285755..27ba4b2b7593 100644 --- a/packages/cli/src/commands/type-checkHandler.js +++ b/packages/cli/src/commands/type-checkHandler.js @@ -78,7 +78,7 @@ export const handler = async ({ sides, verbose, prisma, generate }) => { { renderer: verbose && 'verbose', rendererOptions: { collapseSubtasks: false }, - } + }, ).run() } diff --git a/packages/cli/src/commands/upgrade.js b/packages/cli/src/commands/upgrade.js index aebe934bbbcf..dbc0827d9d18 100644 --- a/packages/cli/src/commands/upgrade.js +++ b/packages/cli/src/commands/upgrade.js @@ -20,7 +20,7 @@ export const builder = (yargs) => { yargs .example( 'rw upgrade -t 0.20.1-canary.5', - 'Specify a version. URL for Version History:\nhttps://www.npmjs.com/package/@redwoodjs/core' + 'Specify a version. URL for Version History:\nhttps://www.npmjs.com/package/@redwoodjs/core', ) .option('dry-run', { alias: 'd', @@ -49,11 +49,11 @@ export const builder = (yargs) => { .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference for the upgrade command', - 'https://redwoodjs.com/docs/cli-commands#upgrade' + 'https://redwoodjs.com/docs/cli-commands#upgrade', )}.\nAnd the ${terminalLink( 'GitHub releases page', - 'https://github.com/redwoodjs/redwood/releases' - )} for more information on the current release.` + 'https://github.com/redwoodjs/redwood/releases', + )} for more information on the current release.`, ) } @@ -76,8 +76,8 @@ export const validateTag = (tag) => { // Stop execution throw new Error( c.error( - "Invalid tag supplied. Supported values: 'rc', 'canary', 'latest', 'next', 'experimental', or a valid semver version\n" - ) + "Invalid tag supplied. Supported values: 'rc', 'canary', 'latest', 'next', 'experimental', or a valid semver version\n", + ), ) } @@ -132,7 +132,7 @@ export const handler = async ({ dryRun, tag, verbose, dedupe }) => { const version = ctx.versionToUpgradeTo const messageSections = [ `One more thing...\n\n ${c.warning( - `🎉 Your project has been upgraded to RedwoodJS ${version}!` + `🎉 Your project has been upgraded to RedwoodJS ${version}!`, )} \n\n`, ] // Show links when switching to 'latest' or 'rc', undefined is essentially an alias of 'latest' @@ -140,11 +140,11 @@ export const handler = async ({ dryRun, tag, verbose, dedupe }) => { messageSections.push( ` Please review the release notes for any manual steps: \n ❖ ${terminalLink( `Redwood community discussion`, - `https://community.redwoodjs.com/search?q=${version}%23announcements` + `https://community.redwoodjs.com/search?q=${version}%23announcements`, )}\n ❖ ${terminalLink( `GitHub Release notes`, - `https://github.com/redwoodjs/redwood/releases` // intentionally not linking to specific version - )} \n\n` + `https://github.com/redwoodjs/redwood/releases`, // intentionally not linking to specific version + )} \n\n`, ) } // @MARK @@ -157,14 +157,14 @@ export const handler = async ({ dryRun, tag, verbose, dedupe }) => { isValidRedwoodJSTag(tag) ) { additionalMessages.push( - ` ❖ You may want to update your redwood.toml config so that \`notifications.versionUpdates\` includes "${tag}"\n` + ` ❖ You may want to update your redwood.toml config so that \`notifications.versionUpdates\` includes "${tag}"\n`, ) } // Append additional messages with a header if (additionalMessages.length > 0) { messageSections.push( ` 📢 ${c.warning(`We'd also like to remind you that:`)} \n`, - ...additionalMessages + ...additionalMessages, ) } } @@ -175,7 +175,7 @@ export const handler = async ({ dryRun, tag, verbose, dedupe }) => { { renderer: verbose && 'verbose', rendererOptions: { collapseSubtasks: false }, - } + }, ) await tasks.run() @@ -192,11 +192,11 @@ async function yarnInstall({ verbose }) { stdio: verbose ? 'inherit' : 'pipe', cwd: getPaths().base, - } + }, ) } catch (e) { throw new Error( - 'Could not finish installation. Please run `yarn install` and then `yarn dedupe`, before continuing' + 'Could not finish installation. Please run `yarn install` and then `yarn dedupe`, before continuing', ) } } @@ -205,7 +205,7 @@ async function setLatestVersionToContext(ctx, tag) { try { const foundVersion = await latestVersion( '@redwoodjs/core', - tag ? { version: tag } : {} + tag ? { version: tag } : {}, ) ctx.versionToUpgradeTo = foundVersion @@ -220,12 +220,12 @@ async function setLatestVersionToContext(ctx, tag) { */ function updatePackageJsonVersion(pkgPath, version, { dryRun, verbose }) { const pkg = JSON.parse( - fs.readFileSync(path.join(pkgPath, 'package.json'), 'utf-8') + fs.readFileSync(path.join(pkgPath, 'package.json'), 'utf-8'), ) if (pkg.dependencies) { for (const depName of Object.keys(pkg.dependencies).filter( - (x) => x.startsWith('@redwoodjs/') && x !== '@redwoodjs/studio' + (x) => x.startsWith('@redwoodjs/') && x !== '@redwoodjs/studio', )) { if (verbose || dryRun) { console.log(` - ${depName}: ${pkg.dependencies[depName]} => ${version}`) @@ -235,11 +235,11 @@ function updatePackageJsonVersion(pkgPath, version, { dryRun, verbose }) { } if (pkg.devDependencies) { for (const depName of Object.keys(pkg.devDependencies).filter( - (x) => x.startsWith('@redwoodjs/') && x !== '@redwoodjs/studio' + (x) => x.startsWith('@redwoodjs/') && x !== '@redwoodjs/studio', )) { if (verbose || dryRun) { console.log( - ` - ${depName}: ${pkg.devDependencies[depName]} => ${version}` + ` - ${depName}: ${pkg.devDependencies[depName]} => ${version}`, ) } pkg.devDependencies[depName] = `${version}` @@ -249,7 +249,7 @@ function updatePackageJsonVersion(pkgPath, version, { dryRun, verbose }) { if (!dryRun) { fs.writeFileSync( path.join(pkgPath, 'package.json'), - JSON.stringify(pkg, undefined, 2) + JSON.stringify(pkg, undefined, 2), ) } } @@ -274,7 +274,7 @@ function updateRedwoodDepsForAllSides(ctx, options) { updatePackageJsonVersion(basePath, ctx.versionToUpgradeTo, options), skip: () => !fs.existsSync(pkgJsonPath), } - }) + }), ) } @@ -318,13 +318,13 @@ async function updatePackageVersionsFromTemplate(ctx, { dryRun, verbose }) { if (!depName.startsWith('@redwoodjs/')) { if (verbose || dryRun) { console.log( - ` - ${depName}: ${localPackageJson.dependencies[depName]} => ${depVersion}` + ` - ${depName}: ${localPackageJson.dependencies[depName]} => ${depVersion}`, ) } localPackageJson.dependencies[depName] = depVersion } - } + }, ) Object.entries(templatePackageJson.devDependencies || {}).forEach( @@ -333,25 +333,25 @@ async function updatePackageVersionsFromTemplate(ctx, { dryRun, verbose }) { if (!depName.startsWith('@redwoodjs/')) { if (verbose || dryRun) { console.log( - ` - ${depName}: ${localPackageJson.devDependencies[depName]} => ${depVersion}` + ` - ${depName}: ${localPackageJson.devDependencies[depName]} => ${depVersion}`, ) } localPackageJson.devDependencies[depName] = depVersion } - } + }, ) if (!dryRun) { fs.writeFileSync( pkgJsonPath, - JSON.stringify(localPackageJson, null, 2) + JSON.stringify(localPackageJson, null, 2), ) } }, skip: () => !fs.existsSync(pkgJsonPath), } - }) + }), ) } @@ -366,7 +366,7 @@ async function refreshPrismaClient(task, { verbose }) { } catch (e) { task.skip('Refreshing the Prisma client caused an Error.') console.log( - 'You may need to update your prisma client manually: $ yarn rw prisma generate' + 'You may need to update your prisma client manually: $ yarn rw prisma generate', ) console.log(c.error(e.message)) } @@ -407,13 +407,13 @@ const dedupeDeps = async (task, { verbose }) => { await execa( 'npx', [...npxArgs, 'yarn-deduplicate'], - baseExecaArgsForDedupe + baseExecaArgsForDedupe, ) } } catch (e) { console.log(c.error(e.message)) throw new Error( - 'Could not finish de-duplication. For yarn 1.x, please run `npx yarn-deduplicate`, or for yarn 3 run `yarn dedupe` before continuing' + 'Could not finish de-duplication. For yarn 1.x, please run `npx yarn-deduplicate`, or for yarn 3 run `yarn dedupe` before continuing', ) } await yarnInstall({ verbose }) diff --git a/packages/cli/src/index.js b/packages/cli/src/index.js index 425af6548bf0..c57e899f4c3d 100644 --- a/packages/cli/src/index.js +++ b/packages/cli/src/index.js @@ -88,7 +88,7 @@ try { if (!redwoodTOMLPath) { throw new Error( - `Couldn't find up a "redwood.toml" file from ${process.cwd()}` + `Couldn't find up a "redwood.toml" file from ${process.cwd()}`, ) } @@ -171,7 +171,7 @@ async function runYargs() { }, telemetry && telemetryMiddleware, updateCheck.isEnabled() && updateCheck.updateCheckMiddleware, - ].filter(Boolean) + ].filter(Boolean), ) .option('cwd', { describe: 'Working directory to use (where `redwood.toml` is located)', @@ -183,7 +183,7 @@ async function runYargs() { }) .example( 'yarn rw exec migrateUsers --load-env-files stripe nakama', - "Run a script, also loading env vars from '.env.stripe' and '.env.nakama'" + "Run a script, also loading env vars from '.env.stripe' and '.env.nakama'", ) .option('telemetry', { describe: 'Whether to send anonymous usage telemetry to RedwoodJS', @@ -192,7 +192,7 @@ async function runYargs() { }) .example( 'yarn rw g page home /', - "Create a page component named 'Home' at path '/'" + "Create a page component named 'Home' at path '/'", ) .demandCommand() .strict() diff --git a/packages/cli/src/lib/__tests__/index.test.js b/packages/cli/src/lib/__tests__/index.test.js index 049bb4b92f8e..4543783143a2 100644 --- a/packages/cli/src/lib/__tests__/index.test.js +++ b/packages/cli/src/lib/__tests__/index.test.js @@ -65,7 +65,7 @@ test('generateTemplate returns a lodash-templated string', async () => { { name: 'amet', noun: 'world', - } + }, ) expect(output).toEqual(`Lorem ipsum dolar sit amet\nHello, world!\n`) @@ -79,11 +79,11 @@ test('generateTemplate returns prettified JS code', async () => { { name: 'fox', foo: 'dog', - } + }, ) expect(output).toEqual( - `const line1 = 'The quick brown foxes jumps over the lazy dog.'\nconst line2 = 'Sphinx of black quartz, judge my vow.'\n` + `const line1 = 'The quick brown foxes jumps over the lazy dog.'\nconst line2 = 'Sphinx of black quartz, judge my vow.'\n`, ) }) diff --git a/packages/cli/src/lib/__tests__/mergeBasics.test.js b/packages/cli/src/lib/__tests__/mergeBasics.test.js index 121e76cc7955..ad9f6db4dad6 100644 --- a/packages/cli/src/lib/__tests__/mergeBasics.test.js +++ b/packages/cli/src/lib/__tests__/mergeBasics.test.js @@ -7,7 +7,7 @@ import { unindented } from './fixtures/unindented' const expectMerged = async (base, ext, merged, strategy = {}) => { expect(await merge(unindented(base), unindented(ext), strategy)).toBe( - unindented(merged) + unindented(merged), ) } @@ -34,7 +34,7 @@ describe('the basics', () => { const y = 'y' const list = [x, y] `, - { ArrayExpression: concatUnique } + { ArrayExpression: concatUnique }, ) }) it('Merges JSX strings', async () => { @@ -64,7 +64,7 @@ describe('the basics', () => { const y: string = 'y' const list: string[] = [x, y] `, - { ArrayExpression: concatUnique } + { ArrayExpression: concatUnique }, ) }) }) @@ -73,63 +73,63 @@ describe('Import behavior', () => { it('keeps both identical namespace imports', async () => { await expectTrivialConcat( "import * as React from 'react'", - "import * as React from 'react'" + "import * as React from 'react'", ) }) it('keeps both identical specifier imports', async () => { await expectTrivialConcat( "import { foo } from 'source'", - "import { foo } from 'source'" + "import { foo } from 'source'", ) }) it('keeps both differing import specifiers in separate imports', async () => { await expectTrivialConcat( "import { bar } from 'source'", - "import { foo } from 'source'" + "import { foo } from 'source'", ) }) it('keeps both differing sets of import specifiers, even with an overlap.', async () => { await expectTrivialConcat( "import { foo, bar } from 'source'", - "import { bar, baz } from 'source'" + "import { bar, baz } from 'source'", ) }) it('keeps both default and specifier imports', async () => { await expectTrivialConcat( "import def from 'source'", - "import { foo } from 'source'" + "import { foo } from 'source'", ) }) it('keeps both default + specifier and specifier imports', async () => { await expectTrivialConcat( "import def, { foo } from 'source'", - "import { bar } from 'source'" + "import { bar } from 'source'", ) }) it('keeps both specifier and default imports', async () => { await expectTrivialConcat( "import { foo } from 'source'", - "import def from 'source'" + "import def from 'source'", ) }) it('does not merge import namespace identifiers with conflicting local names', async () => { await expectTrivialConcat( "import * as One from 'source'", - "import * as Two from 'source'" + "import * as Two from 'source'", ) }) it('does not merge default specifiers with conflicting local names', async () => { await expectTrivialConcat( "import One from 'source'", - "import Two from 'source'" + "import Two from 'source'", ) }) @@ -140,49 +140,49 @@ describe('Import behavior', () => { it('does not merge side-effect imports and namespace imports', async () => { await expectTrivialConcat( "import 'source'", - "import * as Name from 'source'" + "import * as Name from 'source'", ) }) it('does not merge side-effect imports import specifiers', async () => { await expectTrivialConcat( "import 'source'", - "import { foo, bar } from 'source'" + "import { foo, bar } from 'source'", ) }) it('Does not merge side-effect imports with other import types', async () => { await expectTrivialConcat( "import def, { foo, bar } from 'source'", - "import 'source'" + "import 'source'", ) }) it('keeps both import default specifiers and import namespace identifiers', async () => { await expectTrivialConcat( "import src from 'source'", - "import * as Source from 'source'" + "import * as Source from 'source'", ) }) it('keeps all imports with the same source', async () => { await expectTrivialConcat( "import { foo } from 'source'", - "import { bar } from 'source'\nimport { baz } from 'source'" + "import { bar } from 'source'\nimport { baz } from 'source'", ) }) it('keeps multiple default imports with the same source', async () => { await expectTrivialConcat( "import default1 from 'source'", - "import default2 from 'source'\nimport { foo } from 'source'" + "import default2 from 'source'\nimport { foo } from 'source'", ) }) it('keeps multiple types of imports with the same source', async () => { await expectTrivialConcat( "import default1 from 'source'\nimport * as namespace from 'source'", - "import default2 from 'source'\nimport { foo } from 'source'" + "import default2 from 'source'\nimport { foo } from 'source'", ) }) }) diff --git a/packages/cli/src/lib/__tests__/mergeConfig.test.js b/packages/cli/src/lib/__tests__/mergeConfig.test.js index 1781251e2d3a..cee0f1c09202 100644 --- a/packages/cli/src/lib/__tests__/mergeConfig.test.js +++ b/packages/cli/src/lib/__tests__/mergeConfig.test.js @@ -27,7 +27,7 @@ function mergeConfig(base, ext) { const expectMerged = async (base, ext, merged) => { expect(await mergeConfig(unindented(base), unindented(ext))).toBe( - unindented(merged) + unindented(merged), ) } @@ -36,7 +36,7 @@ describe('Import behavior', () => { await expectMerged( "import * as React from 'react'", "import * as React from 'react'", - "import * as React from 'react'\n" + "import * as React from 'react'\n", ) }) @@ -44,7 +44,7 @@ describe('Import behavior', () => { await expectMerged( "import { foo } from 'source'", "import { foo } from 'source'", - "import { foo } from 'source'\n" + "import { foo } from 'source'\n", ) }) @@ -52,7 +52,7 @@ describe('Import behavior', () => { await expectMerged( "import { bar } from 'source'", "import { foo } from 'source'", - "import { bar, foo } from 'source'\n" + "import { bar, foo } from 'source'\n", ) }) @@ -60,7 +60,7 @@ describe('Import behavior', () => { await expectMerged( "import { foo, bar } from 'source'", "import { bar, baz } from 'source'", - "import { foo, bar, baz } from 'source'\n" + "import { foo, bar, baz } from 'source'\n", ) }) @@ -68,7 +68,7 @@ describe('Import behavior', () => { await expectMerged( "import def from 'source'", "import { foo } from 'source'", - "import def, { foo } from 'source'\n" + "import def, { foo } from 'source'\n", ) }) @@ -76,7 +76,7 @@ describe('Import behavior', () => { await expectMerged( "import def, { foo } from 'source'", "import { bar } from 'source'", - "import def, { foo, bar } from 'source'\n" + "import def, { foo, bar } from 'source'\n", ) }) @@ -84,7 +84,7 @@ describe('Import behavior', () => { await expectMerged( "import { foo } from 'source'", "import def from 'source'", - "import def, { foo } from 'source'\n" + "import def, { foo } from 'source'\n", ) }) @@ -92,7 +92,7 @@ describe('Import behavior', () => { await expectMerged( "import * as One from 'source'", "import * as Two from 'source'", - "import * as One from 'source'\nimport * as Two from 'source'\n" + "import * as One from 'source'\nimport * as Two from 'source'\n", ) }) @@ -100,7 +100,7 @@ describe('Import behavior', () => { await expectMerged( "import One from 'source'", "import Two from 'source'", - "import One from 'source'\nimport Two from 'source'\n" + "import One from 'source'\nimport Two from 'source'\n", ) }) @@ -111,7 +111,7 @@ describe('Import behavior', () => { `\ import 'source' import Def from 'source' - ` + `, ) }) @@ -122,7 +122,7 @@ describe('Import behavior', () => { `\ import 'source' import * as Name from 'source' - ` + `, ) }) @@ -133,7 +133,7 @@ describe('Import behavior', () => { `\ import 'source' import { foo, bar } from 'source' - ` + `, ) }) @@ -144,7 +144,7 @@ describe('Import behavior', () => { `\ import def, { foo, bar } from 'source' import 'source' - ` + `, ) }) @@ -152,7 +152,7 @@ describe('Import behavior', () => { await expectMerged( "import src from 'source'", "import * as Source from 'source'", - "import src, * as Source from 'source'\n" + "import src, * as Source from 'source'\n", ) }) @@ -160,7 +160,7 @@ describe('Import behavior', () => { await expectMerged( "import * as Source from 'source'", "import src from 'source'", - "import src, * as Source from 'source'\n" + "import src, * as Source from 'source'\n", ) }) @@ -171,7 +171,7 @@ describe('Import behavior', () => { import { bar } from 'source' import { baz } from 'source' `, - "import { foo, bar, baz } from 'source'\n" + "import { foo, bar, baz } from 'source'\n", ) }) @@ -185,7 +185,7 @@ describe('Import behavior', () => { `\ import default1, { foo } from 'source' import default2 from 'source' - ` + `, ) }) @@ -203,7 +203,7 @@ describe('Import behavior', () => { import default1, { foo } from 'source' import default2 from 'source' import * as namespace from 'source' - ` + `, ) }) }) @@ -218,7 +218,7 @@ describe('Object behavior', () => { foo: 'foo', bar: 'bar', } - ` + `, ) }) @@ -232,7 +232,7 @@ describe('Object behavior', () => { bar: 'bar', baz: 'baz', } - ` + `, ) }) @@ -247,7 +247,7 @@ describe('Object behavior', () => { bird: 'bird', }, } - ` + `, ) }) @@ -262,7 +262,7 @@ describe('Object behavior', () => { bird: 'bird', }, } - ` + `, ) }) @@ -276,7 +276,7 @@ describe('Object behavior', () => { arr: [1, 2, 3, 4, 5], }, } - ` + `, ) }) it('merges deeply nested objects', async () => { @@ -293,7 +293,7 @@ describe('Object behavior', () => { }, }, } - ` + `, ) }) }) @@ -303,7 +303,7 @@ describe('Array behavior', () => { await expectMerged( 'const x = [1, 2, 3]', 'const x = [4, 5, 6]', - 'const x = [1, 2, 3, 4, 5, 6]\n' + 'const x = [1, 2, 3, 4, 5, 6]\n', ) }) @@ -314,7 +314,7 @@ describe('Array behavior', () => { `\ const x = [1, 2, 3] const y = [4, 5, 6] - ` + `, ) }) @@ -322,7 +322,7 @@ describe('Array behavior', () => { await expectMerged( 'const x = [1, 2, 3]', 'const x = [3, 4, 5]', - 'const x = [1, 2, 3, 4, 5]\n' + 'const x = [1, 2, 3, 4, 5]\n', ) }) @@ -335,7 +335,7 @@ describe('Array behavior', () => { const x = { foo: 'foo', } - ` + `, ) }) @@ -344,7 +344,7 @@ describe('Array behavior', () => { "const x = [1, 2, 3, ['a', 'b', 'c']]", "const x = [1, 5, ['c', 'd', 'e']]", // We might also want [1, 2, 3, 5, ['a', 'b', 'c', 'd', 'e']], but that seems tricky to implement. - "const x = [1, 2, 3, ['a', 'b', 'c', 'd', 'e'], 5]\n" + "const x = [1, 2, 3, ['a', 'b', 'c', 'd', 'e'], 5]\n", ) }) }) @@ -357,7 +357,7 @@ describe('opaque function behavior', () => { `\ const x = (a) => ['a', 'b', 'c'].contains(a) const x = (a) => ['d', 'e', 'f'].contains(a) - ` + `, ) }) @@ -384,7 +384,7 @@ describe('opaque function behavior', () => { const array = ['a', 'b', 'c'] return array.contains(a) } - ` + `, ) }) }) @@ -394,7 +394,7 @@ describe('nop behavior', () => { await expectMerged( 'const x = "foo"', 'const x = "bar"', - "const x = 'foo'\nconst x = 'bar'\n" + "const x = 'foo'\nconst x = 'bar'\n", ) }) @@ -408,7 +408,7 @@ describe('nop behavior', () => { bar: 'baz', }, } - ` + `, ) }) @@ -419,7 +419,7 @@ describe('nop behavior', () => { `\ const x = (x, y) => x + y const x = (x, y) => x - y - ` + `, ) }) @@ -427,7 +427,7 @@ describe('nop behavior', () => { await expectMerged( 'export const x = [1, 2, 3]', 'const x = [3, 4, 5]', - 'export const x = [1, 2, 3]\nconst x = [3, 4, 5]\n' + 'export const x = [1, 2, 3]\nconst x = [3, 4, 5]\n', ) }) }) @@ -446,7 +446,7 @@ describe('Comment behavior', () => { `\ // This is a test const x = [1, 2, 3, 4, 5, 6] - ` + `, ) }) @@ -463,7 +463,7 @@ describe('Comment behavior', () => { `\ // This is a test const x = [1, 2, 3, 4, 5, 6] - ` + `, ) }) @@ -483,7 +483,7 @@ describe('Comment behavior', () => { import { foo, bar } from 'source' // This is a test const x = [1, 2, 3, 4, 5, 6] - ` + `, ) }) }) @@ -498,7 +498,7 @@ describe('Integration tests', () => { const baseDir = './src/lib/__tests__/fixtures/merge' const tests = fs.readdirSync(baseDir).map((caseDir) => { return ['it.txt', 'base.jsx', 'ext.jsx', 'expected.jsx'].map((file) => - fs.readFileSync(path.join(baseDir, caseDir, file), { encoding: 'utf-8' }) + fs.readFileSync(path.join(baseDir, caseDir, file), { encoding: 'utf-8' }), ) }) test.each(tests)('%s', async (_it, base, ext, expected) => { diff --git a/packages/cli/src/lib/__tests__/mergeSemantics.test.js b/packages/cli/src/lib/__tests__/mergeSemantics.test.js index c9d1de49add9..71576874560c 100644 --- a/packages/cli/src/lib/__tests__/mergeSemantics.test.js +++ b/packages/cli/src/lib/__tests__/mergeSemantics.test.js @@ -66,7 +66,7 @@ describe('Basic behavior', () => { expId( 'ImportDeclaration', (i) => i.node.source.value === 'src', - 'Program.ImportDeclaration.source.src' + 'Program.ImportDeclaration.source.src', ) }) @@ -74,7 +74,7 @@ describe('Basic behavior', () => { expId( 'VariableDeclarator', (e) => e.node.id.name === 'globalTypes', - 'Program.ExportNamedDeclaration.VariableDeclaration.globalTypes' + 'Program.ExportNamedDeclaration.VariableDeclaration.globalTypes', ) }) @@ -82,7 +82,7 @@ describe('Basic behavior', () => { expId( 'ObjectProperty', (p) => p.node.key.name === 'locale', - 'Program.ExportNamedDeclaration.VariableDeclaration.globalTypes.ObjectExpression.locale' + 'Program.ExportNamedDeclaration.VariableDeclaration.globalTypes.ObjectExpression.locale', ) }) @@ -90,7 +90,7 @@ describe('Basic behavior', () => { expId( 'ObjectProperty', (p) => p.node.key.name === 'items', - 'Program.ExportNamedDeclaration.VariableDeclaration.globalTypes.ObjectExpression.locale.ObjectExpression.toolbar.ObjectExpression.items' + 'Program.ExportNamedDeclaration.VariableDeclaration.globalTypes.ObjectExpression.locale.ObjectExpression.toolbar.ObjectExpression.items', ) }) @@ -98,7 +98,7 @@ describe('Basic behavior', () => { expId( 'ArrayExpression', (p) => p.node.elements[0].value === 7, - 'Program.VariableDeclaration.nestedArray.ArrayExpression.ArrayExpression.ArrayExpression' + 'Program.VariableDeclaration.nestedArray.ArrayExpression.ArrayExpression.ArrayExpression', ) }) @@ -106,7 +106,7 @@ describe('Basic behavior', () => { expId( 'ArrowFunctionExpression', (p) => p.parentPath.node.id.name === 'func', - 'Program.VariableDeclaration.func.ArrowFunctionExpression' + 'Program.VariableDeclaration.func.ArrowFunctionExpression', ) }) @@ -114,7 +114,7 @@ describe('Basic behavior', () => { expId( 'VariableDeclarator', (p) => p.node.id.name === 'hello', - 'Program.VariableDeclaration.func.ArrowFunctionExpression.BlockStatement.VariableDeclaration.hello' + 'Program.VariableDeclaration.func.ArrowFunctionExpression.BlockStatement.VariableDeclaration.hello', ) }) @@ -124,7 +124,7 @@ describe('Basic behavior', () => { (p) => p.node.properties[0].key.name === 'value' && p.node.properties[0].value.value === 'en', - 'Program.ExportNamedDeclaration.VariableDeclaration.globalTypes.ObjectExpression.locale.ObjectExpression.toolbar.ObjectExpression.items.ArrayExpression.ObjectExpression' + 'Program.ExportNamedDeclaration.VariableDeclaration.globalTypes.ObjectExpression.locale.ObjectExpression.toolbar.ObjectExpression.items.ArrayExpression.ObjectExpression', ) }) }) diff --git a/packages/cli/src/lib/__tests__/rollback.test.js b/packages/cli/src/lib/__tests__/rollback.test.js index 6a85167adc6c..5e34cfdd0453 100644 --- a/packages/cli/src/lib/__tests__/rollback.test.js +++ b/packages/cli/src/lib/__tests__/rollback.test.js @@ -46,16 +46,16 @@ it('removes empty folders after removing files', async () => { [path.join('fake_dir', 'mock_dir', 'test_dir')]: undefined, }) rollback.addFileToRollback( - path.join('fake_dir', 'mock_dir', 'test_dir', 'fake-file') + path.join('fake_dir', 'mock_dir', 'test_dir', 'fake-file'), ) fs.writeFileSync( path.join('fake_dir', 'mock_dir', 'test_dir', 'fake-file'), - 'fake-content' + 'fake-content', ) await rollback.executeRollback() expect( - fs.existsSync(path.join('fake_dir', 'mock_dir', 'test_dir', 'fake-file')) + fs.existsSync(path.join('fake_dir', 'mock_dir', 'test_dir', 'fake-file')), ).toBe(false) expect(fs.readdirSync('fake_dir')).toStrictEqual([]) }) @@ -187,7 +187,7 @@ it('prepare sets listr2 rollback functions and rollback executes correctly', asy }, }, ], - { silentRendererCondition: true } + { silentRendererCondition: true }, ) rollback.prepareForRollback(tasks) diff --git a/packages/cli/src/lib/background.js b/packages/cli/src/lib/background.js index a48d1c15385b..68335616d328 100644 --- a/packages/cli/src/lib/background.js +++ b/packages/cli/src/lib/background.js @@ -32,13 +32,13 @@ export function spawnBackgroundProcess(name, cmd, args) { const stdout = fs.openSync( path.join(logDirectory, `${safeName}.out.log`), - 'w' + 'w', ) fs.writeSync(stdout, logHeader) const stderr = fs.openSync( path.join(logDirectory, `${safeName}.err.log`), - 'w' + 'w', ) fs.writeSync(stderr, logHeader) diff --git a/packages/cli/src/lib/configureStorybook.js b/packages/cli/src/lib/configureStorybook.js index 3f79e0abb238..3ffde87a175b 100644 --- a/packages/cli/src/lib/configureStorybook.js +++ b/packages/cli/src/lib/configureStorybook.js @@ -19,7 +19,7 @@ import { getPaths, transformTSToJS, writeFile } from '.' * @param {string} newConfigPath - The path to the new configuration file */ export default async function extendStorybookConfiguration( - newConfigPath = undefined + newConfigPath = undefined, ) { const webPaths = getPaths().web const ts = isTypeScriptProject() @@ -31,7 +31,7 @@ export default async function extendStorybookConfiguration( if (!fse.existsSync(sbPreviewConfigPath)) { // If the Storybook preview config file doesn't exist, create it from the template const templateContent = read( - path.resolve(__dirname, 'templates', 'storybook.preview.tsx.template') + path.resolve(__dirname, 'templates', 'storybook.preview.tsx.template'), ) const storybookPreviewContent = ts ? templateContent diff --git a/packages/cli/src/lib/exit.js b/packages/cli/src/lib/exit.js index 1c78cdabf8d9..a20aa2554c27 100644 --- a/packages/cli/src/lib/exit.js +++ b/packages/cli/src/lib/exit.js @@ -11,17 +11,17 @@ const DEFAULT_ERROR_EPILOGUE = [ 'Need help?', ` - Not sure about something or need advice? Reach out on our ${terminalLink( 'Forum', - 'https://community.redwoodjs.com/' + 'https://community.redwoodjs.com/', )}`, ` - Think you've found a bug? Open an issue on our ${terminalLink( 'GitHub', - 'https://github.com/redwoodjs/redwood' + 'https://github.com/redwoodjs/redwood', )}`, ].join('\n') export function exitWithError( error, - { exitCode, message, epilogue, includeEpilogue, includeReferenceCode } = {} + { exitCode, message, epilogue, includeEpilogue, includeReferenceCode } = {}, ) { // Set the default values exitCode ??= error?.exitCode ?? 1 diff --git a/packages/cli/src/lib/extendFile.js b/packages/cli/src/lib/extendFile.js index fd1fec98a0c5..29ba942ead59 100644 --- a/packages/cli/src/lib/extendFile.js +++ b/packages/cli/src/lib/extendFile.js @@ -47,7 +47,7 @@ export function extendJSXFile( }, imports = [], moduleScopeLines = [], - } + }, ) { const content = fs.readFileSync(path).toString().split('\n') @@ -56,7 +56,7 @@ export function extendJSXFile( content.findLastIndex((l) => l.trimStart().startsWith('import')) + 1, 0, '', // Empty string to add a newline when we .join('\n') below. - ...moduleScopeLines + ...moduleScopeLines, ) } @@ -65,7 +65,7 @@ export function extendJSXFile( content.findLastIndex((l) => l.includes('@redwoodjs')) + 1, 0, '', // Empty string to add a newline when we .join('\n') below. - ...imports + ...imports, ) } @@ -100,11 +100,11 @@ export function extendJSXFile( */ function insertComponent( content, - { component, props, around, within, insertBefore, insertAfter } + { component, props, around, within, insertBefore, insertAfter }, ) { if ((around && within) || !(around || within)) { throw new Error( - 'Exactly one of (around | within) must be defined. Choose one.' + 'Exactly one of (around | within) must be defined. Choose one.', ) } @@ -134,7 +134,7 @@ function insertComponent( // Increase indent of each now-nested tag by one tab (two spaces) ...content.slice(open, close).map((line) => ' ' + line), componentDepth + ``, - insertAfter && componentDepth + insertAfter + insertAfter && componentDepth + insertAfter, ) } @@ -155,7 +155,7 @@ function buildOpeningTag(componentName, props) { return props default: throw new Error( - `Illegal argument passed for 'props'. Required: {Object | string | undefined}, got ${typeof props}` + `Illegal argument passed for 'props'. Required: {Object | string | undefined}, got ${typeof props}`, ) } })() @@ -173,7 +173,7 @@ function buildOpeningTag(componentName, props) { */ export function objectToComponentProps( obj, - options = { exclude: [], raw: false } + options = { exclude: [], raw: false }, ) { const props = [] diff --git a/packages/cli/src/lib/generatePrismaClient.js b/packages/cli/src/lib/generatePrismaClient.js index 39fb53486d20..03f5cb12a820 100644 --- a/packages/cli/src/lib/generatePrismaClient.js +++ b/packages/cli/src/lib/generatePrismaClient.js @@ -9,7 +9,7 @@ import { runCommandTask, getPaths } from '../lib' const skipTask = (schema = getPaths().api.dbSchema) => { if (!fs.existsSync(schema)) { console.log( - `Skipping database and Prisma client generation, no \`schema.prisma\` file found: \`${schema}\`` + `Skipping database and Prisma client generation, no \`schema.prisma\` file found: \`${schema}\``, ) return true } @@ -44,10 +44,9 @@ export const generatePrismaClient = async ({ // The Prisma client throws if it is not generated. try { // Import the client from the redwood apps node_modules path. - const { PrismaClient } = require(path.join( - getPaths().base, - 'node_modules/.prisma/client' - )) + const { PrismaClient } = require( + path.join(getPaths().base, 'node_modules/.prisma/client'), + ) // eslint-disable-next-line new PrismaClient() return // Client exists, so abort. @@ -65,6 +64,6 @@ export const generatePrismaClient = async ({ ], { verbose, - } + }, ) } diff --git a/packages/cli/src/lib/index.js b/packages/cli/src/lib/index.js index bbc3a7b5cdef..e0f814c48d41 100644 --- a/packages/cli/src/lib/index.js +++ b/packages/cli/src/lib/index.js @@ -135,7 +135,7 @@ export const writeFile = ( target, contents, { overwriteExisting = false } = {}, - task = {} + task = {}, ) => { const { base } = getPaths() task.title = `Writing \`./${path.relative(base, target)}\`` @@ -155,7 +155,7 @@ export const writeFile = ( export const saveRemoteFileToDisk = ( url, localPath, - { overwriteExisting = false } = {} + { overwriteExisting = false } = {}, ) => { if (!overwriteExisting && fs.existsSync(localPath)) { throw new Error(`${localPath} already exists.`) @@ -168,10 +168,10 @@ export const saveRemoteFileToDisk = ( resolve() } else { reject( - new Error(`${url} responded with status code ${response.statusCode}`) + new Error(`${url} responded with status code ${response.statusCode}`), ) } - }) + }), ) return downloadPromise @@ -295,7 +295,7 @@ export const writeFilesTask = (files, options) => { title: `...waiting to write file \`./${path.relative(base, file)}\`...`, task: (ctx, task) => writeFile(file, contents, options, task), } - }) + }), ) } @@ -360,7 +360,7 @@ export const cleanupEmptyDirsTask = (files) => { return false }, } - }) + }), ) } @@ -369,10 +369,10 @@ const wrapWithSet = ( layout, routes, newLineAndIndent, - props = {} + props = {}, ) => { const [_, indentOne, indentTwo] = routesContent.match( - /([ \t]*)[^<]*[\r\n]+([ \t]+)/ + /([ \t]*)[^<]*[\r\n]+([ \t]+)/, ) || ['', 0, 2] const oneLevelIndent = indentTwo.slice(0, indentTwo.length - indentOne.length) const newRoutesWithExtraIndent = routes.map((route) => oneLevelIndent + route) @@ -399,7 +399,7 @@ export const addRoutesToRouterTask = (routes, layout, setProps = {}) => { if (newRoutes.length) { const [routerStart, routerParams, newLineAndIndent] = routesContent.match( - /\s*(\s*)/s + /\s*(\s*)/s, ) if (/trailingSlashes={?(["'])always\1}?/.test(routerParams)) { @@ -407,7 +407,7 @@ export const addRoutesToRouterTask = (routes, layout, setProps = {}) => { // [''] // and we need to replace `path="/foo"` with `path="/foo/"` newRoutes = newRoutes.map((route) => - route.replace(/ path="(.+?)" /, ' path="$1/" ') + route.replace(/ path="(.+?)" /, ' path="$1/" '), ) } @@ -417,13 +417,13 @@ export const addRoutesToRouterTask = (routes, layout, setProps = {}) => { layout, newRoutes, newLineAndIndent, - setProps + setProps, ) : newRoutes.join(newLineAndIndent) const newRoutesContent = routesContent.replace( routerStart, - `${routerStart + routesBatch + newLineAndIndent}` + `${routerStart + routesBatch + newLineAndIndent}`, ) writeFile(redwoodPaths.web.routes, newRoutesContent, { @@ -442,7 +442,7 @@ export const addScaffoldImport = () => { appJsContents = appJsContents.replace( "import Routes from 'src/Routes'\n", - "import Routes from 'src/Routes'\n\nimport './scaffold.css'" + "import Routes from 'src/Routes'\n\nimport './scaffold.css'", ) writeFile(appJsPath, appJsContents, { overwriteExisting: true }) @@ -451,7 +451,7 @@ export const addScaffoldImport = () => { const removeEmtpySet = (routesContent, layout) => { const setWithLayoutReg = new RegExp( - `\\s*]*wrap={${layout}}[^<]*>([^<]*)<\/Set>` + `\\s*]*wrap={${layout}}[^<]*>([^<]*)<\/Set>`, ) const [matchedSet, childContent] = routesContent.match(setWithLayoutReg) || [] if (!matchedSet) { @@ -565,7 +565,7 @@ export const runCommandTask = async (commands, { verbose }) => { { renderer: verbose && 'verbose', rendererOptions: { collapseSubtasks: false, dateFormat: false }, - } + }, ) try { @@ -585,7 +585,7 @@ export const getDefaultArgs = (builder) => { options[optionName] = optionConfig.default return options }, - {} + {}, ) } diff --git a/packages/cli/src/lib/loadEnvFiles.js b/packages/cli/src/lib/loadEnvFiles.js index 708bfb0e5a07..cf77c3666f30 100644 --- a/packages/cli/src/lib/loadEnvFiles.js +++ b/packages/cli/src/lib/loadEnvFiles.js @@ -53,7 +53,7 @@ export function loadNodeEnvDerivedEnvFile(cwd) { const nodeEnvDerivedEnvFilePath = path.join( cwd, - `.env.${process.env.NODE_ENV}` + `.env.${process.env.NODE_ENV}`, ) if (!fs.existsSync(nodeEnvDerivedEnvFilePath)) { return @@ -70,7 +70,7 @@ export function loadUserSpecifiedEnvFiles(cwd, loadEnvFiles) { const envPath = path.join(cwd, `.env.${suffix}`) if (!fs.pathExistsSync(envPath)) { throw new Error( - `Couldn't find an .env file at '${envPath}' as specified by '--load-env-files'` + `Couldn't find an .env file at '${envPath}' as specified by '--load-env-files'`, ) } diff --git a/packages/cli/src/lib/locking.js b/packages/cli/src/lib/locking.js index 23095b9b8005..8066bb131751 100644 --- a/packages/cli/src/lib/locking.js +++ b/packages/cli/src/lib/locking.js @@ -29,7 +29,7 @@ export function setLock(identifier) { fs.writeFileSync( path.join(getPaths().generated.base, 'locks', identifier), - '' + '', ) } diff --git a/packages/cli/src/lib/merge/index.js b/packages/cli/src/lib/merge/index.js index 522f949ed8db..fe27dbc2d15f 100644 --- a/packages/cli/src/lib/merge/index.js +++ b/packages/cli/src/lib/merge/index.js @@ -99,7 +99,7 @@ function expressionUses(exp, ...ids) { function insertBeforeFirstUsage(expression, program) { const body = program.get('body') const pos = body.findIndex((exp) => - expressionUses(exp, ...Object.keys(expression.getBindingIdentifiers())) + expressionUses(exp, ...Object.keys(expression.getBindingIdentifiers())), ) return pos !== -1 ? body[pos].insertBefore(expression.node) @@ -194,7 +194,7 @@ function mergeAST(baseAST, extAST, strategy = {}) { const baseProgram = getProgramPath(baseAST) const [imports, others] = partition( getProgramPath(extAST).get('body'), - nodeIs('ImportDeclaration') + nodeIs('ImportDeclaration'), ) imports.forEach((exp) => insertAfterLastImport(exp, baseProgram)) diff --git a/packages/cli/src/lib/merge/strategy.js b/packages/cli/src/lib/merge/strategy.js index d492b85fdf94..b7f3ae2097e9 100644 --- a/packages/cli/src/lib/merge/strategy.js +++ b/packages/cli/src/lib/merge/strategy.js @@ -9,7 +9,7 @@ const OPAQUE_UID_TAG = function requireSameType(base, ext) { if (base.path.type !== ext.path.type) { throw new Error( - 'Attempting to merge nodes with different types. This is not yet supported.' + 'Attempting to merge nodes with different types. This is not yet supported.', ) } } @@ -17,7 +17,7 @@ function requireSameType(base, ext) { function requireStrategyExists(base, _ext, strategy, strategyName) { if (!(base.path.type in strategy)) { throw new Error( - `Attempting to ${strategyName} nodes that do not have an ${strategyName} strategy.` + `Attempting to ${strategyName} nodes that do not have an ${strategyName} strategy.`, ) } } @@ -88,7 +88,7 @@ const interleaveStrategy = { const uniqueSpecifiersOfType = (type) => _.uniqWith( [...baseSpecs, ...extSpecs].filter(nodeIs(type)), - importSpecifierEquality + importSpecifierEquality, ) // Rule 1: If there's exactly 1 import with 0 specifiers, it's a side-effect import and should @@ -114,13 +114,13 @@ const interleaveStrategy = { const [firstSpecifierList, ...rest] = sieve( [uniqueSpecifiersOfType('ImportDefaultSpecifier'), defaultPosition], [uniqueSpecifiersOfType('ImportNamespaceSpecifier'), namespacePosition], - [uniqueSpecifiersOfType('ImportSpecifier'), importPosition] + [uniqueSpecifiersOfType('ImportSpecifier'), importPosition], ) baseImport.specifiers = firstSpecifierList if (rest.length) { baseImport.path.insertAfter( - rest.map((specs) => t.importDeclaration(specs, baseImport.source)) + rest.map((specs) => t.importDeclaration(specs, baseImport.source)), ) } }, diff --git a/packages/cli/src/lib/packages.js b/packages/cli/src/lib/packages.js index 73811a981e2b..2fde6203f6bd 100644 --- a/packages/cli/src/lib/packages.js +++ b/packages/cli/src/lib/packages.js @@ -59,7 +59,7 @@ export async function installRedwoodModule(module) { try { const packumentResponse = await fetch( - `https://registry.npmjs.org/${module}` + `https://registry.npmjs.org/${module}`, ) packument = await packumentResponse.json() @@ -69,7 +69,7 @@ export async function installRedwoodModule(module) { } } catch (error) { throw new Error( - `Couldn't fetch packument for ${module}: ${error.message}` + `Couldn't fetch packument for ${module}: ${error.message}`, ) } @@ -103,7 +103,7 @@ export async function installRedwoodModule(module) { */ export function isModuleInstalled(module) { const { dependencies, devDependencies } = fs.readJSONSync( - path.join(getPaths().base, 'package.json') + path.join(getPaths().base, 'package.json'), ) const deps = { diff --git a/packages/cli/src/lib/plugin.js b/packages/cli/src/lib/plugin.js index eaa888552cfb..ce9d3849eb0d 100644 --- a/packages/cli/src/lib/plugin.js +++ b/packages/cli/src/lib/plugin.js @@ -78,7 +78,7 @@ export function loadCommandCache() { let pluginCommandCache = PLUGIN_CACHE_DEFAULT const commandCachePath = path.join( getPaths().generated.base, - PLUGIN_CACHE_FILENAME + PLUGIN_CACHE_FILENAME, ) try { const localCommandCache = JSON.parse(fs.readFileSync(commandCachePath)) @@ -115,12 +115,12 @@ export function loadCommandCache() { export function saveCommandCache(pluginCommandCache) { const commandCachePath = path.join( getPaths().generated.base, - PLUGIN_CACHE_FILENAME + PLUGIN_CACHE_FILENAME, ) try { fs.writeFileSync( commandCachePath, - JSON.stringify(pluginCommandCache, undefined, 2) + JSON.stringify(pluginCommandCache, undefined, 2), ) } catch (error) { console.error(`Error saving plugin command cache at ${commandCachePath}`) @@ -138,7 +138,7 @@ export function checkPluginListAndWarn(plugins) { for (const plugin of plugins) { if (!plugin.package) { console.warn( - chalk.yellow(`⚠️ A plugin is missing a package, it cannot be loaded.`) + chalk.yellow(`⚠️ A plugin is missing a package, it cannot be loaded.`), ) } } @@ -150,8 +150,8 @@ export function checkPluginListAndWarn(plugins) { if (pluginPackages.length !== new Set(pluginPackages).size) { console.warn( chalk.yellow( - '⚠️ Duplicate plugin packages found in redwood.toml, duplicates will be ignored.' - ) + '⚠️ Duplicate plugin packages found in redwood.toml, duplicates will be ignored.', + ), ) } @@ -161,8 +161,8 @@ export function checkPluginListAndWarn(plugins) { if (ns !== undefined && !ns.startsWith('@')) { console.warn( chalk.yellow( - `⚠️ Plugin "${ns}" is missing a scope/namespace, it will not be loaded.` - ) + `⚠️ Plugin "${ns}" is missing a scope/namespace, it will not be loaded.`, + ), ) } }) @@ -180,7 +180,7 @@ export function checkPluginListAndWarn(plugins) { export async function loadPluginPackage( packageName, packageVersion, - autoInstall + autoInstall, ) { // NOTE: This likely does not handle mismatch versions between what is installed and what is requested if (isModuleInstalled(packageName)) { @@ -190,8 +190,8 @@ export async function loadPluginPackage( if (!autoInstall) { console.warn( chalk.yellow( - `⚠️ Plugin "${packageName}" cannot be loaded because it is not installed and "autoInstall" is disabled.` - ) + `⚠️ Plugin "${packageName}" cannot be loaded because it is not installed and "autoInstall" is disabled.`, + ), ) return null } @@ -224,17 +224,17 @@ async function installPluginPackage(packageName, packageVersion) { try { const compatibilityData = await getCompatibilityData( packageName, - versionToInstall + versionToInstall, ) versionToInstall = compatibilityData.compatible.version console.log( chalk.green( - `Installing the latest compatible version: ${versionToInstall}` - ) + `Installing the latest compatible version: ${versionToInstall}`, + ), ) } catch (error) { console.log( - 'The following error occurred while checking plugin compatibility for automatic installation:' + 'The following error occurred while checking plugin compatibility for automatic installation:', ) const errorMessage = error.message ?? error console.log(errorMessage) diff --git a/packages/cli/src/lib/project.js b/packages/cli/src/lib/project.js index 2be7a7a2cdc2..70353270c625 100644 --- a/packages/cli/src/lib/project.js +++ b/packages/cli/src/lib/project.js @@ -28,7 +28,7 @@ export const sides = () => { export const serverFileExists = () => { const serverFilePath = path.join( getPaths().api.src, - `server.${isTypeScriptProject() ? 'ts' : 'js'}` + `server.${isTypeScriptProject() ? 'ts' : 'js'}`, ) return fs.existsSync(serverFilePath) diff --git a/packages/cli/src/lib/rwPluralize.js b/packages/cli/src/lib/rwPluralize.js index 87fb2bd03491..d3f1511bcc63 100644 --- a/packages/cli/src/lib/rwPluralize.js +++ b/packages/cli/src/lib/rwPluralize.js @@ -103,7 +103,7 @@ export function isSingular(word) { */ export function addSingularPlural(singular, plural) { const existingPlural = Object.keys(mappings.toSingular).find( - (key) => mappings.toSingular[key] === singular + (key) => mappings.toSingular[key] === singular, ) delete mappings.toSingular[existingPlural] delete mappings.toPlural[existingPlural] diff --git a/packages/cli/src/lib/schemaHelpers.js b/packages/cli/src/lib/schemaHelpers.js index 0e0558b3a5a5..6b562d6b6fba 100644 --- a/packages/cli/src/lib/schemaHelpers.js +++ b/packages/cli/src/lib/schemaHelpers.js @@ -52,7 +52,7 @@ export const getSchema = async (name) => { const modelName = await getExistingModelName(name) if (!modelName) { throw new Error( - `No schema definition found for \`${name}\` in schema.prisma file` + `No schema definition found for \`${name}\` in schema.prisma file`, ) } if (!schemaMemo[modelName]) { @@ -100,7 +100,7 @@ export const getEnum = async (name) => { return model } else { throw new Error( - `No enum schema definition found for \`${name}\` in schema.prisma file` + `No enum schema definition found for \`${name}\` in schema.prisma file`, ) } } @@ -131,7 +131,7 @@ export async function verifyModelName(options) { if (modelName === undefined) { throw new Error( - `"${options.name}" model not found, check if it exists in "./api/db/schema.prisma"` + `"${options.name}" model not found, check if it exists in "./api/db/schema.prisma"`, ) } diff --git a/packages/cli/src/lib/test.js b/packages/cli/src/lib/test.js index 94d7fd2bf967..3db12905eddb 100644 --- a/packages/cli/src/lib/test.js +++ b/packages/cli/src/lib/test.js @@ -38,7 +38,7 @@ vi.mock('@redwoodjs/project-config', async (importOriginal) => { dbSchema: path.join( globalThis.__dirname, 'fixtures', - 'schema.prisma' + 'schema.prisma', ), // this folder generators: path.join(BASE_PATH, './api/generators'), src: path.join(BASE_PATH, './api/src'), @@ -78,7 +78,7 @@ vi.mock('./project', () => ({ globalThis.__prettierPath = path.resolve( __dirname, - './__tests__/fixtures/prettier.config.js' + './__tests__/fixtures/prettier.config.js', ) vi.spyOn(Math, 'random').mockReturnValue(0.123456789) @@ -87,7 +87,7 @@ export const generatorsRootPath = path.join( __dirname, '..', 'commands', - 'generate' + 'generate', ) /** @@ -110,8 +110,8 @@ export const loadGeneratorFixture = (generator, name) => { generator, '__tests__', 'fixtures', - name - ) + name, + ), ) } diff --git a/packages/cli/src/lib/updateCheck.js b/packages/cli/src/lib/updateCheck.js index 59c3dfc9aa12..3cae36aa093e 100644 --- a/packages/cli/src/lib/updateCheck.js +++ b/packages/cli/src/lib/updateCheck.js @@ -76,7 +76,7 @@ export async function check() { // Read package.json and extract the @redwood/core version const packageJson = JSON.parse( - fs.readFileSync(path.join(getPaths().base, 'package.json')) + fs.readFileSync(path.join(getPaths().base, 'package.json')), ) let localVersion = packageJson.devDependencies['@redwoodjs/core'] @@ -92,7 +92,7 @@ export async function check() { try { remoteVersions.set( tag, - await latestVersion('@redwoodjs/core', { version: tag }) + await latestVersion('@redwoodjs/core', { version: tag }), ) } catch (error) { // This error may result as the ability of the user to specify arbitrary tags within their config file @@ -217,11 +217,11 @@ export function readUpdateDataFile() { fs.mkdirSync(getPersistenceDirectory(), { recursive: true }) } const persistedData = JSON.parse( - fs.readFileSync(path.join(getPersistenceDirectory(), 'data.json')) + fs.readFileSync(path.join(getPersistenceDirectory(), 'data.json')), ) // Reconstruct the map persistedData.remoteVersions = new Map( - Object.entries(persistedData.remoteVersions) + Object.entries(persistedData.remoteVersions), ) return persistedData } catch (error) { @@ -254,7 +254,7 @@ function updateUpdateDataFile({ const updatedData = { localVersion: localVersion ?? existingData.localVersion, remoteVersions: Object.fromEntries( - remoteVersions ?? existingData.remoteVersions + remoteVersions ?? existingData.remoteVersions, ), checkedAt: checkedAt ?? existingData.checkedAt, shownAt: shownAt ?? existingData.shownAt, @@ -262,7 +262,7 @@ function updateUpdateDataFile({ fs.writeFileSync( path.join(getPersistenceDirectory(), 'data.json'), - JSON.stringify(updatedData, null, 2) + JSON.stringify(updatedData, null, 2), ) } diff --git a/packages/cli/src/middleware/checkNodeVersion.js b/packages/cli/src/middleware/checkNodeVersion.js index f884c4401950..db41cf5144ab 100644 --- a/packages/cli/src/middleware/checkNodeVersion.js +++ b/packages/cli/src/middleware/checkNodeVersion.js @@ -17,7 +17,7 @@ export function checkNodeVersion() { checks.ok = false checks.message = [ `Your Node.js version is ${c.warning( - pVersion + pVersion, )}, but Redwood requires ${c.green(`>=${LOWER_BOUND}`)}.`, 'Upgrade your Node.js version using `nvm` or a similar tool. See https://redwoodjs.com/docs/how-to/using-nvm.', ].join('\n') diff --git a/packages/cli/src/plugin.js b/packages/cli/src/plugin.js index a2f912452538..7552d8db168e 100644 --- a/packages/cli/src/plugin.js +++ b/packages/cli/src/plugin.js @@ -46,7 +46,7 @@ export async function loadPlugins(yargs) { // Plugins are enabled unless explicitly disabled const enabledPlugins = plugins.filter( - (p) => p.package !== undefined && (p.enabled ?? true) + (p) => p.package !== undefined && (p.enabled ?? true), ) // Print warnings about any invalid plugins @@ -101,7 +101,7 @@ export async function loadPlugins(yargs) { redwoodPluginPackage, pluginCommandCache, autoInstall, - true + true, ) yargs.command(commands) } @@ -137,13 +137,13 @@ export async function loadPlugins(yargs) { redwoodPluginPackage, pluginCommandCache, autoInstall, - true + true, ) yargs.command(commands) } } else { const packagesForNamespace = Array.from(thirdPartyPackages).filter((p) => - p.startsWith(namespaceInUse) + p.startsWith(namespaceInUse), ) for (const packageForNamespace of packagesForNamespace) { // We'll load the plugin information from the cache if there is a cache entry @@ -151,7 +151,7 @@ export async function loadPlugins(yargs) { packageForNamespace, pluginCommandCache, autoInstall, - true + true, ) yargs.command({ command: `${namespaceInUse} `, @@ -187,7 +187,7 @@ export async function loadPlugins(yargs) { for (const [command, info] of Object.entries(cacheEntry)) { commandFirstWords.push(command.split(' ')[0]) commandFirstWords.push( - ...(info.aliases?.map((a) => a.split(' ')[0]) ?? []) + ...(info.aliases?.map((a) => a.split(' ')[0]) ?? []), ) } if ( @@ -220,7 +220,7 @@ export async function loadPlugins(yargs) { packageToLoad, pluginCommandCache, autoInstall, - false + false, ) commandsToRegister.push(...commands) } else { @@ -232,7 +232,7 @@ export async function loadPlugins(yargs) { packageToLoad, pluginCommandCache, autoInstall, - true + true, ) commandsToRegister.push(...commands) } @@ -279,7 +279,7 @@ async function loadCommandsFromCacheOrPackage( packageName, cache, autoInstall, - readFromCache + readFromCache, ) { let cacheEntry = undefined if (readFromCache) { diff --git a/packages/cli/src/rwfw.js b/packages/cli/src/rwfw.js index c0fbb490483b..149277c5e481 100644 --- a/packages/cli/src/rwfw.js +++ b/packages/cli/src/rwfw.js @@ -22,7 +22,7 @@ if (!RWFW_PATH) { if (!fs.existsSync(RWFW_PATH)) { console.error( - `Error: The specified path to Redwood Framework (${RWFW_PATH}) does not exist.` + `Error: The specified path to Redwood Framework (${RWFW_PATH}) does not exist.`, ) console.error('Usage: `RWFW_PATH=~/gh/redwoodjs/redwood yarn rwfw ') process.exit(1) @@ -33,11 +33,11 @@ config.set('RWFW_PATH', absRwFwPath) // Execute the commands in the Redwood Framework Tools package. const projectPath = path.dirname( - getConfigPath(process.env.RWJS_CWD ?? process.cwd()) + getConfigPath(process.env.RWJS_CWD ?? process.cwd()), ) console.log( 'Redwood Framework Tools Path:', - TerminalLink(absRwFwPath, absRwFwPath) + TerminalLink(absRwFwPath, absRwFwPath), ) let command = process.argv.slice(2) diff --git a/packages/cli/src/telemetry/exporter.js b/packages/cli/src/telemetry/exporter.js index 226c8d50a381..e37c7659fcd4 100644 --- a/packages/cli/src/telemetry/exporter.js +++ b/packages/cli/src/telemetry/exporter.js @@ -33,7 +33,7 @@ export class CustomFileExporter { this.#storageFilePath = path.join( getPaths().generated.base, 'telemetry', - this.#storageFileName + this.#storageFileName, ) fs.ensureDirSync(path.dirname(this.#storageFilePath)) @@ -51,7 +51,7 @@ export class CustomFileExporter { delete span['_spanProcessor'] // This is a circular reference and will cause issues with JSON.stringify fs.appendFileSync( this.#storageFilePath, - JSON.stringify(span, undefined, 2) + JSON.stringify(span, undefined, 2), ) fs.appendFileSync(this.#storageFilePath, ',') } @@ -65,7 +65,7 @@ export class CustomFileExporter { // Remove the trailing comma fs.truncateSync( this.#storageFilePath, - fs.statSync(this.#storageFilePath).size - 1 + fs.statSync(this.#storageFilePath).size - 1, ) fs.appendFileSync(this.#storageFilePath, ']') this.#isShutdown = true diff --git a/packages/cli/src/telemetry/resource.js b/packages/cli/src/telemetry/resource.js index 976264031b75..7667cb6845cd 100644 --- a/packages/cli/src/telemetry/resource.js +++ b/packages/cli/src/telemetry/resource.js @@ -45,8 +45,8 @@ export async function getResources() { npmPackages: '@redwoodjs/*', IDEs: ['VSCode'], }, - { json: true } - ) + { json: true }, + ), ) // get shell name instead of path diff --git a/packages/cli/src/telemetry/send.js b/packages/cli/src/telemetry/send.js index 0ee99717a296..f55a6f7e8027 100644 --- a/packages/cli/src/telemetry/send.js +++ b/packages/cli/src/telemetry/send.js @@ -11,17 +11,17 @@ import { getResources } from './resource' async function main() { // Log out the telemetry notice console.log( - "You can disable telemetry by:\n - setting the 'REDWOOD_DISABLE_TELEMETRY' environment variable\n - passing the '--no-telemetry' flag when using the CLI" + "You can disable telemetry by:\n - setting the 'REDWOOD_DISABLE_TELEMETRY' environment variable\n - passing the '--no-telemetry' flag when using the CLI", ) console.log( - 'Information about Redwood telemetry can be found at:\n - https://telemetry.redwoodjs.com\n' + 'Information about Redwood telemetry can be found at:\n - https://telemetry.redwoodjs.com\n', ) // Get all telemetry files const telemetryDir = path.join(getPaths().generated.base, 'telemetry') fs.ensureDirSync(telemetryDir) const telemetryFiles = fs.readdirSync( - path.join(getPaths().generated.base, 'telemetry') + path.join(getPaths().generated.base, 'telemetry'), ) // Compute all the resource information @@ -60,7 +60,7 @@ async function main() { if (!Array.isArray(spans)) { console.error( - `Telemetry file '${file}' does not contain an array of spans. Deleting this file to prevent further errors.` + `Telemetry file '${file}' does not contain an array of spans. Deleting this file to prevent further errors.`, ) fs.unlinkSync(path.join(telemetryDir, file)) continue @@ -106,7 +106,7 @@ async function main() { // We keep the last 8 telemetry files for visibility/transparency console.log( - 'Keeping the lastest 8 telemetry files for visibility/transparency.' + 'Keeping the lastest 8 telemetry files for visibility/transparency.', ) const sortedTelemetryFiles = telemetryFiles.sort((a, b) => { return ( diff --git a/packages/cli/src/testLib/getRootPackageJSON.ts b/packages/cli/src/testLib/getRootPackageJSON.ts index f68c3a52a605..dd5cedff24ab 100644 --- a/packages/cli/src/testLib/getRootPackageJSON.ts +++ b/packages/cli/src/testLib/getRootPackageJSON.ts @@ -7,7 +7,7 @@ const getRootPackageJSON = () => { const rootPackageJSONPath = path.join(getPaths().base, 'package.json') const rootPackageJSON = JSON.parse( - fs.readFileSync(rootPackageJSONPath, 'utf8') + fs.readFileSync(rootPackageJSONPath, 'utf8'), ) return [rootPackageJSON, rootPackageJSONPath] diff --git a/packages/cli/src/testUtils/matchFolderTransform.ts b/packages/cli/src/testUtils/matchFolderTransform.ts index 03bdb766c7c3..3a81987ace65 100644 --- a/packages/cli/src/testUtils/matchFolderTransform.ts +++ b/packages/cli/src/testUtils/matchFolderTransform.ts @@ -22,7 +22,7 @@ type Options = { type MatchFolderTransformFunction = ( transformFunctionOrName: (() => any) | string, fixtureName?: string, - options?: Options + options?: Options, ) => Promise const require = createRequire(import.meta.url) @@ -34,7 +34,7 @@ export const matchFolderTransform: MatchFolderTransformFunction = async ( removeWhitespace = false, targetPathsGlob = '**/*', useJsCodeshift = false, - } = {} + } = {}, ) => { const tempDir = createProjectMock() @@ -53,7 +53,7 @@ export const matchFolderTransform: MatchFolderTransformFunction = async ( const fixtureFolder = path.join( testPath, '../../__testfixtures__', - fixtureName || '' + fixtureName || '', ) const fixtureInputDir = path.join(fixtureFolder, 'input') @@ -74,12 +74,12 @@ export const matchFolderTransform: MatchFolderTransformFunction = async ( if (useJsCodeshift) { if (typeof transformFunctionOrName !== 'string') { throw new Error( - 'When running matchFolderTransform with useJsCodeshift, transformFunction must be a string (file name of jscodeshift transform)' + 'When running matchFolderTransform with useJsCodeshift, transformFunction must be a string (file name of jscodeshift transform)', ) } const transformName = transformFunctionOrName const transformPath = require.resolve( - path.join(testPath, '../../', transformName + '.ts') + path.join(testPath, '../../', transformName + '.ts'), ) const targetPaths = fg.sync(targetPathsGlob, { @@ -98,7 +98,7 @@ export const matchFolderTransform: MatchFolderTransformFunction = async ( } else { if (typeof transformFunctionOrName !== 'function') { throw new Error( - 'transformFunction must be a function, if useJsCodeshift set to false' + 'transformFunction must be a function, if useJsCodeshift set to false', ) } const transformFunction = transformFunctionOrName diff --git a/packages/cli/src/testUtils/matchInlineTransformSnapshot.ts b/packages/cli/src/testUtils/matchInlineTransformSnapshot.ts index 95638a2abb41..65179c87e397 100644 --- a/packages/cli/src/testUtils/matchInlineTransformSnapshot.ts +++ b/packages/cli/src/testUtils/matchInlineTransformSnapshot.ts @@ -15,7 +15,7 @@ export const matchInlineTransformSnapshot = async ( transformName: string, fixtureCode: string, expectedCode: string, - parser: 'ts' | 'tsx' | 'babel' = 'tsx' + parser: 'ts' | 'tsx' | 'babel' = 'tsx', ) => { const tempFilePath = tempy.file() @@ -27,7 +27,7 @@ export const matchInlineTransformSnapshot = async ( } const transformPath = require.resolve( - path.join(testPath, '../../', transformName + '.ts') + path.join(testPath, '../../', transformName + '.ts'), ) // Step 1: Write passed in code to a temp file diff --git a/packages/cli/src/vitest.codemods.setup.ts b/packages/cli/src/vitest.codemods.setup.ts index 422caa5a830d..efff0acab752 100644 --- a/packages/cli/src/vitest.codemods.setup.ts +++ b/packages/cli/src/vitest.codemods.setup.ts @@ -24,7 +24,7 @@ expect.extend({ toMatchFileContents( receivedPath, expectedPath, - { removeWhitespace } = { removeWhitespace: false } + { removeWhitespace } = { removeWhitespace: false }, ) { let pass = true let message = '' @@ -41,7 +41,7 @@ expect.extend({ } catch (e) { const relativePath = path.relative( path.join(__dirname, 'src/commands/setup'), - expectedPath + expectedPath, ) pass = false message = `${e}\nFile contents do not match for fixture at: \n ${relativePath}` diff --git a/packages/cli/testUtils.d.ts b/packages/cli/testUtils.d.ts index 9f95cacd5687..ae1bfb95f640 100644 --- a/packages/cli/testUtils.d.ts +++ b/packages/cli/testUtils.d.ts @@ -10,7 +10,7 @@ declare module 'jscodeshift/dist/testUtils' { testFilePrefix?: string | null, testOptions?: { parser: 'ts' | 'tsx' | 'js' | 'jsx' | Parser - } + }, ): () => any function defineInlineTest( @@ -18,7 +18,7 @@ declare module 'jscodeshift/dist/testUtils' { options: Options, inputSource: string, expectedOutputSource: string, - testName?: string + testName?: string, ): () => any function runInlineTest( @@ -29,7 +29,7 @@ declare module 'jscodeshift/dist/testUtils' { source: string }, expectedOutput: string, - testOptions?: TestOptions + testOptions?: TestOptions, ): string } @@ -45,14 +45,14 @@ type MatchFolderTransformFunction = ( * as well as modifies file names. e.g. convertJsToJsx */ useJsCodeshift?: boolean - } + }, ) => Promise type MatchInlineTransformSnapshotFunction = ( transformName: string, fixtureCode: string, expectedCode: string, - parser: 'ts' | 'tsx' | 'babel' = 'tsx' + parser: 'ts' | 'tsx' | 'babel' = 'tsx', ) => Promise // These files gets loaded in vitest setup, so becomes available globally in tests @@ -70,7 +70,7 @@ declare global { interface CustomMatchers { toMatchFileContents( fixturePath: string, - { removeWhitespace }: { removeWhitespace: boolean } + { removeWhitespace }: { removeWhitespace: boolean }, ): R } diff --git a/packages/codemods/src/codemods/v0.37.x/updateApiImports/updateApiImports.ts b/packages/codemods/src/codemods/v0.37.x/updateApiImports/updateApiImports.ts index 1d3a54e3f5d0..866f6006b9ac 100644 --- a/packages/codemods/src/codemods/v0.37.x/updateApiImports/updateApiImports.ts +++ b/packages/codemods/src/codemods/v0.37.x/updateApiImports/updateApiImports.ts @@ -35,7 +35,7 @@ export default function transform(file: FileInfo, api: API) { } else { graphqlServerSpecifiers.add(name) } - } + }, ) j(importDeclaration).remove() @@ -47,7 +47,7 @@ export default function transform(file: FileInfo, api: API) { .find(j.Program) .get('body', 0) .insertBefore( - `import { ${[...apiSpecifiers].join(', ')} } from '@redwoodjs/api'` + `import { ${[...apiSpecifiers].join(', ')} } from '@redwoodjs/api'`, ) } @@ -57,8 +57,8 @@ export default function transform(file: FileInfo, api: API) { .get('body', 0) .insertBefore( `import { ${[...graphqlServerSpecifiers].join( - ', ' - )} } from '@redwoodjs/graphql-server'` + ', ', + )} } from '@redwoodjs/graphql-server'`, ) } diff --git a/packages/codemods/src/codemods/v0.37.x/updateApiImports/updateApiImports.yargs.ts b/packages/codemods/src/codemods/v0.37.x/updateApiImports/updateApiImports.yargs.ts index d3851816e321..76afb38c96f6 100644 --- a/packages/codemods/src/codemods/v0.37.x/updateApiImports/updateApiImports.yargs.ts +++ b/packages/codemods/src/codemods/v0.37.x/updateApiImports/updateApiImports.yargs.ts @@ -30,6 +30,6 @@ export const handler = () => { targetPaths: files, }) } - } + }, ) } diff --git a/packages/codemods/src/codemods/v0.37.x/updateForms/updateForms.ts b/packages/codemods/src/codemods/v0.37.x/updateForms/updateForms.ts index d7aeef1868ba..9068cd431b0d 100644 --- a/packages/codemods/src/codemods/v0.37.x/updateForms/updateForms.ts +++ b/packages/codemods/src/codemods/v0.37.x/updateForms/updateForms.ts @@ -6,7 +6,7 @@ export default function transform(file: FileInfo, api: API) { const j = api.jscodeshift const mapTransformValueToValidationProperty = ( - transformValue: TransformValue + transformValue: TransformValue, ) => { const j = api.jscodeshift @@ -14,27 +14,27 @@ export default function transform(file: FileInfo, api: API) { case 'Float': return j.objectProperty( j.identifier('valueAsNumber'), - j.booleanLiteral(true) + j.booleanLiteral(true), ) case 'Json': return j.objectProperty( j.identifier('valueAsJSON'), - j.booleanLiteral(true) + j.booleanLiteral(true), ) case 'Int': return j.objectProperty( j.identifier('valueAsNumber'), - j.booleanLiteral(true) + j.booleanLiteral(true), ) case 'Boolean': return j.objectProperty( j.identifier('valueAsBoolean'), - j.booleanLiteral(true) + j.booleanLiteral(true), ) case 'DateTime': return j.objectProperty( j.identifier('valueAsDate'), - j.booleanLiteral(true) + j.booleanLiteral(true), ) } } @@ -52,7 +52,7 @@ export default function transform(file: FileInfo, api: API) { j.JSXIdentifier, { name: 'validation', - } + }, ) // formValidationProp is an array so we have to iterate over it. @@ -78,15 +78,15 @@ export default function transform(file: FileInfo, api: API) { const validationAttribute = field.node.attributes.filter( (attr: any) => { return attr.name.name === 'validation' - } + }, ) const validationAttributeObjectProperties = validationAttribute[0].value.expression.properties validationAttributeObjectProperties.push( mapTransformValueToValidationProperty( - transformValue as TransformValue - ) + transformValue as TransformValue, + ), ) } else { // add the whole validation attribute @@ -95,10 +95,10 @@ export default function transform(file: FileInfo, api: API) { j.jsxExpressionContainer( j.objectExpression([ mapTransformValueToValidationProperty( - transformValue as TransformValue + transformValue as TransformValue, ), - ]) - ) + ]), + ), ) field.value.attributes.push(prop) diff --git a/packages/codemods/src/codemods/v0.37.x/updateGraphQLFunction/__tests__/updateGraphQLFunction.test.ts b/packages/codemods/src/codemods/v0.37.x/updateGraphQLFunction/__tests__/updateGraphQLFunction.test.ts index c14e8f3dd912..dc321afa5803 100644 --- a/packages/codemods/src/codemods/v0.37.x/updateGraphQLFunction/__tests__/updateGraphQLFunction.test.ts +++ b/packages/codemods/src/codemods/v0.37.x/updateGraphQLFunction/__tests__/updateGraphQLFunction.test.ts @@ -18,7 +18,7 @@ describe('Update GraphQL Function', () => { createGraphQLHandler, makeMergedSchema, } from '@redwoodjs/api'`, - `import { createGraphQLHandler } from '@redwoodjs/graphql-server'` + `import { createGraphQLHandler } from '@redwoodjs/graphql-server'`, ) }) }) diff --git a/packages/codemods/src/codemods/v0.37.x/updateGraphQLFunction/updateGraphQLFunction.ts b/packages/codemods/src/codemods/v0.37.x/updateGraphQLFunction/updateGraphQLFunction.ts index 7bd459cb2a4c..01a105230f31 100644 --- a/packages/codemods/src/codemods/v0.37.x/updateGraphQLFunction/updateGraphQLFunction.ts +++ b/packages/codemods/src/codemods/v0.37.x/updateGraphQLFunction/updateGraphQLFunction.ts @@ -13,8 +13,8 @@ export default function transform(file: FileInfo, api: API) { j(path).replaceWith( j.importDeclaration( [j.importSpecifier(j.identifier('createGraphQLHandler'))], - j.literal('@redwoodjs/graphql-server') - ) + j.literal('@redwoodjs/graphql-server'), + ), ) } @@ -25,11 +25,11 @@ export default function transform(file: FileInfo, api: API) { j(path).replaceWith([ j.importDeclaration( [j.importDefaultSpecifier(j.identifier('directives'))], - j.literal('src/directives/**/*.{js,ts}') + j.literal('src/directives/**/*.{js,ts}'), ), j.importDeclaration( [j.importDefaultSpecifier(j.identifier('sdls'))], - j.literal('src/graphql/**/*.sdl.{js,ts}') + j.literal('src/graphql/**/*.sdl.{js,ts}'), ), ]) } diff --git a/packages/codemods/src/codemods/v0.38.x/updateNodeEngine/updateNodeEngine.ts b/packages/codemods/src/codemods/v0.38.x/updateNodeEngine/updateNodeEngine.ts index 3dae0aaa14d1..3c7950fc54d4 100644 --- a/packages/codemods/src/codemods/v0.38.x/updateNodeEngine/updateNodeEngine.ts +++ b/packages/codemods/src/codemods/v0.38.x/updateNodeEngine/updateNodeEngine.ts @@ -9,6 +9,6 @@ export const updateNodeEngine = () => { fs.writeFileSync( rootPackageJSONPath, - JSON.stringify(rootPackageJSON, null, 2) + '\n' + JSON.stringify(rootPackageJSON, null, 2) + '\n', ) } diff --git a/packages/codemods/src/codemods/v0.38.x/updateSeedScript/updateSeedScript.ts b/packages/codemods/src/codemods/v0.38.x/updateSeedScript/updateSeedScript.ts index 261c91335718..8c0c64554b5d 100644 --- a/packages/codemods/src/codemods/v0.38.x/updateSeedScript/updateSeedScript.ts +++ b/packages/codemods/src/codemods/v0.38.x/updateSeedScript/updateSeedScript.ts @@ -27,7 +27,7 @@ export const updateSeedScript = async () => { fs.writeFileSync( rootPackageJSONPath, - JSON.stringify(rootPackageJSON, null, 2) + '\n' + JSON.stringify(rootPackageJSON, null, 2) + '\n', ) /** @@ -42,7 +42,7 @@ export const updateSeedScript = async () => { } const res = await fetch( - 'https://raw.githubusercontent.com/redwoodjs/redwood/main/packages/create-redwood-app/template/scripts/seed.ts' + 'https://raw.githubusercontent.com/redwoodjs/redwood/main/packages/create-redwood-app/template/scripts/seed.ts', ) let text: string | null = await res.text() @@ -53,6 +53,6 @@ export const updateSeedScript = async () => { fs.writeFileSync( path.join(rwPaths.scripts, `seed.${isTSProject ? 'ts' : 'js'}`), - text ? text : '' + text ? text : '', ) } diff --git a/packages/codemods/src/codemods/v0.39.x/updateBabelConfig/__tests__/updateBabelConfig.test.ts b/packages/codemods/src/codemods/v0.39.x/updateBabelConfig/__tests__/updateBabelConfig.test.ts index 0ef89737e611..cfd9f5b0a360 100644 --- a/packages/codemods/src/codemods/v0.39.x/updateBabelConfig/__tests__/updateBabelConfig.test.ts +++ b/packages/codemods/src/codemods/v0.39.x/updateBabelConfig/__tests__/updateBabelConfig.test.ts @@ -16,8 +16,8 @@ test('Should preserve custom web config', async () => { test('Should throw if root babel.config.js has custom config', async () => { expect(async () => - matchFolderTransform(transform, 'rootCustom') + matchFolderTransform(transform, 'rootCustom'), ).rejects.toThrowError( - 'Cannot automatically codemod your project. Please move your root babel.config.js settings manually' + 'Cannot automatically codemod your project. Please move your root babel.config.js settings manually', ) }) diff --git a/packages/codemods/src/codemods/v0.39.x/updateBabelConfig/updateBabelConfig.ts b/packages/codemods/src/codemods/v0.39.x/updateBabelConfig/updateBabelConfig.ts index b1325c779f0e..0c2fa98f58d5 100644 --- a/packages/codemods/src/codemods/v0.39.x/updateBabelConfig/updateBabelConfig.ts +++ b/packages/codemods/src/codemods/v0.39.x/updateBabelConfig/updateBabelConfig.ts @@ -26,7 +26,7 @@ export const removeBabelConfig = async () => { // Fail and ask them to move config manually console.warn('Detected custom config in your root babel.config.js') throw new Error( - 'Cannot automatically codemod your project. Please move your root babel.config.js settings manually' + 'Cannot automatically codemod your project. Please move your root babel.config.js settings manually', ) } } diff --git a/packages/codemods/src/codemods/v0.39.x/updateCellMocks/updateCellMocks.ts b/packages/codemods/src/codemods/v0.39.x/updateCellMocks/updateCellMocks.ts index abdaff996bc5..18765ad9af0a 100644 --- a/packages/codemods/src/codemods/v0.39.x/updateCellMocks/updateCellMocks.ts +++ b/packages/codemods/src/codemods/v0.39.x/updateCellMocks/updateCellMocks.ts @@ -7,10 +7,10 @@ export default function transform(file: FileInfo, api: API) { const exportDeclarations = ast.find(j.ExportNamedDeclaration) const createStandardMockFunction = ( - originalMockObject: ASTPath + originalMockObject: ASTPath, ) => { const newMockedObject = j.objectExpression( - originalMockObject.value.properties + originalMockObject.value.properties, ) const returnStatement = j.returnStatement(newMockedObject) @@ -18,7 +18,7 @@ export default function transform(file: FileInfo, api: API) { return j.variableDeclarator( //@MARK cheating... not sure how to add const j.identifier('const standard'), - j.arrowFunctionExpression([], j.blockStatement([returnStatement])) + j.arrowFunctionExpression([], j.blockStatement([returnStatement])), ) } diff --git a/packages/codemods/src/codemods/v0.39.x/updateCellMocks/updateCellMocks.yargs.ts b/packages/codemods/src/codemods/v0.39.x/updateCellMocks/updateCellMocks.yargs.ts index ffb50251d116..764a7d2ce837 100644 --- a/packages/codemods/src/codemods/v0.39.x/updateCellMocks/updateCellMocks.yargs.ts +++ b/packages/codemods/src/codemods/v0.39.x/updateCellMocks/updateCellMocks.yargs.ts @@ -33,6 +33,6 @@ export const handler = () => { } setOutput('All done! Run `yarn rw lint --fix` to prettify your code') - } + }, ) } diff --git a/packages/codemods/src/codemods/v0.39.x/updateRouterParamTypes/updateRouterParamTypes.ts b/packages/codemods/src/codemods/v0.39.x/updateRouterParamTypes/updateRouterParamTypes.ts index 5b8a4584b1c6..3336a260d55f 100644 --- a/packages/codemods/src/codemods/v0.39.x/updateRouterParamTypes/updateRouterParamTypes.ts +++ b/packages/codemods/src/codemods/v0.39.x/updateRouterParamTypes/updateRouterParamTypes.ts @@ -47,7 +47,7 @@ export default function transform(file: FileInfo, api: API) { } const mapToNewSyntax = ( - allParamTypeProperties: ObjectExpression['properties'] + allParamTypeProperties: ObjectExpression['properties'], ) => { // allParamTypeProperties here is array of following marked as 👉 /* @@ -74,7 +74,7 @@ export default function transform(file: FileInfo, api: API) { // As they're quite edgecase-ey // like paramTypes={{...myParams}} (spreadelement) console.warn( - 'Unable to update your custom Route parameters. Please follow manual instructions' + 'Unable to update your custom Route parameters. Please follow manual instructions', ) return } @@ -117,7 +117,7 @@ export default function transform(file: FileInfo, api: API) { j.JSXAttribute, { name: { name: 'paramTypes' }, - } + }, ) paramTypeProp.forEach((prop) => { const paramTypeValue = (prop?.value?.value as JSXExpressionContainer) diff --git a/packages/codemods/src/codemods/v0.39.x/updateRouterParamTypes/updateRouterParamTypes.yargs.ts b/packages/codemods/src/codemods/v0.39.x/updateRouterParamTypes/updateRouterParamTypes.yargs.ts index 4b7cdce0602c..5d19cfa505dd 100644 --- a/packages/codemods/src/codemods/v0.39.x/updateRouterParamTypes/updateRouterParamTypes.yargs.ts +++ b/packages/codemods/src/codemods/v0.39.x/updateRouterParamTypes/updateRouterParamTypes.yargs.ts @@ -27,6 +27,6 @@ export const handler = () => { targetPaths: [routesFilePath], }) } - } + }, ) } diff --git a/packages/codemods/src/codemods/v0.44.x/updateJestConfig/updateJestConfig.transform.js b/packages/codemods/src/codemods/v0.44.x/updateJestConfig/updateJestConfig.transform.js index 121867e6d788..435145592f73 100644 --- a/packages/codemods/src/codemods/v0.44.x/updateJestConfig/updateJestConfig.transform.js +++ b/packages/codemods/src/codemods/v0.44.x/updateJestConfig/updateJestConfig.transform.js @@ -10,13 +10,13 @@ export default async function transform(file, api) { const match = file.source .trim() .match( - /module.exports = require\('@redwoodjs\/testing\/config\/jest\/(?api|web)'\)/ + /module.exports = require\('@redwoodjs\/testing\/config\/jest\/(?api|web)'\)/, ) if (match?.length) { file.source = await fetchFileFromTemplate( 'main', - `${match.groups?.side}/jest.config.js` + `${match.groups?.side}/jest.config.js`, ) return file.source @@ -38,8 +38,8 @@ export default async function transform(file, api) { oldConfig.replaceWith( ["rootDir: '../'", "preset: '@redwoodjs/testing/config/jest/web'"].join( - ',\n' - ) + ',\n', + ), ) return ast.toSource({ trailingComma: true }) diff --git a/packages/codemods/src/codemods/v0.44.x/updateJestConfig/updateJestConfig.ts b/packages/codemods/src/codemods/v0.44.x/updateJestConfig/updateJestConfig.ts index 420f07369e19..4651b9792f50 100644 --- a/packages/codemods/src/codemods/v0.44.x/updateJestConfig/updateJestConfig.ts +++ b/packages/codemods/src/codemods/v0.44.x/updateJestConfig/updateJestConfig.ts @@ -28,7 +28,7 @@ export default async function updateJestConfig() { if (!fs.existsSync(rootJestConfigPath)) { const rootJestConfigTemplate = await fetchFileFromTemplate( tag, - 'jest.config.js' + 'jest.config.js', ) fs.writeFileSync(rootJestConfigPath, rootJestConfigTemplate) } diff --git a/packages/codemods/src/codemods/v0.48.x/renameVerifierTimestamp/renameVerifierTimestamp.ts b/packages/codemods/src/codemods/v0.48.x/renameVerifierTimestamp/renameVerifierTimestamp.ts index c234d68ec43c..9b8158ca2266 100644 --- a/packages/codemods/src/codemods/v0.48.x/renameVerifierTimestamp/renameVerifierTimestamp.ts +++ b/packages/codemods/src/codemods/v0.48.x/renameVerifierTimestamp/renameVerifierTimestamp.ts @@ -3,7 +3,7 @@ import type core from 'jscodeshift' function renameTimestamp( j: core.JSCodeshift, - optionsObject: ASTNode | ASTNode[] | ASTPath | ASTPath[] + optionsObject: ASTNode | ASTNode[] | ASTPath | ASTPath[], ) { j(optionsObject) .find(j.ObjectProperty, { key: { name: 'timestamp' } }) diff --git a/packages/codemods/src/codemods/v0.48.x/renameVerifierTimestamp/renameVerifierTimestamp.yargs.ts b/packages/codemods/src/codemods/v0.48.x/renameVerifierTimestamp/renameVerifierTimestamp.yargs.ts index aac582d1ccab..24050c9963b4 100644 --- a/packages/codemods/src/codemods/v0.48.x/renameVerifierTimestamp/renameVerifierTimestamp.yargs.ts +++ b/packages/codemods/src/codemods/v0.48.x/renameVerifierTimestamp/renameVerifierTimestamp.yargs.ts @@ -45,6 +45,6 @@ export const handler = () => { } catch (e: any) { setError('Failed to codemod your project \n' + e?.message) } - } + }, ) } diff --git a/packages/codemods/src/codemods/v0.48.x/upgradeYarn/upgradeYarn.ts b/packages/codemods/src/codemods/v0.48.x/upgradeYarn/upgradeYarn.ts index 8c1dac199ccc..34b82be898c9 100644 --- a/packages/codemods/src/codemods/v0.48.x/upgradeYarn/upgradeYarn.ts +++ b/packages/codemods/src/codemods/v0.48.x/upgradeYarn/upgradeYarn.ts @@ -14,7 +14,7 @@ async function upgradeYarn() { { shell: true, cwd: rwPaths.base, - } + }, ) if (corepackPreparePO.status !== 0) { @@ -33,7 +33,7 @@ async function upgradeYarn() { 'For more information, see:', '- https://yarnpkg.com/getting-started/install', '- https://nodejs.org/dist/latest/docs/api/corepack.html', - ].join('\n') + ].join('\n'), ) } @@ -71,7 +71,7 @@ async function upgradeYarn() { 'nodeLinker: node-modules', '', `yarnPath: .yarn/releases/yarn-${yarnVersion}.cjs`, - ].join('\n') + ].join('\n'), ) const gitignorePath = path.join(rwPaths.base, '.gitignore') @@ -86,7 +86,7 @@ async function upgradeYarn() { '!.yarn/releases', '!.yarn/sdks', '!.yarn/versions', - ].join('\n')}` + ].join('\n')}`, ) console.log('Installing...') diff --git a/packages/codemods/src/codemods/v0.50.x/updateDevFatalErrorPage/updateDevFatalErrorPage.ts b/packages/codemods/src/codemods/v0.50.x/updateDevFatalErrorPage/updateDevFatalErrorPage.ts index 26abf5e270d6..9bbdba323e0d 100644 --- a/packages/codemods/src/codemods/v0.50.x/updateDevFatalErrorPage/updateDevFatalErrorPage.ts +++ b/packages/codemods/src/codemods/v0.50.x/updateDevFatalErrorPage/updateDevFatalErrorPage.ts @@ -28,7 +28,7 @@ export const updateDevFatalErrorPage = async () => { */ for (const [_dir, filenamesToUrls] of Object.entries(dirs)) { const isTSPage = fs.existsSync( - path.join(webFatalErrorPagesDir, 'FatalErrorPage.tsx') + path.join(webFatalErrorPagesDir, 'FatalErrorPage.tsx'), ) for (const [filename, url] of Object.entries(filenamesToUrls)) { diff --git a/packages/codemods/src/codemods/v2.3.x/tsconfigForRouteHooks/tsconfigForRouteHooks.ts b/packages/codemods/src/codemods/v2.3.x/tsconfigForRouteHooks/tsconfigForRouteHooks.ts index d081b8d8d097..dafa47a5335a 100644 --- a/packages/codemods/src/codemods/v2.3.x/tsconfigForRouteHooks/tsconfigForRouteHooks.ts +++ b/packages/codemods/src/codemods/v2.3.x/tsconfigForRouteHooks/tsconfigForRouteHooks.ts @@ -8,12 +8,12 @@ export default async function addApiAliasToTsConfig() { const webConfigPath = ts.findConfigFile( getPaths().web.base, - ts.sys.fileExists + ts.sys.fileExists, ) if (!webConfigPath) { throw new Error( - 'Could not find tsconfig.json in your web side. Please follow release notes to update your config manually.' + 'Could not find tsconfig.json in your web side. Please follow release notes to update your config manually.', ) } @@ -21,7 +21,7 @@ export default async function addApiAliasToTsConfig() { // Also why I'm not using jscodeshift here - sadly I can't preserve the comments const { config: webConfig } = ts.parseConfigFileTextToJson( webConfigPath, - ts.sys.readFile(webConfigPath) as string // If file exists, it has contents + ts.sys.readFile(webConfigPath) as string, // If file exists, it has contents ) if (webConfig && webConfig?.compilerOptions) { @@ -41,11 +41,11 @@ export default async function addApiAliasToTsConfig() { ts.sys.writeFile( webConfigPath, // @NOTE: prettier will remove trailing commas, but whatever - await prettify(JSON.stringify(updatedConfig), { parser: 'json' }) + await prettify(JSON.stringify(updatedConfig), { parser: 'json' }), ) } else { throw new Error( - 'Could not read your web/tsconfig.json. Please follow release notes to update your config manually.' + 'Could not read your web/tsconfig.json. Please follow release notes to update your config manually.', ) } } diff --git a/packages/codemods/src/codemods/v2.x.x/configureFastify/configureFastify.ts b/packages/codemods/src/codemods/v2.x.x/configureFastify/configureFastify.ts index 17ac11a54a3c..f106fb729139 100644 --- a/packages/codemods/src/codemods/v2.x.x/configureFastify/configureFastify.ts +++ b/packages/codemods/src/codemods/v2.x.x/configureFastify/configureFastify.ts @@ -13,9 +13,9 @@ export default function transform(file: FileInfo, api: API) { j.assignmentExpression( '=', j.identifier('module.exports'), - j.identifier('{ config }') - ) - ) + j.identifier('{ config }'), + ), + ), ) } }) diff --git a/packages/codemods/src/codemods/v2.x.x/configureFastify/configureFastify.yargs.ts b/packages/codemods/src/codemods/v2.x.x/configureFastify/configureFastify.yargs.ts index a55f573bf45a..f76b4eff6bd1 100644 --- a/packages/codemods/src/codemods/v2.x.x/configureFastify/configureFastify.yargs.ts +++ b/packages/codemods/src/codemods/v2.x.x/configureFastify/configureFastify.yargs.ts @@ -36,25 +36,25 @@ export const handler = () => { // They don't show up in tests cause we run prettier. Let's do the same here. fs.writeFileSync( API_SERVER_CONFIG_PATH, - await prettify(fs.readFileSync(API_SERVER_CONFIG_PATH, 'utf-8')) + await prettify(fs.readFileSync(API_SERVER_CONFIG_PATH, 'utf-8')), ) setOutput('All done!') } else { const res = await fetch( - 'https://raw.githubusercontent.com/redwoodjs/redwood/main/packages/create-redwood-app/template/api/server.config.js' + 'https://raw.githubusercontent.com/redwoodjs/redwood/main/packages/create-redwood-app/template/api/server.config.js', ) const text = await res.text() const NEW_API_SERVER_CONFIG_PATH = path.join( getPaths().api.base, - 'server.config.js' + 'server.config.js', ) fs.writeFileSync(NEW_API_SERVER_CONFIG_PATH, await prettify(text)) setOutput( - 'Done! No server.config.js found, so we updated your project to use the latest version.' + 'Done! No server.config.js found, so we updated your project to use the latest version.', ) } }) diff --git a/packages/codemods/src/codemods/v2.x.x/updateResolverTypes/updateResolverTypes.ts b/packages/codemods/src/codemods/v2.x.x/updateResolverTypes/updateResolverTypes.ts index 3c8def0c27bd..2720f62606eb 100644 --- a/packages/codemods/src/codemods/v2.x.x/updateResolverTypes/updateResolverTypes.ts +++ b/packages/codemods/src/codemods/v2.x.x/updateResolverTypes/updateResolverTypes.ts @@ -2,7 +2,7 @@ import type { API, FileInfo, TSTypeAnnotation } from 'jscodeshift' import { Identifier, TSTypeReference } from 'jscodeshift' const isTypeReference = ( - typeAnnotation: TSTypeAnnotation['typeAnnotation'] + typeAnnotation: TSTypeAnnotation['typeAnnotation'], ): typeAnnotation is TSTypeReference => TSTypeReference.check(typeAnnotation) const getTypeName = (node: TSTypeReference) => { @@ -36,7 +36,7 @@ export default function transform(file: FileInfo, api: API) { }) .forEach((importStatement) => { importStatement.node.specifiers?.push( - j.importSpecifier(j.identifier(importName)) + j.importSpecifier(j.identifier(importName)), ) }) } @@ -69,13 +69,13 @@ export default function transform(file: FileInfo, api: API) { const newTypeName = originalTypeName.replace( 'Resolvers', - 'RelationResolvers' + 'RelationResolvers', ) console.log(`Converting ${originalTypeName} to ${newTypeName}....`) path.replace( - j.tsTypeAnnotation(j.tsTypeReference(j.identifier(newTypeName))) + j.tsTypeAnnotation(j.tsTypeReference(j.identifier(newTypeName))), ) findImportFromGqlTypes(originalTypeName)?.remove() diff --git a/packages/codemods/src/codemods/v4.2.x/updateClerkGetCurrentUser/updateClerkGetCurrentUser.ts b/packages/codemods/src/codemods/v4.2.x/updateClerkGetCurrentUser/updateClerkGetCurrentUser.ts index b90d69aac46e..6efff1d71959 100644 --- a/packages/codemods/src/codemods/v4.2.x/updateClerkGetCurrentUser/updateClerkGetCurrentUser.ts +++ b/packages/codemods/src/codemods/v4.2.x/updateClerkGetCurrentUser/updateClerkGetCurrentUser.ts @@ -58,7 +58,7 @@ export default function transform(file: FileInfo, api: API) { path.value.argument as ObjectExpression ).properties.filter( (property) => - property.type !== 'SpreadElement' && property.name !== 'decoded' + property.type !== 'SpreadElement' && property.name !== 'decoded', ) properties.push(j.spreadElement(j.identifier(newReturn))) diff --git a/packages/codemods/src/codemods/v4.x.x/useArmor/__tests__/useArmor.test.ts b/packages/codemods/src/codemods/v4.x.x/useArmor/__tests__/useArmor.test.ts index 3427e56b5a63..182ca9a98b74 100644 --- a/packages/codemods/src/codemods/v4.x.x/useArmor/__tests__/useArmor.test.ts +++ b/packages/codemods/src/codemods/v4.x.x/useArmor/__tests__/useArmor.test.ts @@ -63,7 +63,7 @@ describe('useArmor', () => { // Disconnect from your database with an unhandled exception. db.$disconnect() }, - })` + })`, ) }) }) diff --git a/packages/codemods/src/codemods/v4.x.x/useArmor/useArmor.ts b/packages/codemods/src/codemods/v4.x.x/useArmor/useArmor.ts index eda420ba469c..2d4059746663 100644 --- a/packages/codemods/src/codemods/v4.x.x/useArmor/useArmor.ts +++ b/packages/codemods/src/codemods/v4.x.x/useArmor/useArmor.ts @@ -30,19 +30,19 @@ export default function transform(file: FileInfo, api: API) { depthLimitOptionsProp.replaceWith([ j.identifier( - `armorConfig: { maxDepth: { n: ${depthLimitOptionValue || 11} } }` + `armorConfig: { maxDepth: { n: ${depthLimitOptionValue || 11} } }`, ), ]) console.info( `useArmor configured to use existing maxDepth of ${ depthLimitOptionValue || 11 - }.` + }.`, ) } } else { console.info( - `No mods needed to createGraphQLHandler config in ${file.path}. Skipping...` + `No mods needed to createGraphQLHandler config in ${file.path}. Skipping...`, ) } }) diff --git a/packages/codemods/src/codemods/v4.x.x/useArmor/useArmor.yargs.ts b/packages/codemods/src/codemods/v4.x.x/useArmor/useArmor.yargs.ts index 68a6d6d9ae64..dee82cea84bf 100644 --- a/packages/codemods/src/codemods/v4.x.x/useArmor/useArmor.yargs.ts +++ b/packages/codemods/src/codemods/v4.x.x/useArmor/useArmor.yargs.ts @@ -22,7 +22,7 @@ export const handler = () => { }) setOutput( - 'Updating createGraphQLHandler for useArmor config is done! Run `yarn rw lint --fix` to prettify your code' + 'Updating createGraphQLHandler for useArmor config is done! Run `yarn rw lint --fix` to prettify your code', ) }) } diff --git a/packages/codemods/src/codemods/v5.x.x/cellQueryResult/cellQueryResult.ts b/packages/codemods/src/codemods/v5.x.x/cellQueryResult/cellQueryResult.ts index 0eaa855c0715..294be9294436 100644 --- a/packages/codemods/src/codemods/v5.x.x/cellQueryResult/cellQueryResult.ts +++ b/packages/codemods/src/codemods/v5.x.x/cellQueryResult/cellQueryResult.ts @@ -65,21 +65,21 @@ export default function transform(file: FileInfo, api: API) { usedProperty.value.type !== 'Identifier' ) { throw new Error( - 'Unable to process a parameter within the cell function' + 'Unable to process a parameter within the cell function', ) } const prop = j.property( 'init', j.identifier(usedProperty.key.name), - j.identifier(usedProperty.value.name) + j.identifier(usedProperty.value.name), ) // Use an alias if one was previously defined by the user prop.shorthand = usedProperty.shorthand return prop - } - ) - ) - ) + }, + ), + ), + ), ) // Remove the existing function parameters corresponding to previously spread variables firstParameter.properties = firstParameter.properties.filter( @@ -88,18 +88,18 @@ export default function transform(file: FileInfo, api: API) { throw new Error('Unable to process a parameter') } return !nonSpreadVariables.includes(property.key.name) - } + }, ) } } else { console.warn( - `The first parameter to '${variableName}' was not an object and we could not process this.` + `The first parameter to '${variableName}' was not an object and we could not process this.`, ) } } } else { console.warn( - `'${variableName}' is not a function and we could not process this.` + `'${variableName}' is not a function and we could not process this.`, ) } } else { diff --git a/packages/codemods/src/codemods/v5.x.x/cellQueryResult/cellQueryResult.yargs.ts b/packages/codemods/src/codemods/v5.x.x/cellQueryResult/cellQueryResult.yargs.ts index 6a1189654647..bf60463ca61a 100644 --- a/packages/codemods/src/codemods/v5.x.x/cellQueryResult/cellQueryResult.yargs.ts +++ b/packages/codemods/src/codemods/v5.x.x/cellQueryResult/cellQueryResult.yargs.ts @@ -17,7 +17,7 @@ export const handler = () => { }) setOutput( - 'Updates to your cells are complete! Please run `yarn rw lint --fix` to prettify your code' + 'Updates to your cells are complete! Please run `yarn rw lint --fix` to prettify your code', ) }) } diff --git a/packages/codemods/src/codemods/v5.x.x/detectEmptyCells/detectEmptyCells.ts b/packages/codemods/src/codemods/v5.x.x/detectEmptyCells/detectEmptyCells.ts index 54c4f45ba21d..5bd54fbc61d7 100644 --- a/packages/codemods/src/codemods/v5.x.x/detectEmptyCells/detectEmptyCells.ts +++ b/packages/codemods/src/codemods/v5.x.x/detectEmptyCells/detectEmptyCells.ts @@ -34,7 +34,7 @@ async function detectEmptyCells(taskContext: TaskInnerAPI) { if (susceptibleCells.length === 0 && warnings.length === 0) { taskContext.setOutput( - "None of your project's Cells are susceptible to the new `isDataEmpty` behavior." + "None of your project's Cells are susceptible to the new `isDataEmpty` behavior.", ) return } @@ -48,7 +48,7 @@ async function detectEmptyCells(taskContext: TaskInnerAPI) { '', susceptibleCells.map((c) => `• ${c}`).join('\n'), '', - ].join('\n') + ].join('\n'), ) } @@ -66,7 +66,7 @@ async function detectEmptyCells(taskContext: TaskInnerAPI) { '', "You'll have to audit them manually.", '', - ].join('\n') + ].join('\n'), ) } @@ -75,7 +75,7 @@ async function detectEmptyCells(taskContext: TaskInnerAPI) { 'The new behavior is documented in detail on the forums: https://community.redwoodjs.com/t/redwood-v5-0-0-rc-is-now-available/4715.', "It's most likely what you want, but consider whether it affects you.", "If you'd like to revert to the old behavior, you can override the `isDataEmpty` function.", - ].join('\n') + ].join('\n'), ) const taskContextMethod = warnings.length > 0 ? 'setWarning' : 'setOutput' diff --git a/packages/codemods/src/codemods/v5.x.x/detectEmptyCells/detectEmptyCells.yargs.ts b/packages/codemods/src/codemods/v5.x.x/detectEmptyCells/detectEmptyCells.yargs.ts index b0c30b02d3d5..718ed4f445c8 100644 --- a/packages/codemods/src/codemods/v5.x.x/detectEmptyCells/detectEmptyCells.yargs.ts +++ b/packages/codemods/src/codemods/v5.x.x/detectEmptyCells/detectEmptyCells.yargs.ts @@ -16,9 +16,9 @@ export const handler = () => { } catch (e: any) { taskContext.setError( 'Failed to detect cells susceptible to the new Empty behavior in your project \n' + - e?.message + e?.message, ) } - } + }, ) } diff --git a/packages/codemods/src/codemods/v5.x.x/renameValidateWith/renameValidateWith.yargs.ts b/packages/codemods/src/codemods/v5.x.x/renameValidateWith/renameValidateWith.yargs.ts index b36f01ad02d7..afbaf3ea0e3f 100644 --- a/packages/codemods/src/codemods/v5.x.x/renameValidateWith/renameValidateWith.yargs.ts +++ b/packages/codemods/src/codemods/v5.x.x/renameValidateWith/renameValidateWith.yargs.ts @@ -29,6 +29,6 @@ export const handler = () => { }) setOutput('All done! Run `yarn rw lint --fix` to prettify your code') - } + }, ) } diff --git a/packages/codemods/src/codemods/v5.x.x/updateAuth0ToV2/updateAuth0ToV2.ts b/packages/codemods/src/codemods/v5.x.x/updateAuth0ToV2/updateAuth0ToV2.ts index bd5214b179e4..0e1e80a5314d 100644 --- a/packages/codemods/src/codemods/v5.x.x/updateAuth0ToV2/updateAuth0ToV2.ts +++ b/packages/codemods/src/codemods/v5.x.x/updateAuth0ToV2/updateAuth0ToV2.ts @@ -22,8 +22,8 @@ export default function transform(file: FileInfo, api: API) { .insertAfter( j.objectProperty( j.identifier('authorizationParams'), - j.objectExpression(nodes) - ) + j.objectExpression(nodes), + ), ) ast.find(j.Identifier, { name: 'client_id' }).replaceWith('clientId') diff --git a/packages/codemods/src/codemods/v5.x.x/updateAuth0ToV2/updateAuth0ToV2.yargs.ts b/packages/codemods/src/codemods/v5.x.x/updateAuth0ToV2/updateAuth0ToV2.yargs.ts index 6e0cf1a30f58..3135e9a4c1e7 100644 --- a/packages/codemods/src/codemods/v5.x.x/updateAuth0ToV2/updateAuth0ToV2.yargs.ts +++ b/packages/codemods/src/codemods/v5.x.x/updateAuth0ToV2/updateAuth0ToV2.yargs.ts @@ -23,7 +23,7 @@ export const handler = () => { }) } catch { console.error( - "Couldn't update @auth0/auth0-spa-js; you'll have to upgrade it manually to the latest v2.x.x version" + "Couldn't update @auth0/auth0-spa-js; you'll have to upgrade it manually to the latest v2.x.x version", ) } diff --git a/packages/codemods/src/codemods/v5.x.x/updateNodeEngineTo18/updateNodeEngineTo18.yargs.ts b/packages/codemods/src/codemods/v5.x.x/updateNodeEngineTo18/updateNodeEngineTo18.yargs.ts index bfde2d9e918e..42912324bf1d 100644 --- a/packages/codemods/src/codemods/v5.x.x/updateNodeEngineTo18/updateNodeEngineTo18.yargs.ts +++ b/packages/codemods/src/codemods/v5.x.x/updateNodeEngineTo18/updateNodeEngineTo18.yargs.ts @@ -16,6 +16,6 @@ export const handler = () => { } catch (e: any) { setError('Failed to codemod your project \n' + e?.message) } - } + }, ) } diff --git a/packages/codemods/src/codemods/v5.x.x/upgradeToReact18/__tests__/upgradeToReact18.test.ts b/packages/codemods/src/codemods/v5.x.x/upgradeToReact18/__tests__/upgradeToReact18.test.ts index f5190a19e90d..e27b184a7ecc 100644 --- a/packages/codemods/src/codemods/v5.x.x/upgradeToReact18/__tests__/upgradeToReact18.test.ts +++ b/packages/codemods/src/codemods/v5.x.x/upgradeToReact18/__tests__/upgradeToReact18.test.ts @@ -7,7 +7,7 @@ describe('upgradeToReact18', () => { it('Checks and transforms the react root', async () => { await matchFolderTransform( () => checkAndTransformReactRoot({ setWarning: () => {} }), - 'default' + 'default', ) }) }) diff --git a/packages/codemods/src/codemods/v5.x.x/upgradeToReact18/upgradeToReact18.ts b/packages/codemods/src/codemods/v5.x.x/upgradeToReact18/upgradeToReact18.ts index 5fb15c617966..bef60720a7b6 100644 --- a/packages/codemods/src/codemods/v5.x.x/upgradeToReact18/upgradeToReact18.ts +++ b/packages/codemods/src/codemods/v5.x.x/upgradeToReact18/upgradeToReact18.ts @@ -20,7 +20,7 @@ function checkAndTransformReactRoot(taskContext: TaskInnerAPI) { if (!reactRootHTML) { throw new Error( - `Couldn't get HTML in react root (div with id="redwood-app")` + `Couldn't get HTML in react root (div with id="redwood-app")`, ) } @@ -39,7 +39,7 @@ function checkAndTransformReactRoot(taskContext: TaskInnerAPI) { '', 'React expects to control this DOM node completely. This codemod has moved the children outside the react root,', 'but consider moving them into a layout.', - ].join('\n') + ].join('\n'), ) } @@ -54,11 +54,11 @@ async function upgradeReactDepsTo18() { const webPackageJSONPath = path.join( redwoodProjectPaths.web.base, - 'package.json' + 'package.json', ) const webPackageJSON = JSON.parse( - fs.readFileSync(webPackageJSONPath, 'utf-8') + fs.readFileSync(webPackageJSONPath, 'utf-8'), ) const latestReactVersion = '18.2.0' @@ -66,7 +66,7 @@ async function upgradeReactDepsTo18() { for (const requiredReactDep of ['react', 'react-dom']) { if (!Object.hasOwn(webPackageJSON.dependencies, requiredReactDep)) { throw new Error( - `Couldn't find ${requiredReactDep} in web/package.json dependencies` + `Couldn't find ${requiredReactDep} in web/package.json dependencies`, ) } @@ -90,7 +90,7 @@ async function checkAndUpdateCustomWebIndex(taskContext: TaskInnerAPI) { } const customWebIndexFound = Object.entries(bundlerToCustomWebIndex).find( - ([, filepath]) => fs.existsSync(filepath) + ([, filepath]) => fs.existsSync(filepath), ) if (!customWebIndexFound) { @@ -103,7 +103,7 @@ async function checkAndUpdateCustomWebIndex(taskContext: TaskInnerAPI) { [ `We updated the custom web index for you at ${customWebIndexFound[1]}.`, " If you made manual changes to this file, you'll have to copy them over manually from the diff.", - ].join('\n') + ].join('\n'), ) } diff --git a/packages/codemods/src/codemods/v6.x.x/convertJsToJsx/convertJsToJsx.ts b/packages/codemods/src/codemods/v6.x.x/convertJsToJsx/convertJsToJsx.ts index 2b02f44862ec..1edf4e636c47 100644 --- a/packages/codemods/src/codemods/v6.x.x/convertJsToJsx/convertJsToJsx.ts +++ b/packages/codemods/src/codemods/v6.x.x/convertJsToJsx/convertJsToJsx.ts @@ -14,7 +14,7 @@ export default function transform(file: FileInfo, api: API) { if (containsJSX) { fs.renameSync( file.path, - file.path.substring(0, file.path.lastIndexOf('.')) + '.jsx' + file.path.substring(0, file.path.lastIndexOf('.')) + '.jsx', ) } diff --git a/packages/codemods/src/codemods/v6.x.x/convertJsToJsx/convertJsToJsx.yargs.ts b/packages/codemods/src/codemods/v6.x.x/convertJsToJsx/convertJsToJsx.yargs.ts index 0621e4e41c93..4974a1421620 100644 --- a/packages/codemods/src/codemods/v6.x.x/convertJsToJsx/convertJsToJsx.yargs.ts +++ b/packages/codemods/src/codemods/v6.x.x/convertJsToJsx/convertJsToJsx.yargs.ts @@ -19,7 +19,7 @@ export const handler = () => { }) setOutput( - 'All done! Your file contents have not been changed just the extension.' + 'All done! Your file contents have not been changed just the extension.', ) }) } diff --git a/packages/codemods/src/codemods/v6.x.x/entryClientNullCheck/entryClientNullCheck.ts b/packages/codemods/src/codemods/v6.x.x/entryClientNullCheck/entryClientNullCheck.ts index 21a7c94a3837..ff49f5f1b100 100644 --- a/packages/codemods/src/codemods/v6.x.x/entryClientNullCheck/entryClientNullCheck.ts +++ b/packages/codemods/src/codemods/v6.x.x/entryClientNullCheck/entryClientNullCheck.ts @@ -12,7 +12,7 @@ export default function transform(file: FileInfo, api: API) { // If it doesn't exist, bail out and let the user know if (node.length === 0) { console.warn( - "\nCould not find 'redwoodAppElement' variable declaration. Please make the necessary changes to your 'web/src/index.js' file manually.\n" + "\nCould not find 'redwoodAppElement' variable declaration. Please make the necessary changes to your 'web/src/index.js' file manually.\n", ) return file.source } @@ -25,12 +25,12 @@ export default function transform(file: FileInfo, api: API) { j.throwStatement( j.newExpression(j.identifier('Error'), [ j.literal( - "Could not find an element with ID 'redwood-app'. Please ensure it exists in your 'web/src/index.html' file." + "Could not find an element with ID 'redwood-app'. Please ensure it exists in your 'web/src/index.html' file.", ), - ]) + ]), ), - ]) - ) + ]), + ), ) return ast.toSource() diff --git a/packages/codemods/src/codemods/v6.x.x/processEnvDotNotation/processEnvDotNotation.ts b/packages/codemods/src/codemods/v6.x.x/processEnvDotNotation/processEnvDotNotation.ts index cdc4737ebe60..6307c86a689d 100644 --- a/packages/codemods/src/codemods/v6.x.x/processEnvDotNotation/processEnvDotNotation.ts +++ b/packages/codemods/src/codemods/v6.x.x/processEnvDotNotation/processEnvDotNotation.ts @@ -20,7 +20,7 @@ export default function transform(file: FileInfo, api: API) { if (j.StringLiteral.check(envVarName)) { const dotNotation = j.memberExpression( j.memberExpression(j.identifier('process'), j.identifier('env')), - j.identifier(envVarName.value) + j.identifier(envVarName.value), ) j(path).replaceWith(dotNotation) } diff --git a/packages/codemods/src/codemods/v6.x.x/replaceComponentSvgs/replaceComponentSvgs.ts b/packages/codemods/src/codemods/v6.x.x/replaceComponentSvgs/replaceComponentSvgs.ts index dfbee82b58eb..d0f406b5a696 100644 --- a/packages/codemods/src/codemods/v6.x.x/replaceComponentSvgs/replaceComponentSvgs.ts +++ b/packages/codemods/src/codemods/v6.x.x/replaceComponentSvgs/replaceComponentSvgs.ts @@ -17,7 +17,7 @@ async function convertSvgToReactComponent( svgFilePath: string, outputPath: string, componentName: string, - typescript: boolean + typescript: boolean, ) { const svgContents = await fs.readFile(svgFilePath, 'utf-8') @@ -30,7 +30,7 @@ async function convertSvgToReactComponent( }, { componentName: componentName, - } + }, ) await fs.writeFile(outputPath, jsCode) @@ -59,7 +59,7 @@ export default async function transform(file: FileInfo, api: API) { return Boolean( source && typeof source.value === 'string' && - source.value.endsWith('.svg') + source.value.endsWith('.svg'), ) }) @@ -153,7 +153,7 @@ export default async function transform(file: FileInfo, api: API) { svgsToConvert.map(async (svg) => { const svgFileNameWithoutExtension = path.basename( svg.filePath, - path.extname(svg.filePath) + path.extname(svg.filePath), ) const componentName = pascalcase(svgFileNameWithoutExtension) @@ -163,7 +163,7 @@ export default async function transform(file: FileInfo, api: API) { // The absolute path to the new file const outputPath = path.join( path.dirname(svg.filePath), - `${newFileName}.${isTS ? 'tsx' : 'jsx'}` + `${newFileName}.${isTS ? 'tsx' : 'jsx'}`, ) try { @@ -171,11 +171,11 @@ export default async function transform(file: FileInfo, api: API) { svg.filePath, outputPath, componentName, - isTS + isTS, ) } catch (error: any) { console.error( - `Error converting ${svg.filePath} to React component: ${error.message}` + `Error converting ${svg.filePath} to React component: ${error.message}`, ) // Don't proceed if SVGr fails @@ -187,9 +187,9 @@ export default async function transform(file: FileInfo, api: API) { // Use extname, incase ext casing does not match svg.importSourcePath.value = svg.importSourcePath.value.replace( `${svgFileNameWithoutExtension}${path.extname(svg.filePath)}`, - newFileName + newFileName, ) - }) + }), ) } diff --git a/packages/codemods/src/codemods/v6.x.x/updateDevFatalErrorPage/updateDevFatalErrorPage.ts b/packages/codemods/src/codemods/v6.x.x/updateDevFatalErrorPage/updateDevFatalErrorPage.ts index ba19dd9c9da8..b805453f4614 100644 --- a/packages/codemods/src/codemods/v6.x.x/updateDevFatalErrorPage/updateDevFatalErrorPage.ts +++ b/packages/codemods/src/codemods/v6.x.x/updateDevFatalErrorPage/updateDevFatalErrorPage.ts @@ -18,10 +18,10 @@ export const updateDevFatalErrorPage = async () => { 'https://raw.githubusercontent.com/redwoodjs/redwood/29138f59dc5abe7b3d3c2a11c6e6f5fee32580c5/packages/create-redwood-app/templates/ts/web/src/pages/FatalErrorPage/FatalErrorPage.tsx' const isTsxPage = fs.existsSync( - path.join(webFatalErrorPagesDir, 'FatalErrorPage.tsx') + path.join(webFatalErrorPagesDir, 'FatalErrorPage.tsx'), ) const isJsxPage = fs.existsSync( - path.join(webFatalErrorPagesDir, 'FatalErrorPage.jsx') + path.join(webFatalErrorPagesDir, 'FatalErrorPage.jsx'), ) const ext = isTsxPage ? 'tsx' : isJsxPage ? 'jsx' : 'js' diff --git a/packages/codemods/src/codemods/v6.x.x/updateThemeConfig/updateThemeConfig.ts b/packages/codemods/src/codemods/v6.x.x/updateThemeConfig/updateThemeConfig.ts index a5b71411c50b..599d81be2ff9 100644 --- a/packages/codemods/src/codemods/v6.x.x/updateThemeConfig/updateThemeConfig.ts +++ b/packages/codemods/src/codemods/v6.x.x/updateThemeConfig/updateThemeConfig.ts @@ -39,7 +39,7 @@ export default function transform(file: FileInfo, api: API) { // Add export default statement const exportDefaultStatement = j.exportDefaultDeclaration( - j.identifier(themeObjectName) + j.identifier(themeObjectName), ) j(path.parentPath).insertAfter(exportDefaultStatement) diff --git a/packages/codemods/src/codemods/v7.x.x/updateGraphQLConfig/updateGraphqlConfig.ts b/packages/codemods/src/codemods/v7.x.x/updateGraphQLConfig/updateGraphqlConfig.ts index e00172c980d7..3448fd89c773 100644 --- a/packages/codemods/src/codemods/v7.x.x/updateGraphQLConfig/updateGraphqlConfig.ts +++ b/packages/codemods/src/codemods/v7.x.x/updateGraphQLConfig/updateGraphqlConfig.ts @@ -10,7 +10,7 @@ export const updateGraphqlConfig = async () => { // TODO: Have to come back here to update the URL when we have a more // stable location than main // 'https://raw.githubusercontent.com/redwoodjs/redwood/release/major/v7.0.0/packages/create-redwood-app/templates/ts/graphql.config.js' - 'https://raw.githubusercontent.com/redwoodjs/redwood/main/packages/create-redwood-app/templates/ts/graphql.config.js' + 'https://raw.githubusercontent.com/redwoodjs/redwood/main/packages/create-redwood-app/templates/ts/graphql.config.js', ) const text = await res.text() fs.writeFileSync(path.join(getPaths().base, 'graphql.config.js'), text) diff --git a/packages/codemods/src/lib/getRootPackageJSON.ts b/packages/codemods/src/lib/getRootPackageJSON.ts index f68c3a52a605..dd5cedff24ab 100644 --- a/packages/codemods/src/lib/getRootPackageJSON.ts +++ b/packages/codemods/src/lib/getRootPackageJSON.ts @@ -7,7 +7,7 @@ const getRootPackageJSON = () => { const rootPackageJSONPath = path.join(getPaths().base, 'package.json') const rootPackageJSON = JSON.parse( - fs.readFileSync(rootPackageJSONPath, 'utf8') + fs.readFileSync(rootPackageJSONPath, 'utf8'), ) return [rootPackageJSON, rootPackageJSONPath] diff --git a/packages/codemods/src/testUtils/matchFolderTransform.ts b/packages/codemods/src/testUtils/matchFolderTransform.ts index c443fceab74c..5aec8d4cec01 100644 --- a/packages/codemods/src/testUtils/matchFolderTransform.ts +++ b/packages/codemods/src/testUtils/matchFolderTransform.ts @@ -21,7 +21,7 @@ type Options = { type MatchFolderTransformFunction = ( transformFunctionOrName: (() => any) | string, fixtureName?: string, - options?: Options + options?: Options, ) => Promise export const matchFolderTransform: MatchFolderTransformFunction = async ( @@ -31,7 +31,7 @@ export const matchFolderTransform: MatchFolderTransformFunction = async ( removeWhitespace = false, targetPathsGlob = '**/*', useJsCodeshift = false, - } = {} + } = {}, ) => { const tempDir = createProjectMock() @@ -48,7 +48,7 @@ export const matchFolderTransform: MatchFolderTransformFunction = async ( const fixtureFolder = path.join( testPath, '../../__testfixtures__', - fixtureName || '' + fixtureName || '', ) const fixtureInputDir = path.join(fixtureFolder, 'input') @@ -69,12 +69,12 @@ export const matchFolderTransform: MatchFolderTransformFunction = async ( if (useJsCodeshift) { if (typeof transformFunctionOrName !== 'string') { throw new Error( - 'When running matchFolderTransform with useJsCodeshift, transformFunction must be a string (file name of jscodeshift transform)' + 'When running matchFolderTransform with useJsCodeshift, transformFunction must be a string (file name of jscodeshift transform)', ) } const transformName = transformFunctionOrName const transformPath = require.resolve( - path.join(testPath, '../../', `${transformName}.ts`) + path.join(testPath, '../../', `${transformName}.ts`), ) const targetPaths = fg.sync(targetPathsGlob, { @@ -93,7 +93,7 @@ export const matchFolderTransform: MatchFolderTransformFunction = async ( } else { if (typeof transformFunctionOrName !== 'function') { throw new Error( - 'transformFunction must be a function, if useJsCodeshift set to false' + 'transformFunction must be a function, if useJsCodeshift set to false', ) } const transformFunction = transformFunctionOrName diff --git a/packages/codemods/src/testUtils/matchInlineTransformSnapshot.ts b/packages/codemods/src/testUtils/matchInlineTransformSnapshot.ts index f6b753aa4c4c..743d56b7b2fa 100644 --- a/packages/codemods/src/testUtils/matchInlineTransformSnapshot.ts +++ b/packages/codemods/src/testUtils/matchInlineTransformSnapshot.ts @@ -12,7 +12,7 @@ export const matchInlineTransformSnapshot = async ( transformName: string, fixtureCode: string, expectedCode: string, - parser: 'ts' | 'tsx' | 'babel' = 'tsx' + parser: 'ts' | 'tsx' | 'babel' = 'tsx', ) => { const tempFilePath = tempy.file() @@ -24,7 +24,7 @@ export const matchInlineTransformSnapshot = async ( } const transformPath = require.resolve( - path.join(testPath, '../../', `${transformName}.ts`) + path.join(testPath, '../../', `${transformName}.ts`), ) // Step 1: Write passed in code to a temp file @@ -44,6 +44,6 @@ export const matchInlineTransformSnapshot = async ( const transformedContent = fs.readFileSync(tempFilePath, 'utf-8') expect(await formatCode(transformedContent)).toEqual( - await formatCode(expectedCode) + await formatCode(expectedCode), ) } diff --git a/packages/codemods/src/testUtils/matchTransformSnapshot.ts b/packages/codemods/src/testUtils/matchTransformSnapshot.ts index 97647adacc21..96e4ceb4f81f 100644 --- a/packages/codemods/src/testUtils/matchTransformSnapshot.ts +++ b/packages/codemods/src/testUtils/matchTransformSnapshot.ts @@ -15,7 +15,7 @@ export interface MatchTransformSnapshotFunction { export const matchTransformSnapshot: MatchTransformSnapshotFunction = async ( transformName, fixtureName, - parser + parser, ) => { const tempFilePath = tempy.file() @@ -31,7 +31,7 @@ export const matchTransformSnapshot: MatchTransformSnapshotFunction = async ( const maybeFixturePath = path.join( testPath, '../../__testfixtures__', - `${fixtureName}.input` + `${fixtureName}.input`, ) for (const extension of ['ts', 'tsx', 'js', 'jsx']) { @@ -44,12 +44,12 @@ export const matchTransformSnapshot: MatchTransformSnapshotFunction = async ( if (!fixturePath) { throw new Error( - `Could not find fixture for ${fixtureName} in ${maybeFixturePath}` + `Could not find fixture for ${fixtureName} in ${maybeFixturePath}`, ) } const transformPath = require.resolve( - path.join(testPath, '../../', `${transformName}.ts`) + path.join(testPath, '../../', `${transformName}.ts`), ) // Step 1: Copy fixture to temp file @@ -71,10 +71,10 @@ export const matchTransformSnapshot: MatchTransformSnapshotFunction = async ( const expectedOutput = fs.readFileSync( fixturePath.replace('.input.', '.output.'), - 'utf-8' + 'utf-8', ) expect(await formatCode(transformedContent)).toEqual( - await formatCode(expectedOutput) + await formatCode(expectedOutput), ) } diff --git a/packages/codemods/testUtils.d.ts b/packages/codemods/testUtils.d.ts index 6581b6d833aa..9408d93cf902 100644 --- a/packages/codemods/testUtils.d.ts +++ b/packages/codemods/testUtils.d.ts @@ -9,7 +9,7 @@ declare module 'jscodeshift/dist/testUtils' { testFilePrefix?: string | null, testOptions?: { parser: 'ts' | 'tsx' | 'js' | 'jsx' | Parser - } + }, ): () => any function defineInlineTest( @@ -17,7 +17,7 @@ declare module 'jscodeshift/dist/testUtils' { options: Options, inputSource: string, expectedOutputSource: string, - testName?: string + testName?: string, ): () => any function runInlineTest( @@ -28,7 +28,7 @@ declare module 'jscodeshift/dist/testUtils' { source: string }, expectedOutput: string, - testOptions?: TestOptions + testOptions?: TestOptions, ): string } @@ -36,7 +36,7 @@ declare module 'jscodeshift/dist/testUtils' { type MatchTransformSnapshotFunction = ( transformName: string, fixtureName?: string, - parser?: 'ts' | 'tsx' + parser?: 'ts' | 'tsx', ) => Promise type MatchFolderTransformFunction = ( @@ -50,14 +50,14 @@ type MatchFolderTransformFunction = ( * as well as modifies file names. e.g. convertJsToJsx */ useJsCodeshift?: boolean - } + }, ) => Promise type MatchInlineTransformSnapshotFunction = ( transformName: string, fixtureCode: string, expectedCode: string, - parser: 'ts' | 'tsx' | 'babel' = 'tsx' + parser: 'ts' | 'tsx' | 'babel' = 'tsx', ) => Promise // These files gets loaded in jest setup, so becomes available globally in tests @@ -69,7 +69,7 @@ declare global { interface Matchers { toMatchFileContents( fixturePath: string, - { removeWhitespace }: { removeWhitespace: boolean } + { removeWhitespace }: { removeWhitespace: boolean }, ): R } } diff --git a/packages/core/config/webpack.common.js b/packages/core/config/webpack.common.js index 0e224add37e0..c9c8d046681a 100644 --- a/packages/core/config/webpack.common.js +++ b/packages/core/config/webpack.common.js @@ -237,14 +237,14 @@ module.exports = (webpackEnv) => { 'styled-components': path.resolve( redwoodPaths.base, 'node_modules', - 'styled-components' + 'styled-components', ), '~redwood-app-root': path.resolve(redwoodPaths.web.app), react: path.resolve(redwoodPaths.base, 'node_modules', 'react'), 'react-hook-form': path.resolve( redwoodPaths.base, 'node_modules', - 'react-hook-form' + 'react-hook-form', ), }, }, diff --git a/packages/core/config/webpack.development.js b/packages/core/config/webpack.development.js index 39aaf5095ddb..f132c3926fe7 100644 --- a/packages/core/config/webpack.development.js +++ b/packages/core/config/webpack.development.js @@ -75,7 +75,7 @@ const getProxyConfig = () => { console.error('Error: `apiUrl` is configured incorrectly.') console.error( - 'It should be an absolute path (thats starts with `/`) or an absolute URI that starts with `http[s]://`' + 'It should be an absolute path (thats starts with `/`) or an absolute URI that starts with `http[s]://`', ) process.exit(1) } diff --git a/packages/core/config/webpack.perf.js b/packages/core/config/webpack.perf.js index c15cb1f392bb..0e36d79ad22a 100644 --- a/packages/core/config/webpack.perf.js +++ b/packages/core/config/webpack.perf.js @@ -12,7 +12,7 @@ config.plugins.push( output: 'console', expandPackages: true, aggregateBy: 'plugins', - }) + }), ) /** Note: Only matches regex */ @@ -24,7 +24,7 @@ const indexOfRulesTest = (regex) => { const babel = indexOfRulesTest(/\.(js|mjs|jsx|ts|tsx)$/) config.module.rules[0].oneOf[babel].use[0].options.customize = require.resolve( - 'babel-timing/webpack/babel-loader-customize' + 'babel-timing/webpack/babel-loader-customize', ) module.exports = config diff --git a/packages/core/src/bins/cross-env.ts b/packages/core/src/bins/cross-env.ts index a01c07c5df66..7b9c151ce72b 100644 --- a/packages/core/src/bins/cross-env.ts +++ b/packages/core/src/bins/cross-env.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromCrossEnv = createRequire( - require.resolve('cross-env/package.json') + require.resolve('cross-env/package.json'), ) const bins = requireFromCrossEnv('./package.json')['bin'] diff --git a/packages/core/src/bins/nodemon.ts b/packages/core/src/bins/nodemon.ts index 82c33c06c015..6b6543e29bf3 100644 --- a/packages/core/src/bins/nodemon.ts +++ b/packages/core/src/bins/nodemon.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromNodemon = createRequire( - require.resolve('nodemon/package.json') + require.resolve('nodemon/package.json'), ) const bins = requireFromNodemon('./package.json')['bin'] diff --git a/packages/core/src/bins/redwood.ts b/packages/core/src/bins/redwood.ts index 7939f0c04dad..f5fc8a995c02 100644 --- a/packages/core/src/bins/redwood.ts +++ b/packages/core/src/bins/redwood.ts @@ -25,7 +25,7 @@ import { createRequire } from 'module' // // See https://github.com/nodejs/node/issues/40567#issuecomment-949825461. const requireFromCli = createRequire( - require.resolve('@redwoodjs/cli/package.json') + require.resolve('@redwoodjs/cli/package.json'), ) const bins = requireFromCli('./package.json')['bin'] diff --git a/packages/core/src/bins/rw-api-server-watch.ts b/packages/core/src/bins/rw-api-server-watch.ts index c55b59a3ceeb..6a42ab7ecd22 100644 --- a/packages/core/src/bins/rw-api-server-watch.ts +++ b/packages/core/src/bins/rw-api-server-watch.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromApiServer = createRequire( - require.resolve('@redwoodjs/api-server/package.json') + require.resolve('@redwoodjs/api-server/package.json'), ) const bins = requireFromApiServer('./package.json')['bin'] diff --git a/packages/core/src/bins/rw-dev-fe.ts b/packages/core/src/bins/rw-dev-fe.ts index e25b584ad397..ecd5fd1b9138 100644 --- a/packages/core/src/bins/rw-dev-fe.ts +++ b/packages/core/src/bins/rw-dev-fe.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromRwVite = createRequire( - require.resolve('@redwoodjs/vite/package.json') + require.resolve('@redwoodjs/vite/package.json'), ) const bins = requireFromRwVite('./package.json')['bin'] diff --git a/packages/core/src/bins/rw-gen-watch.ts b/packages/core/src/bins/rw-gen-watch.ts index 1f6854e2f73d..26ea5dcdb58d 100644 --- a/packages/core/src/bins/rw-gen-watch.ts +++ b/packages/core/src/bins/rw-gen-watch.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromInternal = createRequire( - require.resolve('@redwoodjs/internal/package.json') + require.resolve('@redwoodjs/internal/package.json'), ) const bins = requireFromInternal('./package.json')['bin'] diff --git a/packages/core/src/bins/rw-gen.ts b/packages/core/src/bins/rw-gen.ts index 557d81daec35..35dc82d752be 100644 --- a/packages/core/src/bins/rw-gen.ts +++ b/packages/core/src/bins/rw-gen.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromInternal = createRequire( - require.resolve('@redwoodjs/internal/package.json') + require.resolve('@redwoodjs/internal/package.json'), ) const bins = requireFromInternal('./package.json')['bin'] diff --git a/packages/core/src/bins/rw-log-formatter.ts b/packages/core/src/bins/rw-log-formatter.ts index 2a502078eeed..df9917a8db3e 100644 --- a/packages/core/src/bins/rw-log-formatter.ts +++ b/packages/core/src/bins/rw-log-formatter.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromApiServer = createRequire( - require.resolve('@redwoodjs/api-server/package.json') + require.resolve('@redwoodjs/api-server/package.json'), ) const bins = requireFromApiServer('./package.json')['bin'] diff --git a/packages/core/src/bins/rw-serve-api.ts b/packages/core/src/bins/rw-serve-api.ts index 4156ecaa86f7..43a2de0478c5 100644 --- a/packages/core/src/bins/rw-serve-api.ts +++ b/packages/core/src/bins/rw-serve-api.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromApiServer = createRequire( - require.resolve('@redwoodjs/api-server/package.json') + require.resolve('@redwoodjs/api-server/package.json'), ) const bins = requireFromApiServer('./package.json')['bin'] diff --git a/packages/core/src/bins/rw-serve-fe.ts b/packages/core/src/bins/rw-serve-fe.ts index a31988ae98bf..bc9497e49fea 100644 --- a/packages/core/src/bins/rw-serve-fe.ts +++ b/packages/core/src/bins/rw-serve-fe.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromRwVite = createRequire( - require.resolve('@redwoodjs/vite/package.json') + require.resolve('@redwoodjs/vite/package.json'), ) const bins = requireFromRwVite('./package.json')['bin'] diff --git a/packages/core/src/bins/rw-server.ts b/packages/core/src/bins/rw-server.ts index 05b40f9c1076..6de88f63bb14 100644 --- a/packages/core/src/bins/rw-server.ts +++ b/packages/core/src/bins/rw-server.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromApiServer = createRequire( - require.resolve('@redwoodjs/api-server/package.json') + require.resolve('@redwoodjs/api-server/package.json'), ) const bins = requireFromApiServer('./package.json')['bin'] diff --git a/packages/core/src/bins/rw-web-server.ts b/packages/core/src/bins/rw-web-server.ts index eaa87af6af0b..4e85da8a0936 100644 --- a/packages/core/src/bins/rw-web-server.ts +++ b/packages/core/src/bins/rw-web-server.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromWebServer = createRequire( - require.resolve('@redwoodjs/web-server/package.json') + require.resolve('@redwoodjs/web-server/package.json'), ) const bins = requireFromWebServer('./package.json')['bin'] diff --git a/packages/core/src/bins/rwfw.ts b/packages/core/src/bins/rwfw.ts index 3e613a4a674f..5d09e6d133ef 100644 --- a/packages/core/src/bins/rwfw.ts +++ b/packages/core/src/bins/rwfw.ts @@ -2,7 +2,7 @@ import { createRequire } from 'module' const requireFromCli = createRequire( - require.resolve('@redwoodjs/cli/package.json') + require.resolve('@redwoodjs/cli/package.json'), ) const bins = requireFromCli('./package.json')['bin'] diff --git a/packages/create-redwood-app/scripts/buildPack.js b/packages/create-redwood-app/scripts/buildPack.js index 8ec6bb7d1574..cede91b65346 100644 --- a/packages/create-redwood-app/scripts/buildPack.js +++ b/packages/create-redwood-app/scripts/buildPack.js @@ -5,10 +5,10 @@ import { fileURLToPath } from 'node:url' import { cd, path, within, $ } from 'zx' const tsTemplatePath = fileURLToPath( - new URL('../templates/ts', import.meta.url) + new URL('../templates/ts', import.meta.url), ) const jsTemplatePath = fileURLToPath( - new URL('../templates/js', import.meta.url) + new URL('../templates/js', import.meta.url), ) await within(async () => { diff --git a/packages/create-redwood-app/scripts/setUpTestProject.js b/packages/create-redwood-app/scripts/setUpTestProject.js index 464a9ac0cc2c..879a6541eafe 100644 --- a/packages/create-redwood-app/scripts/setUpTestProject.js +++ b/packages/create-redwood-app/scripts/setUpTestProject.js @@ -27,7 +27,7 @@ const tarball = 'create-redwood-app.tgz' await fs.move( path.join(packagePath, tarball), path.join(projectPath, tarball), - { overwrite: true } + { overwrite: true }, ) cd(projectPath) diff --git a/packages/create-redwood-app/scripts/tsToJS.js b/packages/create-redwood-app/scripts/tsToJS.js index 5d03a7c94a27..c99cbd80551d 100644 --- a/packages/create-redwood-app/scripts/tsToJS.js +++ b/packages/create-redwood-app/scripts/tsToJS.js @@ -7,7 +7,7 @@ import { format } from 'prettier' import { fs, glob, path } from 'zx' const TS_TEMPLATE_PATH = fileURLToPath( - new URL('../templates/ts', import.meta.url) + new URL('../templates/ts', import.meta.url), ) // Remove `node_modules`, `.yarn/install-state.gz`. @@ -19,13 +19,13 @@ console.log("Removing yarn's `install-state.gz` in the TS template") const tsTemplateYarnInstallStatePath = path.join( TS_TEMPLATE_PATH, '.yarn', - 'install-state.gz' + 'install-state.gz', ) await fs.rm(tsTemplateYarnInstallStatePath, { force: true }) // Clean and copy the TS template to the JS template. const JS_TEMPLATE_PATH = fileURLToPath( - new URL('../templates/js', import.meta.url) + new URL('../templates/js', import.meta.url), ) console.log('Removing the JS template') @@ -75,7 +75,7 @@ for (const filePath of filePaths) { await fs.writeFile( filePath.replace('.tsx', '.jsx').replace('.ts', '.js'), formattedCode, - 'utf-8' + 'utf-8', ) await fs.rm(filePath) @@ -84,7 +84,7 @@ for (const filePath of filePaths) { console.groupEnd() console.group( - 'Transforming `tsconfig.json`s in the JS template to `jsconfig.json`s' + 'Transforming `tsconfig.json`s in the JS template to `jsconfig.json`s', ) const tsConfigFilePaths = await glob(['{api,web,scripts}/**/tsconfig.json'], { @@ -97,7 +97,7 @@ for (const tsConfigFilePath of tsConfigFilePaths) { const jsConfigFilePath = path.join( path.dirname(tsConfigFilePath), - 'jsconfig.json' + 'jsconfig.json', ) await fs.rename(tsConfigFilePath, jsConfigFilePath) diff --git a/packages/create-redwood-app/src/create-redwood-app.js b/packages/create-redwood-app/src/create-redwood-app.js index 8e9e535a7634..742d6646b7c6 100644 --- a/packages/create-redwood-app/src/create-redwood-app.js +++ b/packages/create-redwood-app/src/create-redwood-app.js @@ -60,7 +60,7 @@ const USE_GITPOD_TEXT = [ { fallback: () => 'Launch Redwood using GitPod https://gitpod.io/#https://github.com/redwoodjs/starter', - } + }, )}`, ] @@ -91,7 +91,7 @@ async function executeCompatibilityCheck(templateDir) { if (!checksPassed) { const foundNodeVersionIsLessThanRequired = semver.lt( checksData.node.version.version, - semver.minVersion(checksData.node.wanted.raw) + semver.minVersion(checksData.node.wanted.raw), ) if (foundNodeVersionIsLessThanRequired) { @@ -109,7 +109,7 @@ async function executeCompatibilityCheck(templateDir) { { fallback: () => 'How to - Using nvm https://redwoodjs.com/docs/how-to/using-nvm', - } + }, )}`, ` See: ${terminalLink( 'Tutorial - Prerequisites', @@ -117,11 +117,11 @@ async function executeCompatibilityCheck(templateDir) { { fallback: () => 'Tutorial - Prerequisites https://redwoodjs.com/docs/tutorial/chapter1/prerequisites', - } + }, )}`, '', ...USE_GITPOD_TEXT, - ].join('\n') + ].join('\n'), ) recordErrorViaTelemetry('Compatibility checks failed') @@ -145,7 +145,7 @@ async function executeCompatibilityCheck(templateDir) { { fallback: () => 'How to - Use nvm https://redwoodjs.com/docs/how-to/using-nvm', - } + }, )}`, ` See: ${terminalLink( 'Tutorial - Prerequisites', @@ -153,11 +153,11 @@ async function executeCompatibilityCheck(templateDir) { { fallback: () => 'Tutorial - Prerequisites https://redwoodjs.com/docs/tutorial/chapter1/prerequisites', - } + }, )}`, '', ...USE_GITPOD_TEXT, - ].join('\n') + ].join('\n'), ) // Try catch for handling if the user cancels the prompt. @@ -220,7 +220,7 @@ async function createProjectFiles(appDir, { templateDir, overwrite }) { // .gitignore is renamed here to force file inclusion during publishing fs.renameSync( path.join(newAppDir, 'gitignore.template'), - path.join(newAppDir, '.gitignore') + path.join(newAppDir, '.gitignore'), ) // Write the uid @@ -265,11 +265,11 @@ async function installNodeModules(newAppDir) { "Couldn't install node modules", [ `We couldn't install node modules via ${RedwoodStyling.info( - "'yarn install'" + "'yarn install'", )}. Please see below for the full error message.`, '', error, - ].join('\n') + ].join('\n'), ) recordErrorViaTelemetry(error) await shutdownTelemetry() @@ -312,11 +312,11 @@ async function generateTypes(newAppDir) { "Couldn't generate types", [ `We could not generate types using ${RedwoodStyling.info( - "'yarn rw-gen'" + "'yarn rw-gen'", )}. Please see below for the full error message.`, '', error, - ].join('\n') + ].join('\n'), ) recordErrorViaTelemetry(error) await shutdownTelemetry() @@ -347,7 +347,7 @@ async function initializeGit(newAppDir, commitMessage) { { shell: true, cwd: newAppDir, - } + }, ) try { @@ -358,11 +358,11 @@ async function initializeGit(newAppDir, commitMessage) { "Couldn't initialize a git repo", [ `We could not initialize a git repo using ${RedwoodStyling.info( - `git init && git add . && git commit -m "${commitMessage}"` + `git init && git add . && git commit -m "${commitMessage}"`, )}. Please see below for the full error message.`, '', error, - ].join('\n') + ].join('\n'), ) recordErrorViaTelemetry(error) await shutdownTelemetry() @@ -371,7 +371,7 @@ async function initializeGit(newAppDir, commitMessage) { tuiContent.update({ content: `${RedwoodStyling.green( - '✔' + '✔', )} Initialized a git repo with commit message "${commitMessage}"`, spinner: { enabled: false, @@ -384,8 +384,8 @@ async function handleTargetDirPreference(targetDir) { if (targetDir) { tui.drawText( `${RedwoodStyling.green( - '✔' - )} Creating your Redwood app in ${targetDir} based on command line argument` + '✔', + )} Creating your Redwood app in ${targetDir} based on command line argument`, ) return targetDir @@ -404,7 +404,7 @@ async function handleTargetDirPreference(targetDir) { tui.stopReactive(true) tui.displayError( 'The `~username` syntax is not supported here', - 'Please use the full path or specify the target directory on the command line.' + 'Please use the full path or specify the target directory on the command line.', ) recordErrorViaTelemetry('Target dir prompt path syntax not supported') @@ -426,7 +426,7 @@ async function handleTypescriptPreference(typescriptFlag) { tui.drawText( `${RedwoodStyling.green('✔')} Using ${ typescriptFlag ? 'TypeScript' : 'JavaScript' - } based on command line flag` + } based on command line flag`, ) return typescriptFlag } @@ -454,7 +454,7 @@ async function handleGitPreference(gitInitFlag) { tui.drawText( `${RedwoodStyling.green('✔')} ${ gitInitFlag ? 'Will' : 'Will not' - } initialize a git repo based on command line flag` + } initialize a git repo based on command line flag`, ) return gitInitFlag } @@ -479,7 +479,7 @@ async function handleGitPreference(gitInitFlag) { async function doesDirectoryAlreadyExist( appDir, - { overwrite, suppressWarning } + { overwrite, suppressWarning }, ) { let newAppDir = appDir @@ -493,7 +493,7 @@ async function doesDirectoryAlreadyExist( tui.stopReactive(true) tui.displayWarning( 'Project directory already contains files', - [`'${styledAppDir}' already exists and is not empty`].join('\n') + [`'${styledAppDir}' already exists and is not empty`].join('\n'), ) } @@ -528,7 +528,7 @@ async function doesDirectoryAlreadyExist( tui.stopReactive(true) tui.displayError( 'The `~username` syntax is not supported here', - 'Please use the full path or specify the target directory on the command line.' + 'Please use the full path or specify the target directory on the command line.', ) // Calling doesDirectoryAlreadyExist again with the same old @@ -548,7 +548,7 @@ async function doesDirectoryAlreadyExist( else if (response.projectDirectoryAlreadyExists === 'Quit install') { // quit and throw an error recordErrorViaTelemetry( - 'User quit after directory already exists error' + 'User quit after directory already exists error', ) await shutdownTelemetry() process.exit(1) @@ -556,7 +556,7 @@ async function doesDirectoryAlreadyExist( // overwrite the existing files } catch (_error) { recordErrorViaTelemetry( - `User cancelled install after directory already exists error` + `User cancelled install after directory already exists error`, ) await shutdownTelemetry() process.exit(1) @@ -578,7 +578,7 @@ async function handleNewDirectoryNamePreference() { return response.targetDirectoryInput } catch (_error) { recordErrorViaTelemetry( - 'User cancelled install at specify a different directory prompt' + 'User cancelled install at specify a different directory prompt', ) await shutdownTelemetry() process.exit(1) @@ -619,7 +619,7 @@ async function handleYarnInstallPreference(yarnInstallFlag) { tui.drawText( `${RedwoodStyling.green('✔')} ${ yarnInstallFlag ? 'Will' : 'Will not' - } run yarn install based on command line flag` + } run yarn install based on command line flag`, ) return yarnInstallFlag } @@ -707,10 +707,10 @@ async function createRedwoodApp() { [ `${RedwoodStyling.redwood('-'.repeat(66))}`, `${' '.repeat(16)}🌲⚡️ ${RedwoodStyling.header( - 'Welcome to RedwoodJS!' + 'Welcome to RedwoodJS!', )} ⚡️🌲`, `${RedwoodStyling.redwood('-'.repeat(66))}`, - ].join('\n') + ].join('\n'), ) // Extract the args as provided by the user in the command line @@ -798,7 +798,7 @@ async function createRedwoodApp() { RedwoodStyling.success('Thanks for trying out Redwood!'), '', ` ⚡️ ${RedwoodStyling.redwood( - 'Get up and running fast with this Quick Start guide' + 'Get up and running fast with this Quick Start guide', )}: https://redwoodjs.com/quick-start`, '', `${RedwoodStyling.header(`Fire it up!`)} 🚀`, @@ -806,19 +806,19 @@ async function createRedwoodApp() { ...[ `${RedwoodStyling.redwood( ` > ${RedwoodStyling.green( - `cd ${path.relative(process.cwd(), newAppDir)}` - )}` + `cd ${path.relative(process.cwd(), newAppDir)}`, + )}`, )}`, !yarnInstall && `${RedwoodStyling.redwood( - ` > ${RedwoodStyling.green(`yarn install`)}` + ` > ${RedwoodStyling.green(`yarn install`)}`, )}`, `${RedwoodStyling.redwood( - ` > ${RedwoodStyling.green(`yarn rw dev`)}` + ` > ${RedwoodStyling.green(`yarn rw dev`)}`, )}`, ].filter(Boolean), '', - ].join('\n') + ].join('\n'), ) } diff --git a/packages/create-redwood-app/src/telemetry.js b/packages/create-redwood-app/src/telemetry.js index 471261101029..c014153552b7 100644 --- a/packages/create-redwood-app/src/telemetry.js +++ b/packages/create-redwood-app/src/telemetry.js @@ -43,8 +43,8 @@ export async function startTelemetry() { npmPackages: '@redwoodjs/*', IDEs: ['VSCode'], }, - { json: true } - ) + { json: true }, + ), ) // get shell name instead of path @@ -82,7 +82,7 @@ export async function startTelemetry() { 'ci.isci': ci.isCI, 'dev.environment': developmentEnvironment, uid: UID, - }) + }), ) // Tracing diff --git a/packages/create-redwood-app/tests/e2e.test.ts b/packages/create-redwood-app/tests/e2e.test.ts index c4f75af38cfb..86157053dcfb 100644 --- a/packages/create-redwood-app/tests/e2e.test.ts +++ b/packages/create-redwood-app/tests/e2e.test.ts @@ -90,7 +90,9 @@ describe('create-redwood-app', () => { [?25l✔ Initialized a git repo with commit message "Initial commit" [?25h" `) - expect(p.stderr).toMatchInlineSnapshot(`"[?25l[?25h[?25l[?25h[?25l[?25h[?25l[?25h[?25l[?25h[?25l[?25h[?25l[?25h"`) + expect(p.stderr).toMatchInlineSnapshot( + `"[?25l[?25h[?25l[?25h[?25l[?25h[?25l[?25h[?25l[?25h[?25l[?25h[?25l[?25h"`, + ) await fs.rm('./redwood-app', { recursive: true, force: true }) }) diff --git a/packages/create-redwood-app/tests/templates.test.ts b/packages/create-redwood-app/tests/templates.test.ts index 9743e7c80f2d..61ed0219efab 100644 --- a/packages/create-redwood-app/tests/templates.test.ts +++ b/packages/create-redwood-app/tests/templates.test.ts @@ -5,7 +5,7 @@ import klawSync from 'klaw-sync' import { describe, it, expect } from 'vitest' const TS_TEMPLATE_DIR = fileURLToPath( - new URL('../templates/ts', import.meta.url) + new URL('../templates/ts', import.meta.url), ) describe('TS template', () => { @@ -87,7 +87,7 @@ describe('TS template', () => { }) const JS_TEMPLATE_DIR = fileURLToPath( - new URL('../templates/js', import.meta.url) + new URL('../templates/js', import.meta.url), ) describe('JS template', () => { @@ -197,11 +197,11 @@ function getDirectoryStructure(dir) { .filter( (file) => !filePathsToIgnore.some((filePathToIgnore) => - file.path.includes(filePathToIgnore) - ) + file.path.includes(filePathToIgnore), + ), ) .map((file) => - file.path.replace(dir, '').split(path.sep).join(path.posix.sep) + file.path.replace(dir, '').split(path.sep).join(path.posix.sep), ) .sort() } diff --git a/packages/eslint-plugin/src/service-type-annotations.ts b/packages/eslint-plugin/src/service-type-annotations.ts index eab27f32416a..40dee333ef6f 100644 --- a/packages/eslint-plugin/src/service-type-annotations.ts +++ b/packages/eslint-plugin/src/service-type-annotations.ts @@ -73,7 +73,7 @@ export const serviceTypeAnnotations: Rule.RuleModule = { if (!importForThisFile) { yield fixer.insertTextBeforeRange( [0, 0], - `import type { ${typeName} } from "${thisFileCorrespondingImport}"\n` + `import type { ${typeName} } from "${thisFileCorrespondingImport}"\n`, ) } else { const lastImportSpecifier = @@ -82,7 +82,7 @@ export const serviceTypeAnnotations: Rule.RuleModule = { ] yield fixer.insertTextAfter( lastImportSpecifier, - `, ${typeName}` + `, ${typeName}`, ) } }, @@ -122,7 +122,7 @@ export const serviceTypeAnnotations: Rule.RuleModule = { if (!importForThisFile) { yield fixer.insertTextBeforeRange( [0, 0], - `import type { ${typeName} } from "${thisFileCorrespondingImport}"\n` + `import type { ${typeName} } from "${thisFileCorrespondingImport}"\n`, ) } else { const lastImportSpecifier = @@ -131,7 +131,7 @@ export const serviceTypeAnnotations: Rule.RuleModule = { ] yield fixer.insertTextAfter( lastImportSpecifier, - `, ${typeName}` + `, ${typeName}`, ) } }, @@ -161,6 +161,6 @@ const capitalizeFirstLetter = (str: string) => str.charAt(0).toUpperCase() + str.slice(1) const isVariableDeclaration = ( - node: Declaration + node: Declaration, ): node is VariableDeclaration => typeof node !== 'undefined' && 'declarations' in node diff --git a/packages/forms/src/__tests__/form.test.tsx b/packages/forms/src/__tests__/form.test.tsx index e1edc0dc8fda..4952e2378d7f 100644 --- a/packages/forms/src/__tests__/form.test.tsx +++ b/packages/forms/src/__tests__/form.test.tsx @@ -166,7 +166,7 @@ describe('Form', () => { datetimeLocal: new Date('2021-04-16T12:34'), date: new Date('2021-04-16'), }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -180,7 +180,7 @@ describe('Form', () => { await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { 'wrapped-ff': 3.14, 'wrapped-nf-1': 101, 'wrapped-nf-2': 102 }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -215,7 +215,7 @@ describe('Form', () => { Save - + , ) fireEvent.click(screen.getByText('Save')) @@ -223,7 +223,7 @@ describe('Form', () => { await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { tf: 123456, select: 'Option-2' }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -241,7 +241,7 @@ describe('Form', () => { Save - + , ) fireEvent.click(screen.getByText('Save')) @@ -249,7 +249,7 @@ describe('Form', () => { await waitFor(() => expect(mockFn).toHaveBeenCalledTimes(1)) expect(mockFn).toBeCalledWith( { userId: null, groupId: null }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -265,12 +265,12 @@ describe('Form', () => { /> Save - + , ) fireEvent.submit(screen.getByText('Save')) await waitFor(() => - expect(screen.getByTestId('fieldError')).toBeInTheDocument() + expect(screen.getByTestId('fieldError')).toBeInTheDocument(), ) // The validation should catch and prevent the onSubmit from being called expect(mockFn).not.toHaveBeenCalled() @@ -292,12 +292,12 @@ describe('Form', () => { {' '} Save - + , ) fireEvent.submit(screen.getByText('Save')) await waitFor(() => - expect(screen.getByTestId('fieldError')).toBeInTheDocument() + expect(screen.getByTestId('fieldError')).toBeInTheDocument(), ) // The validation should catch and prevent the onSubmit from being called @@ -317,7 +317,7 @@ describe('Form', () => { validation={{ valueAsNumber: true }} /> Save - + , ) fireEvent.click(screen.getByText('Save')) @@ -327,7 +327,7 @@ describe('Form', () => { int: NaN, float: NaN, }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -344,11 +344,11 @@ describe('Form', () => { /> Save - + , ) fireEvent.submit(screen.getByText('Save')) await waitFor(() => - expect(screen.getByTestId('fieldError')).toBeInTheDocument() + expect(screen.getByTestId('fieldError')).toBeInTheDocument(), ) // The validation should catch and prevent the onSubmit from being called @@ -367,11 +367,11 @@ describe('Form', () => { /> Save - + , ) fireEvent.submit(screen.getByText('Save')) await waitFor(() => - expect(screen.getByTestId('fieldError')).toBeInTheDocument() + expect(screen.getByTestId('fieldError')).toBeInTheDocument(), ) // The validation should catch and prevent the onSubmit from being called @@ -398,12 +398,12 @@ describe('Form', () => { /> Save - + , ) fireEvent.submit(screen.getByText('Save')) await waitFor(() => - expect(screen.getByTestId('phoneFieldError')).toBeInTheDocument() + expect(screen.getByTestId('phoneFieldError')).toBeInTheDocument(), ) // The validation should catch and prevent the onSubmit from being called expect(mockFn).not.toHaveBeenCalled() @@ -429,13 +429,13 @@ describe('Form', () => { /> Save - + , ) fireEvent.click(screen.getByText('Save')) const phoneError = await waitFor( - () => screen.getByTestId('phoneFieldError').textContent + () => screen.getByTestId('phoneFieldError').textContent, ) expect(phoneError).toEqual('phone is not formatted correctly') }) @@ -451,13 +451,13 @@ describe('Form', () => { /> Save - + , ) fireEvent.click(screen.getByText('Save')) const phoneError = await waitFor( - () => screen.getByTestId('phoneFieldError').textContent + () => screen.getByTestId('phoneFieldError').textContent, ) expect(phoneError).toEqual('false is not formatted correctly') }) @@ -472,13 +472,13 @@ describe('Form', () => { /> Save - + , ) fireEvent.click(screen.getByText('Save')) const phoneError = await waitFor( - () => screen.getByTestId('phoneFieldError').textContent + () => screen.getByTestId('phoneFieldError').textContent, ) expect(phoneError).toEqual('0 is not formatted correctly') }) @@ -508,7 +508,7 @@ describe('Form', () => { Save - + , ) fireEvent.click(screen.getByText('Save')) @@ -526,7 +526,7 @@ describe('Form', () => { jsonField: null, fieldId: null, }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -565,7 +565,7 @@ describe('Form', () => { Save - + , ) fireEvent.click(screen.getByText('Save')) @@ -582,7 +582,7 @@ describe('Form', () => { jsonField: undefined, fieldId: undefined, }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -610,7 +610,7 @@ describe('Form', () => { Save - + , ) fireEvent.click(screen.getByText('Save')) @@ -626,7 +626,7 @@ describe('Form', () => { jsonField: null, fieldId: null, }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -654,7 +654,7 @@ describe('Form', () => { Save - + , ) fireEvent.click(screen.getByText('Save')) @@ -671,7 +671,7 @@ describe('Form', () => { jsonField: 0, fieldId: 0, }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -699,7 +699,7 @@ describe('Form', () => { Save - + , ) fireEvent.click(screen.getByText('Save')) @@ -716,7 +716,7 @@ describe('Form', () => { jsonField: '', fieldId: '', }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -734,14 +734,14 @@ describe('Form', () => { Save - + , ) fireEvent.change(screen.getByTestId('numberField'), { target: { value: 2 }, }) fireEvent.submit(screen.getByText('Save')) await waitFor(() => - expect(screen.getByTestId('numberFieldError')).toBeInTheDocument() + expect(screen.getByTestId('numberFieldError')).toBeInTheDocument(), ) // The validation should catch and prevent the onSubmit from being called @@ -783,7 +783,7 @@ describe('Form', () => { Save - + , ) fireEvent.click(screen.getByText('Save')) @@ -799,7 +799,7 @@ describe('Form', () => { jsonField: null, fieldId: null, }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -832,7 +832,7 @@ describe('Form', () => { emptyAs={0} /> Save - + , ) fireEvent.click(screen.getByText('Save')) @@ -846,7 +846,7 @@ describe('Form', () => { tf3: 42, tf4: 42, }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -879,7 +879,7 @@ describe('Form', () => { emptyAs={0} /> Save - + , ) fireEvent.click(screen.getByText('Save')) @@ -893,7 +893,7 @@ describe('Form', () => { tf3: new Date('2022-02-01'), tf4: new Date('2022-02-01'), }, - expect.anything() // event that triggered the onSubmit call + expect.anything(), // event that triggered the onSubmit call ) }) @@ -906,7 +906,7 @@ describe('Form', () => { {/* @ts-expect-error - Testing a JS scenario */} Save - + , ) expect(testRender).toThrow('`name` prop must be provided') diff --git a/packages/forms/src/index.tsx b/packages/forms/src/index.tsx index b830ba20364c..aa0573e601ed 100644 --- a/packages/forms/src/index.tsx +++ b/packages/forms/src/index.tsx @@ -86,7 +86,7 @@ interface FieldProps< Element extends | HTMLTextAreaElement | HTMLSelectElement - | HTMLInputElement = HTMLInputElement + | HTMLInputElement = HTMLInputElement, > { name: string id?: string @@ -270,7 +270,7 @@ const getSetValueAsFn = ( type: ValueAsType, emptyAs: EmptyAsValue | undefined, required: boolean, - isId: boolean + isId: boolean, ) => { const typeObj = SET_VALUE_AS_FUNCTIONS[type] if (typeObj === undefined) { @@ -361,7 +361,7 @@ interface SetCoersionProps { const setCoercion = ( validation: RedwoodRegisterOptions, - { type, name, emptyAs }: SetCoersionProps + { type, name, emptyAs }: SetCoersionProps, ) => { if (validation.setValueAs) { // Note, this case could override other props @@ -400,7 +400,7 @@ const setCoercion = ( valueAs, // type emptyAs, // emptyAs validation.required !== undefined && validation.required !== false, // required - /Id$/.test(name || '') // isId + /Id$/.test(name || ''), // isId ) } @@ -408,7 +408,7 @@ export type UseRegisterProps< Element extends | HTMLTextAreaElement | HTMLSelectElement - | HTMLInputElement = HTMLInputElement + | HTMLInputElement = HTMLInputElement, > = Pick< FieldProps, 'name' | 'validation' | 'type' | 'onBlur' | 'onChange' @@ -431,11 +431,11 @@ const useRegister = < Element extends | HTMLTextAreaElement | HTMLSelectElement - | HTMLInputElement = HTMLInputElement + | HTMLInputElement = HTMLInputElement, >( props: UseRegisterProps & { element?: string }, ref?: React.ForwardedRef, - emptyAs?: EmptyAsValue + emptyAs?: EmptyAsValue, ) => { const { register } = useFormContext() const { name } = props @@ -544,7 +544,7 @@ function FormInner( children, ...rest }: FormProps, - ref: ForwardedRef + ref: ForwardedRef, ) { const hookFormMethods = useForm(config) const formMethods = propFormMethods || hookFormMethods @@ -554,7 +554,7 @@ function FormInner( ref={ref} {...rest} onSubmit={formMethods.handleSubmit((data, event) => - onSubmit?.(data, event) + onSubmit?.(data, event), )} > ( // > that you cast the type // https://github.com/chakra-ui/chakra-ui/issues/4528#issuecomment-902566185 const Form = forwardRef(FormInner) as ( - props: FormProps & React.RefAttributes + props: FormProps & React.RefAttributes, ) => React.ReactElement | null export interface LabelProps @@ -711,7 +711,7 @@ const TextAreaField = forwardRef( ...rest }: TextAreaFieldProps, - ref: ForwardedRef + ref: ForwardedRef, ) => { const styles = useErrorStyles({ name, @@ -729,13 +729,13 @@ const TextAreaField = forwardRef( onChange, }, ref, - emptyAs + emptyAs, ) return (