UNPKG

@swplabs/peanutforwp

Version:

Peanut for WordPress. Build your themes and blocks with components.

1,231 lines (1,134 loc) 35.2 kB
/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 980: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const nodePath = __webpack_require__(928); const envVars = __webpack_require__(471); const { engines: { node: nodeVersion }, dependencies, version } = __webpack_require__(330); const nodeEnv = envVars.get('NODE_ENV') || 'production'; const rootDir = nodePath.resolve(__dirname, '../'); const serverSideEventHost = `${envVars.get('PFWP_SSE_HOST')}:${envVars.get('PFWP_SSE_PORT')}`; const serverSideEventTimeout = 10000; const debugModeInterval = 5000; const appSrcPath = envVars.get('PFWP_APP_SRC_PATH'); const directoryEntrySrcPath = envVars.get('PFWP_DIR_ENT_SRC_PATH'); const isDebugMode = () => envVars.getBoolean('PFWP_DEBUG') === true; const enableWhiteboard = () => envVars.getBoolean('PFWP_ENABLE_WB') === true; const enableHMR = () => envVars.getBoolean('PFWP_ENABLE_HMR') === true && envVars.getBoolean('PFWP_SECONDARY') !== true; const enableTS = () => envVars.getBoolean('PFWP_ENABLE_TS') === true; const hotRefreshEnabled = srcType => enableHMR() && nodeEnv === 'development' && ['blocks', 'plugins' /* , 'whiteboard'*/].includes(srcType); const isWebTarget = ({ buildType }) => !['server'].includes(buildType); const isHotRefreshEntry = ({ srcType, entryKey }) => enableHMR() && nodeEnv === 'development' && ['blocks', 'plugins'].includes(srcType) && ['editor'].includes(entryKey); /* || (srcType === 'whiteboard' && entryKey === 'view')*/ const getHotMiddlewareEntry = ({ srcType, buildType }) => `webpack-hot-middleware/client?name=${srcType}_${buildType}&timeout=${serverSideEventTimeout}&path=${encodeURIComponent(`${serverSideEventHost}/__webpack_hmr`)}`; const getAppSrcPath = srcType => { return srcType === 'whiteboard' ? `${rootDir}/src` : appSrcPath; }; const getDirectoryEntrySrcPath = srcType => srcType === 'whiteboard' ? '' : directoryEntrySrcPath; const isCoreDev = () => envVars.getBoolean('PFWP_CORE_DEV') === true; const isCLI = () => envVars.getBoolean('PFWP_IS_CLI') === true; const getCLICommand = () => envVars.get('PFWP_CMD') || 'develop'; const getEnv = () => envVars.get('ENVIRONMENT') || 'prod'; const getNodeEnv = () => envVars.get('NODE_ENV') || 'production'; module.exports = { hotRefreshEnabled, isWebTarget, isHotRefreshEntry, getHotMiddlewareEntry, getAppSrcPath, getDirectoryEntrySrcPath, isCoreDev, isCLI, isDebugMode, enableWhiteboard, enableHMR, enableTS, getCLICommand, getEnv, getNodeEnv, corejs: parseFloat(dependencies['core-js']), node: process.version ? `${parseFloat(process.version.replace('v', ''))}` : parseFloat(nodeVersion.replace(/[\=\>\<]/g, '')), browsers: ['last 2 versions, not dead'], version, reactVersion: dependencies['react'], reactDOMVersion: dependencies['react-dom'], appSrcPath, directoryEntrySrcPath, rootDir, debugModeInterval }; /***/ }), /***/ 471: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const nconf = __webpack_require__(88); const cwd = process.cwd(); const fs = __webpack_require__(896); // Pull in ENV vars nconf.env(['ENVIRONMENT', 'NODE_ENV', 'PFWP_DEBUG', 'PFWP_COMPONENTS', 'PFWP_BUILD', 'PFWP_EXPORT_TYPE', 'PFWP_DIST', 'PFWP_WB_PUBLIC_PATH', 'PFWP_WP_HOST', 'PFWP_WP_PUBLIC_PATH', 'PFWP_CSS_IN_JS', 'PFWP_APP_SRC_PATH', 'PFWP_WP_ROOT', 'PFWP_THEME_PATH', 'PFWP_DIR_ENT_SRC_PATH', 'PFWP_CORE_BLOCK_FILTERS', 'PFWP_WB_PORT', 'PFWP_WB_HTTPS_PORT', 'PFWP_WB_ENABLE_HTTPS', 'PFWP_SSE_HOST', 'PFWP_SSE_PORT', 'PFWP_SSE_ENABLE_HTTPS', 'PFWP_SSE_HTTPS_PORT', 'PFWP_WB_HEAD_COMPONENTS', 'PFWP_WB_FOOTER_COMPONENTS', 'PFWP_CORE_DEV', 'PFWP_IS_CLI', 'PFWP_DATA_MODE', 'PFWP_CONFIG_HOOKS', 'PFWP_CONFIG_ESLINT', 'PFWP_CONFIG_WEBPACK', 'PFWP_ENABLE_HMR', 'PFWP_ENABLE_WB', 'PFWP_ENABLE_TS', 'PFWP_PRIMARY', 'PFWP_SECONDARY', 'PFWP_CMD']); let config = {}; try { // TODO: add method so that if "fileConfData" passed in to require statement in "parent" file, skip this const configFile = fs.readFileSync(`${nconf.get('PFWP_APP_SRC_PATH') || cwd}/peanut.config.json`, 'utf8'); config = JSON.parse(configFile); } catch (e) { if (e?.code === 'ENOENT') { throw new Error(`A peanut.config.json file was not found.${e?.message ? `\nError Message: ${e?.message}` : ''}`); } else { throw e; } } const defaultConfig = { ENVIRONMENT: 'local', NODE_ENV: 'development', PFWP_BUILD: 'stack', PFWP_DIST: 'develop', PFWP_CMD: 'develop', PFWP_DEBUG: 'false', PFWP_CSS_IN_JS: 'false', PFWP_APP_SRC_PATH: cwd, PFWP_DATA_MODE: 'path', PFWP_DIR_ENT_SRC_PATH: '', PFWP_WP_PUBLIC_PATH: '/', PFWP_COMP_ALLOW_LIST: [], PFWP_CORE_BLOCK_FILTERS: {}, PFWP_ENABLE_WB: false, PFWP_ENABLE_TS: false, PFWP_WB_PORT: 5000, PFWP_WB_HTTPS_PORT: 9000, PFWP_WB_ENABLE_HTTPS: false, PFWP_ENABLE_HMR: true, PFWP_WP_HOST: 'http://localhost', PFWP_SSE_HOST: nconf.get('PFWP_WP_HOST') || config.PFWP_WP_HOST || 'http://localhost', PFWP_SSE_PORT: 5050, PFWP_SSE_ENABLE_HTTPS: false, PFWP_SSE_HTTPS_PORT: 9090, PFWP_WB_HEAD_COMPONENTS: [], PFWP_WB_FOOTER_COMPONENTS: [], PFWP_CORE_DEV: false, PFWP_IS_CLI: '', ...config }; // TODO: add wp.hooks import so that we can override envvars programatically // Set the defaults for all environments nconf.defaults(defaultConfig); // Method to convert env string to booleans nconf.getBoolean = function (envVarName) { const value = nconf.get(envVarName); let booleanValue = false; if (value === 'true' || value === true) { booleanValue = true; } else if (value === null) { console.log('environment variable ' + envVarName + ' not found'); } return booleanValue; }; module.exports = nconf; /***/ }), /***/ 806: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const http = __webpack_require__(611); const https = __webpack_require__(692); const { readFileSync } = __webpack_require__(896); const extendServer = server => { const connections = {}; server.on('connection', conn => { const key = conn.remoteAddress + ':' + conn.remotePort; connections[key] = conn; conn.on('close', () => { delete connections[key]; }); }); server.destroy = () => { // server.close(cb); Object.keys(connections).forEach(key => { connections[key].destroy(); }); return new Promise((resolve, reject) => { server.close(err => { if (err) { reject(err); } else { resolve(); } }); }); }; }; const createServer = ({ env, port, httpsPort, requestHandler }) => { let httpsServer; const httpServer = http.createServer({}, requestHandler); httpServer.listen(port, () => { console.log(`[server] App runing on http://localhost:${port}`); console.log('[server]', 'Environment set to: ' + env); }); extendServer(httpServer); if (httpsPort) { httpsServer = https.createServer({ key: readFileSync('./certs/localhost.key.pem'), cert: readFileSync('./certs/localhost.cert.pem'), allowHTTP1: true }, requestHandler); httpsServer.listen(httpsPort, () => { console.log('[server]', 'HTTPS is enabled and running on https://localhost:' + httpsPort); }); extendServer(httpsServer); } return { httpServer, httpsServer }; }; module.exports = { createServer }; /***/ }), /***/ 498: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const zlib = __webpack_require__(106); const getGzipData = function ({ acceptEncoding, content }) { // Compressed response if (/\bgzip\b/.test(acceptEncoding)) { return { headers: { 'Content-Encoding': 'gzip' }, content: zlib.gzipSync(content) }; } else if (/\bdeflate\b/.test(acceptEncoding)) { return { headers: { 'Content-Encoding': 'deflate' }, content: zlib.deflateSync(content) }; } else { return { headers: {}, content }; } }; module.exports = { getGzipData }; /***/ }), /***/ 751: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const url = __webpack_require__(16); const parse = url.parse; const Url = url.Url; function parseurl(req) { let url = req.url; if (url === undefined) { // URL is undefined return undefined; } let parsed = req._parsedUrl; if (fresh(url, parsed)) { // Return cached URL parse return parsed; } // Parse the URL parsed = fastparse(url); parsed._raw = url; return req._parsedUrl = parsed; } function originalurl(req) { let url = req.originalUrl; if (typeof url !== 'string') { // Fallback return parseurl(req); } let parsed = req._parsedOriginalUrl; if (fresh(url, parsed)) { // Return cached URL parse return parsed; } // Parse the URL parsed = fastparse(url); parsed._raw = url; return req._parsedOriginalUrl = parsed; } function fastparse(str) { if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { return parse(str); } let pathname = str; let query = null; let search = null; // This takes the regexp from https://github.com/joyent/node/pull/7878 // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ // And unrolls it into a for loop for (let i = 1; i < str.length; i++) { switch (str.charCodeAt(i)) { case 0x3f /* ? */: if (search === null) { pathname = str.substring(0, i); query = str.substring(i + 1); search = str.substring(i); } break; case 0x09: /* \t */ case 0x0a: /* \n */ case 0x0c: /* \f */ case 0x0d: /* \r */ case 0x20: /* */ case 0x23: /* # */ case 0xa0: case 0xfeff: return parse(str); } } let url = Url !== undefined ? new Url() : {}; url.path = str; url.href = str; url.pathname = pathname; url.query = query; url.search = search; return url; } function fresh(url, parsedUrl) { return typeof parsedUrl === 'object' && parsedUrl !== null && (Url === undefined || parsedUrl instanceof Url) && parsedUrl._raw === url; } module.exports = parseurl; module.exports.original = originalurl; /***/ }), /***/ 103: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* Adapted from: https://raw.githubusercontent.com/creationix/node-router/master/lib/node-router.js */ const { debug: log } = __webpack_require__(19); const parseUrl = __webpack_require__(751); let routes = []; // Adds a route the the current server const addRoute = (method, pattern, handler, format) => { if (typeof pattern === 'string') { pattern = new RegExp('^' + pattern + '$', 'i'); } let route = { method, pattern, handler, match: {} }; if (format !== undefined) { route.format = format; } routes.push(route); }; const get = (pattern, handler) => { return addRoute('GET', pattern, handler); }; const post = (pattern, handler, format) => { return addRoute('POST', pattern, handler, format); }; const put = (pattern, handler, format) => { return addRoute('PUT', pattern, handler, format); }; const del = (pattern, handler) => { return addRoute('DELETE', pattern, handler); }; const head = (pattern, handler) => { return addRoute('HEAD', pattern, handler); }; const getRoutes = () => { return routes; }; const match = req => { const path = parseUrl(req).pathname; log('[server:router]', path, req.method); let i, l; for (i = 0, l = routes.length; i < l; i += 1) { let route = routes[i]; if (req.method === route.method) { const match = path.match(route.pattern); if (match?.[0]?.length > 0) { log('[server:router] Match found:', match[0]); if (match[1]) { req.locals = req.locals || {}; req.locals.route = { match: match.groups || [...match].splice(-3) }; } return route; } } } return null; }; module.exports = { get, post, put, del, head, getRoutes, match }; /***/ }), /***/ 808: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { getGzipData } = __webpack_require__(498); module.exports = async (req, res) => { const { defaultRouter, cacheTimings: { minorSeconds } } = req; const route = defaultRouter.match(req); const acceptEncoding = req && req.headers && typeof req.headers['accept-encoding'] === 'string' ? req.headers['accept-encoding'] : ''; const status = route !== null && typeof route.handler === 'function' ? 200 : 404; // Compressed response if (status === 200) { const { headers = {}, content = '' } = getGzipData({ acceptEncoding, content: await route.handler({ req, res }) }); res.writeHead(status, { 'Content-Type': 'text/html', 'Cache-Control': `max-age=${minorSeconds}`, ...headers }); res.end(content); } else { res.writeHead(404, { 'Content-Type': 'application/json' }); const response = { status: 404 }; res.end(JSON.stringify(response)); } }; /***/ }), /***/ 267: /***/ ((module) => { // TODO: inject app version by passing options in and returning the 'async' function module.exports = async (req, res, next) => { if (req.url === '/_healthcheck') { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ version: '' })); } else { await next(); } }; /***/ }), /***/ 133: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = { default: __webpack_require__(808), serveStatic: __webpack_require__(475), health: __webpack_require__(267), sse: __webpack_require__(136) }; /***/ }), /***/ 136: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { getGzipData } = __webpack_require__(498); module.exports = async (req, res) => { const { defaultRouter, cacheTimings: { minorSeconds } } = req; const route = defaultRouter.match(req); const acceptEncoding = req && req.headers && typeof req.headers['accept-encoding'] === 'string' ? req.headers['accept-encoding'] : ''; const status = route !== null && typeof route.handler === 'function' ? 200 : 404; // Compressed response if (status === 200) { const { headers = {}, content = '' } = getGzipData({ acceptEncoding, content: await route.handler({ req }) }); res.writeHead(status, { 'Content-Type': 'text/html', 'Cache-Control': `max-age=${minorSeconds}`, ...headers }); res.end(content); } else { res.writeHead(404, { 'Content-Type': 'application/json' }); const response = { status: 404 }; res.end(JSON.stringify(response)); } }; /***/ }), /***/ 475: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { debug: log } = __webpack_require__(19); const parseUrl = __webpack_require__(751); const { getGzipData } = __webpack_require__(498); const { resolve, extname } = __webpack_require__(928); const fs = __webpack_require__(896); const allowedMimes = { woff: 'application/font-woff', woff2: 'application/font-woff2', js: 'application/javascript', json: 'application/json', map: 'application/json', xml: 'application/xml', otf: 'font/otf', gif: 'image/gif', jpg: 'image/jpeg', png: 'image/png', svg: 'image/svg+xml', css: 'text/css', html: 'text/html', txt: 'text/plain', eot: 'application/vnd.ms-fontobject"', ttf: 'application/x-font-ttf', ico: 'image/x-icon', xsl: 'text/xsl' }; const serveStatic = (root, options) => { if (!root) { throw new TypeError('root path required'); } if (typeof root !== 'string') { throw new TypeError('root path must be a string'); } // copy options object let opts = { ...options }; // setup options for send opts.root = resolve(root); return async (req, res, next) => { if (req.method !== 'GET' && req.method !== 'HEAD') { // method not allowed res.statusCode = 405; res.setHeader('Allow', 'GET, HEAD'); res.setHeader('Content-Length', '0'); res.end(); return; } const originalUrl = parseUrl.original(req), acceptEncoding = req && req.headers && typeof req.headers['accept-encoding'] === 'string' ? req.headers['accept-encoding'] : ''; let path = parseUrl(req).pathname; const { basePath } = opts; if (basePath) path = path.replace(basePath, ''); // make sure redirect occurs at mount if (path === '/' && originalUrl.pathname.substr(-1) !== '/') { path = ''; } const file = opts.root + collapseLeadingSlashes(path); try { const ext = extname(file); if (!(typeof ext === 'string' && ext.length > 0)) { throw new TypeError('Static request is a directory and not a file'); } const mime = typeof allowedMimes[ext.substring(1)] !== 'undefined' ? allowedMimes[ext.substring(1)] : null; if (mime === null) { // throw new Error('File not supported: ' + path); log(`[server:static:${opts.root}] File not supported:`, path); await next(); return; } else { const stat = fs.statSync(file); if (stat.isDirectory()) { throw new TypeError('Static request is a directory and not a file'); } let data = fs.readFileSync(file); let headers = { 'content-length': stat.size, 'last-modified': stat.mtime.toUTCString(), 'access-control-allow-origin': '*', 'content-type': mime, 'cache-control': 'max-age=' + opts.majorSeconds }; // if css or js compress if (['application/javascript', 'text/css'].includes(mime)) { const { headers: gzHeaders = {}, content = '' } = getGzipData({ acceptEncoding, content: data }); data = content; headers = { ...headers, ...gzHeaders, 'content-length': Buffer.byteLength(data) }; } res.writeHead(200, headers); res.end(data); } } catch (e) { if (e.code && e.code === 'ENOENT') { if (typeof next !== 'function') log('[server:static]', opts.root, 'File not found', path); } else if (!(e instanceof TypeError)) { log('[server:static]', opts.root, 'Error caught:', e.message); } await next(); return; } }; }; const collapseLeadingSlashes = str => { let i; for (i = 0; i < str.length; i++) { if (str.charCodeAt(i) !== 0x2f) { break; } } return i > 1 ? '/' + str.substr(i) : str; }; module.exports = serveStatic; /***/ }), /***/ 19: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* global __DEBUG__ */ const fs = __webpack_require__(896); const colors = { reset: '\u001b[0m', red: '\u001b[31m', magenta: '\u001b[35m', yellow: '\u001b[33m', blue: '\x1b[34m', green: '\x1b[32m' }; const debug = (...messages) => { if (false) {} }; const toCamelCase = (str = '') => { return str.replace(/[^a-z0-9]/gi, ' ').toLowerCase().split(' ').map((el, ind) => ind === 0 ? el : el[0].toUpperCase() + el.substring(1, el.length)).join(''); }; const validateEnvVarConfig = envVars => { const config = { PFWP_WP_ROOT: envVars.get('PFWP_WP_ROOT'), PFWP_THEME_PATH: envVars.get('PFWP_THEME_PATH') }; // Check existence of wordpress root and theme paths if (!config.PFWP_WP_ROOT) { throw new Error(`The WordPress root (PFWP_WP_ROOT) value in your peanut.config.json was not defined.`); } else if (!fs.existsSync(config.PFWP_WP_ROOT)) { throw new Error(`The WordPress root directory (PFWP_WP_ROOT) defined in your peanut.config.json does not exist.`); } if (!config.PFWP_THEME_PATH) { throw new Error(`The WordPress theme path (PFWP_THEME_PATH) value in your peanut.config.json was not defined.`); } else if (!fs.existsSync(`${config.PFWP_WP_ROOT}${config.PFWP_THEME_PATH}`)) { console.warn(`The WordPress theme directory (PFWP_THEME_PATH) defined in your peanut.config.json does not exist.`); } }; module.exports = { debug, toCamelCase, validateEnvVarConfig }; /***/ }), /***/ 42: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { debug: log } = __webpack_require__(19); const { buildClientAssets, getServerFile, resetAssets, htmlTemplate, getConfigs } = __webpack_require__(812); const { renderToString } = __webpack_require__(468); const cntrlResponses = {}; const controller = ({ route }) => { const { pfwpConfig } = getConfigs(); return async () => { const { id, srcType, buildType } = route; if (typeof cntrlResponses[id] !== 'string') { log('[server] Getting base response:', id); resetAssets({ srcType, buildType }); const reactTemplate = (await getServerFile(`js_render_${id}.js`))?.default; const { js = [], css = [] } = buildClientAssets({ srcType, buildType, id }) || {}; cntrlResponses[id] = typeof reactTemplate === 'function' ? htmlTemplate({ id, reactHtml: renderToString(reactTemplate({ config: pfwpConfig })), js, css, config: pfwpConfig }) : '<html><head></head><body>No Template Found for Page</body></html>'; } else { log('[server] Returning cached base response:', id); } return cntrlResponses[id]; }; }; module.exports = { controller }; /***/ }), /***/ 756: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { debug: log } = __webpack_require__(19); const { buildClientAssets, getServerFile, resetAssets } = __webpack_require__(812); const cntrlResponses = {}; const controller = ({ route }) => { return async () => { const { id, title, srcType, buildType } = route; if (typeof cntrlResponses[id] !== 'string') { log('[server] Getting base response:', id); resetAssets({ srcType, buildType }); const template = await getServerFile(`hbs_${id}.js`); const { js = '', css = '' } = buildClientAssets({ id, srcType, buildType }) || {}; cntrlResponses[id] = typeof template === 'function' ? template({ title, header: title, js, css }) : '<html><head></head><body>No Template Found for Page</body></html>'; } else { log('[server] Returning cached base response:', id); } return cntrlResponses[id]; }; }; module.exports = { controller }; /***/ }), /***/ 812: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const { debug: log } = __webpack_require__(19); const envVars = __webpack_require__(471); const { reactVersion, reactDOMVersion } = __webpack_require__(980); const wbPublicPath = envVars.get('PFWP_WB_PUBLIC_PATH') || '/'; const wordpressPublicPath = envVars.get('PFWP_WP_PUBLIC_PATH'); const serverImports = {}; let buildAssets = {}; let pfwpConfig; let appConfig; const setConfigs = (app, pfwp) => { appConfig = app; pfwpConfig = pfwp; }; const getConfigs = () => { return { pfwpConfig, appConfig }; }; // TODO: Add max limit to "cached" files const getServerFile = async key => { if (typeof serverImports[key] === 'undefined') { try { log('[server] Importing file:', key); serverImports[key] = (await import(/* webpackIgnore: true */`./${key}`)).default; } catch (e) { log('[server] Error importing file:', key, e?.message); } } else { log('[server] Already imported:', key); } return serverImports[key]; }; const resetAssets = ({ srcType }) => { buildAssets[`${srcType}_elements`] = {}; }; const addAssetData = ({ id, type, assetIndex, name, publicPath, data }) => { if (!buildAssets[assetIndex][id][type]) { buildAssets[assetIndex][id][type] = {}; } if (typeof buildAssets[assetIndex][id][type][name] === 'undefined') { buildAssets[assetIndex][id][type][name] = true; data.push({ parentId: id, url: `${publicPath}${name}` }); log(`[server] Generated ${type} client asset:`, assetIndex, id, name); } else { log('[server] Already generated client asset:', assetIndex, id, name); } }; const buildClientAssets = ({ srcType, id }) => { const assetIndex = `${srcType}_elements`; if (!buildAssets[assetIndex]) buildAssets[assetIndex] = {}; if (!buildAssets[assetIndex][id]) buildAssets[assetIndex][id] = {}; const publicPath = srcType === 'whiteboard' ? wbPublicPath : wordpressPublicPath; const jsData = []; const cssData = []; const compilation = srcType === 'whiteboard' ? appConfig.compilations[assetIndex] : pfwpConfig.compilations[assetIndex]; const clientAssets = compilation.chunk_groups[`view_${id}`]; const eachAsset = ({ name, type }) => addAssetData({ id, type, assetIndex, name, publicPath, data: type === 'js' ? jsData : cssData }); if (clientAssets.main_assets?.length) { clientAssets.deps?.forEach(eachAsset); clientAssets.main_assets.forEach(eachAsset); } else { log('[server] Requested empty client asset:', assetIndex, id); } return { js: jsData, css: cssData }; }; const addParamsToData = (compData, { schema, params }) => { if (params?.toString()) { Object.keys(schema).filter(key => !key.startsWith('_') && !key.startsWith('peanut_') && schema[key]?._has?.input).forEach(key => { const { _has: { input } = {} } = schema[key] || {}; let value; if (['text', 'select'].includes(input)) { value = params.get(key); } else if (input === 'number') { value = Number(params.get(key)); } else if (input === 'checkbox') { const paramVal = params.get(key); value = typeof paramVal === 'string' ? paramVal === 'true' : params.get(key); } else if (input === 'object') { const keyValue = params.has(key) ? params.getAll(key) : null; if (Array.isArray(keyValue)) { if (keyValue.length === 1 && keyValue[0] === '') { value = []; } else { value = keyValue.map(data => { try { return JSON.parse(data); } catch (e) { return {}; } }); } } } if (value !== undefined && value !== null) { compData[key] = value; } }); } }; const htmlTemplate = ({ id, reactHtml, js, css, config }) => { const html = ` <html> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Whiteboard (Peanut For WordPress)</title> <script crossorigin src="https://unpkg.com/react@${reactVersion}/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@${reactDOMVersion}/umd/react-dom.development.js"></script> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"> ${css.map(item => { return `<link rel="stylesheet" href="${item.url}" />\n`; }).join('')} </head> <body> <div id="root">${reactHtml}</div> ${js.map(item => { return `<script src="${item.url}"></script>\n`; }).join('')} <script> window.peanutSrcClientJs['view_${id}'].default({ config: ${JSON.stringify(config)} }); </script> </body> </html> `; return html; }; module.exports = { setConfigs, getConfigs, buildClientAssets, resetAssets, getServerFile, addParamsToData, htmlTemplate }; /***/ }), /***/ 224: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /* global __ROUTES__ */ const envVars = __webpack_require__(471); const router = __webpack_require__(103); const { createServer } = __webpack_require__(806); const environment = envVars.get('ENVIRONMENT'); const isLocal = environment === 'local'; const minorSeconds = isLocal ? 0 : 60; const majorSeconds = isLocal ? 0 : 31536000; // TODO: Do we need this now that routes can be part of pfwp.json file? const routes = [{"url":"/","title":"Whiteboard","id":"whiteboard_app","srcPath":"/home/ubuntu/github/swplabs/peanut/src/whiteboard/shared/routes/app","path":"app","type":"base","srcType":"whiteboard","buildType":"server","initialData":{},"controller":"app","hasRenderJs":true,"hasViewScript":true},{"url":"/page/home/","title":"Home","id":"whiteboard_home","srcPath":"/home/ubuntu/github/swplabs/peanut/src/whiteboard/shared/routes/home","path":"home","type":"base","srcType":"whiteboard","buildType":"server","initialData":{},"controller":"base","hasRenderJs":true,"hasViewScript":true}]; const cntrls = { base: __webpack_require__(756), app: __webpack_require__(42), utils: __webpack_require__(812) }; const { default: defaultRequests, health: healthCheck, serveStatic } = __webpack_require__(133); // Set up route controllers const routeController = route => { const { controller: routeCntrl = 'base' } = route; return cntrls[routeCntrl].controller({ route, routes }); }; const serverStart = ({ appConfig, pfwpConfig, rootDir }) => { const staticFiles = serveStatic(`${rootDir}/dist/${envVars.get('PFWP_DIST')}/static`, { minorSeconds, majorSeconds }); const exportFiles = isLocal ? serveStatic(`${rootDir}/dist/export`, { minorSeconds, majorSeconds, basePath: '/exports' }) : async (_req, _res, next) => { await next(); }; cntrls.utils.setConfigs(appConfig, pfwpConfig); routes.forEach(route => router.get(route.url, routeController(route))); createServer({ port: envVars.get('PFWP_WB_PORT') || 5000, env: environment, httpsPort: envVars.getBoolean('PFWP_WB_ENABLE_HTTPS') ? envVars.get('PFWP_WB_HTTPS_PORT') || 9000 : null, requestHandler: (req, res) => { req.defaultRouter = router; req.cacheTimings = { minorSeconds, majorSeconds }; staticFiles(req, res, () => exportFiles(req, res, () => healthCheck(req, res, () => defaultRequests(req, res)))); } }); }; module.exports = { serverStart }; /***/ }), /***/ 88: /***/ ((module) => { "use strict"; module.exports = require("nconf"); /***/ }), /***/ 468: /***/ ((module) => { "use strict"; module.exports = require("react-dom/server"); /***/ }), /***/ 896: /***/ ((module) => { "use strict"; module.exports = require("fs"); /***/ }), /***/ 611: /***/ ((module) => { "use strict"; module.exports = require("http"); /***/ }), /***/ 692: /***/ ((module) => { "use strict"; module.exports = require("https"); /***/ }), /***/ 928: /***/ ((module) => { "use strict"; module.exports = require("path"); /***/ }), /***/ 16: /***/ ((module) => { "use strict"; module.exports = require("url"); /***/ }), /***/ 106: /***/ ((module) => { "use strict"; module.exports = require("zlib"); /***/ }), /***/ 330: /***/ ((module) => { "use strict"; module.exports = /*#__PURE__*/JSON.parse('{"name":"@swplabs/peanutforwp","version":"0.1.0-alpha.10","description":"Peanut for WordPress. Build your themes and blocks with components.","scripts":{"start":"npm run develop","develop":"node ./cli.js","build":"ENVIRONMENT=${ENVIRONMENT:=prod} NODE_ENV=${NODE_ENV:=production} PFWP_DIST=${PFWP_DIST:=build} node ./cli.js build","clean":"npx rimraf ./dist ./package-lock.json ./node_modules","clean-dist":"PFWP_DIST=${PFWP_DIST:=develop} && npx rimraf ./dist/${PFWP_DIST}/*","make-dist":"PFWP_DIST=${PFWP_DIST:=develop} && npx mkdirp ./dist/${PFWP_DIST}","install-app":"NODE_ENV=development npm install","clean-install":"npm run clean && npm run install-app"},"bin":{"peanut":"./cli.js"},"keywords":["wordpress","components","webpack","peanut"],"author":"SWP Labs","license":"GPL-3.0","homepage":"https://www.peanutforwp.com/","repository":{"type":"git","url":"https://github.com/swplabs/peanut.git"},"engines":{"node":">=18.12.0"},"funding":{"type":"ko-fi","url":"https://ko-fi.com/swplabs"},"dependencies":{"@babel/core":"7.26.0","@babel/eslint-parser":"7.25.9","@babel/preset-env":"7.26.0","@babel/preset-typescript":"7.26.0","@inquirer/prompts":"7.2.1","@pmmmwh/react-refresh-webpack-plugin":"0.5.15","@wordpress/babel-preset-default":"8.14.0","@wordpress/dependency-extraction-webpack-plugin":"6.14.0","@wordpress/eslint-plugin":"22.0.0","adm-zip":"0.5.16","autoprefixer":"10.4.20","babel-loader":"9.2.1","chokidar":"4.0.3","commander":"12.1.0","core-js":"3.39.0","css-loader":"7.1.2","eslint":"8.57.0","glob":"11.0.0","mini-css-extract-plugin":"2.9.2","mkdirp":"3.0.1","nconf":"0.12.1","postcss":"8.4.49","postcss-import":"16.1.0","postcss-loader":"8.1.1","postcss-preset-env":"10.1.3","prettier":"3.4.2","react":"18.3.1","react-dom":"18.3.1","react-refresh":"0.16.0","resolve-url-loader":"5.0.0","rimraf":"6.0.1","sass":"1.83.0","sass-loader":"16.0.4","style-loader":"4.0.0","typescript":"5.7.2","webpack":"5.97.1","webpack-cli":"6.0.1","webpack-dev-middleware":"7.4.2","webpack-hot-middleware":"2.26.1","webpack-node-externals":"3.0.0"},"devDependencies":{"@commitlint/cli":"19.6.1","@commitlint/config-conventional":"19.6.0","husky":"9.1.7"},"config":{"published":false,"pluginGitUrl":"https://github.com/swplabs/peanut-plugin/archive/refs/heads/main.zip"}}'); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module is referenced by other modules so it can't be inlined /******/ var __webpack_exports__ = __webpack_require__(224); /******/ module.exports = __webpack_exports__; /******/ /******/ })() ;