@oiyo/core 0.1.1 → 0.1.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/dist/index.cjs CHANGED
@@ -1,25 +1,25 @@
1
1
  /**
2
- * @oiyo/core v0.1.1
2
+ * @oiyo/core v0.1.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
7
  Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`node:process`);c=s(c);let l=require(`node:readline`);l=s(l);let u=require(`ansis`),d=require(`node:fs`),f=require(`node:fs/promises`),p=require(`pathe`),ee=require(`node:crypto`),m=require(`node:module`),h=require(`@babel/parser`),g=require(`@babel/traverse`);g=s(g);let te=require(`tinyglobby`),_=require(`@vue/compiler-sfc`),ne=require(`@oiyo/config`),re=require(`vue`),v=require(`magic-string`);v=s(v);let ie=require(`c12`),ae=require(`defu`),y=require(`fs`),b=require(`fs/promises`),oe=require(`events`),x=require(`path`);x=s(x);let se=require(`node:stream`),S=require(`node:path`);S=s(S);let ce=require(`os`);const C={silent:0,error:1,warn:2,info:3,debug:4,verbose:5};let le,ue,de=0,fe;function pe(){let e=c.default.stdout.rows-2,t=e>0?`
8
- `.repeat(e):``;c.default.stdout.write(t),l.default.cursorTo(c.default.stdout,0,0),l.default.clearScreenDown(c.default.stdout)}function me(){return fe??=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`numeric`,second:`numeric`}),fe}function w(e=`info`,t={}){if(t.customLogger)return t.customLogger;let n=new WeakSet,r=new Set,{prefix:i=`[OIYO]`,scope:a,allowClearScreen:o=!0,console:s=globalThis.console}=t,l=C[e],d=o&&c.default.stdout.isTTY&&!c.default.env.CI,f=d?pe:()=>{};function p(e,t,n={}){let r=ee(e,n.scope??a);return n.timestamp?`${(0,u.dim)(me().format(new Date))} ${(0,u.blue)(i)} ${r} ${t}`:`${(0,u.blue)((0,u.bold)(i))} ${r} ${t}`}function ee(e,t){if(!t)return` `;let n=`[${t.toUpperCase()}]`;return{info:(0,u.cyan)(n),warn:(0,u.yellow)(n),error:(0,u.red)(n),debug:(0,u.dim)((0,u.cyan)(n))}[e]}function m(e,t,r={}){if(l<C[e])return;let i=e;if(r.error&&n.add(r.error),d){if(e===le&&t===ue){de++,f(),s[e](p(e,t,r),(0,u.yellow)(`(x${de+1})`));return}de=0,le=e,ue=t,r.clear&&f()}s[i](p(e,t,r))}let h={hasWarned:!1,withScope(n){return w(e,{...t,scope:n})},debug(e,t){m(`debug`,e,t)},info(e,t){m(`info`,e,t)},warn(e,t){h.hasWarned=!0,m(`warn`,e,t)},warnOnce(e,t){r.has(e)||(r.add(e),h.hasWarned=!0,m(`warn`,e,t))},error(e,t){h.hasWarned=!0,m(`error`,e,t)},clearScreen(e){l>=C[e]&&f()},hasErrorLogged(e){return n.has(e)}};return h}const T=typeof g.default==`function`?g.default:g.default.default,he=(0,m.createRequire)(require(`url`).pathToFileURL(__filename).href),ge=`**/*`;function E(e){return e?Array.isArray(e)?e:[e]:[]}function _e(e){if(!(0,d.existsSync)(e))return[ge];try{return(0,d.statSync)(e).isFile()?[(0,p.basename)(e)]:[ge]}catch{return[ge]}}async function D(e){let{dir:t,pattern:n,ignore:r}=e;if(!(0,d.existsSync)(t))return[];let i=(0,d.statSync)(t).isFile()?(0,p.dirname)(t):t,a=E(n),o=a.length>0?a:_e(t);try{return(await(0,te.glob)(o,{cwd:i,absolute:!0,ignore:E(r)})).map(e=>(0,p.normalize)((0,p.resolve)(e)))}catch(e){return console.error(`[oiyo] Error scanning file:`,e),[]}}function ve(e,t,n){let r=(0,p.normalize)(e),i=(0,p.normalize)(t);if((0,d.existsSync)(i))try{if((0,d.statSync)(i).isFile())return r===i}catch{return!1}if(r!==i&&!r.startsWith(`${i}/`))return!1;let a=(0,p.normalize)((0,p.relative)(i,r)),o=E(n?.pattern);return E(n?.ignore).some(e=>(0,p.matchesGlob)(a,e))?!1:o.length===0?!0:o.some(e=>(0,p.matchesGlob)(a,e))}function O(e,t=8){return(0,ee.createHash)(`sha256`).update(e).digest(`hex`).slice(0,t)}function k(e,t){let n=`${e}.${c.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;return(0,d.writeFileSync)(n,t,`utf-8`),(0,d.existsSync)(e)&&(0,d.unlinkSync)(e),(0,d.renameSync)(n,e),!0}function ye(e,t,n){let r=(0,p.normalize)((0,p.relative)(e,t));return n?.stripExtension&&(r=r.replace(/\.[cm]?[jt]sx?$/,``)),r.startsWith(`.`)?r:`./${r}`}function A(e){return!e.startsWith(`.`)&&!e.startsWith(`/`)&&!/^[a-z]:[\\/]/i.test(e)}function be(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function xe(e,t){if(!A(t))return{path:(0,p.normalize)((0,p.resolve)(e,t))};try{let n=be(t),r=(0,p.dirname)((0,p.normalize)(he.resolve(`${n}/package.json`,{paths:[e]}))),i=t.slice(n.length).replace(/^\/+/,``);return{importBase:t.replace(/\\/g,`/`),path:i?(0,p.normalize)((0,p.resolve)(r,i)):(0,p.normalize)(r)}}catch{return{path:(0,p.normalize)((0,p.resolve)(e,t))}}}function Se(e,t,n){if(!n)return e;let r=(0,p.normalize)((0,p.relative)(t,e));return!r||r===`.`?n:`${n}/${r}`}function Ce(e,t,n){return A(t)?n?.stripExtension?t.replace(/\.[cm]?[jt]sx?$/,``):t:ye(e,t,n)}function we(e){if(!e)return``;let t=e.replace(/\p{Lu}/gu,e=>`-${e.toLowerCase()}`);return t.startsWith(`-`)?t.slice(1):t}function j(e){return e?e.replace(/[-_](.)/g,(e,t)=>t.toUpperCase()).replace(/^(.)/,e=>e.toUpperCase()):``}function Te(e,t){let n=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),r={start:0,end:0};return T(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 Ee(e){return e.replace(/\s+/g,``)}const De=(0,m.createRequire)(require(`url`).pathToFileURL(__filename).href),Oe=[`.ts`,`.mts`,`.cts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.jsx`,`.vue`,`.d.ts`,`.d.mts`,`.d.cts`];function ke(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function Ae(e,t){let n=(0,p.normalize)(e);for(;;){let e=(0,p.resolve)(n,`node_modules`,t,`package.json`);if((0,d.existsSync)(e))return(0,p.normalize)(e);let r=(0,p.dirname)(n);if(r===n)return;n=r}}function je(e,t,n){let r=(0,p.normalize)((0,p.resolve)((0,p.parse)(e).dir,t)),i=n?.preferTypes?[`.d.ts`,`.d.mts`,`.d.cts`,...Oe]:Oe;if((0,d.existsSync)(r))return r;for(let e of i){let t=`${r}${e}`;if((0,d.existsSync)(t))return(0,p.normalize)(t)}for(let e of i){let t=(0,p.resolve)(r,`index${e}`);if((0,d.existsSync)(t))return(0,p.normalize)(t)}return r}function Me(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 M(e,t,n){try{let r=ke(t),i=Ae(e,r)||(0,p.normalize)(De.resolve(`${r}/package.json`,{paths:[e]})),a=(0,p.dirname)(i),o=JSON.parse(await(0,f.readFile)(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?Me(l,`types`)||(c===`.`?o.types:void 0):Me(l,`import`)||(c===`.`?o.module||o.main:void 0);return u?(0,p.normalize)((0,p.resolve)(a,u)):(0,p.normalize)(De.resolve(t,{paths:[e]}))}catch{return}}async function Ne(e,t,n){return A(t)?await M((0,p.dirname)(e),t,n)||t:je(e,t,n)}function Pe(e,t){return t.startsWith(`.`)||t.startsWith(`/`)?je(e,t,{preferTypes:!0}):t}function Fe(e,t,n){return A(t)?n||(Ae(e,ke(t))?t.replace(/\\/g,`/`):void 0):n}async function Ie(e,t){if(!e.importBase||!A(e.importBase))return{typePath:e.path,valuePath:e.path};let n=await M(t,e.importBase),r=await M(t,e.importBase,{preferTypes:!0});return{typePath:r||n||e.path,valuePath:n||r||e.path}}function Le(e,t){return!t||!e.importPath||!A(t)?e:e.importPath.startsWith(`${t}/..`)||e.importPath.startsWith(`${t}/.`)?{...e,importPath:t}:e}function Re(e){let t=j(e);return t?t[0].toLowerCase()+t.slice(1):``}function N(e){try{return(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`,`jsx`]})}catch{return(0,h.parse)(`(${e})`,{sourceType:`module`,plugins:[`typescript`,`jsx`]})}}function P(e){return e.type===`Identifier`?[e.name]:e.type===`ObjectPattern`?e.properties.flatMap(e=>e.type===`ObjectProperty`?P(e.value):e.type===`RestElement`?P(e.argument):[]):e.type===`ArrayPattern`?e.elements.flatMap(e=>e?P(e):[]):e.type===`AssignmentPattern`?P(e.left):e.type===`RestElement`?P(e.argument):[]}function ze(e){let t=(0,p.parse)(e);return Re(t.name===`index`?(0,p.parse)(t.dir).name:t.name)}function Be(e,t){if(!e.endsWith(`.vue`))return t;try{let{descriptor:n}=(0,_.parse)(t,{filename:e});return[n.script?.content,n.scriptSetup?.content].filter(e=>!!e).join(`
9
- `)}catch{return t}}async function Ve(e,t,n=e,r){let i=N(Be(e,t)),a=[],o=[],s=[],c=!1;if(r?.visitedFiles?.add(e),T(i,{ExportDefaultDeclaration(){c=!0},ExportAllDeclaration(e){let t=e.node.source?.value;t&&s.push({exportKind:e.node.exportKind,source:t})},ExportNamedDeclaration(t){let{node:i}=t,s=i.exportKind;if(i.declaration)switch(i.declaration.type){case`FunctionDeclaration`:case`TSDeclareFunction`:case`ClassDeclaration`:case`TSEnumDeclaration`:s!==`type`&&i.declaration.id?.name&&a.push({exportName:i.declaration.id.name,filePath:e,importPath:n,name:i.declaration.id.name});break;case`VariableDeclaration`:if(s===`type`)break;for(let t of i.declaration.declarations)for(let r of P(t.id))a.push({exportName:r,filePath:e,importPath:n,name:r});break;case`TSInterfaceDeclaration`:case`TSTypeAliasDeclaration`:r?.includeTypes&&i.declaration.id?.name&&o.push({exportName:i.declaration.id.name,filePath:e,importPath:n,name:i.declaration.id.name});break}for(let t of i.specifiers){if(t.type!==`ExportSpecifier`){if(s===`type`&&!r?.includeTypes||t.exported.type!==`Identifier`)continue;a.push({exportName:t.exported.name,filePath:e,importPath:n,name:t.exported.name});continue}if(s===`type`||t.exportKind===`type`){if(!r?.includeTypes||t.exported.type!==`Identifier`)continue;let a=t.exported.name,s=e,c=n;i.source?.value&&t.local.type===`Identifier`&&(a=t.local.name,c=Pe(e,i.source.value),s=A(c)?e:c),o.push({exportName:a,filePath:s,importPath:c,name:t.exported.name});continue}t.exported.type===`Identifier`&&a.push({exportName:t.exported.name,filePath:e,importPath:n,name:t.exported.name})}}}),c){let t=ze(e);t&&a.push({exportName:`default`,filePath:e,importPath:n,name:t})}for(let t of s){let i=await Ne(e,t.source,{preferTypes:r?.includeTypes});if(!(!i||A(i)||r?.visitedFiles?.has(i)))try{let e=await Ve(i,await(0,f.readFile)(i,`utf-8`),n,{includeTypes:r?.includeTypes,visitedFiles:r?.visitedFiles});t.exportKind!==`type`&&a.push(...e.valueItems.map(e=>({...e,importPath:n}))),r?.includeTypes&&o.push(...e.typeItems.map(e=>({...e,importPath:n})))}catch{continue}}return{typeItems:o,valueItems:a}}function He(e){let t=N(e),n=new Set;return T(t,{Program(e){Object.keys(e.scope.bindings).forEach(e=>n.add(e)),e.stop()}}),n}function Ue(e,t,n){let r=N(e),i=new Set(t),a=new Set(n?.boundNames||[]),o=new Set;return T(r,{ReferencedIdentifier(e){let t=e.node.name;a.has(t)||e.scope.hasBinding(t)||i.has(t)&&o.add(t)}}),o}function We(e){let t=e.importPath||e.filePath;return e.exportName===`default`?`import ${e.name} from '${t}'`:e.exportName===e.name?`import { ${e.name} } from '${t}'`:`import { ${e.exportName} as ${e.name} } from '${t}'`}function Ge(e,t){let n=Ce(t,e.importPath||e.filePath,{stripExtension:!0});return` const ${e.name}: typeof import('${n}')['${e.exportName}'];`}const Ke=[`**/*.ts`,`**/*.mts`,`**/*.cts`,`**/*.js`,`**/*.mjs`,`**/*.cjs`,`**/*.tsx`,`**/*.jsx`];function qe(e){return typeof e==`string`?{isType:void 0,localName:e,sourceName:e}:{isType:e.isType,localName:e.as||e.name,sourceName:e.name}}function Je(e){return typeof e!=`string`&&e.only!==void 0}function Ye(e,t){let n=(0,p.resolve)(e.rootDir,e.srcDir),r=typeof t==`string`?t:t.from,i=xe(n,r);return{exclude:typeof t==`string`?void 0:t.exclude,ignore:typeof t==`string`?void 0:t.ignore,importBase:Fe(n,r,i.importBase),path:i.path,pattern:typeof t==`string`?void 0:t.pattern,types:typeof t==`string`?!1:t.types}}function Xe(e){return(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?{exclude:[],ignore:[],importBase:void 0,pattern:Ke,path:(0,p.normalize)((0,p.resolve)(e)),types:!1}:{exclude:e.exclude||[],ignore:e.ignore,importBase:e.importBase,pattern:e.pattern||Ke,path:(0,p.normalize)((0,p.resolve)(e.path)),types:e.types||!1})}function Ze(e){return JSON.stringify({exclude:[...e.exclude||[]].sort(),ignore:E(e.ignore),importBase:e.importBase,path:e.path,pattern:E(e.pattern),types:e.types||!1})}function Qe(e){return{exportName:e.export||e.name,filePath:e.from,importPath:e.from,name:e.name}}function $e(e,t){return{importPath:Ce(t,e.importPath||e.filePath,{stripExtension:!0}),specifier:e.exportName===e.name?e.name:`${e.exportName} as ${e.name}`}}function et(e){return`${e.filePath}#${e.exportName}`}var tt=class{constructor(e,t){this._config=e,this.autoApis=[],this.autoApiTypes=[],this.autoApiMap=new Map,this.autoApiTypeMap=new Map,this.includedApis=[],this.includedApiTypes=[],this.apiSources=[],this.oiyoState=t.oiyoState,this.logger=t.logger.withScope(`AUTO_API`),this.registerConfigScanners()}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return(0,p.resolve)(this.typesDir,`apis.d.ts`)}isAutoApiPath(e){let t=(0,p.normalize)(e);return this.apiSources.some(e=>ve(t,e.path,{ignore:e.ignore,pattern:e.pattern}))}includeApi(e){let t=Array.isArray(e)?e:[e];this.includedApis.push(...t.map(Qe))}includeApiType(e){let t=Array.isArray(e)?e:[e];this.includedApiTypes.push(...t.map(Qe))}includeApis(e){for(let t of Xe(e)){let e=Ze(t);this.apiSources.some(t=>Ze(t)===e)||this.apiSources.push(t)}}registerConfigScanners(){for(let e of this._config.scan?.apis||[]){if(!Je(e)){this.includeApis(Ye(this._config,e));continue}for(let t of e.only){let{isType:n,localName:r,sourceName:i}=qe(t),a={export:i===r?void 0:i,from:e.from,name:r};n??e.types?this.includeApiType(a):this.includeApi(a)}}}resetCollectedState(){this.autoApis=[],this.autoApiTypes=[],this.autoApiMap.clear(),this.autoApiTypeMap.clear()}registerValue(e,t){let n=this.autoApiMap.get(e.name);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||n.filePath===e.filePath&&n.exportName!==`default`&&e.exportName===`default`||this.logger.warn(`自动 API 名称冲突: ${e.name} 已存在,已跳过 ${et(e)}`),!1):(this.autoApiMap.set(e.name,e),t?.trackScanned&&this.autoApis.push(e),!0)}registerType(e,t){let n=this.autoApiTypeMap.get(e.name);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||this.logger.warn(`自动 API 类型名称冲突: ${e.name} 已存在,已跳过 ${et(e)}`),!1):(this.autoApiTypeMap.set(e.name,e),t?.trackScanned&&this.autoApiTypes.push(e),!0)}seedIncludedRegistrations(){this.includedApis.forEach(e=>this.registerValue(e)),this.includedApiTypes.forEach(e=>this.registerType(e))}registerScannedValueItems(e,t){for(let n of t){let t=Le(n,e.importBase);(e.exclude||[]).includes(t.name)||this.registerValue(t,{trackScanned:!0})}}registerScannedTypeItems(e,t){for(let n of t){let t=Le(n,e.importBase);(e.exclude||[]).includes(t.name)||this.registerType(t,{trackScanned:!0})}}async scanSourceFiles(e,t,n,r){for(let i of t)try{let t=await Ve(i,await(0,f.readFile)(i,`utf-8`),Se(i,n,e.importBase),{includeTypes:r.includeTypes,visitedFiles:new Set});r.registerValues&&this.registerScannedValueItems(e,t.valueItems),r.registerTypes&&this.registerScannedTypeItems(e,t.typeItems)}catch{this.logger.warn(`解析自动 API 文件失败,已跳过: ${i}`)}}async collectApis(){let e=(0,p.resolve)(this._config.rootDir,this._config.srcDir);this.resetCollectedState(),this.seedIncludedRegistrations();for(let t of this.apiSources){let{typePath:n,valuePath:r}=await Ie(t,e),i=await D({dir:r,ignore:t.ignore,pattern:t.pattern});if(t.types&&r===n){await this.scanSourceFiles(t,i,r,{includeTypes:!0,registerTypes:!0,registerValues:!0});continue}if(await this.scanSourceFiles(t,i,r,{includeTypes:!1,registerValues:!0}),!t.types)continue;let a=r===n?i:await D({dir:n,ignore:t.ignore,pattern:t.pattern});await this.scanSourceFiles(t,a,n,{includeTypes:!0,registerTypes:!0})}return this.autoApis}collectBoundNames(e){return He(e)}resolveImports(e,t){return!e||this.autoApiMap.size===0?[]:Array.from(Ue(e,this.autoApiMap.keys(),t)).sort().map(e=>We(this.autoApiMap.get(e)))}resolveImport(e){let t=this.autoApiMap.get(e);if(t)return We(t)}generateDeclaration(){let e=Array.from(this.autoApiTypeMap.values()).sort((e,t)=>e.name.localeCompare(t.name)).reduce((e,t)=>{let n=$e(t,this.typesDir),r=e.get(n.importPath)||[];return r.push(n.specifier),e.set(n.importPath,r),e},new Map);return[`// Generated by oiyo`,`declare global {`,...Array.from(this.autoApiMap.values()).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>Ge(e,this.typesDir)),`}`,``,`declare global {`,...Array.from(e.entries()).flatMap(([e,t])=>[` // @ts-ignore`,` export type { ${t.join(`, `)} } from '${e}';`]),`}`,``,`export {}`,``].join(`
10
- `)}writeDeclaration(){return(0,d.mkdirSync)(this.typesDir,{recursive:!0}),k(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}};const F=/<\/?\s*([a-z][\w-]*)\b/gi,nt=[`**/*.vue`,`**/*.nvue`];function rt(e){return typeof e==`string`?{localName:e,sourceName:e}:{localName:e.as||e.name,sourceName:e.name}}function it(e){return typeof e!=`string`&&e.only!==void 0}function at(e,t){let n=xe((0,p.resolve)(e.rootDir,e.srcDir),typeof t==`string`?t:t.from);return{chain:typeof t==`string`?!0:t.chain,ignore:typeof t==`string`?void 0:t.ignore,importBase:n.importBase,path:n.path,pattern:typeof t==`string`?void 0:t.pattern,prefix:typeof t==`string`?void 0:t.prefix}}function ot(e){return(e.scan?.components||[]).filter(e=>!it(e)).map(t=>at(e,t))}function I(e,t){let n=(0,p.normalize)(t);return ot(e).some(e=>ve(n,e.path,{ignore:e.ignore,pattern:e.pattern}))}function st(e){return e?j(e):``}function ct(e){if(e.length<2)return e;let t=e.slice();return t[t.length-1]===t[t.length-2]&&t.pop(),t}function lt(e,t,n){let{dir:r,name:i}=(0,p.parse)((0,p.relative)(t,e)),a=r&&r!==`.`?r.split(p.sep).filter(Boolean):[];(i!==`index`||a.length===0)&&a.push(i);let o=ct(a),s=n?.chain===!1?o.slice(-1):o;return`${st(n?.prefix)}${s.map(e=>j(e)).join(``)}`}function ut(e){let t=new Set;F.lastIndex=0;let n=F.exec(e);for(;n;)t.add(n[1]),n=F.exec(e);return t}function dt(e){return e.includes(`-`)?j(e):e}function ft(e){return{componentName:e.name,exportName:e.export||`default`,filePath:e.from,importPath:e.from}}function pt(e){return(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?{chain:!0,ignore:[],importBase:void 0,pattern:nt,path:(0,p.normalize)((0,p.resolve)(e)),prefix:void 0}:{chain:e.chain??!0,ignore:e.ignore,importBase:e.importBase,pattern:e.pattern||nt,path:(0,p.normalize)((0,p.resolve)(e.path)),prefix:e.prefix})}function mt(e){return JSON.stringify({chain:e.chain,ignore:E(e.ignore),importBase:e.importBase,path:e.path,pattern:E(e.pattern),prefix:e.prefix})}function ht(e){let t=e.importPath||e.filePath;return e.exportName===`default`?`import ${e.componentName} from '${t}'`:e.exportName===e.componentName?`import { ${e.componentName} } from '${t}'`:`import { ${e.exportName} as ${e.componentName} } from '${t}'`}function gt(e,t){let n=Ce(t,e.importPath||e.filePath);return` ${e.componentName}: typeof import('${n}')['${e.exportName}'];`}var _t=class{constructor(e,t){this._config=e,this.autoComponents=[],this.registeredComponents=[],this.componentSources=[],this.autoComponentMap=new Map,this.oiyoState=t.oiyoState,this.logger=t.logger.withScope(`AUTO_COMPONENT`),this.registerConfigScanners()}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return(0,p.resolve)(this.typesDir,`components.d.ts`)}isAutoComponentPath(e){let t=(0,p.normalize)(e);return this.componentSources.some(e=>ve(t,e.path,{ignore:e.ignore,pattern:e.pattern}))}registerComponent(e){this.registeredComponents.push(ft(e))}registerComponents(e){for(let t of pt(e)){let e=mt(t);this.componentSources.some(t=>mt(t)===e)||this.componentSources.push(t)}}registerConfigScanners(){for(let e of this._config.scan?.components||[]){if(!it(e)){this.registerComponents(at(this._config,e));continue}for(let t of e.only){let{localName:n,sourceName:r}=rt(t);this.registerComponent({export:r,from:e.from,name:e.prefix?`${j(e.prefix)}${n}`:n})}}}setResolvedComponent(e,t){let n=this.autoComponentMap.get(e.componentName);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||this.logger.warn(`组件名称冲突: ${e.componentName} 已存在,已跳过 ${e.filePath}`),!1):(this.autoComponentMap.set(e.componentName,e),t?.trackScanned&&this.autoComponents.push(e),!0)}async collectComponents(){this.autoComponents=[],this.autoComponentMap.clear(),this.registeredComponents.forEach(e=>this.setResolvedComponent(e));for(let e of this.componentSources)(await D({dir:e.path,ignore:e.ignore,pattern:e.pattern})).forEach(t=>{let n=e.path===t?(0,p.dirname)(t):e.path;this.setResolvedComponent({componentName:lt(t,n,{chain:e.chain,prefix:e.prefix}),exportName:`default`,filePath:t,importPath:Se(t,e.path,e.importBase)},{trackScanned:!0})});return this.autoComponents}resolveComponentImports(e,t){if(!e||this.autoComponentMap.size===0)return[];let n=[],r=new Set,i=t?(0,p.normalize)(t):void 0;for(let t of ut(e)){let e=dt(t),a=this.autoComponentMap.get(e);a&&(i&&a.filePath===i||r.has(e)||(r.add(e),n.push(ht(a))))}return n}resolveComponentImport(e,t){let n=this.autoComponentMap.get(e);if(!n)return;let r=t?(0,p.normalize)(t):void 0;if(!(r&&n.filePath===r))return ht(n)}generateDeclaration(){return[`// Generated by oiyo`,`declare module 'vue' {`,` export interface GlobalComponents {`,...Array.from(this.autoComponentMap.values()).sort((e,t)=>e.componentName.localeCompare(t.componentName)).map(e=>gt(e,this.typesDir)),` }`,`}`,``,`export {}`,``].join(`
11
- `)}writeDeclaration(){return(0,d.mkdirSync)(this.typesDir,{recursive:!0}),k(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}};function vt(e){return e.includes(`<OiyoLayout`)||e.includes(`<oiyo-layout`)}function yt(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 bt(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 xt(e,t){let{dir:n,name:r}=(0,p.parse)((0,p.relative)(t,e));return(n&&n!==`.`?[...n.split(p.sep),r]:[r]).map(e=>we(e)).join(`-`)}function St(e){return`OiyoLayout${e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}`}const Ct=(0,re.defineComponent)({name:`OiyoLayout`,setup(e,t){return()=>t.slots.default?.()}});var wt=class{constructor(e,t){this.config=e,this.layoutFiles=[],this.logger=t.logger.withScope(`LAYOUT`),this.oiyoState=t.oiyoState}get srcDir(){return(0,p.resolve)(this.config.rootDir,this.config.srcDir)}get layoutDir(){return(0,p.resolve)(this.srcDir,this.config.dir?.layouts||`layouts`)}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return(0,p.resolve)(this.typesDir,`layouts.d.ts`)}isLayoutPath(e){let t=(0,p.normalize)(e);return!t.endsWith(`.vue`)&&!t.endsWith(`.nvue`)||[...ne.DEFAULT_EXCLUDE,...this.config.exclude||[]].some(e=>(0,p.matchesGlob)(t,e))||I(this.config,t)?!1:t.startsWith(`${this.layoutDir}/`)}setLayout(e){if(this.layoutFiles.findIndex(({filePath:t})=>t===e)!==-1)return!1;let t=xt(e,this.layoutDir),n=St(t);return this.layoutFiles.push({useName:t,componentName:n,filePath:e}),!0}async registerLayouts(){let e=await D({dir:this.layoutDir,pattern:[`**/*.vue`,`**/*.nvue`]});return this.layoutFiles=[],e.filter(e=>this.isLayoutPath(e)).map(e=>this.setLayout(e)),this.layoutFiles}generateDeclaration(){return[`// Generated by oiyo`,``,`declare module '@skiyee/oiyo/api' {`,` interface OiyoLayouts {`,...this.layoutFiles.slice().sort((e,t)=>e.useName.localeCompare(t.useName)).map(({useName:e,filePath:t})=>` '${e}': typeof import('${ye(this.typesDir,t)}')['default'];`),` }`,``,` type LayoutKey = keyof OiyoLayouts extends never ? string : keyof OiyoLayouts;`,``,` interface PageMeta {`,` layout?: LayoutKey | false;`,` }`,`}`,``,`export {}`,``].join(`
12
- `)}writeDeclaration(){return(0,d.mkdirSync)(this.typesDir,{recursive:!0}),k(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}applyLayout(e,t){if(!vt(t))return{template:t,script:``,imports:[]};if(e===!1)return{template:yt(t),script:``,imports:[]};e===void 0&&(e=`default`);let n=this.layoutFiles.find(t=>t.useName===e);return n?{template:bt(t,n.componentName),script:``,imports:[`import ${n.componentName} from '${n.filePath}'`]}:(this.logger.error(`未找到布局 "${e}",请检查布局名称或文件位置是否正确`),{template:t,script:``,imports:[]})}};function L(e){if(!e||!e.includes(`import`))return[];let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];return T(t,{ImportDeclaration(t){let r=e.substring(t.node.start,t.node.end);n.push(r)}}),n}function R(e){if(!e||!e.includes(`import`))return new Set;let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=new Set;return T(t,{ImportDeclaration(e){for(let t of e.node.specifiers)n.add(t.local.name)}}),n}function Tt(e){if(!e||!e.includes(`import`))return e;let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];T(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 z(e,t){let n=Et(t),r=Et(e);for(let[e,t]of r){let r=n.get(e);r?Dt(r,t):n.set(e,t)}return Ot(n)}function Et(e){let t=new Map;for(let n of e)T((0,h.parse)(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 Dt(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 Ot(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}function kt(e){if(!e.includes(`defineRootContext`))return``;let{descriptor:t}=(0,_.parse)(e);if(!t.scriptSetup)return``;let n=e=t.scriptSetup.content,r=At(n);return n.substring(r.start,r.end+1).trim()}function At(e){return Te(e,`defineRootContext`)}function jt(e){if(!e.includes(`<template`))return``;let{descriptor:t}=(0,_.parse)(e);return(t.template?.content||``).trim()}function Mt(e,t){let n=e.replace(/\{\{([\s\S]*?)\}\}/g,(e,n)=>e.replace(n,Nt(n,t)));return n=n.replace(/((?:v-(?!for\b)[\w-]+(?::[\w-]+)?|[:@][\w-]+)\s*=\s*)(["'])([\s\S]*?)\2/g,(e,n,r,i)=>`${n}${r}${Nt(i,t)}${r}`),n}function Nt(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=(0,h.parse)(`(${e})`,{sourceType:`module`,plugins:[`typescript`]}),r=new v.default(e);return T(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 Pt(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=Mt(n,t),n.trim()}function Ft(e){if(!e)return;let t=e?.content;if(t){let e=It(t);return e.script?e:void 0}}function It(e){let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return T(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 Lt(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 Rt=`virtual:oiyo-root-context`,B=`\0${Rt}`;function zt(e){let{script:t,imports:n}=e,r=[];return n?.length&&(r.push(...n),r.push(``)),t?(r.push(`let rootContextInstance = null`),r.push(``),r.push(`export function useRootContext() {`),r.push(`if (!rootContextInstance) {`),r.push(`const factory = ${t}`),r.push(`rootContextInstance = factory()`),r.push(`}`),r.push(`return rootContextInstance`),r.push(`}`)):(r.push(`export function useRootContext() {`),r.push(`return {}`),r.push(`}`)),r.join(`
13
- `)}const Bt=e=>e();var Vt=class{constructor(e,t){this.config=e,this.rootView={imports:[],template:`<OiyoPage />`,script:``},this.shouldRefreshVM=e=>{let t=``;this.rootMarco&&(t=O(Ee(`defineRootContext(${this.rootMarco.script})`)));let n=O(Ee(kt(e)));return t!==n},this.logger=t.logger.withScope(`ROOT`),this.oiyoAutoApi=t.oiyoAutoApi}get srcDir(){return(0,p.resolve)(this.config.rootDir,this.config.srcDir)}get rootPath(){return(0,p.resolve)(this.srcDir,`App.vue`)}isRootPath(e){return e===this.rootPath}parseRoot(e){let{descriptor:t}=(0,_.parse)(e),n=Ft(t.scriptSetup);if(n?.script&&t.scriptSetup?.content&&this.oiyoAutoApi){let e=this.oiyoAutoApi.collectBoundNames(t.scriptSetup.content),r=this.oiyoAutoApi.resolveImports(n.script,{boundNames:e});r.length>0&&(n.imports=z(r,n.imports||[]))}return this.rootView={template:Pt(t.template,{varName:n?.variable,varProperties:n?.properties}),imports:[],script:``},n&&(this.rootMarco=n,this.rootVM=zt(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}=(0,_.parse)(e),n=new v.default(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=At(e);if(r.start!==r.end){e.includes(`virtual:oiyo-root-context`)||n.appendLeft(t.scriptSetup.loc.start.offset,`
8
+ `.repeat(e):``;c.default.stdout.write(t),l.default.cursorTo(c.default.stdout,0,0),l.default.clearScreenDown(c.default.stdout)}function me(){return fe??=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`numeric`,second:`numeric`}),fe}function he(e=`info`,t={}){if(t.customLogger)return t.customLogger;let n=new WeakSet,r=new Set,{prefix:i=`[OIYO]`,scope:a,allowClearScreen:o=!0,console:s=globalThis.console}=t,l=C[e],d=o&&c.default.stdout.isTTY&&!c.default.env.CI,f=d?pe:()=>{};function p(e,t,n={}){let r=ee(e,n.scope??a);return n.timestamp?`${(0,u.dim)(me().format(new Date))} ${(0,u.blue)(i)} ${r} ${t}`:`${(0,u.blue)((0,u.bold)(i))} ${r} ${t}`}function ee(e,t){if(!t)return` `;let n=`[${t.toUpperCase()}]`;return{info:(0,u.cyan)(n),warn:(0,u.yellow)(n),error:(0,u.red)(n),debug:(0,u.dim)((0,u.cyan)(n))}[e]}function m(e,t,r={}){if(l<C[e])return;let i=e;if(r.error&&n.add(r.error),d){if(e===le&&t===ue){de++,f(),s[e](p(e,t,r),(0,u.yellow)(`(x${de+1})`));return}de=0,le=e,ue=t,r.clear&&f()}s[i](p(e,t,r))}let h={hasWarned:!1,withScope(n){return he(e,{...t,scope:n})},debug(e,t){m(`debug`,e,t)},info(e,t){m(`info`,e,t)},warn(e,t){h.hasWarned=!0,m(`warn`,e,t)},warnOnce(e,t){r.has(e)||(r.add(e),h.hasWarned=!0,m(`warn`,e,t))},error(e,t){h.hasWarned=!0,m(`error`,e,t)},clearScreen(e){l>=C[e]&&f()},hasErrorLogged(e){return n.has(e)}};return h}const w=typeof g.default==`function`?g.default:g.default.default,ge=(0,m.createRequire)(require(`url`).pathToFileURL(__filename).href),_e=`**/*`;function T(e){return e?Array.isArray(e)?e:[e]:[]}function ve(e){if(!(0,d.existsSync)(e))return[_e];try{return(0,d.statSync)(e).isFile()?[(0,p.basename)(e)]:[_e]}catch{return[_e]}}async function E(e){let{dir:t,pattern:n,ignore:r}=e;if(!(0,d.existsSync)(t))return[];let i=(0,d.statSync)(t).isFile()?(0,p.dirname)(t):t,a=T(n),o=a.length>0?a:ve(t);try{return(await(0,te.glob)(o,{cwd:i,absolute:!0,ignore:T(r)})).map(e=>(0,p.normalize)((0,p.resolve)(e)))}catch(e){return console.error(`[oiyo] Error scanning file:`,e),[]}}function ye(e,t,n){let r=(0,p.normalize)(e),i=(0,p.normalize)(t);if((0,d.existsSync)(i))try{if((0,d.statSync)(i).isFile())return r===i}catch{return!1}if(r!==i&&!r.startsWith(`${i}/`))return!1;let a=(0,p.normalize)((0,p.relative)(i,r)),o=T(n?.pattern);return T(n?.ignore).some(e=>(0,p.matchesGlob)(a,e))?!1:o.length===0?!0:o.some(e=>(0,p.matchesGlob)(a,e))}function D(e,t=8){return(0,ee.createHash)(`sha256`).update(e).digest(`hex`).slice(0,t)}function O(e,t){let n=`${e}.${c.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;return(0,d.writeFileSync)(n,t,`utf-8`),(0,d.existsSync)(e)&&(0,d.unlinkSync)(e),(0,d.renameSync)(n,e),!0}function be(e,t,n){let r=(0,p.normalize)((0,p.relative)(e,t));return n?.stripExtension&&(r=r.replace(/\.[cm]?[jt]sx?$/,``)),r.startsWith(`.`)?r:`./${r}`}function k(e){return!e.startsWith(`.`)&&!e.startsWith(`/`)&&!/^[a-z]:[\\/]/i.test(e)}function xe(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function Se(e,t){if(!k(t))return{path:(0,p.normalize)((0,p.resolve)(e,t))};try{let n=xe(t),r=(0,p.dirname)((0,p.normalize)(ge.resolve(`${n}/package.json`,{paths:[e]}))),i=t.slice(n.length).replace(/^\/+/,``);return{importBase:t.replace(/\\/g,`/`),path:i?(0,p.normalize)((0,p.resolve)(r,i)):(0,p.normalize)(r)}}catch{return{path:(0,p.normalize)((0,p.resolve)(e,t))}}}function Ce(e,t,n){if(!n)return e;let r=(0,p.normalize)((0,p.relative)(t,e));return!r||r===`.`?n:`${n}/${r}`}function we(e,t,n){return k(t)?n?.stripExtension?t.replace(/\.[cm]?[jt]sx?$/,``):t:be(e,t,n)}function Te(e){if(!e)return``;let t=e.replace(/\p{Lu}/gu,e=>`-${e.toLowerCase()}`);return t.startsWith(`-`)?t.slice(1):t}function A(e){return e?e.replace(/[-_](.)/g,(e,t)=>t.toUpperCase()).replace(/^(.)/,e=>e.toUpperCase()):``}function Ee(e,t){let n=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),r={start:0,end:0};return w(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 De(e){return e.replace(/\s+/g,``)}const Oe=(0,m.createRequire)(require(`url`).pathToFileURL(__filename).href),ke=[`.ts`,`.mts`,`.cts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.jsx`,`.vue`,`.d.ts`,`.d.mts`,`.d.cts`];function Ae(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function je(e,t){let n=(0,p.normalize)(e);for(;;){let e=(0,p.resolve)(n,`node_modules`,t,`package.json`);if((0,d.existsSync)(e))return(0,p.normalize)(e);let r=(0,p.dirname)(n);if(r===n)return;n=r}}function Me(e,t,n){let r=(0,p.normalize)((0,p.resolve)((0,p.parse)(e).dir,t)),i=n?.preferTypes?[`.d.ts`,`.d.mts`,`.d.cts`,...ke]:ke;if((0,d.existsSync)(r))return r;for(let e of i){let t=`${r}${e}`;if((0,d.existsSync)(t))return(0,p.normalize)(t)}for(let e of i){let t=(0,p.resolve)(r,`index${e}`);if((0,d.existsSync)(t))return(0,p.normalize)(t)}return r}function Ne(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 j(e,t,n){try{let r=Ae(t),i=je(e,r)||(0,p.normalize)(Oe.resolve(`${r}/package.json`,{paths:[e]})),a=(0,p.dirname)(i),o=JSON.parse(await(0,f.readFile)(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?Ne(l,`types`)||(c===`.`?o.types:void 0):Ne(l,`import`)||(c===`.`?o.module||o.main:void 0);return u?(0,p.normalize)((0,p.resolve)(a,u)):(0,p.normalize)(Oe.resolve(t,{paths:[e]}))}catch{return}}async function Pe(e,t,n){return k(t)?await j((0,p.dirname)(e),t,n)||t:Me(e,t,n)}function Fe(e,t){return t.startsWith(`.`)||t.startsWith(`/`)?Me(e,t,{preferTypes:!0}):t}function Ie(e,t,n){return k(t)?n||(je(e,Ae(t))?t.replace(/\\/g,`/`):void 0):n}async function Le(e,t){if(!e.importBase||!k(e.importBase))return{typePath:e.path,valuePath:e.path};let n=await j(t,e.importBase),r=await j(t,e.importBase,{preferTypes:!0});return{typePath:r||n||e.path,valuePath:n||r||e.path}}function Re(e,t){return!t||!e.importPath||!k(t)?e:e.importPath.startsWith(`${t}/..`)||e.importPath.startsWith(`${t}/.`)?{...e,importPath:t}:e}function ze(e){let t=A(e);return t?t[0].toLowerCase()+t.slice(1):``}function M(e){try{return(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`,`jsx`]})}catch{return(0,h.parse)(`(${e})`,{sourceType:`module`,plugins:[`typescript`,`jsx`]})}}function N(e){return e.type===`Identifier`?[e.name]:e.type===`ObjectPattern`?e.properties.flatMap(e=>e.type===`ObjectProperty`?N(e.value):e.type===`RestElement`?N(e.argument):[]):e.type===`ArrayPattern`?e.elements.flatMap(e=>e?N(e):[]):e.type===`AssignmentPattern`?N(e.left):e.type===`RestElement`?N(e.argument):[]}function Be(e){let t=(0,p.parse)(e);return ze(t.name===`index`?(0,p.parse)(t.dir).name:t.name)}function Ve(e,t){if(!e.endsWith(`.vue`))return t;try{let{descriptor:n}=(0,_.parse)(t,{filename:e});return[n.script?.content,n.scriptSetup?.content].filter(e=>!!e).join(`
9
+ `)}catch{return t}}async function He(e,t,n=e,r){let i=M(Ve(e,t)),a=[],o=[],s=[],c=!1;if(r?.visitedFiles?.add(e),w(i,{ExportDefaultDeclaration(){c=!0},ExportAllDeclaration(e){let t=e.node.source?.value;t&&s.push({exportKind:e.node.exportKind,source:t})},ExportNamedDeclaration(t){let{node:i}=t,s=i.exportKind;if(i.declaration)switch(i.declaration.type){case`FunctionDeclaration`:case`TSDeclareFunction`:case`ClassDeclaration`:case`TSEnumDeclaration`:s!==`type`&&i.declaration.id?.name&&a.push({exportName:i.declaration.id.name,filePath:e,importPath:n,name:i.declaration.id.name});break;case`VariableDeclaration`:if(s===`type`)break;for(let t of i.declaration.declarations)for(let r of N(t.id))a.push({exportName:r,filePath:e,importPath:n,name:r});break;case`TSInterfaceDeclaration`:case`TSTypeAliasDeclaration`:r?.includeTypes&&i.declaration.id?.name&&o.push({exportName:i.declaration.id.name,filePath:e,importPath:n,name:i.declaration.id.name});break}for(let t of i.specifiers){if(t.type!==`ExportSpecifier`){if(s===`type`&&!r?.includeTypes||t.exported.type!==`Identifier`)continue;a.push({exportName:t.exported.name,filePath:e,importPath:n,name:t.exported.name});continue}if(s===`type`||t.exportKind===`type`){if(!r?.includeTypes||t.exported.type!==`Identifier`)continue;let a=t.exported.name,s=e,c=n;i.source?.value&&t.local.type===`Identifier`&&(a=t.local.name,c=Fe(e,i.source.value),s=k(c)?e:c),o.push({exportName:a,filePath:s,importPath:c,name:t.exported.name});continue}t.exported.type===`Identifier`&&a.push({exportName:t.exported.name,filePath:e,importPath:n,name:t.exported.name})}}}),c){let t=Be(e);t&&a.push({exportName:`default`,filePath:e,importPath:n,name:t})}for(let t of s){let i=await Pe(e,t.source,{preferTypes:r?.includeTypes});if(!(!i||k(i)||r?.visitedFiles?.has(i)))try{let e=await He(i,await(0,f.readFile)(i,`utf-8`),n,{includeTypes:r?.includeTypes,visitedFiles:r?.visitedFiles});t.exportKind!==`type`&&a.push(...e.valueItems.map(e=>({...e,importPath:n}))),r?.includeTypes&&o.push(...e.typeItems.map(e=>({...e,importPath:n})))}catch{continue}}return{typeItems:o,valueItems:a}}function Ue(e){let t=M(e),n=new Set;return w(t,{Program(e){Object.keys(e.scope.bindings).forEach(e=>n.add(e)),e.stop()}}),n}function We(e,t,n){let r=M(e),i=new Set(t),a=new Set(n?.boundNames||[]),o=new Set;return w(r,{ReferencedIdentifier(e){let t=e.node.name;a.has(t)||e.scope.hasBinding(t)||i.has(t)&&o.add(t)}}),o}function Ge(e){let t=e.importPath||e.filePath;return e.exportName===`default`?`import ${e.name} from '${t}'`:e.exportName===e.name?`import { ${e.name} } from '${t}'`:`import { ${e.exportName} as ${e.name} } from '${t}'`}function Ke(e,t){let n=we(t,e.importPath||e.filePath,{stripExtension:!0});return` const ${e.name}: typeof import('${n}')['${e.exportName}'];`}const qe=[`**/*.ts`,`**/*.mts`,`**/*.cts`,`**/*.js`,`**/*.mjs`,`**/*.cjs`,`**/*.tsx`,`**/*.jsx`];function Je(e){return typeof e==`string`?{isType:void 0,localName:e,sourceName:e}:{isType:e.isType,localName:e.as||e.name,sourceName:e.name}}function Ye(e){return typeof e!=`string`&&e.only!==void 0}function Xe(e,t){let n=(0,p.resolve)(e.rootDir,e.srcDir),r=typeof t==`string`?t:t.from,i=Se(n,r);return{exclude:typeof t==`string`?void 0:t.exclude,ignore:typeof t==`string`?void 0:t.ignore,importBase:Ie(n,r,i.importBase),path:i.path,pattern:typeof t==`string`?void 0:t.pattern,types:typeof t==`string`?!1:t.types}}function Ze(e){return(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?{exclude:[],ignore:[],importBase:void 0,pattern:qe,path:(0,p.normalize)((0,p.resolve)(e)),types:!1}:{exclude:e.exclude||[],ignore:e.ignore,importBase:e.importBase,pattern:e.pattern||qe,path:(0,p.normalize)((0,p.resolve)(e.path)),types:e.types||!1})}function Qe(e){return JSON.stringify({exclude:[...e.exclude||[]].sort(),ignore:T(e.ignore),importBase:e.importBase,path:e.path,pattern:T(e.pattern),types:e.types||!1})}function $e(e){return{exportName:e.export||e.name,filePath:e.from,importPath:e.from,name:e.name}}function et(e,t){return{importPath:we(t,e.importPath||e.filePath,{stripExtension:!0}),specifier:e.exportName===e.name?e.name:`${e.exportName} as ${e.name}`}}function tt(e){return`${e.filePath}#${e.exportName}`}var nt=class{constructor(e,t){this._config=e,this.autoApis=[],this.autoApiTypes=[],this.autoApiMap=new Map,this.autoApiTypeMap=new Map,this.includedApis=[],this.includedApiTypes=[],this.apiSources=[],this.oiyoState=t.oiyoState,this.logger=t.logger.withScope(`AUTO_API`),this.registerConfigScanners()}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return(0,p.resolve)(this.typesDir,`apis.d.ts`)}isAutoApiPath(e){let t=(0,p.normalize)(e);return this.apiSources.some(e=>ye(t,e.path,{ignore:e.ignore,pattern:e.pattern}))}includeApi(e){let t=Array.isArray(e)?e:[e];this.includedApis.push(...t.map($e))}includeApiType(e){let t=Array.isArray(e)?e:[e];this.includedApiTypes.push(...t.map($e))}includeApis(e){for(let t of Ze(e)){let e=Qe(t);this.apiSources.some(t=>Qe(t)===e)||this.apiSources.push(t)}}registerConfigScanners(){for(let e of this._config.scan?.apis||[]){if(!Ye(e)){this.includeApis(Xe(this._config,e));continue}for(let t of e.only){let{isType:n,localName:r,sourceName:i}=Je(t),a={export:i===r?void 0:i,from:e.from,name:r};n??e.types?this.includeApiType(a):this.includeApi(a)}}}resetCollectedState(){this.autoApis=[],this.autoApiTypes=[],this.autoApiMap.clear(),this.autoApiTypeMap.clear()}registerValue(e,t){let n=this.autoApiMap.get(e.name);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||n.filePath===e.filePath&&n.exportName!==`default`&&e.exportName===`default`||this.logger.warn(`自动 API 名称冲突: ${e.name} 已存在,已跳过 ${tt(e)}`),!1):(this.autoApiMap.set(e.name,e),t?.trackScanned&&this.autoApis.push(e),!0)}registerType(e,t){let n=this.autoApiTypeMap.get(e.name);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||this.logger.warn(`自动 API 类型名称冲突: ${e.name} 已存在,已跳过 ${tt(e)}`),!1):(this.autoApiTypeMap.set(e.name,e),t?.trackScanned&&this.autoApiTypes.push(e),!0)}seedIncludedRegistrations(){this.includedApis.forEach(e=>this.registerValue(e)),this.includedApiTypes.forEach(e=>this.registerType(e))}registerScannedValueItems(e,t){for(let n of t){let t=Re(n,e.importBase);(e.exclude||[]).includes(t.name)||this.registerValue(t,{trackScanned:!0})}}registerScannedTypeItems(e,t){for(let n of t){let t=Re(n,e.importBase);(e.exclude||[]).includes(t.name)||this.registerType(t,{trackScanned:!0})}}async scanSourceFiles(e,t,n,r){for(let i of t)try{let t=await He(i,await(0,f.readFile)(i,`utf-8`),Ce(i,n,e.importBase),{includeTypes:r.includeTypes,visitedFiles:new Set});r.registerValues&&this.registerScannedValueItems(e,t.valueItems),r.registerTypes&&this.registerScannedTypeItems(e,t.typeItems)}catch{this.logger.warn(`解析自动 API 文件失败,已跳过: ${i}`)}}async collectApis(){let e=(0,p.resolve)(this._config.rootDir,this._config.srcDir);this.resetCollectedState(),this.seedIncludedRegistrations();for(let t of this.apiSources){let{typePath:n,valuePath:r}=await Le(t,e),i=await E({dir:r,ignore:t.ignore,pattern:t.pattern});if(t.types&&r===n){await this.scanSourceFiles(t,i,r,{includeTypes:!0,registerTypes:!0,registerValues:!0});continue}if(await this.scanSourceFiles(t,i,r,{includeTypes:!1,registerValues:!0}),!t.types)continue;let a=r===n?i:await E({dir:n,ignore:t.ignore,pattern:t.pattern});await this.scanSourceFiles(t,a,n,{includeTypes:!0,registerTypes:!0})}return this.autoApis}collectBoundNames(e){return Ue(e)}resolveImports(e,t){return!e||this.autoApiMap.size===0?[]:Array.from(We(e,this.autoApiMap.keys(),t)).sort().map(e=>Ge(this.autoApiMap.get(e)))}resolveImport(e){let t=this.autoApiMap.get(e);if(t)return Ge(t)}generateDeclaration(){let e=Array.from(this.autoApiTypeMap.values()).sort((e,t)=>e.name.localeCompare(t.name)).reduce((e,t)=>{let n=et(t,this.typesDir),r=e.get(n.importPath)||[];return r.push(n.specifier),e.set(n.importPath,r),e},new Map);return[`// Generated by oiyo`,`declare global {`,...Array.from(this.autoApiMap.values()).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>Ke(e,this.typesDir)),`}`,``,`declare global {`,...Array.from(e.entries()).flatMap(([e,t])=>[` // @ts-ignore`,` export type { ${t.join(`, `)} } from '${e}';`]),`}`,``,`export {}`,``].join(`
10
+ `)}writeDeclaration(){return(0,d.mkdirSync)(this.typesDir,{recursive:!0}),O(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}};const P=/<\/?\s*([a-z][\w-]*)\b/gi,rt=[`**/*.vue`,`**/*.nvue`];function it(e){return typeof e==`string`?{localName:e,sourceName:e}:{localName:e.as||e.name,sourceName:e.name}}function at(e){return typeof e!=`string`&&e.only!==void 0}function ot(e,t){let n=Se((0,p.resolve)(e.rootDir,e.srcDir),typeof t==`string`?t:t.from);return{chain:typeof t==`string`?!0:t.chain,ignore:typeof t==`string`?void 0:t.ignore,importBase:n.importBase,path:n.path,pattern:typeof t==`string`?void 0:t.pattern,prefix:typeof t==`string`?void 0:t.prefix}}function st(e){return(e.scan?.components||[]).filter(e=>!at(e)).map(t=>ot(e,t))}function F(e,t){let n=(0,p.normalize)(t);return st(e).some(e=>ye(n,e.path,{ignore:e.ignore,pattern:e.pattern}))}function ct(e){return e?A(e):``}function lt(e){if(e.length<2)return e;let t=e.slice();return t[t.length-1]===t[t.length-2]&&t.pop(),t}function ut(e,t,n){let{dir:r,name:i}=(0,p.parse)((0,p.relative)(t,e)),a=r&&r!==`.`?r.split(p.sep).filter(Boolean):[];(i!==`index`||a.length===0)&&a.push(i);let o=lt(a),s=n?.chain===!1?o.slice(-1):o;return`${ct(n?.prefix)}${s.map(e=>A(e)).join(``)}`}function dt(e){let t=new Set;P.lastIndex=0;let n=P.exec(e);for(;n;)t.add(n[1]),n=P.exec(e);return t}function ft(e){return e.includes(`-`)?A(e):e}function pt(e){return{componentName:e.name,exportName:e.export||`default`,filePath:e.from,importPath:e.from}}function mt(e){return(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?{chain:!0,ignore:[],importBase:void 0,pattern:rt,path:(0,p.normalize)((0,p.resolve)(e)),prefix:void 0}:{chain:e.chain??!0,ignore:e.ignore,importBase:e.importBase,pattern:e.pattern||rt,path:(0,p.normalize)((0,p.resolve)(e.path)),prefix:e.prefix})}function ht(e){return JSON.stringify({chain:e.chain,ignore:T(e.ignore),importBase:e.importBase,path:e.path,pattern:T(e.pattern),prefix:e.prefix})}function gt(e){let t=e.importPath||e.filePath;return e.exportName===`default`?`import ${e.componentName} from '${t}'`:e.exportName===e.componentName?`import { ${e.componentName} } from '${t}'`:`import { ${e.exportName} as ${e.componentName} } from '${t}'`}function _t(e,t){let n=we(t,e.importPath||e.filePath);return` ${e.componentName}: typeof import('${n}')['${e.exportName}'];`}var vt=class{constructor(e,t){this._config=e,this.autoComponents=[],this.registeredComponents=[],this.componentSources=[],this.autoComponentMap=new Map,this.oiyoState=t.oiyoState,this.logger=t.logger.withScope(`AUTO_COMPONENT`),this.registerConfigScanners()}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return(0,p.resolve)(this.typesDir,`components.d.ts`)}isAutoComponentPath(e){let t=(0,p.normalize)(e);return this.componentSources.some(e=>ye(t,e.path,{ignore:e.ignore,pattern:e.pattern}))}registerComponent(e){this.registeredComponents.push(pt(e))}registerComponents(e){for(let t of mt(e)){let e=ht(t);this.componentSources.some(t=>ht(t)===e)||this.componentSources.push(t)}}registerConfigScanners(){for(let e of this._config.scan?.components||[]){if(!at(e)){this.registerComponents(ot(this._config,e));continue}for(let t of e.only){let{localName:n,sourceName:r}=it(t);this.registerComponent({export:r,from:e.from,name:e.prefix?`${A(e.prefix)}${n}`:n})}}}setResolvedComponent(e,t){let n=this.autoComponentMap.get(e.componentName);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||this.logger.warn(`组件名称冲突: ${e.componentName} 已存在,已跳过 ${e.filePath}`),!1):(this.autoComponentMap.set(e.componentName,e),t?.trackScanned&&this.autoComponents.push(e),!0)}async collectComponents(){this.autoComponents=[],this.autoComponentMap.clear(),this.registeredComponents.forEach(e=>this.setResolvedComponent(e));for(let e of this.componentSources)(await E({dir:e.path,ignore:e.ignore,pattern:e.pattern})).forEach(t=>{let n=e.path===t?(0,p.dirname)(t):e.path;this.setResolvedComponent({componentName:ut(t,n,{chain:e.chain,prefix:e.prefix}),exportName:`default`,filePath:t,importPath:Ce(t,e.path,e.importBase)},{trackScanned:!0})});return this.autoComponents}resolveComponentImports(e,t){if(!e||this.autoComponentMap.size===0)return[];let n=[],r=new Set,i=t?(0,p.normalize)(t):void 0;for(let t of dt(e)){let e=ft(t),a=this.autoComponentMap.get(e);a&&(i&&a.filePath===i||r.has(e)||(r.add(e),n.push(gt(a))))}return n}resolveComponentImport(e,t){let n=this.autoComponentMap.get(e);if(!n)return;let r=t?(0,p.normalize)(t):void 0;if(!(r&&n.filePath===r))return gt(n)}generateDeclaration(){return[`// Generated by oiyo`,`declare module 'vue' {`,` export interface GlobalComponents {`,...Array.from(this.autoComponentMap.values()).sort((e,t)=>e.componentName.localeCompare(t.componentName)).map(e=>_t(e,this.typesDir)),` }`,`}`,``,`export {}`,``].join(`
11
+ `)}writeDeclaration(){return(0,d.mkdirSync)(this.typesDir,{recursive:!0}),O(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}};function yt(e){return e.includes(`<OiyoLayout`)||e.includes(`<oiyo-layout`)}function bt(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 xt(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 St(e,t){let{dir:n,name:r}=(0,p.parse)((0,p.relative)(t,e));return(n&&n!==`.`?[...n.split(p.sep),r]:[r]).map(e=>Te(e)).join(`-`)}function Ct(e){return`OiyoLayout${e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}`}const wt=(0,re.defineComponent)({name:`OiyoLayout`,setup(e,t){return()=>t.slots.default?.()}});var Tt=class{constructor(e,t){this.config=e,this.layoutFiles=[],this.logger=t.logger.withScope(`LAYOUT`),this.oiyoState=t.oiyoState}get srcDir(){return(0,p.resolve)(this.config.rootDir,this.config.srcDir)}get layoutDir(){return(0,p.resolve)(this.srcDir,this.config.dir?.layouts||`layouts`)}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return(0,p.resolve)(this.typesDir,`layouts.d.ts`)}isLayoutPath(e){let t=(0,p.normalize)(e);return!t.endsWith(`.vue`)&&!t.endsWith(`.nvue`)||[...ne.DEFAULT_EXCLUDE,...this.config.exclude||[]].some(e=>(0,p.matchesGlob)(t,e))||F(this.config,t)?!1:t.startsWith(`${this.layoutDir}/`)}setLayout(e){if(this.layoutFiles.findIndex(({filePath:t})=>t===e)!==-1)return!1;let t=St(e,this.layoutDir),n=Ct(t);return this.layoutFiles.push({useName:t,componentName:n,filePath:e}),!0}async registerLayouts(){let e=await E({dir:this.layoutDir,pattern:[`**/*.vue`,`**/*.nvue`]});return this.layoutFiles=[],e.filter(e=>this.isLayoutPath(e)).map(e=>this.setLayout(e)),this.layoutFiles}generateDeclaration(){return[`// Generated by oiyo`,``,`declare module '@skiyee/oiyo/api' {`,` interface OiyoLayouts {`,...this.layoutFiles.slice().sort((e,t)=>e.useName.localeCompare(t.useName)).map(({useName:e,filePath:t})=>` '${e}': typeof import('${be(this.typesDir,t)}')['default'];`),` }`,``,` type LayoutKey = keyof OiyoLayouts extends never ? string : keyof OiyoLayouts;`,``,` interface PageMeta {`,` layout?: LayoutKey | false;`,` }`,`}`,``,`export {}`,``].join(`
12
+ `)}writeDeclaration(){return(0,d.mkdirSync)(this.typesDir,{recursive:!0}),O(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}applyLayout(e,t){if(!yt(t))return{template:t,script:``,imports:[]};if(e===!1)return{template:bt(t),script:``,imports:[]};e===void 0&&(e=`default`);let n=this.layoutFiles.find(t=>t.useName===e);return n?{template:xt(t,n.componentName),script:``,imports:[`import ${n.componentName} from '${n.filePath}'`]}:(this.logger.error(`未找到布局 "${e}",请检查布局名称或文件位置是否正确`),{template:t,script:``,imports:[]})}};function I(e){if(!e||!e.includes(`import`))return[];let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];return w(t,{ImportDeclaration(t){let r=e.substring(t.node.start,t.node.end);n.push(r)}}),n}function L(e){if(!e||!e.includes(`import`))return new Set;let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=new Set;return w(t,{ImportDeclaration(e){for(let t of e.node.specifiers)n.add(t.local.name)}}),n}function Et(e){if(!e||!e.includes(`import`))return e;let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n=[];w(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 R(e,t){let n=Dt(t),r=Dt(e);for(let[e,t]of r){let r=n.get(e);r?Ot(r,t):n.set(e,t)}return kt(n)}function Dt(e){let t=new Map;for(let n of e)w((0,h.parse)(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 Ot(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 kt(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}function At(e){if(!e.includes(`defineRootContext`))return``;let{descriptor:t}=(0,_.parse)(e);if(!t.scriptSetup)return``;let n=e=t.scriptSetup.content,r=jt(n);return n.substring(r.start,r.end+1).trim()}function jt(e){return Ee(e,`defineRootContext`)}function Mt(e){if(!e.includes(`<template`))return``;let{descriptor:t}=(0,_.parse)(e);return(t.template?.content||``).trim()}function Nt(e,t){let n=e.replace(/\{\{([\s\S]*?)\}\}/g,(e,n)=>e.replace(n,Pt(n,t)));return n=n.replace(/((?:v-(?!for\b)[\w-]+(?::[\w-]+)?|[:@][\w-]+)\s*=\s*)(["'])([\s\S]*?)\2/g,(e,n,r,i)=>`${n}${r}${Pt(i,t)}${r}`),n}function Pt(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=(0,h.parse)(`(${e})`,{sourceType:`module`,plugins:[`typescript`]}),r=new v.default(e);return w(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 Ft(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=Nt(n,t),n.trim()}function It(e){if(!e)return;let t=e?.content;if(t){let e=Lt(t);return e.script?e:void 0}}function Lt(e){let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return w(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 Rt(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`,z=`\0${zt}`;function Bt(e){let{script:t,imports:n}=e,r=[];return n?.length&&(r.push(...n),r.push(``)),t?(r.push(`let rootContextInstance = null`),r.push(``),r.push(`export function useRootContext() {`),r.push(`if (!rootContextInstance) {`),r.push(`const factory = ${t}`),r.push(`rootContextInstance = factory()`),r.push(`}`),r.push(`return rootContextInstance`),r.push(`}`)):(r.push(`export function useRootContext() {`),r.push(`return {}`),r.push(`}`)),r.join(`
13
+ `)}const Vt=e=>e();var Ht=class{constructor(e,t){this.config=e,this.rootView={imports:[],template:`<OiyoPage />`,script:``},this.shouldRefreshVM=e=>{let t=``;this.rootMarco&&(t=D(De(`defineRootContext(${this.rootMarco.script})`)));let n=D(De(At(e)));return t!==n},this.logger=t.logger.withScope(`ROOT`),this.oiyoAutoApi=t.oiyoAutoApi}get srcDir(){return(0,p.resolve)(this.config.rootDir,this.config.srcDir)}get rootPath(){return(0,p.resolve)(this.srcDir,`App.vue`)}isRootPath(e){return e===this.rootPath}parseRoot(e){let{descriptor:t}=(0,_.parse)(e),n=It(t.scriptSetup);if(n?.script&&t.scriptSetup?.content&&this.oiyoAutoApi){let e=this.oiyoAutoApi.collectBoundNames(t.scriptSetup.content),r=this.oiyoAutoApi.resolveImports(n.script,{boundNames:e});r.length>0&&(n.imports=R(r,n.imports||[]))}return this.rootView={template:Ft(t.template,{varName:n?.variable,varProperties:n?.properties}),imports:[],script:``},n&&(this.rootMarco=n,this.rootVM=Bt(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}=(0,_.parse)(e),n=new v.default(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=jt(e);if(r.start!==r.end){e.includes(`virtual:oiyo-root-context`)||n.appendLeft(t.scriptSetup.loc.start.offset,`
14
14
  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 O(this.rootView.template)!==O(jt(e))}applyRoot(e){let t=[],n=``,r=``;return e.template&&(n=Lt(this.rootView.template,e.template.content)),e.scriptSetup&&(t.push(...this.rootView.imports),r=`${this.rootView.script}\n${e.scriptSetup.content}`),{imports:t,script:r,template:n}}};function Ht(e,t){if(!e.includes(`definePageMeta`))return``;if(!t){let{descriptor:t}=(0,_.parse)(e);if(!t.scriptSetup)return``;e=t.scriptSetup.content}let n=Ut(e);return e.substring(n.start,n.end+1).trim()}function Ut(e){return Te(e,`definePageMeta`)}function Wt(e){return e.replace(/definePageMeta\s*\(\s*\{[\s\S]*?\}\s*\)/g,``).trim()}function Gt(e){let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return T(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=Kt(t),e.stop())}}}),n}function Kt(e){let t={};for(let n of e.properties)if(n.type===`ObjectProperty`){let e=qt(n.key),r=Jt(n.value);e&&(t[e]=r)}return t}function qt(e){return e.type===`Identifier`?e.name:e.type===`StringLiteral`?e.value:null}function Jt(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=>Jt(e)).filter(e=>e!==void 0);case`ObjectExpression`:return Kt(e);default:return}}function Yt(e){return`'${e.startsWith(`/`)?e:`/${e}`}'`}function Xt(e){let t=new Set;for(let n of e.pages||[])t.add(Yt(n.path));for(let n of e.subPackages||[])for(let e of n.pages||[])t.add(Yt((0,p.join)(n.root,e.path)));return Array.from(t).sort()}function Zt(e){let t=new Set;for(let n of e.tabBar?.list||[])t.add(Yt(n.pagePath));return Array.from(t).sort()}function Qt(e){return e.length>0?e.join(` |
16
- `):`string`}function $t(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 en(e){let t=Xt(e),n=Zt(e);return[`/* eslint-disable */`,`// Generated by oiyo`,``,`interface NavigateToOptions {`,` url: ${Qt(t)};`,`}`,`interface RedirectToOptions extends NavigateToOptions {}`,``,`interface SwitchTabOptions {`,n.length>0?` url: ${n.join(` |
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 D(this.rootView.template)!==D(Mt(e))}applyRoot(e){let t=[],n=``,r=``;return e.template&&(n=Rt(this.rootView.template,e.template.content)),e.scriptSetup&&(t.push(...this.rootView.imports),r=`${this.rootView.script}\n${e.scriptSetup.content}`),{imports:t,script:r,template:n}}};function Ut(e,t){if(!e.includes(`definePageMeta`))return``;if(!t){let{descriptor:t}=(0,_.parse)(e);if(!t.scriptSetup)return``;e=t.scriptSetup.content}let n=Wt(e);return e.substring(n.start,n.end+1).trim()}function Wt(e){return Ee(e,`definePageMeta`)}function Gt(e){return e.replace(/definePageMeta\s*\(\s*\{[\s\S]*?\}\s*\)/g,``).trim()}function Kt(e){let t=(0,h.parse)(e,{sourceType:`module`,plugins:[`typescript`]}),n={};return w(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=qt(t),e.stop())}}}),n}function qt(e){let t={};for(let n of e.properties)if(n.type===`ObjectProperty`){let e=Jt(n.key),r=Yt(n.value);e&&(t[e]=r)}return t}function Jt(e){return e.type===`Identifier`?e.name:e.type===`StringLiteral`?e.value:null}function Yt(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=>Yt(e)).filter(e=>e!==void 0);case`ObjectExpression`:return qt(e);default:return}}function Xt(e){return`'${e.startsWith(`/`)?e:`/${e}`}'`}function Zt(e){let t=new Set;for(let n of e.pages||[])t.add(Xt(n.path));for(let n of e.subPackages||[])for(let e of n.pages||[])t.add(Xt((0,p.join)(n.root,e.path)));return Array.from(t).sort()}function Qt(e){let t=new Set;for(let n of e.tabBar?.list||[])t.add(Xt(n.pagePath));return Array.from(t).sort()}function $t(e){return e.length>0?e.join(` |
16
+ `):`string`}function en(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 tn(e){let t=Zt(e),n=Qt(e);return[`/* eslint-disable */`,`// Generated by oiyo`,``,`interface NavigateToOptions {`,` url: ${$t(t)};`,`}`,`interface RedirectToOptions extends NavigateToOptions {}`,``,`interface SwitchTabOptions {`,n.length>0?` url: ${n.join(` |
17
17
  `)};`:``,`}`,``,`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
- `)}const tn=e=>{},nn=(0,re.defineComponent)({name:`OiyoPage`});var rn=class{constructor(e,t){this.pageFiles=[],this.pagesConfig={},this.config=e,this.logger=t.logger.withScope(`ROUTE`),this.oiyoState=t.oiyoState,this.oiyoRoot=t.oiyoRoot,this.oiyoLayout=t.oiyoLayout}get srcDir(){return(0,p.resolve)(this.config.rootDir,this.config.srcDir)}get mainPageDir(){return(0,p.resolve)(this.srcDir,this.config.dir.mainPackage)}get subPageDirs(){return this.config.dir.subPackages.map(e=>(0,p.resolve)(this.srcDir,e))}get pagesJsonPath(){return(0,p.resolve)(this.srcDir,`pages.json`)}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return(0,p.resolve)(this.typesDir,`pages.d.ts`)}resolvePagesJson(e){return(0,ae.defu)($t(this.pageFiles),e||this.pagesConfig)}async loadPagesConfig(){try{let{config:e,configFile:t}=await(0,ie.loadConfig)({name:`pages`,cwd:this.srcDir});this.pagesConfig=e||{}}catch{this.pagesConfig={},this.logger.warn(`加载 pages 配置失败,已采用空配置`)}return this.pagesConfig}async watchPagesConfig(e){if(this.pagesConfigWatcher)return;let t=await(0,ie.watchConfig)({name:`pages`,cwd:this.srcDir,acceptHMR({getDiff:e}){return e().length===0},onWatch:e=>{},onUpdate:({newConfig:t})=>{this.pagesConfig=t.config||{},this.writePagesJson(),e&&Promise.resolve(e()).catch(e=>{this.logger.error(`pages 配置更新回调失败,页面配置已更新但后续回调未完成`,{error:e})})}});this.pagesConfig=t.config||this.pagesConfig,this.pagesConfigWatcher=t}async unwatchPagesConfig(){this.pagesConfigWatcher&&=(await this.pagesConfigWatcher.unwatch(),void 0)}isPagePath(e){let t=(0,p.normalize)(e);return!t.endsWith(`.vue`)&&!t.endsWith(`.nvue`)||[...ne.DEFAULT_EXCLUDE,...this.config.exclude||[]].some(e=>(0,p.matchesGlob)(t,e))||I(this.config,t)?!1:[this.mainPageDir,...this.subPageDirs].some(e=>t.startsWith(`${e}/`))}toPageFile(e,t){let n=!0,r=this.mainPageDir,i=this.subPageDirs.find(t=>e.startsWith(`${t}/`));i&&(n=!1);let a=(0,p.parse)((0,p.relative)(n?this.srcDir:i,e)),o=a.dir===``?a.name:(0,p.join)(a.dir,a.name),s=n?r:i;return{filePath:e,pagePath:o,pageBelong:(0,p.relative)(this.srcDir,s),pageMeta:t}}setPageFile(e){let t=this.pageFiles.findIndex(({pagePath:t,pageBelong:n})=>t===e.pagePath&&n===e.pageBelong);if(t===-1)return this.pageFiles.push(e),!0;let n=this.pageFiles[t],r=JSON.stringify(n.pageMeta)!==JSON.stringify(e.pageMeta);return r&&(this.pageFiles[t]=e),r}async loadPagesJson(){try{let e=await(0,f.readFile)(this.pagesJsonPath,`utf-8`),t=JSON.parse(e);for(let e of t.pages||[]){let{path:t,...n}=e,r=(0,p.resolve)(this.srcDir,e.path),i=this.toPageFile(r,n);this.setPageFile(i)}for(let e of t.subPackages||[]){let t=e.root;for(let n of e.pages||[]){let{path:e,...r}=n,i=(0,p.resolve)(this.srcDir,t,n.path);this.setPageFile(this.toPageFile(i,r))}}}catch(e){this.logger.error(`加载 pages.json 失败,已跳过现有文件内容,请检查 pages.json 是否存在且格式正确:`,{error:e})}}writePagesJson(e){try{let t=this.resolvePagesJson(e),n=`${JSON.stringify(t,null,2)}\n`;k(this.pagesJsonPath,n),this.writeDeclaration(e)}catch(e){this.logger.error(`写入 pages.json 失败,请检查目标文件权限和内容格式:`,{error:e})}}generateDeclaration(e){return en(this.resolvePagesJson(e))}writeDeclaration(e){try{(0,d.mkdirSync)(this.typesDir,{recursive:!0}),k(this.declarationPath,this.generateDeclaration(e)),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`写入 pages.d.ts 失败,请检查目标文件权限和内容格式:`,{error:e})}return this.declarationPath}async registerPages(){let e=[this.mainPageDir,...this.subPageDirs],t=(await Promise.all(e.map(e=>D({dir:e,pattern:[`**/*.vue`,`**/*.nvue`]})))).flat(2).filter(e=>this.isPagePath(e));for(let e of t){let t=await(0,f.readFile)(e,`utf-8`),n={},r=Ht(t);r&&(n=Gt(r)),this.setPageFile(this.toPageFile(e,n))}return this.pageFiles}async tryUpdatePage(e,t){let n=Gt(e);this.setPageFile(this.toPageFile(t,n))&&(this.writePagesJson(),await new Promise(e=>setTimeout(e,100)))}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}=(0,_.parse)(e),r=new v.default(e);if(!n.template?.content)return{code:r.toString(),sourceMap:r.generateMap()};n.scriptSetup&&await this.tryUpdatePage(n.scriptSetup.content,t);let i=this.oiyoRoot.applyRoot(n),a=[...i.imports],o=i.template,s=i.script,c={};n.scriptSetup&&(c=this.pageFiles.find(e=>t.startsWith(e.filePath))?.pageMeta||{},s=Wt(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=L(n.scriptSetup.content);a=z(a,e),s=Tt(s),r.overwrite(n.scriptSetup.loc.start.offset,n.scriptSetup.loc.end.offset,`${a.join(`
18
+ `)}const nn=e=>{},rn=(0,re.defineComponent)({name:`OiyoPage`});var an=class{constructor(e,t){this.pageFiles=[],this.pagesConfig={},this.config=e,this.logger=t.logger.withScope(`ROUTE`),this.oiyoState=t.oiyoState,this.oiyoRoot=t.oiyoRoot,this.oiyoLayout=t.oiyoLayout}get srcDir(){return(0,p.resolve)(this.config.rootDir,this.config.srcDir)}get mainPageDir(){return(0,p.resolve)(this.srcDir,this.config.dir.mainPackage)}get subPageDirs(){return this.config.dir.subPackages.map(e=>(0,p.resolve)(this.srcDir,e))}get pagesJsonPath(){return(0,p.resolve)(this.srcDir,`pages.json`)}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return(0,p.resolve)(this.typesDir,`pages.d.ts`)}resolvePagesJson(e){return(0,ae.defu)(en(this.pageFiles),e||this.pagesConfig)}async loadPagesConfig(){try{let{config:e,configFile:t}=await(0,ie.loadConfig)({name:`pages`,cwd:this.srcDir});this.pagesConfig=e||{}}catch{this.pagesConfig={},this.logger.warn(`加载 pages 配置失败,已采用空配置`)}return this.pagesConfig}async watchPagesConfig(e){if(this.pagesConfigWatcher)return;let t=await(0,ie.watchConfig)({name:`pages`,cwd:this.srcDir,acceptHMR({getDiff:e}){return e().length===0},onWatch:e=>{},onUpdate:({newConfig:t})=>{this.pagesConfig=t.config||{},this.writePagesJson(),e&&Promise.resolve(e()).catch(e=>{this.logger.error(`pages 配置更新回调失败,页面配置已更新但后续回调未完成`,{error:e})})}});this.pagesConfig=t.config||this.pagesConfig,this.pagesConfigWatcher=t}async unwatchPagesConfig(){this.pagesConfigWatcher&&=(await this.pagesConfigWatcher.unwatch(),void 0)}isPagePath(e){let t=(0,p.normalize)(e);return!t.endsWith(`.vue`)&&!t.endsWith(`.nvue`)||[...ne.DEFAULT_EXCLUDE,...this.config.exclude||[]].some(e=>(0,p.matchesGlob)(t,e))||F(this.config,t)?!1:[this.mainPageDir,...this.subPageDirs].some(e=>t.startsWith(`${e}/`))}toPageFile(e,t){let n=!0,r=this.mainPageDir,i=this.subPageDirs.find(t=>e.startsWith(`${t}/`));i&&(n=!1);let a=(0,p.parse)((0,p.relative)(n?this.srcDir:i,e)),o=a.dir===``?a.name:(0,p.join)(a.dir,a.name),s=n?r:i;return{filePath:e,pagePath:o,pageBelong:(0,p.relative)(this.srcDir,s),pageMeta:t}}setPageFile(e){let t=this.pageFiles.findIndex(({pagePath:t,pageBelong:n})=>t===e.pagePath&&n===e.pageBelong);if(t===-1)return this.pageFiles.push(e),!0;let n=this.pageFiles[t],r=JSON.stringify(n.pageMeta)!==JSON.stringify(e.pageMeta);return r&&(this.pageFiles[t]=e),r}async loadPagesJson(){try{let e=await(0,f.readFile)(this.pagesJsonPath,`utf-8`),t=JSON.parse(e);for(let e of t.pages||[]){let{path:t,...n}=e,r=(0,p.resolve)(this.srcDir,e.path),i=this.toPageFile(r,n);this.setPageFile(i)}for(let e of t.subPackages||[]){let t=e.root;for(let n of e.pages||[]){let{path:e,...r}=n,i=(0,p.resolve)(this.srcDir,t,n.path);this.setPageFile(this.toPageFile(i,r))}}}catch(e){this.logger.error(`加载 pages.json 失败,已跳过现有文件内容,请检查 pages.json 是否存在且格式正确:`,{error:e})}}writePagesJson(e){try{let t=this.resolvePagesJson(e),n=`${JSON.stringify(t,null,2)}\n`;O(this.pagesJsonPath,n),this.writeDeclaration(e)}catch(e){this.logger.error(`写入 pages.json 失败,请检查目标文件权限和内容格式:`,{error:e})}}generateDeclaration(e){return tn(this.resolvePagesJson(e))}writeDeclaration(e){try{(0,d.mkdirSync)(this.typesDir,{recursive:!0}),O(this.declarationPath,this.generateDeclaration(e)),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`写入 pages.d.ts 失败,请检查目标文件权限和内容格式:`,{error:e})}return this.declarationPath}async registerPages(){let e=[this.mainPageDir,...this.subPageDirs],t=(await Promise.all(e.map(e=>E({dir:e,pattern:[`**/*.vue`,`**/*.nvue`]})))).flat(2).filter(e=>this.isPagePath(e));for(let e of t){let t=await(0,f.readFile)(e,`utf-8`),n={},r=Ut(t);r&&(n=Kt(r)),this.setPageFile(this.toPageFile(e,n))}return this.pageFiles}async tryUpdatePage(e,t){let n=Kt(e);this.setPageFile(this.toPageFile(t,n))&&(this.writePagesJson(),await new Promise(e=>setTimeout(e,100)))}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}=(0,_.parse)(e),r=new v.default(e);if(!n.template?.content)return{code:r.toString(),sourceMap:r.generateMap()};n.scriptSetup&&await this.tryUpdatePage(n.scriptSetup.content,t);let i=this.oiyoRoot.applyRoot(n),a=[...i.imports],o=i.template,s=i.script,c={};n.scriptSetup&&(c=this.pageFiles.find(e=>t.startsWith(e.filePath))?.pageMeta||{},s=Gt(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=I(n.scriptSetup.content);a=R(a,e),s=Et(s),r.overwrite(n.scriptSetup.loc.start.offset,n.scriptSetup.loc.end.offset,`${a.join(`
19
19
  `)}\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 an=new Set([`.ts`,`.mts`,`.cts`,`.js`,`.mjs`,`.cjs`,`.tsx`,`.jsx`]);function on(e){return e.endsWith(`.vue`)||e.endsWith(`.nvue`)}function sn(e){return Array.from(an).some(t=>e.endsWith(t))}function cn(e){return(0,p.normalize)(e.split(`?`,1)[0])}function V(e,t){return[...e,t].filter(Boolean).join(`
21
- `)}function ln(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 un(e,t,n){let r=z(n,L(t.content)),i=Tt(t.content);e.overwrite(t.loc.start.offset,t.loc.end.offset,V(r,i))}function dn(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 fn(e){let t=new Set;return e.script?.content&&R(e.script.content).forEach(e=>t.add(e)),e.scriptSetup?.content&&R(e.scriptSetup.content).forEach(e=>t.add(e)),t}function pn(e,t){let n=R(e),r=t.autoApi.resolveImports(e,{boundNames:n});if(r.length===0)return null;let i=z(r,L(e)),a=Tt(e),o=new v.default(e);return o.overwrite(0,e.length,V(i,a)),{code:o.toString(),sourceMap:o.generateMap()}}function mn(e,t,n){let{descriptor:r}=(0,_.parse)(e),i=fn(r),a=r.template?.content?Array.from(dn(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 v.default(e);return r.scriptSetup?(un(s,r.scriptSetup,[...a,...o]),{code:s.toString(),sourceMap:s.generateMap()}):r.script?(o.length>0&&un(s,r.script,o),a.length>0&&ln(s,r,V(a,``)),{code:s.toString(),sourceMap:s.generateMap()}):(ln(s,r,V([...a,...o],``)),{code:s.toString(),sourceMap:s.generateMap()})}function hn(){let e;return[{name:`oiyo:auto`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`AUTO`)},transform(t,n){let r=cn(n);return sn(r)?r.startsWith(`${e.root.srcDir}/`)&&pn(t,e)||void 0:!on(r)||!r.startsWith(`${e.root.srcDir}/`)&&r!==e.root.rootPath?void 0:mn(t,r,e)||void 0}}]}const H={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},gn={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:H.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(gn);const _n=`READDIRP_RECURSIVE_ERROR`,vn=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,_n]),yn=[H.DIR_TYPE,H.EVERYTHING_TYPE,H.FILE_DIR_TYPE,H.FILE_TYPE],bn=new Set([H.DIR_TYPE,H.EVERYTHING_TYPE,H.FILE_DIR_TYPE]),xn=new Set([H.EVERYTHING_TYPE,H.FILE_DIR_TYPE,H.FILE_TYPE]),Sn=e=>vn.has(e.code),Cn=process.platform===`win32`,wn=e=>!0,Tn=e=>{if(e===void 0)return wn;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 wn};var En=class extends se.Readable{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...gn,...e},{root:n,type:r}=t;this._fileFilter=Tn(t.fileFilter),this._directoryFilter=Tn(t.directoryFilter);let i=t.lstat?f.lstat:f.stat;Cn?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??gn.depth,this._wantsDir=r?bn.has(r):!1,this._wantsFile=r?xn.has(r):!1,this._wantsEverything=r===H.EVERYTHING_TYPE,this._root=(0,S.resolve)(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(0,f.readdir)(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=(0,S.resolve)((0,S.join)(t,r));n={path:(0,S.relative)(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){Sn(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(0,f.realpath)(t),n=await(0,f.lstat)(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===S.sep){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=_n,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 Dn(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&&!yn.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${yn.join(`, `)}`);return t.root=e,new En(t)}const On=()=>{},U=process.platform,kn=U===`win32`,An=U===`darwin`,jn=U===`linux`,Mn=U===`freebsd`,Nn=(0,ce.type)()===`OS400`,W={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},G=W,Pn={lstat:b.lstat,stat:b.stat},K=`listeners`,q=`errHandlers`,J=`rawEmitters`,Fn=[K,q,J],In=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(`.`)),Ln=e=>In.has(x.extname(e).slice(1).toLowerCase()),Rn=(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)},zn=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]},Bn=e=>e instanceof Set?e.size===0:!e,Z=new Map;function Vn(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&Q(x.resolve(e,r),K,x.join(e,r))};try{return(0,y.watch)(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const Q=(e,t,n,r,i)=>{let a=Z.get(e);a&&Rn(a[t],e=>{e(n,r,i)})},Hn=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Z.get(t),c;if(!n.persistent)return c=Vn(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=Vn(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),kn&&n.code===`EPERM`)try{await(await(0,b.open)(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),Bn(s.listeners)&&(s.watcher.close(),Z.delete(t),Fn.forEach(zn(s)),s.watcher=void 0,Object.freeze(s))}},Un=new Map,Wn=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=Un.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&((0,y.unwatchFile)(t),o=void 0),o?(Y(o,K,i),Y(o,J,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:(0,y.watchFile)(t,n,(n,r)=>{Rn(o.rawEmitters,e=>{e(G.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&Rn(o.listeners,t=>t(e,n))})},Un.set(t,o)),()=>{X(o,K,i),X(o,J,a),Bn(o.listeners)&&(Un.delete(t),(0,y.unwatchFile)(t),o.options=o.watcher=void 0,Object.freeze(o))}};var Gn=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=x.dirname(e),i=x.basename(e);this.fsw._getWatchedDir(r).add(i);let a=x.resolve(e),o={persistent:n.persistent};t||=On;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&Ln(i)?n.binaryInterval:n.interval,s=Wn(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=Hn(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=x.dirname(e),i=x.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(0,b.stat)(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),(An||jn||Mn)&&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(0,b.realpath)(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=x.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=x.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=x.join(i,x.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(x.dirname(e)),c=s.has(x.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(G.ADD_DIR,e,t),s.add(x.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 Pn[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=x.resolve(e),l=s?await(0,b.realpath)(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(0,b.realpath)(e):e;if(this.fsw.closed)return;let a=x.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(x.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}}};
20
+ `);r.appendRight(n.template.loc.end.offset+11,`\n\n${e}`)}return{code:r.toString(),sourceMap:r.generateMap()}}};const on=new Set([`.ts`,`.mts`,`.cts`,`.js`,`.mjs`,`.cjs`,`.tsx`,`.jsx`]);function sn(e){return e.endsWith(`.vue`)||e.endsWith(`.nvue`)}function cn(e){return Array.from(on).some(t=>e.endsWith(t))}function ln(e){return(0,p.normalize)(e.split(`?`,1)[0])}function B(e,t){return[...e,t].filter(Boolean).join(`
21
+ `)}function un(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 dn(e,t,n){let r=R(n,I(t.content)),i=Et(t.content);e.overwrite(t.loc.start.offset,t.loc.end.offset,B(r,i))}function fn(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 pn(e){let t=new Set;return e.script?.content&&L(e.script.content).forEach(e=>t.add(e)),e.scriptSetup?.content&&L(e.scriptSetup.content).forEach(e=>t.add(e)),t}function mn(e,t){let n=L(e),r=t.autoApi.resolveImports(e,{boundNames:n});if(r.length===0)return null;let i=R(r,I(e)),a=Et(e),o=new v.default(e);return o.overwrite(0,e.length,B(i,a)),{code:o.toString(),sourceMap:o.generateMap()}}function hn(e,t,n){let{descriptor:r}=(0,_.parse)(e),i=pn(r),a=r.template?.content?Array.from(fn(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 v.default(e);return r.scriptSetup?(dn(s,r.scriptSetup,[...a,...o]),{code:s.toString(),sourceMap:s.generateMap()}):r.script?(o.length>0&&dn(s,r.script,o),a.length>0&&un(s,r,B(a,``)),{code:s.toString(),sourceMap:s.generateMap()}):(un(s,r,B([...a,...o],``)),{code:s.toString(),sourceMap:s.generateMap()})}function gn(){let e;return[{name:`oiyo:auto`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`AUTO`)},transform(t,n){let r=ln(n);return cn(r)?r.startsWith(`${e.root.srcDir}/`)&&mn(t,e)||void 0:!sn(r)||!r.startsWith(`${e.root.srcDir}/`)&&r!==e.root.rootPath?void 0:hn(t,r,e)||void 0}}]}const V={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},_n={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:V.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(_n);const vn=`READDIRP_RECURSIVE_ERROR`,yn=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,vn]),bn=[V.DIR_TYPE,V.EVERYTHING_TYPE,V.FILE_DIR_TYPE,V.FILE_TYPE],xn=new Set([V.DIR_TYPE,V.EVERYTHING_TYPE,V.FILE_DIR_TYPE]),Sn=new Set([V.EVERYTHING_TYPE,V.FILE_DIR_TYPE,V.FILE_TYPE]),Cn=e=>yn.has(e.code),wn=process.platform===`win32`,Tn=e=>!0,En=e=>{if(e===void 0)return Tn;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 Tn};var Dn=class extends se.Readable{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={..._n,...e},{root:n,type:r}=t;this._fileFilter=En(t.fileFilter),this._directoryFilter=En(t.directoryFilter);let i=t.lstat?f.lstat:f.stat;wn?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??_n.depth,this._wantsDir=r?xn.has(r):!1,this._wantsFile=r?Sn.has(r):!1,this._wantsEverything=r===V.EVERYTHING_TYPE,this._root=(0,S.resolve)(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(0,f.readdir)(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=(0,S.resolve)((0,S.join)(t,r));n={path:(0,S.relative)(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){Cn(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(0,f.realpath)(t),n=await(0,f.lstat)(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===S.sep){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=vn,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 On(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=V.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&&!bn.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${bn.join(`, `)}`);return t.root=e,new Dn(t)}const kn=()=>{},H=process.platform,An=H===`win32`,jn=H===`darwin`,Mn=H===`linux`,Nn=H===`freebsd`,Pn=(0,ce.type)()===`OS400`,U={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},W=U,Fn={lstat:b.lstat,stat:b.stat},G=`listeners`,K=`errHandlers`,q=`rawEmitters`,In=[G,K,q],Ln=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(`.`)),Rn=e=>Ln.has(x.extname(e).slice(1).toLowerCase()),zn=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},J=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},Bn=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},Y=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},Vn=e=>e instanceof Set?e.size===0:!e,X=new Map;function Hn(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&Z(x.resolve(e,r),G,x.join(e,r))};try{return(0,y.watch)(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const Z=(e,t,n,r,i)=>{let a=X.get(e);a&&zn(a[t],e=>{e(n,r,i)})},Un=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=X.get(t),c;if(!n.persistent)return c=Hn(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)J(s,G,i),J(s,K,a),J(s,q,o);else{if(c=Hn(e,n,Z.bind(null,t,G),a,Z.bind(null,t,q)),!c)return;c.on(W.ERROR,async n=>{let r=Z.bind(null,t,K);if(s&&(s.watcherUnusable=!0),An&&n.code===`EPERM`)try{await(await(0,b.open)(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},X.set(t,s)}return()=>{Y(s,G,i),Y(s,K,a),Y(s,q,o),Vn(s.listeners)&&(s.watcher.close(),X.delete(t),In.forEach(Bn(s)),s.watcher=void 0,Object.freeze(s))}},Wn=new Map,Gn=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=Wn.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&((0,y.unwatchFile)(t),o=void 0),o?(J(o,G,i),J(o,q,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:(0,y.watchFile)(t,n,(n,r)=>{zn(o.rawEmitters,e=>{e(W.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))})},Wn.set(t,o)),()=>{Y(o,G,i),Y(o,q,a),Vn(o.listeners)&&(Wn.delete(t),(0,y.unwatchFile)(t),o.options=o.watcher=void 0,Object.freeze(o))}};var Kn=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=x.dirname(e),i=x.basename(e);this.fsw._getWatchedDir(r).add(i);let a=x.resolve(e),o={persistent:n.persistent};t||=kn;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&Rn(i)?n.binaryInterval:n.interval,s=Gn(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=Un(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=x.dirname(e),i=x.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(0,b.stat)(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(W.CHANGE,e,n),(jn||Mn||Nn)&&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(W.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(W.ADD,e,0))return;this.fsw._emit(W.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(0,b.realpath)(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(W.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(W.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=x.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=x.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=x.join(i,x.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(W.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(x.dirname(e)),c=s.has(x.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(W.ADD_DIR,e,t),s.add(x.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 Fn[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=x.resolve(e),l=s?await(0,b.realpath)(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(0,b.realpath)(e):e;if(this.fsw.closed)return;let a=x.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(W.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(x.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
23
  /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
24
- const Kn=/\\/g,qn=/\/\//,Jn=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Yn=/^\.[/\\]/;function $(e){return Array.isArray(e)?e:[e]}const Xn=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function Zn(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=x.relative(e.path,t);return n?!n.startsWith(`..`)&&!x.isAbsolute(n):!1}return!1}:()=>!1}function Qn(e){if(typeof e!=`string`)throw Error(`string expected`);e=x.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 $n(e,t,n){let r=Qn(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function er(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=$(e).map(e=>Zn(e));return t==null?(e,t)=>$n(n,e,t):$n(n,t)}const tr=e=>{let t=$(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(rr)},nr=e=>{let t=e.replace(Kn,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(qn);)t=t.replace(qn,`/`);return n&&(t=`/`+t),t},rr=e=>nr(x.normalize(nr(e))),ir=(e=``)=>t=>typeof t==`string`?rr(x.isAbsolute(t)?t:x.join(e,t)):t,ar=(e,t)=>x.isAbsolute(e)?e:x.join(t,e),or=Object.freeze(new Set);var sr=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(0,b.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(x.dirname(n),x.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=On,this.items=or,Object.freeze(this)}},cr=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Yn,``),this.watchPath=r,this.fullWatchPath=x.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return x.join(this.watchPath,x.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)}},lr=class extends oe.EventEmitter{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};Nn&&(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=On,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 Gn(this),Object.freeze(r)}_addIgnoredPath(e){if(Xn(e)){for(let t of this._ignoredPaths)if(Xn(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)Xn(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=tr(e);return r&&(i=i.map(e=>ar(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(x.dirname(e),x.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=tr(e),{cwd:n}=this.options;return t.forEach(e=>{!x.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=x.join(n,e)),e=x.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?x.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;kn&&(t=x.normalize(t)),r.cwd&&(t=x.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?x.join(r.cwd,t):t,n;try{n=await(0,b.stat)(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&&!x.isAbsolute(e)&&(s=x.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){(0,y.stat)(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&&Jn.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(ir(e));this._userIgnored=er([...[...this._ignoredPaths].map(ir(e)),...t],void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new cr(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=x.resolve(e);return this._watched.has(t)||this._watched.set(t,new sr(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=x.join(e,t),i=x.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=x.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=x.dirname(e);this._getWatchedDir(t).remove(x.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=Dn(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 ur(e,t={}){let n=new lr(t);return n.add(e),n}function dr(){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.autoApi.writeDeclaration(),e.autoComponent.writeDeclaration(),e.layout.writeDeclaration(),e.route.writeDeclaration();let r=async t=>{e.layout.isLayoutPath(t)&&(await e.layout.registerLayouts(),e.layout.writeDeclaration()),e.autoComponent.isAutoComponentPath(t)&&(await e.autoComponent.collectComponents(),e.autoComponent.writeDeclaration()),e.autoApi.isAutoApiPath(t)&&(await e.autoApi.collectApis(),e.autoApi.writeDeclaration())};n===`serve`&&ur(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 fr=class{constructor(e){this.config=e}get stateDir(){return(0,p.resolve)(this.config.rootDir,`.oiyo`)}get typesDir(){return(0,p.resolve)(this.stateDir,`types`)}get srcDir(){return(0,p.resolve)(this.config.rootDir,this.config.srcDir)}get declarationEntryPath(){return(0,p.resolve)(this.stateDir,`oiyo.d.ts`)}get appTsconfigPath(){return(0,p.resolve)(this.stateDir,`tsconfig.app.json`)}get nodeTsconfigPath(){return(0,p.resolve)(this.stateDir,`tsconfig.node.json`)}relativeToState(e){return(0,p.normalize)((0,p.relative)(this.stateDir,e))}stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}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
- `)}generateAppTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir),n=this.relativeToState(this.stateDir);return this.stringifyJson({compilerOptions:{paths:{"~/*":[(0,p.join)(t,`*`)],"~~/*":[(0,p.join)(e,`*`)],"@/*":[(0,p.join)(t,`*`)],"@@/*":[(0,p.join)(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:[(0,p.join)(n,`oiyo.d.ts`),(0,p.join)(t,`**/*`),(0,p.join)(e,`*.d.ts`)],exclude:[(0,p.join)(t,`pages.config.*`),(0,p.join)(e,`dist`),(0,p.join)(e,`node_modules`),(0,p.join)(e,`vite.config.*`),(0,p.join)(e,`oiyo.config.*`)]})}generateNodeTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir);return this.stringifyJson({compilerOptions:{paths:{},esModuleInterop:!0,skipLibCheck:!0,target:`ESNext`,allowJs:!0,resolveJsonModule:!0,moduleDetection:`force`,isolatedModules:!0,verbatimModuleSyntax:!0,allowArbitraryExtensions:!0,strict:!0,noUncheckedIndexedAccess:!0,forceConsistentCasingInFileNames:!0,noImplicitOverride:!0,module:`preserve`,noEmit:!0,types:[],moduleResolution:`Bundler`,useDefineForClassFields:!0},include:[(0,p.join)(e,`oiyo.config.*`),(0,p.join)(e,`vite.config.*`),(0,p.join)(e,`vitest.config.*`)],exclude:[(0,p.join)(t,`**/*`),(0,p.join)(e,`dist`),(0,p.join)(e,`node_modules`)]})}writeAppTsconfig(){return(0,d.mkdirSync)(this.stateDir,{recursive:!0}),k(this.appTsconfigPath,this.generateAppTsconfig()),this.appTsconfigPath}writeNodeTsconfig(){return(0,d.mkdirSync)(this.stateDir,{recursive:!0}),k(this.nodeTsconfigPath,this.generateNodeTsconfig()),this.nodeTsconfigPath}writeDeclarationEntry(){return(0,d.mkdirSync)(this.stateDir,{recursive:!0}),k(this.declarationEntryPath,this.generateDeclarationEntry()),this.writeAppTsconfig(),this.writeNodeTsconfig(),this.declarationEntryPath}ensureDeclarationEntry(){return(0,d.existsSync)(this.appTsconfigPath)||this.writeAppTsconfig(),(0,d.existsSync)(this.nodeTsconfigPath)||this.writeNodeTsconfig(),(0,d.existsSync)(this.declarationEntryPath)?this.declarationEntryPath:this.writeDeclarationEntry()}};function pr(e){let t=(0,ne.resolveOiyoConfig)(e),n=w();n.withScope(`CONFIG`);let r=new fr(t),i=new _t(t,{logger:n,oiyoState:r}),a=new tt(t,{logger:n,oiyoState:r}),o=new Vt(t,{oiyoAutoApi:a,logger:n}),s=new wt(t,{logger:n,oiyoState:r});return{logger:n,config:t,autoApi:a,autoComponent:i,layout:s,state:r,route:new rn(t,{logger:n,oiyoState:r,oiyoRoot:o,oiyoLayout:s}),root:o}}function mr(e){return[{name:`oiyo:deps`,enforce:`pre`,async config(t){let{config:n}=await(0,ie.loadConfig)({name:`oiyo`,cwd:t.root}),r=pr(n||e);return(0,ae.defu)(t,{oiyo:r,resolve:{alias:{"~":S.default.resolve(r.config.rootDir,r.config.srcDir),"@":S.default.resolve(r.config.rootDir,r.config.srcDir),"@@":S.default.normalize(r.config.rootDir),"~~":S.default.normalize(r.config.rootDir)}},optimizeDeps:{exclude:[`@skiyee/oiyo`]}})}}]}function hr(){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.autoApi.collectApis(),e.autoComponent.collectComponents(),e.route.loadPagesConfig(),e.route.loadPagesJson(),e.layout.registerLayouts()]),e.autoApi.writeDeclaration(),e.autoComponent.writeDeclaration(),e.layout.writeDeclaration(),e.route.writeDeclaration()},configureServer(t){e.route.watchPagesConfig(()=>{t.hot.send({type:`full-reload`})});let n=async n=>{let r=!1;e.layout.isLayoutPath(n)&&(await e.layout.registerLayouts(),e.layout.writeDeclaration(),r=!0),e.autoComponent.isAutoComponentPath(n)&&(await e.autoComponent.collectComponents(),e.autoComponent.writeDeclaration(),r=!0),e.autoApi.isAutoApiPath(n)&&(await e.autoApi.collectApis(),e.autoApi.writeDeclaration(),r=!0),r&&t.hot.send({type:`full-reload`})};t.watcher.on(`add`,e=>void n(e)),t.watcher.on(`unlink`,e=>void n(e)),t.watcher.on(`change`,e=>void n(e))},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 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(B);e&&(n.moduleGraph.invalidateModule(e),i=!0)}if(i){n.hot.send({type:`full-reload`});return}}},async closeBundle(){await e.route.unwatchPagesConfig()}}]}function gr(e={}){return[...mr(e),...hr(),...dr(),...hn()]}exports.LogLevels=C,exports.OiyoCorePlugin=gr,exports.OiyoLayout=Ct,exports.OiyoModAutoApi=tt,exports.OiyoModAutoComponent=_t,exports.OiyoModLayout=wt,exports.OiyoModRoot=Vt,exports.OiyoModRoute=rn,exports.OiyoPage=nn,exports.OiyoState=fr,exports.RESOLVED_VIRTUAL_ROOT_CONTEXT_ID=B,exports.VIRTUAL_ROOT_CONTEXT_ID=Rt,exports.createLogger=w,exports.definePageMeta=tn,exports.defineRootContext=Bt,exports.isScannedComponentPath=I,exports.resolveComponentName=lt,exports.resolveScannedComponentSources=ot;
24
+ const qn=/\\/g,Jn=/\/\//,Yn=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Xn=/^\.[/\\]/;function Q(e){return Array.isArray(e)?e:[e]}const Zn=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function Qn(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=x.relative(e.path,t);return n?!n.startsWith(`..`)&&!x.isAbsolute(n):!1}return!1}:()=>!1}function $n(e){if(typeof e!=`string`)throw Error(`string expected`);e=x.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 er(e,t,n){let r=$n(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function tr(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=Q(e).map(e=>Qn(e));return t==null?(e,t)=>er(n,e,t):er(n,t)}const nr=e=>{let t=Q(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(ir)},rr=e=>{let t=e.replace(qn,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(Jn);)t=t.replace(Jn,`/`);return n&&(t=`/`+t),t},ir=e=>rr(x.normalize(rr(e))),ar=(e=``)=>t=>typeof t==`string`?ir(x.isAbsolute(t)?t:x.join(e,t)):t,or=(e,t)=>x.isAbsolute(e)?e:x.join(t,e),sr=Object.freeze(new Set);var cr=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(0,b.readdir)(n)}catch{this._removeWatcher&&this._removeWatcher(x.dirname(n),x.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=kn,this.items=sr,Object.freeze(this)}},lr=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Xn,``),this.watchPath=r,this.fullWatchPath=x.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?`stat`:`lstat`}entryPath(e){return x.join(this.watchPath,x.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)}},ur=class extends oe.EventEmitter{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?Q(e.ignored):Q([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};Pn&&(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=kn,this._readyEmitted=!0,process.nextTick(()=>this.emit(U.READY)))},this._emitRaw=(...e)=>this.emit(U.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new Kn(this),Object.freeze(r)}_addIgnoredPath(e){if(Zn(e)){for(let t of this._ignoredPaths)if(Zn(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)Zn(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=>or(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(x.dirname(e),x.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=nr(e),{cwd:n}=this.options;return t.forEach(e=>{!x.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=x.join(n,e)),e=x.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?x.relative(this.options.cwd,n):n)||`.`;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==U.ERROR&&this.emit(U.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;An&&(t=x.normalize(t)),r.cwd&&(t=x.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===U.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(U.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===U.ADD&&this._pendingUnlinks.has(t)&&(e=U.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===U.ADD||e===U.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=U.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===U.CHANGE&&!this._throttle(U.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===U.ADD||e===U.ADD_DIR||e===U.CHANGE)){let e=r.cwd?x.join(r.cwd,t):t,n;try{n=await(0,b.stat)(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(U.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&&!x.isAbsolute(e)&&(s=x.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){(0,y.stat)(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&&Yn.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(ar(e));this._userIgnored=tr([...[...this._ignoredPaths].map(ar(e)),...t],void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new lr(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=x.resolve(e);return this._watched.has(t)||this._watched.set(t,new cr(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=x.join(e,t),i=x.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=x.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===U.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?U.UNLINK_DIR:U.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=x.dirname(e);this._getWatchedDir(t).remove(x.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=On(e,{type:U.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 dr(e,t={}){let n=new ur(t);return n.add(e),n}function fr(){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`&&dr(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 z},load(t){if(t===z)return e.root.rootVM||`export function useRootContext() {return {}}`},async closeBundle(){await e.route.unwatchPagesConfig()}}]}var $=`0.1.2`,pr=class{constructor(e){this.config=e}get stateDir(){return(0,p.resolve)(this.config.rootDir,`.oiyo`)}get typesDir(){return(0,p.resolve)(this.stateDir,`types`)}get srcDir(){return(0,p.resolve)(this.config.rootDir,this.config.srcDir)}get declarationEntryPath(){return(0,p.resolve)(this.stateDir,`oiyo.d.ts`)}get tsconfigPath(){return(0,p.resolve)(this.stateDir,`tsconfig.json`)}get metadataPath(){return(0,p.resolve)(this.stateDir,`oiyo.json`)}get declarationPaths(){return[this.declarationEntryPath,this.tsconfigPath,(0,p.resolve)(this.typesDir,`apis.d.ts`),(0,p.resolve)(this.typesDir,`components.d.ts`),(0,p.resolve)(this.typesDir,`layouts.d.ts`),(0,p.resolve)(this.typesDir,`pages.d.ts`)]}relativeToState(e){return(0,p.normalize)((0,p.relative)(this.stateDir,e))}stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}serializeMetadataInput(){return JSON.stringify({rootDir:(0,p.normalize)(this.config.rootDir||``),srcDir:this.config.srcDir||``,dir:this.config.dir||{},scan:this.config.scan||{},exclude:this.config.exclude||[]})}generateMetadataHash(){return D(`${$}:${this.serializeMetadataInput()}`,16)}generateMetadata(){return{hash:this.generateMetadataHash(),project:{rootDir:(0,p.normalize)(this.config.rootDir||``)},versions:{oiyo:$}}}readMetadata(){if(!(0,d.existsSync)(this.metadataPath))return null;try{return JSON.parse((0,d.readFileSync)(this.metadataPath,`utf-8`))}catch{return null}}writeMetadata(){(0,d.mkdirSync)(this.stateDir,{recursive:!0});let e=this.generateMetadata();return O(this.metadataPath,this.stringifyJson(e)),e}canReuseGeneratedState(){let e=this.readMetadata();return!e||e.project.rootDir!==(0,p.normalize)(this.config.rootDir||``)||e.versions.oiyo!==$||e.hash!==this.generateMetadataHash()?!1:this.declarationPaths.every(e=>(0,d.existsSync)(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:{"~/*":[(0,p.join)(t,`*`)],"~~/*":[(0,p.join)(e,`*`)],"@/*":[(0,p.join)(t,`*`)],"@@/*":[(0,p.join)(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:[(0,p.join)(n,`oiyo.d.ts`),(0,p.join)(t,`**/*`),(0,p.join)(e,`*.d.ts`),(0,p.join)(e,`oiyo.config.*`),(0,p.join)(e,`vite.config.*`),(0,p.join)(e,`vitest.config.*`)],exclude:[(0,p.join)(t,`pages.config.*`),(0,p.join)(e,`dist`),(0,p.join)(e,`node_modules`)]})}writeTsconfig(){return(0,d.mkdirSync)(this.stateDir,{recursive:!0}),O(this.tsconfigPath,this.generateTsconfig()),this.tsconfigPath}writeDeclarationEntry(){return(0,d.mkdirSync)(this.stateDir,{recursive:!0}),O(this.declarationEntryPath,this.generateDeclarationEntry()),this.writeTsconfig(),this.declarationEntryPath}ensureDeclarationEntry(){return(0,d.existsSync)(this.tsconfigPath)||this.writeTsconfig(),(0,d.existsSync)(this.declarationEntryPath)?this.declarationEntryPath:this.writeDeclarationEntry()}markGenerated(){return this.writeMetadata()}};function mr(e){let t=(0,ne.resolveOiyoConfig)(e),n=he();n.withScope(`CONFIG`);let r=new pr(t),i=new vt(t,{logger:n,oiyoState:r}),a=new nt(t,{logger:n,oiyoState:r}),o=new Ht(t,{oiyoAutoApi:a,logger:n}),s=new Tt(t,{logger:n,oiyoState:r});return{logger:n,config:t,autoApi:a,autoComponent:i,layout:s,state:r,route:new an(t,{logger:n,oiyoState:r,oiyoRoot:o,oiyoLayout:s}),root:o}}function hr(e){return[{name:`oiyo:deps`,enforce:`pre`,async config(t){let{config:n}=await(0,ie.loadConfig)({name:`oiyo`,cwd:t.root}),r=mr(n||e);return(0,ae.defu)(t,{oiyo:r,resolve:{alias:{"~":S.default.resolve(r.config.rootDir,r.config.srcDir),"@":S.default.resolve(r.config.rootDir,r.config.srcDir),"@@":S.default.normalize(r.config.rootDir),"~~":S.default.normalize(r.config.rootDir)}},optimizeDeps:{exclude:[`@skiyee/oiyo`]}})}}]}function gr(){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.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())},configureServer(t){e.route.watchPagesConfig(()=>{t.hot.send({type:`full-reload`})});let n=async n=>{let r=!1;e.layout.isLayoutPath(n)&&(await e.layout.registerLayouts(),e.layout.writeDeclaration(),r=!0),e.autoComponent.isAutoComponentPath(n)&&(await e.autoComponent.collectComponents(),e.autoComponent.writeDeclaration(),r=!0),e.autoApi.isAutoApiPath(n)&&(await e.autoApi.collectApis(),e.autoApi.writeDeclaration(),r=!0),r&&t.hot.send({type:`full-reload`})};t.watcher.on(`add`,e=>void n(e)),t.watcher.on(`unlink`,e=>void n(e)),t.watcher.on(`change`,e=>void n(e))},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 z},load(t){if(t===z)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(z);e&&(n.moduleGraph.invalidateModule(e),i=!0)}if(i){n.hot.send({type:`full-reload`});return}}},async closeBundle(){await e.route.unwatchPagesConfig()}}]}function _r(e={}){return[...hr(e),...gr(),...fr(),...gn()]}exports.LogLevels=C,exports.OiyoCorePlugin=_r,exports.OiyoLayout=wt,exports.OiyoModAutoApi=nt,exports.OiyoModAutoComponent=vt,exports.OiyoModLayout=Tt,exports.OiyoModRoot=Ht,exports.OiyoModRoute=an,exports.OiyoPage=rn,exports.OiyoState=pr,exports.RESOLVED_VIRTUAL_ROOT_CONTEXT_ID=z,exports.VIRTUAL_ROOT_CONTEXT_ID=zt,exports.createLogger=he,exports.definePageMeta=nn,exports.defineRootContext=Vt,exports.isScannedComponentPath=F,exports.resolveComponentName=ut,exports.resolveScannedComponentSources=st;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @oiyo/core v0.1.1
2
+ * @oiyo/core v0.1.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
@@ -81,6 +81,15 @@ interface IncludedApisSource {
81
81
  }
82
82
  //#endregion
83
83
  //#region src/state/index.d.ts
84
+ interface OiyoMetadata {
85
+ hash: string;
86
+ project: {
87
+ rootDir: string;
88
+ };
89
+ versions: {
90
+ oiyo: string;
91
+ };
92
+ }
84
93
  declare class OiyoState {
85
94
  private readonly config;
86
95
  constructor(config: OiyoConfig);
@@ -88,17 +97,23 @@ declare class OiyoState {
88
97
  get typesDir(): string;
89
98
  get srcDir(): string;
90
99
  get declarationEntryPath(): string;
91
- get appTsconfigPath(): string;
92
- get nodeTsconfigPath(): string;
100
+ get tsconfigPath(): string;
101
+ get metadataPath(): string;
102
+ get declarationPaths(): string[];
93
103
  private relativeToState;
94
104
  private stringifyJson;
105
+ private serializeMetadataInput;
106
+ generateMetadataHash(): string;
107
+ generateMetadata(): OiyoMetadata;
108
+ readMetadata(): OiyoMetadata | null;
109
+ writeMetadata(): OiyoMetadata;
110
+ canReuseGeneratedState(): boolean;
95
111
  generateDeclarationEntry(): string;
96
- generateAppTsconfig(): string;
97
- generateNodeTsconfig(): string;
98
- writeAppTsconfig(): string;
99
- writeNodeTsconfig(): string;
112
+ generateTsconfig(): string;
113
+ writeTsconfig(): string;
100
114
  writeDeclarationEntry(): string;
101
115
  ensureDeclarationEntry(): string;
116
+ markGenerated(): OiyoMetadata;
102
117
  }
103
118
  //#endregion
104
119
  //#region src/modules/auto-api/index.d.ts
@@ -542,4 +557,4 @@ declare module 'vite' {
542
557
  }
543
558
  declare function OiyoCorePlugin(options?: OiyoConfig): Plugin[];
544
559
  //#endregion
545
- export { type AutoApiItem, AutoComponentFile, type IncludedApi, type IncludedApisSource, LogErrorOptions, LogLevel, LogLevels, LogOptions, LogType, Logger, LoggerOptions, OiyoCorePlugin, OiyoLayout, OiyoModAutoApi, OiyoModAutoComponent, OiyoModLayout, OiyoModRoot, OiyoModRoute, OiyoPage, OiyoState, type PageMeta, RESOLVED_VIRTUAL_ROOT_CONTEXT_ID, RegisteredComponent, RegisteredComponentsSource, VIRTUAL_ROOT_CONTEXT_ID, createLogger, definePageMeta, defineRootContext, isScannedComponentPath, resolveComponentName, resolveScannedComponentSources };
560
+ export { type AutoApiItem, AutoComponentFile, type IncludedApi, type IncludedApisSource, LogErrorOptions, LogLevel, LogLevels, LogOptions, LogType, Logger, LoggerOptions, OiyoCorePlugin, OiyoLayout, OiyoMetadata, OiyoModAutoApi, OiyoModAutoComponent, OiyoModLayout, OiyoModRoot, OiyoModRoute, OiyoPage, OiyoState, type PageMeta, RESOLVED_VIRTUAL_ROOT_CONTEXT_ID, RegisteredComponent, RegisteredComponentsSource, VIRTUAL_ROOT_CONTEXT_ID, createLogger, definePageMeta, defineRootContext, isScannedComponentPath, resolveComponentName, resolveScannedComponentSources };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @oiyo/core v0.1.1
2
+ * @oiyo/core v0.1.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
@@ -81,6 +81,15 @@ interface IncludedApisSource {
81
81
  }
82
82
  //#endregion
83
83
  //#region src/state/index.d.ts
84
+ interface OiyoMetadata {
85
+ hash: string;
86
+ project: {
87
+ rootDir: string;
88
+ };
89
+ versions: {
90
+ oiyo: string;
91
+ };
92
+ }
84
93
  declare class OiyoState {
85
94
  private readonly config;
86
95
  constructor(config: OiyoConfig);
@@ -88,17 +97,23 @@ declare class OiyoState {
88
97
  get typesDir(): string;
89
98
  get srcDir(): string;
90
99
  get declarationEntryPath(): string;
91
- get appTsconfigPath(): string;
92
- get nodeTsconfigPath(): string;
100
+ get tsconfigPath(): string;
101
+ get metadataPath(): string;
102
+ get declarationPaths(): string[];
93
103
  private relativeToState;
94
104
  private stringifyJson;
105
+ private serializeMetadataInput;
106
+ generateMetadataHash(): string;
107
+ generateMetadata(): OiyoMetadata;
108
+ readMetadata(): OiyoMetadata | null;
109
+ writeMetadata(): OiyoMetadata;
110
+ canReuseGeneratedState(): boolean;
95
111
  generateDeclarationEntry(): string;
96
- generateAppTsconfig(): string;
97
- generateNodeTsconfig(): string;
98
- writeAppTsconfig(): string;
99
- writeNodeTsconfig(): string;
112
+ generateTsconfig(): string;
113
+ writeTsconfig(): string;
100
114
  writeDeclarationEntry(): string;
101
115
  ensureDeclarationEntry(): string;
116
+ markGenerated(): OiyoMetadata;
102
117
  }
103
118
  //#endregion
104
119
  //#region src/modules/auto-api/index.d.ts
@@ -542,4 +557,4 @@ declare module 'vite' {
542
557
  }
543
558
  declare function OiyoCorePlugin(options?: OiyoConfig): Plugin[];
544
559
  //#endregion
545
- export { type AutoApiItem, AutoComponentFile, type IncludedApi, type IncludedApisSource, LogErrorOptions, LogLevel, LogLevels, LogOptions, LogType, Logger, LoggerOptions, OiyoCorePlugin, OiyoLayout, OiyoModAutoApi, OiyoModAutoComponent, OiyoModLayout, OiyoModRoot, OiyoModRoute, OiyoPage, OiyoState, type PageMeta, RESOLVED_VIRTUAL_ROOT_CONTEXT_ID, RegisteredComponent, RegisteredComponentsSource, VIRTUAL_ROOT_CONTEXT_ID, createLogger, definePageMeta, defineRootContext, isScannedComponentPath, resolveComponentName, resolveScannedComponentSources };
560
+ export { type AutoApiItem, AutoComponentFile, type IncludedApi, type IncludedApisSource, LogErrorOptions, LogLevel, LogLevels, LogOptions, LogType, Logger, LoggerOptions, OiyoCorePlugin, OiyoLayout, OiyoMetadata, OiyoModAutoApi, OiyoModAutoComponent, OiyoModLayout, OiyoModRoot, OiyoModRoute, OiyoPage, OiyoState, type PageMeta, RESOLVED_VIRTUAL_ROOT_CONTEXT_ID, RegisteredComponent, RegisteredComponentsSource, VIRTUAL_ROOT_CONTEXT_ID, createLogger, definePageMeta, defineRootContext, isScannedComponentPath, resolveComponentName, resolveScannedComponentSources };
package/dist/index.mjs CHANGED
@@ -1,25 +1,25 @@
1
1
  /**
2
- * @oiyo/core v0.1.1
2
+ * @oiyo/core v0.1.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 u,mkdirSync as d,renameSync as ee,statSync as f,unlinkSync as te,writeFileSync as ne}from"node:fs";import{lstat as p,readFile as m,readdir as re,realpath as ie,stat as h}from"node:fs/promises";import{basename as g,dirname as _,join as v,matchesGlob as y,normalize as b,parse as x,relative as S,resolve as C,sep as ae}from"pathe";import{createHash as oe}from"node:crypto";import{parse as w}from"@babel/parser";import se from"@babel/traverse";import{glob as ce}from"tinyglobby";import{parse as T}from"@vue/compiler-sfc";import{DEFAULT_EXCLUDE as le,resolveOiyoConfig as ue}from"@oiyo/config";import{defineComponent as de}from"vue";import E from"magic-string";import{loadConfig as fe,watchConfig as pe}from"c12";import{defu as me}from"defu";import{stat as he,unwatchFile as ge,watch as _e,watchFile as ve}from"fs";import{lstat as ye,open as be,readdir as xe,realpath as Se,stat as Ce}from"fs/promises";import{EventEmitter as we}from"events";import*as D from"path";import{Readable as Te}from"node:stream";import O,{join as Ee,relative as De,resolve as Oe,sep as ke}from"node:path";import{type as Ae}from"os";const k={silent:0,error:1,warn:2,info:3,debug:4,verbose:5};let je,Me,Ne=0,Pe;function Fe(){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 Ie(){return Pe??=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`numeric`,second:`numeric`}),Pe}function Le(e=`info`,n={}){if(n.customLogger)return n.customLogger;let r=new WeakSet,u=new Set,{prefix:d=`[OIYO]`,scope:ee,allowClearScreen:f=!0,console:te=globalThis.console}=n,ne=k[e],p=f&&t.stdout.isTTY&&!t.env.CI,m=p?Fe:()=>{};function re(e,t,n={}){let r=ie(e,n.scope??ee);return n.timestamp?`${s(Ie().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),p){if(e===je&&t===Me){Ne++,m(),te[e](re(e,t,n),l(`(x${Ne+1})`));return}Ne=0,je=e,Me=t,n.clear&&m()}te[i](re(e,t,n))}let g={hasWarned:!1,withScope(t){return Le(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]&&m()},hasErrorLogged(e){return r.has(e)}};return g}const A=typeof se==`function`?se:se.default,Re=e(import.meta.url),ze=`**/*`;function j(e){return e?Array.isArray(e)?e:[e]:[]}function Be(e){if(!u(e))return[ze];try{return f(e).isFile()?[g(e)]:[ze]}catch{return[ze]}}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:Be(t);try{return(await ce(o,{cwd:i,absolute:!0,ignore:j(r)})).map(e=>b(C(e)))}catch(e){return console.error(`[oiyo] Error scanning file:`,e),[]}}function Ve(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 oe(`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 ne(r,t,`utf-8`),u(e)&&te(e),ee(r,e),!0}function He(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 Ue(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function We(e,t){if(!F(t))return{path:b(C(e,t))};try{let n=Ue(t),r=_(b(Re.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 Ge(e,t,n){if(!n)return e;let r=b(S(t,e));return!r||r===`.`?n:`${n}/${r}`}function Ke(e,t,n){return F(t)?n?.stripExtension?t.replace(/\.[cm]?[jt]sx?$/,``):t:He(e,t,n)}function qe(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 Je(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 Ye(e){return e.replace(/\s+/g,``)}const Xe=e(import.meta.url),Ze=[`.ts`,`.mts`,`.cts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.jsx`,`.vue`,`.d.ts`,`.d.mts`,`.d.cts`];function Qe(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function $e(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 et(e,t,n){let r=b(C(x(e).dir,t)),i=n?.preferTypes?[`.d.ts`,`.d.mts`,`.d.cts`,...Ze]:Ze;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 tt(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 nt(e,t,n){try{let r=Qe(t),i=$e(e,r)||b(Xe.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?tt(l,`types`)||(c===`.`?o.types:void 0):tt(l,`import`)||(c===`.`?o.module||o.main:void 0);return b(u?C(a,u):Xe.resolve(t,{paths:[e]}))}catch{return}}async function rt(e,t,n){return F(t)?await nt(_(e),t,n)||t:et(e,t,n)}function it(e,t){return t.startsWith(`.`)||t.startsWith(`/`)?et(e,t,{preferTypes:!0}):t}function at(e,t,n){return F(t)?n||($e(e,Qe(t))?t.replace(/\\/g,`/`):void 0):n}async function ot(e,t){if(!e.importBase||!F(e.importBase))return{typePath:e.path,valuePath:e.path};let n=await nt(t,e.importBase),r=await nt(t,e.importBase,{preferTypes:!0});return{typePath:r||n||e.path,valuePath:n||r||e.path}}function st(e,t){return!t||!e.importPath||!F(t)?e:e.importPath.startsWith(`${t}/..`)||e.importPath.startsWith(`${t}/.`)?{...e,importPath:t}:e}function ct(e){let t=I(e);return t?t[0].toLowerCase()+t.slice(1):``}function lt(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 ut(e){let t=x(e);return ct(t.name===`index`?x(t.dir).name:t.name)}function dt(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
- `)}catch{return t}}async function ft(e,t,n=e,r){let i=lt(dt(e,t)),a=[],o=[],s=[],c=!1;if(r?.visitedFiles?.add(e),A(i,{ExportDefaultDeclaration(){c=!0},ExportAllDeclaration(e){let t=e.node.source?.value;t&&s.push({exportKind:e.node.exportKind,source:t})},ExportNamedDeclaration(t){let{node:i}=t,s=i.exportKind;if(i.declaration)switch(i.declaration.type){case`FunctionDeclaration`:case`TSDeclareFunction`:case`ClassDeclaration`:case`TSEnumDeclaration`:s!==`type`&&i.declaration.id?.name&&a.push({exportName:i.declaration.id.name,filePath:e,importPath:n,name:i.declaration.id.name});break;case`VariableDeclaration`:if(s===`type`)break;for(let t of i.declaration.declarations)for(let r of L(t.id))a.push({exportName:r,filePath:e,importPath:n,name:r});break;case`TSInterfaceDeclaration`:case`TSTypeAliasDeclaration`:r?.includeTypes&&i.declaration.id?.name&&o.push({exportName:i.declaration.id.name,filePath:e,importPath:n,name:i.declaration.id.name});break}for(let t of i.specifiers){if(t.type!==`ExportSpecifier`){if(s===`type`&&!r?.includeTypes||t.exported.type!==`Identifier`)continue;a.push({exportName:t.exported.name,filePath:e,importPath:n,name:t.exported.name});continue}if(s===`type`||t.exportKind===`type`){if(!r?.includeTypes||t.exported.type!==`Identifier`)continue;let a=t.exported.name,s=e,c=n;i.source?.value&&t.local.type===`Identifier`&&(a=t.local.name,c=it(e,i.source.value),s=F(c)?e:c),o.push({exportName:a,filePath:s,importPath:c,name:t.exported.name});continue}t.exported.type===`Identifier`&&a.push({exportName:t.exported.name,filePath:e,importPath:n,name:t.exported.name})}}}),c){let t=ut(e);t&&a.push({exportName:`default`,filePath:e,importPath:n,name:t})}for(let t of s){let i=await rt(e,t.source,{preferTypes:r?.includeTypes});if(!(!i||F(i)||r?.visitedFiles?.has(i)))try{let e=await ft(i,await m(i,`utf-8`),n,{includeTypes:r?.includeTypes,visitedFiles:r?.visitedFiles});t.exportKind!==`type`&&a.push(...e.valueItems.map(e=>({...e,importPath:n}))),r?.includeTypes&&o.push(...e.typeItems.map(e=>({...e,importPath:n})))}catch{continue}}return{typeItems:o,valueItems:a}}function pt(e){let t=lt(e),n=new Set;return A(t,{Program(e){Object.keys(e.scope.bindings).forEach(e=>n.add(e)),e.stop()}}),n}function mt(e,t,n){let r=lt(e),i=new Set(t),a=new Set(n?.boundNames||[]),o=new Set;return A(r,{ReferencedIdentifier(e){let t=e.node.name;a.has(t)||e.scope.hasBinding(t)||i.has(t)&&o.add(t)}}),o}function ht(e){let t=e.importPath||e.filePath;return e.exportName===`default`?`import ${e.name} from '${t}'`:e.exportName===e.name?`import { ${e.name} } from '${t}'`:`import { ${e.exportName} as ${e.name} } from '${t}'`}function gt(e,t){let n=Ke(t,e.importPath||e.filePath,{stripExtension:!0});return` const ${e.name}: typeof import('${n}')['${e.exportName}'];`}const _t=[`**/*.ts`,`**/*.mts`,`**/*.cts`,`**/*.js`,`**/*.mjs`,`**/*.cjs`,`**/*.tsx`,`**/*.jsx`];function vt(e){return typeof e==`string`?{isType:void 0,localName:e,sourceName:e}:{isType:e.isType,localName:e.as||e.name,sourceName:e.name}}function yt(e){return typeof e!=`string`&&e.only!==void 0}function bt(e,t){let n=C(e.rootDir,e.srcDir),r=typeof t==`string`?t:t.from,i=We(n,r);return{exclude:typeof t==`string`?void 0:t.exclude,ignore:typeof t==`string`?void 0:t.ignore,importBase:at(n,r,i.importBase),path:i.path,pattern:typeof t==`string`?void 0:t.pattern,types:typeof t==`string`?!1:t.types}}function xt(e){return(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?{exclude:[],ignore:[],importBase:void 0,pattern:_t,path:b(C(e)),types:!1}:{exclude:e.exclude||[],ignore:e.ignore,importBase:e.importBase,pattern:e.pattern||_t,path:b(C(e.path)),types:e.types||!1})}function St(e){return JSON.stringify({exclude:[...e.exclude||[]].sort(),ignore:j(e.ignore),importBase:e.importBase,path:e.path,pattern:j(e.pattern),types:e.types||!1})}function Ct(e){return{exportName:e.export||e.name,filePath:e.from,importPath:e.from,name:e.name}}function wt(e,t){return{importPath:Ke(t,e.importPath||e.filePath,{stripExtension:!0}),specifier:e.exportName===e.name?e.name:`${e.exportName} as ${e.name}`}}function Tt(e){return`${e.filePath}#${e.exportName}`}var Et=class{constructor(e,t){this._config=e,this.autoApis=[],this.autoApiTypes=[],this.autoApiMap=new Map,this.autoApiTypeMap=new Map,this.includedApis=[],this.includedApiTypes=[],this.apiSources=[],this.oiyoState=t.oiyoState,this.logger=t.logger.withScope(`AUTO_API`),this.registerConfigScanners()}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`apis.d.ts`)}isAutoApiPath(e){let t=b(e);return this.apiSources.some(e=>Ve(t,e.path,{ignore:e.ignore,pattern:e.pattern}))}includeApi(e){let t=Array.isArray(e)?e:[e];this.includedApis.push(...t.map(Ct))}includeApiType(e){let t=Array.isArray(e)?e:[e];this.includedApiTypes.push(...t.map(Ct))}includeApis(e){for(let t of xt(e)){let e=St(t);this.apiSources.some(t=>St(t)===e)||this.apiSources.push(t)}}registerConfigScanners(){for(let e of this._config.scan?.apis||[]){if(!yt(e)){this.includeApis(bt(this._config,e));continue}for(let t of e.only){let{isType:n,localName:r,sourceName:i}=vt(t),a={export:i===r?void 0:i,from:e.from,name:r};n??e.types?this.includeApiType(a):this.includeApi(a)}}}resetCollectedState(){this.autoApis=[],this.autoApiTypes=[],this.autoApiMap.clear(),this.autoApiTypeMap.clear()}registerValue(e,t){let n=this.autoApiMap.get(e.name);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||n.filePath===e.filePath&&n.exportName!==`default`&&e.exportName===`default`||this.logger.warn(`自动 API 名称冲突: ${e.name} 已存在,已跳过 ${Tt(e)}`),!1):(this.autoApiMap.set(e.name,e),t?.trackScanned&&this.autoApis.push(e),!0)}registerType(e,t){let n=this.autoApiTypeMap.get(e.name);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||this.logger.warn(`自动 API 类型名称冲突: ${e.name} 已存在,已跳过 ${Tt(e)}`),!1):(this.autoApiTypeMap.set(e.name,e),t?.trackScanned&&this.autoApiTypes.push(e),!0)}seedIncludedRegistrations(){this.includedApis.forEach(e=>this.registerValue(e)),this.includedApiTypes.forEach(e=>this.registerType(e))}registerScannedValueItems(e,t){for(let n of t){let t=st(n,e.importBase);(e.exclude||[]).includes(t.name)||this.registerValue(t,{trackScanned:!0})}}registerScannedTypeItems(e,t){for(let n of t){let t=st(n,e.importBase);(e.exclude||[]).includes(t.name)||this.registerType(t,{trackScanned:!0})}}async scanSourceFiles(e,t,n,r){for(let i of t)try{let t=await ft(i,await m(i,`utf-8`),Ge(i,n,e.importBase),{includeTypes:r.includeTypes,visitedFiles:new Set});r.registerValues&&this.registerScannedValueItems(e,t.valueItems),r.registerTypes&&this.registerScannedTypeItems(e,t.typeItems)}catch{this.logger.warn(`解析自动 API 文件失败,已跳过: ${i}`)}}async collectApis(){let e=C(this._config.rootDir,this._config.srcDir);this.resetCollectedState(),this.seedIncludedRegistrations();for(let t of this.apiSources){let{typePath:n,valuePath:r}=await ot(t,e),i=await M({dir:r,ignore:t.ignore,pattern:t.pattern});if(t.types&&r===n){await this.scanSourceFiles(t,i,r,{includeTypes:!0,registerTypes:!0,registerValues:!0});continue}if(await this.scanSourceFiles(t,i,r,{includeTypes:!1,registerValues:!0}),!t.types)continue;let a=r===n?i:await M({dir:n,ignore:t.ignore,pattern:t.pattern});await this.scanSourceFiles(t,a,n,{includeTypes:!0,registerTypes:!0})}return this.autoApis}collectBoundNames(e){return pt(e)}resolveImports(e,t){return!e||this.autoApiMap.size===0?[]:Array.from(mt(e,this.autoApiMap.keys(),t)).sort().map(e=>ht(this.autoApiMap.get(e)))}resolveImport(e){let t=this.autoApiMap.get(e);if(t)return ht(t)}generateDeclaration(){let e=Array.from(this.autoApiTypeMap.values()).sort((e,t)=>e.name.localeCompare(t.name)).reduce((e,t)=>{let n=wt(t,this.typesDir),r=e.get(n.importPath)||[];return r.push(n.specifier),e.set(n.importPath,r),e},new Map);return[`// Generated by oiyo`,`declare global {`,...Array.from(this.autoApiMap.values()).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>gt(e,this.typesDir)),`}`,``,`declare global {`,...Array.from(e.entries()).flatMap(([e,t])=>[` // @ts-ignore`,` export type { ${t.join(`, `)} } from '${e}';`]),`}`,``,`export {}`,``].join(`
10
- `)}writeDeclaration(){return d(this.typesDir,{recursive:!0}),P(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}};const Dt=/<\/?\s*([a-z][\w-]*)\b/gi,Ot=[`**/*.vue`,`**/*.nvue`];function kt(e){return typeof e==`string`?{localName:e,sourceName:e}:{localName:e.as||e.name,sourceName:e.name}}function At(e){return typeof e!=`string`&&e.only!==void 0}function jt(e,t){let n=We(C(e.rootDir,e.srcDir),typeof t==`string`?t:t.from);return{chain:typeof t==`string`?!0:t.chain,ignore:typeof t==`string`?void 0:t.ignore,importBase:n.importBase,path:n.path,pattern:typeof t==`string`?void 0:t.pattern,prefix:typeof t==`string`?void 0:t.prefix}}function Mt(e){return(e.scan?.components||[]).filter(e=>!At(e)).map(t=>jt(e,t))}function Nt(e,t){let n=b(t);return Mt(e).some(e=>Ve(n,e.path,{ignore:e.ignore,pattern:e.pattern}))}function Pt(e){return e?I(e):``}function Ft(e){if(e.length<2)return e;let t=e.slice();return t[t.length-1]===t[t.length-2]&&t.pop(),t}function It(e,t,n){let{dir:r,name:i}=x(S(t,e)),a=r&&r!==`.`?r.split(ae).filter(Boolean):[];(i!==`index`||a.length===0)&&a.push(i);let o=Ft(a),s=n?.chain===!1?o.slice(-1):o;return`${Pt(n?.prefix)}${s.map(e=>I(e)).join(``)}`}function Lt(e){let t=new Set;Dt.lastIndex=0;let n=Dt.exec(e);for(;n;)t.add(n[1]),n=Dt.exec(e);return t}function Rt(e){return e.includes(`-`)?I(e):e}function zt(e){return{componentName:e.name,exportName:e.export||`default`,filePath:e.from,importPath:e.from}}function Bt(e){return(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?{chain:!0,ignore:[],importBase:void 0,pattern:Ot,path:b(C(e)),prefix:void 0}:{chain:e.chain??!0,ignore:e.ignore,importBase:e.importBase,pattern:e.pattern||Ot,path:b(C(e.path)),prefix:e.prefix})}function Vt(e){return JSON.stringify({chain:e.chain,ignore:j(e.ignore),importBase:e.importBase,path:e.path,pattern:j(e.pattern),prefix:e.prefix})}function Ht(e){let t=e.importPath||e.filePath;return e.exportName===`default`?`import ${e.componentName} from '${t}'`:e.exportName===e.componentName?`import { ${e.componentName} } from '${t}'`:`import { ${e.exportName} as ${e.componentName} } from '${t}'`}function Ut(e,t){let n=Ke(t,e.importPath||e.filePath);return` ${e.componentName}: typeof import('${n}')['${e.exportName}'];`}var Wt=class{constructor(e,t){this._config=e,this.autoComponents=[],this.registeredComponents=[],this.componentSources=[],this.autoComponentMap=new Map,this.oiyoState=t.oiyoState,this.logger=t.logger.withScope(`AUTO_COMPONENT`),this.registerConfigScanners()}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`components.d.ts`)}isAutoComponentPath(e){let t=b(e);return this.componentSources.some(e=>Ve(t,e.path,{ignore:e.ignore,pattern:e.pattern}))}registerComponent(e){this.registeredComponents.push(zt(e))}registerComponents(e){for(let t of Bt(e)){let e=Vt(t);this.componentSources.some(t=>Vt(t)===e)||this.componentSources.push(t)}}registerConfigScanners(){for(let e of this._config.scan?.components||[]){if(!At(e)){this.registerComponents(jt(this._config,e));continue}for(let t of e.only){let{localName:n,sourceName:r}=kt(t);this.registerComponent({export:r,from:e.from,name:e.prefix?`${I(e.prefix)}${n}`:n})}}}setResolvedComponent(e,t){let n=this.autoComponentMap.get(e.componentName);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||this.logger.warn(`组件名称冲突: ${e.componentName} 已存在,已跳过 ${e.filePath}`),!1):(this.autoComponentMap.set(e.componentName,e),t?.trackScanned&&this.autoComponents.push(e),!0)}async collectComponents(){this.autoComponents=[],this.autoComponentMap.clear(),this.registeredComponents.forEach(e=>this.setResolvedComponent(e));for(let e of this.componentSources)(await M({dir:e.path,ignore:e.ignore,pattern:e.pattern})).forEach(t=>{let n=e.path===t?_(t):e.path;this.setResolvedComponent({componentName:It(t,n,{chain:e.chain,prefix:e.prefix}),exportName:`default`,filePath:t,importPath:Ge(t,e.path,e.importBase)},{trackScanned:!0})});return this.autoComponents}resolveComponentImports(e,t){if(!e||this.autoComponentMap.size===0)return[];let n=[],r=new Set,i=t?b(t):void 0;for(let t of Lt(e)){let e=Rt(t),a=this.autoComponentMap.get(e);a&&(i&&a.filePath===i||r.has(e)||(r.add(e),n.push(Ht(a))))}return n}resolveComponentImport(e,t){let n=this.autoComponentMap.get(e);if(!n)return;let r=t?b(t):void 0;if(!(r&&n.filePath===r))return Ht(n)}generateDeclaration(){return[`// Generated by oiyo`,`declare module 'vue' {`,` export interface GlobalComponents {`,...Array.from(this.autoComponentMap.values()).sort((e,t)=>e.componentName.localeCompare(t.componentName)).map(e=>Ut(e,this.typesDir)),` }`,`}`,``,`export {}`,``].join(`
11
- `)}writeDeclaration(){return d(this.typesDir,{recursive:!0}),P(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}};function Gt(e){return e.includes(`<OiyoLayout`)||e.includes(`<oiyo-layout`)}function Kt(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 qt(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 Jt(e,t){let{dir:n,name:r}=x(S(t,e));return(n&&n!==`.`?[...n.split(ae),r]:[r]).map(e=>qe(e)).join(`-`)}function Yt(e){return`OiyoLayout${e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}`}const Xt=de({name:`OiyoLayout`,setup(e,t){return()=>t.slots.default?.()}});var Zt=class{constructor(e,t){this.config=e,this.layoutFiles=[],this.logger=t.logger.withScope(`LAYOUT`),this.oiyoState=t.oiyoState}get srcDir(){return C(this.config.rootDir,this.config.srcDir)}get layoutDir(){return C(this.srcDir,this.config.dir?.layouts||`layouts`)}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`layouts.d.ts`)}isLayoutPath(e){let t=b(e);return!t.endsWith(`.vue`)&&!t.endsWith(`.nvue`)||[...le,...this.config.exclude||[]].some(e=>y(t,e))||Nt(this.config,t)?!1:t.startsWith(`${this.layoutDir}/`)}setLayout(e){if(this.layoutFiles.findIndex(({filePath:t})=>t===e)!==-1)return!1;let t=Jt(e,this.layoutDir),n=Yt(t);return this.layoutFiles.push({useName:t,componentName:n,filePath:e}),!0}async registerLayouts(){let e=await M({dir:this.layoutDir,pattern:[`**/*.vue`,`**/*.nvue`]});return this.layoutFiles=[],e.filter(e=>this.isLayoutPath(e)).map(e=>this.setLayout(e)),this.layoutFiles}generateDeclaration(){return[`// Generated by oiyo`,``,`declare module '@skiyee/oiyo/api' {`,` interface OiyoLayouts {`,...this.layoutFiles.slice().sort((e,t)=>e.useName.localeCompare(t.useName)).map(({useName:e,filePath:t})=>` '${e}': typeof import('${He(this.typesDir,t)}')['default'];`),` }`,``,` type LayoutKey = keyof OiyoLayouts extends never ? string : keyof OiyoLayouts;`,``,` interface PageMeta {`,` layout?: LayoutKey | false;`,` }`,`}`,``,`export {}`,``].join(`
12
- `)}writeDeclaration(){return d(this.typesDir,{recursive:!0}),P(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}applyLayout(e,t){if(!Gt(t))return{template:t,script:``,imports:[]};if(e===!1)return{template:Kt(t),script:``,imports:[]};e===void 0&&(e=`default`);let n=this.layoutFiles.find(t=>t.useName===e);return n?{template:qt(t,n.componentName),script:``,imports:[`import ${n.componentName} from '${n.filePath}'`]}:(this.logger.error(`未找到布局 "${e}",请检查布局名称或文件位置是否正确`),{template:t,script:``,imports:[]})}};function Qt(e){if(!e||!e.includes(`import`))return[];let t=w(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 $t(e){if(!e||!e.includes(`import`))return new Set;let t=w(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 R(e){if(!e||!e.includes(`import`))return e;let t=w(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 z(e,t){let n=en(t),r=en(e);for(let[e,t]of r){let r=n.get(e);r?tn(r,t):n.set(e,t)}return nn(n)}function en(e){let t=new Map;for(let n of e)A(w(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 tn(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 nn(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}function rn(e){if(!e.includes(`defineRootContext`))return``;let{descriptor:t}=T(e);if(!t.scriptSetup)return``;let n=e=t.scriptSetup.content,r=an(n);return n.substring(r.start,r.end+1).trim()}function an(e){return Je(e,`defineRootContext`)}function on(e){if(!e.includes(`<template`))return``;let{descriptor:t}=T(e);return(t.template?.content||``).trim()}function sn(e,t){let n=e.replace(/\{\{([\s\S]*?)\}\}/g,(e,n)=>e.replace(n,cn(n,t)));return n=n.replace(/((?:v-(?!for\b)[\w-]+(?::[\w-]+)?|[:@][\w-]+)\s*=\s*)(["'])([\s\S]*?)\2/g,(e,n,r,i)=>`${n}${r}${cn(i,t)}${r}`),n}function cn(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=w(`(${e})`,{sourceType:`module`,plugins:[`typescript`]}),r=new E(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 ln(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=sn(n,t),n.trim()}function un(e){if(!e)return;let t=e?.content;if(t){let e=dn(t);return e.script?e:void 0}}function dn(e){let t=w(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 fn(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 pn=`virtual:oiyo-root-context`,B=`\0${pn}`;function mn(e){let{script:t,imports:n}=e,r=[];return n?.length&&(r.push(...n),r.push(``)),t?(r.push(`let rootContextInstance = null`),r.push(``),r.push(`export function useRootContext() {`),r.push(`if (!rootContextInstance) {`),r.push(`const factory = ${t}`),r.push(`rootContextInstance = factory()`),r.push(`}`),r.push(`return rootContextInstance`),r.push(`}`)):(r.push(`export function useRootContext() {`),r.push(`return {}`),r.push(`}`)),r.join(`
13
- `)}const hn=e=>e();var gn=class{constructor(e,t){this.config=e,this.rootView={imports:[],template:`<OiyoPage />`,script:``},this.shouldRefreshVM=e=>{let t=``;this.rootMarco&&(t=N(Ye(`defineRootContext(${this.rootMarco.script})`)));let n=N(Ye(rn(e)));return t!==n},this.logger=t.logger.withScope(`ROOT`),this.oiyoAutoApi=t.oiyoAutoApi}get srcDir(){return C(this.config.rootDir,this.config.srcDir)}get rootPath(){return C(this.srcDir,`App.vue`)}isRootPath(e){return e===this.rootPath}parseRoot(e){let{descriptor:t}=T(e),n=un(t.scriptSetup);if(n?.script&&t.scriptSetup?.content&&this.oiyoAutoApi){let e=this.oiyoAutoApi.collectBoundNames(t.scriptSetup.content),r=this.oiyoAutoApi.resolveImports(n.script,{boundNames:e});r.length>0&&(n.imports=z(r,n.imports||[]))}return this.rootView={template:ln(t.template,{varName:n?.variable,varProperties:n?.properties}),imports:[],script:``},n&&(this.rootMarco=n,this.rootVM=mn(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 E(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=an(e);if(r.start!==r.end){e.includes(`virtual:oiyo-root-context`)||n.appendLeft(t.scriptSetup.loc.start.offset,`
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 u,mkdirSync as d,readFileSync as ee,renameSync as te,statSync as f,unlinkSync as ne,writeFileSync as re}from"node:fs";import{lstat as p,readFile as m,readdir as ie,realpath as h,stat as g}from"node:fs/promises";import{basename as ae,dirname as _,join as v,matchesGlob as y,normalize as b,parse as x,relative as S,resolve as C,sep as oe}from"pathe";import{createHash as se}from"node:crypto";import{parse as w}from"@babel/parser";import ce from"@babel/traverse";import{glob as le}from"tinyglobby";import{parse as T}from"@vue/compiler-sfc";import{DEFAULT_EXCLUDE as ue,resolveOiyoConfig as de}from"@oiyo/config";import{defineComponent as fe}from"vue";import E from"magic-string";import{loadConfig as pe,watchConfig as me}from"c12";import{defu as he}from"defu";import{stat as ge,unwatchFile as _e,watch as ve,watchFile as ye}from"fs";import{lstat as be,open as xe,readdir as Se,realpath as Ce,stat as we}from"fs/promises";import{EventEmitter as Te}from"events";import*as D from"path";import{Readable as Ee}from"node:stream";import O,{join as De,relative as Oe,resolve as ke,sep as Ae}from"node:path";import{type as je}from"os";const k={silent:0,error:1,warn:2,info:3,debug:4,verbose:5};let Me,Ne,Pe=0,Fe;function Ie(){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 Le(){return Fe??=new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`numeric`,second:`numeric`}),Fe}function Re(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?Ie:()=>{};function m(e,t,n={}){let r=ie(e,n.scope??ee);return n.timestamp?`${s(Le().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===Me&&t===Ne){Pe++,p(),f[e](m(e,t,n),l(`(x${Pe+1})`));return}Pe=0,Me=e,Ne=t,n.clear&&p()}f[i](m(e,t,n))}let g={hasWarned:!1,withScope(t){return Re(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,ze=e(import.meta.url),Be=`**/*`;function j(e){return e?Array.isArray(e)?e:[e]:[]}function Ve(e){if(!u(e))return[Be];try{return f(e).isFile()?[ae(e)]:[Be]}catch{return[Be]}}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:Ve(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 He(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 Ue(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 We(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function Ge(e,t){if(!F(t))return{path:b(C(e,t))};try{let n=We(t),r=_(b(ze.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 Ke(e,t,n){if(!n)return e;let r=b(S(t,e));return!r||r===`.`?n:`${n}/${r}`}function qe(e,t,n){return F(t)?n?.stripExtension?t.replace(/\.[cm]?[jt]sx?$/,``):t:Ue(e,t,n)}function Je(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 Ye(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 Xe(e){return e.replace(/\s+/g,``)}const Ze=e(import.meta.url),Qe=[`.ts`,`.mts`,`.cts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.jsx`,`.vue`,`.d.ts`,`.d.mts`,`.d.cts`];function $e(e){let t=e.split(`/`).filter(Boolean);return e.startsWith(`@`)?t.slice(0,2).join(`/`):t[0]||e}function et(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 tt(e,t,n){let r=b(C(x(e).dir,t)),i=n?.preferTypes?[`.d.ts`,`.d.mts`,`.d.cts`,...Qe]:Qe;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 nt(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 rt(e,t,n){try{let r=$e(t),i=et(e,r)||b(Ze.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?nt(l,`types`)||(c===`.`?o.types:void 0):nt(l,`import`)||(c===`.`?o.module||o.main:void 0);return b(u?C(a,u):Ze.resolve(t,{paths:[e]}))}catch{return}}async function it(e,t,n){return F(t)?await rt(_(e),t,n)||t:tt(e,t,n)}function at(e,t){return t.startsWith(`.`)||t.startsWith(`/`)?tt(e,t,{preferTypes:!0}):t}function ot(e,t,n){return F(t)?n||(et(e,$e(t))?t.replace(/\\/g,`/`):void 0):n}async function st(e,t){if(!e.importBase||!F(e.importBase))return{typePath:e.path,valuePath:e.path};let n=await rt(t,e.importBase),r=await rt(t,e.importBase,{preferTypes:!0});return{typePath:r||n||e.path,valuePath:n||r||e.path}}function ct(e,t){return!t||!e.importPath||!F(t)?e:e.importPath.startsWith(`${t}/..`)||e.importPath.startsWith(`${t}/.`)?{...e,importPath:t}:e}function lt(e){let t=I(e);return t?t[0].toLowerCase()+t.slice(1):``}function ut(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 dt(e){let t=x(e);return lt(t.name===`index`?x(t.dir).name:t.name)}function ft(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
+ `)}catch{return t}}async function pt(e,t,n=e,r){let i=ut(ft(e,t)),a=[],o=[],s=[],c=!1;if(r?.visitedFiles?.add(e),A(i,{ExportDefaultDeclaration(){c=!0},ExportAllDeclaration(e){let t=e.node.source?.value;t&&s.push({exportKind:e.node.exportKind,source:t})},ExportNamedDeclaration(t){let{node:i}=t,s=i.exportKind;if(i.declaration)switch(i.declaration.type){case`FunctionDeclaration`:case`TSDeclareFunction`:case`ClassDeclaration`:case`TSEnumDeclaration`:s!==`type`&&i.declaration.id?.name&&a.push({exportName:i.declaration.id.name,filePath:e,importPath:n,name:i.declaration.id.name});break;case`VariableDeclaration`:if(s===`type`)break;for(let t of i.declaration.declarations)for(let r of L(t.id))a.push({exportName:r,filePath:e,importPath:n,name:r});break;case`TSInterfaceDeclaration`:case`TSTypeAliasDeclaration`:r?.includeTypes&&i.declaration.id?.name&&o.push({exportName:i.declaration.id.name,filePath:e,importPath:n,name:i.declaration.id.name});break}for(let t of i.specifiers){if(t.type!==`ExportSpecifier`){if(s===`type`&&!r?.includeTypes||t.exported.type!==`Identifier`)continue;a.push({exportName:t.exported.name,filePath:e,importPath:n,name:t.exported.name});continue}if(s===`type`||t.exportKind===`type`){if(!r?.includeTypes||t.exported.type!==`Identifier`)continue;let a=t.exported.name,s=e,c=n;i.source?.value&&t.local.type===`Identifier`&&(a=t.local.name,c=at(e,i.source.value),s=F(c)?e:c),o.push({exportName:a,filePath:s,importPath:c,name:t.exported.name});continue}t.exported.type===`Identifier`&&a.push({exportName:t.exported.name,filePath:e,importPath:n,name:t.exported.name})}}}),c){let t=dt(e);t&&a.push({exportName:`default`,filePath:e,importPath:n,name:t})}for(let t of s){let i=await it(e,t.source,{preferTypes:r?.includeTypes});if(!(!i||F(i)||r?.visitedFiles?.has(i)))try{let e=await pt(i,await m(i,`utf-8`),n,{includeTypes:r?.includeTypes,visitedFiles:r?.visitedFiles});t.exportKind!==`type`&&a.push(...e.valueItems.map(e=>({...e,importPath:n}))),r?.includeTypes&&o.push(...e.typeItems.map(e=>({...e,importPath:n})))}catch{continue}}return{typeItems:o,valueItems:a}}function mt(e){let t=ut(e),n=new Set;return A(t,{Program(e){Object.keys(e.scope.bindings).forEach(e=>n.add(e)),e.stop()}}),n}function ht(e,t,n){let r=ut(e),i=new Set(t),a=new Set(n?.boundNames||[]),o=new Set;return A(r,{ReferencedIdentifier(e){let t=e.node.name;a.has(t)||e.scope.hasBinding(t)||i.has(t)&&o.add(t)}}),o}function gt(e){let t=e.importPath||e.filePath;return e.exportName===`default`?`import ${e.name} from '${t}'`:e.exportName===e.name?`import { ${e.name} } from '${t}'`:`import { ${e.exportName} as ${e.name} } from '${t}'`}function _t(e,t){let n=qe(t,e.importPath||e.filePath,{stripExtension:!0});return` const ${e.name}: typeof import('${n}')['${e.exportName}'];`}const vt=[`**/*.ts`,`**/*.mts`,`**/*.cts`,`**/*.js`,`**/*.mjs`,`**/*.cjs`,`**/*.tsx`,`**/*.jsx`];function yt(e){return typeof e==`string`?{isType:void 0,localName:e,sourceName:e}:{isType:e.isType,localName:e.as||e.name,sourceName:e.name}}function bt(e){return typeof e!=`string`&&e.only!==void 0}function xt(e,t){let n=C(e.rootDir,e.srcDir),r=typeof t==`string`?t:t.from,i=Ge(n,r);return{exclude:typeof t==`string`?void 0:t.exclude,ignore:typeof t==`string`?void 0:t.ignore,importBase:ot(n,r,i.importBase),path:i.path,pattern:typeof t==`string`?void 0:t.pattern,types:typeof t==`string`?!1:t.types}}function St(e){return(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?{exclude:[],ignore:[],importBase:void 0,pattern:vt,path:b(C(e)),types:!1}:{exclude:e.exclude||[],ignore:e.ignore,importBase:e.importBase,pattern:e.pattern||vt,path:b(C(e.path)),types:e.types||!1})}function Ct(e){return JSON.stringify({exclude:[...e.exclude||[]].sort(),ignore:j(e.ignore),importBase:e.importBase,path:e.path,pattern:j(e.pattern),types:e.types||!1})}function wt(e){return{exportName:e.export||e.name,filePath:e.from,importPath:e.from,name:e.name}}function Tt(e,t){return{importPath:qe(t,e.importPath||e.filePath,{stripExtension:!0}),specifier:e.exportName===e.name?e.name:`${e.exportName} as ${e.name}`}}function Et(e){return`${e.filePath}#${e.exportName}`}var Dt=class{constructor(e,t){this._config=e,this.autoApis=[],this.autoApiTypes=[],this.autoApiMap=new Map,this.autoApiTypeMap=new Map,this.includedApis=[],this.includedApiTypes=[],this.apiSources=[],this.oiyoState=t.oiyoState,this.logger=t.logger.withScope(`AUTO_API`),this.registerConfigScanners()}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`apis.d.ts`)}isAutoApiPath(e){let t=b(e);return this.apiSources.some(e=>He(t,e.path,{ignore:e.ignore,pattern:e.pattern}))}includeApi(e){let t=Array.isArray(e)?e:[e];this.includedApis.push(...t.map(wt))}includeApiType(e){let t=Array.isArray(e)?e:[e];this.includedApiTypes.push(...t.map(wt))}includeApis(e){for(let t of St(e)){let e=Ct(t);this.apiSources.some(t=>Ct(t)===e)||this.apiSources.push(t)}}registerConfigScanners(){for(let e of this._config.scan?.apis||[]){if(!bt(e)){this.includeApis(xt(this._config,e));continue}for(let t of e.only){let{isType:n,localName:r,sourceName:i}=yt(t),a={export:i===r?void 0:i,from:e.from,name:r};n??e.types?this.includeApiType(a):this.includeApi(a)}}}resetCollectedState(){this.autoApis=[],this.autoApiTypes=[],this.autoApiMap.clear(),this.autoApiTypeMap.clear()}registerValue(e,t){let n=this.autoApiMap.get(e.name);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||n.filePath===e.filePath&&n.exportName!==`default`&&e.exportName===`default`||this.logger.warn(`自动 API 名称冲突: ${e.name} 已存在,已跳过 ${Et(e)}`),!1):(this.autoApiMap.set(e.name,e),t?.trackScanned&&this.autoApis.push(e),!0)}registerType(e,t){let n=this.autoApiTypeMap.get(e.name);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||this.logger.warn(`自动 API 类型名称冲突: ${e.name} 已存在,已跳过 ${Et(e)}`),!1):(this.autoApiTypeMap.set(e.name,e),t?.trackScanned&&this.autoApiTypes.push(e),!0)}seedIncludedRegistrations(){this.includedApis.forEach(e=>this.registerValue(e)),this.includedApiTypes.forEach(e=>this.registerType(e))}registerScannedValueItems(e,t){for(let n of t){let t=ct(n,e.importBase);(e.exclude||[]).includes(t.name)||this.registerValue(t,{trackScanned:!0})}}registerScannedTypeItems(e,t){for(let n of t){let t=ct(n,e.importBase);(e.exclude||[]).includes(t.name)||this.registerType(t,{trackScanned:!0})}}async scanSourceFiles(e,t,n,r){for(let i of t)try{let t=await pt(i,await m(i,`utf-8`),Ke(i,n,e.importBase),{includeTypes:r.includeTypes,visitedFiles:new Set});r.registerValues&&this.registerScannedValueItems(e,t.valueItems),r.registerTypes&&this.registerScannedTypeItems(e,t.typeItems)}catch{this.logger.warn(`解析自动 API 文件失败,已跳过: ${i}`)}}async collectApis(){let e=C(this._config.rootDir,this._config.srcDir);this.resetCollectedState(),this.seedIncludedRegistrations();for(let t of this.apiSources){let{typePath:n,valuePath:r}=await st(t,e),i=await M({dir:r,ignore:t.ignore,pattern:t.pattern});if(t.types&&r===n){await this.scanSourceFiles(t,i,r,{includeTypes:!0,registerTypes:!0,registerValues:!0});continue}if(await this.scanSourceFiles(t,i,r,{includeTypes:!1,registerValues:!0}),!t.types)continue;let a=r===n?i:await M({dir:n,ignore:t.ignore,pattern:t.pattern});await this.scanSourceFiles(t,a,n,{includeTypes:!0,registerTypes:!0})}return this.autoApis}collectBoundNames(e){return mt(e)}resolveImports(e,t){return!e||this.autoApiMap.size===0?[]:Array.from(ht(e,this.autoApiMap.keys(),t)).sort().map(e=>gt(this.autoApiMap.get(e)))}resolveImport(e){let t=this.autoApiMap.get(e);if(t)return gt(t)}generateDeclaration(){let e=Array.from(this.autoApiTypeMap.values()).sort((e,t)=>e.name.localeCompare(t.name)).reduce((e,t)=>{let n=Tt(t,this.typesDir),r=e.get(n.importPath)||[];return r.push(n.specifier),e.set(n.importPath,r),e},new Map);return[`// Generated by oiyo`,`declare global {`,...Array.from(this.autoApiMap.values()).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>_t(e,this.typesDir)),`}`,``,`declare global {`,...Array.from(e.entries()).flatMap(([e,t])=>[` // @ts-ignore`,` export type { ${t.join(`, `)} } from '${e}';`]),`}`,``,`export {}`,``].join(`
10
+ `)}writeDeclaration(){return d(this.typesDir,{recursive:!0}),P(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}};const Ot=/<\/?\s*([a-z][\w-]*)\b/gi,kt=[`**/*.vue`,`**/*.nvue`];function At(e){return typeof e==`string`?{localName:e,sourceName:e}:{localName:e.as||e.name,sourceName:e.name}}function jt(e){return typeof e!=`string`&&e.only!==void 0}function Mt(e,t){let n=Ge(C(e.rootDir,e.srcDir),typeof t==`string`?t:t.from);return{chain:typeof t==`string`?!0:t.chain,ignore:typeof t==`string`?void 0:t.ignore,importBase:n.importBase,path:n.path,pattern:typeof t==`string`?void 0:t.pattern,prefix:typeof t==`string`?void 0:t.prefix}}function Nt(e){return(e.scan?.components||[]).filter(e=>!jt(e)).map(t=>Mt(e,t))}function Pt(e,t){let n=b(t);return Nt(e).some(e=>He(n,e.path,{ignore:e.ignore,pattern:e.pattern}))}function Ft(e){return e?I(e):``}function It(e){if(e.length<2)return e;let t=e.slice();return t[t.length-1]===t[t.length-2]&&t.pop(),t}function Lt(e,t,n){let{dir:r,name:i}=x(S(t,e)),a=r&&r!==`.`?r.split(oe).filter(Boolean):[];(i!==`index`||a.length===0)&&a.push(i);let o=It(a),s=n?.chain===!1?o.slice(-1):o;return`${Ft(n?.prefix)}${s.map(e=>I(e)).join(``)}`}function Rt(e){let t=new Set;Ot.lastIndex=0;let n=Ot.exec(e);for(;n;)t.add(n[1]),n=Ot.exec(e);return t}function zt(e){return e.includes(`-`)?I(e):e}function Bt(e){return{componentName:e.name,exportName:e.export||`default`,filePath:e.from,importPath:e.from}}function Vt(e){return(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?{chain:!0,ignore:[],importBase:void 0,pattern:kt,path:b(C(e)),prefix:void 0}:{chain:e.chain??!0,ignore:e.ignore,importBase:e.importBase,pattern:e.pattern||kt,path:b(C(e.path)),prefix:e.prefix})}function Ht(e){return JSON.stringify({chain:e.chain,ignore:j(e.ignore),importBase:e.importBase,path:e.path,pattern:j(e.pattern),prefix:e.prefix})}function Ut(e){let t=e.importPath||e.filePath;return e.exportName===`default`?`import ${e.componentName} from '${t}'`:e.exportName===e.componentName?`import { ${e.componentName} } from '${t}'`:`import { ${e.exportName} as ${e.componentName} } from '${t}'`}function Wt(e,t){let n=qe(t,e.importPath||e.filePath);return` ${e.componentName}: typeof import('${n}')['${e.exportName}'];`}var Gt=class{constructor(e,t){this._config=e,this.autoComponents=[],this.registeredComponents=[],this.componentSources=[],this.autoComponentMap=new Map,this.oiyoState=t.oiyoState,this.logger=t.logger.withScope(`AUTO_COMPONENT`),this.registerConfigScanners()}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`components.d.ts`)}isAutoComponentPath(e){let t=b(e);return this.componentSources.some(e=>He(t,e.path,{ignore:e.ignore,pattern:e.pattern}))}registerComponent(e){this.registeredComponents.push(Bt(e))}registerComponents(e){for(let t of Vt(e)){let e=Ht(t);this.componentSources.some(t=>Ht(t)===e)||this.componentSources.push(t)}}registerConfigScanners(){for(let e of this._config.scan?.components||[]){if(!jt(e)){this.registerComponents(Mt(this._config,e));continue}for(let t of e.only){let{localName:n,sourceName:r}=At(t);this.registerComponent({export:r,from:e.from,name:e.prefix?`${I(e.prefix)}${n}`:n})}}}setResolvedComponent(e,t){let n=this.autoComponentMap.get(e.componentName);return n?(n.filePath===e.filePath&&n.exportName===e.exportName||this.logger.warn(`组件名称冲突: ${e.componentName} 已存在,已跳过 ${e.filePath}`),!1):(this.autoComponentMap.set(e.componentName,e),t?.trackScanned&&this.autoComponents.push(e),!0)}async collectComponents(){this.autoComponents=[],this.autoComponentMap.clear(),this.registeredComponents.forEach(e=>this.setResolvedComponent(e));for(let e of this.componentSources)(await M({dir:e.path,ignore:e.ignore,pattern:e.pattern})).forEach(t=>{let n=e.path===t?_(t):e.path;this.setResolvedComponent({componentName:Lt(t,n,{chain:e.chain,prefix:e.prefix}),exportName:`default`,filePath:t,importPath:Ke(t,e.path,e.importBase)},{trackScanned:!0})});return this.autoComponents}resolveComponentImports(e,t){if(!e||this.autoComponentMap.size===0)return[];let n=[],r=new Set,i=t?b(t):void 0;for(let t of Rt(e)){let e=zt(t),a=this.autoComponentMap.get(e);a&&(i&&a.filePath===i||r.has(e)||(r.add(e),n.push(Ut(a))))}return n}resolveComponentImport(e,t){let n=this.autoComponentMap.get(e);if(!n)return;let r=t?b(t):void 0;if(!(r&&n.filePath===r))return Ut(n)}generateDeclaration(){return[`// Generated by oiyo`,`declare module 'vue' {`,` export interface GlobalComponents {`,...Array.from(this.autoComponentMap.values()).sort((e,t)=>e.componentName.localeCompare(t.componentName)).map(e=>Wt(e,this.typesDir)),` }`,`}`,``,`export {}`,``].join(`
11
+ `)}writeDeclaration(){return d(this.typesDir,{recursive:!0}),P(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}};function Kt(e){return e.includes(`<OiyoLayout`)||e.includes(`<oiyo-layout`)}function qt(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 Jt(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 Yt(e,t){let{dir:n,name:r}=x(S(t,e));return(n&&n!==`.`?[...n.split(oe),r]:[r]).map(e=>Je(e)).join(`-`)}function Xt(e){return`OiyoLayout${e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}`}const Zt=fe({name:`OiyoLayout`,setup(e,t){return()=>t.slots.default?.()}});var Qt=class{constructor(e,t){this.config=e,this.layoutFiles=[],this.logger=t.logger.withScope(`LAYOUT`),this.oiyoState=t.oiyoState}get srcDir(){return C(this.config.rootDir,this.config.srcDir)}get layoutDir(){return C(this.srcDir,this.config.dir?.layouts||`layouts`)}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`layouts.d.ts`)}isLayoutPath(e){let t=b(e);return!t.endsWith(`.vue`)&&!t.endsWith(`.nvue`)||[...ue,...this.config.exclude||[]].some(e=>y(t,e))||Pt(this.config,t)?!1:t.startsWith(`${this.layoutDir}/`)}setLayout(e){if(this.layoutFiles.findIndex(({filePath:t})=>t===e)!==-1)return!1;let t=Yt(e,this.layoutDir),n=Xt(t);return this.layoutFiles.push({useName:t,componentName:n,filePath:e}),!0}async registerLayouts(){let e=await M({dir:this.layoutDir,pattern:[`**/*.vue`,`**/*.nvue`]});return this.layoutFiles=[],e.filter(e=>this.isLayoutPath(e)).map(e=>this.setLayout(e)),this.layoutFiles}generateDeclaration(){return[`// Generated by oiyo`,``,`declare module '@skiyee/oiyo/api' {`,` interface OiyoLayouts {`,...this.layoutFiles.slice().sort((e,t)=>e.useName.localeCompare(t.useName)).map(({useName:e,filePath:t})=>` '${e}': typeof import('${Ue(this.typesDir,t)}')['default'];`),` }`,``,` type LayoutKey = keyof OiyoLayouts extends never ? string : keyof OiyoLayouts;`,``,` interface PageMeta {`,` layout?: LayoutKey | false;`,` }`,`}`,``,`export {}`,``].join(`
12
+ `)}writeDeclaration(){return d(this.typesDir,{recursive:!0}),P(this.declarationPath,this.generateDeclaration()),this.oiyoState.ensureDeclarationEntry(),this.declarationPath}applyLayout(e,t){if(!Kt(t))return{template:t,script:``,imports:[]};if(e===!1)return{template:qt(t),script:``,imports:[]};e===void 0&&(e=`default`);let n=this.layoutFiles.find(t=>t.useName===e);return n?{template:Jt(t,n.componentName),script:``,imports:[`import ${n.componentName} from '${n.filePath}'`]}:(this.logger.error(`未找到布局 "${e}",请检查布局名称或文件位置是否正确`),{template:t,script:``,imports:[]})}};function $t(e){if(!e||!e.includes(`import`))return[];let t=w(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 en(e){if(!e||!e.includes(`import`))return new Set;let t=w(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 tn(e){if(!e||!e.includes(`import`))return e;let t=w(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 R(e,t){let n=nn(t),r=nn(e);for(let[e,t]of r){let r=n.get(e);r?rn(r,t):n.set(e,t)}return an(n)}function nn(e){let t=new Map;for(let n of e)A(w(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 rn(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 an(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}function on(e){if(!e.includes(`defineRootContext`))return``;let{descriptor:t}=T(e);if(!t.scriptSetup)return``;let n=e=t.scriptSetup.content,r=sn(n);return n.substring(r.start,r.end+1).trim()}function sn(e){return Ye(e,`defineRootContext`)}function cn(e){if(!e.includes(`<template`))return``;let{descriptor:t}=T(e);return(t.template?.content||``).trim()}function ln(e,t){let n=e.replace(/\{\{([\s\S]*?)\}\}/g,(e,n)=>e.replace(n,un(n,t)));return n=n.replace(/((?:v-(?!for\b)[\w-]+(?::[\w-]+)?|[:@][\w-]+)\s*=\s*)(["'])([\s\S]*?)\2/g,(e,n,r,i)=>`${n}${r}${un(i,t)}${r}`),n}function un(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=w(`(${e})`,{sourceType:`module`,plugins:[`typescript`]}),r=new E(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 dn(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=ln(n,t),n.trim()}function fn(e){if(!e)return;let t=e?.content;if(t){let e=pn(t);return e.script?e:void 0}}function pn(e){let t=w(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 mn(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 hn=`virtual:oiyo-root-context`,z=`\0${hn}`;function gn(e){let{script:t,imports:n}=e,r=[];return n?.length&&(r.push(...n),r.push(``)),t?(r.push(`let rootContextInstance = null`),r.push(``),r.push(`export function useRootContext() {`),r.push(`if (!rootContextInstance) {`),r.push(`const factory = ${t}`),r.push(`rootContextInstance = factory()`),r.push(`}`),r.push(`return rootContextInstance`),r.push(`}`)):(r.push(`export function useRootContext() {`),r.push(`return {}`),r.push(`}`)),r.join(`
13
+ `)}const _n=e=>e();var vn=class{constructor(e,t){this.config=e,this.rootView={imports:[],template:`<OiyoPage />`,script:``},this.shouldRefreshVM=e=>{let t=``;this.rootMarco&&(t=N(Xe(`defineRootContext(${this.rootMarco.script})`)));let n=N(Xe(on(e)));return t!==n},this.logger=t.logger.withScope(`ROOT`),this.oiyoAutoApi=t.oiyoAutoApi}get srcDir(){return C(this.config.rootDir,this.config.srcDir)}get rootPath(){return C(this.srcDir,`App.vue`)}isRootPath(e){return e===this.rootPath}parseRoot(e){let{descriptor:t}=T(e),n=fn(t.scriptSetup);if(n?.script&&t.scriptSetup?.content&&this.oiyoAutoApi){let e=this.oiyoAutoApi.collectBoundNames(t.scriptSetup.content),r=this.oiyoAutoApi.resolveImports(n.script,{boundNames:e});r.length>0&&(n.imports=R(r,n.imports||[]))}return this.rootView={template:dn(t.template,{varName:n?.variable,varProperties:n?.properties}),imports:[],script:``},n&&(this.rootMarco=n,this.rootVM=gn(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 E(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=sn(e);if(r.start!==r.end){e.includes(`virtual:oiyo-root-context`)||n.appendLeft(t.scriptSetup.loc.start.offset,`
14
14
  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 N(this.rootView.template)!==N(on(e))}applyRoot(e){let t=[],n=``,r=``;return e.template&&(n=fn(this.rootView.template,e.template.content)),e.scriptSetup&&(t.push(...this.rootView.imports),r=`${this.rootView.script}\n${e.scriptSetup.content}`),{imports:t,script:r,template:n}}};function _n(e,t){if(!e.includes(`definePageMeta`))return``;if(!t){let{descriptor:t}=T(e);if(!t.scriptSetup)return``;e=t.scriptSetup.content}let n=vn(e);return e.substring(n.start,n.end+1).trim()}function vn(e){return Je(e,`definePageMeta`)}function yn(e){return e.replace(/definePageMeta\s*\(\s*\{[\s\S]*?\}\s*\)/g,``).trim()}function bn(e){let t=w(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=xn(t),e.stop())}}}),n}function xn(e){let t={};for(let n of e.properties)if(n.type===`ObjectProperty`){let e=Sn(n.key),r=Cn(n.value);e&&(t[e]=r)}return t}function Sn(e){return e.type===`Identifier`?e.name:e.type===`StringLiteral`?e.value:null}function Cn(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=>Cn(e)).filter(e=>e!==void 0);case`ObjectExpression`:return xn(e);default:return}}function wn(e){return`'${e.startsWith(`/`)?e:`/${e}`}'`}function Tn(e){let t=new Set;for(let n of e.pages||[])t.add(wn(n.path));for(let n of e.subPackages||[])for(let e of n.pages||[])t.add(wn(v(n.root,e.path)));return Array.from(t).sort()}function En(e){let t=new Set;for(let n of e.tabBar?.list||[])t.add(wn(n.pagePath));return Array.from(t).sort()}function Dn(e){return e.length>0?e.join(` |
16
- `):`string`}function On(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 kn(e){let t=Tn(e),n=En(e);return[`/* eslint-disable */`,`// Generated by oiyo`,``,`interface NavigateToOptions {`,` url: ${Dn(t)};`,`}`,`interface RedirectToOptions extends NavigateToOptions {}`,``,`interface SwitchTabOptions {`,n.length>0?` url: ${n.join(` |
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 N(this.rootView.template)!==N(cn(e))}applyRoot(e){let t=[],n=``,r=``;return e.template&&(n=mn(this.rootView.template,e.template.content)),e.scriptSetup&&(t.push(...this.rootView.imports),r=`${this.rootView.script}\n${e.scriptSetup.content}`),{imports:t,script:r,template:n}}};function yn(e,t){if(!e.includes(`definePageMeta`))return``;if(!t){let{descriptor:t}=T(e);if(!t.scriptSetup)return``;e=t.scriptSetup.content}let n=bn(e);return e.substring(n.start,n.end+1).trim()}function bn(e){return Ye(e,`definePageMeta`)}function xn(e){return e.replace(/definePageMeta\s*\(\s*\{[\s\S]*?\}\s*\)/g,``).trim()}function Sn(e){let t=w(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=Cn(t),e.stop())}}}),n}function Cn(e){let t={};for(let n of e.properties)if(n.type===`ObjectProperty`){let e=wn(n.key),r=Tn(n.value);e&&(t[e]=r)}return t}function wn(e){return e.type===`Identifier`?e.name:e.type===`StringLiteral`?e.value:null}function Tn(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=>Tn(e)).filter(e=>e!==void 0);case`ObjectExpression`:return Cn(e);default:return}}function En(e){return`'${e.startsWith(`/`)?e:`/${e}`}'`}function Dn(e){let t=new Set;for(let n of e.pages||[])t.add(En(n.path));for(let n of e.subPackages||[])for(let e of n.pages||[])t.add(En(v(n.root,e.path)));return Array.from(t).sort()}function On(e){let t=new Set;for(let n of e.tabBar?.list||[])t.add(En(n.pagePath));return Array.from(t).sort()}function kn(e){return e.length>0?e.join(` |
16
+ `):`string`}function An(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 jn(e){let t=Dn(e),n=On(e);return[`/* eslint-disable */`,`// Generated by oiyo`,``,`interface NavigateToOptions {`,` url: ${kn(t)};`,`}`,`interface RedirectToOptions extends NavigateToOptions {}`,``,`interface SwitchTabOptions {`,n.length>0?` url: ${n.join(` |
17
17
  `)};`:``,`}`,``,`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
- `)}const An=e=>{},jn=de({name:`OiyoPage`});var Mn=class{constructor(e,t){this.pageFiles=[],this.pagesConfig={},this.config=e,this.logger=t.logger.withScope(`ROUTE`),this.oiyoState=t.oiyoState,this.oiyoRoot=t.oiyoRoot,this.oiyoLayout=t.oiyoLayout}get srcDir(){return C(this.config.rootDir,this.config.srcDir)}get mainPageDir(){return C(this.srcDir,this.config.dir.mainPackage)}get subPageDirs(){return this.config.dir.subPackages.map(e=>C(this.srcDir,e))}get pagesJsonPath(){return C(this.srcDir,`pages.json`)}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`pages.d.ts`)}resolvePagesJson(e){return me(On(this.pageFiles),e||this.pagesConfig)}async loadPagesConfig(){try{let{config:e,configFile:t}=await fe({name:`pages`,cwd:this.srcDir});this.pagesConfig=e||{}}catch{this.pagesConfig={},this.logger.warn(`加载 pages 配置失败,已采用空配置`)}return this.pagesConfig}async watchPagesConfig(e){if(this.pagesConfigWatcher)return;let t=await pe({name:`pages`,cwd:this.srcDir,acceptHMR({getDiff:e}){return e().length===0},onWatch:e=>{},onUpdate:({newConfig:t})=>{this.pagesConfig=t.config||{},this.writePagesJson(),e&&Promise.resolve(e()).catch(e=>{this.logger.error(`pages 配置更新回调失败,页面配置已更新但后续回调未完成`,{error:e})})}});this.pagesConfig=t.config||this.pagesConfig,this.pagesConfigWatcher=t}async unwatchPagesConfig(){this.pagesConfigWatcher&&=(await this.pagesConfigWatcher.unwatch(),void 0)}isPagePath(e){let t=b(e);return!t.endsWith(`.vue`)&&!t.endsWith(`.nvue`)||[...le,...this.config.exclude||[]].some(e=>y(t,e))||Nt(this.config,t)?!1:[this.mainPageDir,...this.subPageDirs].some(e=>t.startsWith(`${e}/`))}toPageFile(e,t){let n=!0,r=this.mainPageDir,i=this.subPageDirs.find(t=>e.startsWith(`${t}/`));i&&(n=!1);let a=x(S(n?this.srcDir:i,e)),o=a.dir===``?a.name:v(a.dir,a.name),s=n?r:i;return{filePath:e,pagePath:o,pageBelong:S(this.srcDir,s),pageMeta:t}}setPageFile(e){let t=this.pageFiles.findIndex(({pagePath:t,pageBelong:n})=>t===e.pagePath&&n===e.pageBelong);if(t===-1)return this.pageFiles.push(e),!0;let n=this.pageFiles[t],r=JSON.stringify(n.pageMeta)!==JSON.stringify(e.pageMeta);return r&&(this.pageFiles[t]=e),r}async loadPagesJson(){try{let e=await m(this.pagesJsonPath,`utf-8`),t=JSON.parse(e);for(let e of t.pages||[]){let{path:t,...n}=e,r=C(this.srcDir,e.path),i=this.toPageFile(r,n);this.setPageFile(i)}for(let e of t.subPackages||[]){let t=e.root;for(let n of e.pages||[]){let{path:e,...r}=n,i=C(this.srcDir,t,n.path);this.setPageFile(this.toPageFile(i,r))}}}catch(e){this.logger.error(`加载 pages.json 失败,已跳过现有文件内容,请检查 pages.json 是否存在且格式正确:`,{error:e})}}writePagesJson(e){try{let t=this.resolvePagesJson(e),n=`${JSON.stringify(t,null,2)}\n`;P(this.pagesJsonPath,n),this.writeDeclaration(e)}catch(e){this.logger.error(`写入 pages.json 失败,请检查目标文件权限和内容格式:`,{error:e})}}generateDeclaration(e){return kn(this.resolvePagesJson(e))}writeDeclaration(e){try{d(this.typesDir,{recursive:!0}),P(this.declarationPath,this.generateDeclaration(e)),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`写入 pages.d.ts 失败,请检查目标文件权限和内容格式:`,{error:e})}return this.declarationPath}async registerPages(){let e=[this.mainPageDir,...this.subPageDirs],t=(await Promise.all(e.map(e=>M({dir:e,pattern:[`**/*.vue`,`**/*.nvue`]})))).flat(2).filter(e=>this.isPagePath(e));for(let e of t){let t=await m(e,`utf-8`),n={},r=_n(t);r&&(n=bn(r)),this.setPageFile(this.toPageFile(e,n))}return this.pageFiles}async tryUpdatePage(e,t){let n=bn(e);this.setPageFile(this.toPageFile(t,n))&&(this.writePagesJson(),await new Promise(e=>setTimeout(e,100)))}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 E(e);if(!n.template?.content)return{code:r.toString(),sourceMap:r.generateMap()};n.scriptSetup&&await this.tryUpdatePage(n.scriptSetup.content,t);let i=this.oiyoRoot.applyRoot(n),a=[...i.imports],o=i.template,s=i.script,c={};n.scriptSetup&&(c=this.pageFiles.find(e=>t.startsWith(e.filePath))?.pageMeta||{},s=yn(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=Qt(n.scriptSetup.content);a=z(a,e),s=R(s),r.overwrite(n.scriptSetup.loc.start.offset,n.scriptSetup.loc.end.offset,`${a.join(`
18
+ `)}const Mn=e=>{},Nn=fe({name:`OiyoPage`});var Pn=class{constructor(e,t){this.pageFiles=[],this.pagesConfig={},this.config=e,this.logger=t.logger.withScope(`ROUTE`),this.oiyoState=t.oiyoState,this.oiyoRoot=t.oiyoRoot,this.oiyoLayout=t.oiyoLayout}get srcDir(){return C(this.config.rootDir,this.config.srcDir)}get mainPageDir(){return C(this.srcDir,this.config.dir.mainPackage)}get subPageDirs(){return this.config.dir.subPackages.map(e=>C(this.srcDir,e))}get pagesJsonPath(){return C(this.srcDir,`pages.json`)}get stateDir(){return this.oiyoState.stateDir}get typesDir(){return this.oiyoState.typesDir}get declarationPath(){return C(this.typesDir,`pages.d.ts`)}resolvePagesJson(e){return he(An(this.pageFiles),e||this.pagesConfig)}async loadPagesConfig(){try{let{config:e,configFile:t}=await pe({name:`pages`,cwd:this.srcDir});this.pagesConfig=e||{}}catch{this.pagesConfig={},this.logger.warn(`加载 pages 配置失败,已采用空配置`)}return this.pagesConfig}async watchPagesConfig(e){if(this.pagesConfigWatcher)return;let t=await me({name:`pages`,cwd:this.srcDir,acceptHMR({getDiff:e}){return e().length===0},onWatch:e=>{},onUpdate:({newConfig:t})=>{this.pagesConfig=t.config||{},this.writePagesJson(),e&&Promise.resolve(e()).catch(e=>{this.logger.error(`pages 配置更新回调失败,页面配置已更新但后续回调未完成`,{error:e})})}});this.pagesConfig=t.config||this.pagesConfig,this.pagesConfigWatcher=t}async unwatchPagesConfig(){this.pagesConfigWatcher&&=(await this.pagesConfigWatcher.unwatch(),void 0)}isPagePath(e){let t=b(e);return!t.endsWith(`.vue`)&&!t.endsWith(`.nvue`)||[...ue,...this.config.exclude||[]].some(e=>y(t,e))||Pt(this.config,t)?!1:[this.mainPageDir,...this.subPageDirs].some(e=>t.startsWith(`${e}/`))}toPageFile(e,t){let n=!0,r=this.mainPageDir,i=this.subPageDirs.find(t=>e.startsWith(`${t}/`));i&&(n=!1);let a=x(S(n?this.srcDir:i,e)),o=a.dir===``?a.name:v(a.dir,a.name),s=n?r:i;return{filePath:e,pagePath:o,pageBelong:S(this.srcDir,s),pageMeta:t}}setPageFile(e){let t=this.pageFiles.findIndex(({pagePath:t,pageBelong:n})=>t===e.pagePath&&n===e.pageBelong);if(t===-1)return this.pageFiles.push(e),!0;let n=this.pageFiles[t],r=JSON.stringify(n.pageMeta)!==JSON.stringify(e.pageMeta);return r&&(this.pageFiles[t]=e),r}async loadPagesJson(){try{let e=await m(this.pagesJsonPath,`utf-8`),t=JSON.parse(e);for(let e of t.pages||[]){let{path:t,...n}=e,r=C(this.srcDir,e.path),i=this.toPageFile(r,n);this.setPageFile(i)}for(let e of t.subPackages||[]){let t=e.root;for(let n of e.pages||[]){let{path:e,...r}=n,i=C(this.srcDir,t,n.path);this.setPageFile(this.toPageFile(i,r))}}}catch(e){this.logger.error(`加载 pages.json 失败,已跳过现有文件内容,请检查 pages.json 是否存在且格式正确:`,{error:e})}}writePagesJson(e){try{let t=this.resolvePagesJson(e),n=`${JSON.stringify(t,null,2)}\n`;P(this.pagesJsonPath,n),this.writeDeclaration(e)}catch(e){this.logger.error(`写入 pages.json 失败,请检查目标文件权限和内容格式:`,{error:e})}}generateDeclaration(e){return jn(this.resolvePagesJson(e))}writeDeclaration(e){try{d(this.typesDir,{recursive:!0}),P(this.declarationPath,this.generateDeclaration(e)),this.oiyoState.ensureDeclarationEntry()}catch(e){this.logger.error(`写入 pages.d.ts 失败,请检查目标文件权限和内容格式:`,{error:e})}return this.declarationPath}async registerPages(){let e=[this.mainPageDir,...this.subPageDirs],t=(await Promise.all(e.map(e=>M({dir:e,pattern:[`**/*.vue`,`**/*.nvue`]})))).flat(2).filter(e=>this.isPagePath(e));for(let e of t){let t=await m(e,`utf-8`),n={},r=yn(t);r&&(n=Sn(r)),this.setPageFile(this.toPageFile(e,n))}return this.pageFiles}async tryUpdatePage(e,t){let n=Sn(e);this.setPageFile(this.toPageFile(t,n))&&(this.writePagesJson(),await new Promise(e=>setTimeout(e,100)))}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 E(e);if(!n.template?.content)return{code:r.toString(),sourceMap:r.generateMap()};n.scriptSetup&&await this.tryUpdatePage(n.scriptSetup.content,t);let i=this.oiyoRoot.applyRoot(n),a=[...i.imports],o=i.template,s=i.script,c={};n.scriptSetup&&(c=this.pageFiles.find(e=>t.startsWith(e.filePath))?.pageMeta||{},s=xn(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=$t(n.scriptSetup.content);a=R(a,e),s=tn(s),r.overwrite(n.scriptSetup.loc.start.offset,n.scriptSetup.loc.end.offset,`${a.join(`
19
19
  `)}\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 Nn=new Set([`.ts`,`.mts`,`.cts`,`.js`,`.mjs`,`.cjs`,`.tsx`,`.jsx`]);function Pn(e){return e.endsWith(`.vue`)||e.endsWith(`.nvue`)}function Fn(e){return Array.from(Nn).some(t=>e.endsWith(t))}function In(e){return b(e.split(`?`,1)[0])}function V(e,t){return[...e,t].filter(Boolean).join(`
21
- `)}function Ln(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 Rn(e,t,n){let r=z(n,Qt(t.content)),i=R(t.content);e.overwrite(t.loc.start.offset,t.loc.end.offset,V(r,i))}function zn(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 Bn(e){let t=new Set;return e.script?.content&&$t(e.script.content).forEach(e=>t.add(e)),e.scriptSetup?.content&&$t(e.scriptSetup.content).forEach(e=>t.add(e)),t}function Vn(e,t){let n=$t(e),r=t.autoApi.resolveImports(e,{boundNames:n});if(r.length===0)return null;let i=z(r,Qt(e)),a=R(e),o=new E(e);return o.overwrite(0,e.length,V(i,a)),{code:o.toString(),sourceMap:o.generateMap()}}function Hn(e,t,n){let{descriptor:r}=T(e),i=Bn(r),a=r.template?.content?Array.from(zn(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?(Rn(s,r.scriptSetup,[...a,...o]),{code:s.toString(),sourceMap:s.generateMap()}):r.script?(o.length>0&&Rn(s,r.script,o),a.length>0&&Ln(s,r,V(a,``)),{code:s.toString(),sourceMap:s.generateMap()}):(Ln(s,r,V([...a,...o],``)),{code:s.toString(),sourceMap:s.generateMap()})}function Un(){let e;return[{name:`oiyo:auto`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`AUTO`)},transform(t,n){let r=In(n);return Fn(r)?r.startsWith(`${e.root.srcDir}/`)&&Vn(t,e)||void 0:!Pn(r)||!r.startsWith(`${e.root.srcDir}/`)&&r!==e.root.rootPath?void 0:Hn(t,r,e)||void 0}}]}const H={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},Wn={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:H.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Wn);const Gn=`READDIRP_RECURSIVE_ERROR`,Kn=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,Gn]),qn=[H.DIR_TYPE,H.EVERYTHING_TYPE,H.FILE_DIR_TYPE,H.FILE_TYPE],Jn=new Set([H.DIR_TYPE,H.EVERYTHING_TYPE,H.FILE_DIR_TYPE]),Yn=new Set([H.EVERYTHING_TYPE,H.FILE_DIR_TYPE,H.FILE_TYPE]),Xn=e=>Kn.has(e.code),Zn=process.platform===`win32`,Qn=e=>!0,$n=e=>{if(e===void 0)return Qn;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 Qn};var er=class extends Te{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...Wn,...e},{root:n,type:r}=t;this._fileFilter=$n(t.fileFilter),this._directoryFilter=$n(t.directoryFilter);let i=t.lstat?p:h;Zn?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??Wn.depth,this._wantsDir=r?Jn.has(r):!1,this._wantsFile=r?Yn.has(r):!1,this._wantsEverything=r===H.EVERYTHING_TYPE,this._root=Oe(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 re(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=Oe(Ee(t,r));n={path:De(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){Xn(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 p(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===ke){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=Gn,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 tr(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&&!qn.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${qn.join(`, `)}`);return t.root=e,new er(t)}const nr=()=>{},U=process.platform,rr=U===`win32`,ir=U===`darwin`,ar=U===`linux`,or=U===`freebsd`,sr=Ae()===`OS400`,W={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},G=W,cr={lstat:ye,stat:Ce},K=`listeners`,q=`errHandlers`,J=`rawEmitters`,lr=[K,q,J],ur=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(`.`)),dr=e=>ur.has(D.extname(e).slice(1).toLowerCase()),fr=(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)},pr=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]},mr=e=>e instanceof Set?e.size===0:!e,Z=new Map;function hr(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 _e(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const Q=(e,t,n,r,i)=>{let a=Z.get(e);a&&fr(a[t],e=>{e(n,r,i)})},gr=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Z.get(t),c;if(!n.persistent)return c=hr(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=hr(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),rr&&n.code===`EPERM`)try{await(await be(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),mr(s.listeners)&&(s.watcher.close(),Z.delete(t),lr.forEach(pr(s)),s.watcher=void 0,Object.freeze(s))}},_r=new Map,vr=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=_r.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(ge(t),o=void 0),o?(Y(o,K,i),Y(o,J,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:ve(t,n,(n,r)=>{fr(o.rawEmitters,e=>{e(G.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&fr(o.listeners,t=>t(e,n))})},_r.set(t,o)),()=>{X(o,K,i),X(o,J,a),mr(o.listeners)&&(_r.delete(t),ge(t),o.options=o.watcher=void 0,Object.freeze(o))}};var yr=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||=nr;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&dr(i)?n.binaryInterval:n.interval,s=vr(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=gr(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 Ce(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),(ir||ar||or)&&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 Se(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 cr[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 Se(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 Se(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}}};
20
+ `);r.appendRight(n.template.loc.end.offset+11,`\n\n${e}`)}return{code:r.toString(),sourceMap:r.generateMap()}}};const Fn=new Set([`.ts`,`.mts`,`.cts`,`.js`,`.mjs`,`.cjs`,`.tsx`,`.jsx`]);function In(e){return e.endsWith(`.vue`)||e.endsWith(`.nvue`)}function Ln(e){return Array.from(Fn).some(t=>e.endsWith(t))}function Rn(e){return b(e.split(`?`,1)[0])}function B(e,t){return[...e,t].filter(Boolean).join(`
21
+ `)}function zn(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 Bn(e,t,n){let r=R(n,$t(t.content)),i=tn(t.content);e.overwrite(t.loc.start.offset,t.loc.end.offset,B(r,i))}function Vn(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 Hn(e){let t=new Set;return e.script?.content&&en(e.script.content).forEach(e=>t.add(e)),e.scriptSetup?.content&&en(e.scriptSetup.content).forEach(e=>t.add(e)),t}function Un(e,t){let n=en(e),r=t.autoApi.resolveImports(e,{boundNames:n});if(r.length===0)return null;let i=R(r,$t(e)),a=tn(e),o=new E(e);return o.overwrite(0,e.length,B(i,a)),{code:o.toString(),sourceMap:o.generateMap()}}function Wn(e,t,n){let{descriptor:r}=T(e),i=Hn(r),a=r.template?.content?Array.from(Vn(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?(Bn(s,r.scriptSetup,[...a,...o]),{code:s.toString(),sourceMap:s.generateMap()}):r.script?(o.length>0&&Bn(s,r.script,o),a.length>0&&zn(s,r,B(a,``)),{code:s.toString(),sourceMap:s.generateMap()}):(zn(s,r,B([...a,...o],``)),{code:s.toString(),sourceMap:s.generateMap()})}function Gn(){let e;return[{name:`oiyo:auto`,enforce:`pre`,configResolved(t){e=t.oiyo,e.logger.withScope(`AUTO`)},transform(t,n){let r=Rn(n);return Ln(r)?r.startsWith(`${e.root.srcDir}/`)&&Un(t,e)||void 0:!In(r)||!r.startsWith(`${e.root.srcDir}/`)&&r!==e.root.rootPath?void 0:Wn(t,r,e)||void 0}}]}const V={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},Kn={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:V.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(Kn);const qn=`READDIRP_RECURSIVE_ERROR`,Jn=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,qn]),Yn=[V.DIR_TYPE,V.EVERYTHING_TYPE,V.FILE_DIR_TYPE,V.FILE_TYPE],Xn=new Set([V.DIR_TYPE,V.EVERYTHING_TYPE,V.FILE_DIR_TYPE]),Zn=new Set([V.EVERYTHING_TYPE,V.FILE_DIR_TYPE,V.FILE_TYPE]),Qn=e=>Jn.has(e.code),$n=process.platform===`win32`,er=e=>!0,tr=e=>{if(e===void 0)return er;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 er};var nr=class extends Ee{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...Kn,...e},{root:n,type:r}=t;this._fileFilter=tr(t.fileFilter),this._directoryFilter=tr(t.directoryFilter);let i=t.lstat?p:g;$n?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth??Kn.depth,this._wantsDir=r?Xn.has(r):!1,this._wantsFile=r?Zn.has(r):!1,this._wantsEverything=r===V.EVERYTHING_TYPE,this._root=ke(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=ke(De(t,r));n={path:Oe(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){Qn(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)===Ae){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=qn,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 rr(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=V.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&&!Yn.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${Yn.join(`, `)}`);return t.root=e,new nr(t)}const ir=()=>{},H=process.platform,ar=H===`win32`,or=H===`darwin`,sr=H===`linux`,cr=H===`freebsd`,lr=je()===`OS400`,U={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},W=U,ur={lstat:be,stat:we},G=`listeners`,K=`errHandlers`,q=`rawEmitters`,dr=[G,K,q],fr=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(`.`)),pr=e=>fr.has(D.extname(e).slice(1).toLowerCase()),mr=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},J=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},hr=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},Y=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},gr=e=>e instanceof Set?e.size===0:!e,X=new Map;function _r(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&Z(D.resolve(e,r),G,D.join(e,r))};try{return ve(e,{persistent:t.persistent},a)}catch(e){r(e);return}}const Z=(e,t,n,r,i)=>{let a=X.get(e);a&&mr(a[t],e=>{e(n,r,i)})},vr=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=X.get(t),c;if(!n.persistent)return c=_r(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)J(s,G,i),J(s,K,a),J(s,q,o);else{if(c=_r(e,n,Z.bind(null,t,G),a,Z.bind(null,t,q)),!c)return;c.on(W.ERROR,async n=>{let r=Z.bind(null,t,K);if(s&&(s.watcherUnusable=!0),ar&&n.code===`EPERM`)try{await(await xe(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},X.set(t,s)}return()=>{Y(s,G,i),Y(s,K,a),Y(s,q,o),gr(s.listeners)&&(s.watcher.close(),X.delete(t),dr.forEach(hr(s)),s.watcher=void 0,Object.freeze(s))}},yr=new Map,br=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=yr.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(_e(t),o=void 0),o?(J(o,G,i),J(o,q,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:ye(t,n,(n,r)=>{mr(o.rawEmitters,e=>{e(W.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&mr(o.listeners,t=>t(e,n))})},yr.set(t,o)),()=>{Y(o,G,i),Y(o,q,a),gr(o.listeners)&&(yr.delete(t),_e(t),o.options=o.watcher=void 0,Object.freeze(o))}};var xr=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||=ir;let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&pr(i)?n.binaryInterval:n.interval,s=br(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=vr(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 we(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(W.CHANGE,e,n),(or||sr||cr)&&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(W.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(W.ADD,e,0))return;this.fsw._emit(W.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 Ce(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(W.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(W.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(W.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(W.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 ur[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 Ce(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 Ce(e):e;if(this.fsw.closed)return;let a=D.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(W.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
23
  /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
24
- const br=/\\/g,xr=/\/\//,Sr=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Cr=/^\.[/\\]/;function $(e){return Array.isArray(e)?e:[e]}const wr=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function Tr(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 Er(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 Dr(e,t,n){let r=Er(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Or(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=$(e).map(e=>Tr(e));return t==null?(e,t)=>Dr(n,e,t):Dr(n,t)}const kr=e=>{let t=$(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(jr)},Ar=e=>{let t=e.replace(br,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(xr);)t=t.replace(xr,`/`);return n&&(t=`/`+t),t},jr=e=>Ar(D.normalize(Ar(e))),Mr=(e=``)=>t=>typeof t==`string`?jr(D.isAbsolute(t)?t:D.join(e,t)):t,Nr=(e,t)=>D.isAbsolute(e)?e:D.join(t,e),Pr=Object.freeze(new Set);var Fr=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 xe(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=nr,this.items=Pr,Object.freeze(this)}},Ir=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Cr,``),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)}},Lr=class extends we{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};sr&&(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=nr,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 yr(this),Object.freeze(r)}_addIgnoredPath(e){if(wr(e)){for(let t of this._ignoredPaths)if(wr(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)wr(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=kr(e);return r&&(i=i.map(e=>Nr(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=kr(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;rr&&(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 Ce(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){he(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(Mr(e));this._userIgnored=Or([...[...this._ignoredPaths].map(Mr(e)),...t],void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Ir(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=D.resolve(e);return this._watched.has(t)||this._watched.set(t,new Fr(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=tr(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 Rr(e,t={}){let n=new Lr(t);return n.add(e),n}function zr(){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.autoApi.writeDeclaration(),e.autoComponent.writeDeclaration(),e.layout.writeDeclaration(),e.route.writeDeclaration();let r=async t=>{e.layout.isLayoutPath(t)&&(await e.layout.registerLayouts(),e.layout.writeDeclaration()),e.autoComponent.isAutoComponentPath(t)&&(await e.autoComponent.collectComponents(),e.autoComponent.writeDeclaration()),e.autoApi.isAutoApiPath(t)&&(await e.autoApi.collectApis(),e.autoApi.writeDeclaration())};n===`serve`&&Rr(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 Br=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 appTsconfigPath(){return C(this.stateDir,`tsconfig.app.json`)}get nodeTsconfigPath(){return C(this.stateDir,`tsconfig.node.json`)}relativeToState(e){return b(S(this.stateDir,e))}stringifyJson(e){return`${JSON.stringify(e,null,2)}\n`}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
- `)}generateAppTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir),n=this.relativeToState(this.stateDir);return this.stringifyJson({compilerOptions:{paths:{"~/*":[v(t,`*`)],"~~/*":[v(e,`*`)],"@/*":[v(t,`*`)],"@@/*":[v(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:[v(n,`oiyo.d.ts`),v(t,`**/*`),v(e,`*.d.ts`)],exclude:[v(t,`pages.config.*`),v(e,`dist`),v(e,`node_modules`),v(e,`vite.config.*`),v(e,`oiyo.config.*`)]})}generateNodeTsconfig(){let e=this.relativeToState(this.config.rootDir),t=this.relativeToState(this.srcDir);return this.stringifyJson({compilerOptions:{paths:{},esModuleInterop:!0,skipLibCheck:!0,target:`ESNext`,allowJs:!0,resolveJsonModule:!0,moduleDetection:`force`,isolatedModules:!0,verbatimModuleSyntax:!0,allowArbitraryExtensions:!0,strict:!0,noUncheckedIndexedAccess:!0,forceConsistentCasingInFileNames:!0,noImplicitOverride:!0,module:`preserve`,noEmit:!0,types:[],moduleResolution:`Bundler`,useDefineForClassFields:!0},include:[v(e,`oiyo.config.*`),v(e,`vite.config.*`),v(e,`vitest.config.*`)],exclude:[v(t,`**/*`),v(e,`dist`),v(e,`node_modules`)]})}writeAppTsconfig(){return d(this.stateDir,{recursive:!0}),P(this.appTsconfigPath,this.generateAppTsconfig()),this.appTsconfigPath}writeNodeTsconfig(){return d(this.stateDir,{recursive:!0}),P(this.nodeTsconfigPath,this.generateNodeTsconfig()),this.nodeTsconfigPath}writeDeclarationEntry(){return d(this.stateDir,{recursive:!0}),P(this.declarationEntryPath,this.generateDeclarationEntry()),this.writeAppTsconfig(),this.writeNodeTsconfig(),this.declarationEntryPath}ensureDeclarationEntry(){return u(this.appTsconfigPath)||this.writeAppTsconfig(),u(this.nodeTsconfigPath)||this.writeNodeTsconfig(),u(this.declarationEntryPath)?this.declarationEntryPath:this.writeDeclarationEntry()}};function Vr(e){let t=ue(e),n=Le();n.withScope(`CONFIG`);let r=new Br(t),i=new Wt(t,{logger:n,oiyoState:r}),a=new Et(t,{logger:n,oiyoState:r}),o=new gn(t,{oiyoAutoApi:a,logger:n}),s=new Zt(t,{logger:n,oiyoState:r});return{logger:n,config:t,autoApi:a,autoComponent:i,layout:s,state:r,route:new Mn(t,{logger:n,oiyoState:r,oiyoRoot:o,oiyoLayout:s}),root:o}}function Hr(e){return[{name:`oiyo:deps`,enforce:`pre`,async config(t){let{config:n}=await fe({name:`oiyo`,cwd:t.root}),r=Vr(n||e);return me(t,{oiyo:r,resolve:{alias:{"~":O.resolve(r.config.rootDir,r.config.srcDir),"@":O.resolve(r.config.rootDir,r.config.srcDir),"@@":O.normalize(r.config.rootDir),"~~":O.normalize(r.config.rootDir)}},optimizeDeps:{exclude:[`@skiyee/oiyo`]}})}}]}function Ur(){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.autoApi.collectApis(),e.autoComponent.collectComponents(),e.route.loadPagesConfig(),e.route.loadPagesJson(),e.layout.registerLayouts()]),e.autoApi.writeDeclaration(),e.autoComponent.writeDeclaration(),e.layout.writeDeclaration(),e.route.writeDeclaration()},configureServer(t){e.route.watchPagesConfig(()=>{t.hot.send({type:`full-reload`})});let n=async n=>{let r=!1;e.layout.isLayoutPath(n)&&(await e.layout.registerLayouts(),e.layout.writeDeclaration(),r=!0),e.autoComponent.isAutoComponentPath(n)&&(await e.autoComponent.collectComponents(),e.autoComponent.writeDeclaration(),r=!0),e.autoApi.isAutoApiPath(n)&&(await e.autoApi.collectApis(),e.autoApi.writeDeclaration(),r=!0),r&&t.hot.send({type:`full-reload`})};t.watcher.on(`add`,e=>void n(e)),t.watcher.on(`unlink`,e=>void n(e)),t.watcher.on(`change`,e=>void n(e))},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 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(B);e&&(n.moduleGraph.invalidateModule(e),i=!0)}if(i){n.hot.send({type:`full-reload`});return}}},async closeBundle(){await e.route.unwatchPagesConfig()}}]}function Wr(e={}){return[...Hr(e),...Ur(),...zr(),...Un()]}export{k as LogLevels,Wr as OiyoCorePlugin,Xt as OiyoLayout,Et as OiyoModAutoApi,Wt as OiyoModAutoComponent,Zt as OiyoModLayout,gn as OiyoModRoot,Mn as OiyoModRoute,jn as OiyoPage,Br as OiyoState,B as RESOLVED_VIRTUAL_ROOT_CONTEXT_ID,pn as VIRTUAL_ROOT_CONTEXT_ID,Le as createLogger,An as definePageMeta,hn as defineRootContext,Nt as isScannedComponentPath,It as resolveComponentName,Mt as resolveScannedComponentSources};
24
+ const Sr=/\\/g,Cr=/\/\//,wr=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Tr=/^\.[/\\]/;function Q(e){return Array.isArray(e)?e:[e]}const $=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp);function Er(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 Dr(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 Or(e,t,n){let r=Dr(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function kr(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=Q(e).map(e=>Er(e));return t==null?(e,t)=>Or(n,e,t):Or(n,t)}const Ar=e=>{let t=Q(e).flat();if(!t.every(e=>typeof e==`string`))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Mr)},jr=e=>{let t=e.replace(Sr,`/`),n=!1;for(t.startsWith(`//`)&&(n=!0);t.match(Cr);)t=t.replace(Cr,`/`);return n&&(t=`/`+t),t},Mr=e=>jr(D.normalize(jr(e))),Nr=(e=``)=>t=>typeof t==`string`?Mr(D.isAbsolute(t)?t:D.join(e,t)):t,Pr=(e,t)=>D.isAbsolute(e)?e:D.join(t,e),Fr=Object.freeze(new Set);var Ir=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 Se(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=ir,this.items=Fr,Object.freeze(this)}},Lr=class{constructor(e,t,n){this.fsw=n;let r=e;this.path=e=e.replace(Tr,``),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)}},Rr=class extends Te{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?Q(e.ignored):Q([]),awaitWriteFinish:t===!0?n:typeof t==`object`?{...n,...t}:!1};lr&&(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=ir,this._readyEmitted=!0,process.nextTick(()=>this.emit(U.READY)))},this._emitRaw=(...e)=>this.emit(U.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new xr(this),Object.freeze(r)}_addIgnoredPath(e){if($(e)){for(let t of this._ignoredPaths)if($(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)$(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=Ar(e);return r&&(i=i.map(e=>Pr(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=Ar(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!==U.ERROR&&this.emit(U.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;ar&&(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===U.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(U.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===U.ADD&&this._pendingUnlinks.has(t)&&(e=U.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===U.ADD||e===U.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=U.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===U.CHANGE&&!this._throttle(U.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===U.ADD||e===U.ADD_DIR||e===U.CHANGE)){let e=r.cwd?D.join(r.cwd,t):t,n;try{n=await we(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(U.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){ge(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&&wr.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(Nr(e));this._userIgnored=kr([...[...this._ignoredPaths].map(Nr(e)),...t],void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Lr(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=D.resolve(e);return this._watched.has(t)||this._watched.set(t,new Ir(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()===U.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?U.UNLINK_DIR:U.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=rr(e,{type:U.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 zr(e,t={}){let n=new Rr(t);return n.add(e),n}function Br(){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`&&zr(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 z},load(t){if(t===z)return e.root.rootVM||`export function useRootContext() {return {}}`},async closeBundle(){await e.route.unwatchPagesConfig()}}]}var Vr=`0.1.2`,Hr=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(`${Vr}:${this.serializeMetadataInput()}`,16)}generateMetadata(){return{hash:this.generateMetadataHash(),project:{rootDir:b(this.config.rootDir||``)},versions:{oiyo:Vr}}}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!==Vr||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:{"~/*":[v(t,`*`)],"~~/*":[v(e,`*`)],"@/*":[v(t,`*`)],"@@/*":[v(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:[v(n,`oiyo.d.ts`),v(t,`**/*`),v(e,`*.d.ts`),v(e,`oiyo.config.*`),v(e,`vite.config.*`),v(e,`vitest.config.*`)],exclude:[v(t,`pages.config.*`),v(e,`dist`),v(e,`node_modules`)]})}writeTsconfig(){return d(this.stateDir,{recursive:!0}),P(this.tsconfigPath,this.generateTsconfig()),this.tsconfigPath}writeDeclarationEntry(){return d(this.stateDir,{recursive:!0}),P(this.declarationEntryPath,this.generateDeclarationEntry()),this.writeTsconfig(),this.declarationEntryPath}ensureDeclarationEntry(){return u(this.tsconfigPath)||this.writeTsconfig(),u(this.declarationEntryPath)?this.declarationEntryPath:this.writeDeclarationEntry()}markGenerated(){return this.writeMetadata()}};function Ur(e){let t=de(e),n=Re();n.withScope(`CONFIG`);let r=new Hr(t),i=new Gt(t,{logger:n,oiyoState:r}),a=new Dt(t,{logger:n,oiyoState:r}),o=new vn(t,{oiyoAutoApi:a,logger:n}),s=new Qt(t,{logger:n,oiyoState:r});return{logger:n,config:t,autoApi:a,autoComponent:i,layout:s,state:r,route:new Pn(t,{logger:n,oiyoState:r,oiyoRoot:o,oiyoLayout:s}),root:o}}function Wr(e){return[{name:`oiyo:deps`,enforce:`pre`,async config(t){let{config:n}=await pe({name:`oiyo`,cwd:t.root}),r=Ur(n||e);return he(t,{oiyo:r,resolve:{alias:{"~":O.resolve(r.config.rootDir,r.config.srcDir),"@":O.resolve(r.config.rootDir,r.config.srcDir),"@@":O.normalize(r.config.rootDir),"~~":O.normalize(r.config.rootDir)}},optimizeDeps:{exclude:[`@skiyee/oiyo`]}})}}]}function Gr(){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.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())},configureServer(t){e.route.watchPagesConfig(()=>{t.hot.send({type:`full-reload`})});let n=async n=>{let r=!1;e.layout.isLayoutPath(n)&&(await e.layout.registerLayouts(),e.layout.writeDeclaration(),r=!0),e.autoComponent.isAutoComponentPath(n)&&(await e.autoComponent.collectComponents(),e.autoComponent.writeDeclaration(),r=!0),e.autoApi.isAutoApiPath(n)&&(await e.autoApi.collectApis(),e.autoApi.writeDeclaration(),r=!0),r&&t.hot.send({type:`full-reload`})};t.watcher.on(`add`,e=>void n(e)),t.watcher.on(`unlink`,e=>void n(e)),t.watcher.on(`change`,e=>void n(e))},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 z},load(t){if(t===z)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(z);e&&(n.moduleGraph.invalidateModule(e),i=!0)}if(i){n.hot.send({type:`full-reload`});return}}},async closeBundle(){await e.route.unwatchPagesConfig()}}]}function Kr(e={}){return[...Wr(e),...Gr(),...Br(),...Gn()]}export{k as LogLevels,Kr as OiyoCorePlugin,Zt as OiyoLayout,Dt as OiyoModAutoApi,Gt as OiyoModAutoComponent,Qt as OiyoModLayout,vn as OiyoModRoot,Pn as OiyoModRoute,Nn as OiyoPage,Hr as OiyoState,z as RESOLVED_VIRTUAL_ROOT_CONTEXT_ID,hn as VIRTUAL_ROOT_CONTEXT_ID,Re as createLogger,Mn as definePageMeta,_n as defineRootContext,Pt as isScannedComponentPath,Lt as resolveComponentName,Nt as resolveScannedComponentSources};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oiyo/core",
3
3
  "type": "module",
4
- "version": "0.1.1",
4
+ "version": "0.1.2",
5
5
  "author": {
6
6
  "name": "skiyee",
7
7
  "email": "319619193@qq.com",
@@ -49,7 +49,7 @@
49
49
  "pathe": "^2.0.3",
50
50
  "tinyglobby": "^0.2.15",
51
51
  "vue": "3.4.21",
52
- "@oiyo/config": "0.1.1"
52
+ "@oiyo/config": "0.1.2"
53
53
  },
54
54
  "devDependencies": {
55
55
  "chokidar": "4.0.3",