diff --git a/README.md b/README.md index 84e5916..ec07eb6 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,8 @@ # Create React WP Theme -Dec. 15, 2019 +Dec. 24, 2019
-[v3.3.0](https://github.com/facebook/create-react-app/releases/tag/v3.3.0) of [Create React App](https://create-react-app.dev/) was released. It's a major change and it's going take me another week to make the changes to `create-react-wptheme`. - -But don't let that stop you from creating a new theme now, as updating your theme is quite painless (see [Updating Existing Themes](#updating-existing-themes)) below. - -The current release of `create-react-wptheme` is based on [v3.2.0](https://github.com/facebook/create-react-app/releases/tag/v3.2.0) of [Create React App](https://create-react-app.dev/). +Updated to use [Create React App](https://create-react-app.dev/) version [3.3.0](https://github.com/facebook/create-react-app/releases/tag/v3.3.0). --- diff --git a/lerna.json b/lerna.json new file mode 100644 index 0000000..d6707ca --- /dev/null +++ b/lerna.json @@ -0,0 +1,6 @@ +{ + "packages": [ + "packages/*" + ], + "version": "0.0.0" +} diff --git a/package.json b/package.json index b025efc..0b34301 100644 --- a/package.json +++ b/package.json @@ -1,54 +1,7 @@ { - "name": "@devloco/create-react-wptheme", - "version": "3.2.0-wp.6", - "description": "Create React WP themes with no build configuration.", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/devloco/create-react-wptheme.git" - }, - "keywords": [ - "wordpress", - "create-react-app", - "wordpress-theme", - "wordpress-development", - "wordpress-starter-theme", - "wordpress-api", - "reactjs", - "react", - "react-theme", - "wordpress-server", - "react-tutorial", - "react-wordpress-themes", - "php" - ], - "author": "devloco", - "license": "MIT", - "engines": { - "node": ">=8" - }, - "bugs": { - "url": "https://github.com/devloco/create-react-wptheme/issues" - }, - "files": [ - "index.js", - "createReactWpTheme.js" - ], - "homepage": "https://github.com/devloco/create-react-wptheme#readme", - "bin": { - "create-react-wptheme": "./index.js" - }, - "dependencies": { - "chalk": "2.4.2", - "commander": "2.20.0", - "cross-spawn": "6.0.5", - "envinfo": "7.3.1", - "fs-extra": "7.0.1", - "semver": "6.3.0", - "tmp": "0.0.33", - "validate-npm-package-name": "3.0.0" + "name": "root", + "private": true, + "devDependencies": { + "lerna": "^3.19.0" } } diff --git a/packages/cra-template-wptheme-typescript/README.md b/packages/cra-template-wptheme-typescript/README.md new file mode 100644 index 0000000..9851a25 --- /dev/null +++ b/packages/cra-template-wptheme-typescript/README.md @@ -0,0 +1,11 @@ +# cra-template-wptheme-typescript + +This is the official TypeScript template for [Create React WPTheme](https://github.com/devloco/create-react-wptheme). + +To use this template, add `--template typescript` when creating a new wp theme. + +For example: + +```sh +npx create-react-wptheme my-theme --template typescript +``` diff --git a/packages/cra-template-wptheme-typescript/package.json b/packages/cra-template-wptheme-typescript/package.json new file mode 100644 index 0000000..d28ae33 --- /dev/null +++ b/packages/cra-template-wptheme-typescript/package.json @@ -0,0 +1,38 @@ +{ + "name": "cra-template-wptheme-typescript", + "version": "3.3.0-wp.1", + "keywords": [ + "wordpress", + "create-react-app", + "wordpress-theme", + "wordpress-development", + "wordpress-starter-theme", + "wordpress-api", + "reactjs", + "react", + "react-theme", + "wordpress-server", + "react-tutorial", + "react-wordpress-themes", + "php", + "typescript", + "template" + ], + "description": "The TypeScript template for Create React WPTheme.", + "main": "template.json", + "repository": { + "type": "git", + "url": "https://github.com/devloco/create-react-wptheme.git" + }, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "bugs": { + "url": "https://github.com/devloco/create-react-wptheme/issues" + }, + "files": [ + "template", + "template.json" + ] +} diff --git a/packages/cra-template-wptheme-typescript/template.json b/packages/cra-template-wptheme-typescript/template.json new file mode 100644 index 0000000..b2c6f8d --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template.json @@ -0,0 +1,8 @@ +{ + "dependencies": { + "@types/node": "^12.0.0", + "@types/react": "^16.9.0", + "@types/react-dom": "^16.9.0", + "typescript": "~3.7.2" + } +} diff --git a/packages/cra-template-wptheme-typescript/template/README.md b/packages/cra-template-wptheme-typescript/template/README.md new file mode 100644 index 0000000..a31481c --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/README.md @@ -0,0 +1,44 @@ +This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). + +## Available Scripts + +In the project directory, you can run: + +### `npm start` + +Runs the app in the development mode.
+Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.
+You will also see any lint errors in the console. + +### `npm test` + +Launches the test runner in the interactive watch mode.
+See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. + +### `npm run build` + +Builds the app for production to the `build` folder.
+It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.
+Your app is ready to be deployed! + +See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. + +### `npm run eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. + +Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. + +You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. + +## Learn More + +You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). + +To learn React, check out the [React documentation](https://reactjs.org/). diff --git a/packages/cra-template-wptheme-typescript/template/gitignore b/packages/cra-template-wptheme-typescript/template/gitignore new file mode 100644 index 0000000..4d29575 --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/gitignore @@ -0,0 +1,23 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/packages/cra-template-wptheme-typescript/template/public/favicon.ico b/packages/cra-template-wptheme-typescript/template/public/favicon.ico new file mode 100644 index 0000000..c2c86b8 Binary files /dev/null and b/packages/cra-template-wptheme-typescript/template/public/favicon.ico differ diff --git a/packages/cra-template-wptheme-typescript/template/public/index.html b/packages/cra-template-wptheme-typescript/template/public/index.html new file mode 100644 index 0000000..c240d2c --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/public/index.html @@ -0,0 +1,43 @@ + + + + + + + + + + + + + React App + + + +
+ + + diff --git a/packages/cra-template-wptheme-typescript/template/public/index.php b/packages/cra-template-wptheme-typescript/template/public/index.php new file mode 100644 index 0000000..faf7b78 --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/public/index.php @@ -0,0 +1,37 @@ + + +Now, back in your command prompt, rerun the "start" script again... + + diff --git a/packages/cra-template-wptheme-typescript/template/public/logo192.png b/packages/cra-template-wptheme-typescript/template/public/logo192.png new file mode 100644 index 0000000..fa313ab Binary files /dev/null and b/packages/cra-template-wptheme-typescript/template/public/logo192.png differ diff --git a/packages/cra-template-wptheme-typescript/template/public/logo512.png b/packages/cra-template-wptheme-typescript/template/public/logo512.png new file mode 100644 index 0000000..bd5d4b5 Binary files /dev/null and b/packages/cra-template-wptheme-typescript/template/public/logo512.png differ diff --git a/packages/cra-template-wptheme-typescript/template/public/manifest.json b/packages/cra-template-wptheme-typescript/template/public/manifest.json new file mode 100644 index 0000000..080d6c7 --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/public/manifest.json @@ -0,0 +1,25 @@ +{ + "short_name": "React App", + "name": "Create React App Sample", + "icons": [ + { + "src": "favicon.ico", + "sizes": "64x64 32x32 24x24 16x16", + "type": "image/x-icon" + }, + { + "src": "logo192.png", + "type": "image/png", + "sizes": "192x192" + }, + { + "src": "logo512.png", + "type": "image/png", + "sizes": "512x512" + } + ], + "start_url": ".", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/packages/cra-template-wptheme-typescript/template/public/post_installer.php b/packages/cra-template-wptheme-typescript/template/public/post_installer.php new file mode 100644 index 0000000..db3f720 --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/public/post_installer.php @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + React WordPress Theme + + + +
+ + + diff --git a/packages/cra-template-wptheme-typescript/template/public/robots.txt b/packages/cra-template-wptheme-typescript/template/public/robots.txt new file mode 100644 index 0000000..01b0f9a --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/public/robots.txt @@ -0,0 +1,2 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * diff --git a/packages/cra-template-wptheme-typescript/template/public/screenshot.png b/packages/cra-template-wptheme-typescript/template/public/screenshot.png new file mode 100644 index 0000000..ed4277c Binary files /dev/null and b/packages/cra-template-wptheme-typescript/template/public/screenshot.png differ diff --git a/packages/cra-template-wptheme-typescript/template/public/style.css b/packages/cra-template-wptheme-typescript/template/public/style.css new file mode 100644 index 0000000..9034d75 --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/public/style.css @@ -0,0 +1,13 @@ +/* +Theme Name: REPLACE_WITH_THEME_NAME +Author: your-name +Author URI: https://github.com/your-github +Description: Create React WP Themes with no build configuration +Version: 0.1 +License: GNU General Public License v2 or later +License URI: http://www.gnu.org/licenses/gpl-2.0.html +Tags: starter +Text Domain: your-domain + +This theme, like WordPress, is licensed under the GPL. +*/ diff --git a/packages/cra-template-wptheme-typescript/template/src/App.css b/packages/cra-template-wptheme-typescript/template/src/App.css new file mode 100644 index 0000000..afc3885 --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/src/App.css @@ -0,0 +1,22 @@ +.App { + text-align: center; +} + +.App-logo { + height: 40vmin; +} + +.App-header { + background-color: #282c34; + min-height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: calc(10px + 2vmin); + color: white; +} + +.App-link { + color: #09d3ac; +} diff --git a/packages/cra-template-wptheme-typescript/template/src/App.test.tsx b/packages/cra-template-wptheme-typescript/template/src/App.test.tsx new file mode 100644 index 0000000..a754b20 --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/src/App.test.tsx @@ -0,0 +1,9 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; +import App from './App'; + +it('renders without crashing', () => { + const div = document.createElement('div'); + ReactDOM.render(, div); + ReactDOM.unmountComponentAtNode(div); +}); diff --git a/packages/cra-template-wptheme-typescript/template/src/App.tsx b/packages/cra-template-wptheme-typescript/template/src/App.tsx new file mode 100644 index 0000000..7f0f195 --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/src/App.tsx @@ -0,0 +1,26 @@ +import React from 'react'; +import logo from './logo.svg'; +import './App.css'; + +const App: React.FC = () => { + return ( +
+
+ logo +

+ Edit react-src/src/App.tsx and save to reload. +

+ + Learn React + +
+
+ ); +}; + +export default App; diff --git a/packages/cra-template-wptheme-typescript/template/src/index.css b/packages/cra-template-wptheme-typescript/template/src/index.css new file mode 100644 index 0000000..ec2585e --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/src/index.css @@ -0,0 +1,13 @@ +body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +code { + font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', + monospace; +} diff --git a/packages/cra-template-wptheme-typescript/template/src/index.tsx b/packages/cra-template-wptheme-typescript/template/src/index.tsx new file mode 100644 index 0000000..825db58 --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/src/index.tsx @@ -0,0 +1,12 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; +import './index.css'; +import App from './App'; +// import * as serviceWorker from './serviceWorker'; + +ReactDOM.render(, document.getElementById('root')); + +// If you want your app to work offline and load faster, you can change +// unregister() to register() below. Note this comes with some pitfalls. +// Learn more about service workers: https://bit.ly/CRA-PWA +// serviceWorker.unregister(); diff --git a/packages/cra-template-wptheme-typescript/template/src/logo.svg b/packages/cra-template-wptheme-typescript/template/src/logo.svg new file mode 100644 index 0000000..2e5df0d --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/src/logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/cra-template-wptheme-typescript/template/src/serviceWorker.ts b/packages/cra-template-wptheme-typescript/template/src/serviceWorker.ts new file mode 100644 index 0000000..15d90cb --- /dev/null +++ b/packages/cra-template-wptheme-typescript/template/src/serviceWorker.ts @@ -0,0 +1,143 @@ +// This optional code is used to register a service worker. +// register() is not called by default. + +// This lets the app load faster on subsequent visits in production, and gives +// it offline capabilities. However, it also means that developers (and users) +// will only see deployed updates on subsequent visits to a page, after all the +// existing tabs open on the page have been closed, since previously cached +// resources are updated in the background. + +// To learn more about the benefits of this model and instructions on how to +// opt-in, read https://bit.ly/CRA-PWA + +const isLocalhost = Boolean( + window.location.hostname === 'localhost' || + // [::1] is the IPv6 localhost address. + window.location.hostname === '[::1]' || + // 127.0.0.1/8 is considered localhost for IPv4. + window.location.hostname.match( + /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ + ) +); + +type Config = { + onSuccess?: (registration: ServiceWorkerRegistration) => void; + onUpdate?: (registration: ServiceWorkerRegistration) => void; +}; + +export function register(config?: Config) { + if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { + // The URL constructor is available in all browsers that support SW. + const publicUrl = new URL( + (process as { env: { [key: string]: string } }).env.PUBLIC_URL, + window.location.href + ); + if (publicUrl.origin !== window.location.origin) { + // Our service worker won't work if PUBLIC_URL is on a different origin + // from what our page is served on. This might happen if a CDN is used to + // serve assets; see https://github.com/facebook/create-react-app/issues/2374 + return; + } + + window.addEventListener('load', () => { + const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; + + if (isLocalhost) { + // This is running on localhost. Let's check if a service worker still exists or not. + checkValidServiceWorker(swUrl, config); + + // Add some additional logging to localhost, pointing developers to the + // service worker/PWA documentation. + navigator.serviceWorker.ready.then(() => { + console.log( + 'This web app is being served cache-first by a service ' + + 'worker. To learn more, visit https://bit.ly/CRA-PWA' + ); + }); + } else { + // Is not localhost. Just register service worker + registerValidSW(swUrl, config); + } + }); + } +} + +function registerValidSW(swUrl: string, config?: Config) { + navigator.serviceWorker + .register(swUrl) + .then(registration => { + registration.onupdatefound = () => { + const installingWorker = registration.installing; + if (installingWorker == null) { + return; + } + installingWorker.onstatechange = () => { + if (installingWorker.state === 'installed') { + if (navigator.serviceWorker.controller) { + // At this point, the updated precached content has been fetched, + // but the previous service worker will still serve the older + // content until all client tabs are closed. + console.log( + 'New content is available and will be used when all ' + + 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' + ); + + // Execute callback + if (config && config.onUpdate) { + config.onUpdate(registration); + } + } else { + // At this point, everything has been precached. + // It's the perfect time to display a + // "Content is cached for offline use." message. + console.log('Content is cached for offline use.'); + + // Execute callback + if (config && config.onSuccess) { + config.onSuccess(registration); + } + } + } + }; + }; + }) + .catch(error => { + console.error('Error during service worker registration:', error); + }); +} + +function checkValidServiceWorker(swUrl: string, config?: Config) { + // Check if the service worker can be found. If it can't reload the page. + fetch(swUrl) + .then(response => { + // Ensure service worker exists, and that we really are getting a JS file. + const contentType = response.headers.get('content-type'); + if ( + response.status === 404 || + (contentType != null && contentType.indexOf('javascript') === -1) + ) { + // No service worker found. Probably a different app. Reload the page. + navigator.serviceWorker.ready.then(registration => { + registration.unregister().then(() => { + window.location.reload(); + }); + }); + } else { + // Service worker found. Proceed as normal. + registerValidSW(swUrl, config); + } + }) + .catch(() => { + console.log( + 'No internet connection found. App is running in offline mode.' + ); + }); +} + +export function unregister() { + if ('serviceWorker' in navigator) { + navigator.serviceWorker.ready.then(registration => { + registration.unregister(); + }); + } +} diff --git a/packages/cra-template-wptheme/README.md b/packages/cra-template-wptheme/README.md new file mode 100644 index 0000000..1c797ad --- /dev/null +++ b/packages/cra-template-wptheme/README.md @@ -0,0 +1,5 @@ +# cra-template-wptheme + +This is the official base template for [Create React WPTheme](https://github.com/devloco/create-react-wptheme). + +If you don't specify a template (for example, `--template typescript`), this template will be used by default. diff --git a/packages/cra-template-wptheme/package.json b/packages/cra-template-wptheme/package.json new file mode 100644 index 0000000..dfb9256 --- /dev/null +++ b/packages/cra-template-wptheme/package.json @@ -0,0 +1,37 @@ +{ + "name": "@devloco/cra-template-wptheme", + "version": "3.3.0-wp.1", + "keywords": [ + "wordpress", + "create-react-app", + "wordpress-theme", + "wordpress-development", + "wordpress-starter-theme", + "wordpress-api", + "reactjs", + "react", + "react-theme", + "wordpress-server", + "react-tutorial", + "react-wordpress-themes", + "php", + "template" + ], + "description": "The base template for Create React WPTheme.", + "main": "template.json", + "repository": { + "type": "git", + "url": "https://github.com/devloco/create-react-wptheme.git" + }, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "bugs": { + "url": "https://github.com/devloco/create-react-wptheme/issues" + }, + "files": [ + "template", + "template.json" + ] +} diff --git a/packages/cra-template-wptheme/template.json b/packages/cra-template-wptheme/template.json new file mode 100644 index 0000000..92a4250 --- /dev/null +++ b/packages/cra-template-wptheme/template.json @@ -0,0 +1,3 @@ +{ + "dependencies": {} +} diff --git a/packages/cra-template-wptheme/template/README.md b/packages/cra-template-wptheme/template/README.md new file mode 100644 index 0000000..859d27a --- /dev/null +++ b/packages/cra-template-wptheme/template/README.md @@ -0,0 +1,68 @@ +This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). + +## Available Scripts + +In the project directory, you can run: + +### `npm start` + +Runs the app in the development mode.
+Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.
+You will also see any lint errors in the console. + +### `npm test` + +Launches the test runner in the interactive watch mode.
+See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. + +### `npm run build` + +Builds the app for production to the `build` folder.
+It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.
+Your app is ready to be deployed! + +See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. + +### `npm run eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. + +Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. + +You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. + +## Learn More + +You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). + +To learn React, check out the [React documentation](https://reactjs.org/). + +### Code Splitting + +This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting + +### Analyzing the Bundle Size + +This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size + +### Making a Progressive Web App + +This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app + +### Advanced Configuration + +This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration + +### Deployment + +This section has moved here: https://facebook.github.io/create-react-app/docs/deployment + +### `npm run build` fails to minify + +This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify diff --git a/packages/cra-template-wptheme/template/gitignore b/packages/cra-template-wptheme/template/gitignore new file mode 100644 index 0000000..4d29575 --- /dev/null +++ b/packages/cra-template-wptheme/template/gitignore @@ -0,0 +1,23 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/packages/cra-template-wptheme/template/public/favicon.ico b/packages/cra-template-wptheme/template/public/favicon.ico new file mode 100644 index 0000000..c2c86b8 Binary files /dev/null and b/packages/cra-template-wptheme/template/public/favicon.ico differ diff --git a/packages/cra-template-wptheme/template/public/index.html b/packages/cra-template-wptheme/template/public/index.html new file mode 100644 index 0000000..c240d2c --- /dev/null +++ b/packages/cra-template-wptheme/template/public/index.html @@ -0,0 +1,43 @@ + + + + + + + + + + + + + React App + + + +
+ + + diff --git a/packages/cra-template-wptheme/template/public/index.php b/packages/cra-template-wptheme/template/public/index.php new file mode 100644 index 0000000..faf7b78 --- /dev/null +++ b/packages/cra-template-wptheme/template/public/index.php @@ -0,0 +1,37 @@ + + +Now, back in your command prompt, rerun the "start" script again... + + diff --git a/packages/cra-template-wptheme/template/public/logo192.png b/packages/cra-template-wptheme/template/public/logo192.png new file mode 100644 index 0000000..fa313ab Binary files /dev/null and b/packages/cra-template-wptheme/template/public/logo192.png differ diff --git a/packages/cra-template-wptheme/template/public/logo512.png b/packages/cra-template-wptheme/template/public/logo512.png new file mode 100644 index 0000000..bd5d4b5 Binary files /dev/null and b/packages/cra-template-wptheme/template/public/logo512.png differ diff --git a/packages/cra-template-wptheme/template/public/manifest.json b/packages/cra-template-wptheme/template/public/manifest.json new file mode 100644 index 0000000..080d6c7 --- /dev/null +++ b/packages/cra-template-wptheme/template/public/manifest.json @@ -0,0 +1,25 @@ +{ + "short_name": "React App", + "name": "Create React App Sample", + "icons": [ + { + "src": "favicon.ico", + "sizes": "64x64 32x32 24x24 16x16", + "type": "image/x-icon" + }, + { + "src": "logo192.png", + "type": "image/png", + "sizes": "192x192" + }, + { + "src": "logo512.png", + "type": "image/png", + "sizes": "512x512" + } + ], + "start_url": ".", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/packages/cra-template-wptheme/template/public/post_installer.php b/packages/cra-template-wptheme/template/public/post_installer.php new file mode 100644 index 0000000..db3f720 --- /dev/null +++ b/packages/cra-template-wptheme/template/public/post_installer.php @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + React WordPress Theme + + + +
+ + + diff --git a/packages/cra-template-wptheme/template/public/robots.txt b/packages/cra-template-wptheme/template/public/robots.txt new file mode 100644 index 0000000..01b0f9a --- /dev/null +++ b/packages/cra-template-wptheme/template/public/robots.txt @@ -0,0 +1,2 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * diff --git a/packages/cra-template-wptheme/template/public/screenshot.png b/packages/cra-template-wptheme/template/public/screenshot.png new file mode 100644 index 0000000..ed4277c Binary files /dev/null and b/packages/cra-template-wptheme/template/public/screenshot.png differ diff --git a/packages/cra-template-wptheme/template/public/style.css b/packages/cra-template-wptheme/template/public/style.css new file mode 100644 index 0000000..9034d75 --- /dev/null +++ b/packages/cra-template-wptheme/template/public/style.css @@ -0,0 +1,13 @@ +/* +Theme Name: REPLACE_WITH_THEME_NAME +Author: your-name +Author URI: https://github.com/your-github +Description: Create React WP Themes with no build configuration +Version: 0.1 +License: GNU General Public License v2 or later +License URI: http://www.gnu.org/licenses/gpl-2.0.html +Tags: starter +Text Domain: your-domain + +This theme, like WordPress, is licensed under the GPL. +*/ diff --git a/packages/cra-template-wptheme/template/src/App.css b/packages/cra-template-wptheme/template/src/App.css new file mode 100644 index 0000000..afc3885 --- /dev/null +++ b/packages/cra-template-wptheme/template/src/App.css @@ -0,0 +1,22 @@ +.App { + text-align: center; +} + +.App-logo { + height: 40vmin; +} + +.App-header { + background-color: #282c34; + min-height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: calc(10px + 2vmin); + color: white; +} + +.App-link { + color: #09d3ac; +} diff --git a/packages/cra-template-wptheme/template/src/App.js b/packages/cra-template-wptheme/template/src/App.js new file mode 100644 index 0000000..e55c89f --- /dev/null +++ b/packages/cra-template-wptheme/template/src/App.js @@ -0,0 +1,26 @@ +import React from 'react'; +import logo from './logo.svg'; +import './App.css'; + +function App() { + return ( +
+
+ logo +

+ Edit react-src/src/App.js and save to reload. +

+ + Learn React + +
+
+ ); +} + +export default App; diff --git a/packages/cra-template-wptheme/template/src/App.test.js b/packages/cra-template-wptheme/template/src/App.test.js new file mode 100644 index 0000000..a754b20 --- /dev/null +++ b/packages/cra-template-wptheme/template/src/App.test.js @@ -0,0 +1,9 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; +import App from './App'; + +it('renders without crashing', () => { + const div = document.createElement('div'); + ReactDOM.render(, div); + ReactDOM.unmountComponentAtNode(div); +}); diff --git a/packages/cra-template-wptheme/template/src/index.css b/packages/cra-template-wptheme/template/src/index.css new file mode 100644 index 0000000..4a1df4d --- /dev/null +++ b/packages/cra-template-wptheme/template/src/index.css @@ -0,0 +1,13 @@ +body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", + "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +code { + font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", + monospace; +} diff --git a/packages/cra-template-wptheme/template/src/index.js b/packages/cra-template-wptheme/template/src/index.js new file mode 100644 index 0000000..825db58 --- /dev/null +++ b/packages/cra-template-wptheme/template/src/index.js @@ -0,0 +1,12 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; +import './index.css'; +import App from './App'; +// import * as serviceWorker from './serviceWorker'; + +ReactDOM.render(, document.getElementById('root')); + +// If you want your app to work offline and load faster, you can change +// unregister() to register() below. Note this comes with some pitfalls. +// Learn more about service workers: https://bit.ly/CRA-PWA +// serviceWorker.unregister(); diff --git a/packages/cra-template-wptheme/template/src/logo.svg b/packages/cra-template-wptheme/template/src/logo.svg new file mode 100644 index 0000000..2e5df0d --- /dev/null +++ b/packages/cra-template-wptheme/template/src/logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/packages/cra-template-wptheme/template/src/serviceWorker.js b/packages/cra-template-wptheme/template/src/serviceWorker.js new file mode 100644 index 0000000..f8c7e50 --- /dev/null +++ b/packages/cra-template-wptheme/template/src/serviceWorker.js @@ -0,0 +1,135 @@ +// This optional code is used to register a service worker. +// register() is not called by default. + +// This lets the app load faster on subsequent visits in production, and gives +// it offline capabilities. However, it also means that developers (and users) +// will only see deployed updates on subsequent visits to a page, after all the +// existing tabs open on the page have been closed, since previously cached +// resources are updated in the background. + +// To learn more about the benefits of this model and instructions on how to +// opt-in, read https://bit.ly/CRA-PWA + +const isLocalhost = Boolean( + window.location.hostname === 'localhost' || + // [::1] is the IPv6 localhost address. + window.location.hostname === '[::1]' || + // 127.0.0.1/8 is considered localhost for IPv4. + window.location.hostname.match( + /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ + ) +); + +export function register(config) { + if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { + // The URL constructor is available in all browsers that support SW. + const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); + if (publicUrl.origin !== window.location.origin) { + // Our service worker won't work if PUBLIC_URL is on a different origin + // from what our page is served on. This might happen if a CDN is used to + // serve assets; see https://github.com/facebook/create-react-app/issues/2374 + return; + } + + window.addEventListener('load', () => { + const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; + + if (isLocalhost) { + // This is running on localhost. Let's check if a service worker still exists or not. + checkValidServiceWorker(swUrl, config); + + // Add some additional logging to localhost, pointing developers to the + // service worker/PWA documentation. + navigator.serviceWorker.ready.then(() => { + console.log( + 'This web app is being served cache-first by a service ' + + 'worker. To learn more, visit https://bit.ly/CRA-PWA' + ); + }); + } else { + // Is not localhost. Just register service worker + registerValidSW(swUrl, config); + } + }); + } +} + +function registerValidSW(swUrl, config) { + navigator.serviceWorker + .register(swUrl) + .then(registration => { + registration.onupdatefound = () => { + const installingWorker = registration.installing; + if (installingWorker == null) { + return; + } + installingWorker.onstatechange = () => { + if (installingWorker.state === 'installed') { + if (navigator.serviceWorker.controller) { + // At this point, the updated precached content has been fetched, + // but the previous service worker will still serve the older + // content until all client tabs are closed. + console.log( + 'New content is available and will be used when all ' + + 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' + ); + + // Execute callback + if (config && config.onUpdate) { + config.onUpdate(registration); + } + } else { + // At this point, everything has been precached. + // It's the perfect time to display a + // "Content is cached for offline use." message. + console.log('Content is cached for offline use.'); + + // Execute callback + if (config && config.onSuccess) { + config.onSuccess(registration); + } + } + } + }; + }; + }) + .catch(error => { + console.error('Error during service worker registration:', error); + }); +} + +function checkValidServiceWorker(swUrl, config) { + // Check if the service worker can be found. If it can't reload the page. + fetch(swUrl) + .then(response => { + // Ensure service worker exists, and that we really are getting a JS file. + const contentType = response.headers.get('content-type'); + if ( + response.status === 404 || + (contentType != null && contentType.indexOf('javascript') === -1) + ) { + // No service worker found. Probably a different app. Reload the page. + navigator.serviceWorker.ready.then(registration => { + registration.unregister().then(() => { + window.location.reload(); + }); + }); + } else { + // Service worker found. Proceed as normal. + registerValidSW(swUrl, config); + } + }) + .catch(() => { + console.log( + 'No internet connection found. App is running in offline mode.' + ); + }); +} + +export function unregister() { + if ('serviceWorker' in navigator) { + navigator.serviceWorker.ready.then(registration => { + registration.unregister(); + }); + } +} diff --git a/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/.gitignore b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/.gitignore new file mode 100644 index 0000000..16892f9 --- /dev/null +++ b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/.gitignore @@ -0,0 +1,12 @@ +.idea/ +.vscode/ +node_modules/ +build +.DS_Store +*.tgz +my-app* +template/src/__tests__/__snapshots__/ +npm-debug.log* +yarn* +/.changelog +wpThemeErrorOverlay.js diff --git a/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/.npmignore b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/.npmignore new file mode 100644 index 0000000..a3d9842 --- /dev/null +++ b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/.npmignore @@ -0,0 +1,4 @@ +__tests__ +*.test.js +*.spec.js +yarn* diff --git a/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/.npmrc b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/.npmrc new file mode 100644 index 0000000..46db3e1 --- /dev/null +++ b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/.npmrc @@ -0,0 +1,2 @@ +package-lock=false +shrinkwrap=false diff --git a/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/README.md b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/README.md new file mode 100644 index 0000000..aa412c8 --- /dev/null +++ b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/README.md @@ -0,0 +1,3 @@ +# react-scripts-wptheme-error-overlay + +[create-react-wptheme](https://github.com/devloco/create-react-wptheme) client with error overlay diff --git a/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/package.json b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/package.json new file mode 100644 index 0000000..f08303f --- /dev/null +++ b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/package.json @@ -0,0 +1,31 @@ +{ + "name": "@devloco/create-react-wptheme-error-overlay", + "version": "3.3.0-wp.1", + "description": "create-react-wptheme client with error overlay", + "main": "wptheme-error-overlay.js", + "scripts": { + "build": "npx webpack" + }, + "author": "devloco", + "license": "MIT", + "homepage": "https://github.com/devloco/create-react-wptheme", + "repository": { + "type": "git", + "url": "https://github.com/devloco/create-react-wptheme.git" + }, + "files": [ + "wpThemeErrorOverlay.js" + ], + "dependencies": { + "react-dev-utils": "^10.0.0", + "react-error-overlay": "^6.0.4" + }, + "devDependencies": { + "@babel/code-frame": "^7.5.5", + "@babel/core": "^7.7.5", + "@webpack-cli/info": "^0.2.0", + "babel-loader": "^8.0.6", + "webpack": "^4.41.2", + "webpack-cli": "^3.3.10" + } +} diff --git a/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/src/index.js b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/src/index.js new file mode 100644 index 0000000..a79c41a --- /dev/null +++ b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/src/index.js @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2018-present, https://github.com/devloco + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +"use strict"; + +var stripAnsi = require("strip-ansi"); +var ErrorOverlay = require("react-error-overlay"); +var formatWebpackMessages = require("react-dev-utils/formatWebpackMessages"); + +// Remember some state related to hot module replacement. +var isFirstCompilation = true; +var mostRecentCompilationHash = null; +var hasCompileErrors = false; + +// We need to keep track of if there has been a runtime error. +// Essentially, we cannot guarantee application state was not corrupted by the +// runtime error. To prevent confusing behavior, we forcibly reload the entire +// application. This is handled below when we are notified of a compile (code +// change). +// See https://github.com/facebookincubator/create-react-app/issues/3096 +var hadRuntimeError = false; +var runtimeOptions = { + onError: function() { + hadRuntimeError = true; + }, + filename: "/static/js/bundle.js" +}; +ErrorOverlay.startReportingRuntimeErrors(runtimeOptions); + +export function clearConsole() { + // Clean up outdated compile errors, if any. + if (typeof console !== "undefined" && typeof console.clear === "function") { + console.clear(); + } +} + +export function handleSuccess() { + // Successful compilation. + clearConsole(); + isFirstCompilation = false; + hasCompileErrors = false; + hadRuntimeError = false; +} + +export function handleWarnings(warnings) { + //clearConsole(); + + // var isHotUpdate = !isFirstCompilation; + isFirstCompilation = false; + hasCompileErrors = false; + + function printWarnings() { + // Print warnings to the console. + var formatted = formatWebpackMessages({ + warnings: warnings, + errors: [] + }); + + if (typeof console !== "undefined" && typeof console.warn === "function") { + for (var i = 0; i < formatted.warnings.length; i++) { + if (i === 5) { + console.warn("There were more warnings in other files.\n" + "You can find a complete log in the terminal."); + break; + } + + console.warn(stripAnsi(formatted.warnings[i])); + } + } + } + + printWarnings(); +} + +export function handleErrors(errors) { + //clearConsole(); + + isFirstCompilation = false; + hasCompileErrors = true; + + // Format webpack messages. + var formatted = formatWebpackMessages({ + errors: errors, + warnings: [] + }); + + if (Array.isArray(formatted.errors) && formatted.errors.length > 0) { + // Only show the first error. + ErrorOverlay.reportBuildError(formatted.errors[0]); + } else { + if (typeof console !== "undefined" && typeof console.error === "function") { + console.error("UNKNOWN ERROR from react-scripts-wptheme-error-overlay:handleErrors:", errors); + } + } + + // Do not attempt to reload now. + // We will reload on next success instead. +} diff --git a/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/webpack.config.js b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/webpack.config.js new file mode 100644 index 0000000..0ab505d --- /dev/null +++ b/packages/create-react-wptheme-utils/create-react-wptheme-error-overlay/webpack.config.js @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2018-present, https://github.com/devloco + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +"use strict"; + +const path = require("path"); + +module.exports = { + mode: "none", + entry: path.join(__dirname, "src", "index.js"), + watch: false, + watchOptions: { + aggregateTimeout: 600, + ignored: [__dirname, "node_modules", "webpack.config.js", "wpThemeErrorOverlay.js"] + }, + output: { + path: path.join(__dirname, ".."), + filename: "wpThemeErrorOverlay.js", + library: "wpThemeErrorOverlay", + libraryTarget: "umd" + }, + module: { + rules: [ + { + test: /\.js$/, + include: path.join(__dirname, "src"), + use: "babel-loader" + } + ] + } +}; diff --git a/packages/create-react-wptheme-utils/fileFunctions.js b/packages/create-react-wptheme-utils/fileFunctions.js new file mode 100644 index 0000000..754880e --- /dev/null +++ b/packages/create-react-wptheme-utils/fileFunctions.js @@ -0,0 +1,183 @@ +/** + * Copyright (c) 2018-present, https://github.com/devloco + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +"use strict"; + +const fs = require("fs-extra"); +const path = require("path"); +const { rm, cp } = require("shelljs"); +const wpThemePostInstallerInfo = require("@devloco/create-react-wptheme-utils/postInstallerInfo"); +const wpThemeUserConfig = require("@devloco/create-react-wptheme-utils/getUserConfig"); //(paths, process.env.NODE_ENV); + +const _doNotEditFileName = "!DO_NOT_EDIT_THESE_FILES!.txt"; +const _readyToDeployFileName = "!READY_TO_DEPLOY!.txt"; +const _forBuild = () => { + const nodeEnv = process.env.NODE_ENV; + switch (nodeEnv) { + case "dev": + case "development": + return false; + case "build": + case "prod": + case "production": + return true; + default: + console.log(chalk.red(`Unknown env.NODE_ENV: ${nodeEnv}`)); + return false; + } +}; + +const fileFunctions = { + copyPublicFolder: function(paths) { + fs.copySync(paths.appPublic, paths.appBuild, { + dereference: true, + filter: (file) => file !== paths.appHtml && file.indexOf("index.html") == -1 && file.indexOf(wpThemePostInstallerInfo.postInstallerName) == -1 + }); + }, + copyToThemeFolder: function(paths) { + const userConfig = wpThemeUserConfig(paths, process.env.NODE_ENV); + const forBuild = _forBuild(); + let actionPath = (forBuild && userConfig && userConfig.finalBuildPath) || ".."; + + const copyFrom = path.join(paths.appBuild, "/*"); + + if (forBuild === true) { + fileFunctions.cleanThemeFolder(paths, true); + fileFunctions.deleteDeployFolder(paths); + + const themeName = require(paths.appPackageJson).name; + actionPath = (userConfig && userConfig.finalBuildPath) || path.join("..", themeName); + fs.ensureDirSync(actionPath); + } + + cp("-rf", copyFrom, actionPath); + }, + cleanThemeFolder: function(paths) { + const userConfig = wpThemeUserConfig(paths, process.env.NODE_ENV); + const forBuild = _forBuild(); + let actionPath = (forBuild && userConfig && userConfig.finalBuildPath) || ".."; + + rm("-rf", path.join(actionPath, "static")); + + if (forBuild === true) { + const doNotEditFile = path.join(actionPath, _doNotEditFileName); + rm("-f", doNotEditFile); + + const readyToDeployFile = path.join(actionPath, _readyToDeployFileName); + rm("-f", readyToDeployFile); + + const assetManifest = path.join(actionPath, "asset-manifest*"); + rm("-r", assetManifest); + + const favIconIco = path.join(actionPath, "favicon.ico"); + rm("-r", favIconIco); + + const indexPhp = path.join(actionPath, "index.php"); + rm("-r", indexPhp); + + const logoFiles = path.join(actionPath, "logo*"); + rm("-r", logoFiles); + + const precacheFiles = path.join(actionPath, "precache*"); + rm("-r", precacheFiles); + + const manifestJson = path.join(actionPath, "manifest.json"); + rm("-r", manifestJson); + + const robotsTxt = path.join(actionPath, "robots.txt"); + rm("-r", robotsTxt); + + const screenShotPng = path.join(actionPath, "screenshot.png"); + rm("-r", screenShotPng); + + const serviceWorker = path.join(actionPath, "service-worker.js"); + rm("-r", serviceWorker); + + const styleCss = path.join(actionPath, "style.css"); + rm("-r", styleCss); + } + }, + deleteDeployFolder: function(paths) { + const userConfig = wpThemeUserConfig(paths, process.env.NODE_ENV); + const forBuild = _forBuild(); + const themeName = require(paths.appPackageJson).name; + + let deployFolder = (forBuild && userConfig && userConfig.finalBuildPath) || path.join("..", themeName); + if (fs.existsSync(deployFolder)) { + var files = fs.readdirSync(deployFolder); + files.forEach((file) => { + if (file !== "react-src") { + const fileDir = path.join(deployFolder, file); + rm("-rf", fileDir); + } + }); + } + }, + setupCopyToThemeFolder: function(paths) { + const userConfig = wpThemeUserConfig(paths, process.env.NODE_ENV); + const forBuild = _forBuild(); + let actionPath = (forBuild && userConfig && userConfig.finalBuildPath) || ".."; + + const indexPhp = path.join(paths.appPublic, "index.php"); + cp("-rf", indexPhp, actionPath); + + const styleCss = path.join(paths.appPublic, "style.css"); + cp("-rf", styleCss, actionPath); + + const screenShotPng = path.join(paths.appPublic, "screenshot.png"); + cp("-rf", screenShotPng, actionPath); + + const favIconIco = path.join(paths.appPublic, "favicon.ico"); + cp("-rf", favIconIco, actionPath); + }, + writeDoNotEditFile: function(paths) { + const userConfig = wpThemeUserConfig(paths, process.env.NODE_ENV); + const forBuild = _forBuild(); + let actionPath = (forBuild && userConfig && userConfig.finalBuildPath) || ".."; + const readyToDeployFile = path.join(actionPath, _readyToDeployFileName); + fs.access(readyToDeployFile, fs.constants.F_OK, (err) => { + if (!err) { + rm("-f", readyToDeployFile); + } + }); + + let doNotEditContent = `Instead, edit the files in the "react-src/src" and "react-src/public" folders.`; + doNotEditContent += "\nThese files are overwritten by Webpack every time you make edits to the files in those folders."; + doNotEditContent += "\nYou will lose all changes made to these files when that happens."; + + const doNotEditFile = path.join(actionPath, _doNotEditFileName); + fs.access(doNotEditFile, fs.constants.F_OK, (err) => { + if (err) { + fs.writeFile(doNotEditFile, doNotEditContent, "utf8", (err) => {}); + } + }); + }, + writeReadyToDeployFile: function(paths) { + const userConfig = wpThemeUserConfig(paths, process.env.NODE_ENV); + const forBuild = _forBuild(); + let actionPath = (forBuild && userConfig && userConfig.finalBuildPath) || ".."; + const doNotEditFile = path.join(actionPath, _doNotEditFileName); + fs.access(doNotEditFile, fs.constants.F_OK, (err) => { + if (!err) { + rm("-f", doNotEditFile); + } + }); + + const themeName = require(paths.appPackageJson).name; + let readyToDeployContent = `The theme named "${themeName}" is ready to deploy to your production server.`; + readyToDeployContent += '\n\nIf you need to continue developing your theme, simply change to the "react-src" folder and type the command: npm run start'; + + const readyToDeployFile = path.join(actionPath, _readyToDeployFileName); + fs.access(readyToDeployFile, fs.constants.F_OK, (err) => { + if (err) { + fs.writeFile(readyToDeployFile, readyToDeployContent, "utf8", (err) => {}); + } + }); + } +}; + +module.exports = fileFunctions; diff --git a/packages/create-react-wptheme-utils/fileWatcherPlugin.js b/packages/create-react-wptheme-utils/fileWatcherPlugin.js new file mode 100644 index 0000000..aa0d916 --- /dev/null +++ b/packages/create-react-wptheme-utils/fileWatcherPlugin.js @@ -0,0 +1,147 @@ +/** + * Copyright (c) 2018-present, https://github.com/devloco + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/// +/// big thanks to: +/// https://www.npmjs.com/package/filewatcher-webpack-plugin +/// +/// this plugin causes WebPack to do a rebuild by touching a file under WebPack's control when +/// a file *not* under WebPack's control changes. +/// +/// Usage example: (to watch all JS, CSS and PHP files under the "public" folder in a create-react-wptheme project (or create-react-app project)) +/// NOTE: "touchFile" is used to force WebPack to do a rebuild. It must be a file that WebPack is watching. +/// +/// const FileWatcherPlugin = require("./fileWatcherPlugin.wptheme"); +/// ... +/// plugins: [ +// new FileWatcherPlugin({ +// touchFile: "./public/index.php", // create-react-wptheme emits index.php and thus it is watched by WebPack... +// ignored: "./public/index.php", // ... so no need to watch it here as well. Without ignoring it, you'd cause infinite build loops. +// watchFileGlobs: ["./public/**/*.js", "./public/**/*.css", "./public/**/*.php"] +// }), +/// ], +/// ... +/// + +"use strict"; + +const chokidar = require("chokidar"); +const { touch } = require("shelljs"); + +function FileWatcherPlugin(options) { + this.options = options; +} + +FileWatcherPlugin.prototype.apply = function (compiler) { + if (!this.options) { + return; + } + + const options = this.options; + const touchFile = options.touchFile; + const forceBuild = function (touchFileName) { + // -c to not create a file if one doesn't already exist. + // Remember this file needs to be watched by WebPack, thus it should already exist + touch("-c", touchFileName); + }; + + compiler.hooks.done.tap("FileWatcherPlugin", function (compilation) { + var watcher = chokidar.watch(options.watchFileGlobs, { + persistent: options.persistance || true, + ignored: options.ignored || false, + ignoreInitial: options.ignoreInitial || false, + followSymlinks: options.followSymlinks || true, + cwd: options.cwd || ".", + disableGlobbing: options.disableGlobbing || false, + usePolling: options.usePolling || true, + interval: options.interval || 100, + binaryInterval: options.binaryInterval || 300, + alwaysStat: options.alwaysStat || false, + depth: options.depth || 99, + awaitWriteFinish: { + stabilityThreshold: options.stabilityThreshold || 250, + pollInterval: options.pollInterval || 100 + }, + + ignorePermissionErrors: options.ignorePermissionErrors || false, + atomic: options.atomic || true + }); + + watcher + .on( + "add", + options.onAddCallback || + function (path) { + //forceBuild(touchFile); // causes infinite loops for "add" + return null; + } + ) + .on( + "change", + options.onChangeCallback || + function (path) { + // console.log(`\n\n Compilation Started after change of - ${path} \n\n`); + // compiler.run(function(err) { + // if (err) throw err; + // watcher.close(); + // }); + //console.log(`\n\n Compilation ended for change of - ${path} \n\n`); + forceBuild(touchFile); + } + ) + .on( + "unlink", + options.onUnlinkCallback || + function (path) { + // console.log(`File ${path} has been removed`); + forceBuild(touchFile); + } + ); + + watcher + .on( + "addDir", + options.onAddDirCallback || + function (path) { + // console.log(`Directory ${path} has been added`); + forceBuild(touchFile); + } + ) + .on( + "unlinkDir", + options.unlinkDirCallback || + function (path) { + // console.log(`Directory ${path} has been removed`); + forceBuild(touchFile); + } + ) + .on( + "error", + options.onErrorCallback || + function (error) { + console.log(`FileWatcherPlugin error: ${error}`); + return null; + } + ) + .on( + "ready", + options.onReadyCallback || + function () { + console.log("Watching for changes in the Public folder."); + } + ) + .on( + "raw", + options.onRawCallback || + function (event, path, details) { + return null; + } + ); + }); +}; + +module.exports = FileWatcherPlugin; diff --git a/packages/create-react-wptheme-utils/getUserConfig.js b/packages/create-react-wptheme-utils/getUserConfig.js new file mode 100644 index 0000000..2d12f27 --- /dev/null +++ b/packages/create-react-wptheme-utils/getUserConfig.js @@ -0,0 +1,90 @@ +/** + * Copyright (c) 2018-present, https://github.com/devloco + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +"use strict"; + +const fs = require("fs-extra"); +const chalk = require("chalk"); +const path = require("path"); +const wpThemePostInstallerInfo = require("@devloco/create-react-wptheme-utils/postInstallerInfo"); + +const _userDevConfigName = "user.dev.json"; +const _userProdConfigName = "user.prod.json"; + +function _writeUserConfig(paths, configName, configString) { + let configPath = path.join(paths.appPath, configName); + fs.writeFileSync(configPath, configString); +} + +function _getUserConfig(paths, configName, defaultConfig) { + let userConfig = null; + try { + userConfig = require(path.join(paths.appPath, configName)); + } catch (err) { + userConfig = JSON.stringify(defaultConfig, null, 4); + _writeUserConfig(paths, configName, userConfig); + return defaultConfig; + } + + return userConfig; +} + +module.exports = function(paths, nodeEnv) { + const appPackageJson = require(paths.appPackageJson); + + const defaultUserDevConfig = { + fileWatcherPlugin: { + touchFile: "./public/index.php", + ignored: "./public/index.php", + watchFileGlobs: ["./public/**/*.js", "./public/**/*.css", "./public/**/*.php"] + }, + wpThemeServer: { + enable: true, + host: "127.0.0.1", + port: 8090, + sslCert: null, + sslKey: null, + watchFile: "../index.php" + }, + injectWpThemeClient: { + override: null, + file: "./build/index.php" + } + }; + + const defaultUserProdConfig = { + finalBuildPath: null, + homepage: appPackageJson.homepage + }; + + // Create both files ASAP. + if (!wpThemePostInstallerInfo.postInstallerExists(paths)) { + _getUserConfig(paths, _userDevConfigName, defaultUserDevConfig); + _getUserConfig(paths, _userProdConfigName, defaultUserProdConfig); + } + + if (wpThemePostInstallerInfo.postInstallerExists(paths)) { + return null; + } + + if (typeof nodeEnv !== "string") { + nodeEnv = process.env.NODE_ENV; + } + + switch (nodeEnv) { + case "dev": + case "development": + return _getUserConfig(paths, _userDevConfigName, defaultUserDevConfig); + case "build": + case "prod": + case "production": + return _getUserConfig(paths, _userProdConfigName, defaultUserProdConfig); + default: + console.log(chalk.red(`Unknown env.NODE_ENV: ${nodeEnv}`)); + return null; + } +}; diff --git a/packages/create-react-wptheme-utils/package.json b/packages/create-react-wptheme-utils/package.json new file mode 100644 index 0000000..4059dda --- /dev/null +++ b/packages/create-react-wptheme-utils/package.json @@ -0,0 +1,38 @@ +{ + "name": "@devloco/create-react-wptheme-utils", + "version": "3.3.0-wp.3", + "description": "Utilities used by create-react-wptheme.", + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://github.com/devloco/create-react-wptheme" + }, + "author": "devloco", + "license": "MIT", + "bugs": { + "url": "https://github.com/devloco/create-react-wptheme/issues" + }, + "files": [ + "fileFunctions.js", + "fileWatcherPlugin.js", + "getUserConfig.js", + "postInstallerInfo.js", + "shell-js.js", + "wpThemeClient.js", + "wpThemeErrorOverlay.js", + "wpThemeServer.js" + ], + "dependencies": { + "chalk": "^3.0.0", + "chokidar": "^3.3.0", + "shelljs": "^0.8.3", + "fs-extra": "^8.1.0", + "ws": "^7.2.1" + }, + "devDependencies": {} +} diff --git a/packages/create-react-wptheme-utils/postInstallerInfo.js b/packages/create-react-wptheme-utils/postInstallerInfo.js new file mode 100644 index 0000000..6bf7abd --- /dev/null +++ b/packages/create-react-wptheme-utils/postInstallerInfo.js @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2018-present, https://github.com/devloco + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const postInstallerName = "post_installer.php"; + +class PostInstallerException { + constructor(message) { + this.message = message; + this.name = "PostInstallerException"; + } +} + +const postInstallerInfo = { + postInstallerExists: function(paths) { + if (!paths) { + throw new PostInstallerException("'paths' not provided."); + } + + try { + fs.accessSync(path.join(paths.appPublic, postInstallerName), fs.constants.F_OK); + return true; + } catch (err) { + return false; + } + }, + postInstallerName: postInstallerName +}; + +module.exports = postInstallerInfo; diff --git a/packages/create-react-wptheme-utils/shell-js.js b/packages/create-react-wptheme-utils/shell-js.js new file mode 100644 index 0000000..1712e71 --- /dev/null +++ b/packages/create-react-wptheme-utils/shell-js.js @@ -0,0 +1,12 @@ +/** + * Copyright (c) 2018-present, https://github.com/devloco + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +"use strict"; + +var shelljs = require("shelljs"); + +module.exports = shelljs; diff --git a/packages/create-react-wptheme-utils/wpThemeClient.js b/packages/create-react-wptheme-utils/wpThemeClient.js new file mode 100644 index 0000000..9f45f5e --- /dev/null +++ b/packages/create-react-wptheme-utils/wpThemeClient.js @@ -0,0 +1,142 @@ +/** + * Copyright (c) 2018-present, https://github.com/devloco + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +var wpThemeClient = { + hash: null, + socket: null, + start: function(wsHostProtocol, wsHostname, wsPort) { + var hostProtocol = null; + switch (wsHostProtocol) { + case "ws": + case "wss": + hostProtocol = wsHostProtocol; + break; + default: + console.log(`WPTHEME CLIENT: configHostProtocol is not "ws" or "wss": ` + new String(wsHostProtocol)); + console.error("This is a bug. Please report to: https://github.com/devloco/create-react-wptheme/issues"); + return; + } + + if (wsHostname !== "__from-window__") { + if (typeof wsHostname !== "string" && wsHostname.length <= 0) { + console.log("WPTHEME CLIENT: hostname is not '__from-window__' or a non-empty string: ", wsHostname); + return; + } + } + + var parsedConfigPort = null; + if (wsPort !== "__from-window__") { + parsedConfigPort = parseInt(wsPort, 10); + if (typeof parsedConfigPort !== "number") { + console.log("WPTHEME CLIENT: port is not '__from-window__' or a number: ", wsPort); + return; + } + } + + var hostName = wsHostname === "__from-window__" ? window.location.hostname : wsHostname; + var portNum = wsPort === "__from-window__" ? window.location.port : parsedConfigPort; + var hostURL = hostProtocol + "://" + hostName + ":" + portNum; + + var newlyReloaded = true; + + wpThemeClient.socket = new WebSocket(hostURL); + wpThemeClient.socket.onmessage = function(response) { + if (response && typeof response.data === "string") { + try { + var msg = JSON.parse(response.data); + + if (msg) { + var msgHash = msg && msg.stats && msg.stats.hash; + + if (msg.type === "content-changed") { + if (msg.stats.errors && msg.stats.errors.length > 0) { + msg.type = "errors"; + } + if (msg.stats.warnings && msg.stats.warnings.length > 0) { + msg.type = "warnings"; + } + } + + switch (msg.type) { + case "content-changed": + if (!newlyReloaded || (wpThemeClient.hash === null || (typeof msgHash === "string" && msgHash.length > 0 && msgHash !== wpThemeClient.hash))) { + // Webpack successfully creates a new compile if there are only warnings (unlike errors which do not compile at all). + window.location.reload(); + } + break; + case "errors": + try { + wpThemeErrorOverlay.handleErrors(msg.stats.errors); + } catch (err) { + console.log("'errors' try block error:", err); + console.log("Compile ERRORS", msg); + } + break; + case "hash-check": + if (wpThemeClient.hash === null) { + wpThemeClient.hash = msgHash; + setTimeout(() => { + // In 500ms, let's double-check we have the latest hash... a build on the server may have gotten missed. + if (wpThemeClient.socket && wpThemeClient.socket.send) { + var msgJson = JSON.stringify({ + type: "hash-check" + }); + + wpThemeClient.socket.send(msgJson); + } + }, 500); + } else if (!newlyReloaded && typeof wpThemeClient.hash === "string" && wpThemeClient.hash !== msgHash) { + window.location.reload(); + } + break; + case "warnings": + try { + wpThemeErrorOverlay.handleWarnings(msg.stats.warnings); + if (!newlyReloaded) { + // Webpack successfully creates a new compile if there are only warnings (unlike errors which do not compile at all). + window.location.reload(); + } + } catch (err) { + console.log("'warnings' try block error:", err); + console.log("Compile WARNINGS", err, msg); + } + break; + } + } + } catch (err) { + if (console && typeof console.error === "function") { + console.error(err); + console.log("Raw websocket message:", response); + } + } + + newlyReloaded = false; + wpThemeClient.hash = typeof msgHash === "string" && msgHash.length > 0 ? msgHash : null; + } + }; + + wpThemeClient.socket.onclose = function() { + if (console && typeof console.info === "function") { + switch (wpThemeClient.socket.readyState) { + case wpThemeClient.socket.CLOSED: + case wpThemeClient.socket.CLOSING: + setTimeout(() => { + console.info("It's possible the browser refresh server has disconnected.\nYou can manually refresh the page if necessary."); + }, 1000); + break; + } + } + }; + + wpThemeClient.socket.onopen = function() { + if (console && typeof console.clear === "function") { + //console.clear(); + console.info("The browser refresh server is connected."); + } + }; + } +}; diff --git a/packages/create-react-wptheme-utils/wpThemeErrorOverlay.js b/packages/create-react-wptheme-utils/wpThemeErrorOverlay.js new file mode 100644 index 0000000..6916825 --- /dev/null +++ b/packages/create-react-wptheme-utils/wpThemeErrorOverlay.js @@ -0,0 +1,2387 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["wpThemeErrorOverlay"] = factory(); + else + root["wpThemeErrorOverlay"] = factory(); +})(window, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearConsole", function() { return clearConsole; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "handleSuccess", function() { return handleSuccess; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "handleWarnings", function() { return handleWarnings; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "handleErrors", function() { return handleErrors; }); +/** + * Copyright (c) 2018-present, https://github.com/devloco + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +var stripAnsi = __webpack_require__(1); + +var ErrorOverlay = __webpack_require__(3); + +var formatWebpackMessages = __webpack_require__(5); // Remember some state related to hot module replacement. + + +var isFirstCompilation = true; +var mostRecentCompilationHash = null; +var hasCompileErrors = false; // We need to keep track of if there has been a runtime error. +// Essentially, we cannot guarantee application state was not corrupted by the +// runtime error. To prevent confusing behavior, we forcibly reload the entire +// application. This is handled below when we are notified of a compile (code +// change). +// See https://github.com/facebookincubator/create-react-app/issues/3096 + +var hadRuntimeError = false; +var runtimeOptions = { + onError: function () { + hadRuntimeError = true; + }, + filename: "/static/js/bundle.js" +}; +ErrorOverlay.startReportingRuntimeErrors(runtimeOptions); +function clearConsole() { + // Clean up outdated compile errors, if any. + if (typeof console !== "undefined" && typeof console.clear === "function") { + console.clear(); + } +} +function handleSuccess() { + // Successful compilation. + clearConsole(); + isFirstCompilation = false; + hasCompileErrors = false; + hadRuntimeError = false; +} +function handleWarnings(warnings) { + //clearConsole(); + // var isHotUpdate = !isFirstCompilation; + isFirstCompilation = false; + hasCompileErrors = false; + + function printWarnings() { + // Print warnings to the console. + var formatted = formatWebpackMessages({ + warnings: warnings, + errors: [] + }); + + if (typeof console !== "undefined" && typeof console.warn === "function") { + for (var i = 0; i < formatted.warnings.length; i++) { + if (i === 5) { + console.warn("There were more warnings in other files.\n" + "You can find a complete log in the terminal."); + break; + } + + console.warn(stripAnsi(formatted.warnings[i])); + } + } + } + + printWarnings(); +} +function handleErrors(errors) { + //clearConsole(); + isFirstCompilation = false; + hasCompileErrors = true; // Format webpack messages. + + var formatted = formatWebpackMessages({ + errors: errors, + warnings: [] + }); + + if (Array.isArray(formatted.errors) && formatted.errors.length > 0) { + // Only show the first error. + ErrorOverlay.reportBuildError(formatted.errors[0]); + } else { + if (typeof console !== "undefined" && typeof console.error === "function") { + console.error("UNKNOWN ERROR from react-scripts-wptheme-error-overlay:handleErrors:", errors); + } + } // Do not attempt to reload now. + // We will reload on next success instead. + +} + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const ansiRegex = __webpack_require__(2); + +const stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; + +module.exports = stripAnsi; +module.exports.default = stripAnsi; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = options => { + options = Object.assign({ + onlyFirst: false + }, options); + + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, options.onlyFirst ? undefined : 'g'); +}; + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process) {!function(e,t){ true?module.exports=t():undefined}(window,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var u=t[r]={i:r,l:!1,exports:{}};return e[r].call(u.exports,u,u.exports,n),u.l=!0,u.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var u in e)n.d(r,u,function(t){return e[t]}.bind(null,u));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=16)}([function(e,t,n){e.exports=n(9)},function(e,t){t.getArg=function(e,t,n){if(t in e)return e[t];if(3===arguments.length)return n;throw new Error('"'+t+'" is a required argument.')};var n=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,r=/^data:.+\,.+$/;function u(e){var t=e.match(n);return t?{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}:null}function o(e){var t="";return e.scheme&&(t+=e.scheme+":"),t+="//",e.auth&&(t+=e.auth+"@"),e.host&&(t+=e.host),e.port&&(t+=":"+e.port),e.path&&(t+=e.path),t}function i(e){var n=e,r=u(e);if(r){if(!r.path)return e;n=r.path}for(var i,a=t.isAbsolute(n),l=n.split(/\/+/),c=0,s=l.length-1;s>=0;s--)"."===(i=l[s])?l.splice(s,1):".."===i?c++:c>0&&(""===i?(l.splice(s+1,c),c=0):(l.splice(s,2),c--));return""===(n=l.join("/"))&&(n=a?"/":"."),r?(r.path=n,o(r)):n}t.urlParse=u,t.urlGenerate=o,t.normalize=i,t.join=function(e,t){""===e&&(e="."),""===t&&(t=".");var n=u(t),a=u(e);if(a&&(e=a.path||"/"),n&&!n.scheme)return a&&(n.scheme=a.scheme),o(n);if(n||t.match(r))return t;if(a&&!a.host&&!a.path)return a.host=t,o(a);var l="/"===t.charAt(0)?t:i(e.replace(/\/+$/,"")+"/"+t);return a?(a.path=l,o(a)):l},t.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(n)},t.relative=function(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");for(var n=0;0!==t.indexOf(e+"/");){var r=e.lastIndexOf("/");if(r<0)return t;if((e=e.slice(0,r)).match(/^([^\/]+:\/)?\/*$/))return t;++n}return Array(n+1).join("../")+t.substr(e.length+1)};var a=!("__proto__"in Object.create(null));function l(e){return e}function c(e){if(!e)return!1;var t=e.length;if(t<9)return!1;if(95!==e.charCodeAt(t-1)||95!==e.charCodeAt(t-2)||111!==e.charCodeAt(t-3)||116!==e.charCodeAt(t-4)||111!==e.charCodeAt(t-5)||114!==e.charCodeAt(t-6)||112!==e.charCodeAt(t-7)||95!==e.charCodeAt(t-8)||95!==e.charCodeAt(t-9))return!1;for(var n=t-10;n>=0;n--)if(36!==e.charCodeAt(n))return!1;return!0}function s(e,t){return e===t?0:e>t?1:-1}t.toSetString=a?l:function(e){return c(e)?"$"+e:e},t.fromSetString=a?l:function(e){return c(e)?e.slice(1):e},t.compareByOriginalPositions=function(e,t,n){var r=e.source-t.source;return 0!==r?r:0!==(r=e.originalLine-t.originalLine)?r:0!==(r=e.originalColumn-t.originalColumn)||n?r:0!==(r=e.generatedColumn-t.generatedColumn)?r:0!==(r=e.generatedLine-t.generatedLine)?r:e.name-t.name},t.compareByGeneratedPositionsDeflated=function(e,t,n){var r=e.generatedLine-t.generatedLine;return 0!==r?r:0!==(r=e.generatedColumn-t.generatedColumn)||n?r:0!==(r=e.source-t.source)?r:0!==(r=e.originalLine-t.originalLine)?r:0!==(r=e.originalColumn-t.originalColumn)?r:e.name-t.name},t.compareByGeneratedPositionsInflated=function(e,t){var n=e.generatedLine-t.generatedLine;return 0!==n?n:0!==(n=e.generatedColumn-t.generatedColumn)?n:0!==(n=s(e.source,t.source))?n:0!==(n=e.originalLine-t.originalLine)?n:0!==(n=e.originalColumn-t.originalColumn)?n:s(e.name,t.name)}},function(e,t){function n(e,t){for(var n=0,r=e.length-1;r>=0;r--){var u=e[r];"."===u?e.splice(r,1):".."===u?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;n)e.unshift("..");return e}function r(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r=-1&&!t;u--){var o=u>=0?arguments[u]:process.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(e=o+"/"+e,t="/"===o.charAt(0))}return(t?"/":"")+(e=n(r(e.split("/"),(function(e){return!!e})),!t).join("/"))||"."},t.normalize=function(e){var o=t.isAbsolute(e),i="/"===u(e,-1);return(e=n(r(e.split("/"),(function(e){return!!e})),!o).join("/"))||o||(e="."),e&&i&&(e+="/"),(o?"/":"")+e},t.isAbsolute=function(e){return"/"===e.charAt(0)},t.join=function(){var e=Array.prototype.slice.call(arguments,0);return t.normalize(r(e,(function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e})).join("/"))},t.relative=function(e,n){function r(e){for(var t=0;t=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=t.resolve(e).substr(1),n=t.resolve(n).substr(1);for(var u=r(e.split("/")),o=r(n.split("/")),i=Math.min(u.length,o.length),a=i,l=0;l=1;--o)if(47===(t=e.charCodeAt(o))){if(!u){r=o;break}}else u=!1;return-1===r?n?"/":".":n&&1===r?"/":e.slice(0,r)},t.basename=function(e,t){var n=function(e){"string"!=typeof e&&(e+="");var t,n=0,r=-1,u=!0;for(t=e.length-1;t>=0;--t)if(47===e.charCodeAt(t)){if(!u){n=t+1;break}}else-1===r&&(u=!1,r=t+1);return-1===r?"":e.slice(n,r)}(e);return t&&n.substr(-1*t.length)===t&&(n=n.substr(0,n.length-t.length)),n},t.extname=function(e){"string"!=typeof e&&(e+="");for(var t=-1,n=0,r=-1,u=!0,o=0,i=e.length-1;i>=0;--i){var a=e.charCodeAt(i);if(47!==a)-1===r&&(u=!1,r=i+1),46===a?-1===t?t=i:1!==o&&(o=1):-1!==t&&(o=-1);else if(!u){n=i+1;break}}return-1===t||-1===r||0===o||1===o&&t===r-1&&t===n+1?"":e.slice(t,r)};var u="b"==="ab".substr(-1)?function(e,t,n){return e.substr(t,n)}:function(e,t,n){return t<0&&(t=e.length+t),e.substr(t,n)}},function(e,t,n){t.SourceMapGenerator=n(4).SourceMapGenerator,t.SourceMapConsumer=n(12).SourceMapConsumer,t.SourceNode=n(15).SourceNode},function(e,t,n){var r=n(5),u=n(1),o=n(6).ArraySet,i=n(11).MappingList;function a(e){e||(e={}),this._file=u.getArg(e,"file",null),this._sourceRoot=u.getArg(e,"sourceRoot",null),this._skipValidation=u.getArg(e,"skipValidation",!1),this._sources=new o,this._names=new o,this._mappings=new i,this._sourcesContents=null}a.prototype._version=3,a.fromSourceMap=function(e){var t=e.sourceRoot,n=new a({file:e.file,sourceRoot:t});return e.eachMapping((function(e){var r={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(r.source=e.source,null!=t&&(r.source=u.relative(t,r.source)),r.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(r.name=e.name)),n.addMapping(r)})),e.sources.forEach((function(t){var r=e.sourceContentFor(t);null!=r&&n.setSourceContent(t,r)})),n},a.prototype.addMapping=function(e){var t=u.getArg(e,"generated"),n=u.getArg(e,"original",null),r=u.getArg(e,"source",null),o=u.getArg(e,"name",null);this._skipValidation||this._validateMapping(t,n,r,o),null!=r&&(r=String(r),this._sources.has(r)||this._sources.add(r)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:null!=n&&n.line,originalColumn:null!=n&&n.column,source:r,name:o})},a.prototype.setSourceContent=function(e,t){var n=e;null!=this._sourceRoot&&(n=u.relative(this._sourceRoot,n)),null!=t?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[u.toSetString(n)]=t):this._sourcesContents&&(delete this._sourcesContents[u.toSetString(n)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},a.prototype.applySourceMap=function(e,t,n){var r=t;if(null==t){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');r=e.file}var i=this._sourceRoot;null!=i&&(r=u.relative(i,r));var a=new o,l=new o;this._mappings.unsortedForEach((function(t){if(t.source===r&&null!=t.originalLine){var o=e.originalPositionFor({line:t.originalLine,column:t.originalColumn});null!=o.source&&(t.source=o.source,null!=n&&(t.source=u.join(n,t.source)),null!=i&&(t.source=u.relative(i,t.source)),t.originalLine=o.line,t.originalColumn=o.column,null!=o.name&&(t.name=o.name))}var c=t.source;null==c||a.has(c)||a.add(c);var s=t.name;null==s||l.has(s)||l.add(s)}),this),this._sources=a,this._names=l,e.sources.forEach((function(t){var r=e.sourceContentFor(t);null!=r&&(null!=n&&(t=u.join(n,t)),null!=i&&(t=u.relative(i,t)),this.setSourceContent(t,r))}),this)},a.prototype._validateMapping=function(e,t,n,r){if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||t||n||r)&&!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&n))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:n,original:t,name:r}))},a.prototype._serializeMappings=function(){for(var e,t,n,o,i=0,a=1,l=0,c=0,s=0,f=0,p="",d=this._mappings.toArray(),h=0,g=d.length;h0){if(!u.compareByGeneratedPositionsInflated(t,d[h-1]))continue;e+=","}e+=r.encode(t.generatedColumn-i),i=t.generatedColumn,null!=t.source&&(o=this._sources.indexOf(t.source),e+=r.encode(o-f),f=o,e+=r.encode(t.originalLine-1-c),c=t.originalLine-1,e+=r.encode(t.originalColumn-l),l=t.originalColumn,null!=t.name&&(n=this._names.indexOf(t.name),e+=r.encode(n-s),s=n)),p+=e}return p},a.prototype._generateSourcesContent=function(e,t){return e.map((function(e){if(!this._sourcesContents)return null;null!=t&&(e=u.relative(t,e));var n=u.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null}),this)},a.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},a.prototype.toString=function(){return JSON.stringify(this.toJSON())},t.SourceMapGenerator=a},function(e,t,n){var r=n(10);t.encode=function(e){var t,n="",u=function(e){return e<0?1+(-e<<1):0+(e<<1)}(e);do{t=31&u,(u>>>=5)>0&&(t|=32),n+=r.encode(t)}while(u>0);return n},t.decode=function(e,t,n){var u,o,i,a,l=e.length,c=0,s=0;do{if(t>=l)throw new Error("Expected more digits in base 64 VLQ value.");if(-1===(o=r.decode(e.charCodeAt(t++))))throw new Error("Invalid base64 digit: "+e.charAt(t-1));u=!!(32&o),c+=(o&=31)<>1,1==(1&i)?-a:a),n.rest=t}},function(e,t,n){var r=n(1),u=Object.prototype.hasOwnProperty;function o(){this._array=[],this._set=Object.create(null)}o.fromArray=function(e,t){for(var n=new o,r=0,u=e.length;r=0&&eh;h++)if((g=s?y(r(D=e[h])[0],D[1]):y(e[h]))&&g instanceof c)return g;return new c(!1)}d=p.call(e)}for(v=d.next;!(D=v.call(d)).done;)if("object"==typeof(g=l(d,y,D.value,s))&&g&&g instanceof c)return g;return new c(!1)}).stop=function(e){return new c(!0,e)}},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e}},function(e,t,n){var r=n(8),u=n(24),o=n(32),i=n(63),a=r.Symbol,l=u("wks");e.exports=function(e){return l[e]||(l[e]=i&&a[e]||(i?a:o)("Symbol."+e))}},function(e,t,n){var r=n(5);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 0:return function(){return e.call(t)};case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,u){return e.call(t,n,r,u)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){(function(t){var n=function(e){return e&&e.Math==Math&&e};e.exports=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof t&&t)||Function("return this")()}).call(this,n(35))},function(e,t,n){var r=n(57),u=n(12),o=n(78),i=n(14).f;e.exports=function(e){var t=r.Symbol||(r.Symbol={});u(t,e)||i(t,e,{value:o.f(e)})}},function(e,t,n){var r=n(57),u=n(8),o=function(e){return"function"==typeof e?e:void 0};e.exports=function(e,t){return arguments.length<2?o(r[e])||o(u[e]):r[e]&&r[e][t]||u[e]&&u[e][t]}},function(e,t){e.exports=function(e){return"object"===typeof e?null!==e:"function"===typeof e}},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t,n){var r=n(16),u=n(53),o=n(2),i=n(30),a=Object.defineProperty;t.f=r?a:function(e,t,n){if(o(e),t=i(t,!0),o(n),u)try{return a(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){var r=n(3),u=n(45);e.exports=r?u:function(e){return Map.prototype.entries.call(e)}},function(e,t,n){var r=n(13);e.exports=!r((function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}))},function(e,t,n){var r=n(16),u=n(14),o=n(23);e.exports=r?function(e,t,n){return u.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(2),u=n(5),o=n(6)("species");e.exports=function(e,t){var n,i=r(e).constructor;return void 0===i||void 0==(n=r(i)[o])?t:u(n)}},function(e,t,n){var r=n(3),u=n(45);e.exports=r?u:function(e){return Set.prototype.values.call(e)}},function(e,t,n){var r=n(52),u=n(38);e.exports=function(e){return r(u(e))}},function(e,t,n){var r=n(8),u=n(24),o=n(17),i=n(12),a=n(39),l=n(55),c=n(25),s=c.get,f=c.enforce,d=String(l).split("toString");u("inspectSource",(function(e){return l.call(e)})),(e.exports=function(e,t,n,u){var l=!!u&&!!u.unsafe,c=!!u&&!!u.enumerable,s=!!u&&!!u.noTargetGet;"function"==typeof n&&("string"!=typeof t||i(n,"name")||o(n,"name",t),f(n).source=d.join("string"==typeof t?t:"")),e!==r?(l?!s&&e[t]&&(c=!0):delete e[t],c?e[t]=n:o(e,t,n)):c?e[t]=n:a(t,n)})(Function.prototype,"toString",(function(){return"function"==typeof this&&s(this).source||l.call(this)}))},function(e,t,n){var r=n(14).f,u=n(12),o=n(6)("toStringTag");e.exports=function(e,t,n){e&&!u(e=n?e:e.prototype,o)&&r(e,o,{configurable:!0,value:t})}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(3),u=n(90);(e.exports=function(e,t){return u[e]||(u[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.4.0",mode:r?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(e,t,n){var r,u,o,i=n(91),a=n(8),l=n(11),c=n(17),s=n(12),f=n(31),d=n(26),p=a.WeakMap;if(i){var h=new p,m=h.get,g=h.has,v=h.set;r=function(e,t){return v.call(h,e,t),t},u=function(e){return m.call(h,e)||{}},o=function(e){return g.call(h,e)}}else{var D=f("state");d[D]=!0,r=function(e,t){return c(e,D,t),t},u=function(e){return s(e,D)?e[D]:{}},o=function(e){return s(e,D)}}e.exports={set:r,get:u,has:o,enforce:function(e){return o(e)?u(e):r(e,{})},getterFor:function(e){return function(t){var n;if(!l(t)||(n=u(t)).type!==e)throw TypeError("Incompatible receiver, "+e+" required");return n}}}},function(e,t){e.exports={}},function(e,t,n){var r=n(41),u=Math.min;e.exports=function(e){return e>0?u(r(e),9007199254740991):0}},function(e,t){e.exports={}},function(e,t,n){var r=n(38);e.exports=function(e){return Object(r(e))}},function(e,t,n){var r=n(11);e.exports=function(e,t){if(!r(e))return e;var n,u;if(t&&"function"==typeof(n=e.toString)&&!r(u=n.call(e)))return u;if("function"==typeof(n=e.valueOf)&&!r(u=n.call(e)))return u;if(!t&&"function"==typeof(n=e.toString)&&!r(u=n.call(e)))return u;throw TypeError("Can\'t convert object to primitive value")}},function(e,t,n){var r=n(24),u=n(32),o=r("keys");e.exports=function(e){return o[e]||(o[e]=u(e))}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol("+String(void 0===e?"":e)+")_"+(++n+r).toString(36)}},function(e,t,n){var r=n(2),u=n(98),o=n(42),i=n(26),a=n(99),l=n(54),c=n(31)("IE_PROTO"),s=function(){},f=function(){var e,t=l("iframe"),n=o.length;for(t.style.display="none",a.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(" + `; + } + + try { + _webServer = new https.createServer( + { + cert: fs.readFileSync(_configSslCert), + key: fs.readFileSync(_configSslKey) + }, + (req, res) => { + res.writeHead(200); + res.end(getWsClientResp(_configHost, _serverPort)); + } + ); + } catch (err) { + console.log("Failed to start SSL server. ERR:", err); + process.exit(1); + } + + _webSocketServer = new WebSocket.Server({ server: _webServer }); + _webSocketServerSetup(); + + _webServer.listen(_serverPort); +} + +const wpThemeServer = { + getClientInjectString: function(mode, token) { + if (_serverConfig.enable !== true || typeof mode !== "string") { + return ""; + } + + if (_clientInjectString) { + return _clientInjectString; + } + + const phpStuff = ``; + const jsTags = [ + "\n", + "\n" + ]; + const jsCall = `\n`; + + let toInject = []; + switch (mode) { + case "afterToken": + // note in this case, we put the token back into the file (i.e. the token is something you want to keep in the file like ""). + toInject = [token, phpStuff, jsTags.join("\n"), jsCall]; + break; + case "beforeToken": + // note in this case, we put the token back into the file (i.e. the token is something you want to keep in the file like ""). + toInject = [phpStuff, jsTags.join("\n"), jsCall, token]; + break; + case "endOfFile": + case "replaceToken": + toInject = [phpStuff, jsTags.join("\n"), jsCall]; + break; + default: + console.log(chalk.magenta(`wpstart::injectWpThemeClient: unknown inject mode: ${mode}.`)); + console.log(`Available inject modes: ${chalk.cyan("disable, afterToken, beforeToken, replaceToken, endOfFile")}`); + process.exit(); + } + + _clientInjectString = toInject.join("\n"); + + return _clientInjectString; + }, + startServer: function(paths) { + try { + _serverConfig = _getUserConfig(paths, process.env.NODE_ENV).wpThemeServer; + } catch (err) { + console.log("unable to get wpThemeServer config from user config. Err:", err); + process.exit(1); + } + + _configHost = _serverConfig && typeof _serverConfig.host === "string" && _serverConfig.host.length > 0 ? _serverConfig.host : "127.0.0.1"; + _configPort = _serverConfig && typeof _serverConfig.port === "number" ? _serverConfig.port : null; + _serverPort = parseInt(process.env.PORT, 10) || _configPort || 8090; + + if (_serverPort > 0) { + _configSslCert = _serverConfig && typeof _serverConfig.sslCert === "string" && _serverConfig.sslCert.length > 0 ? _serverConfig.sslCert : null; + _configSslKey = _serverConfig && typeof _serverConfig.sslKey === "string" && _serverConfig.sslKey.length > 0 ? _serverConfig.sslKey : null; + + if (typeof _configSslCert === "string" && typeof _configSslKey === "string") { + _webSocketServerProtocol = "wss"; + _startSslServer(); + } else { + _webSocketServerProtocol = "ws"; + _startNonSslServer(); + } + + console.log("Browser Refresh Server ready."); + } + }, + update: function(stats, msgType) { + if (stats) { + if (typeof stats.hasErrors === "undefined") { + // This is probably a TypeScript deferred message + switch (msgType) { + case _typeBuildError: + _sendMessage(_typeBuildError, stats); + break; + case _typeBuildWarning: + _sendMessage(_typeBuildWarning, stats); + break; + } + } else { + // Normal Webpack compile message + if (typeof stats.hasErrors === "function " && stats.hasErrors()) { + _sendMessage(_typeBuildError, stats); + } else if (typeof stats.hasWarnings === "function " && stats.hasWarnings()) { + _sendMessage(_typeBuildWarning, stats); + } else { + _sendMessage(_typeBuildContentChanged, stats); + } + } + } + } +}; + +module.exports = wpThemeServer; diff --git a/packages/create-react-wptheme/.npmignore b/packages/create-react-wptheme/.npmignore new file mode 100644 index 0000000..7bd879d --- /dev/null +++ b/packages/create-react-wptheme/.npmignore @@ -0,0 +1,3 @@ +/.git +/.gitignore +.gitattributes diff --git a/packages/create-react-wptheme/.npmrc b/packages/create-react-wptheme/.npmrc new file mode 100644 index 0000000..46db3e1 --- /dev/null +++ b/packages/create-react-wptheme/.npmrc @@ -0,0 +1,2 @@ +package-lock=false +shrinkwrap=false diff --git a/packages/create-react-wptheme/LICENSE b/packages/create-react-wptheme/LICENSE new file mode 100644 index 0000000..d43c3b4 --- /dev/null +++ b/packages/create-react-wptheme/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-present, https://github.com/devloco + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/createReactWpTheme.js b/packages/create-react-wptheme/createReactWpTheme.js similarity index 94% rename from createReactWpTheme.js rename to packages/create-react-wptheme/createReactWpTheme.js index 0d72e89..a1bfb5e 100644 --- a/createReactWpTheme.js +++ b/packages/create-react-wptheme/createReactWpTheme.js @@ -50,7 +50,7 @@ const _wpThemeVersion = packageJson.version; const _createReactAppVersion = _wpThemeVersion.split("-wp.")[0]; // Check these!!!! -const _reactScriptsWpThemeVersion = "3.2.0-wp.2"; +const _reactScriptsWpThemeVersion = "3.3.0-wp.2"; const _getScriptsPath = function() { return scriptsFromNpm(); }; @@ -110,7 +110,7 @@ const program = new commander.Command(packageJson.name) .option("--info", "print environment debug info") .option("--use-npm", "force downloading packages using npm instead of yarn (if both are installed)") .option("--use-pnp") - .option("--typescript") + .option("--typescript", "set your theme to use TypeScript") .allowUnknownOption() .on("--help", () => { console.log(` Only ${chalk.green("")} is required.`); @@ -161,7 +161,7 @@ function printValidationResults(results) { console.log(program.name() + " version: " + chalk.magenta(_wpThemeVersion)); console.log("@devloco/react-scripts-wptheme version: " + chalk.magenta(_reactScriptsWpThemeVersion)); -console.log("create-react-app version: " + chalk.magenta(_createReactAppVersion)); +console.log(); createApp(projectName, program.verbose, program.scriptsVersion, program.useNpm, program.usePnp, program.typescript); function createApp(name, verbose, version, useNpm, usePnp, useTypescript, template) { @@ -172,6 +172,7 @@ function createApp(name, verbose, version, useNpm, usePnp, useTypescript, templa fs.ensureDirSync(name); console.log(`Creating a new React WP theme in ${chalk.green(root)}.`); + console.log(`Using Create React App ${chalk.green(_createReactAppVersion)} to scaffold the theme's source code...`); console.log(); let useYarn = useNpm ? false : shouldUseYarn(); @@ -194,6 +195,14 @@ function shouldUseYarn() { function createWpTheme(root, appName, version, verbose, originalDirectory, template, useYarn, usePnp, useTypescript) { const packageToInstall = "create-react-app"; + if (useTypescript === true) { + template = "wptheme-typescript"; + } + + if (typeof template !== "string" || template.trim().length === 0) { + template = "wptheme"; + } + return Promise.resolve(packageToInstall) .then((packageName) => checkIfOnline(useYarn).then((isOnline) => ({ @@ -207,7 +216,7 @@ function createWpTheme(root, appName, version, verbose, originalDirectory, templ } let createWpThemeReactRoot = "react-src"; - createReactApp(createWpThemeReactRoot, appName, version, verbose, originalDirectory, template, useYarn, usePnp, useTypescript); + createReactApp(createWpThemeReactRoot, appName, version, verbose, originalDirectory, template, useYarn, usePnp); }) .catch((reason) => { console.log(); @@ -227,7 +236,7 @@ function createWpTheme(root, appName, version, verbose, originalDirectory, templ }); } -function createReactApp(createWpThemeReactRoot, appName, version, verbose, originalDirectory, template, useYarn, usePnp, useTypescript) { +function createReactApp(createWpThemeReactRoot, appName, version, verbose, originalDirectory, template, useYarn, usePnp) { return new Promise((resolve, reject) => { let command = "npx"; @@ -247,9 +256,8 @@ function createReactApp(createWpThemeReactRoot, appName, version, verbose, origi args.push("--use-pnp"); } - if (useTypescript) { - args.push("--typescript"); - } + args.push("--template"); + args.push(template); let scriptsPath = _getScriptsPath(); args.push("--scripts-version"); diff --git a/index.js b/packages/create-react-wptheme/index.js similarity index 100% rename from index.js rename to packages/create-react-wptheme/index.js diff --git a/packages/create-react-wptheme/package.json b/packages/create-react-wptheme/package.json new file mode 100644 index 0000000..b5d75b4 --- /dev/null +++ b/packages/create-react-wptheme/package.json @@ -0,0 +1,54 @@ +{ + "name": "create-react-wptheme", + "version": "3.3.0-wp.2", + "description": "Create React-enabled WP themes.", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://github.com/devloco/create-react-wptheme.git" + }, + "keywords": [ + "wordpress", + "create-react-app", + "wordpress-theme", + "wordpress-development", + "wordpress-starter-theme", + "wordpress-api", + "reactjs", + "react", + "react-theme", + "wordpress-server", + "react-tutorial", + "react-wordpress-themes", + "php" + ], + "author": "devloco", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "bugs": { + "url": "https://github.com/devloco/create-react-wptheme/issues" + }, + "files": [ + "index.js", + "createReactWpTheme.js" + ], + "homepage": "https://github.com/devloco/create-react-wptheme#readme", + "bin": { + "create-react-wptheme": "./index.js" + }, + "dependencies": { + "chalk": "2.4.2", + "commander": "2.20.0", + "cross-spawn": "6.0.5", + "envinfo": "7.3.1", + "fs-extra": "7.0.1", + "semver": "6.3.0", + "tmp": "0.0.33", + "validate-npm-package-name": "3.0.0" + } +}