@canva/cli 0.0.1-beta.8 → 1.0.0

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 (150) hide show
  1. package/README.md +131 -31
  2. package/cli.js +852 -427
  3. package/lib/cjs/index.cjs +11 -0
  4. package/lib/esm/index.mjs +11 -0
  5. package/package.json +19 -4
  6. package/templates/base/backend/routers/auth.ts +4 -4
  7. package/templates/base/backend/routers/oauth.ts +3 -3
  8. package/templates/base/eslint.config.mjs +2 -25
  9. package/templates/base/package.json +29 -26
  10. package/templates/base/scripts/ssl/ssl.ts +1 -1
  11. package/templates/base/scripts/start/app_runner.ts +42 -5
  12. package/templates/base/scripts/start/context.ts +12 -6
  13. package/templates/base/scripts/start/start.ts +12 -1
  14. package/templates/base/scripts/start/tests/start.tests.ts +61 -0
  15. package/templates/base/utils/backend/base_backend/create.ts +3 -3
  16. package/templates/base/utils/backend/bearer_middleware/bearer_middleware.ts +2 -2
  17. package/templates/base/utils/backend/jwt_middleware/jwt_middleware.ts +4 -4
  18. package/templates/base/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +1 -1
  19. package/templates/base/utils/use_add_element.ts +1 -1
  20. package/templates/base/utils/use_feature_support.ts +1 -1
  21. package/templates/{dam/webpack.config.cjs → base/webpack.config.ts} +51 -67
  22. package/templates/common/.env.template +3 -3
  23. package/templates/common/README.md +16 -17
  24. package/templates/common/jest.config.mjs +29 -2
  25. package/templates/common/jest.setup.ts +20 -0
  26. package/templates/common/utils/backend/base_backend/create.ts +3 -3
  27. package/templates/common/utils/backend/jwt_middleware/jwt_middleware.ts +4 -4
  28. package/templates/common/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +1 -1
  29. package/templates/common/utils/tests/table_wrapper.tests.ts +1 -1
  30. package/templates/common/utils/use_add_element.ts +1 -1
  31. package/templates/common/utils/use_feature_support.ts +1 -1
  32. package/templates/dam/backend/routers/dam.ts +24 -20
  33. package/templates/dam/backend/server.ts +1 -1
  34. package/templates/dam/canva-app.json +16 -0
  35. package/templates/dam/eslint.config.mjs +2 -28
  36. package/templates/dam/package.json +43 -40
  37. package/templates/dam/scripts/ssl/ssl.ts +1 -1
  38. package/templates/dam/scripts/start/app_runner.ts +42 -5
  39. package/templates/dam/scripts/start/context.ts +12 -6
  40. package/templates/dam/scripts/start/start.ts +12 -1
  41. package/templates/dam/scripts/start/tests/start.tests.ts +61 -0
  42. package/templates/dam/src/app.tsx +24 -3
  43. package/templates/dam/src/config.ts +212 -87
  44. package/templates/dam/src/index.tsx +1 -1
  45. package/templates/dam/utils/backend/base_backend/create.ts +3 -3
  46. package/templates/dam/utils/backend/jwt_middleware/jwt_middleware.ts +4 -4
  47. package/templates/dam/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +1 -1
  48. package/templates/{base/webpack.config.cjs → dam/webpack.config.ts} +51 -67
  49. package/templates/data_connector/README.md +84 -0
  50. package/templates/data_connector/canva-app.json +21 -0
  51. package/templates/data_connector/declarations/declarations.d.ts +29 -0
  52. package/templates/data_connector/eslint.config.mjs +14 -0
  53. package/templates/data_connector/package.json +91 -0
  54. package/templates/data_connector/scripts/ssl/ssl.ts +131 -0
  55. package/templates/data_connector/scripts/start/app_runner.ts +201 -0
  56. package/templates/data_connector/scripts/start/context.ts +171 -0
  57. package/templates/data_connector/scripts/start/start.ts +46 -0
  58. package/templates/data_connector/scripts/start/tests/start.tests.ts +61 -0
  59. package/templates/data_connector/src/api/connect_client.ts +6 -0
  60. package/templates/data_connector/src/api/data_source.ts +96 -0
  61. package/templates/data_connector/src/api/data_sources/designs.tsx +296 -0
  62. package/templates/data_connector/src/api/data_sources/index.ts +4 -0
  63. package/templates/data_connector/src/api/data_sources/templates.tsx +329 -0
  64. package/templates/data_connector/src/api/fetch_data_table.ts +55 -0
  65. package/templates/data_connector/src/api/index.ts +4 -0
  66. package/templates/data_connector/src/api/oauth.ts +8 -0
  67. package/templates/data_connector/src/api/tests/data_source.test.tsx +99 -0
  68. package/templates/data_connector/src/app.tsx +20 -0
  69. package/templates/data_connector/src/components/app_error.tsx +15 -0
  70. package/templates/data_connector/src/components/footer.tsx +26 -0
  71. package/templates/data_connector/src/components/header.tsx +40 -0
  72. package/templates/data_connector/src/components/index.ts +3 -0
  73. package/templates/data_connector/src/components/inputs/messages.tsx +99 -0
  74. package/templates/data_connector/src/components/inputs/search_filter.tsx +108 -0
  75. package/templates/data_connector/src/components/inputs/select_field.tsx +26 -0
  76. package/templates/data_connector/src/context/app_context.tsx +124 -0
  77. package/templates/data_connector/src/context/index.ts +2 -0
  78. package/templates/data_connector/src/context/use_app_context.ts +17 -0
  79. package/templates/data_connector/src/entrypoint.tsx +70 -0
  80. package/templates/data_connector/src/home.tsx +21 -0
  81. package/templates/data_connector/src/index.tsx +68 -0
  82. package/templates/data_connector/src/pages/data_source_config.tsx +9 -0
  83. package/templates/data_connector/src/pages/error.tsx +37 -0
  84. package/templates/data_connector/src/pages/index.ts +4 -0
  85. package/templates/data_connector/src/pages/login.tsx +145 -0
  86. package/templates/data_connector/src/pages/select_source.tsx +24 -0
  87. package/templates/data_connector/src/routes/index.ts +2 -0
  88. package/templates/data_connector/src/routes/protected_route.tsx +25 -0
  89. package/templates/data_connector/src/routes/routes.tsx +46 -0
  90. package/templates/data_connector/src/utils/data_params.ts +17 -0
  91. package/templates/data_connector/src/utils/data_table.ts +115 -0
  92. package/templates/data_connector/src/utils/fetch_result.ts +36 -0
  93. package/templates/data_connector/src/utils/index.ts +2 -0
  94. package/templates/data_connector/src/utils/tests/data_table.test.ts +133 -0
  95. package/templates/data_connector/styles/components.css +38 -0
  96. package/templates/data_connector/tsconfig.json +54 -0
  97. package/templates/{gen_ai/webpack.config.cjs → data_connector/webpack.config.ts} +51 -67
  98. package/templates/gen_ai/backend/routers/image.ts +8 -8
  99. package/templates/gen_ai/backend/server.ts +1 -1
  100. package/templates/gen_ai/canva-app.json +20 -0
  101. package/templates/gen_ai/eslint.config.mjs +2 -25
  102. package/templates/gen_ai/package.json +47 -42
  103. package/templates/gen_ai/scripts/ssl/ssl.ts +1 -1
  104. package/templates/gen_ai/scripts/start/app_runner.ts +42 -5
  105. package/templates/gen_ai/scripts/start/context.ts +12 -6
  106. package/templates/gen_ai/scripts/start/start.ts +12 -1
  107. package/templates/gen_ai/scripts/start/tests/start.tests.ts +61 -0
  108. package/templates/gen_ai/src/app.tsx +16 -10
  109. package/templates/gen_ai/src/components/footer.tsx +4 -4
  110. package/templates/gen_ai/src/components/image_grid.tsx +1 -1
  111. package/templates/gen_ai/src/components/loading_results.tsx +8 -8
  112. package/templates/gen_ai/src/components/prompt_input.tsx +3 -3
  113. package/templates/gen_ai/src/components/remaining_credits.tsx +1 -1
  114. package/templates/gen_ai/src/components/report_box.tsx +1 -1
  115. package/templates/gen_ai/src/components/tests/remaining_credit.tests.tsx +43 -0
  116. package/templates/gen_ai/src/home.tsx +13 -0
  117. package/templates/gen_ai/src/index.tsx +2 -18
  118. package/templates/gen_ai/src/pages/error.tsx +2 -2
  119. package/templates/gen_ai/src/pages/results.tsx +1 -1
  120. package/templates/gen_ai/src/routes/routes.tsx +2 -2
  121. package/templates/gen_ai/utils/backend/base_backend/create.ts +3 -3
  122. package/templates/gen_ai/utils/backend/bearer_middleware/bearer_middleware.ts +2 -2
  123. package/templates/{hello_world/webpack.config.cjs → gen_ai/webpack.config.ts} +51 -67
  124. package/templates/hello_world/canva-app.json +16 -0
  125. package/templates/hello_world/eslint.config.mjs +2 -25
  126. package/templates/hello_world/package.json +42 -37
  127. package/templates/hello_world/scripts/copy_env.ts +10 -0
  128. package/templates/hello_world/scripts/ssl/ssl.ts +1 -1
  129. package/templates/hello_world/scripts/start/app_runner.ts +42 -5
  130. package/templates/hello_world/scripts/start/context.ts +12 -6
  131. package/templates/hello_world/scripts/start/start.ts +12 -1
  132. package/templates/hello_world/scripts/start/tests/start.tests.ts +61 -0
  133. package/templates/hello_world/src/app.tsx +21 -1
  134. package/templates/hello_world/src/index.tsx +1 -1
  135. package/templates/hello_world/src/tests/__snapshots__/app.tests.tsx.snap +45 -0
  136. package/templates/hello_world/src/tests/app.tests.tsx +86 -0
  137. package/templates/hello_world/utils/use_add_element.ts +1 -1
  138. package/templates/hello_world/utils/use_feature_support.ts +1 -1
  139. package/templates/hello_world/webpack.config.ts +254 -0
  140. package/templates/optional/.cursor/mcp.json +8 -0
  141. package/templates/optional/.vscode/mcp.json +9 -0
  142. package/templates/optional/AGENTS.md +76 -0
  143. package/templates/optional/CLAUDE.md +76 -0
  144. package/templates/common/conf/eslint-general.mjs +0 -303
  145. package/templates/common/conf/eslint-i18n.mjs +0 -38
  146. /package/templates/base/scripts/{copy-env.ts → copy_env.ts} +0 -0
  147. /package/templates/dam/scripts/{copy-env.ts → copy_env.ts} +0 -0
  148. /package/templates/{gen_ai/scripts/copy-env.ts → data_connector/scripts/copy_env.ts} +0 -0
  149. /package/templates/{hello_world/scripts/copy-env.ts → gen_ai/scripts/copy_env.ts} +0 -0
  150. /package/templates/{common → optional}/.vscode/extensions.json +0 -0
@@ -0,0 +1,84 @@
1
+ # Data Connector Template
2
+
3
+ ## Overview
4
+
5
+ This template provides a working example of a data connector app which uses the Canva Connect API as a data source. It demonstrates how to log in with OAuth and then fetch data from an external source, using Canva's API for listing Designs and Brand Templates. There are instructions below for how to configure your authentication settings to try it out.
6
+
7
+ The template provides a list / detail interface for choosing a data source. The user would first select the data source they want to import from a list. Next, they configure the data source to select the desired query by applying search filters or sort criteria. The app turns their configured data source into an API request and then returns the data in a table format for use in a Canva Design.
8
+
9
+ ## Best Practices
10
+
11
+ This template captures best practices for improving user experience in your application.
12
+
13
+ ### State Management
14
+
15
+ In this template, we've set up state management using `React Context`. It's just one way to do it, not a strict rule. If your app gets more complicated, you might want to check out other options like `Redux` or `MobX`.
16
+
17
+ ### Routing
18
+
19
+ As your application evolves, you may find the need for routing to manage multiple views or pages. In this template, we've integrated React Router to illustrate how routing can facilitate seamless navigation between various components.
20
+
21
+ ### App UI Kit
22
+
23
+ The App UI Kit is a React-based component library designed for creating apps that emulate Canva's look and feel. We strongly recommend using the App UI Kit if you're planning to release an app to the public, because this makes it easier to comply with our [design guidelines](https://www.canva.dev/docs/apps/design-guidelines/).
24
+
25
+ ### Data Sources
26
+
27
+ A data source is a type of data that this connector can retrieve. It has:
28
+
29
+ - properties that define the configuration for this source - e.g. search criteria, ordering conditions, selection filters
30
+ - UI for how to edit this configuration
31
+ - columns to display for each data item
32
+ - logic for how to fetch the data from an external API
33
+
34
+ The initial data sources for the Canva Connect API (Designs and Brand Templates) in this template are located in `src/api/data_sources/`.
35
+
36
+ This template provides a `DataSourceHandler` class in `src/api/data_source.ts` as a suggested starting point for defining a reusable concept for a data source and convert API responses into data table outputs.
37
+
38
+ ## Setup - Authentication
39
+
40
+ This template is a working app that reads the [Canva Connect API](https://www.canva.dev/docs/connect/).
41
+
42
+ To run it and authenticate with the Canva Connect API via OAuth you must first complete some authentication setup steps.
43
+
44
+ ### 0. Set up an App
45
+
46
+ - If not already handled by the Canva CLI, you need to create an app.
47
+ Go to [Your Apps](https://www.canva.com/developers/apps) and create an app.
48
+ - On the **Configuration** page, enable the `Data Connector` intent.
49
+
50
+ ### 1. Set up a Connect API Integration
51
+
52
+ - Go to [Your Integrations](https://www.canva.com/developers/integrations/connect-api) and create a new integration
53
+ - On the **Configuration** page, generate a client secret - you need the client ID and client secret in the app setup.
54
+ - On the **Scopes** page, add the `designs:meta` and `brandtemplate:meta` read scopes
55
+ - On the **Authentication** page, set `https://www.canva.com/apps/oauth/authorized` as an Authorized redirect
56
+
57
+ ### 2. Set up OAuth for the app
58
+
59
+ - Go to [Your Apps](https://www.canva.com/developers/apps) and open your data connector app.
60
+ - On the **Authentication** page, add an OAuth 2.0 provider with the following settings:
61
+ > Provider: `CanvaConnect`
62
+ >
63
+ > Client ID: `(generated in step 1)`
64
+ >
65
+ > Client secret: `(generated in step 1)`
66
+ >
67
+ > Credential transfer mode: `Headers (default)`
68
+ >
69
+ > Authorization server URL: `https://www.canva.com/api/oauth/authorize`
70
+ >
71
+ > Token exchange URL: `https://api.canva.com/rest/v1/oauth/token`
72
+ >
73
+ > Proof Key for Code Exchange (PKCE): `Enabled`
74
+
75
+ ### 3. Run your app
76
+
77
+ - Run `npm start` to run the app.
78
+ - You should be able to log in and then choose from the available data sources.
79
+
80
+ ### To use another OAuth source
81
+
82
+ - `src/api/oauth.ts` has a `scope` property that will be used in the oauth flow.
83
+ - This template starts with the scope for the Canva Connect API login set to `["design:meta:read", "brandtemplate:meta:read"]`
84
+ - It should match the scopes set in Step 1.
@@ -0,0 +1,21 @@
1
+ {
2
+ "$schema": "https://www.canva.dev/schemas/app/v1/manifest-schema.json",
3
+ "manifest_schema_version": 1,
4
+ "runtime": {
5
+ "permissions": [
6
+ {
7
+ "name": "canva:design:content:read",
8
+ "type": "mandatory"
9
+ },
10
+ {
11
+ "name": "canva:design:content:write",
12
+ "type": "mandatory"
13
+ }
14
+ ]
15
+ },
16
+ "intent": {
17
+ "data_connector": {
18
+ "enrolled": true
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,29 @@
1
+ declare module "*.css" {
2
+ const styles: { [className: string]: string };
3
+ export = styles;
4
+ }
5
+
6
+ declare module "*.jpg" {
7
+ const content: string;
8
+ export default content;
9
+ }
10
+
11
+ declare module "*.jpeg" {
12
+ const content: string;
13
+ export default content;
14
+ }
15
+
16
+ declare module "*.png" {
17
+ const content: string;
18
+ export default content;
19
+ }
20
+
21
+ declare module "*.svg" {
22
+ const content: React.FunctionComponent<{
23
+ size?: "tiny" | "small" | "medium" | "large";
24
+ className?: string;
25
+ }>;
26
+ export default content;
27
+ }
28
+
29
+ declare const BACKEND_HOST: string;
@@ -0,0 +1,14 @@
1
+ import canvaPlugin from "@canva/app-eslint-plugin";
2
+
3
+ export default [
4
+ {
5
+ ignores: [
6
+ "**/node_modules/",
7
+ "**/dist",
8
+ "**/*.d.ts",
9
+ "**/*.d.tsx",
10
+ "**/*.config.*",
11
+ ],
12
+ },
13
+ ...canvaPlugin.configs.apps,
14
+ ];
@@ -0,0 +1,91 @@
1
+ {
2
+ "private": true,
3
+ "name": "data_connector",
4
+ "description": "An example Canva Data Connector App",
5
+ "scripts": {
6
+ "extract": "formatjs extract \"src/**/*.{ts,tsx}\" --out-file dist/messages_en.json",
7
+ "build": "webpack --config webpack.config.ts --mode production && npm run extract",
8
+ "format": "prettier '**/*.{css,ts,tsx}' --no-config --write",
9
+ "format:check": "prettier '**/*.{css,ts,tsx}' --no-config --check --ignore-path",
10
+ "format:file": "prettier $1 --no-config --write",
11
+ "lint": "eslint .",
12
+ "lint:fix": "eslint . --fix",
13
+ "lint:types": "tsc",
14
+ "start": "ts-node ./scripts/start/start.ts",
15
+ "start:preview": "npm run start -- --preview",
16
+ "test": "jest --no-cache",
17
+ "test:watch": "jest --watchAll",
18
+ "test:update": "npm run test -- -u",
19
+ "postinstall": "ts-node ./scripts/copy_env.ts"
20
+ },
21
+ "dependencies": {
22
+ "@canva/app-i18n-kit": "^1.0.3",
23
+ "@canva/app-ui-kit": "^4.10.0",
24
+ "@canva/asset": "^2.2.1",
25
+ "@canva/design": "^2.7.2",
26
+ "@canva/error": "^2.1.0",
27
+ "@canva/intents": "^2.0.0",
28
+ "@canva/platform": "^2.2.0",
29
+ "@canva/user": "^2.1.1",
30
+ "react": "18.3.1",
31
+ "react-dom": "18.3.1",
32
+ "react-error-boundary": "6.0.0",
33
+ "react-intl": "6.8.7",
34
+ "react-router-dom": "7.6.3"
35
+ },
36
+ "devDependencies": {
37
+ "@canva/app-eslint-plugin": "^1.0.0-beta.3",
38
+ "@canva/cli": ">= 0.0.1-beta.13",
39
+ "@formatjs/cli": "6.7.2",
40
+ "@formatjs/ts-transformer": "3.14.0",
41
+ "@ngrok/ngrok": "1.5.1",
42
+ "@pmmmwh/react-refresh-webpack-plugin": "0.6.1",
43
+ "@svgr/webpack": "8.1.0",
44
+ "@testing-library/react": "16.3.0",
45
+ "@types/express": "4.17.21",
46
+ "@types/express-serve-static-core": "5.0.6",
47
+ "@types/jest": "29.5.14",
48
+ "@types/jsonwebtoken": "9.0.10",
49
+ "@types/node": "20.19.2",
50
+ "@types/node-fetch": "2.6.12",
51
+ "@types/node-forge": "1.3.11",
52
+ "@types/nodemon": "1.19.6",
53
+ "@types/react": "18.3.12",
54
+ "@types/react-dom": "18.3.1",
55
+ "@types/webpack-env": "1.18.8",
56
+ "chalk": "4.1.2",
57
+ "cli-table3": "0.6.5",
58
+ "css-loader": "7.1.2",
59
+ "css-modules-typescript-loader": "4.0.1",
60
+ "cssnano": "7.0.7",
61
+ "debug": "4.4.1",
62
+ "dotenv": "16.6.0",
63
+ "express": "4.21.2",
64
+ "express-basic-auth": "1.2.1",
65
+ "jest": "29.7.0",
66
+ "jest-css-modules-transform": "4.4.2",
67
+ "jest-environment-jsdom": "29.7.0",
68
+ "jsonwebtoken": "9.0.2",
69
+ "jwks-rsa": "3.2.0",
70
+ "mini-css-extract-plugin": "2.9.2",
71
+ "node-fetch": "3.3.2",
72
+ "node-forge": "1.3.1",
73
+ "nodemon": "3.0.1",
74
+ "open": "8.4.2",
75
+ "postcss-loader": "8.1.1",
76
+ "prettier": "3.6.2",
77
+ "react-refresh": "0.17.0",
78
+ "style-loader": "4.0.0",
79
+ "terser-webpack-plugin": "5.3.14",
80
+ "tree-kill": "1.2.2",
81
+ "ts-jest": "29.4.0",
82
+ "ts-loader": "9.5.2",
83
+ "ts-node": "10.9.2",
84
+ "typescript": "5.8.2",
85
+ "url-loader": "4.1.1",
86
+ "webpack": "5.99.9",
87
+ "webpack-cli": "6.0.1",
88
+ "webpack-dev-server": "5.2.2",
89
+ "yargs": "17.7.2"
90
+ }
91
+ }
@@ -0,0 +1,131 @@
1
+ import * as crypto from "crypto";
2
+ import * as fs from "fs/promises";
3
+ import { pki } from "node-forge";
4
+ import * as path from "path";
5
+
6
+ const SSL_CERT_DIR = path.resolve(process.cwd(), "..", "..", ".ssl");
7
+ const CERT_FILE = path.resolve(SSL_CERT_DIR, "certificate.pem");
8
+ const KEY_FILE = path.resolve(SSL_CERT_DIR, "private-key.pem");
9
+
10
+ export interface Certificate {
11
+ keyFile: string;
12
+ certFile: string;
13
+ }
14
+
15
+ const CERT_ATTRS: { name: string; value: string }[] = [
16
+ {
17
+ name: "commonName",
18
+ value: "localhost",
19
+ },
20
+ {
21
+ name: "countryName",
22
+ value: "AU",
23
+ },
24
+ {
25
+ name: "stateOrProvinceName",
26
+ value: "New South Wales",
27
+ },
28
+ {
29
+ name: "localityName",
30
+ value: "Sydney",
31
+ },
32
+ {
33
+ name: "organizationName",
34
+ value: "Test",
35
+ },
36
+ {
37
+ name: "organizationalUnitName",
38
+ value: "Test",
39
+ },
40
+ ];
41
+
42
+ const generateRsaKeys = async (): Promise<{
43
+ publicKey: string;
44
+ privateKey: string;
45
+ }> =>
46
+ new Promise((resolve, reject) => {
47
+ crypto.generateKeyPair(
48
+ "rsa",
49
+ {
50
+ modulusLength: 2096,
51
+ publicKeyEncoding: {
52
+ type: "spki",
53
+ format: "pem",
54
+ },
55
+ privateKeyEncoding: {
56
+ type: "pkcs8",
57
+ format: "pem",
58
+ },
59
+ },
60
+ (err, publicKey, privateKey) => {
61
+ if (err) {
62
+ reject(err);
63
+ } else {
64
+ resolve({ publicKey, privateKey });
65
+ }
66
+ },
67
+ );
68
+ });
69
+
70
+ const generateCertificate = (opts: {
71
+ privateKey: string;
72
+ publicKey: string;
73
+ }): string => {
74
+ const privateKey = pki.privateKeyFromPem(opts.privateKey);
75
+ const publicKey = pki.publicKeyFromPem(opts.publicKey);
76
+
77
+ const cert = pki.createCertificate();
78
+
79
+ cert.publicKey = publicKey;
80
+ cert.serialNumber = "01";
81
+ cert.validity.notBefore = new Date();
82
+ cert.validity.notAfter = new Date();
83
+ cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);
84
+
85
+ cert.setSubject(CERT_ATTRS);
86
+ cert.setIssuer(CERT_ATTRS);
87
+
88
+ // the actual certificate signing
89
+ cert.sign(privateKey);
90
+
91
+ // now convert the Forge certificate to PEM format
92
+ return pki.certificateToPem(cert);
93
+ };
94
+
95
+ const writeCertFiles = async (opts: {
96
+ cert: string;
97
+ privateKey: string;
98
+ }): Promise<void> => {
99
+ const { cert, privateKey } = opts;
100
+
101
+ await fs.mkdir(SSL_CERT_DIR, { recursive: true });
102
+ await Promise.all([
103
+ fs.writeFile(CERT_FILE, cert, { encoding: "utf8" }),
104
+ fs.writeFile(KEY_FILE, privateKey, { encoding: "utf8" }),
105
+ ]);
106
+ };
107
+
108
+ const cerfFilesExist = async (): Promise<boolean> => {
109
+ try {
110
+ await Promise.all([
111
+ fs.access(CERT_FILE, fs.constants.R_OK | fs.constants.W_OK),
112
+ fs.access(KEY_FILE, fs.constants.R_OK | fs.constants.W_OK),
113
+ ]);
114
+ return true;
115
+ } catch {
116
+ return false;
117
+ }
118
+ };
119
+
120
+ export const createOrRetrieveCertificate = async (): Promise<Certificate> => {
121
+ if (!(await cerfFilesExist())) {
122
+ const keys = await generateRsaKeys();
123
+ const cert = generateCertificate(keys);
124
+ await writeCertFiles({ cert, privateKey: keys.privateKey });
125
+ }
126
+
127
+ return {
128
+ certFile: CERT_FILE,
129
+ keyFile: KEY_FILE,
130
+ };
131
+ };
@@ -0,0 +1,201 @@
1
+ /* eslint-disable no-console */
2
+ import { generatePreviewUrl } from "@canva/cli";
3
+ import * as ngrok from "@ngrok/ngrok";
4
+ import * as chalk from "chalk";
5
+ import * as Table from "cli-table3";
6
+ import * as nodemon from "nodemon";
7
+ import * as open from "open";
8
+ import * as webpack from "webpack";
9
+ import * as WebpackDevServer from "webpack-dev-server";
10
+ import { buildConfig } from "../../webpack.config";
11
+ import type { Certificate } from "../ssl/ssl";
12
+ import { createOrRetrieveCertificate } from "../ssl/ssl";
13
+ import type { Context } from "./context";
14
+
15
+ export const infoChalk = chalk.blue.bold;
16
+ export const warnChalk = chalk.bgYellow.bold;
17
+ export const errorChalk = chalk.bgRed.bold;
18
+ export const highlightChalk = chalk.greenBright.bold;
19
+ export const linkChalk = chalk.cyan;
20
+
21
+ export class AppRunner {
22
+ async run(ctx: Context) {
23
+ console.log(
24
+ infoChalk("Info:"),
25
+ `Starting development server for ${highlightChalk(ctx.entryDir)}\n`,
26
+ );
27
+
28
+ if (!ctx.hmrEnabled) {
29
+ console.log(
30
+ `${infoChalk(
31
+ "Note:",
32
+ )} Hot Module Replacement (HMR) not enabled. To enable it, please refer to the instructions in the ${highlightChalk(
33
+ "README.md",
34
+ )}\n`,
35
+ );
36
+ }
37
+
38
+ let cert: Certificate | undefined;
39
+ if (ctx.httpsEnabled) {
40
+ try {
41
+ cert = await createOrRetrieveCertificate();
42
+ } catch (err) {
43
+ console.log(
44
+ errorChalk("Error:"),
45
+ "Unable to generate SSL certificate.",
46
+ );
47
+ throw err;
48
+ }
49
+ }
50
+
51
+ const table = new Table({
52
+ colWidths: [30, 80],
53
+ wordWrap: true,
54
+ wrapOnWordBoundary: true,
55
+ });
56
+
57
+ const server = await this.runWebpackDevServer(ctx, table, cert);
58
+
59
+ await this.maybeRunBackendServer(ctx, table, cert, server);
60
+
61
+ await this.generateAndOpenPreviewUrl(ctx.openPreview, table);
62
+
63
+ console.log(table.toString(), "\n");
64
+
65
+ console.log(
66
+ `${infoChalk(
67
+ "Note:",
68
+ )} For instructions on how to set up the app via the Developer Portal, see the ${highlightChalk(
69
+ "README.md",
70
+ )}.\n`,
71
+ );
72
+ }
73
+
74
+ private readonly maybeRunBackendServer = async (
75
+ ctx: Context,
76
+ table: Table.Table,
77
+ cert: Certificate | undefined,
78
+ webpackDevServer: WebpackDevServer,
79
+ ) => {
80
+ if (!ctx.developerBackendEntryPath) {
81
+ return;
82
+ }
83
+
84
+ // App ID must be set when running a backend example
85
+ if (!ctx.appId) {
86
+ console.log(
87
+ errorChalk("Error:"),
88
+ `'CANVA_APP_ID' environment variable is undefined. Refer to the instructions in the ${highlightChalk(
89
+ "README.md",
90
+ )} on starting a backend example.`,
91
+ );
92
+ throw new Error("'CANVA_APP_ID' env variable not set.");
93
+ }
94
+
95
+ await new Promise((resolve) => {
96
+ const nodemonServer = nodemon({
97
+ script: ctx.developerBackendEntryPath,
98
+ ext: "ts",
99
+ env: {
100
+ SHOULD_ENABLE_HTTPS: ctx.httpsEnabled,
101
+ HTTPS_CERT_FILE: cert?.certFile || "",
102
+ HTTPS_KEY_FILE: cert?.keyFile || "",
103
+ },
104
+ });
105
+
106
+ nodemonServer.on("start", resolve);
107
+
108
+ nodemonServer.on("crash", async () => {
109
+ console.log(errorChalk("Shutting down local server.\n"));
110
+
111
+ await webpackDevServer.stop();
112
+ process.exit(1);
113
+ });
114
+ });
115
+
116
+ if (ctx.ngrokEnabled) {
117
+ console.log(
118
+ warnChalk("Warning:"),
119
+ `ngrok exposes a local port via a public URL. Be mindful of what's exposed and shut down the server when it's not in use.\n`,
120
+ );
121
+ }
122
+
123
+ let url = ctx.backendUrl;
124
+ if (ctx.ngrokEnabled) {
125
+ try {
126
+ const ngrokListener = await ngrok.forward({
127
+ addr: ctx.backendPort,
128
+ // requires an `NGROK_AUTHTOKEN` env var to be set
129
+ authtoken_from_env: true,
130
+ });
131
+ url = ngrokListener.url() ?? url;
132
+ } catch (err) {
133
+ console.log(
134
+ errorChalk("Error:"),
135
+ `Unable to start ngrok server: ${err}`,
136
+ );
137
+ }
138
+ }
139
+
140
+ table.push(["Base URL (Backend)", linkChalk(url)]);
141
+ };
142
+
143
+ private readonly runWebpackDevServer = async (
144
+ ctx: Context,
145
+ table: Table.Table,
146
+ cert: Certificate | undefined,
147
+ ): Promise<WebpackDevServer> => {
148
+ const runtimeWebpackConfig = buildConfig({
149
+ appEntry: ctx.frontendEntryPath,
150
+ backendHost: ctx.backendHost,
151
+ devConfig: {
152
+ port: ctx.frontendPort,
153
+ enableHmr: ctx.hmrEnabled,
154
+ appId: ctx.appId,
155
+ appOrigin: ctx.appOrigin,
156
+ enableHttps: ctx.httpsEnabled,
157
+ ...cert,
158
+ },
159
+ });
160
+
161
+ const compiler = webpack(runtimeWebpackConfig);
162
+ const server = new WebpackDevServer(
163
+ runtimeWebpackConfig.devServer,
164
+ compiler,
165
+ );
166
+ await server.start();
167
+
168
+ table.push(["Development URL (Frontend)", linkChalk(ctx.frontendUrl)]);
169
+
170
+ return server;
171
+ };
172
+
173
+ /**
174
+ * Calls the Canva CLI to generate a preview URL for the app
175
+ */
176
+ private readonly generateAndOpenPreviewUrl = async (
177
+ openPreview: boolean,
178
+ table: Table.Table,
179
+ ) => {
180
+ const previewCellHeader = { content: "Preview your app in Canva" };
181
+
182
+ const generatePreviewResult = await generatePreviewUrl();
183
+
184
+ if (!generatePreviewResult.success) {
185
+ table.push([
186
+ previewCellHeader,
187
+ { content: warnChalk(generatePreviewResult.message) },
188
+ ]);
189
+ return;
190
+ }
191
+
192
+ table.push([
193
+ previewCellHeader,
194
+ { content: "Preview URL", href: generatePreviewResult.data },
195
+ ]);
196
+
197
+ if (openPreview) {
198
+ open(generatePreviewResult.data);
199
+ }
200
+ };
201
+ }