@moneko/core 3.0.0-beta.102 → 3.0.0-beta.104

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1,211 @@
1
- import{resolve as e}from"path";import s from"mini-css-extract-plugin";import o from"mini-svg-data-uri";import{CONFIG as t,PUBLICPATH as l}from"./common.js";import{hasPkg as r}from"./has-pkg.js";import a from"./modifyVars.js";import{APPTYPE as n,DEV as i,FRAMEWORK as c,__dirname as m}from"./process-env.js";import p from"./swcrc.js";import d from"./tsloader.config.js";import{resolveNodeModulesPath as u,resolveProgramPath as f}from"./utils.js";let y="single-spa"===n?l:"../",x={loader:s.loader,options:{publicPath:"/"!==y?y:"../"}},g=r("@moneko/postcss")&&{loader:"postcss-loader",options:{postcssOptions:await import("@moneko/postcss")}};i&&(x="style-loader");let $=[...t.cssModules,`@moneko/${c}`,"neko-ui"].map(u),j=[...["src/styles/variables/*.less","src/styles/mixins/*.less","site/styles/variables/*.less","site/styles/mixins/*.less"].map(f)],b=["components","example","mock","site","src"].map(f),v=[x,{loader:"@teamsupercell/typings-for-css-modules-loader",options:{verifyOnly:!i}},{loader:"css-loader",options:{modules:{auto:e=>{for(let s=0,o=$.length;s<o;s++)if(e&&e?.includes($[s]))return/(.*(?<!\.global\.(le|c)ss)$)/i.test(e);return/(^(?!.*node_modules))(.*(?<!\.global\.(le|c)ss)$)/i.test(e)},localIdentName:"[path][name]__[local]",exportLocalsConvention:"dashesOnly"},importLoaders:2}},g,"css-unicode-loader",{loader:"less-loader",options:{sourceMap:!!t.sourceMap,lessOptions:{modifyVars:a,javascriptEnabled:!0}}},{loader:"style-resources-loader",options:{patterns:j}}].filter(Boolean),w={loader:"tsc"===t.compiler?"ts-loader":"swc-loader",options:"tsc"===t.compiler?d:p(i)},h={rules:[{test:/\.mdx?$/,include:[f("components")],exclude:[/(.+)\/examples\/(.+).mdx?$/i],enforce:"pre",use:[{loader:e(m,"./loader/frontmatter.cjs")}]},{oneOf:[{resourceQuery:/raw/,type:"asset/source"},{test:/\.wasm$/,type:"webassembly/async"},{test:/\.txt$/,type:"asset/source"},{test:/\.(gif|png|jpe?g|ico|mp4)$/i,type:"asset",dependency:{not:["url"]},generator:{filename:"assets/images/[name][ext][query]"},include:b.concat(t.rulesInclude?.media?.map(u)||[])},{test:/\.svg$/,type:"asset/inline",generator:{dataUrl:e=>o("string"!=typeof e?e.toString():e)}},{test:/\.(eot|ttf|otf|woff(|2))$/,type:"asset",generator:{filename:"assets/fonts/[name][ext][query]"},include:b.concat(t.rulesInclude?.fonts?.map(u)||[])},{test:/\.less$/,use:v,include:b.concat(t.rulesInclude?.less?.map(u)||[])},{test:/\.css$/,use:[x,"css-loader",g,"css-unicode-loader"].filter(Boolean),include:b.concat(t.rulesInclude?.css?.map(u)||[])},{test:/\.(cj|mj|t|j)s(|x)$/,use:[...t.prefixJsLoader,w].filter(Boolean),include:b.concat(t.rulesInclude?.js?.map(u)||[])},{test:/\.mdx?$/,use:[...t.prefixJsLoader,w,{loader:"@mdx-js/loader",options:t.mdx}].filter(Boolean),include:b,exclude:[/(.+)\/examples\/(.+).mdx?$/i]},{test:/\.mdx?$/,type:"asset/source",include:[/(.+)\/examples\/(.+).mdx?$/i]},{type:"asset/source",include:[/(.+)\/examples\/(.+).*?$/i]}]},...t.moduleRules]};export default h;
1
+ import { resolve } from 'path';
2
+ import MiniCssExtractPlugin from 'mini-css-extract-plugin';
3
+ import svgToMiniDataURI from 'mini-svg-data-uri';
4
+ import { CONFIG, PUBLICPATH } from './common.js';
5
+ import { hasPkg } from './has-pkg.js';
6
+ import modifyVars from './modifyVars.js';
7
+ import { APPTYPE, DEV, FRAMEWORK, __dirname } from './process-env.js';
8
+ import swcOption from './swcrc.js';
9
+ import tsLoaderConfig from './tsloader.config.js';
10
+ import { resolveNodeModulesPath, resolveProgramPath } from './utils.js';
11
+ const cssAssetsPublicPath = APPTYPE === 'single-spa' ? PUBLICPATH : '../';
12
+ let styleLoader = {
13
+ loader: MiniCssExtractPlugin.loader,
14
+ options: {
15
+ publicPath: cssAssetsPublicPath !== '/' ? cssAssetsPublicPath : '../'
16
+ }
17
+ };
18
+ const postcssLoader = hasPkg('@moneko/postcss') && {
19
+ loader: 'postcss-loader',
20
+ options: {
21
+ postcssOptions: await import('@moneko/postcss')
22
+ }
23
+ };
24
+ if (DEV) {
25
+ styleLoader = 'style-loader';
26
+ }
27
+ const customCssModules = [
28
+ ...CONFIG.cssModules,
29
+ `@moneko/${FRAMEWORK}`,
30
+ 'neko-ui'
31
+ ].map(resolveNodeModulesPath);
32
+ const styleResources = [
33
+ ...[
34
+ 'src/styles/variables/*.less',
35
+ 'src/styles/mixins/*.less',
36
+ 'site/styles/variables/*.less',
37
+ 'site/styles/mixins/*.less'
38
+ ].map(resolveProgramPath)
39
+ ];
40
+ const entryResolveProgramPath = [
41
+ 'components',
42
+ 'example',
43
+ 'mock',
44
+ 'site',
45
+ 'src'
46
+ ].map(resolveProgramPath);
47
+ const lessLoaderRule = [
48
+ styleLoader,
49
+ {
50
+ loader: '@teamsupercell/typings-for-css-modules-loader',
51
+ options: {
52
+ verifyOnly: !DEV
53
+ }
54
+ },
55
+ {
56
+ loader: 'css-loader',
57
+ options: {
58
+ modules: {
59
+ auto: (resourcePath)=>{
60
+ for(let i = 0, len = customCssModules.length; i < len; i++){
61
+ if (resourcePath && resourcePath?.includes(customCssModules[i])) {
62
+ return /(.*(?<!\.global\.(le|c)ss)$)/i.test(resourcePath);
63
+ }
64
+ }
65
+ return /(^(?!.*node_modules))(.*(?<!\.global\.(le|c)ss)$)/i.test(resourcePath);
66
+ },
67
+ localIdentName: '[path][name]__[local]',
68
+ exportLocalsConvention: 'dashesOnly'
69
+ },
70
+ importLoaders: 2
71
+ }
72
+ },
73
+ postcssLoader,
74
+ 'css-unicode-loader',
75
+ {
76
+ loader: 'less-loader',
77
+ options: {
78
+ sourceMap: !!CONFIG.sourceMap,
79
+ lessOptions: {
80
+ modifyVars: modifyVars,
81
+ javascriptEnabled: true
82
+ }
83
+ }
84
+ },
85
+ {
86
+ loader: 'style-resources-loader',
87
+ options: {
88
+ patterns: styleResources
89
+ }
90
+ }
91
+ ].filter(Boolean);
92
+ const tsLoader = {
93
+ loader: CONFIG.compiler === 'tsc' ? 'ts-loader' : 'swc-loader',
94
+ options: CONFIG.compiler === 'tsc' ? tsLoaderConfig : swcOption(DEV)
95
+ };
96
+ const moduleOptions = {
97
+ rules: [
98
+ {
99
+ test: /\.mdx?$/,
100
+ include: [
101
+ resolveProgramPath('components')
102
+ ],
103
+ exclude: [
104
+ /(.+)\/examples\/(.+).mdx?$/i
105
+ ],
106
+ enforce: 'pre',
107
+ use: [
108
+ {
109
+ loader: resolve(__dirname, './loader/frontmatter.cjs')
110
+ }
111
+ ]
112
+ },
113
+ {
114
+ oneOf: [
115
+ {
116
+ resourceQuery: /raw/,
117
+ type: 'asset/source'
118
+ },
119
+ {
120
+ test: /\.wasm$/,
121
+ type: 'webassembly/async'
122
+ },
123
+ {
124
+ test: /\.txt$/,
125
+ type: 'asset/source'
126
+ },
127
+ {
128
+ test: /\.(gif|png|jpe?g|ico|mp4)$/i,
129
+ type: 'asset',
130
+ dependency: {
131
+ not: [
132
+ 'url'
133
+ ]
134
+ },
135
+ generator: {
136
+ filename: 'assets/images/[name][ext][query]'
137
+ },
138
+ include: entryResolveProgramPath.concat(CONFIG.rulesInclude?.media?.map(resolveNodeModulesPath) || [])
139
+ },
140
+ {
141
+ test: /\.svg$/,
142
+ type: 'asset/inline',
143
+ generator: {
144
+ dataUrl: (content)=>svgToMiniDataURI(typeof content !== 'string' ? content.toString() : content)
145
+ }
146
+ },
147
+ {
148
+ test: /\.(eot|ttf|otf|woff(|2))$/,
149
+ type: 'asset',
150
+ generator: {
151
+ filename: 'assets/fonts/[name][ext][query]'
152
+ },
153
+ include: entryResolveProgramPath.concat(CONFIG.rulesInclude?.fonts?.map(resolveNodeModulesPath) || [])
154
+ },
155
+ {
156
+ test: /\.less$/,
157
+ use: lessLoaderRule,
158
+ include: entryResolveProgramPath.concat(CONFIG.rulesInclude?.less?.map(resolveNodeModulesPath) || [])
159
+ },
160
+ {
161
+ test: /\.css$/,
162
+ use: [
163
+ styleLoader,
164
+ 'css-loader',
165
+ postcssLoader,
166
+ 'css-unicode-loader'
167
+ ].filter(Boolean),
168
+ include: entryResolveProgramPath.concat(CONFIG.rulesInclude?.css?.map(resolveNodeModulesPath) || [])
169
+ },
170
+ {
171
+ test: /\.(cj|mj|t|j)s(|x)$/,
172
+ use: [
173
+ ...CONFIG.prefixJsLoader,
174
+ tsLoader
175
+ ].filter(Boolean),
176
+ include: entryResolveProgramPath.concat(CONFIG.rulesInclude?.js?.map(resolveNodeModulesPath) || [])
177
+ },
178
+ {
179
+ test: /\.mdx?$/,
180
+ use: [
181
+ ...CONFIG.prefixJsLoader,
182
+ tsLoader,
183
+ {
184
+ loader: '@mdx-js/loader',
185
+ options: CONFIG.mdx
186
+ }
187
+ ].filter(Boolean),
188
+ include: entryResolveProgramPath,
189
+ exclude: [
190
+ /(.+)\/examples\/(.+).mdx?$/i
191
+ ]
192
+ },
193
+ {
194
+ test: /\.mdx?$/,
195
+ type: 'asset/source',
196
+ include: [
197
+ /(.+)\/examples\/(.+).mdx?$/i
198
+ ]
199
+ },
200
+ {
201
+ type: 'asset/source',
202
+ include: [
203
+ /(.+)\/examples\/(.+).*?$/i
204
+ ]
205
+ }
206
+ ]
207
+ },
208
+ ...CONFIG.moduleRules
209
+ ]
210
+ };
211
+ export default moduleOptions;
package/lib/net.js CHANGED
@@ -1 +1,33 @@
1
- import{createConnection as t}from"net";import{networkInterfaces as e}from"os";import r from"webpack-dev-server";let{internalIPSync:o}=r;export function getNetworkAdress(){let t=e();for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let r=t[e];for(let t=0;t<r.length;t++){let e=r[t];if("IPv4"===e.family&&"127.0.0.1"!==e.address&&!e.address.startsWith("169.254")&&!e.internal)return e.address}}}export function getIPv4(){return o("v4")}export function getPort(e,r,o="0.0.0.0"){return new Promise(n=>{let s=t(e,o);s.on("connect",()=>{s.destroy(),n(getPort(e+1,r,o))}),s.on("error",()=>{n(e)})})}
1
+ import { createConnection } from 'net';
2
+ import { networkInterfaces } from 'os';
3
+ import devServer from 'webpack-dev-server';
4
+ const { internalIPSync } = devServer;
5
+ export function getNetworkAdress() {
6
+ const interfaces = networkInterfaces();
7
+ for(const devName in interfaces){
8
+ if (Object.prototype.hasOwnProperty.call(interfaces, devName)) {
9
+ const iface = interfaces[devName];
10
+ for(let i = 0; i < iface.length; i++){
11
+ const alias = iface[i];
12
+ if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.address.startsWith('169.254') && !alias.internal) {
13
+ return alias.address;
14
+ }
15
+ }
16
+ }
17
+ }
18
+ }
19
+ export function getIPv4() {
20
+ return internalIPSync('v4');
21
+ }
22
+ export function getPort(start, end, host = '0.0.0.0') {
23
+ return new Promise((resolve)=>{
24
+ const tester = createConnection(start, host);
25
+ tester.on('connect', ()=>{
26
+ tester.destroy();
27
+ resolve(getPort(start + 1, end, host));
28
+ });
29
+ tester.on('error', ()=>{
30
+ resolve(start);
31
+ });
32
+ });
33
+ }
@@ -1 +1,28 @@
1
- export default function e(e){let t=[],n=new Proxy(e,{set:(e,n,r)=>(e[n]=r,t.forEach(t=>{t(e)}),!0)});return{data:n,listener:function(e){return t.push(e),()=>{let n=t.indexOf(e);-1!==n&&t.splice(n,1)}}}}
1
+ export default function objectListener(initialData) {
2
+ const listeners = [];
3
+ function notifyListeners(target) {
4
+ listeners.forEach((callback)=>{
5
+ callback(target);
6
+ });
7
+ }
8
+ function listener(callback) {
9
+ listeners.push(callback);
10
+ return ()=>{
11
+ const index = listeners.indexOf(callback);
12
+ if (index !== -1) {
13
+ listeners.splice(index, 1);
14
+ }
15
+ };
16
+ }
17
+ const data = new Proxy(initialData, {
18
+ set (target, property, value) {
19
+ target[property] = value;
20
+ notifyListeners(target);
21
+ return true;
22
+ }
23
+ });
24
+ return {
25
+ data,
26
+ listener
27
+ };
28
+ }
@@ -1 +1,65 @@
1
- import{existsSync as e,mkdirSync as o,readFileSync as r}from"fs";import{join as s}from"path";import t from"url";import{hasPkg as n}from"./has-pkg.js";import{resolveProgramPath as p}from"./utils.js";import c from"./yarn-argv.js";export const __dirname=t.fileURLToPath(new URL(".",import.meta.url));export const APPTYPE=process.env.APPTYPE;export const FRAMEWORK=process.env.FRAMEWORK;export const isReact="react"===FRAMEWORK;export const isSolid="solid-js"===FRAMEWORK;export const jsxImportSource={react:"react","solid-js":"solid-js/h"}[FRAMEWORK];export const PROGRAMPATH=process.cwd();export const PACKAGENAME=process.env.npm_package_name;export const PACKAGEVERSION=process.env.npm_package_version;let a=r(s(__dirname,"../package.json"),{encoding:"utf-8"});export const pkgName=JSON.parse(a).name;export const DEV="development"===process.env.NODE_ENV;export const cacheDir=s(PROGRAMPATH,"./node_modules/.cache/.mo/");e(cacheDir)||o(cacheDir,{recursive:!0});export const NODE_ENV=process.env.NODE_ENV;export const CUSTOMCONFIG=process.env.npm_config_config||c.config;export let hasEslintConfig=!!Object.keys(process.env).filter(e=>e.startsWith("npm_package_eslintConfig_")).length;export let hasStylelintConfig=!!Object.keys(process.env).filter(e=>e.startsWith("npm_package_stylelint_")).length;export const hasAntd=n("antd");export const programInfo={name:PACKAGENAME,version:PACKAGEVERSION,type:APPTYPE,description:process.env.npm_package_description,author:{name:process.env.npm_package_author_name,email:process.env.npm_package_author_email,url:process.env.npm_package_author_url},repository:{type:process.env.npm_package_repository_type,url:process.env.npm_package_repository_url,directory:process.env.npm_package_repository_directory}};if(parseInt(process.versions.node)>14){let e=r(p("package.json"),{encoding:"utf-8"}),{description:o,author:s,repository:t,eslintConfig:n,stylelint:c}=JSON.parse(e);programInfo.author="string"==typeof s?{name:s}:s,programInfo.repository="string"==typeof s?{url:t}:t,programInfo.description=o,hasEslintConfig=!!n,hasStylelintConfig=!!c}
1
+ import { existsSync, mkdirSync, readFileSync } from 'fs';
2
+ import { join } from 'path';
3
+ import url from 'url';
4
+ import { hasPkg } from './has-pkg.js';
5
+ import { resolveProgramPath } from './utils.js';
6
+ import yarnArgv from './yarn-argv.js';
7
+ export const __dirname = url.fileURLToPath(new URL('.', import.meta.url));
8
+ export const APPTYPE = process.env.APPTYPE;
9
+ export const FRAMEWORK = process.env.FRAMEWORK;
10
+ export const isReact = FRAMEWORK === 'react';
11
+ export const isSolid = FRAMEWORK === 'solid-js';
12
+ export const jsxImportSource = {
13
+ react: 'react',
14
+ 'solid-js': 'solid-js/h'
15
+ }[FRAMEWORK];
16
+ export const PROGRAMPATH = process.cwd();
17
+ export const PACKAGENAME = process.env.npm_package_name;
18
+ export const PACKAGEVERSION = process.env.npm_package_version;
19
+ const pkg = readFileSync(join(__dirname, '../package.json'), {
20
+ encoding: 'utf-8'
21
+ });
22
+ export const pkgName = JSON.parse(pkg).name;
23
+ export const DEV = process.env.NODE_ENV === 'development';
24
+ export const cacheDir = join(PROGRAMPATH, './node_modules/.cache/.mo/');
25
+ if (!existsSync(cacheDir)) {
26
+ mkdirSync(cacheDir, {
27
+ recursive: true
28
+ });
29
+ }
30
+ export const NODE_ENV = process.env.NODE_ENV;
31
+ export const CUSTOMCONFIG = process.env.npm_config_config || yarnArgv.config;
32
+ export let hasEslintConfig = !!Object.keys(process.env).filter((k)=>k.startsWith('npm_package_eslintConfig_')).length;
33
+ export let hasStylelintConfig = !!Object.keys(process.env).filter((k)=>k.startsWith('npm_package_stylelint_')).length;
34
+ export const hasAntd = hasPkg('antd');
35
+ export const programInfo = {
36
+ name: PACKAGENAME,
37
+ version: PACKAGEVERSION,
38
+ type: APPTYPE,
39
+ description: process.env.npm_package_description,
40
+ author: {
41
+ name: process.env.npm_package_author_name,
42
+ email: process.env.npm_package_author_email,
43
+ url: process.env.npm_package_author_url
44
+ },
45
+ repository: {
46
+ type: process.env.npm_package_repository_type,
47
+ url: process.env.npm_package_repository_url,
48
+ directory: process.env.npm_package_repository_directory
49
+ }
50
+ };
51
+ if (parseInt(process.versions.node) > 14) {
52
+ const ikpg = readFileSync(resolveProgramPath('package.json'), {
53
+ encoding: 'utf-8'
54
+ });
55
+ const { description , author , repository , eslintConfig , stylelint } = JSON.parse(ikpg);
56
+ programInfo.author = typeof author === 'string' ? {
57
+ name: author
58
+ } : author;
59
+ programInfo.repository = typeof author === 'string' ? {
60
+ url: repository
61
+ } : repository;
62
+ programInfo.description = description;
63
+ hasEslintConfig = !!eslintConfig;
64
+ hasStylelintConfig = !!stylelint;
65
+ }
@@ -1 +1,21 @@
1
- import*as e from"fs";import s from"enhanced-resolve";let{CachedInputFileSystem:o,ResolverFactory:n}=s,m=n.createResolver({fileSystem:new o(e,4e3),conditionNames:["node"],extensions:[".js",".json",".node"],useSyncFileSystemCalls:!0,mainFields:["esm","module","main"]});export default m;
1
+ import * as fs from 'fs';
2
+ import enhancedResolve from 'enhanced-resolve';
3
+ const { CachedInputFileSystem , ResolverFactory } = enhancedResolve;
4
+ const resolverSync = ResolverFactory.createResolver({
5
+ fileSystem: new CachedInputFileSystem(fs, 4000),
6
+ conditionNames: [
7
+ 'node'
8
+ ],
9
+ extensions: [
10
+ '.js',
11
+ '.json',
12
+ '.node'
13
+ ],
14
+ useSyncFileSystemCalls: true,
15
+ mainFields: [
16
+ 'esm',
17
+ 'module',
18
+ 'main'
19
+ ]
20
+ });
21
+ export default resolverSync;
package/lib/routes.js CHANGED
@@ -1 +1,187 @@
1
- let e,t;import{readFileSync as r,readdirSync as o,statSync as n}from"fs";import{join as s,relative as a}from"path";import{watch as i}from"chokidar";import{load as l}from"js-yaml";import c from"./object-listener.js";import{APPTYPE as p,FRAMEWORK as m,PROGRAMPATH as u}from"./process-env.js";let d=/^---\n([\s\S]+?)\n---\n/;function f(e,t){let{regex:i,alia:c,base:p=e,outputSource:m}=t,u=o(e);return u.reduce((o,u)=>{let g=s(e,u),x=n(g);if(x.isDirectory()){let e=f(g,{...t,base:p});if(e.length>0){let t={},r={path:u,key:a(p,g)};if(m)Object.assign(t,{children:e});else{let o=e.splice(0,1)[0];e.length?Object.assign(t,{children:[{...o,path:"/",key:r.key},...e]}):Object.assign(t,o)}o.push(Object.assign(t,r))}}else if(i.test(g)){let e=r(g,{encoding:"utf-8"}),t=function(e){let t=e.match(d);return t&&t[1]?t[1].trim():null}(e),n=t?l(t):{},i=a(p,g);o.push(Object.assign({path:u,key:i,meta:{...n}},c&&{component:`rr(() => import(/* webpackChunkName: '${i}' */'${s(c,i)}'))rr`},m&&{codes:function(e){let t;let r={},o=/```(.+?)\n([\s\S]*?)\n```/g;for(;null!==(t=o.exec(e));){let[,e="jsx",o]=t,n=e.split(" ").pop()||"jsx";r[n]=o.trim()}return Object.keys(r).length?r:{jsx:e}}(e.replace(d,"").replace(/^\n+|\n+$/g,""))}))}return o},[])}let g=s(u,"./components");export const route=c({name:"@app/routes",data:"export default []"});export const example=c({name:"@app/example",data:{}});export let routes=[];function x(e,t,r){let o=i(e,{ignored:(e,r)=>{if(r)return!r?.isDirectory()&&t.test(e)},persistent:!0,ignoreInitial:!1});o.on("add",()=>{r()}).on("change",()=>{r()}).on("unlink",()=>{r()}),process.on("SIGINT",function(){o.close()})}"library"===p&&(x(g,/(?<!README\.mdx?)$/,function(){clearTimeout(e),e=setTimeout(()=>{clearTimeout(e);let t={react:"createElement","solid-js":"createComponent"}[m],r=`() => ${t}(SuspenseComp, { comp: $1 })`,o=`import { ${t} } from "${m}";import { SuspenseComp } from "@moneko/${m}";`;["react","solid-js"].includes(m)||(r="$1",o=""),routes=f(g,{regex:/README\.mdx?$/,alia:"@pkg"});let n=JSON.stringify(routes).replace(/"rr\((.+?)\)rr"/g,r);Object.assign(route.data,{data:`${o}export default ${n}`})},100)}),x(g,/(?<!\/examples\/(.+)\.md)$/,function(){clearTimeout(t),t=setTimeout(()=>{clearTimeout(t);let e={};f(g,{regex:/\/examples\/(.+)\.md$/,outputSource:!0}).forEach(t=>{let r=[example.data.name,t.key].filter(Boolean).join("/"),o=t.children?.[0].children?.filter(e=>e.codes)?.map(e=>({title:e.path.replace(/.md$/,""),order:0,...e.meta,codes:e.codes})).sort((e,t)=>e.order-t.order);Object.assign(e,{[r]:`export default ${JSON.stringify(o)};`})}),Object.assign(example.data,{data:e})},100)}));
1
+ import { readFileSync, readdirSync, statSync } from 'fs';
2
+ import { join, relative } from 'path';
3
+ import { watch } from 'chokidar';
4
+ import { load } from 'js-yaml';
5
+ import { hasCustomRouter } from './common.js';
6
+ import objectListener from './object-listener.js';
7
+ import { APPTYPE, FRAMEWORK, PROGRAMPATH } from './process-env.js';
8
+ const frontmatterRegex = /^---\n([\s\S]+?)\n---\n/;
9
+ function extractFrontmatter(md) {
10
+ const matches = md.match(frontmatterRegex);
11
+ return matches && matches[1] ? matches[1].trim() : null;
12
+ }
13
+ function extractCode(codeStr) {
14
+ const codes = {};
15
+ const regex = /```(.+?)\n([\s\S]*?)\n```/g;
16
+ let match;
17
+ while((match = regex.exec(codeStr)) !== null){
18
+ const [, language = 'jsx', source] = match;
19
+ const lang = language.split(' ').pop() || 'jsx';
20
+ codes[lang] = source.trim();
21
+ }
22
+ return Object.keys(codes).length ? codes : {
23
+ jsx: codeStr
24
+ };
25
+ }
26
+ function getTree(directory, option) {
27
+ const { regex , alia , base =directory , outputSource } = option;
28
+ const files = readdirSync(directory);
29
+ return files.reduce((tree, file)=>{
30
+ const filePath = join(directory, file);
31
+ const stats = statSync(filePath);
32
+ if (stats.isDirectory()) {
33
+ const children = getTree(filePath, {
34
+ ...option,
35
+ base
36
+ });
37
+ if (children.length > 0) {
38
+ const item = {};
39
+ const baseItem = {
40
+ path: file,
41
+ key: relative(base, filePath)
42
+ };
43
+ if (outputSource) {
44
+ Object.assign(item, {
45
+ children
46
+ });
47
+ } else {
48
+ const frist = children.splice(0, 1)[0];
49
+ if (children.length) {
50
+ Object.assign(item, {
51
+ children: [
52
+ {
53
+ ...frist,
54
+ path: '/',
55
+ key: baseItem.key
56
+ },
57
+ ...children
58
+ ]
59
+ });
60
+ } else {
61
+ Object.assign(item, frist);
62
+ }
63
+ }
64
+ tree.push(Object.assign(item, baseItem));
65
+ }
66
+ } else if (regex.test(filePath)) {
67
+ const source = readFileSync(filePath, {
68
+ encoding: 'utf-8'
69
+ });
70
+ const frontmatter = extractFrontmatter(source);
71
+ const meta = frontmatter ? load(frontmatter) : {};
72
+ const reslove = relative(base, filePath);
73
+ tree.push(Object.assign({
74
+ path: file,
75
+ key: reslove,
76
+ meta: {
77
+ ...meta
78
+ }
79
+ }, alia && {
80
+ component: `rr(() => import(/* webpackChunkName: '${reslove}' */'${join(alia, reslove)}'))rr`
81
+ }, outputSource && {
82
+ codes: extractCode(source.replace(frontmatterRegex, '').replace(/^\n+|\n+$/g, ''))
83
+ }));
84
+ }
85
+ return tree;
86
+ }, []);
87
+ }
88
+ const compPath = join(PROGRAMPATH, './components');
89
+ export const route = objectListener({
90
+ name: '@app/routes',
91
+ data: 'export default []'
92
+ });
93
+ export const example = objectListener({
94
+ name: '@app/example',
95
+ data: {}
96
+ });
97
+ const createElement = {
98
+ react: 'createElement',
99
+ 'solid-js': 'createComponent'
100
+ }[FRAMEWORK];
101
+ let replaceStr = `() => ${createElement}(SuspenseComp, { comp: $1 })`;
102
+ let prefixStr = `import { ${createElement} } from "${FRAMEWORK}";import { SuspenseComp } from "@moneko/${FRAMEWORK}";`;
103
+ if (hasCustomRouter) {
104
+ prefixStr += `import merge from "@moneko/${FRAMEWORK}/lib/merge.js";import customRouter from "@/router";`;
105
+ }
106
+ if (![
107
+ 'react',
108
+ 'solid-js'
109
+ ].includes(FRAMEWORK)) {
110
+ replaceStr = '$1';
111
+ prefixStr = '';
112
+ }
113
+ export let routes = [];
114
+ let timerRoutes;
115
+ function generatorLibraryRouter() {
116
+ clearTimeout(timerRoutes);
117
+ timerRoutes = setTimeout(()=>{
118
+ clearTimeout(timerRoutes);
119
+ routes = getTree(compPath, {
120
+ regex: /README\.mdx?$/,
121
+ alia: '@pkg'
122
+ });
123
+ const tree = JSON.stringify(routes).replace(/"rr\((.+?)\)rr"/g, replaceStr).slice(1, -1);
124
+ Object.assign(route.data, {
125
+ data: `${prefixStr}const routes = [{ path: "/", children: [{ path: "/" }, ${tree}] }];
126
+ export default ${hasCustomRouter ? 'merge([...routes, ...customRouter], "path")' : 'routes'}`
127
+ });
128
+ }, 100);
129
+ }
130
+ let timerExample;
131
+ function generatorLibraryDemo() {
132
+ clearTimeout(timerExample);
133
+ timerExample = setTimeout(()=>{
134
+ clearTimeout(timerExample);
135
+ const exampleNext = {};
136
+ getTree(compPath, {
137
+ regex: /\/examples\/(.+)\.md$/,
138
+ outputSource: true
139
+ }).forEach((item)=>{
140
+ const _name = [
141
+ example.data.name,
142
+ item.key
143
+ ].filter(Boolean).join('/');
144
+ const data = item.children?.[0].children?.filter((e)=>e.codes)?.map((e)=>({
145
+ title: e.path.replace(/.md$/, ''),
146
+ order: 0,
147
+ ...e.meta,
148
+ codes: e.codes
149
+ })).sort((a, b)=>a.order - b.order);
150
+ Object.assign(exampleNext, {
151
+ [_name]: `export default ${JSON.stringify(data)};`
152
+ });
153
+ });
154
+ Object.assign(example.data, {
155
+ data: exampleNext
156
+ });
157
+ }, 100);
158
+ }
159
+ function watchFiles(root, ignored, call) {
160
+ const ignoredRouter = (src, stats)=>{
161
+ if (stats) {
162
+ if (stats?.isDirectory()) {
163
+ return false;
164
+ }
165
+ return ignored.test(src);
166
+ }
167
+ };
168
+ const watcher = watch(root, {
169
+ ignored: ignoredRouter,
170
+ persistent: true,
171
+ ignoreInitial: false
172
+ });
173
+ watcher.on('add', ()=>{
174
+ call();
175
+ }).on('change', ()=>{
176
+ call();
177
+ }).on('unlink', ()=>{
178
+ call();
179
+ });
180
+ process.on('SIGINT', function() {
181
+ watcher.close();
182
+ });
183
+ }
184
+ if (APPTYPE === 'library') {
185
+ watchFiles(compPath, /(?<!README\.mdx?)$/, generatorLibraryRouter);
186
+ watchFiles(compPath, /(?<!\/examples\/(.+)\.md)$/, generatorLibraryDemo);
187
+ }
package/lib/seo.js CHANGED
@@ -1 +1,39 @@
1
- import{existsSync as t,mkdirSync as o,writeFileSync as r}from"fs";import{join as e}from"path";import{CONFIG as s}from"./common.js";import{routes as m}from"./routes.js";import{resolveProgramPath as i}from"./utils.js";import{outputConfig as p}from"./webpack.common.js";function n(t,o){try{r(t,o,"utf-8")}catch(t){}}export const seo=()=>{let{domain:r,nojekyll:c,path:a}=s.seo||{};if(!r)return;let f=s.routeBaseName,h=f.endsWith("/")?f:`${f}/`,l=a&&i(a)||p?.path||process.cwd();t(l)||o(l),n(e(l,"CNAME"),r),n(e(l,"robots"),`Sitemap: https://${r}${h}sitemap.txt`);let u=[];!function t(o){o.forEach(o=>{u.push(`https://${r}${h}${o.key}`),Array.isArray(o.children)&&t(o.children)})}(m),n(e(l,"sitemap.txt"),u.join("\n")),c&&n(e(l,".nojekyll"),"")};
1
+ import { existsSync, mkdirSync, writeFileSync } from 'fs';
2
+ import { join } from 'path';
3
+ import { CONFIG } from './common.js';
4
+ import { routes } from './routes.js';
5
+ import { resolveProgramPath } from './utils.js';
6
+ import { outputConfig } from './webpack.common.js';
7
+ function writeFile(path, data) {
8
+ try {
9
+ writeFileSync(path, data, 'utf-8');
10
+ } catch (error) {}
11
+ }
12
+ export const seo = ()=>{
13
+ const { domain , nojekyll , path } = CONFIG.seo || {};
14
+ if (!domain) {
15
+ return;
16
+ }
17
+ const routeBase = CONFIG.routeBaseName;
18
+ const base = routeBase.endsWith('/') ? routeBase : `${routeBase}/`;
19
+ const baseDir = path && resolveProgramPath(path) || outputConfig?.path || process.cwd();
20
+ if (!existsSync(baseDir)) {
21
+ mkdirSync(baseDir);
22
+ }
23
+ writeFile(join(baseDir, 'CNAME'), domain);
24
+ writeFile(join(baseDir, 'robots'), `Sitemap: https://${domain}${base}sitemap.txt`);
25
+ const sitemap = [];
26
+ function getSiteMap(list) {
27
+ list.forEach((item)=>{
28
+ sitemap.push(`https://${domain}${base}${item.key}`);
29
+ if (Array.isArray(item.children)) {
30
+ getSiteMap(item.children);
31
+ }
32
+ });
33
+ }
34
+ getSiteMap(routes);
35
+ writeFile(join(baseDir, 'sitemap.txt'), sitemap.join('\n'));
36
+ if (nojekyll) {
37
+ writeFile(join(baseDir, '.nojekyll'), '');
38
+ }
39
+ };