├── .nvmrc ├── packages ├── core │ ├── src │ │ ├── generators │ │ │ ├── wasm.ts │ │ │ ├── __snapshots__ │ │ │ │ └── swift.test.ts.snap │ │ │ ├── swift.test.ts │ │ │ ├── kotlin.ts │ │ │ ├── go.ts │ │ │ └── swift.ts │ │ ├── internal-types.d.ts │ │ ├── helpers │ │ │ ├── is-upper-case.ts │ │ │ ├── fast-clone.ts │ │ │ ├── dash-case.ts │ │ │ ├── format.ts │ │ │ └── babel-transform.ts │ │ ├── types │ │ │ ├── string-map.ts │ │ │ └── json.ts │ │ ├── constants │ │ │ ├── method-literal-prefix.ts │ │ │ ├── function-literal-prefix.ts │ │ │ └── media-sizes.ts │ │ ├── index.ts │ │ ├── parsers │ │ │ └── ts.ts │ │ └── modules │ │ │ └── plugins.ts │ ├── CHANGELOG.md │ ├── tsconfig.json │ ├── jest.config.js │ ├── README.md │ └── package.json ├── fiddle │ ├── .firebaserc │ ├── .env │ ├── public │ │ ├── robots.txt │ │ ├── favicon.ico │ │ ├── logo192.png │ │ ├── logo512.png │ │ ├── manifest.json │ │ ├── index.html │ │ └── preview.html │ ├── src │ │ ├── internal-types.d.ts │ │ ├── assets │ │ │ ├── ts-lite-logo-white.png │ │ │ └── GitHub-Mark-Light-64px.png │ │ ├── functions │ │ │ ├── get-query-param.ts │ │ │ ├── delete-query-param.ts │ │ │ ├── set-query-param.ts │ │ │ ├── local-storage-set.ts │ │ │ ├── local-storage-get.ts │ │ │ └── prompt-upload-figma-file.ts │ │ ├── setupTests.ts │ │ ├── constants │ │ │ ├── breakpoints.ts │ │ │ ├── templates.ts │ │ │ ├── theme.ts │ │ │ ├── colors.ts │ │ │ └── device.ts │ │ ├── hooks │ │ │ ├── use-reaction.ts │ │ │ └── use-event-listener.ts │ │ ├── components │ │ │ ├── Show.tsx │ │ │ ├── TextLink.tsx │ │ │ ├── App.tsx │ │ │ └── Fiddle.tsx │ │ ├── reportWebVitals.ts │ │ ├── index.css │ │ ├── index.tsx │ │ └── react-app-env.d.ts │ ├── firebase.json │ ├── config │ │ ├── jest │ │ │ ├── cssTransform.js │ │ │ └── fileTransform.js │ │ ├── pnpTs.js │ │ ├── getHttpsConfig.js │ │ ├── paths.js │ │ ├── modules.js │ │ ├── env.js │ │ ├── webpackDevServer.config.js │ │ └── webpack.config.js │ ├── .gitignore │ ├── tsconfig.json │ ├── scripts │ │ ├── test.js │ │ ├── start.js │ │ └── build.js │ └── package.json └── eslint-plugin │ ├── CHANGELOG.md │ ├── tsconfig.json │ ├── package.json │ ├── jest.config.js │ └── src │ ├── __test__ │ └── no-conditional-render.test.ts │ └── index.ts ├── .eslintignore ├── .stylelintrc ├── .gitignore ├── .prettierignore ├── .prettierrc ├── lerna.json ├── tsconfig.build.json ├── .eslintrc.js ├── tsconfig.json ├── jest.config.js ├── .github └── workflows │ └── pr-runner.yml ├── babel.config.js ├── LICENSE ├── package.json └── README.MD /.nvmrc: -------------------------------------------------------------------------------- 1 | v10.23.0 -------------------------------------------------------------------------------- /packages/core/src/generators/wasm.ts: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | *.d.ts 3 | node_modules -------------------------------------------------------------------------------- /packages/core/src/internal-types.d.ts: -------------------------------------------------------------------------------- 1 | declare module '@fake*'; 2 | -------------------------------------------------------------------------------- /.stylelintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "stylelint-config-standard" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | *.log 4 | .vscode 5 | .idea 6 | coverage 7 | .DS_Store -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | coverage 2 | node_modules 3 | dist 4 | .next 5 | .cache-loader 6 | .cache 7 | docs 8 | -------------------------------------------------------------------------------- /packages/fiddle/.firebaserc: -------------------------------------------------------------------------------- 1 | { 2 | "projects": { 3 | "default": "ts-lite-fiddle" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /packages/fiddle/.env: -------------------------------------------------------------------------------- 1 | # Ignore a CRA warning that is not an actual issue for us 2 | SKIP_PREFLIGHT_CHECK=true -------------------------------------------------------------------------------- /packages/fiddle/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /packages/core/src/helpers/is-upper-case.ts: -------------------------------------------------------------------------------- 1 | export const isUpperCase = (str: string) => str.toUpperCase() === str; 2 | -------------------------------------------------------------------------------- /packages/core/src/types/string-map.ts: -------------------------------------------------------------------------------- 1 | export interface StringMap { 2 | [key: string]: string | undefined; 3 | } 4 | -------------------------------------------------------------------------------- /packages/core/src/constants/method-literal-prefix.ts: -------------------------------------------------------------------------------- 1 | export const methodLiteralPrefix = `@builder.io/ts-lite/method:`; 2 | -------------------------------------------------------------------------------- /packages/fiddle/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BuilderIO/ts-lite/main/packages/fiddle/public/favicon.ico -------------------------------------------------------------------------------- /packages/fiddle/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BuilderIO/ts-lite/main/packages/fiddle/public/logo192.png -------------------------------------------------------------------------------- /packages/fiddle/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BuilderIO/ts-lite/main/packages/fiddle/public/logo512.png -------------------------------------------------------------------------------- /packages/core/src/constants/function-literal-prefix.ts: -------------------------------------------------------------------------------- 1 | export const functionLiteralPrefix = `@builder.io/ts-lite/function:`; 2 | -------------------------------------------------------------------------------- /packages/fiddle/src/internal-types.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'raw-loader!*' { 2 | const value: string; 3 | export default value; 4 | } 5 | -------------------------------------------------------------------------------- /packages/core/src/helpers/fast-clone.ts: -------------------------------------------------------------------------------- 1 | export const fastClone = (obj: T): T => 2 | JSON.parse(JSON.stringify(obj)); 3 | -------------------------------------------------------------------------------- /packages/core/src/helpers/dash-case.ts: -------------------------------------------------------------------------------- 1 | import { kebabCase } from 'lodash'; 2 | 3 | export const dashCase = (string: string) => kebabCase(string); 4 | -------------------------------------------------------------------------------- /packages/fiddle/src/assets/ts-lite-logo-white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BuilderIO/ts-lite/main/packages/fiddle/src/assets/ts-lite-logo-white.png -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "tabWidth": 2, 4 | "singleQuote": true, 5 | "trailingComma": "all", 6 | "arrowParens": "always" 7 | } 8 | -------------------------------------------------------------------------------- /packages/fiddle/src/assets/GitHub-Mark-Light-64px.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BuilderIO/ts-lite/main/packages/fiddle/src/assets/GitHub-Mark-Light-64px.png -------------------------------------------------------------------------------- /packages/core/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. 5 | -------------------------------------------------------------------------------- /packages/core/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './parsers/ts'; 2 | export * from './generators/swift'; 3 | export * from './generators/go'; 4 | export * from './generators/kotlin'; 5 | export * from './helpers/format'; 6 | -------------------------------------------------------------------------------- /packages/eslint-plugin/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. 5 | -------------------------------------------------------------------------------- /packages/fiddle/src/functions/get-query-param.ts: -------------------------------------------------------------------------------- 1 | export const getQueryParam = (name: string): string | null => { 2 | const urlParams = new URLSearchParams(window.location.search); 3 | return urlParams.get(name); 4 | }; 5 | -------------------------------------------------------------------------------- /packages/eslint-plugin/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "outDir": "./dist", 5 | "rootDir": "./src", 6 | "baseUrl": "./", 7 | "skipLibCheck": true 8 | }, 9 | "include": ["./src"] 10 | } 11 | -------------------------------------------------------------------------------- /packages/fiddle/src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /lerna.json: -------------------------------------------------------------------------------- 1 | { 2 | "packages": ["packages/*"], 3 | "version": "independent", 4 | "useWorkspaces": true, 5 | "command": { 6 | "publish": { 7 | "conventionalCommits": true, 8 | "access": "public", 9 | "allowBranch": ["master", "feature/*"] 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "noEmit": false, 5 | "emitDeclarationOnly": true, 6 | "declaration": true, 7 | "skipLibCheck": true 8 | }, 9 | "exclude": ["**/*.story.*", "**/*.test.*", "dist"], 10 | "include": [] 11 | } 12 | -------------------------------------------------------------------------------- /packages/core/src/parsers/ts.ts: -------------------------------------------------------------------------------- 1 | import * as ts from 'typescript'; 2 | 3 | export const FILE_NAME = 'code.tsx'; 4 | 5 | export function parse(code: string, options = {}) { 6 | return ts.createSourceFile( 7 | FILE_NAME, 8 | code, 9 | ts.ScriptTarget.Latest, 10 | true, 11 | ts.ScriptKind.TSX, 12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /packages/fiddle/firebase.json: -------------------------------------------------------------------------------- 1 | { 2 | "hosting": { 3 | "public": "build", 4 | "ignore": [ 5 | "firebase.json", 6 | "**/.*", 7 | "**/node_modules/**" 8 | ], 9 | "rewrites": [ 10 | { 11 | "source": "**", 12 | "destination": "/index.html" 13 | } 14 | ] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /packages/core/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "dist", 4 | "strict": true, 5 | "declaration": true, 6 | "jsx": "preserve", 7 | "skipLibCheck": true, 8 | "skipDefaultLibCheck": true, 9 | "esModuleInterop": true, 10 | "target": "ES5", 11 | "baseUrl": "." 12 | }, 13 | "include": ["./src"] 14 | } 15 | -------------------------------------------------------------------------------- /packages/fiddle/src/constants/breakpoints.ts: -------------------------------------------------------------------------------- 1 | const getBreakpointMediaQuery = (maxWidth: number) => 2 | `@media (max-width: ${maxWidth}px)`; 3 | 4 | export const breakpoints = { 5 | sizes: { 6 | small: 700, 7 | }, 8 | mediaQueries: { 9 | get small() { 10 | return getBreakpointMediaQuery(breakpoints.sizes.small); 11 | }, 12 | }, 13 | }; 14 | -------------------------------------------------------------------------------- /packages/fiddle/src/hooks/use-reaction.ts: -------------------------------------------------------------------------------- 1 | import { IReactionOptions, reaction } from 'mobx'; 2 | import { useEffect } from 'react'; 3 | 4 | export function useReaction( 5 | expression: () => T, 6 | effect: (value: T) => void, 7 | options: IReactionOptions = { fireImmediately: true }, 8 | ): void { 9 | useEffect(() => reaction(expression, effect, options), []); 10 | } 11 | -------------------------------------------------------------------------------- /packages/core/src/generators/__snapshots__/swift.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Can generate some swift 1`] = ` 4 | "func fib(index: Int) -> Int { 5 | var n = index 6 | var a = 0 7 | var b = 1 8 | if n > 0 { 9 | while --n { 10 | var t = a + b 11 | a = b 12 | b = t 13 | } 14 | return b 15 | } 16 | return a 17 | }" 18 | `; 19 | -------------------------------------------------------------------------------- /packages/fiddle/src/functions/delete-query-param.ts: -------------------------------------------------------------------------------- 1 | export const deleteQueryParam = (name: string): void => { 2 | var searchParams = new URLSearchParams(window.location.search); 3 | searchParams.delete(name); 4 | const search = searchParams.toString(); 5 | window.history.replaceState( 6 | null, 7 | '', 8 | window.location.pathname + (search.length ? `?${search}` : ''), 9 | ); 10 | }; 11 | -------------------------------------------------------------------------------- /packages/fiddle/config/jest/cssTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // This is a custom Jest transformer turning style imports into empty objects. 4 | // http://facebook.github.io/jest/docs/en/webpack.html 5 | 6 | module.exports = { 7 | process() { 8 | return 'module.exports = {};'; 9 | }, 10 | getCacheKey() { 11 | // The output is always the same. 12 | return 'cssTransform'; 13 | }, 14 | }; 15 | -------------------------------------------------------------------------------- /packages/fiddle/src/components/Show.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export type ShowProps = { 4 | when?: any; 5 | }; 6 | 7 | /** 8 | * Declarative show/hide, as opposed to {foo && } 9 | * 10 | * 11 | * 12 | */ 13 | export function Show(props: React.PropsWithChildren) { 14 | return <>{Boolean(props.when) ? props.children : null}; 15 | } 16 | -------------------------------------------------------------------------------- /packages/fiddle/src/functions/set-query-param.ts: -------------------------------------------------------------------------------- 1 | export const setQueryParam = (name: string, value: string): void => { 2 | var searchParams = new URLSearchParams(window.location.search); 3 | searchParams.set(name, value); 4 | const search = searchParams.toString(); 5 | window.history.replaceState( 6 | null, 7 | '', 8 | window.location.pathname + (search.length ? `?${search}` : ''), 9 | ); 10 | }; 11 | -------------------------------------------------------------------------------- /packages/fiddle/src/constants/templates.ts: -------------------------------------------------------------------------------- 1 | export const defaultCode = ` 2 | function fib(index: Int): Int { 3 | let n = index 4 | let a = 0 5 | let b = 1 6 | if (n > 0) { 7 | while (--n) { 8 | let t = a + b 9 | a = b 10 | b = t 11 | } 12 | return b 13 | } 14 | return a 15 | } 16 | `.trim(); 17 | 18 | export const templates: { [key: string]: string } = { 19 | fibonacci: defaultCode, 20 | }; 21 | -------------------------------------------------------------------------------- /packages/fiddle/src/constants/theme.ts: -------------------------------------------------------------------------------- 1 | import { observable, reaction } from 'mobx'; 2 | import { localStorageGet } from '../functions/local-storage-get'; 3 | import { localStorageSet } from '../functions/local-storage-set'; 4 | 5 | export const theme = observable({ 6 | darkMode: localStorageGet('darkMode') ?? false, 7 | }); 8 | 9 | reaction( 10 | () => theme.darkMode, 11 | (darkMode) => localStorageSet('darkMode', darkMode), 12 | ); 13 | -------------------------------------------------------------------------------- /packages/fiddle/src/constants/colors.ts: -------------------------------------------------------------------------------- 1 | import { observable } from 'mobx'; 2 | import { theme } from './theme'; 3 | 4 | export const colors = observable({ 5 | get primary() { 6 | return theme.darkMode ? 'rgb(84, 203, 255)' : 'rgba(28, 151, 204, 1)'; 7 | }, 8 | get contrast() { 9 | return theme.darkMode ? '#444' : '#ddd'; 10 | }, 11 | get background() { 12 | return theme.darkMode ? '#1e1e1e' : '#f8f8f8'; 13 | }, 14 | }); 15 | -------------------------------------------------------------------------------- /packages/fiddle/src/constants/device.ts: -------------------------------------------------------------------------------- 1 | import { observable } from 'mobx'; 2 | import { breakpoints } from './breakpoints'; 3 | 4 | export const device = observable({ 5 | width: window.innerWidth, 6 | get small() { 7 | return device.width < breakpoints.sizes.small; 8 | }, 9 | }); 10 | 11 | window.addEventListener( 12 | 'resize', 13 | () => { 14 | device.width = window.innerWidth; 15 | }, 16 | { passive: true }, 17 | ); 18 | -------------------------------------------------------------------------------- /packages/fiddle/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | 25 | .firebase -------------------------------------------------------------------------------- /packages/fiddle/src/components/TextLink.tsx: -------------------------------------------------------------------------------- 1 | import React, { AnchorHTMLAttributes } from 'react'; 2 | import { colors } from '../constants/colors'; 3 | 4 | export function TextLink(props: AnchorHTMLAttributes) { 5 | return ( 6 | // eslint-disable-next-line jsx-a11y/anchor-has-content 7 | 12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /packages/fiddle/src/functions/local-storage-set.ts: -------------------------------------------------------------------------------- 1 | export type LocalStorageSetOptions = { 2 | suppressWarning?: boolean; 3 | }; 4 | 5 | export const localStorageSet = ( 6 | key: string, 7 | value: any, 8 | options: LocalStorageSetOptions = {}, 9 | ): any => { 10 | try { 11 | return localStorage.setItem(key, JSON.stringify(value)); 12 | } catch (err) { 13 | if (!options.suppressWarning) { 14 | console.warn('Could not set from localStorage', err); 15 | } 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | node: true, 4 | browser: true, 5 | jest: true, 6 | }, 7 | parser: '@typescript-eslint/parser', // Specifies the ESLint parser 8 | extends: [], 9 | parserOptions: { 10 | ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features 11 | sourceType: 'module', // Allows for the use of imports 12 | ecmaFeatures: { 13 | jsx: true, // Allows for the parsing of JSX 14 | }, 15 | }, 16 | 17 | rules: {}, 18 | }; 19 | -------------------------------------------------------------------------------- /packages/core/src/types/json.ts: -------------------------------------------------------------------------------- 1 | // Pure JSON 2 | export type JSONPrimitive = string | null | number | boolean | undefined; 3 | export type JSONObject = { [key: string]: JSON }; 4 | export type JSON = JSONPrimitive | JSONObject | JSON[]; 5 | 6 | // JSON mixed with babel nodes for intermediary compilation steps 7 | export type JSONPrimitiveOrNode = JSONPrimitive | babel.Node; 8 | export type JSONOrNodeObject = { [key: string]: JSONOrNode }; 9 | export type JSONOrNode = JSONPrimitiveOrNode | JSONOrNodeObject | JSONOrNode[]; 10 | -------------------------------------------------------------------------------- /packages/fiddle/src/reportWebVitals.ts: -------------------------------------------------------------------------------- 1 | import { ReportHandler } from 'web-vitals'; 2 | 3 | const reportWebVitals = (onPerfEntry?: ReportHandler) => { 4 | if (onPerfEntry && onPerfEntry instanceof Function) { 5 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 6 | getCLS(onPerfEntry); 7 | getFID(onPerfEntry); 8 | getFCP(onPerfEntry); 9 | getLCP(onPerfEntry); 10 | getTTFB(onPerfEntry); 11 | }); 12 | } 13 | }; 14 | 15 | export default reportWebVitals; 16 | -------------------------------------------------------------------------------- /packages/fiddle/src/functions/local-storage-get.ts: -------------------------------------------------------------------------------- 1 | export type LocalStorageGetOptions = { 2 | suppressWarning?: boolean; 3 | }; 4 | 5 | export const localStorageGet = ( 6 | key: string, 7 | options: LocalStorageGetOptions = {}, 8 | ): any => { 9 | try { 10 | const val = localStorage.getItem(key); 11 | if (typeof val === 'string') { 12 | return JSON.parse(val); 13 | } 14 | return val; 15 | } catch (err) { 16 | if (!options.suppressWarning) { 17 | console.warn('Could not get from localStorage', err); 18 | } 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /packages/core/src/generators/swift.test.ts: -------------------------------------------------------------------------------- 1 | import { expect, test } from '@jest/globals'; 2 | import { toSwift } from './swift'; 3 | 4 | test('Can generate some swift', () => { 5 | const tsCode = ` 6 | function fib(index: Int): Int { 7 | let n = index 8 | let a = 0 9 | let b = 1 10 | if (n > 0) { 11 | while (--n) { 12 | let t = a + b 13 | a = b 14 | b = t 15 | } 16 | return b 17 | } 18 | return a 19 | } 20 | `; 21 | 22 | expect(toSwift(tsCode)).toMatchSnapshot(); 23 | }); 24 | -------------------------------------------------------------------------------- /packages/fiddle/src/index.css: -------------------------------------------------------------------------------- 1 | html, 2 | body, 3 | #root { 4 | height: 100vh; 5 | } 6 | 7 | body { 8 | margin: 0; 9 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 10 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 11 | sans-serif; 12 | -webkit-font-smoothing: antialiased; 13 | -moz-osx-font-smoothing: grayscale; 14 | } 15 | 16 | code { 17 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 18 | monospace; 19 | } 20 | 21 | a { 22 | text-decoration: none; 23 | color: inherit; 24 | } 25 | -------------------------------------------------------------------------------- /packages/fiddle/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "noEmit": true, 4 | "strict": true, 5 | "jsx": "preserve", 6 | "target": "esnext", 7 | "module": "esnext", 8 | "moduleResolution": "node", 9 | "esModuleInterop": true, 10 | "removeComments": true, 11 | "skipLibCheck": true, 12 | "rootDir": ".", 13 | "baseUrl": ".", 14 | "paths": { 15 | "*": ["node_modules", "packages"] 16 | } 17 | }, 18 | "awesomeTypescriptLoaderOptions": { 19 | "useBabel": true, 20 | "babelCore": "@babel/core" 21 | }, 22 | "include": ["packages", "jest-dom/extend-expect"], 23 | "exclude": ["node_modules", "dist"] 24 | } 25 | -------------------------------------------------------------------------------- /packages/fiddle/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "module": "esnext", 17 | "moduleResolution": "node", 18 | "resolveJsonModule": true, 19 | "isolatedModules": true, 20 | "noEmit": true, 21 | "jsx": "react" 22 | }, 23 | "include": [ 24 | "src" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /packages/eslint-plugin/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "eslint-plugin-ts-lite", 3 | "version": "0.0.1", 4 | "main": "./dist/index.js", 5 | "types": "./dist/index.d.ts", 6 | "license": "MIT", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/BuilderIO/ts-lite" 10 | }, 11 | "scripts": { 12 | "test": "jest", 13 | "build": "tsc", 14 | "start": "tsc -w", 15 | "build:declaration": "tsc --project tsconfig.build.json" 16 | }, 17 | "files": [ 18 | "dist" 19 | ], 20 | "dependencies": { 21 | "eslint": "^7.13.0" 22 | }, 23 | "devDependencies": { 24 | "@types/eslint": "^7.2.4", 25 | "jest": "^26.6.3", 26 | "typescript": "^4.0.5" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | clearMocks: true, 3 | coverageDirectory: 'coverage', 4 | coverageReporters: ['text', 'clover'], 5 | coverageThreshold: { 6 | global: { 7 | branches: 80, 8 | functions: 80, 9 | lines: 80, 10 | statements: 80, 11 | }, 12 | }, 13 | globals: { 14 | 'ts-jest': { 15 | extends: './babel.config.js', 16 | }, 17 | }, 18 | moduleFileExtensions: ['ts', 'tsx', 'js'], 19 | modulePathIgnorePatterns: ['dist'], 20 | notify: true, 21 | notifyMode: 'always', 22 | roots: ['packages'], 23 | testMatch: ['**/__tests__/*.+(ts|tsx|js)', '**/*.test.+(ts|tsx|js)'], 24 | transform: { 25 | '^.+\\.(ts|tsx)$': 'ts-jest', 26 | }, 27 | }; 28 | -------------------------------------------------------------------------------- /packages/fiddle/config/pnpTs.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { resolveModuleName } = require('ts-pnp'); 4 | 5 | exports.resolveModuleName = ( 6 | typescript, 7 | moduleName, 8 | containingFile, 9 | compilerOptions, 10 | resolutionHost 11 | ) => { 12 | return resolveModuleName( 13 | moduleName, 14 | containingFile, 15 | compilerOptions, 16 | resolutionHost, 17 | typescript.resolveModuleName 18 | ); 19 | }; 20 | 21 | exports.resolveTypeReferenceDirective = ( 22 | typescript, 23 | moduleName, 24 | containingFile, 25 | compilerOptions, 26 | resolutionHost 27 | ) => { 28 | return resolveModuleName( 29 | moduleName, 30 | containingFile, 31 | compilerOptions, 32 | resolutionHost, 33 | typescript.resolveTypeReferenceDirective 34 | ); 35 | }; 36 | -------------------------------------------------------------------------------- /.github/workflows/pr-runner.yml: -------------------------------------------------------------------------------- 1 | name: PR Runner 2 | on: pull_request 3 | 4 | jobs: 5 | prettier: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - name: Setup 9 | uses: actions/checkout@v2 10 | - name: Use Node.js 11 | uses: actions/setup-node@v1 12 | with: 13 | node-version: '10.x' 14 | 15 | - name: Install and run prettier 16 | run: npm install && npm run prettier -- --check . 17 | 18 | tests: 19 | runs-on: ubuntu-latest 20 | steps: 21 | - name: Setup 22 | uses: actions/checkout@v2 23 | - name: Use Node.js 24 | uses: actions/setup-node@v1 25 | with: 26 | node-version: '10.x' 27 | 28 | - name: Install and run prettier 29 | run: npm install && cd packages/core && npm install && npm run test 30 | -------------------------------------------------------------------------------- /packages/core/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | clearMocks: true, 3 | coverageDirectory: 'coverage', 4 | coverageReporters: ['text', 'clover'], 5 | coverageThreshold: { 6 | global: { 7 | branches: 80, 8 | functions: 80, 9 | lines: 80, 10 | statements: 80, 11 | }, 12 | }, 13 | globals: { 14 | 'ts-jest': { 15 | extends: './babel.config.js', 16 | // module: 'commonjs', 17 | }, 18 | }, 19 | moduleFileExtensions: ['ts', 'tsx', 'js'], 20 | modulePathIgnorePatterns: ['dist'], 21 | notify: true, 22 | notifyMode: 'always', 23 | roots: [''], 24 | testMatch: ['**/__tests__/*.+(ts|tsx|js)', '**/*.test.+(ts|tsx|js)'], 25 | transform: { 26 | '^.+\\.raw\\.(ts|tsx|js|jsx)$': 'jest-raw-loader', 27 | '^.+\\.(ts|tsx)$': 'ts-jest', 28 | }, 29 | }; 30 | -------------------------------------------------------------------------------- /packages/eslint-plugin/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | clearMocks: true, 3 | coverageDirectory: 'coverage', 4 | coverageReporters: ['text', 'clover'], 5 | coverageThreshold: { 6 | global: { 7 | branches: 80, 8 | functions: 80, 9 | lines: 80, 10 | statements: 80, 11 | }, 12 | }, 13 | globals: { 14 | 'ts-jest': { 15 | extends: './babel.config.js', 16 | // module: 'commonjs', 17 | }, 18 | }, 19 | moduleFileExtensions: ['ts', 'tsx', 'js'], 20 | modulePathIgnorePatterns: ['dist'], 21 | notify: true, 22 | notifyMode: 'always', 23 | roots: [''], 24 | testMatch: ['**/__tests__/*.+(ts|tsx|js)', '**/*.test.+(ts|tsx|js)'], 25 | transform: { 26 | '^.+\\.(ts|tsx)$': 'ts-jest', 27 | }, 28 | setupFilesAfterEnv: ['../../jest/setupTests.ts'], 29 | }; 30 | -------------------------------------------------------------------------------- /packages/core/src/constants/media-sizes.ts: -------------------------------------------------------------------------------- 1 | export type Size = 'large' | 'medium' | 'small'; 2 | export const sizeNames: Size[] = ['small', 'medium', 'large']; 3 | 4 | export const sizes = { 5 | small: { 6 | min: 320, 7 | default: 321, 8 | max: 640, 9 | }, 10 | medium: { 11 | min: 641, 12 | default: 642, 13 | max: 991, 14 | }, 15 | large: { 16 | min: 990, 17 | default: 991, 18 | max: 1200, 19 | }, 20 | getWidthForSize(size: Size) { 21 | return this[size].default; 22 | }, 23 | getSizeForWidth(width: number) { 24 | for (const size of sizeNames) { 25 | const value = this[size]; 26 | if (width <= value.max) { 27 | return size; 28 | } 29 | } 30 | return 'large'; 31 | }, 32 | }; 33 | 34 | export const mediaQueryRegex = /@\s*?media\s*?\(\s*?max-width\s*?:\s*?(\d+)(px)\s*?\)\s*?/; 35 | -------------------------------------------------------------------------------- /packages/fiddle/src/hooks/use-event-listener.ts: -------------------------------------------------------------------------------- 1 | import { useRef, useEffect } from 'react'; 2 | 3 | export function useEventListener( 4 | element: EventTarget, 5 | eventName: string, 6 | handler: (event: EventType) => void, 7 | listenerOptions?: AddEventListenerOptions, 8 | ) { 9 | const { once, passive } = listenerOptions || {}; 10 | const savedHandler = useRef(handler); 11 | 12 | useEffect(() => { 13 | savedHandler.current = handler; 14 | }, [handler]); 15 | 16 | useEffect(() => { 17 | const eventListener = (event: Event) => 18 | savedHandler.current(event as EventType); 19 | 20 | element.addEventListener(eventName, eventListener, { once, passive }); 21 | 22 | return () => { 23 | element.removeEventListener(eventName, eventListener); 24 | }; 25 | }, [eventName, element, once, passive]); 26 | } 27 | -------------------------------------------------------------------------------- /packages/fiddle/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './components/App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | import { configure } from 'mobx'; 7 | 8 | configure({ 9 | enforceActions: 'never', 10 | }); 11 | 12 | if (process.env.NODE_ENV === 'development') { 13 | const { stopReportingRuntimeErrors } = require('react-error-overlay'); 14 | // These freeze the browser when syntax highlighting, sometimes for **long** periods 15 | stopReportingRuntimeErrors(); 16 | } 17 | 18 | ReactDOM.render(, document.getElementById('root')); 19 | 20 | // If you want to start measuring performance in your app, pass a function 21 | // to log results (for example: reportWebVitals(console.log)) 22 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 23 | reportWebVitals(); 24 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = (api) => { 2 | api.cache(true); 3 | 4 | return { 5 | presets: [ 6 | [ 7 | '@babel/env', 8 | { 9 | useBuiltIns: 'usage', 10 | corejs: 3, 11 | targets: { 12 | browsers: 'Last 2 Chrome versions, Firefox ESR', 13 | node: 'current', 14 | }, 15 | }, 16 | ], 17 | [ 18 | '@babel/preset-react', 19 | { 20 | development: process.env.BABEL_ENV !== 'build', 21 | }, 22 | ], 23 | '@babel/preset-typescript', 24 | ], 25 | env: { 26 | build: { 27 | ignore: [ 28 | '**/*.test.tsx', 29 | '**/*.test.ts', 30 | '**/*.story.tsx', 31 | '__snapshots__', 32 | '__tests__', 33 | '__stories__', 34 | ], 35 | }, 36 | }, 37 | ignore: ['node_modules'], 38 | }; 39 | }; 40 | -------------------------------------------------------------------------------- /packages/core/src/helpers/format.ts: -------------------------------------------------------------------------------- 1 | const preSpaceRegex = /^\s*/g; 2 | 3 | const DEFAULT_INDENT_SPACES = 2; 4 | 5 | /** 6 | * Generic formatter for languages prettier doesn't support, like Swift 7 | * 8 | * Not super sophisticated, but much better than nothing 9 | */ 10 | export const format = (str: string, indentSpaces = DEFAULT_INDENT_SPACES) => { 11 | let currentIndent = 0; 12 | const lines = str.split('\n'); 13 | lines.forEach((item, index) => { 14 | item = item.trimEnd(); 15 | 16 | lines[index] = item.replace( 17 | preSpaceRegex, 18 | ' '.repeat(currentIndent * indentSpaces), 19 | ); 20 | 21 | const nextLine = lines[index + 1]; 22 | if (!nextLine) { 23 | return; 24 | } 25 | 26 | if (nextLine.match(/^\s*[})][,;]?\s*$/)) { 27 | currentIndent--; 28 | } else if (item.match(/[({]$/)) { 29 | currentIndent++; 30 | } 31 | 32 | currentIndent = Math.max(currentIndent, 0); 33 | }); 34 | return lines.join('\n').replace(/\n{3,}/g, '\n\n'); 35 | }; 36 | -------------------------------------------------------------------------------- /packages/core/src/helpers/babel-transform.ts: -------------------------------------------------------------------------------- 1 | import * as babel from '@babel/core'; 2 | const jsxPlugin = require('@babel/plugin-syntax-jsx'); 3 | const tsPreset = require('@babel/preset-typescript'); 4 | const decorators = require('@babel/plugin-syntax-decorators'); 5 | 6 | type Visitor = { 7 | [key: string]: (path: any, context: ContextType) => void; 8 | }; 9 | 10 | export const babelTransform = ( 11 | code: string, 12 | visitor: Visitor, 13 | ) => { 14 | return babel.transform(code, { 15 | sourceFileName: 'file.tsx', 16 | presets: [[tsPreset, { isTSX: true, allExtensions: true }]], 17 | plugins: [ 18 | [decorators, { legacy: true }], 19 | jsxPlugin, 20 | () => ({ 21 | visitor, 22 | }), 23 | ], 24 | }); 25 | }; 26 | export const babelTransformCode = ( 27 | code: string, 28 | visitor: Visitor, 29 | ) => { 30 | return babelTransform(code, visitor)?.code || ''; 31 | }; 32 | -------------------------------------------------------------------------------- /packages/fiddle/src/components/App.tsx: -------------------------------------------------------------------------------- 1 | import '@emotion/core'; 2 | import { useObserver } from 'mobx-react-lite'; 3 | import React from 'react'; 4 | import { createMuiTheme, ThemeProvider } from '@material-ui/core'; 5 | import CssBaseline from '@material-ui/core/CssBaseline'; 6 | import { colors } from '../constants/colors'; 7 | import Fiddle from './Fiddle'; 8 | import { theme } from '../constants/theme'; 9 | 10 | export default function App() { 11 | return useObserver(() => { 12 | const muiTheme = createMuiTheme({ 13 | palette: { 14 | type: theme.darkMode ? 'dark' : 'light', 15 | primary: { main: colors.primary }, 16 | }, 17 | }); 18 | return ( 19 | 20 | 21 | 22 | 27 | 28 | 29 | 30 | ); 31 | }); 32 | } 33 | -------------------------------------------------------------------------------- /packages/fiddle/src/functions/prompt-upload-figma-file.ts: -------------------------------------------------------------------------------- 1 | import { BuilderContent } from '@builder.io/sdk'; 2 | 3 | export async function promptUploadFigmaJsonFile(): Promise { 4 | return new Promise((resolve, reject) => { 5 | const input = document.createElement('input'); 6 | input.style.display = 'none'; 7 | input.type = 'file'; 8 | document.body.appendChild(input); 9 | input.click(); 10 | 11 | // TODO: parse and upload images! 12 | input.addEventListener('change', async (event) => { 13 | const file = (event.target as any).files[0]; 14 | if (file) { 15 | const reader = new FileReader(); 16 | 17 | // Closure to capture the file information. 18 | reader.onload = async (e) => { 19 | const text = (e.target as any).result; 20 | try { 21 | const json = JSON.parse(text); 22 | resolve(json); 23 | } catch (err) { 24 | reject(err); 25 | } 26 | input.remove(); 27 | }; 28 | 29 | reader.readAsText(file); 30 | } 31 | }); 32 | }); 33 | } 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Builder.io, Inc 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /packages/eslint-plugin/src/__test__/no-conditional-render.test.ts: -------------------------------------------------------------------------------- 1 | import { RuleTester } from 'eslint'; 2 | 3 | import { staticControlFlow } from '../index'; 4 | 5 | const ruleTester = new RuleTester(); 6 | 7 | const options = { 8 | parserOptions: { 9 | ecmaVersion: 2018 as 2018, // Allows for the parsing of modern ECMAScript features 10 | sourceType: 'module' as 'module', // Allows for the use of imports 11 | ecmaFeatures: { 12 | jsx: true, // Allows for the parsing of JSX 13 | }, 14 | }, 15 | }; 16 | 17 | ruleTester.run('static-control-flow', staticControlFlow, { 18 | valid: [ 19 | { 20 | ...options, 21 | code: '{bar}', 22 | }, 23 | { 24 | ...options, 25 | code: '{item => }', 26 | }, 27 | ], 28 | 29 | invalid: [ 30 | { 31 | ...options, 32 | code: '
{foo ?
: }
', 33 | errors: [{ message: /static/i }], 34 | }, 35 | { 36 | ...options, 37 | code: '
{list.map(item => )}
', 38 | errors: [{ message: /static/i }], 39 | }, 40 | ], 41 | }); 42 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@builder.io/ts-lite-repo", 3 | "version": "0.0.0", 4 | "workspaces": [ 5 | "packages/*" 6 | ], 7 | "private": true, 8 | "scripts": { 9 | "postinstall": "lerna link", 10 | "prettier": "prettier --parser=typescript 'packages/**/*.ts{,x}'", 11 | "build": "lerna run --parallel 'build'", 12 | "commit": "git-cz", 13 | "fix": "run-p -c 'lint:* --fix'", 14 | "lint:css": "stylelint 'packages/**/*.ts{,x}'", 15 | "lint:ts": "eslint 'packages/**/*.ts{,x}'", 16 | "lint": "run-p -c lint:*", 17 | "prerelease": "npm run build", 18 | "release": "lerna publish" 19 | }, 20 | "repository": { 21 | "type": "git", 22 | "url": "https://github.com/BuilderIO/ts-lite" 23 | }, 24 | "resolutions": { 25 | "babel-core": "^7.0.0-bridge.0" 26 | }, 27 | "devDependencies": { 28 | "commitizen": "^3.0.2", 29 | "lerna": "^3.4.0", 30 | "moment": "^2.22.2", 31 | "prettier": "^1.19.1" 32 | }, 33 | "config": { 34 | "commitizen": { 35 | "path": "./node_modules/cz-lerna-changelog" 36 | } 37 | }, 38 | "dependencies": { 39 | "@testing-library/jest-dom": "^5.11.6" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /packages/eslint-plugin/src/index.ts: -------------------------------------------------------------------------------- 1 | import { Rule } from 'eslint'; 2 | import { types } from '@babel/core'; 3 | 4 | export const staticControlFlow = { 5 | create: (context: Readonly): Rule.RuleListener => { 6 | return { 7 | JSXExpressionContainer(node: any) { 8 | if (types.isJSXExpressionContainer(node)) { 9 | if (types.isConditionalExpression(node.expression)) { 10 | context.report({ 11 | node: node as any, 12 | message: 13 | 'Static rendering is required. E.g. {foo ? bar : baz} should be {bar}', 14 | }); 15 | } 16 | if (types.isCallExpression(node.expression)) { 17 | const firstArg = node.expression.arguments[0]; 18 | if ( 19 | types.isArrowFunctionExpression(firstArg) || 20 | types.isFunctionExpression(firstArg) 21 | ) { 22 | context.report({ 23 | node: node as any, 24 | message: 25 | 'Static rendering is required. E.g. {foo.map(...)} should be {...}', 26 | }); 27 | } 28 | } 29 | } 30 | }, 31 | }; 32 | }, 33 | }; 34 | 35 | export const rules = { 36 | 'static-control-flow': staticControlFlow, 37 | }; 38 | -------------------------------------------------------------------------------- /packages/fiddle/config/jest/fileTransform.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const camelcase = require('camelcase'); 5 | 6 | // This is a custom Jest transformer turning file imports into filenames. 7 | // http://facebook.github.io/jest/docs/en/webpack.html 8 | 9 | module.exports = { 10 | process(src, filename) { 11 | const assetFilename = JSON.stringify(path.basename(filename)); 12 | 13 | if (filename.match(/\.svg$/)) { 14 | // Based on how SVGR generates a component name: 15 | // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6 16 | const pascalCaseFilename = camelcase(path.parse(filename).name, { 17 | pascalCase: true, 18 | }); 19 | const componentName = `Svg${pascalCaseFilename}`; 20 | return `const React = require('react'); 21 | module.exports = { 22 | __esModule: true, 23 | default: ${assetFilename}, 24 | ReactComponent: React.forwardRef(function ${componentName}(props, ref) { 25 | return { 26 | $$typeof: Symbol.for('react.element'), 27 | type: 'svg', 28 | ref: ref, 29 | key: null, 30 | props: Object.assign({}, props, { 31 | children: ${assetFilename} 32 | }) 33 | }; 34 | }), 35 | };`; 36 | } 37 | 38 | return `module.exports = ${assetFilename};`; 39 | }, 40 | }; 41 | -------------------------------------------------------------------------------- /packages/fiddle/scripts/test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Do this as the first thing so that any code reading it knows the right env. 4 | process.env.BABEL_ENV = 'test'; 5 | process.env.NODE_ENV = 'test'; 6 | process.env.PUBLIC_URL = ''; 7 | 8 | // Makes the script crash on unhandled rejections instead of silently 9 | // ignoring them. In the future, promise rejections that are not handled will 10 | // terminate the Node.js process with a non-zero exit code. 11 | process.on('unhandledRejection', err => { 12 | throw err; 13 | }); 14 | 15 | // Ensure environment variables are read. 16 | require('../config/env'); 17 | 18 | 19 | const jest = require('jest'); 20 | const execSync = require('child_process').execSync; 21 | let argv = process.argv.slice(2); 22 | 23 | function isInGitRepository() { 24 | try { 25 | execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' }); 26 | return true; 27 | } catch (e) { 28 | return false; 29 | } 30 | } 31 | 32 | function isInMercurialRepository() { 33 | try { 34 | execSync('hg --cwd . root', { stdio: 'ignore' }); 35 | return true; 36 | } catch (e) { 37 | return false; 38 | } 39 | } 40 | 41 | // Watch unless on CI or explicitly running all tests 42 | if ( 43 | !process.env.CI && 44 | argv.indexOf('--watchAll') === -1 && 45 | argv.indexOf('--watchAll=false') === -1 46 | ) { 47 | // https://github.com/facebook/create-react-app/issues/5210 48 | const hasSourceControl = isInGitRepository() || isInMercurialRepository(); 49 | argv.push(hasSourceControl ? '--watch' : '--watchAll'); 50 | } 51 | 52 | 53 | jest.run(argv); 54 | -------------------------------------------------------------------------------- /packages/fiddle/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | 5 | declare namespace NodeJS { 6 | interface ProcessEnv { 7 | readonly NODE_ENV: 'development' | 'production' | 'test'; 8 | readonly PUBLIC_URL: string; 9 | } 10 | } 11 | 12 | declare module '*.avif' { 13 | const src: string; 14 | export default src; 15 | } 16 | 17 | declare module '*.bmp' { 18 | const src: string; 19 | export default src; 20 | } 21 | 22 | declare module '*.gif' { 23 | const src: string; 24 | export default src; 25 | } 26 | 27 | declare module '*.jpg' { 28 | const src: string; 29 | export default src; 30 | } 31 | 32 | declare module '*.jpeg' { 33 | const src: string; 34 | export default src; 35 | } 36 | 37 | declare module '*.png' { 38 | const src: string; 39 | export default src; 40 | } 41 | 42 | declare module '*.webp' { 43 | const src: string; 44 | export default src; 45 | } 46 | 47 | declare module '*.svg' { 48 | import * as React from 'react'; 49 | 50 | export const ReactComponent: React.FunctionComponent & { 53 | title?: string; 54 | }>; 55 | 56 | const src: string; 57 | export default src; 58 | } 59 | 60 | declare module '*.module.css' { 61 | const classes: { readonly [key: string]: string }; 62 | export default classes; 63 | } 64 | 65 | declare module '*.module.scss' { 66 | const classes: { readonly [key: string]: string }; 67 | export default classes; 68 | } 69 | 70 | declare module '*.module.sass' { 71 | const classes: { readonly [key: string]: string }; 72 | export default classes; 73 | } 74 | -------------------------------------------------------------------------------- /packages/core/src/modules/plugins.ts: -------------------------------------------------------------------------------- 1 | import { SourceFile } from 'typescript'; 2 | 3 | export type Plugin = { 4 | json?: { 5 | // Happens before any modifiers 6 | pre?: (json: SourceFile) => SourceFile | void; 7 | // Happens after built in modifiers 8 | post?: (json: SourceFile) => SourceFile | void; 9 | }; 10 | code?: { 11 | // Happens before formatting 12 | pre?: (code: string) => string; 13 | // Happens after formatting 14 | post?: (code: string) => string; 15 | }; 16 | }; 17 | 18 | export const runPreJsonPlugins = (json: SourceFile, plugins: Plugin[]) => { 19 | let useJson = json; 20 | for (const plugin of plugins) { 21 | const preFunction = plugin.json?.pre; 22 | if (preFunction) { 23 | useJson = preFunction(json) || json; 24 | } 25 | } 26 | return useJson; 27 | }; 28 | 29 | export const runPostJsonPlugins = (json: SourceFile, plugins: Plugin[]) => { 30 | let useJson = json; 31 | for (const plugin of plugins) { 32 | const postFunction = plugin.json?.post; 33 | if (postFunction) { 34 | useJson = postFunction(json) || json; 35 | } 36 | } 37 | return useJson; 38 | }; 39 | 40 | export const runPreCodePlugins = (code: string, plugins: Plugin[]) => { 41 | let string = code; 42 | for (const plugin of plugins) { 43 | const preFunction = plugin.code?.pre; 44 | if (preFunction) { 45 | string = preFunction(string); 46 | } 47 | } 48 | return string; 49 | }; 50 | 51 | export const runPostCodePlugins = (code: string, plugins: Plugin[]) => { 52 | let string = code; 53 | for (const plugin of plugins) { 54 | const postFunction = plugin.code?.post; 55 | if (postFunction) { 56 | string = postFunction(string); 57 | } 58 | } 59 | return string; 60 | }; 61 | -------------------------------------------------------------------------------- /packages/core/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | Compiled TypeScript. Generates Go, Swift, Kotlin, WASM 5 |

6 | 7 |

8 | code style: prettier 9 | PRs Welcome 10 | License 11 | Types 12 | 13 |

14 | 15 |

16 | 17 |

18 | 19 | ## Status 20 | 21 | This package is highly experimental. 22 | 23 | | Language | Status | 24 | | -------- | ------ | 25 | | Go | WIP | 26 | | Swift | WIP | 27 | | Kotlin | WIP | 28 | | WASM | WIP | 29 | 30 | ## Who uses it 31 | 32 | Don't use this for production today. The below use cases are what we are building this for: 33 | 34 | - [Builder.io](https://github.com/builderio/builder) 35 | - [JSX Lite](https://github.com/builderio/jsx-lite) 36 | - [Build.](https://github.com/builderio/build.) 37 | 38 | ## Coming soon 39 | 40 | - Fiddle/playground 41 | - Plugin API docs for custom syntaxes and extensions 42 | - Stable (v1) release 43 | - VS code plugin 44 | - Build. support 45 | 46 |
47 |

48 | Made with ❤️ by Builder.io 49 |

50 | -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | Compiled TypeScript. Generates Go, Swift, Kotlin, WASM 5 |

6 | 7 |

8 | code style: prettier 9 | PRs Welcome 10 | License 11 | Types 12 | 13 |

14 | 15 |

16 | 17 |

18 | 19 | ## Status 20 | 21 | This package is highly experimental. 22 | 23 | | Language | Status | 24 | | -------- | ------ | 25 | | Go | WIP | 26 | | Swift | WIP | 27 | | Kotlin | WIP | 28 | | WASM | WIP | 29 | 30 | ## Who uses it 31 | 32 | Don't use this for production today. The below use cases are what we are building this for: 33 | 34 | - [Builder.io](https://github.com/builderio/builder) 35 | - [JSX Lite](https://github.com/builderio/jsx-lite) 36 | - [Build.](https://github.com/builderio/build.) 37 | 38 | ## Coming soon 39 | 40 | - Fiddle/playground 41 | - Plugin API docs for custom syntaxes and extensions 42 | - Stable (v1) release 43 | - VS code plugin 44 | - Build. support 45 | 46 |
47 |

48 | Made with ❤️ by Builder.io 49 |

50 | -------------------------------------------------------------------------------- /packages/fiddle/config/getHttpsConfig.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const crypto = require('crypto'); 6 | const chalk = require('react-dev-utils/chalk'); 7 | const paths = require('./paths'); 8 | 9 | // Ensure the certificate and key provided are valid and if not 10 | // throw an easy to debug error 11 | function validateKeyAndCerts({ cert, key, keyFile, crtFile }) { 12 | let encrypted; 13 | try { 14 | // publicEncrypt will throw an error with an invalid cert 15 | encrypted = crypto.publicEncrypt(cert, Buffer.from('test')); 16 | } catch (err) { 17 | throw new Error( 18 | `The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}` 19 | ); 20 | } 21 | 22 | try { 23 | // privateDecrypt will throw an error with an invalid key 24 | crypto.privateDecrypt(key, encrypted); 25 | } catch (err) { 26 | throw new Error( 27 | `The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${ 28 | err.message 29 | }` 30 | ); 31 | } 32 | } 33 | 34 | // Read file and throw an error if it doesn't exist 35 | function readEnvFile(file, type) { 36 | if (!fs.existsSync(file)) { 37 | throw new Error( 38 | `You specified ${chalk.cyan( 39 | type 40 | )} in your env, but the file "${chalk.yellow(file)}" can't be found.` 41 | ); 42 | } 43 | return fs.readFileSync(file); 44 | } 45 | 46 | // Get the https config 47 | // Return cert files if provided in env, otherwise just true or false 48 | function getHttpsConfig() { 49 | const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env; 50 | const isHttps = HTTPS === 'true'; 51 | 52 | if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) { 53 | const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE); 54 | const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE); 55 | const config = { 56 | cert: readEnvFile(crtFile, 'SSL_CRT_FILE'), 57 | key: readEnvFile(keyFile, 'SSL_KEY_FILE'), 58 | }; 59 | 60 | validateKeyAndCerts({ ...config, keyFile, crtFile }); 61 | return config; 62 | } 63 | return isHttps; 64 | } 65 | 66 | module.exports = getHttpsConfig; 67 | -------------------------------------------------------------------------------- /packages/fiddle/config/paths.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const path = require('path'); 4 | const fs = require('fs'); 5 | const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath'); 6 | 7 | // Make sure any symlinks in the project folder are resolved: 8 | // https://github.com/facebook/create-react-app/issues/637 9 | const appDirectory = fs.realpathSync(process.cwd()); 10 | const resolveApp = relativePath => path.resolve(appDirectory, relativePath); 11 | 12 | // We use `PUBLIC_URL` environment variable or "homepage" field to infer 13 | // "public path" at which the app is served. 14 | // webpack needs to know it to put the right 55 | 56 | 57 | 58 | 59 |
60 | 70 | 71 | 72 | 73 | 74 | 78 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /packages/core/src/generators/go.ts: -------------------------------------------------------------------------------- 1 | import dedent from 'dedent'; 2 | import * as ts from 'typescript'; 3 | import { format } from '../helpers/format'; 4 | import { parse } from '../parsers/ts'; 5 | 6 | export function toGo(code: string, options = {}) { 7 | const parsed = parse(code); 8 | return format(types.SourceFile(parsed)); 9 | } 10 | 11 | const typesMap: { [key: string]: string | undefined } = { 12 | Int: 'int', 13 | }; 14 | 15 | const getType = (text: string) => typesMap[text] || text; 16 | 17 | const types = { 18 | SourceFile(node: ts.SourceFile): string { 19 | return node.statements.map((statement) => this.Node(statement)).join('\n'); 20 | }, 21 | VariableStatement(node: ts.VariableStatement) { 22 | return `var ${node.declarationList.declarations 23 | .map((declaration) => this.VariableDeclaration(declaration)) 24 | .join(', ')}`; 25 | }, 26 | VariableDeclaration(node: ts.VariableDeclaration) { 27 | return `${node.name.getText()}${ 28 | node.initializer ? ` := ${this.Node(node.initializer)}` : '' 29 | }`; 30 | }, 31 | NumericLiteral(node: ts.NumericLiteral) { 32 | return node.getText(); 33 | }, 34 | BooleanLiteral(node: ts.BooleanLiteral) { 35 | return node.getText(); 36 | }, 37 | StringLiteral(node: ts.StringLiteral) { 38 | return `"${node.text}"`; 39 | }, 40 | ReturnStatement(node: ts.ReturnStatement) { 41 | return `return ${node.expression ? this.Node(node.expression) : ''}`; 42 | }, 43 | Block(node: ts.Block) { 44 | // TODO 45 | return dedent`{ 46 | ${node.statements.map((statement) => this.Node(statement)).join('\n')} 47 | }`; 48 | }, 49 | BinaryExpression(node: ts.BinaryExpression) { 50 | return `${this.Node(node.left)} ${node.operatorToken.getText()} ${this.Node( 51 | node.right, 52 | )}`; 53 | }, 54 | Identifier(node: ts.Identifier) { 55 | return node.getText(); 56 | }, 57 | ExpressionStatement(node: ts.ExpressionStatement) { 58 | return this.Node(node.expression); 59 | }, 60 | WhileStatement(node: ts.WhileStatement) { 61 | return `for (${this.Node(node.expression)}) ${this.Node(node.statement)}`; 62 | }, 63 | PrefixUnaryExpression(node: ts.PrefixUnaryExpression) { 64 | // TODo: operator map 65 | return `${node.operator === 46 ? '--' : '++'}${this.Node(node.operand)}`; 66 | }, 67 | IfStatement(node: ts.IfStatement) { 68 | return dedent`if ${this.Node(node.expression)} ${this.Node( 69 | node.thenStatement, 70 | )}`; 71 | }, 72 | Parameter(node: ts.ParameterDeclaration) { 73 | return `${node.name.getText()}${ 74 | node.type ? `: ${getType(node.type.getText())}` : '' 75 | }`; 76 | }, 77 | FunctionDeclaration(node: ts.FunctionDeclaration): string { 78 | return dedent`func ${ 79 | node.name?.escapedText 80 | }(${node.parameters.map((param) => this.Parameter(param)).join(', ')})${ 81 | node.type ? ` ${getType(node.type.getText()).replace(':', '')}` : '' 82 | } { 83 | ${node.body?.statements 84 | .map((statement) => this.Node(statement)) 85 | .join('\n')} 86 | }`; 87 | }, 88 | Node(node: ts.Node): string { 89 | for (const key in this) { 90 | if (key === 'Node') { 91 | continue; 92 | } 93 | const checker = (ts as any)[`is${key}`]; 94 | if (checker) { 95 | if (checker(node)) { 96 | return (this as any)[key](node); 97 | } 98 | } 99 | } 100 | 101 | console.warn(`Node type not found for node ${node.kind}`, node); 102 | return `/* Unsupported node type: ${node.kind} */`; 103 | }, 104 | }; 105 | -------------------------------------------------------------------------------- /packages/fiddle/config/modules.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const paths = require('./paths'); 6 | const chalk = require('react-dev-utils/chalk'); 7 | const resolve = require('resolve'); 8 | 9 | /** 10 | * Get additional module paths based on the baseUrl of a compilerOptions object. 11 | * 12 | * @param {Object} options 13 | */ 14 | function getAdditionalModulePaths(options = {}) { 15 | const baseUrl = options.baseUrl; 16 | 17 | if (!baseUrl) { 18 | return ''; 19 | } 20 | 21 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl); 22 | 23 | // We don't need to do anything if `baseUrl` is set to `node_modules`. This is 24 | // the default behavior. 25 | if (path.relative(paths.appNodeModules, baseUrlResolved) === '') { 26 | return null; 27 | } 28 | 29 | // Allow the user set the `baseUrl` to `appSrc`. 30 | if (path.relative(paths.appSrc, baseUrlResolved) === '') { 31 | return [paths.appSrc]; 32 | } 33 | 34 | // If the path is equal to the root directory we ignore it here. 35 | // We don't want to allow importing from the root directly as source files are 36 | // not transpiled outside of `src`. We do allow importing them with the 37 | // absolute path (e.g. `src/Components/Button.js`) but we set that up with 38 | // an alias. 39 | if (path.relative(paths.appPath, baseUrlResolved) === '') { 40 | return null; 41 | } 42 | 43 | // Otherwise, throw an error. 44 | throw new Error( 45 | chalk.red.bold( 46 | "Your project's `baseUrl` can only be set to `src` or `node_modules`." + 47 | ' Create React App does not support other values at this time.' 48 | ) 49 | ); 50 | } 51 | 52 | /** 53 | * Get webpack aliases based on the baseUrl of a compilerOptions object. 54 | * 55 | * @param {*} options 56 | */ 57 | function getWebpackAliases(options = {}) { 58 | const baseUrl = options.baseUrl; 59 | 60 | if (!baseUrl) { 61 | return {}; 62 | } 63 | 64 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl); 65 | 66 | if (path.relative(paths.appPath, baseUrlResolved) === '') { 67 | return { 68 | src: paths.appSrc, 69 | }; 70 | } 71 | } 72 | 73 | /** 74 | * Get jest aliases based on the baseUrl of a compilerOptions object. 75 | * 76 | * @param {*} options 77 | */ 78 | function getJestAliases(options = {}) { 79 | const baseUrl = options.baseUrl; 80 | 81 | if (!baseUrl) { 82 | return {}; 83 | } 84 | 85 | const baseUrlResolved = path.resolve(paths.appPath, baseUrl); 86 | 87 | if (path.relative(paths.appPath, baseUrlResolved) === '') { 88 | return { 89 | '^src/(.*)$': '/src/$1', 90 | }; 91 | } 92 | } 93 | 94 | function getModules() { 95 | // Check if TypeScript is setup 96 | const hasTsConfig = fs.existsSync(paths.appTsConfig); 97 | const hasJsConfig = fs.existsSync(paths.appJsConfig); 98 | 99 | if (hasTsConfig && hasJsConfig) { 100 | throw new Error( 101 | 'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.' 102 | ); 103 | } 104 | 105 | let config; 106 | 107 | // If there's a tsconfig.json we assume it's a 108 | // TypeScript project and set up the config 109 | // based on tsconfig.json 110 | if (hasTsConfig) { 111 | const ts = require(resolve.sync('typescript', { 112 | basedir: paths.appNodeModules, 113 | })); 114 | config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config; 115 | // Otherwise we'll check if there is jsconfig.json 116 | // for non TS projects. 117 | } else if (hasJsConfig) { 118 | config = require(paths.appJsConfig); 119 | } 120 | 121 | config = config || {}; 122 | const options = config.compilerOptions || {}; 123 | 124 | const additionalModulePaths = getAdditionalModulePaths(options); 125 | 126 | return { 127 | additionalModulePaths: additionalModulePaths, 128 | webpackAliases: getWebpackAliases(options), 129 | jestAliases: getJestAliases(options), 130 | hasTsConfig, 131 | }; 132 | } 133 | 134 | module.exports = getModules(); 135 | -------------------------------------------------------------------------------- /packages/fiddle/config/env.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const paths = require('./paths'); 6 | 7 | // Make sure that including paths.js after env.js will read .env variables. 8 | delete require.cache[require.resolve('./paths')]; 9 | 10 | const NODE_ENV = process.env.NODE_ENV; 11 | if (!NODE_ENV) { 12 | throw new Error( 13 | 'The NODE_ENV environment variable is required but was not specified.' 14 | ); 15 | } 16 | 17 | // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use 18 | const dotenvFiles = [ 19 | `${paths.dotenv}.${NODE_ENV}.local`, 20 | // Don't include `.env.local` for `test` environment 21 | // since normally you expect tests to produce the same 22 | // results for everyone 23 | NODE_ENV !== 'test' && `${paths.dotenv}.local`, 24 | `${paths.dotenv}.${NODE_ENV}`, 25 | paths.dotenv, 26 | ].filter(Boolean); 27 | 28 | // Load environment variables from .env* files. Suppress warnings using silent 29 | // if this file is missing. dotenv will never modify any environment variables 30 | // that have already been set. Variable expansion is supported in .env files. 31 | // https://github.com/motdotla/dotenv 32 | // https://github.com/motdotla/dotenv-expand 33 | dotenvFiles.forEach(dotenvFile => { 34 | if (fs.existsSync(dotenvFile)) { 35 | require('dotenv-expand')( 36 | require('dotenv').config({ 37 | path: dotenvFile, 38 | }) 39 | ); 40 | } 41 | }); 42 | 43 | // We support resolving modules according to `NODE_PATH`. 44 | // This lets you use absolute paths in imports inside large monorepos: 45 | // https://github.com/facebook/create-react-app/issues/253. 46 | // It works similar to `NODE_PATH` in Node itself: 47 | // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders 48 | // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. 49 | // Otherwise, we risk importing Node.js core modules into an app instead of webpack shims. 50 | // https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421 51 | // We also resolve them to make sure all tools using them work consistently. 52 | const appDirectory = fs.realpathSync(process.cwd()); 53 | process.env.NODE_PATH = (process.env.NODE_PATH || '') 54 | .split(path.delimiter) 55 | .filter(folder => folder && !path.isAbsolute(folder)) 56 | .map(folder => path.resolve(appDirectory, folder)) 57 | .join(path.delimiter); 58 | 59 | // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be 60 | // injected into the application via DefinePlugin in webpack configuration. 61 | const REACT_APP = /^REACT_APP_/i; 62 | 63 | function getClientEnvironment(publicUrl) { 64 | const raw = Object.keys(process.env) 65 | .filter(key => REACT_APP.test(key)) 66 | .reduce( 67 | (env, key) => { 68 | env[key] = process.env[key]; 69 | return env; 70 | }, 71 | { 72 | // Useful for determining whether we’re running in production mode. 73 | // Most importantly, it switches React into the correct mode. 74 | NODE_ENV: process.env.NODE_ENV || 'development', 75 | // Useful for resolving the correct path to static assets in `public`. 76 | // For example, . 77 | // This should only be used as an escape hatch. Normally you would put 78 | // images into the `src` and `import` them in code to get their paths. 79 | PUBLIC_URL: publicUrl, 80 | // We support configuring the sockjs pathname during development. 81 | // These settings let a developer run multiple simultaneous projects. 82 | // They are used as the connection `hostname`, `pathname` and `port` 83 | // in webpackHotDevClient. They are used as the `sockHost`, `sockPath` 84 | // and `sockPort` options in webpack-dev-server. 85 | WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST, 86 | WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH, 87 | WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT, 88 | // Whether or not react-refresh is enabled. 89 | // react-refresh is not 100% stable at this time, 90 | // which is why it's disabled by default. 91 | // It is defined here so it is available in the webpackHotDevClient. 92 | FAST_REFRESH: process.env.FAST_REFRESH !== 'false', 93 | } 94 | ); 95 | // Stringify all values so we can feed into webpack DefinePlugin 96 | const stringified = { 97 | 'process.env': Object.keys(raw).reduce((env, key) => { 98 | env[key] = JSON.stringify(raw[key]); 99 | return env; 100 | }, {}), 101 | }; 102 | 103 | return { raw, stringified }; 104 | } 105 | 106 | module.exports = getClientEnvironment; 107 | -------------------------------------------------------------------------------- /packages/core/src/generators/swift.ts: -------------------------------------------------------------------------------- 1 | import dedent from 'dedent'; 2 | import * as ts from 'typescript'; 3 | import { format } from '../helpers/format'; 4 | import { parse } from '../parsers/ts'; 5 | 6 | export type ToSwiftOptions = { 7 | /** 8 | * The type of code to generate 9 | * `'idiomatic'` - attempts to generate idiomatic swift, but may need some human adjustments to get 100% ready to run 10 | * `'safe'` - attempts to generate code that will always run as expected without human editing, even if less idiomatic 11 | */ 12 | type: 'idiomatic' | 'safe'; 13 | }; 14 | 15 | export function toSwift( 16 | code: string, 17 | options: Partial = {}, 18 | ): string { 19 | const useOptions: ToSwiftOptions = { 20 | type: 'safe', 21 | ...options, 22 | }; 23 | const parsed = parse(code); 24 | return format(types.SourceFile(parsed, useOptions)); 25 | } 26 | 27 | type TypesMap = Record< 28 | string, 29 | (node: ts.Node, options: ToSwiftOptions) => string 30 | >; 31 | 32 | const types = { 33 | SourceFile(node: ts.SourceFile, options: ToSwiftOptions): string { 34 | return node.statements 35 | .map((statement) => this.Node(statement, options)) 36 | .join('\n'); 37 | }, 38 | VariableStatement( 39 | node: ts.VariableStatement, 40 | options: ToSwiftOptions, 41 | ): string { 42 | return `var ${node.declarationList.declarations 43 | .map((declaration) => this.VariableDeclaration(declaration, options)) 44 | .join(', ')}`; 45 | }, 46 | VariableDeclaration( 47 | node: ts.VariableDeclaration, 48 | options: ToSwiftOptions, 49 | ): string { 50 | return `${node.name.getText()}${ 51 | node.initializer ? ` = ${this.Node(node.initializer, options)}` : '' 52 | }`; 53 | }, 54 | NumericLiteral(node: ts.NumericLiteral, options: ToSwiftOptions): string { 55 | return node.getText(); 56 | }, 57 | BooleanLiteral(node: ts.BooleanLiteral, options: ToSwiftOptions): string { 58 | return node.getText(); 59 | }, 60 | StringLiteral(node: ts.StringLiteral, options: ToSwiftOptions): string { 61 | return `"${node.text}"`; 62 | }, 63 | ReturnStatement(node: ts.ReturnStatement, options: ToSwiftOptions): string { 64 | return `return ${ 65 | node.expression ? this.Node(node.expression, options) : '' 66 | }`; 67 | }, 68 | Block(node: ts.Block, options: ToSwiftOptions): string { 69 | // TODO 70 | return dedent`{ 71 | ${node.statements 72 | .map((statement) => this.Node(statement, options)) 73 | .join('\n')} 74 | }`; 75 | }, 76 | BinaryExpression(node: ts.BinaryExpression, options: ToSwiftOptions): string { 77 | return `${this.Node( 78 | node.left, 79 | options, 80 | )} ${node.operatorToken.getText()} ${this.Node(node.right, options)}`; 81 | }, 82 | Identifier(node: ts.Identifier, options: ToSwiftOptions): string { 83 | return node.getText(); 84 | }, 85 | ExpressionStatement( 86 | node: ts.ExpressionStatement, 87 | options: ToSwiftOptions, 88 | ): string { 89 | return this.Node(node.expression, options); 90 | }, 91 | WhileStatement(node: ts.WhileStatement, options: ToSwiftOptions): string { 92 | return `while ${this.Node(node.expression, options)} ${this.Node( 93 | node.statement, 94 | options, 95 | )}`; 96 | }, 97 | PrefixUnaryExpression( 98 | node: ts.PrefixUnaryExpression, 99 | options: ToSwiftOptions, 100 | ): string { 101 | // TODo: operator map 102 | return `${node.operator === 46 ? '--' : '++'}${this.Node( 103 | node.operand, 104 | options, 105 | )}`; 106 | }, 107 | IfStatement(node: ts.IfStatement, options: ToSwiftOptions): string { 108 | return dedent`if ${this.Node(node.expression, options)} ${this.Node( 109 | node.thenStatement, 110 | options, 111 | )}`; 112 | }, 113 | Parameter(node: ts.ParameterDeclaration, options: ToSwiftOptions): string { 114 | return `${node.name.getText()}${ 115 | node.type ? `: ${node.type.getText()}` : '' 116 | }`; 117 | }, 118 | FunctionDeclaration( 119 | node: ts.FunctionDeclaration, 120 | options: ToSwiftOptions, 121 | ): string { 122 | return dedent`func ${ 123 | node.name?.escapedText 124 | }(${node.parameters 125 | .map((param) => this.Parameter(param, options)) 126 | .join(', ')})${node.type ? ` -> ${node.type.getText()}` : ''} { 127 | ${node.body?.statements 128 | .map((statement) => this.Node(statement, options)) 129 | .join('\n')} 130 | }`; 131 | }, 132 | Node(node: ts.Node, options: ToSwiftOptions): string { 133 | for (const key in this) { 134 | if (key === 'Node') { 135 | continue; 136 | } 137 | const checker = (ts as any)[`is${key}`]; 138 | if (checker) { 139 | if (checker(node)) { 140 | return ((this as any) as TypesMap)[key](node, options); 141 | } 142 | } 143 | } 144 | 145 | console.warn(`Node type not found for node ${node.kind}`, node); 146 | return `/* Unsupported node type: ${node.kind} */`; 147 | }, 148 | }; 149 | -------------------------------------------------------------------------------- /packages/fiddle/public/preview.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Builder 5 | 6 | 10 | 11 | 12 | 13 | 227 | 228 | 229 | 230 |
231 | 235 |
236 |
237 | 238 | 239 | -------------------------------------------------------------------------------- /packages/fiddle/scripts/start.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Do this as the first thing so that any code reading it knows the right env. 4 | process.env.BABEL_ENV = 'development'; 5 | process.env.NODE_ENV = 'development'; 6 | 7 | // Makes the script crash on unhandled rejections instead of silently 8 | // ignoring them. In the future, promise rejections that are not handled will 9 | // terminate the Node.js process with a non-zero exit code. 10 | process.on('unhandledRejection', err => { 11 | throw err; 12 | }); 13 | 14 | // Ensure environment variables are read. 15 | require('../config/env'); 16 | 17 | 18 | const fs = require('fs'); 19 | const chalk = require('react-dev-utils/chalk'); 20 | const webpack = require('webpack'); 21 | const WebpackDevServer = require('webpack-dev-server'); 22 | const clearConsole = require('react-dev-utils/clearConsole'); 23 | const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); 24 | const { 25 | choosePort, 26 | createCompiler, 27 | prepareProxy, 28 | prepareUrls, 29 | } = require('react-dev-utils/WebpackDevServerUtils'); 30 | const openBrowser = require('react-dev-utils/openBrowser'); 31 | const semver = require('semver'); 32 | const paths = require('../config/paths'); 33 | const configFactory = require('../config/webpack.config'); 34 | const createDevServerConfig = require('../config/webpackDevServer.config'); 35 | const getClientEnvironment = require('../config/env'); 36 | const react = require(require.resolve('react', { paths: [paths.appPath] })); 37 | 38 | const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1)); 39 | const useYarn = fs.existsSync(paths.yarnLockFile); 40 | const isInteractive = process.stdout.isTTY; 41 | 42 | // Warn and crash if required files are missing 43 | if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { 44 | process.exit(1); 45 | } 46 | 47 | // Tools like Cloud9 rely on this. 48 | const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; 49 | const HOST = process.env.HOST || '0.0.0.0'; 50 | 51 | if (process.env.HOST) { 52 | console.log( 53 | chalk.cyan( 54 | `Attempting to bind to HOST environment variable: ${chalk.yellow( 55 | chalk.bold(process.env.HOST) 56 | )}` 57 | ) 58 | ); 59 | console.log( 60 | `If this was unintentional, check that you haven't mistakenly set it in your shell.` 61 | ); 62 | console.log( 63 | `Learn more here: ${chalk.yellow('https://cra.link/advanced-config')}` 64 | ); 65 | console.log(); 66 | } 67 | 68 | // We require that you explicitly set browsers and do not fall back to 69 | // browserslist defaults. 70 | const { checkBrowsers } = require('react-dev-utils/browsersHelper'); 71 | checkBrowsers(paths.appPath, isInteractive) 72 | .then(() => { 73 | // We attempt to use the default port but if it is busy, we offer the user to 74 | // run on a different port. `choosePort()` Promise resolves to the next free port. 75 | return choosePort(HOST, DEFAULT_PORT); 76 | }) 77 | .then(port => { 78 | if (port == null) { 79 | // We have not found a port. 80 | return; 81 | } 82 | 83 | const config = configFactory('development'); 84 | const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; 85 | const appName = require(paths.appPackageJson).name; 86 | 87 | const useTypeScript = fs.existsSync(paths.appTsConfig); 88 | const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true'; 89 | const urls = prepareUrls( 90 | protocol, 91 | HOST, 92 | port, 93 | paths.publicUrlOrPath.slice(0, -1) 94 | ); 95 | const devSocket = { 96 | warnings: warnings => 97 | devServer.sockWrite(devServer.sockets, 'warnings', warnings), 98 | errors: errors => 99 | devServer.sockWrite(devServer.sockets, 'errors', errors), 100 | }; 101 | // Create a webpack compiler that is configured with custom messages. 102 | const compiler = createCompiler({ 103 | appName, 104 | config, 105 | devSocket, 106 | urls, 107 | useYarn, 108 | useTypeScript, 109 | tscCompileOnError, 110 | webpack, 111 | }); 112 | // Load proxy config 113 | const proxySetting = require(paths.appPackageJson).proxy; 114 | const proxyConfig = prepareProxy( 115 | proxySetting, 116 | paths.appPublic, 117 | paths.publicUrlOrPath 118 | ); 119 | // Serve webpack assets generated by the compiler over a web server. 120 | const serverConfig = createDevServerConfig( 121 | proxyConfig, 122 | urls.lanUrlForConfig 123 | ); 124 | const devServer = new WebpackDevServer(compiler, serverConfig); 125 | // Launch WebpackDevServer. 126 | devServer.listen(port, HOST, err => { 127 | if (err) { 128 | return console.log(err); 129 | } 130 | if (isInteractive) { 131 | clearConsole(); 132 | } 133 | 134 | if (env.raw.FAST_REFRESH && semver.lt(react.version, '16.10.0')) { 135 | console.log( 136 | chalk.yellow( 137 | `Fast Refresh requires React 16.10 or higher. You are using React ${react.version}.` 138 | ) 139 | ); 140 | } 141 | 142 | console.log(chalk.cyan('Starting the development server...\n')); 143 | openBrowser(urls.localUrlForBrowser); 144 | }); 145 | 146 | ['SIGINT', 'SIGTERM'].forEach(function (sig) { 147 | process.on(sig, function () { 148 | devServer.close(); 149 | process.exit(); 150 | }); 151 | }); 152 | 153 | if (process.env.CI !== 'true') { 154 | // Gracefully exit when stdin ends 155 | process.stdin.on('end', function () { 156 | devServer.close(); 157 | process.exit(); 158 | }); 159 | } 160 | }) 161 | .catch(err => { 162 | if (err && err.message) { 163 | console.log(err.message); 164 | } 165 | process.exit(1); 166 | }); 167 | -------------------------------------------------------------------------------- /packages/fiddle/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@builder.io/ts-lite-fiddle", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@babel/core": "7.12.3", 7 | "@builder.io/ts-lite": "0.0.1", 8 | "@emotion/babel-preset-css-prop": "^10.2.1", 9 | "@emotion/core": "^10.1.1", 10 | "@material-ui/core": "^4.11.0", 11 | "@material-ui/lab": "^4.0.0-alpha.56", 12 | "@pmmmwh/react-refresh-webpack-plugin": "0.4.2", 13 | "@svgr/webpack": "5.4.0", 14 | "@testing-library/jest-dom": "^5.11.5", 15 | "@testing-library/react": "^11.1.1", 16 | "@testing-library/user-event": "^12.2.0", 17 | "@types/dedent": "^0.7.0", 18 | "@types/jest": "^26.0.15", 19 | "@types/node": "^12.19.4", 20 | "@types/react": "^16.9.56", 21 | "@types/react-dom": "^16.9.9", 22 | "@typescript-eslint/eslint-plugin": "^4.5.0", 23 | "@typescript-eslint/parser": "^4.5.0", 24 | "babel-eslint": "^10.1.0", 25 | "babel-jest": "^26.6.0", 26 | "babel-loader": "8.1.0", 27 | "babel-plugin-named-asset-import": "^0.3.7", 28 | "babel-preset-react-app": "^10.0.0", 29 | "bfj": "^7.0.2", 30 | "camelcase": "^6.1.0", 31 | "case-sensitive-paths-webpack-plugin": "2.3.0", 32 | "css-loader": "4.3.0", 33 | "dedent": "^0.7.0", 34 | "dotenv": "8.2.0", 35 | "dotenv-expand": "5.1.0", 36 | "eslint": "^7.11.0", 37 | "eslint-config-react-app": "^6.0.0", 38 | "eslint-plugin-flowtype": "^5.2.0", 39 | "eslint-plugin-import": "^2.22.1", 40 | "eslint-plugin-jest": "^24.1.0", 41 | "eslint-plugin-jsx-a11y": "^6.3.1", 42 | "eslint-plugin-react": "^7.21.5", 43 | "eslint-plugin-react-hooks": "^4.2.0", 44 | "eslint-plugin-testing-library": "^3.9.2", 45 | "eslint-webpack-plugin": "^2.1.0", 46 | "file-loader": "6.1.1", 47 | "fs-extra": "^9.0.1", 48 | "html-webpack-plugin": "4.5.0", 49 | "identity-obj-proxy": "3.0.0", 50 | "install": "^0.13.0", 51 | "jest": "26.6.0", 52 | "jest-circus": "26.6.0", 53 | "jest-resolve": "26.6.0", 54 | "jest-watch-typeahead": "0.6.1", 55 | "jscodeshift": "^0.11.0", 56 | "mini-css-extract-plugin": "0.11.3", 57 | "mobx": "^6.0.3", 58 | "mobx-react-lite": "^3.1.5", 59 | "monaco-editor": "^0.21.2", 60 | "monaco-editor-webpack-plugin": "^2.0.0", 61 | "monaco-jsx-highlighter": "0.0.15", 62 | "monaco-themes": "^0.3.3", 63 | "npm": "^6.14.8", 64 | "optimize-css-assets-webpack-plugin": "5.0.4", 65 | "pnp-webpack-plugin": "1.6.4", 66 | "postcss-flexbugs-fixes": "4.2.1", 67 | "postcss-loader": "3.0.0", 68 | "postcss-normalize": "8.0.1", 69 | "postcss-preset-env": "6.7.0", 70 | "postcss-safe-parser": "5.0.2", 71 | "prettier": "^2.1.2", 72 | "react": "^17.0.1", 73 | "react-app-polyfill": "^2.0.0", 74 | "react-dev-utils": "^11.0.0", 75 | "react-dom": "^17.0.1", 76 | "react-error-overlay": "^6.0.8", 77 | "react-monaco-editor": "^0.40.0", 78 | "react-refresh": "^0.8.3", 79 | "resolve": "1.18.1", 80 | "resolve-url-loader": "^3.1.2", 81 | "sass-loader": "8.0.2", 82 | "semver": "7.3.2", 83 | "style-loader": "1.3.0", 84 | "terser-webpack-plugin": "4.2.3", 85 | "ts-pnp": "1.2.0", 86 | "typescript": "^4.0.5", 87 | "url-loader": "4.1.1", 88 | "web-vitals": "^0.2.4", 89 | "webcomponents-in-react": "^1.0.1", 90 | "webpack": "4.44.2", 91 | "webpack-dev-server": "3.11.0", 92 | "webpack-manifest-plugin": "2.2.0", 93 | "workbox-webpack-plugin": "5.1.4" 94 | }, 95 | "scripts": { 96 | "start": "node scripts/start.js", 97 | "build": "GENERATE_SOURCEMAP=false node scripts/build.js", 98 | "test": "node scripts/test.js", 99 | "release": "npm run build && firebase deploy --only hosting" 100 | }, 101 | "eslintConfig": { 102 | "extends": [ 103 | "react-app", 104 | "react-app/jest" 105 | ] 106 | }, 107 | "browserslist": { 108 | "production": [ 109 | ">0.2%", 110 | "not dead", 111 | "not op_mini all" 112 | ], 113 | "development": [ 114 | "last 1 chrome version", 115 | "last 1 firefox version", 116 | "last 1 safari version" 117 | ] 118 | }, 119 | "devDependencies": { 120 | "@builder.io/sdk": "^1.1.20", 121 | "@types/jscodeshift": "^0.7.1", 122 | "customize-cra": "^1.0.0", 123 | "raw-loader": "^4.0.2", 124 | "react-app-rewired": "^2.1.6" 125 | }, 126 | "jest": { 127 | "roots": [ 128 | "/src" 129 | ], 130 | "collectCoverageFrom": [ 131 | "src/**/*.{js,jsx,ts,tsx}", 132 | "!src/**/*.d.ts" 133 | ], 134 | "setupFiles": [ 135 | "react-app-polyfill/jsdom" 136 | ], 137 | "setupFilesAfterEnv": [ 138 | "/src/setupTests.ts" 139 | ], 140 | "testMatch": [ 141 | "/src/**/__tests__/**/*.{js,jsx,ts,tsx}", 142 | "/src/**/*.{spec,test}.{js,jsx,ts,tsx}" 143 | ], 144 | "testEnvironment": "jsdom", 145 | "testRunner": "/Users/stephensewell/Projects/builder/ts-lite/packages/fiddle/node_modules/jest-circus/runner.js", 146 | "transform": { 147 | "^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "/node_modules/babel-jest", 148 | "^.+\\.css$": "/config/jest/cssTransform.js", 149 | "^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)": "/config/jest/fileTransform.js" 150 | }, 151 | "transformIgnorePatterns": [ 152 | "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$", 153 | "^.+\\.module\\.(css|sass|scss)$" 154 | ], 155 | "modulePaths": [], 156 | "moduleNameMapper": { 157 | "^react-native$": "react-native-web", 158 | "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy" 159 | }, 160 | "moduleFileExtensions": [ 161 | "web.js", 162 | "js", 163 | "web.ts", 164 | "ts", 165 | "web.tsx", 166 | "tsx", 167 | "json", 168 | "web.jsx", 169 | "jsx", 170 | "node" 171 | ], 172 | "watchPlugins": [ 173 | "jest-watch-typeahead/filename", 174 | "jest-watch-typeahead/testname" 175 | ], 176 | "resetMocks": true 177 | }, 178 | "babel": { 179 | "presets": [ 180 | "react-app" 181 | ] 182 | } 183 | } 184 | -------------------------------------------------------------------------------- /packages/fiddle/config/webpackDevServer.config.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware'); 5 | const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware'); 6 | const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware'); 7 | const ignoredFiles = require('react-dev-utils/ignoredFiles'); 8 | const redirectServedPath = require('react-dev-utils/redirectServedPathMiddleware'); 9 | const paths = require('./paths'); 10 | const getHttpsConfig = require('./getHttpsConfig'); 11 | 12 | const host = process.env.HOST || '0.0.0.0'; 13 | const sockHost = process.env.WDS_SOCKET_HOST; 14 | const sockPath = process.env.WDS_SOCKET_PATH; // default: '/sockjs-node' 15 | const sockPort = process.env.WDS_SOCKET_PORT; 16 | 17 | module.exports = function (proxy, allowedHost) { 18 | return { 19 | // WebpackDevServer 2.4.3 introduced a security fix that prevents remote 20 | // websites from potentially accessing local content through DNS rebinding: 21 | // https://github.com/webpack/webpack-dev-server/issues/887 22 | // https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a 23 | // However, it made several existing use cases such as development in cloud 24 | // environment or subdomains in development significantly more complicated: 25 | // https://github.com/facebook/create-react-app/issues/2271 26 | // https://github.com/facebook/create-react-app/issues/2233 27 | // While we're investigating better solutions, for now we will take a 28 | // compromise. Since our WDS configuration only serves files in the `public` 29 | // folder we won't consider accessing them a vulnerability. However, if you 30 | // use the `proxy` feature, it gets more dangerous because it can expose 31 | // remote code execution vulnerabilities in backends like Django and Rails. 32 | // So we will disable the host check normally, but enable it if you have 33 | // specified the `proxy` setting. Finally, we let you override it if you 34 | // really know what you're doing with a special environment variable. 35 | disableHostCheck: 36 | !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true', 37 | // Enable gzip compression of generated files. 38 | compress: true, 39 | // Silence WebpackDevServer's own logs since they're generally not useful. 40 | // It will still show compile warnings and errors with this setting. 41 | clientLogLevel: 'none', 42 | // By default WebpackDevServer serves physical files from current directory 43 | // in addition to all the virtual build products that it serves from memory. 44 | // This is confusing because those files won’t automatically be available in 45 | // production build folder unless we copy them. However, copying the whole 46 | // project directory is dangerous because we may expose sensitive files. 47 | // Instead, we establish a convention that only files in `public` directory 48 | // get served. Our build script will copy `public` into the `build` folder. 49 | // In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%: 50 | // 51 | // In JavaScript code, you can access it with `process.env.PUBLIC_URL`. 52 | // Note that we only recommend to use `public` folder as an escape hatch 53 | // for files like `favicon.ico`, `manifest.json`, and libraries that are 54 | // for some reason broken when imported through webpack. If you just want to 55 | // use an image, put it in `src` and `import` it from JavaScript instead. 56 | contentBase: paths.appPublic, 57 | contentBasePublicPath: paths.publicUrlOrPath, 58 | // By default files from `contentBase` will not trigger a page reload. 59 | watchContentBase: true, 60 | // Enable hot reloading server. It will provide WDS_SOCKET_PATH endpoint 61 | // for the WebpackDevServer client so it can learn when the files were 62 | // updated. The WebpackDevServer client is included as an entry point 63 | // in the webpack development configuration. Note that only changes 64 | // to CSS are currently hot reloaded. JS changes will refresh the browser. 65 | hot: true, 66 | // Use 'ws' instead of 'sockjs-node' on server since we're using native 67 | // websockets in `webpackHotDevClient`. 68 | transportMode: 'ws', 69 | // Prevent a WS client from getting injected as we're already including 70 | // `webpackHotDevClient`. 71 | injectClient: false, 72 | // Enable custom sockjs pathname for websocket connection to hot reloading server. 73 | // Enable custom sockjs hostname, pathname and port for websocket connection 74 | // to hot reloading server. 75 | sockHost, 76 | sockPath, 77 | sockPort, 78 | // It is important to tell WebpackDevServer to use the same "publicPath" path as 79 | // we specified in the webpack config. When homepage is '.', default to serving 80 | // from the root. 81 | // remove last slash so user can land on `/test` instead of `/test/` 82 | publicPath: paths.publicUrlOrPath.slice(0, -1), 83 | // WebpackDevServer is noisy by default so we emit custom message instead 84 | // by listening to the compiler events with `compiler.hooks[...].tap` calls above. 85 | quiet: true, 86 | // Reportedly, this avoids CPU overload on some systems. 87 | // https://github.com/facebook/create-react-app/issues/293 88 | // src/node_modules is not ignored to support absolute imports 89 | // https://github.com/facebook/create-react-app/issues/1065 90 | watchOptions: { 91 | ignored: ignoredFiles(paths.appSrc), 92 | }, 93 | https: getHttpsConfig(), 94 | host, 95 | overlay: false, 96 | historyApiFallback: { 97 | // Paths with dots should still use the history fallback. 98 | // See https://github.com/facebook/create-react-app/issues/387. 99 | disableDotRule: true, 100 | index: paths.publicUrlOrPath, 101 | }, 102 | public: allowedHost, 103 | // `proxy` is run between `before` and `after` `webpack-dev-server` hooks 104 | proxy, 105 | before(app, server) { 106 | // Keep `evalSourceMapMiddleware` and `errorOverlayMiddleware` 107 | // middlewares before `redirectServedPath` otherwise will not have any effect 108 | // This lets us fetch source contents from webpack for the error overlay 109 | app.use(evalSourceMapMiddleware(server)); 110 | // This lets us open files from the runtime error overlay. 111 | app.use(errorOverlayMiddleware()); 112 | 113 | if (fs.existsSync(paths.proxySetup)) { 114 | // This registers user provided middleware for proxy reasons 115 | require(paths.proxySetup)(app); 116 | } 117 | }, 118 | after(app) { 119 | // Redirect to `PUBLIC_URL` or `homepage` from `package.json` if url not match 120 | app.use(redirectServedPath(paths.publicUrlOrPath)); 121 | 122 | // This service worker file is effectively a 'no-op' that will reset any 123 | // previous service worker registered for the same host:port combination. 124 | // We do this in development to avoid hitting the production cache if 125 | // it used the same host and port. 126 | // https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432 127 | app.use(noopServiceWorkerMiddleware(paths.publicUrlOrPath)); 128 | }, 129 | }; 130 | }; 131 | -------------------------------------------------------------------------------- /packages/fiddle/scripts/build.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Do this as the first thing so that any code reading it knows the right env. 4 | process.env.BABEL_ENV = 'production'; 5 | process.env.NODE_ENV = 'production'; 6 | 7 | // Makes the script crash on unhandled rejections instead of silently 8 | // ignoring them. In the future, promise rejections that are not handled will 9 | // terminate the Node.js process with a non-zero exit code. 10 | process.on('unhandledRejection', err => { 11 | throw err; 12 | }); 13 | 14 | // Ensure environment variables are read. 15 | require('../config/env'); 16 | 17 | 18 | const path = require('path'); 19 | const chalk = require('react-dev-utils/chalk'); 20 | const fs = require('fs-extra'); 21 | const bfj = require('bfj'); 22 | const webpack = require('webpack'); 23 | const configFactory = require('../config/webpack.config'); 24 | const paths = require('../config/paths'); 25 | const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); 26 | const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); 27 | const printHostingInstructions = require('react-dev-utils/printHostingInstructions'); 28 | const FileSizeReporter = require('react-dev-utils/FileSizeReporter'); 29 | const printBuildError = require('react-dev-utils/printBuildError'); 30 | 31 | const measureFileSizesBeforeBuild = 32 | FileSizeReporter.measureFileSizesBeforeBuild; 33 | const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; 34 | const useYarn = fs.existsSync(paths.yarnLockFile); 35 | 36 | // These sizes are pretty large. We'll warn for bundles exceeding them. 37 | const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024; 38 | const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024; 39 | 40 | const isInteractive = process.stdout.isTTY; 41 | 42 | // Warn and crash if required files are missing 43 | if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { 44 | process.exit(1); 45 | } 46 | 47 | const argv = process.argv.slice(2); 48 | const writeStatsJson = argv.indexOf('--stats') !== -1; 49 | 50 | // Generate configuration 51 | const config = configFactory('production'); 52 | 53 | // We require that you explicitly set browsers and do not fall back to 54 | // browserslist defaults. 55 | const { checkBrowsers } = require('react-dev-utils/browsersHelper'); 56 | checkBrowsers(paths.appPath, isInteractive) 57 | .then(() => { 58 | // First, read the current file sizes in build directory. 59 | // This lets us display how much they changed later. 60 | return measureFileSizesBeforeBuild(paths.appBuild); 61 | }) 62 | .then(previousFileSizes => { 63 | // Remove all content but keep the directory so that 64 | // if you're in it, you don't end up in Trash 65 | fs.emptyDirSync(paths.appBuild); 66 | // Merge with the public folder 67 | copyPublicFolder(); 68 | // Start the webpack build 69 | return build(previousFileSizes); 70 | }) 71 | .then( 72 | ({ stats, previousFileSizes, warnings }) => { 73 | if (warnings.length) { 74 | console.log(chalk.yellow('Compiled with warnings.\n')); 75 | console.log(warnings.join('\n\n')); 76 | console.log( 77 | '\nSearch for the ' + 78 | chalk.underline(chalk.yellow('keywords')) + 79 | ' to learn more about each warning.' 80 | ); 81 | console.log( 82 | 'To ignore, add ' + 83 | chalk.cyan('// eslint-disable-next-line') + 84 | ' to the line before.\n' 85 | ); 86 | } else { 87 | console.log(chalk.green('Compiled successfully.\n')); 88 | } 89 | 90 | console.log('File sizes after gzip:\n'); 91 | printFileSizesAfterBuild( 92 | stats, 93 | previousFileSizes, 94 | paths.appBuild, 95 | WARN_AFTER_BUNDLE_GZIP_SIZE, 96 | WARN_AFTER_CHUNK_GZIP_SIZE 97 | ); 98 | console.log(); 99 | 100 | const appPackage = require(paths.appPackageJson); 101 | const publicUrl = paths.publicUrlOrPath; 102 | const publicPath = config.output.publicPath; 103 | const buildFolder = path.relative(process.cwd(), paths.appBuild); 104 | printHostingInstructions( 105 | appPackage, 106 | publicUrl, 107 | publicPath, 108 | buildFolder, 109 | useYarn 110 | ); 111 | }, 112 | err => { 113 | const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true'; 114 | if (tscCompileOnError) { 115 | console.log( 116 | chalk.yellow( 117 | 'Compiled with the following type errors (you may want to check these before deploying your app):\n' 118 | ) 119 | ); 120 | printBuildError(err); 121 | } else { 122 | console.log(chalk.red('Failed to compile.\n')); 123 | printBuildError(err); 124 | process.exit(1); 125 | } 126 | } 127 | ) 128 | .catch(err => { 129 | if (err && err.message) { 130 | console.log(err.message); 131 | } 132 | process.exit(1); 133 | }); 134 | 135 | // Create the production build and print the deployment instructions. 136 | function build(previousFileSizes) { 137 | console.log('Creating an optimized production build...'); 138 | 139 | const compiler = webpack(config); 140 | return new Promise((resolve, reject) => { 141 | compiler.run((err, stats) => { 142 | let messages; 143 | if (err) { 144 | if (!err.message) { 145 | return reject(err); 146 | } 147 | 148 | let errMessage = err.message; 149 | 150 | // Add additional information for postcss errors 151 | if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) { 152 | errMessage += 153 | '\nCompileError: Begins at CSS selector ' + 154 | err['postcssNode'].selector; 155 | } 156 | 157 | messages = formatWebpackMessages({ 158 | errors: [errMessage], 159 | warnings: [], 160 | }); 161 | } else { 162 | messages = formatWebpackMessages( 163 | stats.toJson({ all: false, warnings: true, errors: true }) 164 | ); 165 | } 166 | if (messages.errors.length) { 167 | // Only keep the first error. Others are often indicative 168 | // of the same problem, but confuse the reader with noise. 169 | if (messages.errors.length > 1) { 170 | messages.errors.length = 1; 171 | } 172 | return reject(new Error(messages.errors.join('\n\n'))); 173 | } 174 | if ( 175 | process.env.CI && 176 | (typeof process.env.CI !== 'string' || 177 | process.env.CI.toLowerCase() !== 'false') && 178 | messages.warnings.length 179 | ) { 180 | console.log( 181 | chalk.yellow( 182 | '\nTreating warnings as errors because process.env.CI = true.\n' + 183 | 'Most CI servers set it automatically.\n' 184 | ) 185 | ); 186 | return reject(new Error(messages.warnings.join('\n\n'))); 187 | } 188 | 189 | const resolveArgs = { 190 | stats, 191 | previousFileSizes, 192 | warnings: messages.warnings, 193 | }; 194 | 195 | if (writeStatsJson) { 196 | return bfj 197 | .write(paths.appBuild + '/bundle-stats.json', stats.toJson()) 198 | .then(() => resolve(resolveArgs)) 199 | .catch(error => reject(new Error(error))); 200 | } 201 | 202 | return resolve(resolveArgs); 203 | }); 204 | }); 205 | } 206 | 207 | function copyPublicFolder() { 208 | fs.copySync(paths.appPublic, paths.appBuild, { 209 | dereference: true, 210 | filter: file => file !== paths.appHtml, 211 | }); 212 | } 213 | -------------------------------------------------------------------------------- /packages/fiddle/src/components/Fiddle.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | createMuiTheme, 3 | MenuItem, 4 | Select, 5 | Tab, 6 | Tabs, 7 | ThemeProvider, 8 | Typography, 9 | } from '@material-ui/core'; 10 | import { Alert } from '@material-ui/lab'; 11 | import { useLocalObservable, useObserver } from 'mobx-react-lite'; 12 | import * as monaco from 'monaco-editor'; 13 | // eslint-disable-next-line import/no-webpack-loader-syntax 14 | import React, { useState } from 'react'; 15 | import { toSwift, toGo, toKotlin } from '@builder.io/ts-lite'; 16 | import MonacoEditor from 'react-monaco-editor'; 17 | import githubLogo from '../assets/GitHub-Mark-Light-64px.png'; 18 | import logo from '../assets/ts-lite-logo-white.png'; 19 | import { breakpoints } from '../constants/breakpoints'; 20 | import { colors } from '../constants/colors'; 21 | import { device } from '../constants/device'; 22 | import { defaultCode, templates } from '../constants/templates'; 23 | import { theme } from '../constants/theme'; 24 | import { deleteQueryParam } from '../functions/delete-query-param'; 25 | import { getQueryParam } from '../functions/get-query-param'; 26 | import { localStorageGet } from '../functions/local-storage-get'; 27 | import { localStorageSet } from '../functions/local-storage-set'; 28 | import { setQueryParam } from '../functions/set-query-param'; 29 | import { useEventListener } from '../hooks/use-event-listener'; 30 | import { useReaction } from '../hooks/use-reaction'; 31 | import { Show } from './Show'; 32 | import { TextLink } from './TextLink'; 33 | 34 | const debug = getQueryParam('debug') === 'true'; 35 | 36 | const AlphaPreviewMessage = () => ( 37 | 45 | 52 | This is an early alpha preview, please{' '} 53 | 58 | report bugs and share feedback 59 | 60 | 61 | 62 | ); 63 | 64 | const smallBreakpoint = breakpoints.mediaQueries.small; 65 | const responsiveColHeight = 'calc(50vh - 30px)'; 66 | 67 | monaco.languages.typescript.typescriptDefaults.setCompilerOptions({ 68 | target: monaco.languages.typescript.ScriptTarget.Latest, 69 | allowNonTsExtensions: true, 70 | moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs, 71 | module: monaco.languages.typescript.ModuleKind.CommonJS, 72 | noEmit: true, 73 | esModuleInterop: true, 74 | jsx: monaco.languages.typescript.JsxEmit.React, 75 | reactNamespace: 'React', 76 | allowJs: true, 77 | typeRoots: ['node_modules/@types'], 78 | }); 79 | 80 | monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({ 81 | noSemanticValidation: false, 82 | noSyntaxValidation: false, 83 | }); 84 | 85 | // TODO: add this 86 | monaco.languages.typescript.typescriptDefaults.addExtraLib( 87 | ` 88 | declare type Int = number; 89 | `, 90 | 'ts:filename/index.d.ts' 91 | ); 92 | 93 | // TODO: Build this Fiddle app with TS Lite :) 94 | export default function Fiddle() { 95 | const [staticState] = useState(() => ({ 96 | ignoreNextBuilderUpdate: false, 97 | })); 98 | const state = useLocalObservable(() => ({ 99 | code: getQueryParam('code') || defaultCode, 100 | output: '', 101 | outputTab: getQueryParam('outputTab') || 'vue', 102 | pendingBuilderChange: null as any, 103 | inputTab: getQueryParam('inputTab') || 'builder', 104 | builderData: {} as any, 105 | isDraggingOutputsCodeBar: false, 106 | isDraggingJSXCodeBar: false, 107 | jsxCodeTabWidth: Number(localStorageGet('jsxCodeTabWidth')) || 45, 108 | outputsTabHeight: Number(localStorageGet('outputsTabHeight')) || 100, 109 | updateOutput() { 110 | try { 111 | state.pendingBuilderChange = null; 112 | staticState.ignoreNextBuilderUpdate = true; 113 | // TODO 114 | state.output = 115 | state.outputTab === 'swift' 116 | ? toSwift(state.code) 117 | : state.outputTab === 'go' 118 | ? toGo(state.code) 119 | : toKotlin(state.code); 120 | } catch (err) { 121 | if (debug) { 122 | throw err; 123 | } else { 124 | console.warn(err); 125 | } 126 | } 127 | }, 128 | })); 129 | 130 | useEventListener(document.body, 'mousemove', (e) => { 131 | if (state.isDraggingJSXCodeBar) { 132 | const windowWidth = window.innerWidth; 133 | const pointerRelativeXpos = e.clientX; 134 | const newWidth = Math.max((pointerRelativeXpos / windowWidth) * 100, 5); 135 | state.jsxCodeTabWidth = Math.min(newWidth, 95); 136 | } else if (state.isDraggingOutputsCodeBar) { 137 | const bannerHeight = 0; 138 | const windowHeight = window.innerHeight; 139 | const pointerRelativeYPos = e.clientY; 140 | const newHeight = Math.max( 141 | ((pointerRelativeYPos + bannerHeight) / windowHeight) * 100, 142 | 5, 143 | ); 144 | state.outputsTabHeight = Math.min(newHeight, 95); 145 | } 146 | }); 147 | 148 | useEventListener(document.body, 'mouseup', (e) => { 149 | state.isDraggingJSXCodeBar = false; 150 | state.isDraggingOutputsCodeBar = false; 151 | }); 152 | 153 | useReaction( 154 | () => state.jsxCodeTabWidth, 155 | (width) => localStorageSet('jsxCodeTabWidth', width), 156 | { fireImmediately: false, delay: 1000 }, 157 | ); 158 | 159 | useReaction( 160 | () => state.outputsTabHeight, 161 | (width) => localStorageSet('outputsTabHeight', width), 162 | { fireImmediately: false, delay: 1000 }, 163 | ); 164 | 165 | useReaction( 166 | () => state.code, 167 | (code) => setQueryParam('code', code), 168 | { fireImmediately: false }, 169 | ); 170 | useReaction( 171 | () => state.outputTab, 172 | (tab) => { 173 | if (state.code) { 174 | setQueryParam('outputTab', tab); 175 | } else { 176 | deleteQueryParam('outputTab'); 177 | } 178 | state.updateOutput(); 179 | }, 180 | ); 181 | 182 | useReaction( 183 | () => state.code, 184 | (code) => { 185 | state.updateOutput(); 186 | }, 187 | { delay: 1000 }, 188 | ); 189 | 190 | return useObserver(() => { 191 | const outputMonacoEditorSize = device.small 192 | ? `calc(${state.outputsTabHeight}vh - 50px)` 193 | : `calc(${state.outputsTabHeight}vh - 100px)`; 194 | const inputMonacoEditorSize = `calc(${ 195 | 100 - state.outputsTabHeight 196 | }vh - 100px)`; 197 | const lightColorInvert = {}; // theme.darkMode ? null : { filter: 'invert(1) ' }; 198 | const monacoTheme = theme.darkMode ? 'vs-dark' : 'vs'; 199 | const barStyle: any = { 200 | overflow: 'auto', 201 | whiteSpace: 'nowrap', 202 | ...(theme.darkMode ? null : { backgroundColor: 'white' }), 203 | }; 204 | 205 | return ( 206 |
216 |
221 |
230 | 238 | TS Lite Logo 249 | 250 |
256 | 257 |
258 | 259 | 269 | Source 270 | Github Mark 276 | 277 |
278 |
286 | 287 |
288 |
289 |
296 |
310 |
321 | 325 | TS Lite code: 326 | 327 | 361 |
362 |
363 | (state.code = val)} 377 | /> 378 |
379 |
380 |
{ 395 | event.preventDefault(); 396 | state.isDraggingJSXCodeBar = true; 397 | }} 398 | >
399 |
412 |
426 | 435 | Outputs: 436 | 437 | (state.outputTab = value)} 449 | indicatorColor="primary" 450 | textColor="primary" 451 | > 452 | 453 | 454 | 455 | {/* */} 456 | 457 |
458 |
461 |
462 |
463 | 482 |
483 |
484 |
485 | 486 | 487 |
{ 502 | event.preventDefault(); 503 | state.isDraggingOutputsCodeBar = true; 504 | }} 505 | >
506 |
526 | {/* TODO: some other output preview */} 527 | {/* TODO: Builder drag/drop (Buid.) editor */} 528 |
529 |
530 |
531 |
532 |
533 | ); 534 | }); 535 | } 536 | -------------------------------------------------------------------------------- /packages/fiddle/config/webpack.config.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const webpack = require('webpack'); 6 | const resolve = require('resolve'); 7 | const PnpWebpackPlugin = require('pnp-webpack-plugin'); 8 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 9 | const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); 10 | const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin'); 11 | const TerserPlugin = require('terser-webpack-plugin'); 12 | const MiniCssExtractPlugin = require('mini-css-extract-plugin'); 13 | const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); 14 | const safePostCssParser = require('postcss-safe-parser'); 15 | const ManifestPlugin = require('webpack-manifest-plugin'); 16 | const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); 17 | const WorkboxWebpackPlugin = require('workbox-webpack-plugin'); 18 | const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); 19 | const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); 20 | const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent'); 21 | const ESLintPlugin = require('eslint-webpack-plugin'); 22 | const paths = require('./paths'); 23 | const modules = require('./modules'); 24 | const getClientEnvironment = require('./env'); 25 | const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin'); 26 | const ForkTsCheckerWebpackPlugin = require('react-dev-utils/ForkTsCheckerWebpackPlugin'); 27 | const typescriptFormatter = require('react-dev-utils/typescriptFormatter'); 28 | const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin'); 29 | const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin'); 30 | 31 | const postcssNormalize = require('postcss-normalize'); 32 | 33 | const appPackageJson = require(paths.appPackageJson); 34 | 35 | // Source maps are resource heavy and can cause out of memory issue for large source files. 36 | const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'; 37 | 38 | const webpackDevClientEntry = require.resolve( 39 | 'react-dev-utils/webpackHotDevClient', 40 | ); 41 | const reactRefreshOverlayEntry = require.resolve( 42 | 'react-dev-utils/refreshOverlayInterop', 43 | ); 44 | 45 | // Some apps do not need the benefits of saving a web request, so not inlining the chunk 46 | // makes for a smoother build process. 47 | const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false'; 48 | 49 | const imageInlineSizeLimit = parseInt( 50 | process.env.IMAGE_INLINE_SIZE_LIMIT || '10000', 51 | ); 52 | 53 | // Check if TypeScript is setup 54 | const useTypeScript = fs.existsSync(paths.appTsConfig); 55 | 56 | // Get the path to the uncompiled service worker (if it exists). 57 | const swSrc = paths.swSrc; 58 | 59 | // style files regexes 60 | const cssRegex = /\.css$/; 61 | const cssModuleRegex = /\.module\.css$/; 62 | const sassRegex = /\.(scss|sass)$/; 63 | const sassModuleRegex = /\.module\.(scss|sass)$/; 64 | 65 | const hasJsxRuntime = (() => { 66 | if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') { 67 | return false; 68 | } 69 | 70 | try { 71 | require.resolve('react/jsx-runtime'); 72 | return true; 73 | } catch (e) { 74 | return false; 75 | } 76 | })(); 77 | 78 | // This is the production and development configuration. 79 | // It is focused on developer experience, fast rebuilds, and a minimal bundle. 80 | module.exports = function (webpackEnv) { 81 | const isEnvDevelopment = webpackEnv === 'development'; 82 | const isEnvProduction = webpackEnv === 'production'; 83 | 84 | // Variable used for enabling profiling in Production 85 | // passed into alias object. Uses a flag if passed into the build command 86 | const isEnvProductionProfile = 87 | isEnvProduction && process.argv.includes('--profile'); 88 | 89 | // We will provide `paths.publicUrlOrPath` to our app 90 | // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. 91 | // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz. 92 | // Get environment variables to inject into our app. 93 | const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1)); 94 | 95 | const shouldUseReactRefresh = env.raw.FAST_REFRESH; 96 | 97 | // common function to get style loaders 98 | const getStyleLoaders = (cssOptions, preProcessor) => { 99 | const loaders = [ 100 | isEnvDevelopment && require.resolve('style-loader'), 101 | isEnvProduction && { 102 | loader: MiniCssExtractPlugin.loader, 103 | // css is located in `static/css`, use '../../' to locate index.html folder 104 | // in production `paths.publicUrlOrPath` can be a relative path 105 | options: paths.publicUrlOrPath.startsWith('.') 106 | ? { publicPath: '../../' } 107 | : {}, 108 | }, 109 | { 110 | loader: require.resolve('css-loader'), 111 | options: cssOptions, 112 | }, 113 | { 114 | // Options for PostCSS as we reference these options twice 115 | // Adds vendor prefixing based on your specified browser support in 116 | // package.json 117 | loader: require.resolve('postcss-loader'), 118 | options: { 119 | // Necessary for external CSS imports to work 120 | // https://github.com/facebook/create-react-app/issues/2677 121 | ident: 'postcss', 122 | plugins: () => [ 123 | require('postcss-flexbugs-fixes'), 124 | require('postcss-preset-env')({ 125 | autoprefixer: { 126 | flexbox: 'no-2009', 127 | }, 128 | stage: 3, 129 | }), 130 | // Adds PostCSS Normalize as the reset css with default options, 131 | // so that it honors browserslist config in package.json 132 | // which in turn let's users customize the target behavior as per their needs. 133 | postcssNormalize(), 134 | ], 135 | sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, 136 | }, 137 | }, 138 | ].filter(Boolean); 139 | if (preProcessor) { 140 | loaders.push( 141 | { 142 | loader: require.resolve('resolve-url-loader'), 143 | options: { 144 | sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, 145 | root: paths.appSrc, 146 | }, 147 | }, 148 | { 149 | loader: require.resolve(preProcessor), 150 | options: { 151 | sourceMap: true, 152 | }, 153 | }, 154 | ); 155 | } 156 | return loaders; 157 | }; 158 | 159 | return { 160 | mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development', 161 | // Stop compilation early in production 162 | bail: isEnvProduction, 163 | devtool: isEnvProduction 164 | ? shouldUseSourceMap 165 | ? 'source-map' 166 | : false 167 | : isEnvDevelopment && 'cheap-module-source-map', 168 | // These are the "entry points" to our application. 169 | // This means they will be the "root" imports that are included in JS bundle. 170 | entry: 171 | isEnvDevelopment && !shouldUseReactRefresh 172 | ? [ 173 | // Include an alternative client for WebpackDevServer. A client's job is to 174 | // connect to WebpackDevServer by a socket and get notified about changes. 175 | // When you save a file, the client will either apply hot updates (in case 176 | // of CSS changes), or refresh the page (in case of JS changes). When you 177 | // make a syntax error, this client will display a syntax error overlay. 178 | // Note: instead of the default WebpackDevServer client, we use a custom one 179 | // to bring better experience for Create React App users. You can replace 180 | // the line below with these two lines if you prefer the stock client: 181 | // 182 | // require.resolve('webpack-dev-server/client') + '?/', 183 | // require.resolve('webpack/hot/dev-server'), 184 | // 185 | // When using the experimental react-refresh integration, 186 | // the webpack plugin takes care of injecting the dev client for us. 187 | webpackDevClientEntry, 188 | // Finally, this is your app's code: 189 | paths.appIndexJs, 190 | // We include the app code last so that if there is a runtime error during 191 | // initialization, it doesn't blow up the WebpackDevServer client, and 192 | // changing JS code would still trigger a refresh. 193 | ] 194 | : paths.appIndexJs, 195 | output: { 196 | // The build folder. 197 | path: isEnvProduction ? paths.appBuild : undefined, 198 | // Add /* filename */ comments to generated require()s in the output. 199 | pathinfo: isEnvDevelopment, 200 | // There will be one main bundle, and one file per asynchronous chunk. 201 | // In development, it does not produce real files. 202 | filename: isEnvProduction 203 | ? 'static/js/[name].[contenthash:8].js' 204 | : isEnvDevelopment && 'static/js/bundle.js', 205 | // TODO: remove this when upgrading to webpack 5 206 | futureEmitAssets: true, 207 | // There are also additional JS chunk files if you use code splitting. 208 | chunkFilename: isEnvProduction 209 | ? 'static/js/[name].[contenthash:8].chunk.js' 210 | : isEnvDevelopment && 'static/js/[name].chunk.js', 211 | // webpack uses `publicPath` to determine where the app is being served from. 212 | // It requires a trailing slash, or the file assets will get an incorrect path. 213 | // We inferred the "public path" (such as / or /my-project) from homepage. 214 | publicPath: paths.publicUrlOrPath, 215 | // Point sourcemap entries to original disk location (format as URL on Windows) 216 | devtoolModuleFilenameTemplate: isEnvProduction 217 | ? (info) => 218 | path 219 | .relative(paths.appSrc, info.absoluteResourcePath) 220 | .replace(/\\/g, '/') 221 | : isEnvDevelopment && 222 | ((info) => 223 | path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')), 224 | // Prevents conflicts when multiple webpack runtimes (from different apps) 225 | // are used on the same page. 226 | jsonpFunction: `webpackJsonp${appPackageJson.name}`, 227 | // this defaults to 'window', but by setting it to 'this' then 228 | // module chunks which are built will work in web workers as well. 229 | globalObject: 'this', 230 | }, 231 | optimization: { 232 | minimize: false, // isEnvProduction, // <- currently this is blowing out memory 233 | minimizer: [ 234 | // This is only used in production mode 235 | new TerserPlugin({ 236 | terserOptions: { 237 | parse: { 238 | // We want terser to parse ecma 8 code. However, we don't want it 239 | // to apply any minification steps that turns valid ecma 5 code 240 | // into invalid ecma 5 code. This is why the 'compress' and 'output' 241 | // sections only apply transformations that are ecma 5 safe 242 | // https://github.com/facebook/create-react-app/pull/4234 243 | ecma: 8, 244 | }, 245 | compress: { 246 | ecma: 5, 247 | warnings: false, 248 | // Disabled because of an issue with Uglify breaking seemingly valid code: 249 | // https://github.com/facebook/create-react-app/issues/2376 250 | // Pending further investigation: 251 | // https://github.com/mishoo/UglifyJS2/issues/2011 252 | comparisons: false, 253 | // Disabled because of an issue with Terser breaking valid code: 254 | // https://github.com/facebook/create-react-app/issues/5250 255 | // Pending further investigation: 256 | // https://github.com/terser-js/terser/issues/120 257 | inline: 2, 258 | }, 259 | mangle: { 260 | safari10: true, 261 | }, 262 | // Added for profiling in devtools 263 | keep_classnames: isEnvProductionProfile, 264 | keep_fnames: isEnvProductionProfile, 265 | output: { 266 | ecma: 5, 267 | comments: false, 268 | // Turned on because emoji and regex is not minified properly using default 269 | // https://github.com/facebook/create-react-app/issues/2488 270 | ascii_only: true, 271 | }, 272 | }, 273 | parallel: 2, 274 | sourceMap: shouldUseSourceMap, 275 | }), 276 | // This is only used in production mode 277 | new OptimizeCSSAssetsPlugin({ 278 | cssProcessorOptions: { 279 | parser: safePostCssParser, 280 | map: shouldUseSourceMap 281 | ? { 282 | // `inline: false` forces the sourcemap to be output into a 283 | // separate file 284 | inline: false, 285 | // `annotation: true` appends the sourceMappingURL to the end of 286 | // the css file, helping the browser find the sourcemap 287 | annotation: true, 288 | } 289 | : false, 290 | }, 291 | cssProcessorPluginOptions: { 292 | preset: ['default', { minifyFontValues: { removeQuotes: false } }], 293 | }, 294 | }), 295 | ], 296 | // Automatically split vendor and commons 297 | // https://twitter.com/wSokra/status/969633336732905474 298 | // https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366 299 | splitChunks: { 300 | chunks: 'all', 301 | name: false, 302 | }, 303 | // Keep the runtime chunk separated to enable long term caching 304 | // https://twitter.com/wSokra/status/969679223278505985 305 | // https://github.com/facebook/create-react-app/issues/5358 306 | runtimeChunk: { 307 | name: (entrypoint) => `runtime-${entrypoint.name}`, 308 | }, 309 | }, 310 | resolve: { 311 | // This allows you to set a fallback for where webpack should look for modules. 312 | // We placed these paths second because we want `node_modules` to "win" 313 | // if there are any conflicts. This matches Node resolution mechanism. 314 | // https://github.com/facebook/create-react-app/issues/253 315 | modules: ['node_modules', paths.appNodeModules].concat( 316 | modules.additionalModulePaths || [], 317 | ), 318 | // These are the reasonable defaults supported by the Node ecosystem. 319 | // We also include JSX as a common component filename extension to support 320 | // some tools, although we do not recommend using it, see: 321 | // https://github.com/facebook/create-react-app/issues/290 322 | // `web` extension prefixes have been added for better support 323 | // for React Native Web. 324 | extensions: paths.moduleFileExtensions 325 | .map((ext) => `.${ext}`) 326 | .filter((ext) => useTypeScript || !ext.includes('ts')), 327 | alias: { 328 | // Support React Native Web 329 | // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 330 | 'react-native': 'react-native-web', 331 | // Allows for better profiling with ReactDevTools 332 | ...(isEnvProductionProfile && { 333 | 'react-dom$': 'react-dom/profiling', 334 | 'scheduler/tracing': 'scheduler/tracing-profiling', 335 | }), 336 | ...(modules.webpackAliases || {}), 337 | }, 338 | plugins: [ 339 | // Adds support for installing with Plug'n'Play, leading to faster installs and adding 340 | // guards against forgotten dependencies and such. 341 | PnpWebpackPlugin, 342 | // Prevents users from importing files from outside of src/ (or node_modules/). 343 | // This often causes confusion because we only process files within src/ with babel. 344 | // To fix this, we prevent you from importing files out of src/ -- if you'd like to, 345 | // please link the files into your node_modules/ and let module-resolution kick in. 346 | // Make sure your source files are compiled, as they will not be processed in any way. 347 | new ModuleScopePlugin(paths.appSrc, [ 348 | paths.appPackageJson, 349 | reactRefreshOverlayEntry, 350 | ]), 351 | ], 352 | }, 353 | resolveLoader: { 354 | plugins: [ 355 | // Also related to Plug'n'Play, but this time it tells webpack to load its loaders 356 | // from the current package. 357 | PnpWebpackPlugin.moduleLoader(module), 358 | ], 359 | }, 360 | module: { 361 | strictExportPresence: true, 362 | rules: [ 363 | // Disable require.ensure as it's not a standard language feature. 364 | { parser: { requireEnsure: false } }, 365 | { 366 | // "oneOf" will traverse all following loaders until one will 367 | // match the requirements. When no loader matches it will fall 368 | // back to the "file" loader at the end of the loader list. 369 | oneOf: [ 370 | // TODO: Merge this config once `image/avif` is in the mime-db 371 | // https://github.com/jshttp/mime-db 372 | { 373 | test: [/\.avif$/], 374 | loader: require.resolve('url-loader'), 375 | options: { 376 | limit: imageInlineSizeLimit, 377 | mimetype: 'image/avif', 378 | name: 'static/media/[name].[hash:8].[ext]', 379 | }, 380 | }, 381 | // "url" loader works like "file" loader except that it embeds assets 382 | // smaller than specified limit in bytes as data URLs to avoid requests. 383 | // A missing `test` is equivalent to a match. 384 | { 385 | test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], 386 | loader: require.resolve('url-loader'), 387 | options: { 388 | limit: imageInlineSizeLimit, 389 | name: 'static/media/[name].[hash:8].[ext]', 390 | }, 391 | }, 392 | // Process application JS with Babel. 393 | // The preset includes JSX, Flow, TypeScript, and some ESnext features. 394 | { 395 | test: /\.(js|mjs|jsx|ts|tsx)$/, 396 | include: paths.appSrc, 397 | loader: require.resolve('babel-loader'), 398 | options: { 399 | customize: require.resolve( 400 | 'babel-preset-react-app/webpack-overrides', 401 | ), 402 | 403 | presets: ['@emotion/babel-preset-css-prop'], 404 | 405 | plugins: [ 406 | [ 407 | require.resolve('babel-plugin-named-asset-import'), 408 | { 409 | loaderMap: { 410 | svg: { 411 | ReactComponent: 412 | '@svgr/webpack?-svgo,+titleProp,+ref![path]', 413 | }, 414 | }, 415 | }, 416 | ], 417 | isEnvDevelopment && 418 | shouldUseReactRefresh && 419 | require.resolve('react-refresh/babel'), 420 | ].filter(Boolean), 421 | // This is a feature of `babel-loader` for webpack (not Babel itself). 422 | // It enables caching results in ./node_modules/.cache/babel-loader/ 423 | // directory for faster rebuilds. 424 | cacheDirectory: true, 425 | // See #6846 for context on why cacheCompression is disabled 426 | cacheCompression: false, 427 | compact: isEnvProduction, 428 | }, 429 | }, 430 | // Process any JS outside of the app with Babel. 431 | // Unlike the application JS, we only compile the standard ES features. 432 | // { 433 | // test: /\.(js|mjs)$/, 434 | // exclude: /@babel(?:\/|\\{1,2})runtime|html-parser/, 435 | // loader: require.resolve('babel-loader'), 436 | // options: { 437 | // babelrc: false, 438 | // configFile: false, 439 | // compact: false, 440 | // presets: [ 441 | // [ 442 | // require.resolve('babel-preset-react-app/dependencies'), 443 | // { helpers: true }, 444 | // ], 445 | // ], 446 | // cacheDirectory: true, 447 | // // See #6846 for context on why cacheCompression is disabled 448 | // cacheCompression: false, 449 | 450 | // // Babel sourcemaps are needed for debugging into node_modules 451 | // // code. Without the options below, debuggers like VSCode 452 | // // show incorrect code and set breakpoints on the wrong lines. 453 | // sourceMaps: shouldUseSourceMap, 454 | // inputSourceMap: shouldUseSourceMap, 455 | // }, 456 | // }, 457 | // "postcss" loader applies autoprefixer to our CSS. 458 | // "css" loader resolves paths in CSS and adds assets as dependencies. 459 | // "style" loader turns CSS into JS modules that inject