@canva/cli 0.0.1-beta.2 → 0.0.1-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +184 -108
  2. package/cli.js +467 -394
  3. package/lib/cjs/index.cjs +388 -0
  4. package/lib/esm/index.mjs +388 -0
  5. package/package.json +12 -3
  6. package/templates/base/backend/routers/oauth.ts +393 -0
  7. package/templates/base/eslint.config.mjs +2 -4
  8. package/templates/base/package.json +31 -25
  9. package/templates/base/scripts/copy_env.ts +10 -0
  10. package/templates/base/scripts/start/app_runner.ts +39 -2
  11. package/templates/base/scripts/start/context.ts +12 -6
  12. package/templates/base/scripts/start/start.ts +11 -0
  13. package/templates/base/scripts/start/tests/start.tests.ts +61 -0
  14. package/templates/base/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
  15. package/templates/base/utils/backend/bearer_middleware/index.ts +1 -0
  16. package/templates/base/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
  17. package/templates/base/utils/use_add_element.ts +48 -0
  18. package/templates/base/utils/use_feature_support.ts +28 -0
  19. package/templates/base/{webpack.config.cjs → webpack.config.ts} +34 -42
  20. package/templates/common/.gitignore.template +5 -6
  21. package/templates/common/.nvmrc +1 -0
  22. package/templates/common/.prettierrc +21 -0
  23. package/templates/common/.vscode/extensions.json +6 -0
  24. package/templates/common/README.md +4 -74
  25. package/templates/common/conf/eslint-local-i18n-rules/index.mjs +181 -0
  26. package/templates/common/conf/{eslint-general.mjs → eslint_general.mjs} +40 -0
  27. package/templates/common/conf/eslint_i18n.mjs +41 -0
  28. package/templates/common/jest.config.mjs +29 -2
  29. package/templates/common/jest.setup.ts +20 -0
  30. package/templates/common/utils/backend/base_backend/create.ts +104 -0
  31. package/templates/common/utils/table_wrapper.ts +477 -0
  32. package/templates/common/utils/tests/table_wrapper.tests.ts +252 -0
  33. package/templates/common/utils/use_add_element.ts +48 -0
  34. package/templates/common/utils/use_feature_support.ts +28 -0
  35. package/templates/common/utils/use_overlay_hook.ts +74 -0
  36. package/templates/common/utils/use_selection_hook.ts +37 -0
  37. package/templates/dam/backend/routers/dam.ts +17 -12
  38. package/templates/dam/backend/server.ts +0 -7
  39. package/templates/dam/eslint.config.mjs +2 -2
  40. package/templates/dam/package.json +51 -39
  41. package/templates/dam/scripts/copy_env.ts +10 -0
  42. package/templates/dam/scripts/start/app_runner.ts +39 -2
  43. package/templates/dam/scripts/start/context.ts +12 -6
  44. package/templates/dam/scripts/start/start.ts +11 -0
  45. package/templates/dam/scripts/start/tests/start.tests.ts +61 -0
  46. package/templates/dam/src/app.tsx +26 -138
  47. package/templates/dam/src/config.ts +209 -87
  48. package/templates/{hello_world/webpack.config.cjs → dam/webpack.config.ts} +34 -42
  49. package/templates/gen_ai/README.md +1 -1
  50. package/templates/gen_ai/backend/routers/image.ts +3 -3
  51. package/templates/gen_ai/backend/server.ts +0 -7
  52. package/templates/gen_ai/eslint.config.mjs +2 -4
  53. package/templates/gen_ai/package.json +56 -42
  54. package/templates/gen_ai/scripts/copy_env.ts +10 -0
  55. package/templates/gen_ai/scripts/start/app_runner.ts +39 -2
  56. package/templates/gen_ai/scripts/start/context.ts +12 -6
  57. package/templates/gen_ai/scripts/start/start.ts +11 -0
  58. package/templates/gen_ai/scripts/start/tests/start.tests.ts +61 -0
  59. package/templates/gen_ai/src/api/api.ts +1 -39
  60. package/templates/gen_ai/src/app.tsx +16 -10
  61. package/templates/gen_ai/src/components/footer.messages.ts +0 -5
  62. package/templates/gen_ai/src/components/footer.tsx +2 -16
  63. package/templates/gen_ai/src/components/image_grid.tsx +8 -6
  64. package/templates/gen_ai/src/components/index.ts +0 -1
  65. package/templates/gen_ai/src/components/tests/remaining_credit.tests.tsx +43 -0
  66. package/templates/gen_ai/src/context/app_context.tsx +4 -26
  67. package/templates/gen_ai/src/context/context.messages.ts +1 -12
  68. package/templates/gen_ai/src/home.tsx +13 -0
  69. package/templates/gen_ai/src/index.tsx +2 -18
  70. package/templates/gen_ai/src/routes/routes.tsx +2 -2
  71. package/templates/gen_ai/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
  72. package/templates/gen_ai/utils/backend/bearer_middleware/index.ts +1 -0
  73. package/templates/gen_ai/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
  74. package/templates/gen_ai/{webpack.config.cjs → webpack.config.ts} +34 -42
  75. package/templates/hello_world/eslint.config.mjs +2 -4
  76. package/templates/hello_world/package.json +55 -33
  77. package/templates/hello_world/scripts/copy_env.ts +10 -0
  78. package/templates/hello_world/scripts/start/app_runner.ts +39 -2
  79. package/templates/hello_world/scripts/start/context.ts +12 -6
  80. package/templates/hello_world/scripts/start/start.ts +11 -0
  81. package/templates/hello_world/scripts/start/tests/start.tests.ts +61 -0
  82. package/templates/hello_world/src/app.tsx +24 -2
  83. package/templates/hello_world/src/tests/__snapshots__/app.tests.tsx.snap +45 -0
  84. package/templates/hello_world/src/tests/app.tests.tsx +86 -0
  85. package/templates/hello_world/utils/use_add_element.ts +48 -0
  86. package/templates/hello_world/utils/use_feature_support.ts +28 -0
  87. package/templates/{dam/webpack.config.cjs → hello_world/webpack.config.ts} +34 -42
  88. package/templates/common/conf/eslint-i18n.mjs +0 -23
  89. package/templates/dam/backend/database/database.ts +0 -42
  90. package/templates/dam/backend/routers/auth.ts +0 -285
  91. package/templates/gen_ai/backend/routers/auth.ts +0 -285
  92. package/templates/gen_ai/src/components/logged_in_status.tsx +0 -44
  93. package/templates/gen_ai/src/services/auth.tsx +0 -31
  94. package/templates/gen_ai/src/services/index.ts +0 -1
  95. /package/templates/{gen_ai → common}/utils/backend/jwt_middleware/index.ts +0 -0
  96. /package/templates/{gen_ai → common}/utils/backend/jwt_middleware/jwt_middleware.ts +0 -0
  97. /package/templates/{gen_ai → common}/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +0 -0
@@ -23,6 +23,17 @@ yargs(hideBin(process.argv))
23
23
  default:
24
24
  process.env.npm_config_use_https?.toLocaleLowerCase().trim() === "true",
25
25
  })
26
+ .option("override-frontend-port", {
27
+ description:
28
+ "Port to run the local development server on. Overrides the frontend port set in the .env file.",
29
+ type: "number",
30
+ alias: "p",
31
+ })
32
+ .option("preview", {
33
+ description: "Open the app in Canva.",
34
+ type: "boolean",
35
+ default: false,
36
+ })
26
37
  .command(
27
38
  "$0",
28
39
  "Starts local development",
@@ -0,0 +1,61 @@
1
+ /* eslint-disable no-console */
2
+
3
+ import type { ChildProcess } from "child_process";
4
+ import { spawn } from "child_process";
5
+ import * as treeKill from "tree-kill";
6
+
7
+ describe("start script", () => {
8
+ let serverProcess: ChildProcess;
9
+
10
+ afterEach(() => {
11
+ if (serverProcess?.pid && !serverProcess.exitCode) {
12
+ treeKill(serverProcess.pid);
13
+ }
14
+ });
15
+
16
+ it("should execute 'npm run start' and start a dev server", async () => {
17
+ const testServerPort = 8089;
18
+ serverProcess = await spawn(
19
+ `npm run start -- -p ${testServerPort} --no-preview`,
20
+ {
21
+ shell: true,
22
+ },
23
+ );
24
+
25
+ if (!serverProcess.pid) {
26
+ throw new Error("Unable to start server");
27
+ }
28
+
29
+ // wait for the server to start and collect output until it reports the running URL
30
+ let output = "";
31
+ await new Promise<void>((resolve, reject) => {
32
+ serverProcess.stdout?.on("data", (data) => {
33
+ output += data.toString();
34
+ if (output.includes("Development URL")) {
35
+ resolve();
36
+ }
37
+ });
38
+
39
+ serverProcess.stderr?.on("data", (data) => {
40
+ console.error("Server process error: ", data.toString());
41
+ reject();
42
+ });
43
+
44
+ // timeout and fail test if the server hasn't correctly started in 10 seconds
45
+ setTimeout(() => {
46
+ if (serverProcess?.pid && !serverProcess.exitCode) {
47
+ treeKill(serverProcess.pid);
48
+ }
49
+ reject(new Error("Test timed out"));
50
+ }, 10000);
51
+ });
52
+
53
+ // check that the server is running and accessible
54
+ const expectedServerURL = `http://localhost:${testServerPort}`;
55
+ expect(output).toContain(expectedServerURL);
56
+ expect(serverProcess.exitCode).toBeNull();
57
+
58
+ // clean up
59
+ treeKill(serverProcess.pid);
60
+ }, 15000); // 15 seconds timeout to allow for the server to start
61
+ });
@@ -0,0 +1,101 @@
1
+ /* eslint-disable no-console */
2
+ import * as debug from "debug";
3
+ import type { Request, Response, NextFunction } from "express";
4
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
5
+ import Express from "express-serve-static-core";
6
+
7
+ /**
8
+ * Prefix your start command with `DEBUG=express:middleware:bearer` to enable debug logging
9
+ * for this middleware
10
+ */
11
+ const debugLogger = debug("express:middleware:bearer");
12
+
13
+ /**
14
+ * Augment the Express request context to include the appId/userId/brandId fields decoded
15
+ * from the JWT.
16
+ */
17
+ declare module "express-serve-static-core" {
18
+ export interface Request {
19
+ user_id: string;
20
+ }
21
+ }
22
+
23
+ const sendUnauthorizedResponse = (res: Response, message?: string) =>
24
+ res.status(401).json({ error: "unauthorized", message });
25
+
26
+ /**
27
+ * An Express.js middleware verifying a Bearer token.
28
+ * This middleware extracts the token from the `Authorization` header.
29
+ *
30
+ * @param getTokenFromRequest - A function that extracts a token from the request. If a token isn't found, throw a `JWTAuthorizationError`.
31
+ * @returns An Express.js middleware for verifying and decoding JWTs.
32
+ */
33
+ export function createBearerMiddleware(
34
+ tokenToUser: (access_token: string) => Promise<string | undefined>,
35
+ getTokenFromRequest: GetTokenFromRequest = getTokenFromHttpHeader,
36
+ ): (req: Request, res: Response, next: NextFunction) => void {
37
+ return async (req, res, next) => {
38
+ try {
39
+ debugLogger(`processing token for '${req.url}'`);
40
+
41
+ const token = await getTokenFromRequest(req);
42
+ const user = await tokenToUser(token);
43
+
44
+ if (!user) {
45
+ throw new AuthorizationError("Token is invalid");
46
+ }
47
+
48
+ req.user_id = user;
49
+
50
+ next();
51
+ } catch (e) {
52
+ if (e instanceof AuthorizationError) {
53
+ return sendUnauthorizedResponse(res, e.message);
54
+ }
55
+
56
+ next(e);
57
+ }
58
+ };
59
+ }
60
+
61
+ export type GetTokenFromRequest = (req: Request) => Promise<string> | string;
62
+
63
+ export const getTokenFromHttpHeader: GetTokenFromRequest = (
64
+ req: Request,
65
+ ): string => {
66
+ // The names of a HTTP header bearing the JWT, and a scheme
67
+ const headerName = "Authorization";
68
+ const schemeName = "Bearer";
69
+
70
+ const header = req.header(headerName);
71
+ if (!header) {
72
+ throw new AuthorizationError(`Missing the "${headerName}" header`);
73
+ }
74
+
75
+ if (!header.match(new RegExp(`^${schemeName}\\s+[^\\s]+$`, "i"))) {
76
+ console.trace(
77
+ `jwtMiddleware: failed to match token in "${headerName}" header`,
78
+ );
79
+ throw new AuthorizationError(
80
+ `Missing a "${schemeName}" token in the "${headerName}" header`,
81
+ );
82
+ }
83
+
84
+ const token = header.replace(new RegExp(`^${schemeName}\\s+`, "i"), "");
85
+
86
+ return token;
87
+ };
88
+
89
+ /**
90
+ * A class representing JWT validation errors in the JWT middleware.
91
+ * The error message provided to the constructor will be forwarded to the
92
+ * API consumer trying to access a JWT-protected endpoint.
93
+ * @private
94
+ */
95
+ export class AuthorizationError extends Error {
96
+ constructor(message: string) {
97
+ super(message);
98
+
99
+ Object.setPrototypeOf(this, AuthorizationError.prototype);
100
+ }
101
+ }
@@ -0,0 +1 @@
1
+ export { createBearerMiddleware } from "./bearer_middleware";
@@ -0,0 +1,192 @@
1
+ /* eslint-disable @typescript-eslint/no-require-imports */
2
+ import type { NextFunction, Request, Response } from "express";
3
+ import type {
4
+ createBearerMiddleware,
5
+ GetTokenFromRequest,
6
+ } from "../bearer_middleware";
7
+
8
+ type Middleware = (req: Request, res: Response, next: NextFunction) => void;
9
+
10
+ describe("createBearerMiddleware", () => {
11
+ let fakeGetTokenFromRequest: jest.MockedFn<GetTokenFromRequest>;
12
+ let verify: jest.MockedFn<(token: string) => Promise<string | undefined>>;
13
+
14
+ let req: Request;
15
+ let res: Response;
16
+ let next: jest.MockedFn<() => void>;
17
+
18
+ let AuthorizationError: typeof Error;
19
+ let createBearerMiddlewareFn: typeof createBearerMiddleware;
20
+ let bearerMiddleware: Middleware;
21
+
22
+ beforeEach(() => {
23
+ jest.resetAllMocks();
24
+ jest.resetModules();
25
+
26
+ fakeGetTokenFromRequest = jest.fn();
27
+ verify = jest.fn();
28
+
29
+ const middlewareModule = require("../bearer_middleware");
30
+ createBearerMiddlewareFn = middlewareModule.createBearerMiddleware;
31
+ AuthorizationError = middlewareModule.AuthorizationError;
32
+ });
33
+
34
+ describe("When called", () => {
35
+ beforeEach(() => {
36
+ req = {
37
+ header: (_name: string) => undefined,
38
+ } as Request;
39
+
40
+ res = {
41
+ status: jest.fn().mockReturnThis(),
42
+ json: jest.fn().mockReturnThis(),
43
+ send: jest.fn().mockReturnThis(),
44
+ } as unknown as Response;
45
+
46
+ next = jest.fn();
47
+
48
+ bearerMiddleware = createBearerMiddlewareFn(
49
+ verify,
50
+ fakeGetTokenFromRequest,
51
+ );
52
+ });
53
+
54
+ describe("When `getTokenFromRequest` throws an exception ('Fake error')", () => {
55
+ beforeEach(() => {
56
+ fakeGetTokenFromRequest.mockRejectedValue(
57
+ new AuthorizationError("Fake error"),
58
+ );
59
+ });
60
+
61
+ it(`Does not call next() and returns HTTP 401 with error = "unauthorized" and message = "Fake error"`, async () => {
62
+ expect.assertions(8);
63
+
64
+ expect(fakeGetTokenFromRequest).not.toHaveBeenCalled();
65
+ await bearerMiddleware(req, res, next);
66
+
67
+ expect(fakeGetTokenFromRequest).toHaveBeenCalledTimes(1);
68
+ expect(fakeGetTokenFromRequest).toHaveBeenLastCalledWith(req);
69
+
70
+ expect(res.status).toHaveBeenCalledTimes(1);
71
+ expect(res.status).toHaveBeenLastCalledWith(401);
72
+
73
+ expect(res.json).toHaveBeenCalledTimes(1);
74
+ expect(res.json).toHaveBeenLastCalledWith({
75
+ error: "unauthorized",
76
+ message: "Fake error",
77
+ });
78
+
79
+ expect(next).not.toHaveBeenCalled();
80
+ });
81
+ });
82
+
83
+ describe("When the middleware cannot verify the token", () => {
84
+ beforeEach(() => {
85
+ fakeGetTokenFromRequest.mockReturnValue("TOKEN");
86
+
87
+ verify.mockImplementation(() => Promise.resolve(undefined));
88
+ });
89
+
90
+ it(`Does not call next() and returns HTTP 401 with error = "unauthorized" and message = "Token is invalid"`, async () => {
91
+ expect.assertions(5);
92
+
93
+ await bearerMiddleware(req, res, next);
94
+
95
+ expect(res.status).toHaveBeenCalledTimes(1);
96
+ expect(res.status).toHaveBeenLastCalledWith(401);
97
+
98
+ expect(res.json).toHaveBeenCalledTimes(1);
99
+ expect(res.json).toHaveBeenLastCalledWith({
100
+ error: "unauthorized",
101
+ message: "Token is invalid",
102
+ });
103
+
104
+ expect(next).not.toHaveBeenCalled();
105
+ });
106
+ });
107
+ });
108
+ });
109
+
110
+ describe("getTokenFromHttpHeader", () => {
111
+ let getHeader: jest.MockedFn<(name: string) => string | undefined>;
112
+ let req: Request;
113
+ let getTokenFromHttpHeader: (req: Request) => string;
114
+ let AuthorizationError: typeof Error;
115
+
116
+ beforeEach(() => {
117
+ getHeader = jest.fn();
118
+ req = {
119
+ header: (name: string) => getHeader(name),
120
+ } as Request;
121
+
122
+ const bearerMiddlewareModule = require("../bearer_middleware");
123
+ getTokenFromHttpHeader = bearerMiddlewareModule.getTokenFromHttpHeader;
124
+ AuthorizationError = bearerMiddlewareModule.AuthorizationError;
125
+ });
126
+
127
+ describe("When the 'Authorization' header is missing", () => {
128
+ beforeEach(() => {
129
+ getHeader.mockReturnValue(undefined);
130
+ });
131
+
132
+ it(`Throws a AuthorizationError with message = 'Missing the "Authorization" header'`, async () => {
133
+ expect.assertions(3);
134
+
135
+ expect(() => getTokenFromHttpHeader(req)).toThrow(
136
+ new AuthorizationError('Missing the "Authorization" header'),
137
+ );
138
+ expect(getHeader).toHaveBeenCalledTimes(1);
139
+ expect(getHeader).toHaveBeenLastCalledWith("Authorization");
140
+ });
141
+ });
142
+
143
+ describe("When the 'Authorization' header doesn't have a Bearer scheme", () => {
144
+ beforeEach(() => {
145
+ getHeader.mockReturnValue("Beerer FAKE_TOKEN");
146
+ });
147
+
148
+ it(`Throws a AuthorizationError with message = 'Missing a "Bearer" token in the "Authorization" header''`, async () => {
149
+ expect.assertions(3);
150
+
151
+ expect(() => getTokenFromHttpHeader(req)).toThrow(
152
+ new AuthorizationError(
153
+ 'Missing a "Bearer" token in the "Authorization" header',
154
+ ),
155
+ );
156
+ expect(getHeader).toHaveBeenCalledTimes(1);
157
+ expect(getHeader).toHaveBeenLastCalledWith("Authorization");
158
+ });
159
+ });
160
+
161
+ describe("When the 'Authorization' Bearer scheme header doesn't have a token", () => {
162
+ beforeEach(() => {
163
+ getHeader.mockReturnValue("Bearer ");
164
+ });
165
+
166
+ it(`Throws a AuthorizationError with message = 'Missing a "Bearer" token in the "Authorization" header'`, async () => {
167
+ expect.assertions(3);
168
+
169
+ expect(() => getTokenFromHttpHeader(req)).toThrow(
170
+ new AuthorizationError(
171
+ 'Missing a "Bearer" token in the "Authorization" header',
172
+ ),
173
+ );
174
+ expect(getHeader).toHaveBeenCalledTimes(1);
175
+ expect(getHeader).toHaveBeenLastCalledWith("Authorization");
176
+ });
177
+ });
178
+
179
+ describe("When the 'Authorization' Bearer scheme header has a token", () => {
180
+ beforeEach(() => {
181
+ getHeader.mockReturnValue("Bearer TOKEN");
182
+ });
183
+
184
+ it(`Returns the token`, async () => {
185
+ expect.assertions(3);
186
+
187
+ expect(getTokenFromHttpHeader(req)).toEqual("TOKEN");
188
+ expect(getHeader).toHaveBeenCalledTimes(1);
189
+ expect(getHeader).toHaveBeenLastCalledWith("Authorization");
190
+ });
191
+ });
192
+ });
@@ -0,0 +1,48 @@
1
+ import type {
2
+ EmbedElement,
3
+ ImageElement,
4
+ RichtextElement,
5
+ TableElement,
6
+ TextElement,
7
+ VideoElement,
8
+ } from "@canva/design";
9
+ import { addElementAtCursor, addElementAtPoint } from "@canva/design";
10
+ import { useFeatureSupport } from "./use_feature_support";
11
+ import { features } from "@canva/platform";
12
+ import { useEffect, useState } from "react";
13
+
14
+ type AddElementParams =
15
+ | ImageElement
16
+ | VideoElement
17
+ | EmbedElement
18
+ | TextElement
19
+ | RichtextElement
20
+ | TableElement;
21
+
22
+ export const useAddElement = () => {
23
+ const isSupported = useFeatureSupport();
24
+
25
+ // Store a wrapped addElement function that checks feature support
26
+ const [addElement, setAddElement] = useState(() => {
27
+ return (element: AddElementParams) => {
28
+ if (features.isSupported(addElementAtPoint)) {
29
+ return addElementAtPoint(element);
30
+ } else if (features.isSupported(addElementAtCursor)) {
31
+ return addElementAtCursor(element);
32
+ }
33
+ };
34
+ });
35
+
36
+ useEffect(() => {
37
+ const addElement = (element: AddElementParams) => {
38
+ if (isSupported(addElementAtPoint)) {
39
+ return addElementAtPoint(element);
40
+ } else if (isSupported(addElementAtCursor)) {
41
+ return addElementAtCursor(element);
42
+ }
43
+ };
44
+ setAddElement(() => addElement);
45
+ }, [isSupported]);
46
+
47
+ return addElement;
48
+ };
@@ -0,0 +1,28 @@
1
+ import { features } from "@canva/platform";
2
+ import type { Feature } from "@canva/platform";
3
+ import { useState, useEffect } from "react";
4
+
5
+ /**
6
+ * This hook allows re-rendering of a React component whenever
7
+ * the state of feature support changes in Canva.
8
+ *
9
+ * @returns isSupported - callback to inspect a Canva SDK method.
10
+ **/
11
+ export function useFeatureSupport() {
12
+ // Store a wrapped function that checks feature support
13
+ const [isSupported, setIsSupported] = useState(() => {
14
+ return (...args: Feature[]) => features.isSupported(...args);
15
+ });
16
+
17
+ useEffect(() => {
18
+ // create new function ref when feature support changes to trigger
19
+ // re-render
20
+ return features.registerOnSupportChange(() => {
21
+ setIsSupported(() => {
22
+ return (...args: Feature[]) => features.isSupported(...args);
23
+ });
24
+ });
25
+ }, []);
26
+
27
+ return isSupported;
28
+ }
@@ -1,30 +1,33 @@
1
- require("dotenv").config();
2
- const path = require("path");
3
- const TerserPlugin = require("terser-webpack-plugin");
4
- const { DefinePlugin, optimize } = require("webpack");
5
- const chalk = require("chalk");
6
- const { transform } = require("@formatjs/ts-transformer");
1
+ import type { Configuration } from "webpack";
2
+ import { DefinePlugin, optimize } from "webpack";
3
+ import * as path from "path";
4
+ import * as TerserPlugin from "terser-webpack-plugin";
5
+ import { transform } from "@formatjs/ts-transformer";
6
+ import * as chalk from "chalk";
7
+ import { config } from "dotenv";
8
+ import { Configuration as DevServerConfiguration } from "webpack-dev-server";
7
9
 
8
- /**
9
- *
10
- * @param {Object} [options]
11
- * @param {string} [options.appEntry=./src/index.tsx]
12
- * @param {string} [options.backendHost]
13
- * @param {Object} [options.devConfig]
14
- * @param {number} [options.devConfig.port]
15
- * @param {boolean} [options.devConfig.enableHmr]
16
- * @param {boolean} [options.devConfig.enableHttps]
17
- * @param {string} [options.devConfig.appOrigin]
18
- * @param {string} [options.devConfig.appId] - Deprecated in favour of appOrigin
19
- * @param {string} [options.devConfig.certFile]
20
- * @param {string} [options.devConfig.keyFile]
21
- * @returns {Object}
22
- */
23
- function buildConfig({
10
+ config();
11
+
12
+ type DevConfig = {
13
+ port: number;
14
+ enableHmr: boolean;
15
+ enableHttps: boolean;
16
+ appOrigin?: string;
17
+ appId?: string; // Deprecated in favour of appOrigin
18
+ certFile?: string;
19
+ keyFile?: string;
20
+ };
21
+
22
+ export function buildConfig({
24
23
  devConfig,
25
24
  appEntry = path.join(process.cwd(), "src", "index.tsx"),
26
25
  backendHost = process.env.CANVA_BACKEND_HOST,
27
- } = {}) {
26
+ }: {
27
+ devConfig?: DevConfig;
28
+ appEntry?: string;
29
+ backendHost?: string;
30
+ } = {}): Configuration & DevServerConfiguration {
28
31
  const mode = devConfig ? "development" : "production";
29
32
 
30
33
  if (!backendHost) {
@@ -173,32 +176,23 @@ function buildConfig({
173
176
  }),
174
177
  // Apps can only submit a single JS file via the developer portal
175
178
  new optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
176
- ],
179
+ ].filter(Boolean),
177
180
  ...buildDevConfig(devConfig),
178
181
  };
179
182
  }
180
183
 
181
- /**
182
- *
183
- * @param {Object} [options]
184
- * @param {number} [options.port]
185
- * @param {boolean} [options.enableHmr]
186
- * @param {boolean} [options.enableHttps]
187
- * @param {string} [options.appOrigin]
188
- * @param {string} [options.appId] - Deprecated in favour of appOrigin
189
- * @param {string} [options.certFile]
190
- * @param {string} [options.keyFile]
191
- * @returns {Object|null}
192
- */
193
- function buildDevConfig(options) {
184
+ function buildDevConfig(options?: DevConfig): {
185
+ devtool?: string;
186
+ devServer?: DevServerConfiguration;
187
+ } {
194
188
  if (!options) {
195
- return null;
189
+ return {};
196
190
  }
197
191
 
198
192
  const { port, enableHmr, appOrigin, appId, enableHttps, certFile, keyFile } =
199
193
  options;
200
194
 
201
- let devServer = {
195
+ let devServer: DevServerConfiguration = {
202
196
  server: enableHttps
203
197
  ? {
204
198
  type: "https",
@@ -265,6 +259,4 @@ function buildDevConfig(options) {
265
259
  };
266
260
  }
267
261
 
268
- module.exports = () => buildConfig();
269
-
270
- module.exports.buildConfig = buildConfig;
262
+ export default buildConfig;
@@ -1,9 +1,8 @@
1
- .idea
2
- .ssl
3
- node_modules
4
1
  .DS_Store
5
- yarn-error.log
6
- dist
7
- secrets.json
8
2
  .env
3
+ .idea
4
+ .ssl
5
+ *.log*
9
6
  **/*/db.json
7
+ dist
8
+ node_modules
@@ -0,0 +1 @@
1
+ 20.10.0
@@ -0,0 +1,21 @@
1
+ {
2
+ "arrowParens": "always",
3
+ "bracketSpacing": true,
4
+ "endOfLine": "lf",
5
+ "htmlWhitespaceSensitivity": "css",
6
+ "insertPragma": false,
7
+ "singleAttributePerLine": false,
8
+ "bracketSameLine": false,
9
+ "jsxSingleQuote": false,
10
+ "printWidth": 80,
11
+ "proseWrap": "preserve",
12
+ "quoteProps": "as-needed",
13
+ "requirePragma": false,
14
+ "semi": true,
15
+ "singleQuote": false,
16
+ "tabWidth": 2,
17
+ "trailingComma": "all",
18
+ "useTabs": false,
19
+ "embeddedLanguageFormatting": "auto",
20
+ "experimentalTernaries": false
21
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ // For developers using vscode we recommend the following extensions. Following
3
+ // and listening to the formatting and linting guidelines can help with
4
+ // implementation quality and in some instances reduce app review timelines.
5
+ "recommendations": ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint"]
6
+ }