@oiyo/core 0.2.1 → 0.3.0-beta.2
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.
- package/LICENSE +14 -6
- package/README.md +5 -5
- package/dist/index.cjs +17 -16
- package/dist/index.d.cts +194 -285
- package/dist/index.d.mts +194 -285
- package/dist/index.mjs +17 -16
- package/package.json +7 -4
package/dist/index.mjs
CHANGED
|
@@ -1,25 +1,26 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @oiyo/core v0.
|
|
2
|
+
* @oiyo/core v0.3.0-beta.2
|
|
3
3
|
* Copyright (c) 2026 skiyee. All rights reserved.
|
|
4
4
|
* Commercial software. See LICENSE for terms.
|
|
5
5
|
* Official site: https://oiyo.js.org
|
|
6
6
|
*/
|
|
7
|
-
import{createRequire as e}from"node:module";import t,{pid as n}from"node:process";import r from"node:readline";import{blue as i,bold as a,cyan as o,dim as s,red as c,yellow as l}from"ansis";import{existsSync as
|
|
8
|
-
`.repeat(e):``;t.stdout.write(n),r.cursorTo(t.stdout,0,0),r.clearScreenDown(t.stdout)}function Re(){return Ie??=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`numeric`,second:`numeric`}),Ie}function ze(e=`info`,n={}){if(n.customLogger)return n.customLogger;let r=new WeakSet,u=new Set,{prefix:d=`[OIYO]`,scope:ee,allowClearScreen:te=!0,console:f=globalThis.console}=n,ne=k[e],re=te&&t.stdout.isTTY&&!t.env.CI,p=re?Le:()=>{};function m(e,t,n={}){let r=ie(e,n.scope??ee);return n.timestamp?`${s(Re().format(new Date))} ${i(d)} ${r} ${t}`:`${i(a(d))} ${r} ${t}`}function ie(e,t){if(!t)return` `;let n=`[${t.toUpperCase()}]`;return{info:o(n),warn:l(n),error:c(n),debug:s(o(n))}[e]}function h(e,t,n={}){if(ne<k[e])return;let i=e;if(n.error&&r.add(n.error),re){if(e===Ne&&t===Pe){Fe++,p(),f[e](m(e,t,n),l(`(x${Fe+1})`));return}Fe=0,Ne=e,Pe=t,n.clear&&p()}f[i](m(e,t,n))}let g={hasWarned:!1,withScope(t){return ze(e,{...n,scope:t})},debug(e,t){h(`debug`,e,t)},info(e,t){h(`info`,e,t)},warn(e,t){g.hasWarned=!0,h(`warn`,e,t)},warnOnce(e,t){u.has(e)||(u.add(e),g.hasWarned=!0,h(`warn`,e,t))},error(e,t){g.hasWarned=!0,h(`error`,e,t)},clearScreen(e){ne>=k[e]&&p()},hasErrorLogged(e){return r.has(e)}};return g}const A=typeof ce==`function`?ce:ce.default,Be=e(import.meta.url),Ve=`**/*`;function j(e){return e?Array.isArray(e)?e:[e]:[]}function He(e){if(!u(e))return[Ve];try{return f(e).isFile()?[ae(e)]:[Ve]}catch{return[Ve]}}async function M(e){let{dir:t,pattern:n,ignore:r}=e;if(!u(t))return[];let i=f(t).isFile()?_(t):t,a=j(n),o=a.length>0?a:He(t);try{return(await le(o,{cwd:i,absolute:!0,ignore:j(r)})).map(e=>b(C(e)))}catch(e){return console.error(`[oiyo] Error scanning file:`,e),[]}}function Ue(e,t,n){let r=b(e),i=b(t);if(u(i))try{if(f(i).isFile())return r===i}catch{return!1}if(r!==i&&!r.startsWith(`${i}/`))return!1;let a=b(S(i,r)),o=j(n?.pattern);return j(n?.ignore).some(e=>y(a,e))?!1:o.length===0?!0:o.some(e=>y(a,e))}function N(e,t=8){return se(`sha256`).update(e).digest(`hex`).slice(0,t)}function P(e,t){let r=`${e}.${n}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;return re(r,t,`utf-8`),u(e)&&ne(e),te(r,e),!0}function We(e,t,n){let r=b(S(e,t));return n?.stripExtension&&(r=r.replace(/\.[cm]?[jt]sx?$/,``)),r.startsWith(`.`)?r:`./${r}`}function F(e){return!e.startsWith(`.`)&&!e.startsWith(`/`)&&!/^[a-z]:[\\/]/i.test(e)}function Ge(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function Ke(e,t){if(!F(t))return{path:b(C(e,t))};try{let n=Ge(t),r=_(b(Be.resolve(`${n}/package.json`,{paths:[e]}))),i=t.slice(n.length).replace(/^\/+/,``);return{importBase:t.replace(/\\/g,`/`),path:b(i?C(r,i):r)}}catch{return{path:b(C(e,t))}}}function qe(e,t,n){if(!n)return e;let r=b(S(t,e));return!r||r===`.`?n:`${n}/${r}`}function Je(e,t,n){return F(t)?n?.stripExtension?t.replace(/\.[cm]?[jt]sx?$/,``):t:We(e,t,n)}function Ye(e){if(!e)return``;let t=e.replace(/\p{Lu}/gu,e=>`-${e.toLowerCase()}`);return t.startsWith(`-`)?t.slice(1):t}function I(e){return e?e.replace(/[-_](.)/g,(e,t)=>t.toUpperCase()).replace(/^(.)/,e=>e.toUpperCase()):``}function Xe(e,t){let n=w(e,{sourceType:`module`,plugins:[`typescript`]}),r={start:0,end:0};return A(n,{CallExpression(e){let{callee:n,arguments:i}=e.node;n.type===`Identifier`&&n.name===t&&i.length>0&&e.node.start!=null&&e.node.end!=null&&(r.start=e.node.start,r.end=e.node.end,e.stop())}}),r}function Ze(e){return e.replace(/\s+/g,``)}const Qe=e(import.meta.url),$e=[`.ts`,`.mts`,`.cts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.jsx`,`.vue`,`.d.ts`,`.d.mts`,`.d.cts`];function et(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function tt(e,t){let n=b(e);for(;;){let e=C(n,`node_modules`,t,`package.json`);if(u(e))return b(e);let r=_(n);if(r===n)return;n=r}}function nt(e,t,n){let r=b(C(x(e).dir,t)),i=n?.preferTypes?[`.d.ts`,`.d.mts`,`.d.cts`,...$e]:$e;if(u(r))return r;for(let e of i){let t=`${r}${e}`;if(u(t))return b(t)}for(let e of i){let t=C(r,`index${e}`);if(u(t))return b(t)}return r}function rt(e,t){if(!e||typeof e!=`object`)return t===`import`&&typeof e==`string`?e:void 0;if(t===`types`){let t=e.types;if(typeof t==`string`)return t;if(t&&typeof t==`object`){let e=t;return typeof e.import==`string`?e.import:typeof e.require==`string`?e.require:typeof e.default==`string`?e.default:void 0}}let n=e;return typeof n.import==`string`?n.import:typeof n.default==`string`?n.default:typeof n.require==`string`?n.require:void 0}async function it(e,t,n){try{let r=et(t),i=tt(e,r)||b(Qe.resolve(`${r}/package.json`,{paths:[e]})),a=_(i),o=JSON.parse(await m(i,`utf-8`)),s=t.slice(r.length).replace(/^\/+/,``),c=s?`./${s}`:`.`,l=typeof o.exports==`object`&&o.exports?o.exports[c]??(c===`.`?o.exports:void 0):void 0,u=n?.preferTypes?rt(l,`types`)||(c===`.`?o.types:void 0):rt(l,`import`)||(c===`.`?o.module||o.main:void 0);return b(u?C(a,u):Qe.resolve(t,{paths:[e]}))}catch{return}}async function at(e,t,n){return F(t)?await it(_(e),t,n)||t:nt(e,t,n)}function ot(e,t){return t.startsWith(`.`)||t.startsWith(`/`)?nt(e,t,{preferTypes:!0}):t}function st(e,t,n){return F(t)?n||(tt(e,et(t))?t.replace(/\\/g,`/`):void 0):n}async function ct(e,t){if(!e.importBase||!F(e.importBase))return{typePath:e.path,valuePath:e.path};let n=await it(t,e.importBase),r=await it(t,e.importBase,{preferTypes:!0});return{typePath:r||n||e.path,valuePath:n||r||e.path}}function lt(e,t){return!t||!e.importPath||!F(t)?e:e.importPath.startsWith(`${t}/..`)||e.importPath.startsWith(`${t}/.`)?{...e,importPath:t}:e}function ut(e){let t=I(e);return t?t[0].toLowerCase()+t.slice(1):``}function dt(e){try{return w(e,{sourceType:`module`,plugins:[`typescript`,`jsx`]})}catch{return w(`(${e})`,{sourceType:`module`,plugins:[`typescript`,`jsx`]})}}function L(e){return e.type===`Identifier`?[e.name]:e.type===`ObjectPattern`?e.properties.flatMap(e=>e.type===`ObjectProperty`?L(e.value):e.type===`RestElement`?L(e.argument):[]):e.type===`ArrayPattern`?e.elements.flatMap(e=>e?L(e):[]):e.type===`AssignmentPattern`?L(e.left):e.type===`RestElement`?L(e.argument):[]}function ft(e){let t=x(e);return ut(t.name===`index`?x(t.dir).name:t.name)}function pt(e,t){if(!e.endsWith(`.vue`))return t;try{let{descriptor:n}=T(t,{filename:e});return[n.script?.content,n.scriptSetup?.content].filter(e=>!!e).join(`
|
|
9
|
-
`)
|
|
10
|
-
`)}writeDeclaration(){
|
|
11
|
-
`)
|
|
12
|
-
`)}writeDeclaration(){
|
|
13
|
-
`)
|
|
7
|
+
import{createRequire as e}from"node:module";import t,{pid as n}from"node:process";import r from"node:readline";import{blue as i,bold as a,cyan as o,dim as s,red as c,yellow as l}from"ansis";import*as u from"node:fs";import{existsSync as d,mkdirSync as f,readFileSync as p,renameSync as ee,statSync as m,unlinkSync as te,writeFileSync as h}from"node:fs";import*as ne from"node:fs/promises";import{lstat as re,readFile as g,readdir as _,realpath as ie,stat as ae}from"node:fs/promises";import*as v from"pathe";import{basename as oe,dirname as se,join as y,normalize as b,parse as ce,relative as le,resolve as x,sep as ue}from"pathe";import{createHash as de}from"node:crypto";import{parse as S}from"@babel/parser";import fe from"@babel/traverse";import*as pe from"tinyglobby";import{glob as me,globSync as he}from"tinyglobby";import*as ge from"node:url";import _e from"enhanced-resolve";import*as ve from"node:os";import*as ye from"node:path";import C,{join as be,relative as xe,resolve as Se,sep as Ce}from"node:path";import w from"magic-string";import{parse as T}from"@vue/compiler-sfc";import{DEFAULT_EXCLUDE as we,resolveOiyoConfig as Te}from"@oiyo/config";import{defineComponent as Ee}from"vue";import{loadConfig as De,watchConfig as Oe}from"c12";import{stat as ke,unwatchFile as Ae,watch as je,watchFile as Me}from"fs";import{lstat as Ne,open as Pe,readdir as Fe,realpath as E,stat as D}from"fs/promises";import{EventEmitter as Ie}from"events";import*as O from"path";import{Readable as Le}from"node:stream";import{type as Re}from"os";import{defu as ze}from"defu";const k={silent:0,error:1,warn:2,info:3,debug:4,verbose:5};let Be,Ve,He=0,Ue;function We(){let e=t.stdout.rows-2,n=e>0?`
|
|
8
|
+
`.repeat(e):``;t.stdout.write(n),r.cursorTo(t.stdout,0,0),r.clearScreenDown(t.stdout)}function Ge(){return Ue??=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`numeric`,second:`numeric`}),Ue}function Ke(e=`info`,n={}){if(n.customLogger)return n.customLogger;let r=new WeakSet,u=new Set,{prefix:d=`[OIYO]`,scope:f,allowClearScreen:p=!0,console:ee=globalThis.console}=n,m=k[e],te=p&&t.stdout.isTTY&&!t.env.CI,h=te?We:()=>{};function ne(e,t,n={}){let r=re(e,n.scope??f);return n.timestamp?`${s(Ge().format(new Date))} ${i(d)} ${r} ${t}`:`${i(a(d))} ${r} ${t}`}function re(e,t){if(!t)return` `;let n=`[${t.toUpperCase()}]`;return{info:o(n),warn:l(n),error:c(n),debug:s(o(n))}[e]}function g(e,t,n={}){if(m<k[e])return;let i=e;if(n.error&&r.add(n.error),te){if(e===Be&&t===Ve){He++,h(),ee[e](ne(e,t,n),l(`(x${He+1})`));return}He=0,Be=e,Ve=t,n.clear&&h()}ee[i](ne(e,t,n))}let _={hasWarned:!1,withScope(t){return Ke(e,{...n,scope:t})},debug(e,t){g(`debug`,e,t)},info(e,t){g(`info`,e,t)},warn(e,t){_.hasWarned=!0,g(`warn`,e,t)},warnOnce(e,t){u.has(e)||(u.add(e),_.hasWarned=!0,g(`warn`,e,t))},error(e,t){_.hasWarned=!0,g(`error`,e,t)},clearScreen(e){m>=k[e]&&h()},hasErrorLogged(e){return r.has(e)}};return _}const A=typeof fe==`function`?fe:fe.default;e(import.meta.url);const qe=`**/*`;function j(e){return e==null?[]:Array.isArray(e)?e:[e]}function Je(e){return e?Array.isArray(e)?e:[e]:[]}function Ye(e){if(!d(e))return[qe];try{return m(e).isFile()?[oe(e)]:[qe]}catch{return[qe]}}async function Xe(e){let{dir:t,pattern:n,ignore:r}=e;if(!d(t))return[];let i=m(t).isFile()?se(t):t,a=Je(n),o=a.length>0?a:Ye(t);try{return(await me(o,{cwd:i,absolute:!0,ignore:Je(r)})).map(e=>b(x(e)))}catch(e){return console.error(`[oiyo] Error scanning file:`,e),[]}}function M(e,t=8){return de(`sha256`).update(e).digest(`hex`).slice(0,t)}function N(e,t){let r=`${e}.${n}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;return h(r,t,`utf-8`),d(e)&&te(e),ee(r,e),!0}function Ze(e){if(!e)return``;let t=e.replace(/\p{Lu}/gu,e=>`-${e.toLowerCase()}`);return t.startsWith(`-`)?t.slice(1):t}function P(e){return e?e.replace(/[-_](.)/g,(e,t)=>t.toUpperCase()).replace(/^(.)/,e=>e.toUpperCase()):``}function Qe(e){let t=P(e);return t?t[0].toLowerCase()+t.slice(1):``}function $e(e,t){let n=S(e,{sourceType:`module`,plugins:[`typescript`]}),r={start:0,end:0};return A(n,{CallExpression(e){let{callee:n,arguments:i}=e.node;n.type===`Identifier`&&n.name===t&&i.length>0&&e.node.start!=null&&e.node.end!=null&&(r.start=e.node.start,r.end=e.node.end,e.stop())}}),r}function et(e){return e.replace(/\s+/g,``)}function tt(e){let t=v.extname(e);return t?e.slice(0,-t.length):e}function F(e){try{return u.existsSync(e)&&u.statSync(e).isFile()}catch{return!1}}async function nt(e){let{dir:t,pattern:n,ignore:r}=e;if(!u.existsSync(t))return[];let i=t,a=j(n);F(t)&&(i=v.dirname(t),a=[v.basename(t)]);try{return(await pe.glob(a,{cwd:i,ignore:j(r),absolute:!0})).map(e=>v.normalize(e))}catch(e){return console.error(`[oiyo] Error scanning file:`,e),[]}}const rt=_e.create.sync({conditionNames:[`require`,`import`,`types`],extensions:[`.ts`,`.js`,`.json`,`.vue`,`.cjs`,`.mjs`]}),I=new Set,it=new Map;function at(e,t){let{cwd:n}=Object.assign({cwd:ge.fileURLToPath(import.meta.url)},t);if(I.has(e))return null;if(it.has(e))return it.get(e);try{let t=rt(n,e);if(!t)return I.add(e),null;let r=v.normalize(t);return it.set(e,r),v.normalize(r)}catch{return I.add(e),null}}const ot=new Map;function st(e,t={cwd:ge.fileURLToPath(import.meta.url)}){let{cwd:n}=t;if(I.has(e))return null;if(ot.has(e))return ot.get(e);let r=at(e,{cwd:n});if(!r)return;let i=v.dirname(r),{root:a}=v.parse(i),o=v.resolve(i,a);for(;i;){let t=v.join(i,`package.json`);if(F(t)){let n=v.dirname(t);return ot.set(e,n),n}if(i===o||i===a)break;i=v.dirname(i)}}function ct(e){if(e.startsWith(`.`)||v.isAbsolute(e))return null;let t=e.split(`/`).filter(Boolean);return t.length===0?null:e.startsWith(`@`)?t.length>=2?`${t[0]}/${t[1]}`:null:t[0]||e}function lt(e){let t=ct(e);if(!t)return null;let n=st(t);return n?{root:n,name:t}:null}function ut(e){try{return S(e,{sourceType:`module`,plugins:[`typescript`]})}catch{return S(`(${e})`,{sourceType:`module`,plugins:[`typescript`]})}}const dt=(e,t)=>{let n=e=>{let r=e.type;return r===`Identifier`?[e.name]:r===`ObjectPattern`?e.properties.flatMap(e=>e.type===`ObjectProperty`?n(e.value):e.type===`RestElement`?n(e.argument):(t?.logger?.debug(`未被识别的 ObjectPattern ${e}`),[])):r===`ArrayPattern`?e.elements.flatMap(e=>e?e.type===`RestElement`?n(e.argument):n(e):[]):r===`AssignmentPattern`?n(e.left):(t?.logger?.debug(`未被识别的 Node ${e}`),[])};return e.flatMap(e=>n(e.id))};async function ft(e,t={}){let n=new Set,r=new Set,i=new Set,a=async e=>{A(ut(await ne.readFile(e,`utf-8`)),{ExportAllDeclaration({node:e}){i.add(e.source.value)},ExportDefaultDeclaration({node:e}){let t=e.declaration;switch(t.type){case`Identifier`:n.add(t.name);break;case`ClassDeclaration`:case`FunctionDeclaration`:t.id?n.add(t.id.name):n.add(`default`);break;default:n.add(`default`);break}},ExportNamedDeclaration({node:e}){if(e.declaration){let i=e.declaration;switch(i.type){case`VariableDeclaration`:dt(i.declarations,{logger:t?.logger}).map(e=>n.add(e));break;case`ClassDeclaration`:case`FunctionDeclaration`:i.id?.name&&n.add(i.id.name);break;case`TSTypeAliasDeclaration`:case`TSInterfaceDeclaration`:t?.includeTypes===!0&&r.add(i.id.name);break;case`TSEnumDeclaration`:case`TSModuleDeclaration`:if(i.id.type===`StringLiteral`)break;n.add(i.id.name);break;case`TSDeclareFunction`:i.id?.name&&n.add(i.id.name);break;default:t?.logger?.debug(`未被识别的 ExportNamedDeclaration.declaration ${i}`);break}}else if(e.specifiers){let i=e.exportKind===`type`;e.specifiers.forEach(e=>{switch(e.type){case`ExportSpecifier`:if(e.exported.type===`StringLiteral`)break;if(i??=e.exportKind===`type`,i){t?.includeTypes===!0&&r.add(e.exported.name);break}n.add(e.exported.name);break;case`ExportNamespaceSpecifier`:n.add(e.exported.name);break;default:t?.logger?.debug(`未被识别的 ExportNamedDeclaration.specifiers ${e}`);break}})}}}),i.size&&await Promise.all(Array.from(i.keys()).map(async t=>{i.delete(t);let n=at(t.startsWith(`.`)?v.join(v.dirname(e),t):t);return n?a(n):Promise.resolve()}))};return await a(e),{values:n,types:r}}function pt(e){let t=ut(e),n=new Set;return A(t,{Program(e){n=new Set(Object.keys(e.scope.globals))}}),n}function mt(e=[],t){return e.reduce((e,n)=>{let r=t(n);return e[r]||(e[r]=[]),e[r].push(n),e},{})}function ht(e,t,n){return n===`default`?`import ${t} from '${e}'`:n===t?`import { ${t} } from '${e}'`:`import { ${n} as ${t} } from '${e}'`}function gt(e,t,n,r){return e=r?.baseDir?v.relative(r?.baseDir,e):e,e=r?.noExtension?tt(e):e,`const ${t}: typeof import('${e}')['${n}'];`}function _t(e,t,n,r){return e=r?.baseDir?v.relative(r?.baseDir,e):e,`${t}: typeof import('${e}')['${n}'];`}function vt(e){if(typeof e!=`string`||e===``)return!1;for(let t of e.matchAll(/(\\).|([@?!+*]\(.*\))/g))if(t[2])return!0;return!1}const yt={"{":`}`,"(":`)`,"[":`]`};function bt(e){if(e[0]===`!`)return!0;let t=0,n=-2,r=-2,i=-2,a=-2,o=-2;for(;t<e.length;){if(e[t]===`*`||e[t+1]===`?`&&/[\].+)]/.test(e[t])||r!==-1&&e[t]===`[`&&e[t+1]!==`]`&&(r<t&&(r=e.indexOf(`]`,t)),r>t&&(o===-1||o>r||(o=e.indexOf(`\\`,t),o===-1||o>r)))||i!==-1&&e[t]===`{`&&e[t+1]!==`}`&&(i=e.indexOf(`}`,t),i>t&&(o=e.indexOf(`\\`,t),o===-1||o>i))||a!==-1&&e[t]===`(`&&e[t+1]===`?`&&/[:!=]/.test(e[t+2])&&e[t+3]!==`)`&&(a=e.indexOf(`)`,t),a>t&&(o=e.indexOf(`\\`,t),o===-1||o>a))||n!==-1&&e[t]===`(`&&e[t+1]!==`|`&&(n<t&&(n=e.indexOf(`|`,t)),n!==-1&&e[n+1]!==`)`&&(a=e.indexOf(`)`,n),a>n&&(o=e.indexOf(`\\`,n),o===-1||o>a))))return!0;if(e[t]===`\\`){let n=e[t+1];t+=2;let r=yt[n];if(r){let n=e.indexOf(r,t);n!==-1&&(t=n+1)}if(e[t]===`!`)return!0}else t++}return!1}function xt(e){return typeof e!=`string`||e===``?!1:vt(e)?!0:bt(e)}const St=/\\/g,Ct=/\\([!*?|[\](){}])/g;function wt(e){ve.platform()===`win32`&&!e.includes(`/`)&&(e=e.replace(St,`/`)),Tt(e)&&(e+=`/`),e+=`a`;do e=ye.posix.dirname(e);while(Et(e));return e.replace(Ct,`$1`)}function Tt(e){let t=e.slice(-1),n;switch(t){case`}`:n=`{`;break;case`]`:n=`[`;break;default:return!1}let r=e.indexOf(n);return r<0?!1:e.slice(r+1,-1).includes(`/`)}function Et(e){return/\([^()]+$/.test(e)||e[0]===`{`||e[0]===`[`||/[^\\][{[]/.test(e)?!0:xt(e)}function L(e){return typeof e==`string`}function Dt(e){let t=v.parse(e);return Qe(t.name===`index`?v.parse(t.dir).name:t.name)}var Ot=class{config;logger;oiyoState;sources=new Map;apis=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`API`),this.oiyoState=t.oiyoState}get srcDir(){return v.resolve(this.config.rootDir,this.config.srcDir)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return v.resolve(this.declarationDir,`apis.d.ts`)}shouldSkipImport(e){return[`definePageMeta`,`defineRootContext`].includes(e)}recordApiSource(e){return e.patterns?.length?(j(e.patterns).forEach(t=>{let n=v.resolve(e.dir,t);this.sources.set(n,e)}),!0):(this.sources.set(e.dir,e),!0)}toApiSource(e){let t={from:``,dir:``,types:!1,patterns:[`*.js`,`*.ts`],isNodeModule:!1};L(e)?t.from=e:Object.assign(t,e);let n=xt(t.from);if(n){let e=t.from,n=wt(t.from);t.from=n,t.patterns=[e.slice(n.length+1)]}let r=lt(t.from);if(r){if(t.isNodeModule=!0,!n)if(t.only?.length)t.dir=t.from,t.patterns=[];else{let n=at(t.from);n?(t.dir=n,t.patterns=[]):this.logger.warn(`无法找到 Api 的扫描源,请注意是否存在该来源 from: ${L(e)?e:e.from}`)}if(!t.dir){let e=v.relative(r.name,t.from);t.dir=v.resolve(r.root,e)}}else t.dir=v.resolve(this.srcDir,t.from);return F(t.dir)&&(t.patterns=[]),this.recordApiSource(t),t}saveApi(e){let t=this.apis.get(e.importName);return t&&t.filePath!==e.filePath?(this.logger.warnOnce(`API名称冲突: “${e.importName}” 已存在,已跳过来自 “${e.importPath}” 的重复导出`),t):(this.apis.set(e.importName,e),e)}async directApi(e){return e.only?.map(t=>{let n={filePath:e.dir,exportName:``,importName:``,importPath:e.from,isNodeModule:!0,isType:!1};return L(t)?(n.exportName=t,n.importName=t):(n.exportName=t.name,n.importName=t.as||t.name,n.isType=!!t.isType),this.saveApi(n),n})}async scanApi(e){let t=await Xe({dir:e.dir,ignore:e.ignore,pattern:e.patterns}),n=new Set;return Promise.all(t.map(async t=>{let r=tt(t);if(n.has(r))return;n.add(r);let{values:i,types:a}=await ft(t,{includeTypes:e.types,logger:this.logger}),o=t;if(e.isNodeModule&&(o=v.join(e.from,v.relative(e.dir,t))),e.exclude?.length&&e.exclude.forEach(e=>i.delete(e)),e.only?.length){e.only.forEach(n=>{let{name:r,as:s,isType:c=!1}=L(n)?{name:n}:n;if(!(c?a.has(r):i.has(r)))return;let l={filePath:t,exportName:r,importName:s??r,importPath:o,isNodeModule:e.isNodeModule,isType:c};this.saveApi(l)});return}i.forEach(n=>{let r={filePath:t,exportName:n,importName:n===`default`?Dt(t):n,importPath:o,isNodeModule:e.isNodeModule,isType:!1};this.saveApi(r)}),a.forEach(n=>{let r={filePath:t,exportName:n,importName:n,importPath:o,isNodeModule:e.isNodeModule,isType:!0};this.saveApi(r)})}))}async scanApis(){let e=this.config.scan?.apis||[];return Promise.all(e.map(async e=>{let t=this.toApiSource(e);return t.isNodeModule&&!F(t.dir)&&t.only?this.directApi(t):this.scanApi(t)}))}findApiSource(e){let t=Array.from([...this.sources.keys()]).find(t=>e===t||v.matchesGlob(e,t));if(t)return this.sources.get(t)}isApi(e){return!!this.findApiSource(e)}async enterApi(e){let t=this.findApiSource(e);if(!t)return this.logger.warn(`未找到Api匹配源无法录入Api`),!1;let{values:n,types:r}=await ft(e,{includeTypes:t.types,logger:this.logger}),i=e;return t.exclude?.length&&t.exclude.forEach(e=>n.delete(e)),t.only?.length?(t.only.forEach(a=>{let{name:o,as:s,isType:c=!1}=L(a)?{name:a}:a;if(!(c?r.has(o):n.has(o)))return;let l={filePath:e,exportName:o,importName:s??o,importPath:i,isNodeModule:t.isNodeModule,isType:c};this.saveApi(l)}),!0):(n.forEach(n=>{let r={filePath:e,exportName:n,importName:n===`default`?Dt(e):n,importPath:i,isNodeModule:t.isNodeModule,isType:!1};this.saveApi(r)}),r.forEach(n=>{let r={filePath:e,exportName:n,importName:n,importPath:i,isNodeModule:t.isNodeModule,isType:!0};this.saveApi(r)}),!0)}exitApi(e){let t=Array.from(this.apis.values()).filter(t=>t.filePath===e);return t.length?(t.forEach(e=>{this.apis.delete(e.importName)}),!0):!1}generateDeclaration(){let e=mt(Array.from(this.apis.values()).sort((e,t)=>e.importName.localeCompare(t.importName)),e=>e.isType?`type`:`value`),t=e.value||[],n=mt(e.type||[],e=>{let t=e.isNodeModule?void 0:this.declarationDir;return t?v.relative(t,e.importPath):e.importPath})||{},r=e=>n[e].map(e=>e.importName===e.exportName?e.importName:`${e.exportName} as ${e.importName}`).join(`, `);return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare global {`,...t.map(e=>` ${gt(e.importPath,e.importName,e.exportName,{baseDir:e.isNodeModule?void 0:this.declarationDir})}`),`}`,``,`declare global {`,...Object.keys(n).map(e=>[` // @ts-ignore`,` export type { ${r(e)} } from '${e}';`].join(`
|
|
9
|
+
`)),`}`,``,`export {}`,``].join(`
|
|
10
|
+
`)}writeDeclaration(){try{u.mkdirSync(this.declarationDir,{recursive:!0}),N(this.declarationFile,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`无法写入 apis.d.ts 组件类型声明,请检查目标文件权限和内容格式:`,{error:e})}}applyApis(e,t){let n=new w(e);if(!e)return{code:n.toString(),map:n.generateMap()};let r=Array.from(pt(e));if(!r.length)return{code:n.toString(),map:n.generateMap()};let i=r.map(e=>{let n=this.apis.get(e);return!n||t&&n.filePath===t||this.shouldSkipImport(e)?null:ht(n.importPath,n.importName,n.exportName)}).filter(e=>!!e);if(!i.length)return{code:n.toString(),map:n.generateMap()};let a=i.join(`
|
|
11
|
+
`);return n.prepend(`${a}\n`),{code:n.toString(),map:n.generateMap()}}};function kt(e){let t=new Set,n=e.matchAll(/<\/?\s*([a-z][\w-]*)\b/gi);for(let e of n)t.add(P(e[1]));return t}function At(e){if(!e||!e.includes(`import`))return new Set;let t=S(e,{sourceType:`module`,plugins:[`typescript`]}),n=new Set;return A(t,{ImportDeclaration(e){for(let t of e.node.specifiers)n.add(t.local.name)}}),n}function jt(e,t,n){let r=v.relative(t,e),{dir:i,name:a}=v.parse(r),o=i&&i!==`.`?i.split(v.sep).filter(Boolean):[];(a!==`index`||o.length===0)&&o.push(a);let s=Mt(o),c=n?.chain===!1?s.slice(-1):s;return`${n?.prefix?P(n?.prefix):``}${c.map(e=>P(e)).join(``)}`}function Mt(e){if(e.length<2)return e;let t=e.slice();return t[t.length-1]===t[t.length-2]&&t.pop(),t}var Nt=class{config;logger;oiyoState;oiyoApi;sources=new Map;components=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`COMPONENT`),this.oiyoState=t.oiyoState,this.oiyoApi=t.oiyoApi}get srcDir(){return v.resolve(this.config.rootDir,this.config.srcDir)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return v.resolve(this.declarationDir,`components.d.ts`)}shouldSkipImport(e){return[`OiyoPage`,`OiyoLayout`].includes(e)}recordComponentSource(e){return e.patterns?.length?(j(e.patterns).forEach(t=>{let n=v.resolve(e.dir,t);this.sources.set(n,e)}),!0):(this.sources.set(e.dir,e),!0)}toComponentSource(e){let t={from:``,dir:``,chain:!0,patterns:[`**/*.vue`,`**/*.nvue`],isNodeModule:!1};if(L(e)?t.from=e:Object.assign(t,e),xt(t.from)){let e=t.from,n=wt(t.from),r=n===`.`;t.from=n,t.patterns=[r?e:e.slice(n.length+1)]}let n=lt(t.from);if(n){t.isNodeModule=!0;let e=v.relative(n.name,t.from);t.dir=v.resolve(n.root,e),t?.only?.length&&(t.patterns=[])}else t.dir=v.resolve(this.srcDir,t.from);return F(t.dir)&&(t.patterns=[]),this.recordComponentSource(t),t}saveComponent(e){let t=this.components.get(e.importName);return t&&t.filePath!==e.filePath?(this.logger.warnOnce(`组件名名称冲突: “${e.importName}” 已存在,已跳过来自 “${e.importPath}” 的重复导出`),!1):(this.components.set(e.importName,e),!0)}async scanComponentByDirect(e){return e.only?.map(t=>{let n={filePath:e.dir,exportName:``,importName:``,importPath:e.from,isNodeModule:!0};return L(t)?(n.exportName=t,n.importName=t):(n.exportName=t.name,n.importName=t.as||t.name),e.prefix&&(n.importName=P(`${e.prefix}${n.importName}`)),this.saveComponent(n),n})}async scanComponentByDir(e){return(await nt({dir:e.dir,ignore:e.ignore,pattern:e.patterns})).map(t=>{let n=jt(t,e.dir===t?v.dirname(t):e.dir,{chain:e.chain,prefix:e.prefix}),r=t;e.isNodeModule&&(r=v.join(e.from,v.relative(e.dir,t)));let i={filePath:t,exportName:`default`,importName:n,importPath:r,isNodeModule:e.isNodeModule};return this.saveComponent(i),i})}async scanComponent(e){return e.isNodeModule&&e.only?.length?this.scanComponentByDirect(e):this.scanComponentByDir(e)}async scanComponents(){let e=this.config.scan?.components||[];await Promise.all(e.map(async e=>{let t=this.toComponentSource(e);await this.scanComponent(t)}))}findComponentSource(e){let t=Array.from([...this.sources.keys()]).find(t=>v.matchesGlob(e,t));if(t)return this.sources.get(t)}isComponent(e){return!!this.findComponentSource(e)}enterComponent(e){let t=this.findComponentSource(e);if(!t)return this.logger.warn(`未找到组件匹配源无法录入组件`),!1;let n={filePath:e,exportName:`default`,importName:jt(e,t.dir===e?v.dirname(e):t.dir,{chain:t.chain,prefix:t.prefix}),importPath:e,isNodeModule:!1};return this.saveComponent(n),!0}exitComponent(e){let t=Array.from(this.components.values()).find(t=>t.filePath===e);if(t)return this.components.delete(t.importName),t}generateDeclaration(){return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare module 'vue' {`,` export interface GlobalComponents {`,...Array.from(this.components.values()).sort((e,t)=>e.importName.localeCompare(t.importName)).map(e=>` ${_t(e.importPath,e.importName,e.exportName,{baseDir:e.isNodeModule?void 0:this.declarationDir})}`),` }`,`}`,``,`export {}`,``].join(`
|
|
12
|
+
`)}writeDeclaration(){try{u.mkdirSync(this.declarationDir,{recursive:!0}),N(this.declarationFile,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`无法写入 components.d.ts 组件类型声明,请检查目标文件权限和内容格式:`,{error:e})}}applyComponents(e,t,n={withApis:!0}){let{descriptor:r}=T(e),i=new w(e),a=r.template?.content;if(!a)return{code:i.toString(),map:i.generateMap()};let o=Array.from(kt(a)),s=o,c=[],l=[r.scriptSetup?.content,r.script?.content].filter(e=>!!e);if(l.length){let[e,t]=l.flatMap(e=>[At(e),pt(e)]);s=o.filter(t=>!e.has(t)),n?.withApis&&(c=Array.from(t))}if(!s.length&&!c.length)return{code:i.toString(),map:i.generateMap()};let u=s.map(e=>{let n=this.components.get(e);return!n||t&&n.filePath===t||this.shouldSkipImport(e)?null:ht(n.importPath,n.importName,n.exportName)}).filter(e=>!!e),d=c.map(e=>{let n=this.oiyoApi.apis.get(e);return!n||t&&n.filePath===t||this.oiyoApi.shouldSkipImport(e)?null:ht(n.importPath,n.importName,n.exportName)}).filter(e=>!!e);if(!u.length&&!d.length)return{code:i.toString(),map:i.generateMap()};let f=[...u,...d].join(`
|
|
13
|
+
`),p=r.scriptSetup;if(!p){let e=[`<script setup>`,f,`<\/script>`].join(`
|
|
14
|
+
`);return i.prepend(`${e}\n\n`),{code:i.toString(),map:i.generateMap()}}return i.appendRight(p.loc.start.offset,`\n${f}`),{code:i.toString(),map:i.generateMap()}}};function Pt(e){return e.includes(`<OiyoLayout`)||e.includes(`<oiyo-layout`)}function Ft(e){let t=e;return t=t.replace(/<OiyoLayout[^>]*?\/>/g,``),t=t.replace(/<OiyoLayout[^>]*>/g,``),t=t.replace(/<\/OiyoLayout>/g,``),t=t.replace(/<oiyo-layout[^>]*?\/>/g,``),t=t.replace(/<oiyo-layout[^>]*>/g,``),t=t.replace(/<\/oiyo-layout>/g,``),t}function It(e,t){let n=e;return n=n.replace(/<OiyoLayout[^>]*?\/>/g,``),n=n.replace(/<OiyoLayout[^>]*>/g,`<${t}>`),n=n.replace(/<\/OiyoLayout>/g,`</${t}>`),n=n.replace(/<oiyo-layout[^>]*?\/>/g,``),n=n.replace(/<oiyo-layout[^>]*>/g,`<${t}>`),n=n.replace(/<\/oiyo-layout>/g,`</${t}>`),n}function Lt(e,t){let{dir:n,name:r}=ce(le(t,e));return(n&&n!==`.`?[...n.split(ue),r]:[r]).map(e=>Ze(e)).join(`-`)}function Rt(e){return`OiyoLayout${e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}`}var zt=class{config;logger;oiyoState;layouts=new Map;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`LAYOUT`),this.oiyoState=t.oiyoState}get srcDir(){return v.resolve(this.config.rootDir,this.config.srcDir)}get layoutDir(){return v.resolve(this.srcDir,this.config.dir?.layouts||`layouts`)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return v.resolve(this.declarationDir,`layouts.d.ts`)}toLayout(e){let t=Lt(e,this.layoutDir);return{filePath:e,componentName:Rt(t),useName:t}}saveLayout(e){return this.layouts.has(e.useName)?!1:(this.layouts.set(e.useName,e),!0)}async scanLayouts(){return(await Xe({dir:this.layoutDir,pattern:[`**/*.vue`,`**/*.nvue`],ignore:[...we,...this.config.exclude||[]]})).forEach(e=>{let t=this.toLayout(e);this.saveLayout(t)&&this.logger.debug(`通过“扫描模式”录入页面: ${t.useName}`)}),this.layouts}isLayout(e){return!e.endsWith(`.vue`)&&!e.endsWith(`.nvue`)||[...we,...this.config.exclude||[]].some(t=>v.matchesGlob(e,t))?!1:e.startsWith(`${this.layoutDir}/`)}enterLayout(e){let t=this.toLayout(e),n=this.saveLayout(t);return n&&this.logger.debug(`通过“主动模式”录入布局: ${t.useName}`),n}exitLayout(e){let t=Array.from(this.layouts.values()).find(t=>t.filePath===e);if(!t)return!1;let n=this.layouts.delete(t.useName);return n&&this.logger.debug(`通过“主动模式”脱离布局: ${t.useName}`),n}generateDeclaration(){return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`declare module '@skiyee/oiyo/api' {`,` interface OiyoLayouts {`,...Array.from(this.layouts.values()).sort((e,t)=>e.useName.localeCompare(t.useName)).map(({useName:e,filePath:t})=>` ${_t(t,`'${e}'`,`default`,{baseDir:this.declarationDir})}`),` }`,``,` type LayoutKey = keyof OiyoLayouts extends never ? string : keyof OiyoLayouts;`,``,` interface PageMeta {`,` layout?: LayoutKey | false;`,` }`,`}`,``,`export {}`,``].join(`
|
|
15
|
+
`)}writeDeclaration(){try{return f(this.declarationDir,{recursive:!0}),N(this.declarationFile,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),!0}catch(e){return this.logger.error(`无法写入 layouts.d.ts 布局类型声明,请检查目标文件权限和内容格式:`,{error:e}),!1}}applyLayout(e,t){if(!Pt(t))return{template:t,script:``,imports:[]};if(e===!1)return{template:Ft(t),script:``,imports:[]};e===void 0&&(e=`default`);let n=this.layouts.get(e);return n?{template:It(t,n.componentName),script:``,imports:[`import ${n.componentName} from '${n.filePath}'`]}:(this.logger.error(`未找到布局 "${e}",请检查布局名称或文件位置是否正确`),{template:t,script:``,imports:[]})}};const Bt=Ee({name:`OiyoLayout`,setup(e,t){return()=>t.slots.default?.()}});function Vt(e,t){let n=ut(e),r={start:0,end:0};return A(n,{CallExpression(e){let{callee:n,arguments:i}=e.node;n.type===`Identifier`&&n.name===t&&i.length>0&&e.node.start!=null&&e.node.end!=null&&(r.start=e.node.start,r.end=e.node.end,e.stop())}}),r}function Ht(e){if(!e.includes(`defineRootContext`))return``;let{descriptor:t}=T(e);if(!t.scriptSetup)return``;let n=e=t.scriptSetup.content,r=Ut(n);return n.substring(r.start,r.end+1).trim()}function Ut(e){return Vt(e,`defineRootContext`)}function Wt(e){if(!e.includes(`<template`))return``;let{descriptor:t}=T(e);return(t.template?.content||``).trim()}function Gt(e,t){let n=e.replace(/\{\{([\s\S]*?)\}\}/g,(e,n)=>e.replace(n,Kt(n,t)));return n=n.replace(/((?:v-(?!for\b)[\w-]+(?::[\w-]+)?|[:@][\w-]+)\s*=\s*)(["'])([\s\S]*?)\2/g,(e,n,r,i)=>`${n}${r}${Kt(i,t)}${r}`),n}function Kt(e,t){let n=new Map;t.varName&&n.set(t.varName,`$oiyoRootContext`);for(let{local:e,original:r}of t.varProperties||[])n.set(e,`$oiyoRootContext.${r}`);if(n.size===0)return e;try{let t=S(`(${e})`,{sourceType:`module`,plugins:[`typescript`]}),r=new w(e);return A(t,{Identifier(e){if(!e.isReferencedIdentifier())return;let t=n.get(e.node.name);if(!t)return;let i=e.node.start,a=e.node.end;if(!(i==null||a==null)){if(e.parentPath.isObjectProperty()&&e.parent.shorthand&&e.parent.value===e.node){r.overwrite(i-1,a-1,`${e.node.name}: ${t}`);return}r.overwrite(i-1,a-1,t)}}}),r.toString()}catch{return e}}function qt(e,t){if(!e)throw Error(`[oiyo] App.vue 必须包含 <template> 节点`);let n=e.content;if(!(n.includes(`<OiyoPage`)||n.includes(`<oiyo-page`)))throw Error(`[oiyo] App.vue 的 template 必须包含 <OiyoPage /> 或 <oiyo-page /> 占位节点`);return n=Gt(n,t),n.trim()}function Jt(e){if(!e)return;let t=e?.content;if(t){let e=Yt(t);return e.script?e:void 0}}function Yt(e){let t=S(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return A(t,{ImportDeclaration(t){let r=e.substring(t.node.start,t.node.end);n.imports??=[],n.imports.push(r)},CallExpression(t){let{callee:r,arguments:i}=t.node;if(r.type===`Identifier`&&r.name===`defineRootContext`&&i.length>0){let r=i[0];r.start!=null&&r.end!=null&&(n.script=e.substring(r.start,r.end));let a=t.findParent(e=>e.isVariableDeclarator());if(a&&a.isVariableDeclarator()){let e=a.node.id;e.type===`Identifier`?n.variable=e.name:e.type===`ObjectPattern`&&(n.properties=e.properties.filter(e=>e.type===`ObjectProperty`).map(e=>({original:e.key.type===`Identifier`?e.key.name:String(e.key.value),local:e.value.type===`Identifier`?e.value.name:e.key.name})))}}}}),n}function Xt(e,t){let n=e;return n=n.replace(/<OiyoPage[^>]*?\/>/g,t),n=n.replace(/<OiyoPage[^>]*>\s*<\/OiyoPage>/g,t),n=n.replace(/<oiyo-page[^>]*?\/>/g,t),n=n.replace(/<oiyo-page[^>]*>\s*<\/oiyo-page>/g,t),n}const Zt=`virtual:oiyo-root-context`,R=`\0${Zt}`;function Qt(e){let{script:t,imports:n}=e,r=[];return n?.length&&(r.push(...n),r.push(``)),t?r.push(`let rootContextInstance = null`,``,`export function useRootContext() {`,` if (!rootContextInstance) {`,` const factory = ${t}`,` rootContextInstance = factory()`,` }`,``,` return rootContextInstance`,`}`):r.push(`export function useRootContext() {`,` return {}`,`}`),r.join(`
|
|
16
|
+
`)}var $t=class{config;rootView={imports:[],template:`<OiyoPage />`,script:``};rootVM;rootMarco;logger;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`ROOT`)}get srcDir(){return x(this.config.rootDir,this.config.srcDir)}get rootPath(){return x(this.srcDir,`App.vue`)}isRootPath(e){return e===this.rootPath}parseRoot(e){let{descriptor:t}=T(e),n=Jt(t.scriptSetup),r=qt(t.template,{varName:n?.variable,varProperties:n?.properties});return this.rootView={template:r,imports:[],script:``},n&&(this.rootMarco=n,this.rootVM=Qt(n),n.script&&(this.rootView.imports.push(`import { useRootContext } from 'virtual:oiyo-root-context'`),this.rootView.script=`const $oiyoRootContext = useRootContext()`)),{view:this.rootView,marco:n}}transformRoot(e){let{descriptor:t}=T(e),n=new w(e);if(t.template){let e=t.template.loc.start.offset-10,r=t.template.loc.end.offset+11;n.remove(e,r)}if(t.scriptSetup){let e=t.scriptSetup.content,r=Ut(e);if(r.start!==r.end){e.includes(`virtual:oiyo-root-context`)||n.appendLeft(t.scriptSetup.loc.start.offset,`
|
|
14
17
|
import { useRootContext } from 'virtual:oiyo-root-context'
|
|
15
|
-
`);let i=t.scriptSetup.loc.start.offset+r.start,a=t.scriptSetup.loc.start.offset+r.end;i!==a&&n.overwrite(i,a,`useRootContext()`)}}return{code:n.toString(),sourceMap:n.generateMap()}}shouldRefreshView(e){return
|
|
16
|
-
`):`string`}function
|
|
18
|
+
`);let i=t.scriptSetup.loc.start.offset+r.start,a=t.scriptSetup.loc.start.offset+r.end;i!==a&&n.overwrite(i,a,`useRootContext()`)}}return{code:n.toString(),sourceMap:n.generateMap()}}shouldRefreshView(e){return M(this.rootView.template)!==M(Wt(e))}shouldRefreshVM=e=>{let t=``;this.rootMarco&&(t=M(et(`defineRootContext(${this.rootMarco.script})`)));let n=M(et(Ht(e)));return t!==n};applyRoot(e){let t=[],n=``,r=``;return e.template&&(n=Xt(this.rootView.template,e.template.content)),t.push(...this.rootView.imports),r=`${this.rootView.script}\n${e.scriptSetup?.content||``}`,{imports:t,script:r,template:n}}};const en=e=>e();function tn(e,...t){let n=[e,...t],r={...e},i=nn(n),a=rn(n),o=an(n);return i&&(r.pages=i),a&&(r.subPackages=a),o&&(r.tabBar={...on(n),list:o}),r}function nn(e){let t=[],n=!1;for(let r of e)r.pages&&(n=!0,t.push(...r.pages));return n?z(t,e=>e.path):void 0}function rn(e){let t=new Map,n=!1;for(let r of e)if(r.subPackages){n=!0;for(let e of r.subPackages){let n=t.get(e.root);if(!n){t.set(e.root,{...e,pages:z(e.pages??[],e=>e.path)});continue}t.set(e.root,{...n,...e,pages:z([...n.pages??[],...e.pages??[]],e=>e.path)})}}return n?[...t.values()]:void 0}function an(e){let t=[],n=!1;for(let r of e)r.tabBar?.list&&(n=!0,t.push(...r.tabBar.list));return n?z(t,e=>e.pagePath):void 0}function on(e){let t;for(let n of e)n.tabBar&&(t={...t,...n.tabBar});return t}function z(e,t){let n=new Set,r=[];for(let i=e.length-1;i>=0;i--){let a=e[i],o=t(a);if(o===void 0){r.unshift(a);continue}n.has(o)||(n.add(o),r.unshift(a))}return r}function sn(e,t){if(!e.includes(`definePageMeta`))return``;if(!t){let{descriptor:t}=T(e);if(!t.scriptSetup)return``;e=t.scriptSetup.content}let n=cn(e);return e.substring(n.start,n.end+1).trim()}function cn(e){return $e(e,`definePageMeta`)}function ln(e){return e.replace(/definePageMeta\s*\(\s*\{[\s\S]*?\}\s*\)/g,``).trim()}function un(e){if(!e)return{};let t=S(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return A(t,{CallExpression(e){let{callee:t,arguments:r}=e.node;if(t.type===`Identifier`&&t.name===`definePageMeta`&&r.length>0){let t=r[0];t.type===`ObjectExpression`&&(n=dn(t),e.stop())}}}),n}function dn(e){let t={};for(let n of e.properties)if(n.type===`ObjectProperty`){let e=fn(n.key),r=pn(n.value);e&&(t[e]=r)}return t}function fn(e){return e.type===`Identifier`?e.name:e.type===`StringLiteral`?e.value:null}function pn(e){switch(e.type){case`StringLiteral`:return e.value;case`NumericLiteral`:return e.value;case`BooleanLiteral`:return e.value;case`NullLiteral`:return null;case`ArrayExpression`:return e.elements.map(e=>pn(e)).filter(e=>e!==void 0);case`ObjectExpression`:return dn(e);default:return}}function mn(e){return`'${e.startsWith(`/`)?e:`/${e}`}'`}function hn(e){let t=new Set;for(let n of e.pages||[])t.add(mn(n.path));for(let n of e.subPackages||[])for(let e of n.pages||[])t.add(mn(y(n.root,e.path)));return Array.from(t).sort()}function gn(e){let t=new Set;for(let n of e.tabBar?.list||[])t.add(mn(n.pagePath));return Array.from(t).sort()}function _n(e){return e.length>0?e.join(` |
|
|
19
|
+
`):`string`}function vn(e){let t=e.map(e=>({path:e.pagePath,belong:e.pageBelong,...e.pageMeta})),n=[],r=new Map;t.forEach(e=>{if(e.belong===`pages`)n.push(e);else{let t=r.get(e.belong)||[];t.push(e),r.set(e.belong,t)}}),n.sort((e,t)=>{let r=n.find(t=>t.path===e.path)?.type===`home`,i=n.find(e=>e.path===t.path)?.type===`home`;return r&&!i?-1:!r&&i?1:e.path.localeCompare(t.path)});let i={pages:n.map(e=>{let{belong:t,...n}=e;return n})};return r.size>0&&(i.subPackages=Array.from(r.entries()).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({root:e,pages:t.sort((e,t)=>e.path.localeCompare(t.path)).map(e=>{let{belong:t,...n}=e;return n})}))),i}function yn(e){let t=hn(e),n=gn(e);return[`// Generated by oiyo(https://oiyo.js.org)`,`/* eslint-disable */`,`/* prettier-ignore */`,`// @ts-nocheck`,`interface NavigateToOptions {`,` url: ${_n(t)};`,`}`,`interface RedirectToOptions extends NavigateToOptions {}`,``,`interface SwitchTabOptions {`,n.length>0?` url: ${n.join(` |
|
|
17
20
|
`)};`:``,`}`,``,`type ReLaunchOptions = NavigateToOptions | SwitchTabOptions;`,``,`declare global {`,` interface Uni {`,` navigateTo(options: UniNamespace.NavigateToOptions & NavigateToOptions): void;`,` redirectTo(options: UniNamespace.RedirectToOptions & RedirectToOptions): void;`,` switchTab(options: UniNamespace.SwitchTabOptions & SwitchTabOptions): void;`,` reLaunch(options: UniNamespace.ReLaunchOptions & ReLaunchOptions): void;`,` }`,`}`,``,`export {}`,``].join(`
|
|
18
|
-
`)}
|
|
21
|
+
`)}function bn(e){if(!e||!e.includes(`import`))return[];let t=S(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];return A(t,{ImportDeclaration(t){let r=e.substring(t.node.start,t.node.end);n.push(r)}}),n}function xn(e){if(!e||!e.includes(`import`))return e;let t=S(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];A(t,{ImportDeclaration(e){n.push({start:e.node.start,end:e.node.end})}}),n.sort((e,t)=>t.start-e.start);let r=e;for(let e of n)r=r.substring(0,e.start)+r.substring(e.end);return r.trim()}function Sn(e,t){let n=Cn(t),r=Cn(e);for(let[e,t]of r){let r=n.get(e);r?wn(r,t):n.set(e,t)}return Tn(n)}function Cn(e){let t=new Map;for(let n of e)A(S(n,{sourceType:`module`,plugins:[`typescript`]}),{ImportDeclaration(e){let{node:r}=e,i=r.source.value,a=t.get(i);a||(a={source:i,named:new Set,original:n},t.set(i,a));for(let e of r.specifiers)if(e.type===`ImportSpecifier`){let t=e.imported.type===`Identifier`?e.imported.name:e.imported.value;a.named.add(t)}else e.type===`ImportDefaultSpecifier`?a.defaultImport=e.local.name:e.type===`ImportNamespaceSpecifier`&&(a.namespaceImport=e.local.name)}});return t}function wn(e,t){for(let n of t.named)e.named.add(n);!e.defaultImport&&t.defaultImport&&(e.defaultImport=t.defaultImport),!e.namespaceImport&&t.namespaceImport&&(e.namespaceImport=t.namespaceImport)}function Tn(e){let t=[];for(let[n,r]of e){if(n.includes(`_fallback_`)){t.push(r.original);continue}let e=[];if(r.defaultImport&&e.push(r.defaultImport),r.namespaceImport&&e.push(`* as ${r.namespaceImport}`),r.named.size>0){let t=Array.from(r.named).sort();e.push(`{ ${t.join(`, `)} }`)}e.length>0?t.push(`import ${e.join(`, `)} from '${n}'`):t.push(`import '${n}'`)}return t}var En=class{config;logger;oiyoState;oiyoRoot;oiyoLayout;pages=new Map;pagesConfig={};pagesConfigWatcher;constructor(e,t){this.config=e,this.logger=t.logger.withScope(`ROUTE`),this.oiyoState=t.oiyoState,this.oiyoRoot=t.oiyoRoot,this.oiyoLayout=t.oiyoLayout}get srcDir(){return v.resolve(this.config.rootDir,this.config.srcDir)}get mainPageDir(){return v.resolve(this.srcDir,this.config.dir.mainPackage)}get subPageDirs(){return[...he(`*`,{cwd:v.resolve(this.srcDir,`packages`),deep:1,absolute:!0,onlyDirectories:!0,ignore:j(this.config.exclude)}),...this.config.dir.subPackages].map(e=>v.resolve(this.srcDir,e))}get pagesJsonFile(){return v.resolve(this.srcDir,`pages.json`)}get declarationDir(){return this.oiyoState.typesDir}get declarationFile(){return v.resolve(this.declarationDir,`pages.d.ts`)}toPage(e,t){let n=!0,r=this.mainPageDir,i=this.subPageDirs.find(t=>e.startsWith(`${t}/`));i&&(n=!1);let a=n?this.srcDir:i,o=v.relative(a,e),s=v.parse(o),c=s.dir===``?s.name:v.join(s.dir,s.name),l=n?r:i;return{filePath:e,pagePath:c,pageBelong:v.relative(this.srcDir,l),pageMeta:t||{}}}savePage(e){if(!this.pages.has(e.filePath))return this.pages.set(e.filePath,e),!0;let t=this.pages.get(e.filePath),n=JSON.stringify(t.pageMeta)!==JSON.stringify(e.pageMeta);return n&&this.pages.set(e.filePath,e),n}async loadPagesConfig(){try{let{config:e,configFile:t}=await De({configFile:`pages.config`,cwd:this.srcDir});this.pagesConfig=e||{}}catch{this.pagesConfig={},this.logger.warn(`无法加载 pages.config.* 配置,已采用空配置`)}return this.pagesConfig}async loadPagesJson(){try{let e=await g(this.pagesJsonFile,`utf-8`),t=JSON.parse(e);this.pagesConfig=t}catch(e){this.logger.error(`加载 pages.json 路由文件失败,已跳过现有文件内容,请检查 pages.json 是否存在且格式正确:`,{error:e})}}async scanPages(){await this.loadPagesConfig();let e=[this.mainPageDir,...this.subPageDirs],t=(await Promise.all(e.map(e=>Xe({dir:e,pattern:[`**/*.vue`,`**/*.nvue`]})))).flat(2).filter(e=>this.isPage(e));return await Promise.all(t.map(async e=>{let t=await g(e,`utf-8`),n={},r=sn(t);r&&(n=un(r));let i=this.toPage(e,n);this.savePage(i)&&this.logger.debug(`通过“扫描模式”录入页面: ${i.pageBelong}&${i.pagePath}`)})),this.pages}isPage(e){return!e.endsWith(`.vue`)&&!e.endsWith(`.nvue`)||[...we,...this.config.exclude||[]].some(t=>v.matchesGlob(e,t))?!1:[this.mainPageDir,...this.subPageDirs].some(t=>e.startsWith(`${t}/`))}enterPage(e){let t=this.toPage(e),n=this.savePage(t);return n&&this.logger.debug(`通过“主动模式”录入页面: ${t.pageBelong}&${t.pagePath}`),n}exitPage(e){if(!this.pages.has(e))return!1;let t=this.pages.get(e),n=this.pages.delete(e);return n&&this.logger.debug(`通过“主动模式”脱离页面: ${t.pageBelong}&${t.pagePath}`),n}resolvePagesJson(e){return tn(vn(Array.from(this.pages.values())),e||this.pagesConfig)}writePagesJson(e){try{let t=this.resolvePagesJson(e),n=`${JSON.stringify(t,null,2)}\n`;return N(this.pagesJsonFile,n),!0}catch(e){return this.logger.error(`无法写入 pages.json 路由文件,请检查目标文件权限和内容格式:`,{error:e}),!1}}generateDeclaration(e){return yn(this.resolvePagesJson(e))}writeDeclaration(e){try{f(this.declarationDir,{recursive:!0}),N(this.declarationFile,this.generateDeclaration(e)),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`无法写入 pages.d.ts 页面类型声明,请检查目标文件权限和内容格式:`,{error:e})}return this.declarationFile}async watchPagesConfig(e){if(this.pagesConfigWatcher)return;let t=await Oe({configFile:`pages.config`,cwd:this.srcDir,acceptHMR({getDiff:e}){return e().length===0},onWatch:e=>{},onUpdate:({newConfig:t})=>{this.pagesConfig=t.config||{},e&&Promise.resolve(e()).catch(e=>{this.logger.error(`无法触发 pages.config.* 配置更新回调,页面配置已更新,但后续回调未完成`,{error:e})})}});this.pagesConfig=t.config||this.pagesConfig,this.pagesConfigWatcher=t}async unwatchPagesConfig(){this.pagesConfigWatcher&&=(await this.pagesConfigWatcher.unwatch(),void 0)}async transformPage(e,t){if(!this.oiyoRoot||!this.oiyoLayout)throw Error(`[oiyo] Dependencies are missing; please contact skiyee(319619193@qq.com) to fix them.`);let{descriptor:n}=T(e),r=new w(e);if(!n.template?.content)return{code:r.toString(),sourceMap:r.generateMap()};if(n.scriptSetup){let e=un(n.scriptSetup.content),r=this.toPage(t,e);this.savePage(r)&&(this.writePagesJson()&&this.writeDeclaration(),await new Promise(e=>setTimeout(e,100)))}let i=this.oiyoRoot.applyRoot(n),a=[...i.imports],o=i.template,s=i.script,c={};n.scriptSetup&&(c=this.pages.get(t)?.pageMeta||{},s=ln(s));let l=this.oiyoLayout.applyLayout(c.layout,o);if(o=l.template,a.push(...l.imports),r.overwrite(n.template.loc.start.offset,n.template.loc.end.offset,o),n.scriptSetup){let e=bn(n.scriptSetup.content);a=Sn(a,e),s=xn(s),r.overwrite(n.scriptSetup.loc.start.offset,n.scriptSetup.loc.end.offset,`${a.join(`
|
|
19
22
|
`)}\n${s}`)}else if(s||a.length>0){let e=[`<script setup>`,...a,s,`<\/script>`].filter(Boolean).join(`
|
|
20
|
-
`);r.appendRight(n.template.loc.end.offset+11,`\n\n${e}`)}return{code:r.toString(),sourceMap:r.generateMap()}}};const Ln=new Set([`.ts`,`.mts`,`.cts`,`.js`,`.mjs`,`.cjs`,`.tsx`,`.jsx`]);function Rn(e){return e.endsWith(`.vue`)||e.endsWith(`.nvue`)}function zn(e){return Array.from(Ln).some(t=>e.endsWith(t))}function Bn(e){return b(e.split(`?`,1)[0])}function V(e,t){return[...e,t].filter(Boolean).join(`
|
|
21
|
-
`)}function Vn(e,t,n){let r=[`<script setup>`,n,`<\/script>`].filter(Boolean).join(`
|
|
22
|
-
`);if(t.template){e.appendRight(t.template.loc.end.offset+11,`\n\n${r}`);return}e.append(`\n${r}`)}function Hn(e,t,n){let r=z(n,tn(t.content)),i=rn(t.content);e.overwrite(t.loc.start.offset,t.loc.end.offset,V(r,i))}function Un(e){let t=new Set,n=e.matchAll(/<\/?\s*([a-z][\w-]*)\b/gi);for(let e of n){let n=e[1];t.add(n.includes(`-`)?n.split(`-`).filter(Boolean).map(e=>e[0].toUpperCase()+e.slice(1)).join(``):n)}return t}function Wn(e){let t=new Set;return e.script?.content&&nn(e.script.content).forEach(e=>t.add(e)),e.scriptSetup?.content&&nn(e.scriptSetup.content).forEach(e=>t.add(e)),t}function Gn(e,t){let n=nn(e),r=t.autoApi.resolveImports(e,{boundNames:n});if(r.length===0)return null;let i=z(r,tn(e)),a=rn(e),o=new E(e);return o.overwrite(0,e.length,V(i,a)),{code:o.toString(),sourceMap:o.generateMap()}}function Kn(e,t,n){let{descriptor:r}=T(e),i=Wn(r),a=r.template?.content?Array.from(Un(r.template.content)).filter(e=>!i.has(e)).map(e=>n.autoComponent.resolveComponentImport(e,t)).filter(e=>!!e):[],o=r.scriptSetup?.content?n.autoApi.resolveImports(r.scriptSetup.content,{boundNames:i}):r.script?.content?n.autoApi.resolveImports(r.script.content,{boundNames:i}):[];if(a.length===0&&o.length===0)return null;let s=new E(e);return r.scriptSetup?(Hn(s,r.scriptSetup,[...a,...o]),{code:s.toString(),sourceMap:s.generateMap()}):r.script?(o.length>0&&Hn(s,r.script,o),a.length>0&&Vn(s,r,V(a,``)),{code:s.toString(),sourceMap:s.generateMap()}):(Vn(s,r,V([...a,...o],``)),{code:s.toString(),sourceMap:s.generateMap()})}function qn(){let e;return[{name:`oiyo:auto`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`AUTO`)},transform(t,n){let r=Bn(n);return zn(r)?r.startsWith(`${e.root.srcDir}/`)&&Gn(t,e)||void 0:!Rn(r)||!r.startsWith(`${e.root.srcDir}/`)&&r!==e.root.rootPath?void 0:Kn(t,r,e)||void 0}}]}const H={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},Jn={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:H.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Jn);const Yn=`READDIRP_RECURSIVE_ERROR`,Xn=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,Yn]),Zn=[H.DIR_TYPE,H.EVERYTHING_TYPE,H.FILE_DIR_TYPE,H.FILE_TYPE],Qn=new Set([H.DIR_TYPE,H.EVERYTHING_TYPE,H.FILE_DIR_TYPE]),$n=new Set([H.EVERYTHING_TYPE,H.FILE_DIR_TYPE,H.FILE_TYPE]),er=e=>Xn.has(e.code),tr=process.platform===`win32`,nr=e=>!0,rr=e=>{if(e===void 0)return nr;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return nr};var ir=class extends De{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...Jn,...e},{root:n,type:r}=t;this._fileFilter=rr(t.fileFilter),this._directoryFilter=rr(t.directoryFilter);let i=t.lstat?p:g;tr?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??Jn.depth,this._wantsDir=r?Qn.has(r):!1,this._wantsFile=r?$n.has(r):!1,this._wantsEverything=r===H.EVERYTHING_TYPE,this._root=Ae(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await ie(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=Ae(Oe(t,r));n={path:ke(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){er(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await h(t),n=await p(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===je){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=Yn,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function ar(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=H.FILE_DIR_TYPE),n&&(t.type=n),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!Zn.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${Zn.join(`, `)}`);return t.root=e,new ir(t)}const or=()=>{},U=process.platform,sr=U===`win32`,cr=U===`darwin`,lr=U===`linux`,ur=U===`freebsd`,dr=Me()===`OS400`,W={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},G=W,fr={lstat:xe,stat:Te},K=`listeners`,q=`errHandlers`,J=`rawEmitters`,pr=[K,q,J],mr=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),hr=e=>mr.has(D.extname(e).slice(1).toLowerCase()),gr=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},Y=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},_r=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},X=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},vr=e=>e instanceof Set?e.size===0:!e,Z=new Map;function yr(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&Q(D.resolve(e,r),K,D.join(e,r))};try{return ye(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const Q=(e,t,n,r,i)=>{let a=Z.get(e);a&&gr(a[t],e=>{e(n,r,i)})},br=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Z.get(t),c;if(!n.persistent)return c=yr(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)Y(s,K,i),Y(s,q,a),Y(s,J,o);else{if(c=yr(e,n,Q.bind(null,t,K),a,Q.bind(null,t,J)),!c)return;c.on(G.ERROR,async n=>{let r=Q.bind(null,t,q);if(s&&(s.watcherUnusable=!0),sr&&n.code===`EPERM`)try{await(await Se(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},Z.set(t,s)}return()=>{X(s,K,i),X(s,q,a),X(s,J,o),vr(s.listeners)&&(s.watcher.close(),Z.delete(t),pr.forEach(_r(s)),s.watcher=void 0,Object.freeze(s))}},xr=new Map,Sr=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=xr.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(ve(t),o=void 0),o?(Y(o,K,i),Y(o,J,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:be(t,n,(n,r)=>{gr(o.rawEmitters,e=>{e(G.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&gr(o.listeners,t=>t(e,n))})},xr.set(t,o)),()=>{X(o,K,i),X(o,J,a),vr(o.listeners)&&(xr.delete(t),ve(t),o.options=o.watcher=void 0,Object.freeze(o))}};var Cr=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=D.dirname(e),i=D.basename(e);this.fsw._getWatchedDir(r).add(i);let a=D.resolve(e),o={persistent:n.persistent};t||=or;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&hr(i)?n.binaryInterval:n.interval,s=Sr(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=br(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=D.dirname(e),i=D.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(`watch`,e,5)){if(!n||n.mtimeMs===0)try{let n=await Te(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(G.CHANGE,e,n),(cr||lr||ur)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(G.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(G.ADD,e,0))return;this.fsw._emit(G.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await we(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(G.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(G.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){if(e=D.join(e,``),o=this.fsw._throttle(`readdir`,e,1e3),!o)return;let s=this.fsw._getWatchedDir(n.path),c=new Set,l=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(l)return l.on(`data`,async o=>{if(this.fsw.closed){l=void 0;return}let u=o.path,d=D.join(e,u);if(c.add(u),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,d,u))){if(this.fsw.closed){l=void 0;return}(u===r||!r&&!s.has(u))&&(this.fsw._incrReadyCount(),d=D.join(i,D.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(G.ERROR,this._boundHandleError),new Promise((t,u)=>{if(!l)return u();l.once(`end`,()=>{if(this.fsw.closed){l=void 0;return}let u=o?o.clear():!1;t(void 0),s.getChildren().filter(t=>t!==e&&!c.has(t)).forEach(t=>{this.fsw._remove(e,t)}),l=void 0,u&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(D.dirname(e)),c=s.has(D.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(G.ADD_DIR,e,t),s.add(D.basename(e)),this.fsw._getWatchedDir(e);let l,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,void 0),this.fsw.closed))return;l=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,void 0)})}return l}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await fr[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=D.resolve(e),l=s?await we(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await we(e):e;if(this.fsw.closed)return;let a=D.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(G.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(D.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}};
|
|
23
|
+
`);r.appendRight(n.template.loc.end.offset+11,`\n\n${e}`)}return{code:r.toString(),sourceMap:r.generateMap()}}};const Dn=e=>{},On=Ee({name:`OiyoPage`}),B={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},kn={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:B.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(kn);const An=`READDIRP_RECURSIVE_ERROR`,jn=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,An]),Mn=[B.DIR_TYPE,B.EVERYTHING_TYPE,B.FILE_DIR_TYPE,B.FILE_TYPE],Nn=new Set([B.DIR_TYPE,B.EVERYTHING_TYPE,B.FILE_DIR_TYPE]),Pn=new Set([B.EVERYTHING_TYPE,B.FILE_DIR_TYPE,B.FILE_TYPE]),Fn=e=>jn.has(e.code),In=process.platform===`win32`,Ln=e=>!0,Rn=e=>{if(e===void 0)return Ln;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return Ln};var zn=class extends Le{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...kn,...e},{root:n,type:r}=t;this._fileFilter=Rn(t.fileFilter),this._directoryFilter=Rn(t.directoryFilter);let i=t.lstat?re:ae;In?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??kn.depth,this._wantsDir=r?Nn.has(r):!1,this._wantsFile=r?Pn.has(r):!1,this._wantsEverything=r===B.EVERYTHING_TYPE,this._root=Se(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await _(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=Se(be(t,r));n={path:xe(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){Fn(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await ie(t),n=await re(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===Ce){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=An,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function Bn(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=B.FILE_DIR_TYPE),n&&(t.type=n),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!Mn.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${Mn.join(`, `)}`);return t.root=e,new zn(t)}const Vn=()=>{},V=process.platform,Hn=V===`win32`,Un=V===`darwin`,Wn=V===`linux`,Gn=V===`freebsd`,Kn=Re()===`OS400`,H={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},U=H,qn={lstat:Ne,stat:D},W=`listeners`,G=`errHandlers`,K=`rawEmitters`,Jn=[W,G,K],Yn=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),Xn=e=>Yn.has(O.extname(e).slice(1).toLowerCase()),Zn=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},q=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},Qn=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},J=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},$n=e=>e instanceof Set?e.size===0:!e,Y=new Map;function er(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&X(O.resolve(e,r),W,O.join(e,r))};try{return je(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const X=(e,t,n,r,i)=>{let a=Y.get(e);a&&Zn(a[t],e=>{e(n,r,i)})},tr=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Y.get(t),c;if(!n.persistent)return c=er(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)q(s,W,i),q(s,G,a),q(s,K,o);else{if(c=er(e,n,X.bind(null,t,W),a,X.bind(null,t,K)),!c)return;c.on(U.ERROR,async n=>{let r=X.bind(null,t,G);if(s&&(s.watcherUnusable=!0),Hn&&n.code===`EPERM`)try{await(await Pe(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},Y.set(t,s)}return()=>{J(s,W,i),J(s,G,a),J(s,K,o),$n(s.listeners)&&(s.watcher.close(),Y.delete(t),Jn.forEach(Qn(s)),s.watcher=void 0,Object.freeze(s))}},nr=new Map,rr=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=nr.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(Ae(t),o=void 0),o?(q(o,W,i),q(o,K,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:Me(t,n,(n,r)=>{Zn(o.rawEmitters,e=>{e(U.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&Zn(o.listeners,t=>t(e,n))})},nr.set(t,o)),()=>{J(o,W,i),J(o,K,a),$n(o.listeners)&&(nr.delete(t),Ae(t),o.options=o.watcher=void 0,Object.freeze(o))}};var ir=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=O.dirname(e),i=O.basename(e);this.fsw._getWatchedDir(r).add(i);let a=O.resolve(e),o={persistent:n.persistent};t||=Vn;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&Xn(i)?n.binaryInterval:n.interval,s=rr(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=tr(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=O.dirname(e),i=O.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(`watch`,e,5)){if(!n||n.mtimeMs===0)try{let n=await D(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(U.CHANGE,e,n),(Un||Wn||Gn)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(U.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(U.ADD,e,0))return;this.fsw._emit(U.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await E(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(U.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(U.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){if(e=O.join(e,``),o=this.fsw._throttle(`readdir`,e,1e3),!o)return;let s=this.fsw._getWatchedDir(n.path),c=new Set,l=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(l)return l.on(`data`,async o=>{if(this.fsw.closed){l=void 0;return}let u=o.path,d=O.join(e,u);if(c.add(u),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,d,u))){if(this.fsw.closed){l=void 0;return}(u===r||!r&&!s.has(u))&&(this.fsw._incrReadyCount(),d=O.join(i,O.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(U.ERROR,this._boundHandleError),new Promise((t,u)=>{if(!l)return u();l.once(`end`,()=>{if(this.fsw.closed){l=void 0;return}let u=o?o.clear():!1;t(void 0),s.getChildren().filter(t=>t!==e&&!c.has(t)).forEach(t=>{this.fsw._remove(e,t)}),l=void 0,u&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(O.dirname(e)),c=s.has(O.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(U.ADD_DIR,e,t),s.add(O.basename(e)),this.fsw._getWatchedDir(e);let l,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,void 0),this.fsw.closed))return;l=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,void 0)})}return l}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await qn[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=O.resolve(e),l=s?await E(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await E(e):e;if(this.fsw.closed)return;let a=O.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(U.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(O.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}};
|
|
23
24
|
/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
|
|
24
|
-
const wr=/\\/g,Tr=/\/\//,Er=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Dr=/^\.[/\\]/;function $(e){return Array.isArray(e)?e:[e]}const Or=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function kr(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=D.relative(e.path,t);return n?!n.startsWith(`..`)&&!D.isAbsolute(n):!1}return!1}:()=>!1}function Ar(e){if(typeof e!=`string`)throw Error(`string expected`);e=D.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;e.startsWith(`//`)&&(t=!0);let n=/\/\//;for(;e.match(n);)e=e.replace(n,`/`);return t&&(e=`/`+e),e}function jr(e,t,n){let r=Ar(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Mr(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=$(e).map(e=>kr(e));return t==null?(e,t)=>jr(n,e,t):jr(n,t)}const Nr=e=>{let t=$(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Fr)},Pr=e=>{let t=e.replace(wr,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(Tr);)t=t.replace(Tr,`/`);return n&&(t=`/`+t),t},Fr=e=>Pr(D.normalize(Pr(e))),Ir=(e=``)=>t=>typeof t==`string`?Fr(D.isAbsolute(t)?t:D.join(e,t)):t,Lr=(e,t)=>D.isAbsolute(e)?e:D.join(t,e),Rr=Object.freeze(new Set);var zr=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==`.`&&e!==`..`&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await Ce(n)}catch{this._removeWatcher&&this._removeWatcher(D.dirname(n),D.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=or,this.items=Rr,Object.freeze(this)}},Br=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Dr,``),this.watchPath=r,this.fullWatchPath=D.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return D.join(this.watchPath,D.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Vr=class extends Ee{constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?$(e.ignored):$([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};dr&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=or,this._readyEmitted=!0,process.nextTick(()=>this.emit(W.READY)))},this._emitRaw=(...e)=>this.emit(W.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new Cr(this),Object.freeze(r)}_addIgnoredPath(e){if(Or(e)){for(let t of this._ignoredPaths)if(Or(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)Or(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=Nr(e);return r&&(i=i.map(e=>Lr(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(D.dirname(e),D.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Nr(e),{cwd:n}=this.options;return t.forEach(e=>{!D.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=D.join(n,e)),e=D.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?D.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==W.ERROR&&this.emit(W.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;sr&&(t=D.normalize(t)),r.cwd&&(t=D.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===W.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(W.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===W.ADD&&this._pendingUnlinks.has(t)&&(e=W.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===W.ADD||e===W.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=W.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===W.CHANGE&&!this._throttle(W.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===W.ADD||e===W.ADD_DIR||e===W.CHANGE)){let e=r.cwd?D.join(r.cwd,t):t,n;try{n=await Te(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(W.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!D.isAbsolute(e)&&(s=D.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){_e(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(u,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(e,t){if(this.options.atomic&&Er.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(Ir(e)),n=[...[...this._ignoredPaths].map(Ir(e)),...t];this._userIgnored=Mr(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Br(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=D.resolve(e);return this._watched.has(t)||this._watched.set(t,new zr(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=D.join(e,t),i=D.resolve(r);if(n??=this._watched.has(r)||this._watched.has(i),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=D.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===W.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?W.UNLINK_DIR:W.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=D.dirname(e);this._getWatchedDir(t).remove(D.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=ar(e,{type:W.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(`close`,()=>{n=void 0}),n.once(`end`,()=>{n&&=(this._streams.delete(n),void 0)}),n}};function Hr(e,t={}){let n=new Vr(t);return n.add(e),n}function Ur(){let e,t=!1,n=`build`;return[{name:`oiyo:build`,apply:`build`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`VITE`),n=t.command},async buildStart(){if(t)return;await Promise.all([e.autoApi.collectApis(),e.autoComponent.collectComponents(),e.route.loadPagesConfig(),e.route.loadPagesJson(),e.layout.registerLayouts()]),e.state.canReuseGeneratedState()||(e.autoApi.writeDeclaration(),e.autoComponent.writeDeclaration(),e.layout.writeDeclaration(),e.route.writeDeclaration(),e.state.markGenerated());let r=async t=>{e.layout.isLayoutPath(t)&&(await e.layout.registerLayouts(),e.layout.writeDeclaration(),e.state.markGenerated()),e.autoComponent.isAutoComponentPath(t)&&(await e.autoComponent.collectComponents(),e.autoComponent.writeDeclaration(),e.state.markGenerated()),e.autoApi.isAutoApiPath(t)&&(await e.autoApi.collectApis(),e.autoApi.writeDeclaration(),e.state.markGenerated())};n===`serve`&&Hr(e.layout.layoutDir,{ignoreInitial:!0}).on(`add`,e=>void r(e)).on(`unlink`,e=>void r(e)).on(`change`,e=>void r(e)),t=!0},async transform(t,n){if(e.root.isRootPath(n))return e.root.parseRoot(t),e.root.transformRoot(t);if(e.route.isPagePath(n))return this.addWatchFile(e.root.rootPath),e.route.transformPage(t,n)},resolveId(e){if(e===`virtual:oiyo-root-context`)return B},load(t){if(t===B)return e.root.rootVM||`export function useRootContext() {return {}}`},async closeBundle(){await e.route.unwatchPagesConfig()}}]}var Wr=`0.2.1-beta.1`,Gr=class{constructor(e){this.config=e}get stateDir(){return C(this.config.rootDir,`.oiyo`)}get typesDir(){return C(this.stateDir,`types`)}get srcDir(){return C(this.config.rootDir,this.config.srcDir)}get declarationEntryPath(){return C(this.stateDir,`oiyo.d.ts`)}get tsconfigPath(){return C(this.stateDir,`tsconfig.json`)}get metadataPath(){return C(this.stateDir,`oiyo.json`)}get declarationPaths(){return[this.declarationEntryPath,this.tsconfigPath,C(this.typesDir,`apis.d.ts`),C(this.typesDir,`components.d.ts`),C(this.typesDir,`layouts.d.ts`),C(this.typesDir,`pages.d.ts`)]}relativeToState(e){return b(S(this.stateDir,e))}stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}serializeMetadataInput(){return JSON.stringify({rootDir:b(this.config.rootDir||``),srcDir:this.config.srcDir||``,dir:this.config.dir||{},scan:this.config.scan||{},exclude:this.config.exclude||[]})}generateMetadataHash(){return N(`${Wr}:${this.serializeMetadataInput()}`,16)}generateMetadata(){return{hash:this.generateMetadataHash(),project:{rootDir:b(this.config.rootDir||``)},versions:{oiyo:Wr}}}readMetadata(){if(!u(this.metadataPath))return null;try{return JSON.parse(ee(this.metadataPath,`utf-8`))}catch{return null}}writeMetadata(){d(this.stateDir,{recursive:!0});let e=this.generateMetadata();return P(this.metadataPath,this.stringifyJson(e)),e}canReuseGeneratedState(){let e=this.readMetadata();return!e||e.project.rootDir!==b(this.config.rootDir||``)||e.versions.oiyo!==Wr||e.hash!==this.generateMetadataHash()?!1:this.declarationPaths.every(e=>u(e))}generateDeclarationEntry(){return[`// Generated by oiyo`,``,`/// <reference types="@skiyee/oiyo/types" />`,`/// <reference path="./types/apis.d.ts" />`,`/// <reference path="./types/components.d.ts" />`,`/// <reference path="./types/layouts.d.ts" />`,`/// <reference path="./types/pages.d.ts" />`,``,`export {}`,``].join(`
|
|
25
|
-
`)}generateTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir),n=this.relativeToState(this.stateDir);return this.stringifyJson({compilerOptions:{paths:{"~/*":[
|
|
25
|
+
const ar=/\\/g,or=/\/\//,sr=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,cr=/^\.[/\\]/;function Z(e){return Array.isArray(e)?e:[e]}const Q=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function lr(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=O.relative(e.path,t);return n?!n.startsWith(`..`)&&!O.isAbsolute(n):!1}return!1}:()=>!1}function ur(e){if(typeof e!=`string`)throw Error(`string expected`);e=O.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;e.startsWith(`//`)&&(t=!0);let n=/\/\//;for(;e.match(n);)e=e.replace(n,`/`);return t&&(e=`/`+e),e}function dr(e,t,n){let r=ur(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function fr(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=Z(e).map(e=>lr(e));return t==null?(e,t)=>dr(n,e,t):dr(n,t)}const pr=e=>{let t=Z(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(hr)},mr=e=>{let t=e.replace(ar,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(or);)t=t.replace(or,`/`);return n&&(t=`/`+t),t},hr=e=>mr(O.normalize(mr(e))),gr=(e=``)=>t=>typeof t==`string`?hr(O.isAbsolute(t)?t:O.join(e,t)):t,_r=(e,t)=>O.isAbsolute(e)?e:O.join(t,e),vr=Object.freeze(new Set);var yr=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==`.`&&e!==`..`&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await Fe(n)}catch{this._removeWatcher&&this._removeWatcher(O.dirname(n),O.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=Vn,this.items=vr,Object.freeze(this)}},br=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(cr,``),this.watchPath=r,this.fullWatchPath=O.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return O.join(this.watchPath,O.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},xr=class extends Ie{constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Z(e.ignored):Z([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};Kn&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=Vn,this._readyEmitted=!0,process.nextTick(()=>this.emit(H.READY)))},this._emitRaw=(...e)=>this.emit(H.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new ir(this),Object.freeze(r)}_addIgnoredPath(e){if(Q(e)){for(let t of this._ignoredPaths)if(Q(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)Q(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=pr(e);return r&&(i=i.map(e=>_r(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||=0,this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(O.dirname(e),O.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=pr(e),{cwd:n}=this.options;return t.forEach(e=>{!O.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=O.join(n,e)),e=O.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?O.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==H.ERROR&&this.emit(H.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;Hn&&(t=O.normalize(t)),r.cwd&&(t=O.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===H.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(H.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===H.ADD&&this._pendingUnlinks.has(t)&&(e=H.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===H.ADD||e===H.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=H.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===H.CHANGE&&!this._throttle(H.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===H.ADD||e===H.ADD_DIR||e===H.CHANGE)){let e=r.cwd?O.join(r.cwd,t):t,n;try{n=await D(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(H.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!O.isAbsolute(e)&&(s=O.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){ke(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(u,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(e,t){if(this.options.atomic&&sr.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(gr(e)),n=[...[...this._ignoredPaths].map(gr(e)),...t];this._userIgnored=fr(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new br(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=O.resolve(e);return this._watched.has(t)||this._watched.set(t,new yr(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=O.join(e,t),i=O.resolve(r);if(n??=this._watched.has(r)||this._watched.has(i),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=O.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===H.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?H.UNLINK_DIR:H.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=O.dirname(e);this._getWatchedDir(t).remove(O.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=Bn(e,{type:H.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(`close`,()=>{n=void 0}),n.once(`end`,()=>{n&&=(this._streams.delete(n),void 0)}),n}};function Sr(e,t={}){let n=new xr(t);return n.add(e),n}function Cr(){let e,t=!1,n=`build`;return[{name:`oiyo:build`,apply:`build`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`VITE`),n=t.command},async buildStart(){if(t)return;await Promise.all([e.api.scanApis(),e.component.scanComponents(),e.layout.scanLayouts(),e.route.scanPages()]),e.state.canReuseGeneratedState()||(e.api.writeDeclaration(),e.component.writeDeclaration(),e.layout.writeDeclaration(),e.route.writePagesJson()&&e.route.writeDeclaration(),e.state.markGenerated());let r=async t=>{let n=b(t);e.route.isPage(n)?e.route.enterPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.enterComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?await e.api.enterApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.enterLayout(n)&&e.layout.writeDeclaration()};n===`serve`&&Sr(e.state.srcDir,{ignoreInitial:!0}).on(`add`,e=>void r(e));let i=t=>{let n=b(t);e.route.isPage(n)?e.route.exitPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.exitComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?e.api.exitApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.exitLayout(n)&&e.layout.writeDeclaration()};n===`serve`&&Sr(e.state.srcDir,{ignoreInitial:!0}).on(`unlink`,e=>void i(e));let a=async t=>{e.api.isApi(t)&&await e.api.enterApi(t)&&e.api.writeDeclaration()};n===`serve`&&Sr(e.state.srcDir,{ignoreInitial:!0}).on(`change`,e=>void a(e)),t=!0},async transform(t,n){let r=b(n);if(!r.startsWith(`${b(e.config.srcDir)}/`))return null;let i=t,a=null;return[`.ts`,`.js`].some(e=>r.endsWith(e))?(a=e.api.applyApis(t,r),i=a.code):[`.vue`,`.nvue`].some(e=>r.endsWith(e))&&(a=e.component.applyComponents(t,r,{withApis:!0}),i=a.code),e.root.isRootPath(r)?(e.root.parseRoot(i),e.root.transformRoot(i)):e.route.isPage(r)?(this.addWatchFile(e.root.rootPath),await e.route.transformPage(i,n)):a},resolveId(e){if(e===`virtual:oiyo-root-context`)return R},load(t){if(t===R)return e.root.rootVM||`export function useRootContext() {return {}}`},async closeBundle(){await e.route.unwatchPagesConfig()}}]}var $=`0.3.0-beta.2`,wr=class{config;constructor(e){this.config=e}get stateDir(){return x(this.config.rootDir,`.oiyo`)}get typesDir(){return x(this.stateDir,`types`)}get srcDir(){return x(this.config.rootDir,this.config.srcDir)}get declarationEntryPath(){return x(this.stateDir,`oiyo.d.ts`)}get tsconfigPath(){return x(this.stateDir,`tsconfig.json`)}get metadataPath(){return x(this.stateDir,`oiyo.json`)}get declarationPaths(){return[this.declarationEntryPath,this.tsconfigPath,x(this.typesDir,`apis.d.ts`),x(this.typesDir,`components.d.ts`),x(this.typesDir,`layouts.d.ts`),x(this.typesDir,`pages.d.ts`)]}relativeToState(e){return b(le(this.stateDir,e))}stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}serializeMetadataInput(){return JSON.stringify({rootDir:b(this.config.rootDir||``),srcDir:this.config.srcDir||``,dir:this.config.dir||{},scan:this.config.scan||{},exclude:this.config.exclude||[]})}generateMetadataHash(){return M(`${$}:${this.serializeMetadataInput()}`,16)}generateMetadata(){return{hash:this.generateMetadataHash(),project:{rootDir:b(this.config.rootDir||``)},versions:{oiyo:$}}}readMetadata(){if(!d(this.metadataPath))return null;try{return JSON.parse(p(this.metadataPath,`utf-8`))}catch{return null}}writeMetadata(){f(this.stateDir,{recursive:!0});let e=this.generateMetadata();return N(this.metadataPath,this.stringifyJson(e)),e}canReuseGeneratedState(){let e=this.readMetadata();return!e||e.project.rootDir!==b(this.config.rootDir||``)||e.versions.oiyo!==$||e.hash!==this.generateMetadataHash()?!1:this.declarationPaths.every(e=>d(e))}generateDeclarationEntry(){return[`// Generated by oiyo`,``,`/// <reference types="@skiyee/oiyo/types" />`,`/// <reference path="./types/apis.d.ts" />`,`/// <reference path="./types/components.d.ts" />`,`/// <reference path="./types/layouts.d.ts" />`,`/// <reference path="./types/pages.d.ts" />`,``,`export {}`,``].join(`
|
|
26
|
+
`)}generateTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir),n=this.relativeToState(this.stateDir);return this.stringifyJson({compilerOptions:{paths:{"~/*":[y(t,`*`)],"~~/*":[y(e,`*`)],"@/*":[y(t,`*`)],"@@/*":[y(e,`*`)]},types:[],esModuleInterop:!0,skipLibCheck:!0,target:`ES2018`,allowJs:!0,resolveJsonModule:!0,moduleDetection:`force`,isolatedModules:!0,verbatimModuleSyntax:!0,allowArbitraryExtensions:!0,strict:!0,noUncheckedIndexedAccess:!0,forceConsistentCasingInFileNames:!0,noImplicitOverride:!0,module:`preserve`,noEmit:!0,lib:[`ESNext`,`DOM`,`DOM.Iterable`],moduleResolution:`Bundler`,useDefineForClassFields:!0},include:[y(n,`oiyo.d.ts`),y(t,`**/*`),y(e,`*.d.ts`),y(e,`oiyo.config.*`),y(e,`vite.config.*`),y(e,`vitest.config.*`)],exclude:[y(t,`pages.config.*`),y(e,`dist`),y(e,`node_modules`)]})}writeTsconfig(){return f(this.stateDir,{recursive:!0}),N(this.tsconfigPath,this.generateTsconfig()),this.tsconfigPath}writeDeclarationEntry(){return f(this.stateDir,{recursive:!0}),N(this.declarationEntryPath,this.generateDeclarationEntry()),this.writeTsconfig(),this.declarationEntryPath}ensureDeclarationEntry(){return d(this.tsconfigPath)||this.writeTsconfig(),d(this.declarationEntryPath)?this.declarationEntryPath:this.writeDeclarationEntry()}markGenerated(){return this.writeMetadata()}};function Tr(e){let t=Te(e),n=Ke();n.withScope(`CONFIG`);let r=new wr(t),i=new Ot(t,{logger:n,oiyoState:r}),a=new Nt(t,{logger:n,oiyoState:r,oiyoApi:i}),o=new $t(t,{logger:n}),s=new zt(t,{logger:n,oiyoState:r});return{logger:n,config:t,api:i,component:a,layout:s,state:r,route:new En(t,{logger:n,oiyoState:r,oiyoRoot:o,oiyoLayout:s}),root:o}}function Er(e){return[{name:`oiyo:deps`,enforce:`pre`,async config(t){let{config:n}=await De({name:`oiyo`,cwd:t.root}),r=Tr(n||e);return ze(t,{oiyo:r,resolve:{alias:{"~":C.resolve(r.config.rootDir,r.config.srcDir),"@":C.resolve(r.config.rootDir,r.config.srcDir),"@@":C.normalize(r.config.rootDir),"~~":C.normalize(r.config.rootDir)}},optimizeDeps:{exclude:[`@skiyee/oiyo`]}})}}]}function Dr(){let e;return[{name:`oiyo:serve`,apply:`serve`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`VITE`),e.logger.withScope(`HMR`)},async buildStart(){await Promise.all([e.api.scanApis(),e.component.scanComponents(),e.route.scanPages(),e.layout.scanLayouts()]),e.state.canReuseGeneratedState()||(e.api.writeDeclaration(),e.component.writeDeclaration(),e.route.writePagesJson()&&e.route.writeDeclaration(),e.layout.writeDeclaration(),e.state.markGenerated())},configureServer(t){e.route.watchPagesConfig(()=>{e.route.writePagesJson()&&e.route.writeDeclaration(),t.hot.send({type:`full-reload`})});let n=async t=>{let n=b(t);e.route.isPage(n)?e.route.enterPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.enterComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?await e.api.enterApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.enterLayout(n)&&e.layout.writeDeclaration()};t.watcher.on(`add`,e=>void n(e));let r=t=>{let n=b(t);e.route.isPage(n)?e.route.exitPage(n)&&e.route.writePagesJson()&&e.route.writeDeclaration():e.component.isComponent(n)?e.component.exitComponent(n)&&e.component.writeDeclaration():e.api.isApi(n)?e.api.exitApi(n)&&e.api.writeDeclaration():e.layout.isLayout(n)&&e.layout.exitLayout(n)&&e.layout.writeDeclaration()};t.watcher.on(`unlink`,e=>void r(e));let i=async t=>{e.api.isApi(t)&&await e.api.enterApi(t)&&e.api.writeDeclaration()};t.watcher.on(`change`,e=>void i(e))},async transform(t,n){let r=b(n);if(!r.startsWith(`${b(e.config.srcDir)}/`))return null;let i=t,a=null;return[`.ts`,`.js`].some(e=>r.endsWith(e))?(a=e.api.applyApis(t,r),i=a.code):[`.vue`,`.nvue`].some(e=>r.endsWith(e))&&(a=e.component.applyComponents(t,r,{withApis:!0}),i=a.code),e.root.isRootPath(r)?(e.root.parseRoot(i),e.root.transformRoot(i)):e.route.isPage(r)?(this.addWatchFile(e.root.rootPath),await e.route.transformPage(i,n)):a},resolveId(e){if(e===`virtual:oiyo-root-context`)return R},load(t){if(t===R)return e.root.rootVM||`export function useRootContext() {return {}}`},async handleHotUpdate({file:t,server:n,read:r}){if(e.root.isRootPath(t)){let t=await r(),i=!1;if(e.root.shouldRefreshView(t)&&(i=!0),e.root.shouldRefreshVM(t)){let e=n.moduleGraph.getModuleById(R);e&&(n.moduleGraph.invalidateModule(e),i=!0)}if(i){n.hot.send({type:`full-reload`});return}}},async closeBundle(){await e.route.unwatchPagesConfig()}}]}function Or(e={}){return[...Er(e),...Dr(),...Cr()]}export{k as LogLevels,Or as OiyoCorePlugin,Bt as OiyoLayout,Ot as OiyoModApi,Nt as OiyoModComponent,zt as OiyoModLayout,$t as OiyoModRoot,En as OiyoModRoute,On as OiyoPage,wr as OiyoState,R as RESOLVED_VIRTUAL_ROOT_CONTEXT_ID,Zt as VIRTUAL_ROOT_CONTEXT_ID,Ke as createLogger,Dn as definePageMeta,en as defineRootContext};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oiyo/core",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.2
|
|
4
|
+
"version": "0.3.0-beta.2",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "skiyee",
|
|
7
7
|
"email": "319619193@qq.com",
|
|
@@ -40,18 +40,21 @@
|
|
|
40
40
|
"vue": "3.4.21"
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@babel/parser": "^7.
|
|
44
|
-
"@babel/traverse": "^7.
|
|
43
|
+
"@babel/parser": "^7.29.0",
|
|
44
|
+
"@babel/traverse": "^7.29.0",
|
|
45
45
|
"@vue/compiler-sfc": "3.4.21",
|
|
46
46
|
"ansis": "^4.2.0",
|
|
47
47
|
"c12": "^3.3.3",
|
|
48
48
|
"defu": "^6.1.4",
|
|
49
|
+
"enhanced-resolve": "^5.21.3",
|
|
49
50
|
"magic-string": "^0.30.21",
|
|
50
51
|
"pathe": "^2.0.3",
|
|
51
52
|
"tinyglobby": "^0.2.15",
|
|
52
|
-
"@oiyo/config": "0.2
|
|
53
|
+
"@oiyo/config": "0.3.0-beta.2"
|
|
53
54
|
},
|
|
54
55
|
"devDependencies": {
|
|
56
|
+
"@babel/types": "^7.29.0",
|
|
57
|
+
"@types/babel__traverse": "^7.28.0",
|
|
55
58
|
"chokidar": "4.0.3",
|
|
56
59
|
"vite": "5.2.8",
|
|
57
60
|
"vue": "3.4.21"
|