@canva/cli 0.0.1-beta.1

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 (109) hide show
  1. package/LICENSE.md +48 -0
  2. package/README.md +206 -0
  3. package/cli.js +566 -0
  4. package/package.json +30 -0
  5. package/templates/base/backend/database/database.ts +42 -0
  6. package/templates/base/backend/routers/auth.ts +285 -0
  7. package/templates/base/declarations/declarations.d.ts +29 -0
  8. package/templates/base/eslint.config.mjs +309 -0
  9. package/templates/base/package.json +83 -0
  10. package/templates/base/scripts/ssl/ssl.ts +131 -0
  11. package/templates/base/scripts/start/app_runner.ts +164 -0
  12. package/templates/base/scripts/start/context.ts +165 -0
  13. package/templates/base/scripts/start/start.ts +35 -0
  14. package/templates/base/styles/components.css +38 -0
  15. package/templates/base/tsconfig.json +54 -0
  16. package/templates/base/utils/backend/base_backend/create.ts +104 -0
  17. package/templates/base/utils/backend/jwt_middleware/index.ts +1 -0
  18. package/templates/base/utils/backend/jwt_middleware/jwt_middleware.ts +229 -0
  19. package/templates/base/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +630 -0
  20. package/templates/base/webpack.config.cjs +270 -0
  21. package/templates/common/.env.template +6 -0
  22. package/templates/common/.gitignore.template +9 -0
  23. package/templates/common/LICENSE.md +48 -0
  24. package/templates/common/README.md +250 -0
  25. package/templates/common/jest.config.mjs +8 -0
  26. package/templates/dam/backend/database/database.ts +42 -0
  27. package/templates/dam/backend/routers/auth.ts +285 -0
  28. package/templates/dam/backend/routers/dam.ts +86 -0
  29. package/templates/dam/backend/server.ts +65 -0
  30. package/templates/dam/declarations/declarations.d.ts +29 -0
  31. package/templates/dam/eslint.config.mjs +309 -0
  32. package/templates/dam/package.json +90 -0
  33. package/templates/dam/scripts/ssl/ssl.ts +131 -0
  34. package/templates/dam/scripts/start/app_runner.ts +164 -0
  35. package/templates/dam/scripts/start/context.ts +165 -0
  36. package/templates/dam/scripts/start/start.ts +35 -0
  37. package/templates/dam/src/adapter.ts +44 -0
  38. package/templates/dam/src/app.tsx +147 -0
  39. package/templates/dam/src/config.ts +95 -0
  40. package/templates/dam/src/index.css +10 -0
  41. package/templates/dam/src/index.tsx +22 -0
  42. package/templates/dam/tsconfig.json +54 -0
  43. package/templates/dam/utils/backend/base_backend/create.ts +104 -0
  44. package/templates/dam/utils/backend/jwt_middleware/index.ts +1 -0
  45. package/templates/dam/utils/backend/jwt_middleware/jwt_middleware.ts +229 -0
  46. package/templates/dam/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +630 -0
  47. package/templates/dam/webpack.config.cjs +270 -0
  48. package/templates/gen_ai/README.md +27 -0
  49. package/templates/gen_ai/backend/database/database.ts +42 -0
  50. package/templates/gen_ai/backend/routers/auth.ts +285 -0
  51. package/templates/gen_ai/backend/routers/image.ts +234 -0
  52. package/templates/gen_ai/backend/server.ts +56 -0
  53. package/templates/gen_ai/declarations/declarations.d.ts +29 -0
  54. package/templates/gen_ai/eslint.config.mjs +309 -0
  55. package/templates/gen_ai/package.json +92 -0
  56. package/templates/gen_ai/scripts/ssl/ssl.ts +131 -0
  57. package/templates/gen_ai/scripts/start/app_runner.ts +164 -0
  58. package/templates/gen_ai/scripts/start/context.ts +165 -0
  59. package/templates/gen_ai/scripts/start/start.ts +35 -0
  60. package/templates/gen_ai/src/api/api.ts +228 -0
  61. package/templates/gen_ai/src/api/index.ts +1 -0
  62. package/templates/gen_ai/src/app.tsx +13 -0
  63. package/templates/gen_ai/src/components/app_error.tsx +18 -0
  64. package/templates/gen_ai/src/components/footer.messages.ts +53 -0
  65. package/templates/gen_ai/src/components/footer.tsx +157 -0
  66. package/templates/gen_ai/src/components/image_grid.tsx +96 -0
  67. package/templates/gen_ai/src/components/index.ts +8 -0
  68. package/templates/gen_ai/src/components/loading_results.tsx +169 -0
  69. package/templates/gen_ai/src/components/logged_in_status.tsx +44 -0
  70. package/templates/gen_ai/src/components/prompt_input.messages.ts +14 -0
  71. package/templates/gen_ai/src/components/prompt_input.tsx +149 -0
  72. package/templates/gen_ai/src/components/remaining_credits.tsx +75 -0
  73. package/templates/gen_ai/src/components/report_box.tsx +53 -0
  74. package/templates/gen_ai/src/config.ts +21 -0
  75. package/templates/gen_ai/src/context/app_context.tsx +174 -0
  76. package/templates/gen_ai/src/context/context.messages.ts +41 -0
  77. package/templates/gen_ai/src/context/index.ts +2 -0
  78. package/templates/gen_ai/src/context/use_app_context.ts +17 -0
  79. package/templates/gen_ai/src/index.tsx +31 -0
  80. package/templates/gen_ai/src/pages/error.tsx +41 -0
  81. package/templates/gen_ai/src/pages/generate.tsx +9 -0
  82. package/templates/gen_ai/src/pages/index.ts +3 -0
  83. package/templates/gen_ai/src/pages/results.tsx +31 -0
  84. package/templates/gen_ai/src/routes/index.ts +1 -0
  85. package/templates/gen_ai/src/routes/routes.tsx +26 -0
  86. package/templates/gen_ai/src/services/auth.tsx +31 -0
  87. package/templates/gen_ai/src/services/index.ts +1 -0
  88. package/templates/gen_ai/src/utils/index.ts +1 -0
  89. package/templates/gen_ai/src/utils/obscenity_filter.ts +33 -0
  90. package/templates/gen_ai/styles/components.css +38 -0
  91. package/templates/gen_ai/styles/utils.css +3 -0
  92. package/templates/gen_ai/tsconfig.json +54 -0
  93. package/templates/gen_ai/utils/backend/base_backend/create.ts +104 -0
  94. package/templates/gen_ai/utils/backend/jwt_middleware/index.ts +1 -0
  95. package/templates/gen_ai/utils/backend/jwt_middleware/jwt_middleware.ts +229 -0
  96. package/templates/gen_ai/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +630 -0
  97. package/templates/gen_ai/webpack.config.cjs +270 -0
  98. package/templates/hello_world/declarations/declarations.d.ts +29 -0
  99. package/templates/hello_world/eslint.config.mjs +309 -0
  100. package/templates/hello_world/package.json +73 -0
  101. package/templates/hello_world/scripts/ssl/ssl.ts +131 -0
  102. package/templates/hello_world/scripts/start/app_runner.ts +164 -0
  103. package/templates/hello_world/scripts/start/context.ts +165 -0
  104. package/templates/hello_world/scripts/start/start.ts +35 -0
  105. package/templates/hello_world/src/app.tsx +41 -0
  106. package/templates/hello_world/src/index.tsx +22 -0
  107. package/templates/hello_world/styles/components.css +38 -0
  108. package/templates/hello_world/tsconfig.json +54 -0
  109. package/templates/hello_world/webpack.config.cjs +270 -0
@@ -0,0 +1,309 @@
1
+ import typescriptEslint from "@typescript-eslint/eslint-plugin";
2
+ import jest from "eslint-plugin-jest";
3
+ import react from "eslint-plugin-react";
4
+ import globals from "globals";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import js from "@eslint/js";
8
+ import { FlatCompat } from "@eslint/eslintrc";
9
+
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = path.dirname(__filename);
12
+ const compat = new FlatCompat({
13
+ baseDirectory: __dirname,
14
+ recommendedConfig: js.configs.recommended,
15
+ allConfig: js.configs.all,
16
+ });
17
+
18
+ export default [
19
+ {
20
+ ignores: [
21
+ "**/node_modules/",
22
+ "**/dist",
23
+ "**/*.d.ts",
24
+ "**/*.d.tsx",
25
+ "**/sdk",
26
+ "**/internal",
27
+ "**/*.config.*",
28
+ ],
29
+ },
30
+ ...compat.extends(
31
+ "eslint:recommended",
32
+ "plugin:@typescript-eslint/recommended",
33
+ "plugin:@typescript-eslint/eslint-recommended",
34
+ "plugin:@typescript-eslint/strict",
35
+ "plugin:@typescript-eslint/stylistic",
36
+ "plugin:react/recommended",
37
+ "plugin:jest/recommended"
38
+ ),
39
+ {
40
+ plugins: {
41
+ "@typescript-eslint": typescriptEslint,
42
+ jest,
43
+ react,
44
+ },
45
+ languageOptions: {
46
+ globals: {
47
+ ...globals.serviceworker,
48
+ ...globals.browser,
49
+ },
50
+ },
51
+ settings: {
52
+ react: {
53
+ version: "detect",
54
+ },
55
+ },
56
+ rules: {
57
+ "@typescript-eslint/no-non-null-assertion": "warn",
58
+ "@typescript-eslint/no-empty-function": "off",
59
+ "@typescript-eslint/consistent-type-imports": "error",
60
+ "@typescript-eslint/no-explicit-any": "warn",
61
+ "@typescript-eslint/no-empty-interface": "warn",
62
+ "@typescript-eslint/consistent-type-definitions": "off",
63
+ "@typescript-eslint/explicit-member-accessibility": [
64
+ "error",
65
+ {
66
+ accessibility: "no-public",
67
+ overrides: {
68
+ parameterProperties: "off",
69
+ },
70
+ },
71
+ ],
72
+ "@typescript-eslint/naming-convention": [
73
+ "error",
74
+ {
75
+ selector: "typeLike",
76
+ format: ["PascalCase"],
77
+ leadingUnderscore: "allow",
78
+ },
79
+ ],
80
+ "no-invalid-this": "off",
81
+ "@typescript-eslint/no-invalid-this": "error",
82
+ "@typescript-eslint/no-unused-expressions": [
83
+ "error",
84
+ {
85
+ allowShortCircuit: true,
86
+ allowTernary: true,
87
+ },
88
+ ],
89
+ "no-unused-vars": "off",
90
+ "@typescript-eslint/no-unused-vars": [
91
+ "error",
92
+ {
93
+ vars: "all",
94
+ varsIgnorePattern: "^_",
95
+ args: "none",
96
+ ignoreRestSiblings: true,
97
+ },
98
+ ],
99
+ "@typescript-eslint/no-require-imports": "error",
100
+ "jest/no-restricted-matchers": [
101
+ "error",
102
+ {
103
+ toContainElement:
104
+ "toContainElement is not recommended as it encourages testing the internals of the components",
105
+ toContainHTML:
106
+ "toContainHTML is not recommended as it encourages testing the internals of the components",
107
+ toHaveAttribute:
108
+ "toHaveAttribute is not recommended as it encourages testing the internals of the components",
109
+ toHaveClass:
110
+ "toHaveClass is not recommended as it encourages testing the internals of the components",
111
+ toHaveStyle:
112
+ "toHaveStyle is not recommended as it encourages testing the internals of the components",
113
+ },
114
+ ],
115
+ "react/jsx-curly-brace-presence": [
116
+ "error",
117
+ {
118
+ props: "never",
119
+ children: "never",
120
+ },
121
+ ],
122
+ "react/jsx-tag-spacing": [
123
+ "error",
124
+ {
125
+ closingSlash: "never",
126
+ beforeSelfClosing: "allow",
127
+ afterOpening: "never",
128
+ beforeClosing: "allow",
129
+ },
130
+ ],
131
+ "react/self-closing-comp": "error",
132
+ "react/no-unescaped-entities": "off",
133
+ "react/jsx-uses-react": "off",
134
+ "react/react-in-jsx-scope": "off",
135
+ "default-case": "error",
136
+ eqeqeq: [
137
+ "error",
138
+ "always",
139
+ {
140
+ null: "never",
141
+ },
142
+ ],
143
+ "no-caller": "error",
144
+ "no-console": "error",
145
+ "no-eval": "error",
146
+ "no-inner-declarations": "error",
147
+ "no-new-wrappers": "error",
148
+ "no-restricted-globals": [
149
+ "error",
150
+ {
151
+ name: "fit",
152
+ message: "Don't focus tests",
153
+ },
154
+ {
155
+ name: "fdescribe",
156
+ message: "Don't focus tests",
157
+ },
158
+ {
159
+ name: "length",
160
+ message:
161
+ "Undefined length - Did you mean to use window.length instead?",
162
+ },
163
+ {
164
+ name: "name",
165
+ message: "Undefined name - Did you mean to use window.name instead?",
166
+ },
167
+ {
168
+ name: "status",
169
+ message:
170
+ "Undefined status - Did you mean to use window.status instead?",
171
+ },
172
+ {
173
+ name: "spyOn",
174
+ message: "Don't use spyOn directly, use jest.spyOn",
175
+ },
176
+ ],
177
+ "no-restricted-properties": [
178
+ "error",
179
+ {
180
+ property: "bind",
181
+ message: "Don't o.f.bind(o, ...), use () => o.f(...)",
182
+ },
183
+ {
184
+ object: "ReactDOM",
185
+ property: "findDOMNode",
186
+ message: "Don't use ReactDOM.findDOMNode() as it is deprecated",
187
+ },
188
+ ],
189
+ "no-restricted-syntax": [
190
+ "error",
191
+ {
192
+ selector: "AccessorProperty, TSAbstractAccessorProperty",
193
+ message:
194
+ "Accessor property syntax is not allowed, use getter and setters.",
195
+ },
196
+ {
197
+ selector: "PrivateIdentifier",
198
+ message:
199
+ "Private identifiers are not allowed, use TypeScript private fields.",
200
+ },
201
+ {
202
+ selector:
203
+ "JSXOpeningElement[name.name = /^[A-Z]/] > JSXAttribute[name.name = /-/]",
204
+ message:
205
+ "Passing hyphenated props to custom components is not type-safe. Prefer a camelCased equivalent if available. (See https://github.com/microsoft/TypeScript/issues/55182)",
206
+ },
207
+ {
208
+ selector:
209
+ "CallExpression[callee.object.name='window'][callee.property.name='open']",
210
+ message:
211
+ "Apps are currently not allowed to open popups, or new tabs via browser APIs. Please use `requestOpenExternalUrl` from `@canva/platform` to link to external URLs. To learn more, see https://www.canva.dev/docs/apps/api/platform-request-open-external-url/",
212
+ },
213
+ ],
214
+ "no-return-await": "error",
215
+ "no-throw-literal": "error",
216
+ "no-undef-init": "error",
217
+ "no-var": "error",
218
+ "object-shorthand": "error",
219
+ "prefer-const": [
220
+ "error",
221
+ {
222
+ destructuring: "all",
223
+ },
224
+ ],
225
+ "prefer-object-spread": "error",
226
+ "prefer-rest-params": "error",
227
+ "prefer-spread": "error",
228
+ radix: "error",
229
+ },
230
+ },
231
+ {
232
+ files: ["**/*.tsx"],
233
+ rules: {
234
+ "react/no-deprecated": "error",
235
+ "react/forbid-elements": [
236
+ "error",
237
+ {
238
+ forbid: [
239
+ {
240
+ element: "video",
241
+ message:
242
+ "Don't use HTML video directly. Instead, use the App UI Kit <VideoCard /> as this respects users' auto-playing preferences",
243
+ },
244
+ {
245
+ element: "em",
246
+ message:
247
+ "Don't use <em> to italicize text. Canva's UI fonts don't support italic font style.",
248
+ },
249
+ {
250
+ element: "i",
251
+ message:
252
+ "Don't use <i> to italicize text. Canva's UI fonts don't support italic font style.",
253
+ },
254
+ {
255
+ element: "iframe",
256
+ message:
257
+ "Canva Apps aren't allowed to contain iframes. You should either recreate the UI you want to show in the iframe in the app directly, or link to your page via a `<Link>` tag. For more info see https://www.canva.dev/docs/apps/content-security-policy/#what-is-and-isnt-allowed",
258
+ },
259
+ {
260
+ element: "script",
261
+ message:
262
+ "Script tags are not allowed in Canva SDK Apps. You should import JavaScript modules instead. For more info see https://www.canva.dev/docs/apps/content-security-policy/#what-is-and-isnt-allowed",
263
+ },
264
+ {
265
+ element: "a",
266
+ message:
267
+ "Don't use <a> tags. Instead, use the <Link> component from the App UI Kit, and remember to open the url via the requestOpenExternalUrl method from @canva/platform.",
268
+ },
269
+ {
270
+ element: "img",
271
+ message:
272
+ "Have you considered using <ImageCard /> from the App UI Kit instead?",
273
+ },
274
+ {
275
+ element: "embed",
276
+ message:
277
+ "Have you considered using <EmbedCard /> from the App UI Kit instead?",
278
+ },
279
+ {
280
+ element: "audio",
281
+ message:
282
+ "Have you considered using <AudioCard /> from the App UI Kit instead?",
283
+ },
284
+ {
285
+ element: "button",
286
+ message:
287
+ "Rather than using the native HTML <button> element, use the <Button> component from the App UI Kit for consistency and accessibility.",
288
+ },
289
+ {
290
+ element: "input",
291
+ message:
292
+ "Wherever possible, prefer using the form inputs from the App UI Kit for consistency and accessibility (TextInput, Checkbox, FileInput, etc).",
293
+ },
294
+ {
295
+ element: "base",
296
+ message:
297
+ "The <base> tag is not supported in Canva Apps. We recommend using hash-based routing. For more on what is and isn't allowed in Canva Apps see https://www.canva.dev/docs/apps/content-security-policy/#what-is-and-isnt-allowed",
298
+ },
299
+ {
300
+ element: "link",
301
+ message:
302
+ "If you're trying to include a css stylesheet, we recommend importing css using React, or using embedded stylesheets. For more on what is and isn't allowed in Canva Apps see https://www.canva.dev/docs/apps/content-security-policy/#what-is-and-isnt-allowed",
303
+ },
304
+ ],
305
+ },
306
+ ],
307
+ },
308
+ },
309
+ ];
@@ -0,0 +1,90 @@
1
+ {
2
+ "private": true,
3
+ "name": "digital_asset_management",
4
+ "description": "An example app leveraging @canva/app-components to develop a digital asset management (DAM) app.",
5
+ "scripts": {
6
+ "extract": "formatjs extract 'src/**/*.{ts,tsx}' --out-file dist/messages_en.json",
7
+ "build": "webpack --config webpack.config.cjs --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
+ "test": "jest --no-cache",
16
+ "test:watch": "jest --watchAll"
17
+ },
18
+ "dependencies": {
19
+ "@canva/app-i18n-kit": "^0.0.1-beta.5",
20
+ "@canva/app-components": "^1.0.0-beta.22",
21
+ "@canva/app-ui-kit": "^3.8.0",
22
+ "@canva/asset": "^1.7.1",
23
+ "@canva/design": "^1.10.0",
24
+ "@canva/platform": "^1.1.0",
25
+ "@canva/user": "^1.0.0",
26
+ "cookie-parser": "1.4.6",
27
+ "cors": "2.8.5",
28
+ "react": "18.3.1",
29
+ "react-dom": "18.3.1",
30
+ "react-intl": "6.6.8"
31
+ },
32
+ "devDependencies": {
33
+ "@eslint/eslintrc": "3.1.0",
34
+ "@eslint/js": "9.9.0",
35
+ "@formatjs/cli": "6.2.12",
36
+ "@formatjs/ts-transformer": "3.13.14",
37
+ "@ngrok/ngrok": "1.4.1",
38
+ "@svgr/webpack": "8.1.0",
39
+ "@types/cors": "2.8.17",
40
+ "@types/debug": "4.1.12",
41
+ "@types/express": "4.17.21",
42
+ "@types/express-serve-static-core": "4.19.5",
43
+ "@types/jest": "29.5.12",
44
+ "@types/jsonwebtoken": "9.0.6",
45
+ "@types/node": "20.10.0",
46
+ "@types/node-fetch": "2.6.11",
47
+ "@types/node-forge": "1.3.11",
48
+ "@types/nodemon": "1.19.6",
49
+ "@types/prompts": "2.4.9",
50
+ "@types/react": "18.3.4",
51
+ "@types/react-dom": "18.3.0",
52
+ "@types/webpack-env": "1.18.5",
53
+ "@typescript-eslint/eslint-plugin": "8.2.0",
54
+ "@typescript-eslint/parser": "8.2.0",
55
+ "chalk": "4.1.2",
56
+ "cli-table3": "0.6.5",
57
+ "css-loader": "7.1.2",
58
+ "css-modules-typescript-loader": "4.0.1",
59
+ "cssnano": "7.0.5",
60
+ "debug": "4.3.6",
61
+ "dotenv": "16.4.5",
62
+ "eslint": "9.9.0",
63
+ "eslint-plugin-jest": "28.8.0",
64
+ "eslint-plugin-react": "7.35.0",
65
+ "exponential-backoff": "3.1.1",
66
+ "express": "4.19.2",
67
+ "express-basic-auth": "1.2.1",
68
+ "jest": "29.7.0",
69
+ "jsonwebtoken": "9.0.2",
70
+ "jwks-rsa": "3.1.0",
71
+ "mini-css-extract-plugin": "2.9.1",
72
+ "node-fetch": "3.3.2",
73
+ "node-forge": "1.3.1",
74
+ "nodemon": "3.0.1",
75
+ "postcss-loader": "8.1.1",
76
+ "prettier": "3.3.3",
77
+ "prompts": "2.4.2",
78
+ "style-loader": "4.0.0",
79
+ "terser-webpack-plugin": "5.3.10",
80
+ "ts-jest": "29.2.4",
81
+ "ts-loader": "9.5.1",
82
+ "ts-node": "10.9.2",
83
+ "typescript": "5.5.4",
84
+ "url-loader": "4.1.1",
85
+ "webpack": "5.94.0",
86
+ "webpack-cli": "5.1.4",
87
+ "webpack-dev-server": "5.0.4",
88
+ "yargs": "17.7.2"
89
+ }
90
+ }
@@ -0,0 +1,131 @@
1
+ import * as crypto from "crypto";
2
+ import { pki } from "node-forge";
3
+ import * as path from "path";
4
+ import * as fs from "fs/promises";
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,164 @@
1
+ /* eslint-disable no-console */
2
+ import type { Context } from "./context";
3
+ import * as chalk from "chalk";
4
+ import { buildConfig } from "../../webpack.config.cjs";
5
+ import * as ngrok from "@ngrok/ngrok";
6
+ import * as nodemon from "nodemon";
7
+ import * as Table from "cli-table3";
8
+ import * as webpack from "webpack";
9
+ import * as WebpackDevServer from "webpack-dev-server";
10
+ import type { Certificate } from "../ssl/ssl";
11
+ import { createOrRetrieveCertificate } from "../ssl/ssl";
12
+
13
+ export const infoChalk = chalk.blue.bold;
14
+ export const warnChalk = chalk.bgYellow.bold;
15
+ export const errorChalk = chalk.bgRed.bold;
16
+ export const highlightChalk = chalk.greenBright.bold;
17
+ export const linkChalk = chalk.cyan;
18
+
19
+ export class AppRunner {
20
+ async run(ctx: Context) {
21
+ console.log(
22
+ infoChalk("Info:"),
23
+ `Starting development server for ${highlightChalk(ctx.entryDir)}\n`,
24
+ );
25
+
26
+ if (!ctx.hmrEnabled) {
27
+ console.log(
28
+ `${infoChalk(
29
+ "Note:",
30
+ )} Hot Module Replacement (HMR) not enabled. To enable it, please refer to the instructions in the ${highlightChalk(
31
+ "README.md",
32
+ )}\n`,
33
+ );
34
+ }
35
+
36
+ let cert: Certificate | undefined;
37
+ if (ctx.httpsEnabled) {
38
+ try {
39
+ cert = await createOrRetrieveCertificate();
40
+ } catch (err) {
41
+ console.log(
42
+ errorChalk("Error:"),
43
+ "Unable to generate SSL certificate.",
44
+ );
45
+ throw err;
46
+ }
47
+ }
48
+
49
+ const table = new Table();
50
+
51
+ const server = await this.runWebpackDevServer(ctx, table, cert);
52
+
53
+ await this.maybeRunBackendServer(ctx, table, cert, server);
54
+
55
+ console.log(table.toString(), "\n");
56
+
57
+ console.log(
58
+ `${infoChalk(
59
+ "Note:",
60
+ )} For instructions on how to set up the app via the Developer Portal, see the ${highlightChalk(
61
+ "README.md",
62
+ )}.\n`,
63
+ );
64
+ }
65
+
66
+ private readonly maybeRunBackendServer = async (
67
+ ctx: Context,
68
+ table: Table.Table,
69
+ cert: Certificate | undefined,
70
+ webpackDevServer: WebpackDevServer,
71
+ ) => {
72
+ if (!ctx.developerBackendEntryPath) {
73
+ return;
74
+ }
75
+
76
+ // App ID must be set when running a backend example
77
+ if (!ctx.appId) {
78
+ console.log(
79
+ errorChalk("Error:"),
80
+ `'CANVA_APP_ID' environment variable is undefined. Refer to the instructions in the ${highlightChalk(
81
+ "README.md",
82
+ )} on starting a backend example.`,
83
+ );
84
+ throw new Error("'CANVA_APP_ID' env variable not set.");
85
+ }
86
+
87
+ await new Promise((resolve) => {
88
+ const nodemonServer = nodemon({
89
+ script: ctx.developerBackendEntryPath,
90
+ ext: "ts",
91
+ env: {
92
+ SHOULD_ENABLE_HTTPS: ctx.httpsEnabled,
93
+ HTTPS_CERT_FILE: cert?.certFile || "",
94
+ HTTPS_KEY_FILE: cert?.keyFile || "",
95
+ },
96
+ });
97
+
98
+ nodemonServer.on("start", resolve);
99
+
100
+ nodemonServer.on("crash", async () => {
101
+ console.log(errorChalk("Shutting down local server.\n"));
102
+
103
+ await webpackDevServer.stop();
104
+ process.exit(1);
105
+ });
106
+ });
107
+
108
+ if (ctx.ngrokEnabled) {
109
+ console.log(
110
+ warnChalk("Warning:"),
111
+ `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`,
112
+ );
113
+ }
114
+
115
+ let url = ctx.backendUrl;
116
+ if (ctx.ngrokEnabled) {
117
+ try {
118
+ const ngrokListener = await ngrok.forward({
119
+ addr: ctx.backendPort,
120
+ // requires an `NGROK_AUTHTOKEN` env var to be set
121
+ authtoken_from_env: true,
122
+ });
123
+ url = ngrokListener.url() ?? url;
124
+ } catch (err) {
125
+ console.log(
126
+ errorChalk("Error:"),
127
+ `Unable to start ngrok server: ${err}`,
128
+ );
129
+ }
130
+ }
131
+
132
+ table.push(["Base URL (Backend)", linkChalk(url)]);
133
+ };
134
+
135
+ private readonly runWebpackDevServer = async (
136
+ ctx: Context,
137
+ table: Table.Table,
138
+ cert: Certificate | undefined,
139
+ ): Promise<WebpackDevServer> => {
140
+ const runtimeWebpackConfig = buildConfig({
141
+ appEntry: ctx.frontendEntryPath,
142
+ backendHost: ctx.backendHost,
143
+ devConfig: {
144
+ port: ctx.frontendPort,
145
+ enableHmr: ctx.hmrEnabled,
146
+ appId: ctx.appId,
147
+ appOrigin: ctx.appOrigin,
148
+ enableHttps: ctx.httpsEnabled,
149
+ ...cert,
150
+ },
151
+ });
152
+
153
+ const compiler = webpack(runtimeWebpackConfig);
154
+ const server = new WebpackDevServer(
155
+ runtimeWebpackConfig.devServer,
156
+ compiler,
157
+ );
158
+ await server.start();
159
+
160
+ table.push(["Development URL (Frontend)", linkChalk(ctx.frontendUrl)]);
161
+
162
+ return server;
163
+ };
164
+ }