@aventusjs/cli 0.0.44 → 0.0.46
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/out/RealServer.js +2 -2
- package/out/cli.js +1 -1
- package/package.json +1 -1
package/out/RealServer.js
CHANGED
|
@@ -606,7 +606,7 @@ public `+i+u+`:`+o+`;
|
|
|
606
606
|
|
|
607
607
|
}`}let u=`@Watch(`+l+`)
|
|
608
608
|
public `+r+`?:`+i+`;
|
|
609
|
-
`,f=s.contentUser.slice(0,t),p=s.contentUser.slice(t+1,s.contentUser.length),m=f+u+p,h=d.TextDocument.create(s.uri,T.TypeScript,s.versionUser+1,m);await s.triggerContentChange(h);let g=await s.getFormatting({insertSpaces:!0,tabSize:4});await s.applyTextEdits(g);let _=[{newText:s.contentUser,range:{start:s.documentUser.positionAt(0),end:n}}];$i.send(e,[_])}}},ra=class{static cmd=`aventus.wc.import.viewElement`;static async run(e,t){let n=z.getInstance().getByUri(e);if(n){let r=n.documentUser.positionAt(n.contentUser.length),i=z.getInstance().getBuild(n.documentUser);if(i&&i.length>0){let a=i[0].tsFiles[e];if(a instanceof N){let i=a.getMissingVariablesInfo();if(t==-1&&(t=i.start),t==-1)return;if(i.text!=``){let a=n.contentUser.slice(0,t),o=n.contentUser.slice(t+1,n.contentUser.length),s=a+i.text+o,c=d.TextDocument.create(n.uri,T.TypeScript,n.versionUser+1,s);await n.triggerContentChange(c);let l=await n.getFormatting({insertSpaces:!0,tabSize:4});await n.applyTextEdits(l);let u=[{newText:n.contentUser,range:{start:n.documentUser.positionAt(0),end:r}}];$i.send(e,[u])}}}}}},ia=class{static cmd=`aventus.wc.import.viewMethod`;static async run(e,t){let n=z.getInstance().getByUri(e);if(n){let r=n.documentUser.positionAt(n.contentUser.length),i=z.getInstance().getBuild(n.documentUser);if(i&&i.length>0){let a=i[0].tsFiles[e];if(a instanceof N){let i=a.getMissingMethodsInfo();if(t==-1&&(t=i.start),t==-1)return;if(i.text!=``){let a=n.contentUser.slice(0,t),o=n.contentUser.slice(t+1,n.contentUser.length),s=a+i.text+o,c=d.TextDocument.create(n.uri,T.TypeScript,n.versionUser+1,s);await n.triggerContentChange(c);let l=await n.getFormatting({insertSpaces:!0,tabSize:4});await n.applyTextEdits(l);let u=[{newText:n.contentUser,range:{start:n.documentUser.positionAt(0),end:r}}];$i.send(e,[u])}}}}}},aa=class{static cmd=`aventus.rename`;static async run(e){if(!F.getInstance().settings.updateImportOnRename||!e)return;let t=[];for(let n of e){let e=n.newUri,r=n.oldUri,i=L(e),a=L(r),o,s=!0;if((0,u.existsSync)(i)?o=i:(s=!1,o=a),(0,u.statSync)(o).isDirectory()){let n=i=>{let a=(0,u.readdirSync)(i);for(let o of a){let a=(0,f.join)(i,o);if((0,u.statSync)(a).isDirectory())n(a);else{let n=I(a);s?t.push({newUri:n,oldUri:n.replace(e,r)}):t.push({newUri:n.replace(r,e),oldUri:n})}}};n(o)}else t.push({oldUri:r,newUri:e})}let n=await P.getInstance().onRename(t),r={},i=z.getInstance();for(let e in n){let t=i.getByUri(e);t&&(await t.applyTextEdits(n[e]),r[L(t.uri)]=t.contentUser)}setTimeout(()=>{for(let e in r)(0,u.writeFileSync)(e,r[e])},500)}},oa=class{static cmd=`aventus.component.rename`;static async run(e){if(!e)return;e=e.toString();for(let t of[E.ComponentView,E.ComponentStyle])if(e.endsWith(t)){e=e.slice(0,-t.length)+E.ComponentLogic;break}let t=e.split(`/`),n=t[t.length-1].replace(E.ComponentLogic,``),r=await $.Input({title:`New name`,value:n,validations:[{message:`Your name isn't valid`,regex:`^[_A-Za-z0-9-]+$`}]});if(!r)return;let i=z.getInstance().getByUri(e);if(i&&i instanceof O){let e=z.getInstance(),t=i.documentUser.uri.split(`/`),n=t[t.length-1].replace(E.ComponentLogic,``),a=hs(n),o=i.folderUri,s=o.replace(RegExp(a+`$`),r),c=RegExp(`(class +)`+a+` `).exec(i.contentUser),l={};if(c){let t=c.index+c[1].length,n=i.documentUser.positionAt(t),a=await i.getRename(n,r);if(a&&a.changes)for(let t in a.changes){if(!l[t]){let n=e.getByUri(t);if(!n)continue;l[t]=n}let n=a.changes[t];await l[t].applyTextEdits(n)}}let f=[],p=e=>{let t=o+`/`+n+e;if((0,u.existsSync)(L(t))){let n=s+`/`+r+e;f.push({oldUri:t,newUri:n})}};p(E.ComponentLogic),p(E.ComponentStyle),p(E.ComponentView);let m=await P.getInstance().onRename(f);for(let t in m){if(!l[t]){let n=e.getByUri(t);if(!n)continue;l[t]=n}await l[t].applyTextEdits(m[t])}setTimeout(()=>{for(let e in l)(0,u.writeFileSync)(L(e),l[e].contentUser);(0,u.mkdirSync)(L(s));for(let t of f){let n=t.oldUri,r=t.newUri;(0,u.renameSync)(L(n),L(r)),Wi.send(n);let i=e.getByUri(n);i&&(e.registerFile(d.TextDocument.create(r,ns(r),1,i.contentUser)),e.onClose(i?.documentUser))}let t=L(o),n=(0,u.readdirSync)(t);n.length==0?(0,u.rmdirSync)(t):n.length==1&&n[0].endsWith(`.js`)&&(0,u.rmSync)(t,{recursive:!0,force:!0})},500)}}},sa=class{static cmd=`aventus.filesystem.openAventus`;static async run(){let e=$.savePath;(0,u.existsSync)(e)||(0,u.mkdirSync)(e);let t;switch((0,le.platform)()){case`win32`:t=`explorer`;break;case`linux`:t=`xdg-open`;break;case`darwin`:t=`open`;break}(0,ce.spawn)(t,[e],{detached:!0}).unref()}},ca=class{static waitingResponse={};static send(e,...t){return new Promise(n=>{let r=D();for(;this.waitingResponse[r]!=null;)r=D();this.waitingResponse[r]=e=>{n(e)};try{$.sendNotification(`aventus/popup`,r,e,t)}catch{delete this.waitingResponse[r],n(null)}})}static resolve(e,t){this.waitingResponse[e]&&(this.waitingResponse[e](t),delete this.waitingResponse[e])}},la=class{static cmd=`aventus.popupresponse`;static run(e,t){ca.resolve(e,t)}},ua=class{static waitingResponse={};static send(e){return new Promise(t=>{let n=D();for(;this.waitingResponse[n]!=null;)n=D();this.waitingResponse[n]=e=>{t(e)};try{$.sendNotification(`aventus/askinput`,n,e)}catch{delete this.waitingResponse[n],t(null)}})}static resolve(e,t){this.waitingResponse[e]&&(this.waitingResponse[e](t),delete this.waitingResponse[e])}},da=class{static cmd=`aventus.receiveinput`;static run(e,t){ua.resolve(e,t)}},fa=class{static waitingResponse={};static waitingOptions={};static waitingOptionIds={};static send(e,t){return new Promise(n=>{let r=D();for(;this.waitingResponse[r]!=null;)r=D();this.waitingOptions[r]=e;let i=e.map((e,t)=>`${r}:${t}`);this.waitingOptionIds[r]=i,this.waitingResponse[r]=e=>{n(e)};try{$.sendNotification(`aventus/askselect`,r,e.map((e,t)=>({...e,id:i[t]})),t)}catch{delete this.waitingResponse[r],delete this.waitingOptions[r],delete this.waitingOptionIds[r],n(null)}})}static resolve(e,t){if(this.waitingResponse[e]){if(t){let n=this.waitingOptions[e],r=this.waitingOptionIds[e].indexOf(t.id??``);if(r>=0)t=n[r];else if(t.id)t=null;else{let e=n.filter(e=>e.label===t.label);t=e.length===1?e[0]:null}}this.waitingResponse[e](t),delete this.waitingResponse[e],delete this.waitingOptions[e],delete this.waitingOptionIds[e]}}},pa=class{static cmd=`aventus.receiveselect`;static run(e,t){fa.resolve(e,t)}},ma=class{static waitingResponse={};static waitingOptions={};static waitingOptionIds={};static send(e,t){return new Promise(n=>{let r=D();for(;this.waitingResponse[r]!=null;)r=D();this.waitingOptions[r]=e;let i=e.map((e,t)=>`${r}:${t}`);this.waitingOptionIds[r]=i,this.waitingResponse[r]=e=>{n(e)};try{$.sendNotification(`aventus/askselectmultiple`,r,e.map((e,t)=>({...e,id:i[t]})),t)}catch{delete this.waitingResponse[r],delete this.waitingOptions[r],delete this.waitingOptionIds[r],n(null)}})}static resolve(e,t){if(this.waitingResponse[e]){if(t){let n=this.waitingOptions[e],r=this.waitingOptionIds[e],i=[];for(let e of t){let a=r.indexOf(e.id??``);if(a<0&&!e.id){let t=[];for(let r=0;r<n.length;r++){let i=n[r];i.label===e.label&&i.detail===e.detail&&t.push(r)}t.length===1&&(a=t[0])}if(a<0){t=null;break}i.push(n[a])}t&&=i}this.waitingResponse[e](t),delete this.waitingResponse[e],delete this.waitingOptions[e],delete this.waitingOptionIds[e]}}},ha=class{static cmd=`aventus.receiveselectmultiple`;static run(e,t){ma.resolve(e,t)}},ga=class{static cmd=`aventus.template.import`;static async run(){await $.templateManager?.selectTemplateToImport()}},_a=o(((e,t)=>{var n=require("child_process").exec,r=require("child_process").execSync,i=require("fs"),a=require("path"),o=i.access,s=i.accessSync,c=i.constants||i,l=process.platform==`win32`,u=function(e,t){o(e,c.F_OK,function(e){t(!e)})},d=function(e){try{return s(e,c.F_OK),!1}catch{return!0}},f=function(e,t){o(e,c.F_OK|c.X_OK,function(e){t(null,!e)})},p=function(e){try{return s(e,c.F_OK|c.X_OK),!0}catch{return!1}},m=function(e,t,r){u(e,function(i){if(!i){n(`command -v `+t+` 2>/dev/null && { echo >&1 `+t+`; exit 0; }`,function(e,t,n){r(null,!!t)});return}f(e,r)})},h=function(e,t,r){if(!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(e)){r(null,!1);return}n(`where `+t,function(e){e===null?r(null,!0):r(null,!1)})},g=function(e,t){if(d(e))try{return!!r(`command -v `+t+` 2>/dev/null && { echo >&1 `+t+`; exit 0; }`)}catch{return!1}return p(e)},_=function(e,t,n){if(!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(e))return!1;try{return!!r(`where `+t,{stdio:[]})}catch{return!1}},v=function(e){return/[^A-Za-z0-9_\/:=-]/.test(e)&&(e=`'`+e.replace(/'/g,`'\\''`)+`'`,e=e.replace(/^(?:'')+/g,``).replace(/\\'''/g,`\\'`)),e};l&&(v=function(e){if(/[\\]/.test(e)){var t=`"`+a.dirname(e)+`"`,n=`"`+a.basename(e)+`"`;return t+`:`+n}return`"`+e+`"`}),t.exports=function e(t,n){var r=v(t);if(!n&&typeof Promise<`u`)return new Promise(function(n,r){e(t,function(e,i){i?n(t):r(e)})});l?h(t,r,n):m(t,r,n)},t.exports.sync=function(e){var t=v(e);return l?_(e,t):g(e,t)}})),va=o(((e,t)=>{t.exports=_a()}))(),ya=class{static send(e,t,n){$.sendNotification(`aventus/sharp/compiling`,e,t,n)}},ba=class{static send(e,t){$.sendNotification(`aventus/addDebugFile`,e,t)}},xa=class e{static instance;static getInstance(){return this.instance||=new e,this.instance}files={};onNewFileUUID;onFileRemoveUUID;constructor(){this.onNewFile=this.onNewFile.bind(this),this.onFileRemove=this.onFileRemove.bind(this),this.onNewFileUUID=z.getInstance().onNewFile(this.onNewFile),this.onFileRemoveUUID=z.getInstance().onFileRemove(this.onFileRemove)}async onNewFile(e){e.uri.endsWith(E.CsharpConfig)&&(this.files[e.uri]=new Sa(e))}async onFileRemove(e){delete this.files[e]}destroy(){z.getInstance().removeOnNewFile(this.onNewFileUUID),z.getInstance().removeOnFileRemove(this.onFileRemoveUUID)}},Sa=class{_file;get file(){return this._file}constructor(e){this._file=e,this.addEvents()}uuidEvents={onContentChange:``,onValidate:``,onSave:``,onDelete:``,onCompletion:``,onCompletionResolve:``,onHover:``,onDefinition:``,onFormatting:``,onCodeAction:``,onReferences:``,onCodeLens:``,onRename:``};addEvents(){this.uuidEvents.onContentChange=this.file.onContentChange(this.onContentChange.bind(this)),this.uuidEvents.onValidate=this.file.onValidate(this._onValidate.bind(this)),this.uuidEvents.onSave=this.file.onSave(this.onSave.bind(this)),this.uuidEvents.onDelete=this.file.onDelete(this._onDelete.bind(this)),this.uuidEvents.onCompletion=this.file.onCompletion(this.onCompletion.bind(this)),this.uuidEvents.onCompletionResolve=this.file.onCompletionResolve(this.onCompletionResolve.bind(this)),this.uuidEvents.onHover=this.file.onHover(this.onHover.bind(this)),this.uuidEvents.onDefinition=this.file.onDefinition(this.onDefinition.bind(this)),this.uuidEvents.onFormatting=this.file.onFormatting(this.onFormatting.bind(this)),this.uuidEvents.onCodeAction=this.file.onCodeAction(this.onCodeAction.bind(this)),this.uuidEvents.onReferences=this.file.onReferences(this.onReferences.bind(this)),this.uuidEvents.onCodeLens=this.file.onCodeLens(this.onCodeLens.bind(this)),this.uuidEvents.onRename=this.file.onRename(this.onRename.bind(this))}removeEvents(){this.file.removeOnContentChange(this.uuidEvents.onContentChange),this.file.removeOnValidate(this.uuidEvents.onValidate),this.file.removeOnSave(this.uuidEvents.onSave),this.file.removeOnDelete(this.uuidEvents.onDelete),this.file.removeOnCompletion(this.uuidEvents.onCompletion),this.file.removeOnCompletionResolve(this.uuidEvents.onCompletionResolve),this.file.removeOnHover(this.uuidEvents.onHover),this.file.removeOnDefinition(this.uuidEvents.onDefinition),this.file.removeOnFormatting(this.uuidEvents.onFormatting),this.file.removeOnCodeAction(this.uuidEvents.onCodeAction),this.file.removeOnReferences(this.uuidEvents.onReferences),this.file.removeOnCodeLens(this.uuidEvents.onCodeLens),this.file.removeOnRename(this.uuidEvents.onRename)}async validate(){this.file instanceof O&&await this.file.validate()}triggerSave(){this.file instanceof O&&this.file.triggerSave()}async triggerContentChange(){this.file instanceof O&&await this.file.triggerContentChange(this.file.documentUser)}async _onValidate(){return await this.onValidate()}async onContentChange(){}async onValidate(){return Qe.getInstance().validate(this.file)}async onSave(){}async onDelete(){}async _onDelete(){await this.onDelete(),this.removeEvents()}async onCompletion(e,t){return Qe.getInstance().doComplete(e,t)}async onCompletionResolve(e,t){return Qe.getInstance().doResolve(t)}async onHover(e,t){return Qe.getInstance().doHover(e,t)}async onDefinition(e,t){return null}async onFormatting(e,t,n){return Qe.getInstance().format(e,t,n)}async onCodeAction(e,t){return[]}async onReferences(e,t){return[]}async onCodeLens(e){return[]}async onRename(e,t,n){return null}},Ca=class{static cmd=`aventus.sharp.export`;static isCompiling=!1;static async run(e){if(this.isCompiling)return;if(!(0,va.sync)(`dotnet`)){$.showErrorMessage(`Dotnet isn't installed on your system`);return}if(!(0,va.sync)(`csharp-converter`))try{if(await $.ask(`csharp-converter is missing. Can I install it?`)&&await $.showLoadingMessage(`Installing csharp-converter`,async()=>{await Yo(`dotnet tool install --global AventusSharp.Converter`)}),!(0,va.sync)(`csharp-converter`)){$.showErrorMessage(`Can't find the converter. Run the command : dotnet tool install --global AventusSharp.Converter`);return}}catch(e){$.showErrorMessage(e+``);return}if(!e||!e.endsWith(E.CsharpConfig)){let t=Object.keys(xa.getInstance().files);if(t.length==1)e=t[0];else if(t.length>1){let n=[];for(let e of t)n.push({label:e});let r=await $.Select(n,{title:`Project to compile`});if(r)e=r.label;else return}else{$.showErrorMessage(`No aventus.sharp.avt found`);return}}let t=``;try{let n=(0,u.readFileSync)(L(e),`utf-8`);t=JSON.parse(n).csProj}catch(e){$.error(e),$.showErrorMessage(`Invalid Sharp project configuration: ${e}`);return}this.isCompiling=!0,ya.send(t,`compiling`);try{let{stdout:n,stderr:r}=await Zo(`csharp-converter`,[L(e)]),i=n.toString(),a=r.toString(),o=i.includes(`Error : `)?i:a.includes(`Error : `)?a:null;if(!o)a.trim()&&$.showWarningMessage(a.trim()),ya.send(t,`success`);else{console.clear(),$.error(o);let e=`csharp_errors`;ba.send(e,o),ya.send(t,`error`,[{title:`C# error`,file:e}])}}catch(e){let n=e.stderr?.trim()||String(e);$.showErrorMessage(n),ba.send(`csharp_errors`,n),ya.send(t,`error`,[{title:`C# error`,file:`csharp_errors`}])}this.isCompiling=!1}},wa=class{static cmd=`aventus.reloadSettings`;static async run(){$.refreshSettings()}},Ta=class{static cmd=`aventus.wc.create.cssvar`;static async run(e,t){if(!e||typeof t!=`number`)return;let n=await $.Input({title:`Provide a name for your variable`});if(!n)return;let r=await $.Input({title:`Provide a default value for your variable`}),i=z.getInstance().getByUri(e);if(i){let a=/[A-Z]?[a-z]+|[A-Z]+(?![a-z])|[0-9]+[a-z]*/g,o=i.name.match(/([A-Z][a-z]*)|([0-9]+[a-z]*)/g)?.join(`-`).toLowerCase()??i.name,s=n.match(a)?.join(`-`).toLowerCase()??n,c=r?`, `+r:``,l=i.documentUser.positionAt(i.contentUser.length),u=`--_${o}-${s}: var(--${o}-${s}${c});`,f=i.contentUser.slice(0,t),p=i.contentUser.slice(t+1,i.contentUser.length),m=f+u+p,h=d.TextDocument.create(i.uri,T.SCSS,i.versionUser+1,m);await i.triggerContentChange(h);let g=await i.getFormatting({insertSpaces:!0,tabSize:4});await i.applyTextEdits(g);let _=[{newText:i.contentUser,range:{start:{character:0,line:0},end:l}}];$i.send(e,[_])}}},Ea=class{static cmd=`aventus.storybook.build`;static async run(){let e=[],t=P.getInstance().getAllBuildsWithStory();for(let n of t)e.push({label:n.name,detail:n.uri});if(e.length===0){$.showWarningMessage(`No Storybook build was found.`);return}let n=await $.Select(e,{title:`Story to build`});if(n&&e.some(e=>e.label===n.label&&e.detail===n.detail)){let e=n.detail??``,t=n.label;return await P.getInstance().getProjectByUri(e)?.getBuild(t)?.buildStorybook()}}},Da=class{static cmd=`aventus.template.import_project`;static async run(){await $.templateManager?.selectProjectToImport(!1)}},Oa=class{static cmd=`aventus.npm.build`;static async run(){let e=[],t=P.getInstance().getAllBuildsWithNpm();for(let n of t)e.push({label:n.name,detail:n.uri});if(e.length===0){$.showWarningMessage(`No package to build was found.`);return}let n=e.length==1?e[0]:await $.Select(e,{title:`Package to build`});if(n&&e.some(e=>e.label===n.label&&e.detail===n.detail)){let e=n.detail??``,t=n.label;return await P.getInstance().getProjectByUri(e)?.getBuild(t)?.buildNpm()}}};const ka={$schema:`foo://aventus/i18n.json`,title:`JSON Schema for Aventus I18n`,description:`JSON Schema for Aventus I18n`,type:`object`,additionalProperties:{type:`object`,additionalProperties:{type:`string`}}};var Aa=class e{static empty=`ⵌⵌ`;static instance;static getInstance(){return this.instance||=new e,this.instance}languageService;constructor(){this.languageService=(0,h.getLanguageService)({}),this.languageService.configure({allowComments:!0,schemas:[{fileMatch:[`**`+E.I18n],uri:ka.$schema??``,schema:ka}]})}async validate(t){let n=t.file.documentUser,r=this.languageService.parseJSONDocument(n),i=await this.languageService.doValidation(n,r),a=r.syntaxErrors;if(!r.root||a?.length)return i.length==0&&i.push(ls(n,`Can't parse the json`)),i.map(e=>({...e,severity:h.DiagnosticSeverity.Error}));try{let a=t.parsed??{},o=(t.build.buildConfig.i18n?.locales??[]).filter(e=>!ve.isReservedI18nLocale(e));for(let e of r.root.children??[]){if(e.type!==`property`)continue;let t=e.children?.[0];if(t&&ve.isReservedI18nLocale(String(t.value))&&i.push(us(n,`Translation key ${t.value} is not allowed`,t.offset,t.offset+t.length)),e.children&&e.children.length>1){let t=e.children[1].children??[];for(let e of t){if(e.type!==`property`)continue;let t=e.children[0];t&&ve.isReservedI18nLocale(String(t.value))&&i.push(us(n,`Locale ${t.value} is not allowed`,t.offset,t.offset+t.length))}}}for(let r in a){if(t.isGlobal){let e=t.build.tsLanguageService?.i18nFiles??{};Object.values(e).filter(e=>e!==t&&e.isGlobal&&e.parsed&&Object.hasOwn(e.parsed,r)).length>0&&i.push(us(n,`Duplicate translation key ${r} across global files`,a[r].keyStart,a[r].keyEnd))}for(let n in a[r].locales){let s=a[r].locales[n];o.includes(n)||i.push(ds(t.file.documentUser,`Locale not needed`,s.localeStart,s.localeEnd)),s.value==e.empty&&i.push(ds(t.file.documentUser,`Translation not set`,s.valueStart,s.valueEnd))}let s=[];for(let e of o)a[r].locales[e]===void 0&&s.push(e);s.length>0&&i.push(us(t.file.documentUser,`Missing locales `+s.join(`, `),a[r].keyStart,a[r].keyEnd))}return i}catch{i.length==0&&i.push(ls(n,`Can't parse the json`))}for(let e of i)e.severity=h.DiagnosticSeverity.Error;return i}async format(e,t,n){try{let t;try{let n=JSON.parse(e.contentUser);t=JSON.stringify(this.sortObj(n),null,4)}catch{let n=this.languageService.parseJSONDocument(e.documentUser),r=n.root,i=n.syntaxErrors;if(!r||r.type!==`object`||i?.some(e=>e.code!==h.ErrorCode.TrailingComma))return[];let a=e.contentUser.slice(0,r.offset)+this.sortJsoncObject(e.contentUser,r)+e.contentUser.slice(r.offset+r.length),o=d.TextDocument.create(e.uri,e.documentUser.languageId,e.documentUser.version,a),s=await this.languageService.format(o,void 0,{tabSize:4,insertSpaces:!0});t=d.TextDocument.applyEdits(o,s)}return[{newText:t,range:{start:e.documentUser.positionAt(0),end:e.documentUser.positionAt(e.contentUser.length)}}]}catch{}return[]}sortJsoncObject(e,t){let n=t.properties,r=t.offset+1,i=[];for(let t of n){let n=t.valueNode,a=this.removeJsoncComma(e.slice(r,t.offset));r=t.offset+t.length;let o=e.slice(t.offset,r);if(n?.type===`object`){let r=n.offset-t.offset;o=o.slice(0,r)+this.sortJsoncObject(e,n)+o.slice(r+n.length)}i.push({key:t.keyNode.value,text:a+o})}let a=this.removeJsoncComma(e.slice(r,t.offset+t.length-1));return i.sort((e,t)=>e.key<t.key?-1:+(e.key>t.key)),`{`+i.map(e=>e.text).join(`,`)+a+`}`}removeJsoncComma(e){return e.replace(/^(\s*),/,`$1`)}async codeAction(e,t){let n=[];try{let t=this.actionImportMissingLocales(e);t&&n.push(t)}catch{}return n}sortObj(t){return e.sortObj(t)}static sortObj(e){return Object.keys(e).sort().reduce((t,n)=>{let r=e[n];return t[n]=Object.keys(r).sort().reduce((e,t)=>(e[t]=r[t],e),{}),t},{})}actionImportMissingLocales(t){let n=t.file.documentUser,r=t.file.contentUser,i=this.languageService.parseJSONDocument(n),a=i.syntaxErrors,o=i.root;if(o?.type!==`object`||a?.length){$.showErrorMessage(`The i18n file is malformed. Fix its JSON before importing missing locales.`);return}let s=[],c=(t.build.buildConfig.i18n?.locales??[]).filter(e=>!ve.isReservedI18nLocale(e));for(let t of o.properties){if(ve.isReservedI18nLocale(String(t.keyNode.value)))continue;let i=t.valueNode;if(i?.type!==`object`)continue;let a=c.filter(e=>!i.properties.some(t=>t.keyNode.value===e));if(a.length===0)continue;let o=i.properties[0],l=o?.offset??i.offset+1,u=r.lastIndexOf(`
|
|
609
|
+
`,f=s.contentUser.slice(0,t),p=s.contentUser.slice(t+1,s.contentUser.length),m=f+u+p,h=d.TextDocument.create(s.uri,T.TypeScript,s.versionUser+1,m);await s.triggerContentChange(h);let g=await s.getFormatting({insertSpaces:!0,tabSize:4});await s.applyTextEdits(g);let _=[{newText:s.contentUser,range:{start:s.documentUser.positionAt(0),end:n}}];$i.send(e,[_])}}},ra=class{static cmd=`aventus.wc.import.viewElement`;static async run(e,t){let n=z.getInstance().getByUri(e);if(n){let r=n.documentUser.positionAt(n.contentUser.length),i=z.getInstance().getBuild(n.documentUser);if(i&&i.length>0){let a=i[0].tsFiles[e];if(a instanceof N){let i=a.getMissingVariablesInfo();if(t==-1&&(t=i.start),t==-1)return;if(i.text!=``){let a=n.contentUser.slice(0,t),o=n.contentUser.slice(t+1,n.contentUser.length),s=a+i.text+o,c=d.TextDocument.create(n.uri,T.TypeScript,n.versionUser+1,s);await n.triggerContentChange(c);let l=await n.getFormatting({insertSpaces:!0,tabSize:4});await n.applyTextEdits(l);let u=[{newText:n.contentUser,range:{start:n.documentUser.positionAt(0),end:r}}];$i.send(e,[u])}}}}}},ia=class{static cmd=`aventus.wc.import.viewMethod`;static async run(e,t){let n=z.getInstance().getByUri(e);if(n){let r=n.documentUser.positionAt(n.contentUser.length),i=z.getInstance().getBuild(n.documentUser);if(i&&i.length>0){let a=i[0].tsFiles[e];if(a instanceof N){let i=a.getMissingMethodsInfo();if(t==-1&&(t=i.start),t==-1)return;if(i.text!=``){let a=n.contentUser.slice(0,t),o=n.contentUser.slice(t+1,n.contentUser.length),s=a+i.text+o,c=d.TextDocument.create(n.uri,T.TypeScript,n.versionUser+1,s);await n.triggerContentChange(c);let l=await n.getFormatting({insertSpaces:!0,tabSize:4});await n.applyTextEdits(l);let u=[{newText:n.contentUser,range:{start:n.documentUser.positionAt(0),end:r}}];$i.send(e,[u])}}}}}},aa=class{static cmd=`aventus.rename`;static async run(e){if(!F.getInstance().settings.updateImportOnRename||!e)return;let t=[];for(let n of e){let e=n.newUri,r=n.oldUri,i=L(e),a=L(r),o,s=!0;if((0,u.existsSync)(i)?o=i:(s=!1,o=a),(0,u.statSync)(o).isDirectory()){let n=i=>{let a=(0,u.readdirSync)(i);for(let o of a){let a=(0,f.join)(i,o);if((0,u.statSync)(a).isDirectory())n(a);else{let n=I(a);s?t.push({newUri:n,oldUri:n.replace(e,r)}):t.push({newUri:n.replace(r,e),oldUri:n})}}};n(o)}else t.push({oldUri:r,newUri:e})}let n=await P.getInstance().onRename(t),r={},i=z.getInstance();for(let e in n){let t=i.getByUri(e);t&&(await t.applyTextEdits(n[e]),r[L(t.uri)]=t.contentUser)}setTimeout(()=>{for(let e in r)(0,u.writeFileSync)(e,r[e])},500)}},oa=class{static cmd=`aventus.component.rename`;static async run(e){if(!e)return;e=e.toString();for(let t of[E.ComponentView,E.ComponentStyle])if(e.endsWith(t)){e=e.slice(0,-t.length)+E.ComponentLogic;break}let t=e.split(`/`),n=t[t.length-1].replace(E.ComponentLogic,``),r=await $.Input({title:`New name`,value:n,validations:[{message:`Your name isn't valid`,regex:`^[_A-Za-z0-9-]+$`}]});if(!r)return;let i=z.getInstance().getByUri(e);if(i&&i instanceof O){let e=z.getInstance(),t=i.documentUser.uri.split(`/`),n=t[t.length-1].replace(E.ComponentLogic,``),a=hs(n),o=i.folderUri,s=o.replace(RegExp(a+`$`),r),c=RegExp(`(class +)`+a+` `).exec(i.contentUser),l={};if(c){let t=c.index+c[1].length,n=i.documentUser.positionAt(t),a=await i.getRename(n,r);if(a&&a.changes)for(let t in a.changes){if(!l[t]){let n=e.getByUri(t);if(!n)continue;l[t]=n}let n=a.changes[t];await l[t].applyTextEdits(n)}}let f=[],p=e=>{let t=o+`/`+n+e;if((0,u.existsSync)(L(t))){let n=s+`/`+r+e;f.push({oldUri:t,newUri:n})}};p(E.ComponentLogic),p(E.ComponentStyle),p(E.ComponentView);let m=await P.getInstance().onRename(f);for(let t in m){if(!l[t]){let n=e.getByUri(t);if(!n)continue;l[t]=n}await l[t].applyTextEdits(m[t])}setTimeout(()=>{for(let e in l)(0,u.writeFileSync)(L(e),l[e].contentUser);(0,u.mkdirSync)(L(s));for(let t of f){let n=t.oldUri,r=t.newUri;(0,u.renameSync)(L(n),L(r)),Wi.send(n);let i=e.getByUri(n);i&&(e.registerFile(d.TextDocument.create(r,ns(r),1,i.contentUser)),e.onClose(i?.documentUser))}let t=L(o),n=(0,u.readdirSync)(t);n.length==0?(0,u.rmdirSync)(t):n.length==1&&n[0].endsWith(`.js`)&&(0,u.rmSync)(t,{recursive:!0,force:!0})},500)}}},sa=class{static cmd=`aventus.filesystem.openAventus`;static async run(){let e=$.savePath;(0,u.existsSync)(e)||(0,u.mkdirSync)(e);let t;switch((0,le.platform)()){case`win32`:t=`explorer`;break;case`linux`:t=`xdg-open`;break;case`darwin`:t=`open`;break}(0,ce.spawn)(t,[e],{detached:!0}).unref()}},ca=class{static waitingResponse={};static send(e,...t){return new Promise(n=>{let r=D();for(;this.waitingResponse[r]!=null;)r=D();this.waitingResponse[r]=e=>{n(e)};try{$.sendNotification(`aventus/popup`,r,e,t)}catch{delete this.waitingResponse[r],n(null)}})}static resolve(e,t){this.waitingResponse[e]&&(this.waitingResponse[e](t),delete this.waitingResponse[e])}},la=class{static cmd=`aventus.popupresponse`;static run(e,t){ca.resolve(e,t)}},ua=class{static waitingResponse={};static send(e){return new Promise(t=>{let n=D();for(;this.waitingResponse[n]!=null;)n=D();this.waitingResponse[n]=e=>{t(e)};try{$.sendNotification(`aventus/askinput`,n,e)}catch{delete this.waitingResponse[n],t(null)}})}static resolve(e,t){this.waitingResponse[e]&&(this.waitingResponse[e](t),delete this.waitingResponse[e])}},da=class{static cmd=`aventus.receiveinput`;static run(e,t){ua.resolve(e,t)}},fa=class{static waitingResponse={};static waitingOptions={};static waitingOptionIds={};static send(e,t){return new Promise(n=>{let r=D();for(;this.waitingResponse[r]!=null;)r=D();this.waitingOptions[r]=e;let i=e.map((e,t)=>`${r}:${t}`);this.waitingOptionIds[r]=i,this.waitingResponse[r]=e=>{n(e)};try{$.sendNotification(`aventus/askselect`,r,e.map((e,t)=>({...e,id:i[t]})),t)}catch{delete this.waitingResponse[r],delete this.waitingOptions[r],delete this.waitingOptionIds[r],n(null)}})}static resolve(e,t){if(this.waitingResponse[e]){if(t){let n=this.waitingOptions[e],r=this.waitingOptionIds[e].indexOf(t.id??``);if(r>=0)t=n[r];else if(t.id)t=null;else{let e=n.filter(e=>e.label===t.label);t=e.length===1?e[0]:null}}this.waitingResponse[e](t),delete this.waitingResponse[e],delete this.waitingOptions[e],delete this.waitingOptionIds[e]}}},pa=class{static cmd=`aventus.receiveselect`;static run(e,t){fa.resolve(e,t)}},ma=class{static waitingResponse={};static waitingOptions={};static waitingOptionIds={};static send(e,t){return new Promise(n=>{let r=D();for(;this.waitingResponse[r]!=null;)r=D();this.waitingOptions[r]=e;let i=e.map((e,t)=>`${r}:${t}`);this.waitingOptionIds[r]=i,this.waitingResponse[r]=e=>{n(e)};try{$.sendNotification(`aventus/askselectmultiple`,r,e.map((e,t)=>({...e,id:i[t]})),t)}catch{delete this.waitingResponse[r],delete this.waitingOptions[r],delete this.waitingOptionIds[r],n(null)}})}static resolve(e,t){if(this.waitingResponse[e]){if(t){let n=this.waitingOptions[e],r=this.waitingOptionIds[e],i=[];for(let e of t){let a=r.indexOf(e.id??``);if(a<0&&!e.id){let t=[];for(let r=0;r<n.length;r++){let i=n[r];i.label===e.label&&i.detail===e.detail&&t.push(r)}t.length===1&&(a=t[0])}if(a<0){t=null;break}i.push(n[a])}t&&=i}this.waitingResponse[e](t),delete this.waitingResponse[e],delete this.waitingOptions[e],delete this.waitingOptionIds[e]}}},ha=class{static cmd=`aventus.receiveselectmultiple`;static run(e,t){ma.resolve(e,t)}},ga=class{static cmd=`aventus.template.import`;static async run(){await $.templateManager?.selectTemplateToImport()}},_a=o(((e,t)=>{var n=require("child_process").exec,r=require("child_process").execSync,i=require("fs"),a=require("path"),o=i.access,s=i.accessSync,c=i.constants||i,l=process.platform==`win32`,u=function(e,t){o(e,c.F_OK,function(e){t(!e)})},d=function(e){try{return s(e,c.F_OK),!1}catch{return!0}},f=function(e,t){o(e,c.F_OK|c.X_OK,function(e){t(null,!e)})},p=function(e){try{return s(e,c.F_OK|c.X_OK),!0}catch{return!1}},m=function(e,t,r){u(e,function(i){if(!i){n(`command -v `+t+` 2>/dev/null && { echo >&1 `+t+`; exit 0; }`,function(e,t,n){r(null,!!t)});return}f(e,r)})},h=function(e,t,r){if(!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(e)){r(null,!1);return}n(`where `+t,function(e){e===null?r(null,!0):r(null,!1)})},g=function(e,t){if(d(e))try{return!!r(`command -v `+t+` 2>/dev/null && { echo >&1 `+t+`; exit 0; }`)}catch{return!1}return p(e)},_=function(e,t,n){if(!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(e))return!1;try{return!!r(`where `+t,{stdio:[]})}catch{return!1}},v=function(e){return/[^A-Za-z0-9_\/:=-]/.test(e)&&(e=`'`+e.replace(/'/g,`'\\''`)+`'`,e=e.replace(/^(?:'')+/g,``).replace(/\\'''/g,`\\'`)),e};l&&(v=function(e){if(/[\\]/.test(e)){var t=`"`+a.dirname(e)+`"`,n=`"`+a.basename(e)+`"`;return t+`:`+n}return`"`+e+`"`}),t.exports=function e(t,n){var r=v(t);if(!n&&typeof Promise<`u`)return new Promise(function(n,r){e(t,function(e,i){i?n(t):r(e)})});l?h(t,r,n):m(t,r,n)},t.exports.sync=function(e){var t=v(e);return l?_(e,t):g(e,t)}})),va=o(((e,t)=>{t.exports=_a()}))(),ya=class{static send(e,t,n){$.sendNotification(`aventus/sharp/compiling`,e,t,n)}},ba=class{static send(e,t){$.sendNotification(`aventus/addDebugFile`,e,t)}},xa=class e{static instance;static getInstance(){return this.instance||=new e,this.instance}files={};onNewFileUUID;onFileRemoveUUID;constructor(){this.onNewFile=this.onNewFile.bind(this),this.onFileRemove=this.onFileRemove.bind(this),this.onNewFileUUID=z.getInstance().onNewFile(this.onNewFile),this.onFileRemoveUUID=z.getInstance().onFileRemove(this.onFileRemove)}async onNewFile(e){e.uri.endsWith(E.CsharpConfig)&&(this.files[e.uri]=new Sa(e))}async onFileRemove(e){delete this.files[e]}destroy(){z.getInstance().removeOnNewFile(this.onNewFileUUID),z.getInstance().removeOnFileRemove(this.onFileRemoveUUID)}},Sa=class{_file;get file(){return this._file}constructor(e){this._file=e,this.addEvents()}uuidEvents={onContentChange:``,onValidate:``,onSave:``,onDelete:``,onCompletion:``,onCompletionResolve:``,onHover:``,onDefinition:``,onFormatting:``,onCodeAction:``,onReferences:``,onCodeLens:``,onRename:``};addEvents(){this.uuidEvents.onContentChange=this.file.onContentChange(this.onContentChange.bind(this)),this.uuidEvents.onValidate=this.file.onValidate(this._onValidate.bind(this)),this.uuidEvents.onSave=this.file.onSave(this.onSave.bind(this)),this.uuidEvents.onDelete=this.file.onDelete(this._onDelete.bind(this)),this.uuidEvents.onCompletion=this.file.onCompletion(this.onCompletion.bind(this)),this.uuidEvents.onCompletionResolve=this.file.onCompletionResolve(this.onCompletionResolve.bind(this)),this.uuidEvents.onHover=this.file.onHover(this.onHover.bind(this)),this.uuidEvents.onDefinition=this.file.onDefinition(this.onDefinition.bind(this)),this.uuidEvents.onFormatting=this.file.onFormatting(this.onFormatting.bind(this)),this.uuidEvents.onCodeAction=this.file.onCodeAction(this.onCodeAction.bind(this)),this.uuidEvents.onReferences=this.file.onReferences(this.onReferences.bind(this)),this.uuidEvents.onCodeLens=this.file.onCodeLens(this.onCodeLens.bind(this)),this.uuidEvents.onRename=this.file.onRename(this.onRename.bind(this))}removeEvents(){this.file.removeOnContentChange(this.uuidEvents.onContentChange),this.file.removeOnValidate(this.uuidEvents.onValidate),this.file.removeOnSave(this.uuidEvents.onSave),this.file.removeOnDelete(this.uuidEvents.onDelete),this.file.removeOnCompletion(this.uuidEvents.onCompletion),this.file.removeOnCompletionResolve(this.uuidEvents.onCompletionResolve),this.file.removeOnHover(this.uuidEvents.onHover),this.file.removeOnDefinition(this.uuidEvents.onDefinition),this.file.removeOnFormatting(this.uuidEvents.onFormatting),this.file.removeOnCodeAction(this.uuidEvents.onCodeAction),this.file.removeOnReferences(this.uuidEvents.onReferences),this.file.removeOnCodeLens(this.uuidEvents.onCodeLens),this.file.removeOnRename(this.uuidEvents.onRename)}async validate(){this.file instanceof O&&await this.file.validate()}triggerSave(){this.file instanceof O&&this.file.triggerSave()}async triggerContentChange(){this.file instanceof O&&await this.file.triggerContentChange(this.file.documentUser)}async _onValidate(){return await this.onValidate()}async onContentChange(){}async onValidate(){return Qe.getInstance().validate(this.file)}async onSave(){}async onDelete(){}async _onDelete(){await this.onDelete(),this.removeEvents()}async onCompletion(e,t){return Qe.getInstance().doComplete(e,t)}async onCompletionResolve(e,t){return Qe.getInstance().doResolve(t)}async onHover(e,t){return Qe.getInstance().doHover(e,t)}async onDefinition(e,t){return null}async onFormatting(e,t,n){return Qe.getInstance().format(e,t,n)}async onCodeAction(e,t){return[]}async onReferences(e,t){return[]}async onCodeLens(e){return[]}async onRename(e,t,n){return null}},Ca=class{static cmd=`aventus.sharp.export`;static isCompiling=!1;static async run(e){if(this.isCompiling)return;if(!(0,va.sync)(`dotnet`)){$.showErrorMessage(`Dotnet isn't installed on your system`);return}if(!(0,va.sync)(`csharp-converter`))try{if(await $.ask(`csharp-converter is missing. Can I install it?`)&&await $.showLoadingMessage(`Installing csharp-converter`,async()=>{await Yo(`dotnet tool install --global AventusSharp.Converter`)}),!(0,va.sync)(`csharp-converter`)){$.showErrorMessage(`Can't find the converter. Run the command : dotnet tool install --global AventusSharp.Converter`);return}}catch(e){$.showErrorMessage(e+``);return}if(!e||!e.endsWith(E.CsharpConfig)){let t=Object.keys(xa.getInstance().files);if(t.length==1)e=t[0];else if(t.length>1){let n=[];for(let e of t)n.push({label:e});let r=await $.Select(n,{title:`Project to compile`});if(r)e=r.label;else return}else{$.showErrorMessage(`No aventus.sharp.avt found`);return}}let t=``;try{let n=(0,u.readFileSync)(L(e),`utf-8`);t=JSON.parse(n).csProj}catch(e){$.error(e),$.showErrorMessage(`Invalid Sharp project configuration: ${e}`);return}this.isCompiling=!0,ya.send(t,`compiling`);try{let{stdout:n,stderr:r}=await Zo(`csharp-converter`,[L(e)]),i=n.toString(),a=r.toString(),o=i.includes(`Error : `)?i:a.includes(`Error : `)?a:null;if(!o)a.trim()&&$.showWarningMessage(a.trim()),ya.send(t,`success`);else{console.clear(),$.error(o);let e=`csharp_errors`;ba.send(e,o),ya.send(t,`error`,[{title:`C# error`,file:e}])}}catch(e){let n=e.stderr?.trim()||String(e);$.showErrorMessage(n),ba.send(`csharp_errors`,n),ya.send(t,`error`,[{title:`C# error`,file:`csharp_errors`}])}this.isCompiling=!1}},wa=class{static cmd=`aventus.reloadSettings`;static async run(){$.refreshSettings()}},Ta=class{static cmd=`aventus.wc.create.cssvar`;static async run(e,t){if(!e||typeof t!=`number`)return;let n=await $.Input({title:`Provide a name for your variable`});if(!n)return;let r=await $.Input({title:`Provide a default value for your variable`}),i=z.getInstance().getByUri(e);if(i){let a=/[A-Z]?[a-z]+|[A-Z]+(?![a-z])|[0-9]+[a-z]*/g,o=i.name.match(/([A-Z][a-z]*)|([0-9]+[a-z]*)/g)?.join(`-`).toLowerCase()??i.name,s=n.match(a)?.join(`-`).toLowerCase()??n,c=r?`, `+r:``,l=i.documentUser.positionAt(i.contentUser.length),u=`--_${o}-${s}: var(--${o}-${s}${c});`,f=i.contentUser.slice(0,t),p=i.contentUser.slice(t+1,i.contentUser.length),m=f+u+p,h=d.TextDocument.create(i.uri,T.SCSS,i.versionUser+1,m);await i.triggerContentChange(h);let g=await i.getFormatting({insertSpaces:!0,tabSize:4});await i.applyTextEdits(g);let _=[{newText:i.contentUser,range:{start:{character:0,line:0},end:l}}];$i.send(e,[_])}}},Ea=class{static cmd=`aventus.storybook.build`;static async run(){let e=[],t=P.getInstance().getAllBuildsWithStory();for(let n of t)e.push({label:n.name,detail:n.uri});if(e.length===0){$.showWarningMessage(`No Storybook build was found.`);return}let n=await $.Select(e,{title:`Story to build`});if(n&&e.some(e=>e.label===n.label&&e.detail===n.detail)){let e=n.detail??``,t=n.label;return await P.getInstance().getProjectByUri(e)?.getBuild(t)?.buildStorybook()}}},Da=class{static cmd=`aventus.template.import_project`;static async run(e){await $.templateManager?.selectProjectToImport(!1,e)}},Oa=class{static cmd=`aventus.npm.build`;static async run(){let e=[],t=P.getInstance().getAllBuildsWithNpm();for(let n of t)e.push({label:n.name,detail:n.uri});if(e.length===0){$.showWarningMessage(`No package to build was found.`);return}let n=e.length==1?e[0]:await $.Select(e,{title:`Package to build`});if(n&&e.some(e=>e.label===n.label&&e.detail===n.detail)){let e=n.detail??``,t=n.label;return await P.getInstance().getProjectByUri(e)?.getBuild(t)?.buildNpm()}}};const ka={$schema:`foo://aventus/i18n.json`,title:`JSON Schema for Aventus I18n`,description:`JSON Schema for Aventus I18n`,type:`object`,additionalProperties:{type:`object`,additionalProperties:{type:`string`}}};var Aa=class e{static empty=`ⵌⵌ`;static instance;static getInstance(){return this.instance||=new e,this.instance}languageService;constructor(){this.languageService=(0,h.getLanguageService)({}),this.languageService.configure({allowComments:!0,schemas:[{fileMatch:[`**`+E.I18n],uri:ka.$schema??``,schema:ka}]})}async validate(t){let n=t.file.documentUser,r=this.languageService.parseJSONDocument(n),i=await this.languageService.doValidation(n,r),a=r.syntaxErrors;if(!r.root||a?.length)return i.length==0&&i.push(ls(n,`Can't parse the json`)),i.map(e=>({...e,severity:h.DiagnosticSeverity.Error}));try{let a=t.parsed??{},o=(t.build.buildConfig.i18n?.locales??[]).filter(e=>!ve.isReservedI18nLocale(e));for(let e of r.root.children??[]){if(e.type!==`property`)continue;let t=e.children?.[0];if(t&&ve.isReservedI18nLocale(String(t.value))&&i.push(us(n,`Translation key ${t.value} is not allowed`,t.offset,t.offset+t.length)),e.children&&e.children.length>1){let t=e.children[1].children??[];for(let e of t){if(e.type!==`property`)continue;let t=e.children[0];t&&ve.isReservedI18nLocale(String(t.value))&&i.push(us(n,`Locale ${t.value} is not allowed`,t.offset,t.offset+t.length))}}}for(let r in a){if(t.isGlobal){let e=t.build.tsLanguageService?.i18nFiles??{};Object.values(e).filter(e=>e!==t&&e.isGlobal&&e.parsed&&Object.hasOwn(e.parsed,r)).length>0&&i.push(us(n,`Duplicate translation key ${r} across global files`,a[r].keyStart,a[r].keyEnd))}for(let n in a[r].locales){let s=a[r].locales[n];o.includes(n)||i.push(ds(t.file.documentUser,`Locale not needed`,s.localeStart,s.localeEnd)),s.value==e.empty&&i.push(ds(t.file.documentUser,`Translation not set`,s.valueStart,s.valueEnd))}let s=[];for(let e of o)a[r].locales[e]===void 0&&s.push(e);s.length>0&&i.push(us(t.file.documentUser,`Missing locales `+s.join(`, `),a[r].keyStart,a[r].keyEnd))}return i}catch{i.length==0&&i.push(ls(n,`Can't parse the json`))}for(let e of i)e.severity=h.DiagnosticSeverity.Error;return i}async format(e,t,n){try{let t;try{let n=JSON.parse(e.contentUser);t=JSON.stringify(this.sortObj(n),null,4)}catch{let n=this.languageService.parseJSONDocument(e.documentUser),r=n.root,i=n.syntaxErrors;if(!r||r.type!==`object`||i?.some(e=>e.code!==h.ErrorCode.TrailingComma))return[];let a=e.contentUser.slice(0,r.offset)+this.sortJsoncObject(e.contentUser,r)+e.contentUser.slice(r.offset+r.length),o=d.TextDocument.create(e.uri,e.documentUser.languageId,e.documentUser.version,a),s=await this.languageService.format(o,void 0,{tabSize:4,insertSpaces:!0});t=d.TextDocument.applyEdits(o,s)}return[{newText:t,range:{start:e.documentUser.positionAt(0),end:e.documentUser.positionAt(e.contentUser.length)}}]}catch{}return[]}sortJsoncObject(e,t){let n=t.properties,r=t.offset+1,i=[];for(let t of n){let n=t.valueNode,a=this.removeJsoncComma(e.slice(r,t.offset));r=t.offset+t.length;let o=e.slice(t.offset,r);if(n?.type===`object`){let r=n.offset-t.offset;o=o.slice(0,r)+this.sortJsoncObject(e,n)+o.slice(r+n.length)}i.push({key:t.keyNode.value,text:a+o})}let a=this.removeJsoncComma(e.slice(r,t.offset+t.length-1));return i.sort((e,t)=>e.key<t.key?-1:+(e.key>t.key)),`{`+i.map(e=>e.text).join(`,`)+a+`}`}removeJsoncComma(e){return e.replace(/^(\s*),/,`$1`)}async codeAction(e,t){let n=[];try{let t=this.actionImportMissingLocales(e);t&&n.push(t)}catch{}return n}sortObj(t){return e.sortObj(t)}static sortObj(e){return Object.keys(e).sort().reduce((t,n)=>{let r=e[n];return t[n]=Object.keys(r).sort().reduce((e,t)=>(e[t]=r[t],e),{}),t},{})}actionImportMissingLocales(t){let n=t.file.documentUser,r=t.file.contentUser,i=this.languageService.parseJSONDocument(n),a=i.syntaxErrors,o=i.root;if(o?.type!==`object`||a?.length){$.showErrorMessage(`The i18n file is malformed. Fix its JSON before importing missing locales.`);return}let s=[],c=(t.build.buildConfig.i18n?.locales??[]).filter(e=>!ve.isReservedI18nLocale(e));for(let t of o.properties){if(ve.isReservedI18nLocale(String(t.keyNode.value)))continue;let i=t.valueNode;if(i?.type!==`object`)continue;let a=c.filter(e=>!i.properties.some(t=>t.keyNode.value===e));if(a.length===0)continue;let o=i.properties[0],l=o?.offset??i.offset+1,u=r.lastIndexOf(`
|
|
610
610
|
`,l-1)+1,d=r.slice(u,l),f=r.slice(i.offset,i.offset+i.length).includes(`
|
|
611
611
|
`),p=o&&/^\s*$/.test(d)?d:` `,m=a.map(t=>`${JSON.stringify(t)}: ${JSON.stringify(e.empty)}`),h;h=o?f&&/^\s*$/.test(d)?m.join(`,
|
|
612
612
|
`+p)+`,
|
|
@@ -662,7 +662,7 @@ public `+r+`?:`+i+`;
|
|
|
662
662
|
import { log } from ${no()};
|
|
663
663
|
import { Template } from ${JSON.stringify((0,b.pathToFileURL)(this.config).href)};
|
|
664
664
|
const t = new Template();
|
|
665
|
-
log(t.basicInfo())`,i=(0,f.join)($.savePath,`temp`);(0,u.existsSync)(i)||(0,u.mkdirSync)(i);let a=(0,f.join)(i,n+`.ts`);(0,u.writeFileSync)(a,r);let o={name:``,version:`1.0.0`,description:``,isAllow:!0};var s=``,c=``;try{let e=await Zo(process.execPath,to(a),{cwd:this.folderPath});c=e.stderr.toString(),s=e.stdout.toString();let t=JSON.parse(s.trim());o={...o,...t}}catch(e){$.error(e),$.error(c),$.error(s),this.containsError=!0}ks(a);let l=[...e.preparing[n]];delete e.preparing[n];for(let e of l)e(o);t(o)})}},io=class extends Error{};function ao(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r instanceof ro||typeof r!=`object`||!r?r:ao(r);return t}var oo=class e{static findInstallationCollision(e){let t=new Map;for(let n of e){let e=process.platform===`win32`?n.destination.toLowerCase():n.destination,r=t.get(e);if(r)return`${r} and ${n.name} use the same installation folder: ${n.destination}`;t.set(e,n.name)}}static replaceLocalInstallation(e,t,n){let r=(0,_.randomUUID)(),i=n+`.staged-`+r,a=n+`.backup-`+r;for(let e of[n,i,a])if(this.getInstallationPath(t,(0,f.relative)((0,f.resolve)(t),e))!==e)throw Error(`Invalid installation path`);let o=!1;try{(0,u.cpSync)(e,i,{force:!0,recursive:!0}),(0,u.existsSync)(n)&&((0,u.renameSync)(n,a),o=!0);try{(0,u.renameSync)(i,n)}catch(e){throw o&&(0,u.renameSync)(a,n),e}o&&(0,u.rmSync)(a,{recursive:!0,force:!0})}finally{(0,u.existsSync)(i)&&(0,u.rmSync)(i,{recursive:!0,force:!0})}}static resolveExistingPath(e){let t=(0,f.resolve)(e),n=[];for(;!(0,u.existsSync)(t);){let e=(0,f.dirname)(t);if(e===t)return t;n.unshift(t.slice(e.length+ +!e.endsWith(f.sep))),t=e}return(0,f.resolve)((0,u.realpathSync)(t),...n)}static getInstallationPath(e,t){if(!t||/^[\\/]/.test(t)||f.win32.isAbsolute(t)||/^[A-Za-z]:/.test(t))return null;let n=(0,f.resolve)(e,t.replace(/[\\/]/g,f.sep)),r=(0,f.relative)((0,f.resolve)(e),n);if(!r||r===`..`||r.startsWith(`..`+f.sep))return null;let i=(0,f.relative)(this.resolveExistingPath(e),this.resolveExistingPath(n));return!i||i===`..`||i.startsWith(`..`+f.sep)||(0,f.isAbsolute)(i)?null:n}templatePath=[];projectPath=[];globalPath=[];loadedTemplates={};loadedProjects={};loadedGlobal={};loadedProjectsLength=0;loadedTemplatesLength=0;loadedGlobalLength=0;workspaces=[];getGeneralTemplates(){return this.loadedTemplates}getGeneralTemplatesLength(){return this.loadedTemplatesLength}getGeneralProjects(){return this.loadedProjects}getGeneralProjectsLength(){return this.loadedProjectsLength}getGeneralGlobal(){return this.loadedGlobal}getGeneralGlobalLength(){return this.loadedGlobalLength}constructor(e){this.workspaces=e.map(e=>L(e).replace(/\//g,f.sep))}async init(){$.isIDE?this.loadTemplates():await this.loadTemplates(),F.getInstance().onSettingsChange(()=>{this.loadTemplates()})}async loadTemplates(){let e=$.savePath;(0,u.existsSync)(e)||(0,u.mkdirSync)(e),this.templatePath=F.getInstance().settings.templatePath;let t=(0,f.normalize)(e+f.sep+`templates`);this.prepareFolders(this.templatePath,t),this.globalPath=F.getInstance().settings.globalPath;let n=(0,f.normalize)(e+f.sep+`global`);this.prepareFolders(this.globalPath,n),this.projectPath=F.getInstance().settings.projectPath;let r=(0,f.normalize)(e+f.sep+`projects`),i=!(0,u.existsSync)(r)||(0,u.readdirSync)(r).length==0;this.prepareFolders(this.projectPath,r),i&&await this.askTemplate();let a=[];a.push(this.reloadTemplates()),a.push(this.reloadProjects()),a.push(this.reloadGlobal()),await Promise.all(a)}async reloadTemplates(){let e=await this.readTemplates(this.templatePath);this.loadedTemplates=e.templates,this.loadedTemplatesLength=e.nb}async reloadProjects(){let e=await this.readTemplates(this.projectPath);this.loadedProjects=e.templates,this.loadedProjectsLength=e.nb}async reloadGlobal(){let e=await this.readTemplates(this.globalPath);this.loadedGlobal=e.templates,this.loadedGlobalLength=e.nb}prepareFolders(e,t){e.includes(t)||e.splice(0,0,t);for(let t=0;t<e.length;t++)e[t]=(0,f.normalize)(e[t]),(0,u.existsSync)(e[t])||(0,u.mkdirSync)(e[t])}findWorkspace(e){let t=/^[A-Za-z]:[\\/]|^\\\\/.test(e),n=t?f.win32:e.startsWith(`/`)?f.posix:{resolve:f.resolve,relative:f.relative,isAbsolute:f.isAbsolute,sep:f.sep},r=n.resolve(e),i=``,a=-1;for(let e of this.workspaces){if(/^[A-Za-z]:[\\/]|^\\\\/.test(e)!==t)continue;let o=n.resolve(e),s=n.relative(o,r);s!==`..`&&!s.startsWith(`..`+n.sep)&&!n.isAbsolute(s)&&o.length>a&&(i=e,a=o.length)}return i||($.showErrorMessage(`Can't load the workspace`),``)}async readTemplates(e,t={},n=0){t=ao(t);let r=[],i=e=>{let a=(0,f.join)(e,E.Template);if((0,u.existsSync)(a)){try{r.push(new Promise(async e=>{let r=await ro.create(a);if(r){let i=xs(r.name,t);if(i!=null&&i.folderPath!=r.folderPath){$.showErrorMessage(`You have 2 templates with the same names : `+i?.folderPath+` and `+r.folderPath),e();return}bs(r.name,t,r),n++}e()}))}catch(e){console.error(e),$.showErrorMessage(`Error when parsing file `+a)}return}let o=(0,u.readdirSync)(e);for(let t of o)try{let n=(0,f.join)(e,t);(0,u.statSync)(n).isDirectory()&&i(n)}catch(e){$.error(e)}};for(let t of e)(0,u.existsSync)(t)&&i(t);return await Promise.all(r),{templates:t,nb:n}}async getGitURL(){return await $.Input({title:`Git url`,validations:[{message:`Provide an http(s):// url ending with .git`,regex:`^https?:\\//\\S*\\.git$`}]})}async askTemplate(){await $.ask(`Do you want to install project templates (recommended)?`)&&await this.selectProjectToImport(!0)}async selectProjectToImport(t){if(this.projectPath.length==0){$.showErrorMessage(`No project path registered`);return}let n=await $.Select([{label:`Local`},{label:`Git`}],{title:`Select a source from where to import projects`});if(n){if(n.label==`Local`){let n=$.extensionPath+f.sep+`templates`+f.sep+`projects`,r=(0,u.readdirSync)(n),i=new Map,a={};for(let e of r){let r=n+f.sep+e;if((0,u.statSync)(r).isDirectory()){let n=r+f.sep+E.Template;if((0,u.existsSync)(n))try{let o=await ro.create(n);if(o){a[r]=o;let n={label:o.name,detail:[o.description,e].filter(Boolean).join(` - `),picked:t,id:r};i.set(n,r)}}catch{}}}let o=await $.SelectMultiple(Array.from(i.keys()),{title:`Select projects to import`});if(o){let t=!1,n=[];for(let t of o){let r=this.getSelectItem(i,t);if(r){let t=a[r].installationFolder??r.split(f.sep).pop(),i=e.getInstallationPath(this.projectPath[0],t);if(!i){$.showErrorMessage(`Invalid installation folder`);continue}n.push({path:r,name:a[r].name,destination:i})}}let r=e.findInstallationCollision(n);if(r){$.showErrorMessage(`Projects not installed: `+r);return}for(let r of n)e.replaceLocalInstallation(r.path,this.projectPath[0],r.destination),t=!0;t&&$.showInformationMessage(`Projects installed`)}}else if(n.label==`Git`){let e=await this.getGitURL();e&&await Yo(`git clone `+e,{cwd:this.projectPath[0]})}else n.label==`Store`&&await this.downloadTemplateFromStore();await this.reloadProjects()}}async selectTemplateToImport(){if(this.templatePath.length==0){$.showErrorMessage(`No template path registered`);return}let t=await $.Select([{label:`Local`},{label:`Git`}],{title:`Select a source from where to import templates`});if(t)if(t.label==`Local`){let t=$.extensionPath+f.sep+`templates`+f.sep+`templates`,n=(0,u.readdirSync)(t),r=new Map,i={};if(($.templateManager?.workspaces??[]).length==0)return;for(let e of n){let n=t+f.sep+e;if((0,u.statSync)(n).isDirectory()){let t=n+f.sep+E.Template;if((0,u.existsSync)(t))try{let a=await ro.create(t);if(a){i[n]=a;let t={label:a.name,detail:[a.description,e].filter(Boolean).join(` - `),picked:!1,id:n};r.set(t,n)}}catch{}}}let a=await $.SelectMultiple(Array.from(r.keys()),{title:`Select templates to import`});if(a){let t=[],n=[],o=[];for(let t of a){let a=this.getSelectItem(r,t);if(a){let t=i[a].name,r=i[a].installationFolder??a.split(f.sep).pop(),s=e.getInstallationPath(this.templatePath[0],r);if(!s){n.push(`Template ${t} failed: invalid installation folder`);continue}o.push({path:a,name:t,destination:s})}}let s=e.findInstallationCollision(o);if(s){$.showErrorMessage(`Templates not installed: `+s);return}for(let r of o)try{e.replaceLocalInstallation(r.path,this.templatePath[0],r.destination),t.push(r.name)}catch(e){n.push(`Template ${r.name} failed: ${String(e)}`)}if(t.length>0){await this.reloadTemplates();let e=`Templates installed`;n.length>0&&(e+=`: `+t.join(`, `)),$.showInformationMessage(e)}for(let e of n)$.showErrorMessage(e)}}else if(t.label==`Git`){let e=await this.getGitURL();e&&await Yo(`git clone `+e,{cwd:this.templatePath[0]}),await this.reloadTemplates()}else t.label==`Store`&&await this.downloadTemplateFromStore()}async selectGlobalToImport(t){if(this.globalPath.length==0){$.showErrorMessage(`No global template path registered`);return}let n=await $.Select([{label:`Local`},{label:`Git`}],{title:`Select a source from where to import global templates`});if(n){if(n.label==`Local`){let n=$.extensionPath+f.sep+`templates`+f.sep+`global`,r=(0,u.readdirSync)(n),i=new Map,a={};for(let e of r){let r=n+f.sep+e;if((0,u.statSync)(r).isDirectory()){let n=r+f.sep+E.Template;if((0,u.existsSync)(n))try{let o=await ro.create(n);if(o){a[r]=o;let n={label:o.name,detail:[o.description,e].filter(Boolean).join(` - `),picked:t,id:r};i.set(n,r)}}catch{}}}let o=await $.SelectMultiple(Array.from(i.keys()),{title:`Select global templates to import`});if(o){let t=!1;for(let n of o){let r=this.getSelectItem(i,n);if(r){let n=a[r].installationFolder??r.split(f.sep).pop(),i=e.getInstallationPath(this.globalPath[0],n);if(!i){$.showErrorMessage(`Invalid installation folder`);continue}(0,u.existsSync)(i)&&(0,u.rmSync)(i,{recursive:!0,force:!0}),(0,u.cpSync)(r,i,{force:!0,recursive:!0}),t=!0}}t&&$.showInformationMessage(`Global templates installed`)}}else if(n.label==`Git`){let e=await this.getGitURL();e&&await Yo(`git clone `+e,{cwd:this.globalPath[0]})}else n.label==`Store`&&await this.downloadTemplateFromStore();await this.reloadGlobal()}}async selectProjectToUninstall(){let e=this.getGeneralProjects(),t=[],n=[],r=e=>{for(let i in e){let a=e[i];a instanceof ro?(t.push(a),n.push({label:a.name,detail:a.config})):r(a)}};r(e);let i=await $.SelectMultiple(n,{title:`Select projects to remove`});i&&this.removeSelectedInstallations(i,n,t,()=>this.getGeneralProjects(),this.projectPath)>0&&(await this.reloadProjects(),$.showInformationMessage(`Projects deleted`))}async selectTemplateToUninstall(){let e=this.getGeneralTemplates(),t=[],n=[],r=e=>{for(let i in e){let a=e[i];a instanceof ro?(t.push(a),n.push({label:a.name,detail:a.config})):r(a)}};r(e);let i=await $.SelectMultiple(n,{title:`Select templates to remove`});i&&this.removeSelectedInstallations(i,n,t,()=>this.getGeneralTemplates(),this.templatePath)>0&&(await this.reloadTemplates(),$.showInformationMessage(`Templates deleted`))}async selectGlobalToUninstall(){let e=this.getGeneralGlobal(),t=[],n=[],r=e=>{for(let i in e){let a=e[i];a instanceof ro?(t.push(a),n.push({label:a.name,detail:a.config})):r(a)}};r(e);let i=await $.SelectMultiple(n,{title:`Select global templates to remove`});i&&this.removeSelectedInstallations(i,n,t,()=>this.getGeneralGlobal(),this.globalPath)>0&&(await this.reloadGlobal(),$.showInformationMessage(`Global templates deleted`))}removeSelectedInstallations(e,t,n,r,i){let a=0,o=new Set;for(let s of e){let e=t.findIndex(e=>e.label===s.label&&e.detail===s.detail);if(e<0)continue;let c=n[e];if(o.has(c)||xs(c.name,r())!==c)continue;let l=(0,f.resolve)((0,f.dirname)(c.config));!i.some(e=>{let t=(0,f.relative)((0,f.resolve)(e),l);return t!==``&&t!==`..`&&!t.startsWith(`..`+f.sep)&&!(0,f.isAbsolute)(t)})||!(0,u.existsSync)(c.config)||(o.add(c),(0,u.rmSync)(l,{recursive:!0,force:!0}),a++)}return a}getSelectItem(e,t){if(e.has(t))return e.get(t);for(let n of e.keys())if(t.id?n.id===t.id:n.label===t.label&&n.detail===t.detail)return e.get(n);return null}async query(e,t,n){let r=this.findWorkspace(e),i=async t=>{let n={};for(let[a,o]of Object.entries(t))if(o instanceof ro)await o.isAllowed(e,r)&&(n[a]=o);else{let e=await i(o);Object.keys(e).length>0&&(n[a]=e)}return n},a=await i(t);if(Object.keys(a).length===0&&(!n||n.length===0))throw new io(`No templates available for this location`);return this.queryAllowed(a,n)}async queryAllowed(e,t){let n=!0;t||=(n=!1,[]);let r=new Map,i=new Map;for(let n in e){let a=e[n],o;a instanceof ro?(o={label:n,detail:a.description??``},i.set(o,a)):(o={label:n},r.set(o,a)),t.push(o)}if(t.sort((e,t)=>e.label.localeCompare(t.label)),t.length===0)return null;let a=await $.Select(t,{title:`What do you want to create?`});if(a){let e=this.getSelectItem(i,a);if(e)return e;let t=this.getSelectItem(r,a);if(t)return this.queryAllowed(t);if(n)return a}return null}async downloadTemplateFromStore(t){let n;try{let r=`^${so.url.replace(/\//g,`\\/`)}\\/template\\/download\\/(?<name>[^/]+)\\/(?<version>\\d+\\.\\d+\\.\\d+)$`;if(!t){let e=await $.Input({title:`Store url`,validations:[{message:`The store url must be `+so.url+`/template/download/{name}/{version}$`,regex:r}]});if(!e)return;t=e}let i=t.match(new RegExp(r));if(!i){$.showErrorMessage(`The uri provided is wrong`);return}let a=i[1];i[2],n=(0,f.join)($.savePath,`temp`,`packageTemp`),(0,u.rmSync)(n,{recursive:!0,force:!0}),(0,u.mkdirSync)(n,{recursive:!0});let o=(0,f.join)(n,`temp.zip`);if(!await this.downloadFile(o,t)){$.showErrorMessage(`Error downloading package`);return}if(!await this.extractZip(o,n)){$.showErrorMessage(`Error extracting package to analyze`);return}if((0,u.existsSync)((0,f.join)(n,E.Template))){let t=await ro.create((0,f.join)(n,E.Template));if(!t){$.showErrorMessage(`The template contains error`);return}let r=t.isGlobal?this.globalPath[0]:t.isProject?this.projectPath[0]:this.templatePath[0],i=t.installationFolder??a,s=e.getInstallationPath(r,i);if(!s){$.showErrorMessage(`Invalid installation folder`);return}if(!await this.extractZip(o,s)){$.showErrorMessage(`Error extracting package`);return}t.isGlobal?await this.reloadGlobal():t.isProject?await this.reloadProjects():await this.reloadTemplates(),$.showInformationMessage(`Template `+a+` installed`)}else $.showErrorMessage(E.Template+` not found`)}catch(e){$.showErrorMessage(`Error unknown`),console.error(e)}finally{n&&(0,u.rmSync)(n,{recursive:!0,force:!0})}}downloadFile(e,t){return new Promise(n=>{try{(t.startsWith(`https`)?oe.get:x.get)(t,t=>{if(!t.statusCode||t.statusCode<200||t.statusCode>=300){t.resume(),n(!1);return}(0,C.pipeline)(t,(0,u.createWriteStream)(e),t=>{t&&(0,u.existsSync)(e)&&ks(e),n(!t)})}).on(`error`,()=>n(!1))}catch{n(!1)}})}async extractZip(e,t){try{return await(await se.Open.file(e)).extract({path:t}),!0}catch(e){console.error(`Extract error `,e)}return!1}async readGlobal(){let e=this.getGeneralGlobal(),t=this.getGeneralGlobalLength(),n=$.getWorkspaceUri();if(n){let r=L(n)+`/.aventus/global`;return await this.readTemplates([r],e,t)}return{templates:e,nb:t}}},so=class e{static url=`https://store.aventusjs.com`;static _settings;static sessionRevision=0;static get settings(){return this._settings||=F.getInstance().hiddenSettings.store,this._settings}static get token(){return this.settings.token}static get isConnected(){return this.token!=``}static setSettings(e){let t={...this.settings,...e};F.getInstance().setHiddenSettings({store:t}),this._settings=t}static async connect(e,t){let n=++this.sessionRevision,r=await(0,Ii.machineId)(),i=(0,le.hostname)(),a=await this.post(`/login`,{username:e,password:t,machineId:r,machineName:i},{withoutBearer:!0});return n===this.sessionRevision&&a?(this.setSettings({token:a,username:e}),!0):!1}static async disconnect(){let e=++this.sessionRevision;await this.post(`/logout`),e===this.sessionRevision&&this.setSettings({token:``,username:void 0})}static async publishPackage(e){let t=new FormData;t.append(`name`,e.buildConfig.fullname),t.append(`description`,e.buildConfig.description??``),t.append(`version`,e.buildConfig.version),e.buildConfig.organization&&t.append(`organization`,e.buildConfig.organization),e.buildConfig.documentation&&t.append(`documentation`,e.buildConfig.documentation),e.buildConfig.repository&&t.append(`repository`,e.buildConfig.repository);for(let n of e.buildConfig.tags)t.append(`tags[]`,n);let n=(0,f.join)(lo.getInstance().getPath(),`@locals`,e.buildConfig.fullname+E.Package);if(!(0,u.existsSync)(n))return!1;let r=new Blob([(0,u.readFileSync)(n)],{type:`text/plain`});t.append(`packageFile`,r,e.buildConfig.fullname+E.Package);let i=e.project.getConfigFile().folderPath;if(e.buildConfig.readme){let n;if(e.buildConfig.readme.startsWith(`.`)){let t=(0,f.normalize)((0,f.join)(i,e.buildConfig.readme));if((0,u.existsSync)(t))n=t;else return new co([{code:-1,message:`Readme not found`}])}else if((0,u.existsSync)(e.buildConfig.readme))n=e.buildConfig.readme;else{let t=(0,f.normalize)((0,f.join)(i,e.buildConfig.readme));if((0,u.existsSync)(t))n=t;else return new co([{code:-1,message:`Readme not found`}])}let r=new Blob([(0,u.readFileSync)(n)],{type:`text/plain`});t.append(`readMe`,r,`README.md`)}else{let e=(0,u.readdirSync)(i).find(e=>e.toLowerCase()===`readme.md`);if(e){let n=new Blob([(0,u.readFileSync)((0,f.join)(i,e))],{type:`text/plain`});t.append(`readMe`,n,`README.md`)}}return await this.postWithErrors(`/package/publish`,t)}static async publishTemplate(e){if(!oo.getInstallationPath(e.folderPath,e.installationFolder??e.name))return new co([{code:422,message:`Invalid installation folder`}]);let t=new FormData;t.append(`name`,e.name),t.append(`description`,e.description),t.append(`version`,e.version),t.append(`is_project`,e.isProject?`1`:`0`),t.append(`is_global`,e.isGlobal?`1`:`0`),e.organization&&t.append(`organization`,e.organization),e.documentation&&t.append(`documentation`,e.documentation),e.repository&&t.append(`repository`,e.repository);for(let n of e.tags)t.append(`tags[]`,n);let n=e.folderPath,r=(0,u.readdirSync)(n).find(e=>e.toLowerCase()===`readme.md`);if(r){let e=new Blob([(0,u.readFileSync)((0,f.join)(n,r))],{type:`text/plain`});t.append(`readMe`,e,`README.md`)}let i=(0,f.dirname)(e.config),a=(0,f.join)($.savePath,`temp`,e.name+`.zip`);await this.zip(i,a);let o=new Blob([(0,u.readFileSync)(a)],{type:`application/zip`});t.append(`templateFile`,o,e.name+`.zip`);let s=await this.postWithErrors(`/template/publish`,t);return ks(a),s}static async post(e,t={},n){let r=await this.postWithErrors(e,t,n);if(r instanceof co){for(let e of r.errors)$.error(e.message);return null}return r}static async postWithErrors(t,n={},r){let i=null,a=this.sessionRevision,o=r?.withoutBearer===!0,s=o?void 0:this.token,c=()=>{let e=a===this.sessionRevision,t=o||s===this.token;return e&&t};try{let r={};if(n instanceof FormData||(r[`Content-Type`]=`application/json`),!o){let e=await(0,Ii.machineId)();r.Authorization=`Bearer `+(s+`|`+e)}if(i=await fetch(e.url+`/api/remote`+t,{method:`POST`,body:n instanceof FormData?n:JSON.stringify(n),headers:r}),i.status==401)return c()&&this.setSettings({token:``,username:void 0}),new co([{code:401,message:`No token provided`}]);if(i.status==403)return t!=`/logout`&&c()&&await this.disconnect(),new co([{code:403,message:`You must connect to your account first`}]);if(i.status<200||i.status>=300)return new co([{code:i.status,message:`Store request failed with HTTP ${i.status}`}]);let a=await i.text(),l;try{l=JSON.parse(a)}catch(e){throw $.error(a),e}return!l||!Array.isArray(l.errors)?new co([{code:-500,message:`Wrong response format from the api`}]):l.errors.length>0?new co(l.errors):Object.hasOwn(l,`result`)?l.result:new co([{code:-500,message:`Wrong response format from the api`}])}catch(e){return new co([{code:-500,message:e+``}])}}static zip(e,t){return new Promise(async(n,r)=>{let i=(0,u.createWriteStream)(t),a=(0,ue.create)(`zip`,{zlib:{level:9}});i.on(`close`,()=>{n()}),a.on(`error`,e=>{r(e)}),a.pipe(i),a.directory(e,!1,e=>e.name.split(/[\\/]/).includes(`.git`)?!1:e),await a.finalize()})}},co=class{errors;constructor(e){this.errors=e}},lo=class e{path;static instance;static getInstance(){return this.instance||=new e,this.instance}getPath(){return this.path}constructor(){this.path=(0,f.join)($.savePath,`packages`),(0,u.existsSync)(this.path)||(0,u.mkdirSync)(this.path,{recursive:!0})}predefinedPaths={"Aventus@Main":Tt(),"Aventus@UI":Et(),"Aventus@Sharp":Ot(),"Aventus@Php":kt(),"Aventus@I18n":Dt()};predefinedNpm={"Aventus@Main":`@aventusjs/main`,"Aventus@UI":`@aventusjs/ui`,"Aventus@I18n":`@aventusjs/i18n`,"Aventus@Sharp":`@aventussharp/main`,"Aventus@Php":`@aventusphp/main`};loadedPackages={};get packages(){let e=[];for(let t in this.loadedPackages)e.push(this.loadedPackages[t]);return e}async loadDependenciesFromBuild(e,t){let n={files:[],dependencyNeedUris:[],dependencyFullUris:[],dependencyUris:[]},r={},i={},a=new Set;for(let n in e.dependencies){let o=e.dependencies[n],s=await this.loadDependency(n,o,e,t,r);s&&(a.add(s.name),i[s.name]=o.include??`need`)}for(let e in r)i[e]||(i[e]=r[e].include);r[`Aventus@Main`]||await this.loadDependency(`Aventus@Main`,{uri:``,npm:``,version:`x.x.x`,include:`need`,subDependenciesInclude:{"*":`need`}},e,t,r),r[`Aventus@Main`]&&a.add(`Aventus@Main`),t.buildConfig.i18n!==void 0&&!r[`Aventus@I18n`]&&await this.loadDependency(`Aventus@I18n`,{uri:``,npm:``,version:`x.x.x`,include:`need`,subDependenciesInclude:{"*":`need`}},e,t,r),t.buildConfig.i18n!==void 0&&r[`Aventus@I18n`]&&a.add(`Aventus@I18n`);let o=new Set,s=e=>{if(!(o.has(e)||!r[e])){o.add(e);for(let t of r[e].dependencies)s(t.name)}};for(let e of a)s(e);for(let e of Object.keys(r))o.has(e)||delete r[e];let c=this.findCycle(r);if(c)return n.cycle=c,n;let l=[];for(let e in r){let t=r[e];this.orderLoop(e,t,r,l)}for(let e of l){let t=r[e];t.file.loadWebComponents(),n.files.push(t.file);let a=i[e]??`need`;a==`full`?(n.dependencyFullUris.push(t.uri),n.dependencyUris.push(t.uri)):a==`need`&&(n.dependencyNeedUris.push(t.uri),n.dependencyUris.push(t.uri))}return n}findCycle(e){let t=new Set,n=[],r=i=>{let a=n.indexOf(i);if(a>=0)return[...n.slice(a),i];if(t.has(i))return null;t.add(i),n.push(i);for(let t of e[i].dependencies)if(e[t.name]){let e=r(t.name);if(e)return e}return n.pop(),null};for(let t of Object.keys(e)){let e=r(t);if(e)return e}return null}orderLoop(e,t,n,r){let i=r.indexOf(e);if(i!=-1)return i+1;let a=0;for(let e of t.dependencies)if(n[e.name]){let t=this.orderLoop(e.name,n[e.name],n,r);t>=0&&t>a&&(a=t)}return r.splice(a,0,e),r.length}async loadDependency(e,t,n,r,i){let a,o;if(this.predefinedPaths[e]){t.uri=this.predefinedPaths[e];let n=I(t.uri);a=await this.loadByUri(r,n),o=n}else if(t.uri)if(t.uri.startsWith(`http`))$.showErrorMessage(`http package isn't supported right now. Plz use the store`);else{let e=I(t.uri);a=await this.loadByUri(r,e),o=e}else if(t.isLocal){let t=await this.loadLocal(e,r);a=t.file,o=t.uri}else if(t.version){let n=await this.loadStore(e,t.version,r);n?(a=n.file,o=n.uri):$.showErrorMessage(`Can't load `+e+` from the store`)}else $.showErrorMessage(`You need to define a version to load a package via the store (`+e+`)`);if(o&&a){let s=t.version?this.parseVersion(t.version):{major:-1,minor:-1,patch:-1};if(t.npm)a.npmUri=t.npm;else if(this.predefinedNpm[e])a.npmUri=this.predefinedNpm[e];else{let e=/\/\/ npm:(.*)$/m.exec(a.file.contentUser);e?a.npmUri=e[1]:a.npmUri=``}let c=/\/\* description:(.*) \*\//gm.exec(a.file.contentUser);c?a.description=c[1]:a.description=``;let l=async(e,a)=>{i[e.name]={file:e,uri:a,include:t.include??`need`,version:s,dependencies:[]};for(let a in e.dependencies){let o=e.dependencies[a];typeof o==`string`&&(o={version:o}),t.include==`none`&&(o.include=`none`);let s=await this.loadDependency(a,o,n,r,i);if(s){let n=i[e.name].dependencies.find(e=>e.name==s.name),r=`need`;t.include==`none`&&(r=`none`),o.subDependenciesInclude&&o.subDependenciesInclude[s.name]&&(r=o.subDependenciesInclude[s.name]),n?(n.include==`none`&&r!=`none`||n.include==`need`&&r==`full`)&&(n.include=r):i[e.name].dependencies.push({name:s.name,include:r})}}e.name!=`Aventus@Main`&&(i[e.name].dependencies.find(e=>e.name==`Aventus@Main`)||i[e.name].dependencies.push({name:`Aventus@Main`,include:`need`}))};if(!i[a.name])await l(a,o);else{let e=i[a.name].version;this.compareVersion(e,s,a.name)==s&&await l(a,o)}await qa.register(a)}return a}async loadByUri(e,t){let n=await z.getInstance().registerFilePackage(t);return this.loadPackage(n,e)}async loadLocal(e,t){let n=I((0,f.join)(this.path,`@locals`,e));n.endsWith(E.Package)||(n+=E.Package);let r=await z.getInstance().registerFilePackage(n),i=this.loadPackage(r,t);return{uri:n,file:i}}async loadStore(e,t,n){let r=(0,f.join)(this.path,`store`,e,t),i=(0,u.existsSync)(r),{major:a,minor:o,patch:s}=this.parseVersion(t),c=null;if(i&&(c=this.findPackage(r),c||(i=!1)),!i){(0,u.existsSync)(r)&&(0,u.rmSync)(r,{force:!0,recursive:!0}),(0,u.mkdirSync)(r,{recursive:!0});let n=(0,f.join)(r,`temp.zip`);if(!await this.downloadFile(n,so.url+`/package/download/${e}/${t}`)||!await this.extractZip(n,r))return null;if((0,u.rmSync)(n,{force:!0}),c=this.findPackage(r),!c)return;let i=await this.readFirstLine(c),a=/\/\/ (\S+):([0-9]+)\.([0-9]+)\.([0-9]+)/g.exec(i);if(!a)return console.error(`Invalid package header for "${e}@${t}". First line:`,JSON.stringify(i)),null;let o=a[1],s=Number(a[2]),l=Number(a[3]),d=Number(a[4]),p=s+`.`+l+`.`+d;if(o!==e)return console.error(`Package name mismatch: requested "${e}", downloaded "${o}"`),null;if(p!==t)return console.error(`Package version mismatch: requested "${t}", downloaded "${p}"`),null}if(!c)return console.error(`Package file not found after extracting "${e}@${t}" into "${r}"`),null;let l=I(c),d=await z.getInstance().registerFilePackage(l);return{uri:l,file:this.loadPackage(d,n)}}extractZip(e,t){return new Promise(n=>{let r=!1,i=e=>{r||(r=!0,n(e))},a=(0,u.createReadStream)(e),o=(0,se.Extract)({path:t});a.on(`error`,t=>{console.error(`Can't read ZIP "${e}":`,t),i(!1)}),o.on(`close`,()=>i(!0)),o.on(`error`,t=>{console.error(`Can't extract ZIP "${e}":`,t),(t+``).includes(`Error: invalid signature: 0x4f44213c`)&&console.log((0,u.readFileSync)(e,`utf8`)),i(!1)}),a.pipe(o)})}findPackage(e){let t=null,n=(0,u.readdirSync)(e);for(let r of n)if(r.endsWith(E.Package)){t=(0,f.join)(e,r);break}return t}loadPackage(e,t){if(!e)return;let n=Tn.getQuickInfo(e);if(!n)return;let r=new Tn(e,t);return this.loadedPackages[n.name]=r,e.onDelete(async()=>{this.loadedPackages[n.name]===r&&delete this.loadedPackages[n.name]}),r}downloadFile(e,t){return new Promise(n=>{let r=`${e}.${(0,_.randomUUID)()}.tmp`,i=!1,a=()=>{try{(0,u.existsSync)(r)&&ks(r)}catch{}},o=e=>{i||(i=!0,e||a(),n(e))};(t.startsWith(`https:`)?oe.get:x.get)(t,n=>{let i=n.statusCode??0;if(i>=300&&i<400&&n.headers.location){n.resume(),this.downloadFile(e,new URL(n.headers.location,t).href).then(o).catch(()=>o(!1));return}if(i<200||i>=300){console.error(`Download failed: HTTP ${i} for ${t}`),n.resume(),o(!1);return}let a=(0,u.createWriteStream)(r,{flags:`wx`}),s=!1;a.on(`error`,t=>{console.error(`File write error for ${e}:`,t),s=!0,n.destroy()}),n.on(`error`,e=>{console.error(`HTTP response error for ${t}:`,e),s=!0,a.destroy()}),n.on(`aborted`,()=>{s=!0,a.destroy()}),a.on(`close`,()=>{if(s||!a.writableFinished||!n.complete){o(!1);return}try{(0,u.renameSync)(r,e),o(!0)}catch(t){console.error(`File replace error for ${e}:`,t),o(!1)}}),n.pipe(a)}).on(`error`,e=>{console.error(`HTTP request error for ${t}:`,e),o(!1)})})}readFirstLine(e){return new Promise(function(t,n){var r=(0,u.createReadStream)(e,{encoding:`utf8`}),i=``;r.on(`data`,function(e){i+=e,i.includes(`
|
|
665
|
+
log(t.basicInfo())`,i=(0,f.join)($.savePath,`temp`);(0,u.existsSync)(i)||(0,u.mkdirSync)(i);let a=(0,f.join)(i,n+`.ts`);(0,u.writeFileSync)(a,r);let o={name:``,version:`1.0.0`,description:``,isAllow:!0};var s=``,c=``;try{let e=await Zo(process.execPath,to(a),{cwd:this.folderPath});c=e.stderr.toString(),s=e.stdout.toString();let t=JSON.parse(s.trim());o={...o,...t}}catch(e){$.error(e),$.error(c),$.error(s),this.containsError=!0}ks(a);let l=[...e.preparing[n]];delete e.preparing[n];for(let e of l)e(o);t(o)})}},io=class extends Error{};function ao(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r instanceof ro||typeof r!=`object`||!r?r:ao(r);return t}var oo=class e{static findInstallationCollision(e){let t=new Map;for(let n of e){let e=process.platform===`win32`?n.destination.toLowerCase():n.destination,r=t.get(e);if(r)return`${r} and ${n.name} use the same installation folder: ${n.destination}`;t.set(e,n.name)}}static replaceLocalInstallation(e,t,n){let r=(0,_.randomUUID)(),i=n+`.staged-`+r,a=n+`.backup-`+r;for(let e of[n,i,a])if(this.getInstallationPath(t,(0,f.relative)((0,f.resolve)(t),e))!==e)throw Error(`Invalid installation path`);let o=!1;try{(0,u.cpSync)(e,i,{force:!0,recursive:!0}),(0,u.existsSync)(n)&&((0,u.renameSync)(n,a),o=!0);try{(0,u.renameSync)(i,n)}catch(e){throw o&&(0,u.renameSync)(a,n),e}o&&(0,u.rmSync)(a,{recursive:!0,force:!0})}finally{(0,u.existsSync)(i)&&(0,u.rmSync)(i,{recursive:!0,force:!0})}}static resolveExistingPath(e){let t=(0,f.resolve)(e),n=[];for(;!(0,u.existsSync)(t);){let e=(0,f.dirname)(t);if(e===t)return t;n.unshift(t.slice(e.length+ +!e.endsWith(f.sep))),t=e}return(0,f.resolve)((0,u.realpathSync)(t),...n)}static getInstallationPath(e,t){if(!t||/^[\\/]/.test(t)||f.win32.isAbsolute(t)||/^[A-Za-z]:/.test(t))return null;let n=(0,f.resolve)(e,t.replace(/[\\/]/g,f.sep)),r=(0,f.relative)((0,f.resolve)(e),n);if(!r||r===`..`||r.startsWith(`..`+f.sep))return null;let i=(0,f.relative)(this.resolveExistingPath(e),this.resolveExistingPath(n));return!i||i===`..`||i.startsWith(`..`+f.sep)||(0,f.isAbsolute)(i)?null:n}templatePath=[];projectPath=[];globalPath=[];loadedTemplates={};loadedProjects={};loadedGlobal={};loadedProjectsLength=0;loadedTemplatesLength=0;loadedGlobalLength=0;workspaces=[];getGeneralTemplates(){return this.loadedTemplates}getGeneralTemplatesLength(){return this.loadedTemplatesLength}getGeneralProjects(){return this.loadedProjects}getGeneralProjectsLength(){return this.loadedProjectsLength}getGeneralGlobal(){return this.loadedGlobal}getGeneralGlobalLength(){return this.loadedGlobalLength}constructor(e){this.workspaces=e.map(e=>L(e).replace(/\//g,f.sep))}async init(){$.isIDE?this.loadTemplates():await this.loadTemplates(),F.getInstance().onSettingsChange(()=>{this.loadTemplates()})}async loadTemplates(){let e=$.savePath;(0,u.existsSync)(e)||(0,u.mkdirSync)(e),this.templatePath=F.getInstance().settings.templatePath;let t=(0,f.normalize)(e+f.sep+`templates`);this.prepareFolders(this.templatePath,t),this.globalPath=F.getInstance().settings.globalPath;let n=(0,f.normalize)(e+f.sep+`global`);this.prepareFolders(this.globalPath,n),this.projectPath=F.getInstance().settings.projectPath;let r=(0,f.normalize)(e+f.sep+`projects`),i=!(0,u.existsSync)(r)||(0,u.readdirSync)(r).length==0;this.prepareFolders(this.projectPath,r),i&&await this.askTemplate();let a=[];a.push(this.reloadTemplates()),a.push(this.reloadProjects()),a.push(this.reloadGlobal()),await Promise.all(a)}async reloadTemplates(){let e=await this.readTemplates(this.templatePath);this.loadedTemplates=e.templates,this.loadedTemplatesLength=e.nb}async reloadProjects(){let e=await this.readTemplates(this.projectPath);this.loadedProjects=e.templates,this.loadedProjectsLength=e.nb}async reloadGlobal(){let e=await this.readTemplates(this.globalPath);this.loadedGlobal=e.templates,this.loadedGlobalLength=e.nb}prepareFolders(e,t){e.includes(t)||e.splice(0,0,t);for(let t=0;t<e.length;t++)e[t]=(0,f.normalize)(e[t]),(0,u.existsSync)(e[t])||(0,u.mkdirSync)(e[t])}findWorkspace(e){let t=/^[A-Za-z]:[\\/]|^\\\\/.test(e),n=t?f.win32:e.startsWith(`/`)?f.posix:{resolve:f.resolve,relative:f.relative,isAbsolute:f.isAbsolute,sep:f.sep},r=n.resolve(e),i=``,a=-1;for(let e of this.workspaces){if(/^[A-Za-z]:[\\/]|^\\\\/.test(e)!==t)continue;let o=n.resolve(e),s=n.relative(o,r);s!==`..`&&!s.startsWith(`..`+n.sep)&&!n.isAbsolute(s)&&o.length>a&&(i=e,a=o.length)}return i||($.showErrorMessage(`Can't load the workspace`),``)}async readTemplates(e,t={},n=0){t=ao(t);let r=[],i=e=>{let a=(0,f.join)(e,E.Template);if((0,u.existsSync)(a)){try{r.push(new Promise(async e=>{let r=await ro.create(a);if(r){let i=xs(r.name,t);if(i!=null&&i.folderPath!=r.folderPath){$.showErrorMessage(`You have 2 templates with the same names : `+i?.folderPath+` and `+r.folderPath),e();return}bs(r.name,t,r),n++}e()}))}catch(e){console.error(e),$.showErrorMessage(`Error when parsing file `+a)}return}let o=(0,u.readdirSync)(e);for(let t of o)try{let n=(0,f.join)(e,t);(0,u.statSync)(n).isDirectory()&&i(n)}catch(e){$.error(e)}};for(let t of e)(0,u.existsSync)(t)&&i(t);return await Promise.all(r),{templates:t,nb:n}}async getGitURL(){return await $.Input({title:`Git url`,validations:[{message:`Provide an http(s):// url ending with .git`,regex:`^https?:\\//\\S*\\.git$`}]})}async askTemplate(){await $.ask(`Do you want to install project templates (recommended)?`)&&await this.selectProjectToImport(!0)}async selectProjectToImport(t,n){if(this.projectPath.length==0){$.showErrorMessage(`No project path registered`);return}if(n){let e=RegExp(`^${so.url.replace(/\//g,`\\/`)}\\/template\\/download\\/(?<name>[^/]+)\\/(?<version>\\d+\\.\\d+\\.\\d+)$`),t=RegExp(`^https?:\\//\\S*\\.git$`);e.test(n)?await this.downloadTemplateFromStore(n):t.test(n)?await Yo(`git clone `+n,{cwd:this.projectPath[0]}):$.showErrorMessage(`Can't install template : `+n)}else{let n=[{label:`Local`},{label:`Git`}];$.isIDE||n.push({label:`Store`});let r=await $.Select(n,{title:`Select a source from where to import projects`});if(!r)return;if(r.label==`Local`){let n=$.extensionPath+f.sep+`templates`+f.sep+`projects`,r=(0,u.readdirSync)(n),i=new Map,a={};for(let e of r){let r=n+f.sep+e;if((0,u.statSync)(r).isDirectory()){let n=r+f.sep+E.Template;if((0,u.existsSync)(n))try{let o=await ro.create(n);if(o){a[r]=o;let n={label:o.name,detail:[o.description,e].filter(Boolean).join(` - `),picked:t,id:r};i.set(n,r)}}catch{}}}let o=await $.SelectMultiple(Array.from(i.keys()),{title:`Select projects to import`});if(o){let t=!1,n=[];for(let t of o){let r=this.getSelectItem(i,t);if(r){let t=a[r].installationFolder??r.split(f.sep).pop(),i=e.getInstallationPath(this.projectPath[0],t);if(!i){$.showErrorMessage(`Invalid installation folder`);continue}n.push({path:r,name:a[r].name,destination:i})}}let r=e.findInstallationCollision(n);if(r){$.showErrorMessage(`Projects not installed: `+r);return}for(let r of n)e.replaceLocalInstallation(r.path,this.projectPath[0],r.destination),t=!0;t&&$.showInformationMessage(`Projects installed`)}}else if(r.label==`Git`){let e=await this.getGitURL();e&&await Yo(`git clone `+e,{cwd:this.projectPath[0]})}else r.label==`Store`&&await this.downloadTemplateFromStore()}$.isIDE&&await this.reloadProjects()}async selectTemplateToImport(){if(this.templatePath.length==0){$.showErrorMessage(`No template path registered`);return}let t=await $.Select([{label:`Local`},{label:`Git`}],{title:`Select a source from where to import templates`});if(t)if(t.label==`Local`){let t=$.extensionPath+f.sep+`templates`+f.sep+`templates`,n=(0,u.readdirSync)(t),r=new Map,i={};if(($.templateManager?.workspaces??[]).length==0)return;for(let e of n){let n=t+f.sep+e;if((0,u.statSync)(n).isDirectory()){let t=n+f.sep+E.Template;if((0,u.existsSync)(t))try{let a=await ro.create(t);if(a){i[n]=a;let t={label:a.name,detail:[a.description,e].filter(Boolean).join(` - `),picked:!1,id:n};r.set(t,n)}}catch{}}}let a=await $.SelectMultiple(Array.from(r.keys()),{title:`Select templates to import`});if(a){let t=[],n=[],o=[];for(let t of a){let a=this.getSelectItem(r,t);if(a){let t=i[a].name,r=i[a].installationFolder??a.split(f.sep).pop(),s=e.getInstallationPath(this.templatePath[0],r);if(!s){n.push(`Template ${t} failed: invalid installation folder`);continue}o.push({path:a,name:t,destination:s})}}let s=e.findInstallationCollision(o);if(s){$.showErrorMessage(`Templates not installed: `+s);return}for(let r of o)try{e.replaceLocalInstallation(r.path,this.templatePath[0],r.destination),t.push(r.name)}catch(e){n.push(`Template ${r.name} failed: ${String(e)}`)}if(t.length>0){await this.reloadTemplates();let e=`Templates installed`;n.length>0&&(e+=`: `+t.join(`, `)),$.showInformationMessage(e)}for(let e of n)$.showErrorMessage(e)}}else if(t.label==`Git`){let e=await this.getGitURL();e&&await Yo(`git clone `+e,{cwd:this.templatePath[0]}),await this.reloadTemplates()}else t.label==`Store`&&await this.downloadTemplateFromStore()}async selectGlobalToImport(t){if(this.globalPath.length==0){$.showErrorMessage(`No global template path registered`);return}let n=await $.Select([{label:`Local`},{label:`Git`}],{title:`Select a source from where to import global templates`});if(n){if(n.label==`Local`){let n=$.extensionPath+f.sep+`templates`+f.sep+`global`,r=(0,u.readdirSync)(n),i=new Map,a={};for(let e of r){let r=n+f.sep+e;if((0,u.statSync)(r).isDirectory()){let n=r+f.sep+E.Template;if((0,u.existsSync)(n))try{let o=await ro.create(n);if(o){a[r]=o;let n={label:o.name,detail:[o.description,e].filter(Boolean).join(` - `),picked:t,id:r};i.set(n,r)}}catch{}}}let o=await $.SelectMultiple(Array.from(i.keys()),{title:`Select global templates to import`});if(o){let t=!1;for(let n of o){let r=this.getSelectItem(i,n);if(r){let n=a[r].installationFolder??r.split(f.sep).pop(),i=e.getInstallationPath(this.globalPath[0],n);if(!i){$.showErrorMessage(`Invalid installation folder`);continue}(0,u.existsSync)(i)&&(0,u.rmSync)(i,{recursive:!0,force:!0}),(0,u.cpSync)(r,i,{force:!0,recursive:!0}),t=!0}}t&&$.showInformationMessage(`Global templates installed`)}}else if(n.label==`Git`){let e=await this.getGitURL();e&&await Yo(`git clone `+e,{cwd:this.globalPath[0]})}else n.label==`Store`&&await this.downloadTemplateFromStore();await this.reloadGlobal()}}async selectProjectToUninstall(){let e=this.getGeneralProjects(),t=[],n=[],r=e=>{for(let i in e){let a=e[i];a instanceof ro?(t.push(a),n.push({label:a.name,detail:a.config})):r(a)}};r(e);let i=await $.SelectMultiple(n,{title:`Select projects to remove`});i&&this.removeSelectedInstallations(i,n,t,()=>this.getGeneralProjects(),this.projectPath)>0&&(await this.reloadProjects(),$.showInformationMessage(`Projects deleted`))}async selectTemplateToUninstall(){let e=this.getGeneralTemplates(),t=[],n=[],r=e=>{for(let i in e){let a=e[i];a instanceof ro?(t.push(a),n.push({label:a.name,detail:a.config})):r(a)}};r(e);let i=await $.SelectMultiple(n,{title:`Select templates to remove`});i&&this.removeSelectedInstallations(i,n,t,()=>this.getGeneralTemplates(),this.templatePath)>0&&(await this.reloadTemplates(),$.showInformationMessage(`Templates deleted`))}async selectGlobalToUninstall(){let e=this.getGeneralGlobal(),t=[],n=[],r=e=>{for(let i in e){let a=e[i];a instanceof ro?(t.push(a),n.push({label:a.name,detail:a.config})):r(a)}};r(e);let i=await $.SelectMultiple(n,{title:`Select global templates to remove`});i&&this.removeSelectedInstallations(i,n,t,()=>this.getGeneralGlobal(),this.globalPath)>0&&(await this.reloadGlobal(),$.showInformationMessage(`Global templates deleted`))}removeSelectedInstallations(e,t,n,r,i){let a=0,o=new Set;for(let s of e){let e=t.findIndex(e=>e.label===s.label&&e.detail===s.detail);if(e<0)continue;let c=n[e];if(o.has(c)||xs(c.name,r())!==c)continue;let l=(0,f.resolve)((0,f.dirname)(c.config));!i.some(e=>{let t=(0,f.relative)((0,f.resolve)(e),l);return t!==``&&t!==`..`&&!t.startsWith(`..`+f.sep)&&!(0,f.isAbsolute)(t)})||!(0,u.existsSync)(c.config)||(o.add(c),(0,u.rmSync)(l,{recursive:!0,force:!0}),a++)}return a}getSelectItem(e,t){if(e.has(t))return e.get(t);for(let n of e.keys())if(t.id?n.id===t.id:n.label===t.label&&n.detail===t.detail)return e.get(n);return null}async query(e,t,n){let r=this.findWorkspace(e),i=async t=>{let n={};for(let[a,o]of Object.entries(t))if(o instanceof ro)await o.isAllowed(e,r)&&(n[a]=o);else{let e=await i(o);Object.keys(e).length>0&&(n[a]=e)}return n},a=await i(t);if(Object.keys(a).length===0&&(!n||n.length===0))throw new io(`No templates available for this location`);return this.queryAllowed(a,n)}async queryAllowed(e,t){let n=!0;t||=(n=!1,[]);let r=new Map,i=new Map;for(let n in e){let a=e[n],o;a instanceof ro?(o={label:n,detail:a.description??``},i.set(o,a)):(o={label:n},r.set(o,a)),t.push(o)}if(t.sort((e,t)=>e.label.localeCompare(t.label)),t.length===0)return null;let a=await $.Select(t,{title:`What do you want to create?`});if(a){let e=this.getSelectItem(i,a);if(e)return e;let t=this.getSelectItem(r,a);if(t)return this.queryAllowed(t);if(n)return a}return null}async downloadTemplateFromStore(t){let n;try{let r=`^${so.url.replace(/\//g,`\\/`)}\\/template\\/download\\/(?<name>[^/]+)\\/(?<version>\\d+\\.\\d+\\.\\d+)$`;if(!t){let e=await $.Input({title:`Store url`,validations:[{message:`The store url must be `+so.url+`/template/download/{name}/{version}$`,regex:r}]});if(!e)return;t=e}let i=t.match(new RegExp(r));if(!i){$.showErrorMessage(`The uri provided is wrong`);return}let a=i[1];i[2],n=(0,f.join)($.savePath,`temp`,`packageTemp`),(0,u.rmSync)(n,{recursive:!0,force:!0}),(0,u.mkdirSync)(n,{recursive:!0});let o=(0,f.join)(n,`temp.zip`);if(!await this.downloadFile(o,t)){$.showErrorMessage(`Error downloading package`);return}if(!await this.extractZip(o,n)){$.showErrorMessage(`Error extracting package to analyze`);return}if((0,u.existsSync)((0,f.join)(n,E.Template))){let t=await ro.create((0,f.join)(n,E.Template));if(!t){$.showErrorMessage(`The template contains error`);return}let r=t.isGlobal?this.globalPath[0]:t.isProject?this.projectPath[0]:this.templatePath[0],i=t.installationFolder??a,s=e.getInstallationPath(r,i);if(!s){$.showErrorMessage(`Invalid installation folder`);return}if(!await this.extractZip(o,s)){$.showErrorMessage(`Error extracting package`);return}t.isGlobal?await this.reloadGlobal():t.isProject?await this.reloadProjects():await this.reloadTemplates(),$.showInformationMessage(`Template `+a+` installed`)}else $.showErrorMessage(E.Template+` not found`)}catch(e){$.showErrorMessage(`Error unknown`),console.error(e)}finally{n&&(0,u.rmSync)(n,{recursive:!0,force:!0})}}downloadFile(e,t){return new Promise(n=>{try{(t.startsWith(`https`)?oe.get:x.get)(t,t=>{if(!t.statusCode||t.statusCode<200||t.statusCode>=300){t.resume(),n(!1);return}(0,C.pipeline)(t,(0,u.createWriteStream)(e),t=>{t&&(0,u.existsSync)(e)&&ks(e),n(!t)})}).on(`error`,()=>n(!1))}catch{n(!1)}})}async extractZip(e,t){try{return await(await se.Open.file(e)).extract({path:t}),!0}catch(e){console.error(`Extract error `,e)}return!1}async readGlobal(){let e=this.getGeneralGlobal(),t=this.getGeneralGlobalLength(),n=$.getWorkspaceUri();if(n){let r=L(n)+`/.aventus/global`;return await this.readTemplates([r],e,t)}return{templates:e,nb:t}}},so=class e{static url=`https://store.aventusjs.com`;static _settings;static sessionRevision=0;static get settings(){return this._settings||=F.getInstance().hiddenSettings.store,this._settings}static get token(){return this.settings.token}static get isConnected(){return this.token!=``}static setSettings(e){let t={...this.settings,...e};F.getInstance().setHiddenSettings({store:t}),this._settings=t}static async connect(e,t){let n=++this.sessionRevision,r=await(0,Ii.machineId)(),i=(0,le.hostname)(),a=await this.post(`/login`,{username:e,password:t,machineId:r,machineName:i},{withoutBearer:!0});return n===this.sessionRevision&&a?(this.setSettings({token:a,username:e}),!0):!1}static async disconnect(){let e=++this.sessionRevision;await this.post(`/logout`),e===this.sessionRevision&&this.setSettings({token:``,username:void 0})}static async publishPackage(e){let t=new FormData;t.append(`name`,e.buildConfig.fullname),t.append(`description`,e.buildConfig.description??``),t.append(`version`,e.buildConfig.version),e.buildConfig.organization&&t.append(`organization`,e.buildConfig.organization),e.buildConfig.documentation&&t.append(`documentation`,e.buildConfig.documentation),e.buildConfig.repository&&t.append(`repository`,e.buildConfig.repository);for(let n of e.buildConfig.tags)t.append(`tags[]`,n);let n=(0,f.join)(lo.getInstance().getPath(),`@locals`,e.buildConfig.fullname+E.Package);if(!(0,u.existsSync)(n))return!1;let r=new Blob([(0,u.readFileSync)(n)],{type:`text/plain`});t.append(`packageFile`,r,e.buildConfig.fullname+E.Package);let i=e.project.getConfigFile().folderPath;if(e.buildConfig.readme){let n;if(e.buildConfig.readme.startsWith(`.`)){let t=(0,f.normalize)((0,f.join)(i,e.buildConfig.readme));if((0,u.existsSync)(t))n=t;else return new co([{code:-1,message:`Readme not found`}])}else if((0,u.existsSync)(e.buildConfig.readme))n=e.buildConfig.readme;else{let t=(0,f.normalize)((0,f.join)(i,e.buildConfig.readme));if((0,u.existsSync)(t))n=t;else return new co([{code:-1,message:`Readme not found`}])}let r=new Blob([(0,u.readFileSync)(n)],{type:`text/plain`});t.append(`readMe`,r,`README.md`)}else{let e=(0,u.readdirSync)(i).find(e=>e.toLowerCase()===`readme.md`);if(e){let n=new Blob([(0,u.readFileSync)((0,f.join)(i,e))],{type:`text/plain`});t.append(`readMe`,n,`README.md`)}}return await this.postWithErrors(`/package/publish`,t)}static async publishTemplate(e){if(!oo.getInstallationPath(e.folderPath,e.installationFolder??e.name))return new co([{code:422,message:`Invalid installation folder`}]);let t=new FormData;t.append(`name`,e.name),t.append(`description`,e.description),t.append(`version`,e.version),t.append(`is_project`,e.isProject?`1`:`0`),t.append(`is_global`,e.isGlobal?`1`:`0`),e.organization&&t.append(`organization`,e.organization),e.documentation&&t.append(`documentation`,e.documentation),e.repository&&t.append(`repository`,e.repository);for(let n of e.tags)t.append(`tags[]`,n);let n=e.folderPath,r=(0,u.readdirSync)(n).find(e=>e.toLowerCase()===`readme.md`);if(r){let e=new Blob([(0,u.readFileSync)((0,f.join)(n,r))],{type:`text/plain`});t.append(`readMe`,e,`README.md`)}let i=(0,f.dirname)(e.config),a=(0,f.join)($.savePath,`temp`,e.name+`.zip`);await this.zip(i,a);let o=new Blob([(0,u.readFileSync)(a)],{type:`application/zip`});t.append(`templateFile`,o,e.name+`.zip`);let s=await this.postWithErrors(`/template/publish`,t);return ks(a),s}static async post(e,t={},n){let r=await this.postWithErrors(e,t,n);if(r instanceof co){for(let e of r.errors)$.error(e.message);return null}return r}static async postWithErrors(t,n={},r){let i=null,a=this.sessionRevision,o=r?.withoutBearer===!0,s=o?void 0:this.token,c=()=>{let e=a===this.sessionRevision,t=o||s===this.token;return e&&t};try{let r={};if(n instanceof FormData||(r[`Content-Type`]=`application/json`),!o){let e=await(0,Ii.machineId)();r.Authorization=`Bearer `+(s+`|`+e)}if(i=await fetch(e.url+`/api/remote`+t,{method:`POST`,body:n instanceof FormData?n:JSON.stringify(n),headers:r}),i.status==401)return c()&&this.setSettings({token:``,username:void 0}),new co([{code:401,message:`No token provided`}]);if(i.status==403)return t!=`/logout`&&c()&&await this.disconnect(),new co([{code:403,message:`You must connect to your account first`}]);if(i.status<200||i.status>=300)return new co([{code:i.status,message:`Store request failed with HTTP ${i.status}`}]);let a=await i.text(),l;try{l=JSON.parse(a)}catch(e){throw $.error(a),e}return!l||!Array.isArray(l.errors)?new co([{code:-500,message:`Wrong response format from the api`}]):l.errors.length>0?new co(l.errors):Object.hasOwn(l,`result`)?l.result:new co([{code:-500,message:`Wrong response format from the api`}])}catch(e){return new co([{code:-500,message:e+``}])}}static zip(e,t){return new Promise(async(n,r)=>{let i=(0,u.createWriteStream)(t),a=(0,ue.create)(`zip`,{zlib:{level:9}});i.on(`close`,()=>{n()}),a.on(`error`,e=>{r(e)}),a.pipe(i),a.directory(e,!1,e=>e.name.split(/[\\/]/).includes(`.git`)?!1:e),await a.finalize()})}},co=class{errors;constructor(e){this.errors=e}},lo=class e{path;static instance;static getInstance(){return this.instance||=new e,this.instance}getPath(){return this.path}constructor(){this.path=(0,f.join)($.savePath,`packages`),(0,u.existsSync)(this.path)||(0,u.mkdirSync)(this.path,{recursive:!0})}predefinedPaths={"Aventus@Main":Tt(),"Aventus@UI":Et(),"Aventus@Sharp":Ot(),"Aventus@Php":kt(),"Aventus@I18n":Dt()};predefinedNpm={"Aventus@Main":`@aventusjs/main`,"Aventus@UI":`@aventusjs/ui`,"Aventus@I18n":`@aventusjs/i18n`,"Aventus@Sharp":`@aventussharp/main`,"Aventus@Php":`@aventusphp/main`};loadedPackages={};get packages(){let e=[];for(let t in this.loadedPackages)e.push(this.loadedPackages[t]);return e}async loadDependenciesFromBuild(e,t){let n={files:[],dependencyNeedUris:[],dependencyFullUris:[],dependencyUris:[]},r={},i={},a=new Set;for(let n in e.dependencies){let o=e.dependencies[n],s=await this.loadDependency(n,o,e,t,r);s&&(a.add(s.name),i[s.name]=o.include??`need`)}for(let e in r)i[e]||(i[e]=r[e].include);r[`Aventus@Main`]||await this.loadDependency(`Aventus@Main`,{uri:``,npm:``,version:`x.x.x`,include:`need`,subDependenciesInclude:{"*":`need`}},e,t,r),r[`Aventus@Main`]&&a.add(`Aventus@Main`),t.buildConfig.i18n!==void 0&&!r[`Aventus@I18n`]&&await this.loadDependency(`Aventus@I18n`,{uri:``,npm:``,version:`x.x.x`,include:`need`,subDependenciesInclude:{"*":`need`}},e,t,r),t.buildConfig.i18n!==void 0&&r[`Aventus@I18n`]&&a.add(`Aventus@I18n`);let o=new Set,s=e=>{if(!(o.has(e)||!r[e])){o.add(e);for(let t of r[e].dependencies)s(t.name)}};for(let e of a)s(e);for(let e of Object.keys(r))o.has(e)||delete r[e];let c=this.findCycle(r);if(c)return n.cycle=c,n;let l=[];for(let e in r){let t=r[e];this.orderLoop(e,t,r,l)}for(let e of l){let t=r[e];t.file.loadWebComponents(),n.files.push(t.file);let a=i[e]??`need`;a==`full`?(n.dependencyFullUris.push(t.uri),n.dependencyUris.push(t.uri)):a==`need`&&(n.dependencyNeedUris.push(t.uri),n.dependencyUris.push(t.uri))}return n}findCycle(e){let t=new Set,n=[],r=i=>{let a=n.indexOf(i);if(a>=0)return[...n.slice(a),i];if(t.has(i))return null;t.add(i),n.push(i);for(let t of e[i].dependencies)if(e[t.name]){let e=r(t.name);if(e)return e}return n.pop(),null};for(let t of Object.keys(e)){let e=r(t);if(e)return e}return null}orderLoop(e,t,n,r){let i=r.indexOf(e);if(i!=-1)return i+1;let a=0;for(let e of t.dependencies)if(n[e.name]){let t=this.orderLoop(e.name,n[e.name],n,r);t>=0&&t>a&&(a=t)}return r.splice(a,0,e),r.length}async loadDependency(e,t,n,r,i){let a,o;if(this.predefinedPaths[e]){t.uri=this.predefinedPaths[e];let n=I(t.uri);a=await this.loadByUri(r,n),o=n}else if(t.uri)if(t.uri.startsWith(`http`))$.showErrorMessage(`http package isn't supported right now. Plz use the store`);else{let e=I(t.uri);a=await this.loadByUri(r,e),o=e}else if(t.isLocal){let t=await this.loadLocal(e,r);a=t.file,o=t.uri}else if(t.version){let n=await this.loadStore(e,t.version,r);n?(a=n.file,o=n.uri):$.showErrorMessage(`Can't load `+e+` from the store`)}else $.showErrorMessage(`You need to define a version to load a package via the store (`+e+`)`);if(o&&a){let s=t.version?this.parseVersion(t.version):{major:-1,minor:-1,patch:-1};if(t.npm)a.npmUri=t.npm;else if(this.predefinedNpm[e])a.npmUri=this.predefinedNpm[e];else{let e=/\/\/ npm:(.*)$/m.exec(a.file.contentUser);e?a.npmUri=e[1]:a.npmUri=``}let c=/\/\* description:(.*) \*\//gm.exec(a.file.contentUser);c?a.description=c[1]:a.description=``;let l=async(e,a)=>{i[e.name]={file:e,uri:a,include:t.include??`need`,version:s,dependencies:[]};for(let a in e.dependencies){let o=e.dependencies[a];typeof o==`string`&&(o={version:o}),t.include==`none`&&(o.include=`none`);let s=await this.loadDependency(a,o,n,r,i);if(s){let n=i[e.name].dependencies.find(e=>e.name==s.name),r=`need`;t.include==`none`&&(r=`none`),o.subDependenciesInclude&&o.subDependenciesInclude[s.name]&&(r=o.subDependenciesInclude[s.name]),n?(n.include==`none`&&r!=`none`||n.include==`need`&&r==`full`)&&(n.include=r):i[e.name].dependencies.push({name:s.name,include:r})}}e.name!=`Aventus@Main`&&(i[e.name].dependencies.find(e=>e.name==`Aventus@Main`)||i[e.name].dependencies.push({name:`Aventus@Main`,include:`need`}))};if(!i[a.name])await l(a,o);else{let e=i[a.name].version;this.compareVersion(e,s,a.name)==s&&await l(a,o)}await qa.register(a)}return a}async loadByUri(e,t){let n=await z.getInstance().registerFilePackage(t);return this.loadPackage(n,e)}async loadLocal(e,t){let n=I((0,f.join)(this.path,`@locals`,e));n.endsWith(E.Package)||(n+=E.Package);let r=await z.getInstance().registerFilePackage(n),i=this.loadPackage(r,t);return{uri:n,file:i}}async loadStore(e,t,n){let r=(0,f.join)(this.path,`store`,e,t),i=(0,u.existsSync)(r),{major:a,minor:o,patch:s}=this.parseVersion(t),c=null;if(i&&(c=this.findPackage(r),c||(i=!1)),!i){(0,u.existsSync)(r)&&(0,u.rmSync)(r,{force:!0,recursive:!0}),(0,u.mkdirSync)(r,{recursive:!0});let n=(0,f.join)(r,`temp.zip`);if(!await this.downloadFile(n,so.url+`/package/download/${e}/${t}`)||!await this.extractZip(n,r))return null;if((0,u.rmSync)(n,{force:!0}),c=this.findPackage(r),!c)return;let i=await this.readFirstLine(c),a=/\/\/ (\S+):([0-9]+)\.([0-9]+)\.([0-9]+)/g.exec(i);if(!a)return console.error(`Invalid package header for "${e}@${t}". First line:`,JSON.stringify(i)),null;let o=a[1],s=Number(a[2]),l=Number(a[3]),d=Number(a[4]),p=s+`.`+l+`.`+d;if(o!==e)return console.error(`Package name mismatch: requested "${e}", downloaded "${o}"`),null;if(p!==t)return console.error(`Package version mismatch: requested "${t}", downloaded "${p}"`),null}if(!c)return console.error(`Package file not found after extracting "${e}@${t}" into "${r}"`),null;let l=I(c),d=await z.getInstance().registerFilePackage(l);return{uri:l,file:this.loadPackage(d,n)}}extractZip(e,t){return new Promise(n=>{let r=!1,i=e=>{r||(r=!0,n(e))},a=(0,u.createReadStream)(e),o=(0,se.Extract)({path:t});a.on(`error`,t=>{console.error(`Can't read ZIP "${e}":`,t),i(!1)}),o.on(`close`,()=>i(!0)),o.on(`error`,t=>{console.error(`Can't extract ZIP "${e}":`,t),(t+``).includes(`Error: invalid signature: 0x4f44213c`)&&console.log((0,u.readFileSync)(e,`utf8`)),i(!1)}),a.pipe(o)})}findPackage(e){let t=null,n=(0,u.readdirSync)(e);for(let r of n)if(r.endsWith(E.Package)){t=(0,f.join)(e,r);break}return t}loadPackage(e,t){if(!e)return;let n=Tn.getQuickInfo(e);if(!n)return;let r=new Tn(e,t);return this.loadedPackages[n.name]=r,e.onDelete(async()=>{this.loadedPackages[n.name]===r&&delete this.loadedPackages[n.name]}),r}downloadFile(e,t){return new Promise(n=>{let r=`${e}.${(0,_.randomUUID)()}.tmp`,i=!1,a=()=>{try{(0,u.existsSync)(r)&&ks(r)}catch{}},o=e=>{i||(i=!0,e||a(),n(e))};(t.startsWith(`https:`)?oe.get:x.get)(t,n=>{let i=n.statusCode??0;if(i>=300&&i<400&&n.headers.location){n.resume(),this.downloadFile(e,new URL(n.headers.location,t).href).then(o).catch(()=>o(!1));return}if(i<200||i>=300){console.error(`Download failed: HTTP ${i} for ${t}`),n.resume(),o(!1);return}let a=(0,u.createWriteStream)(r,{flags:`wx`}),s=!1;a.on(`error`,t=>{console.error(`File write error for ${e}:`,t),s=!0,n.destroy()}),n.on(`error`,e=>{console.error(`HTTP response error for ${t}:`,e),s=!0,a.destroy()}),n.on(`aborted`,()=>{s=!0,a.destroy()}),a.on(`close`,()=>{if(s||!a.writableFinished||!n.complete){o(!1);return}try{(0,u.renameSync)(r,e),o(!0)}catch(t){console.error(`File replace error for ${e}:`,t),o(!1)}}),n.pipe(a)}).on(`error`,e=>{console.error(`HTTP request error for ${t}:`,e),o(!1)})})}readFirstLine(e){return new Promise(function(t,n){var r=(0,u.createReadStream)(e,{encoding:`utf8`}),i=``;r.on(`data`,function(e){i+=e,i.includes(`
|
|
666
666
|
`)&&r.close()}).on(`close`,function(){let e=i.indexOf(`
|
|
667
667
|
`);t(e===-1?i:i.slice(0,e))}).on(`error`,function(e){n(e)})})}parseVersion(e){let t=/([0-9xX]+)\.([0-9xX]+)\.([0-9xX]+)/g.exec(e)??[0,-1,-1,-1];return{major:isNaN(Number(t[1]))?-1:Number(t[1]),minor:isNaN(Number(t[2]))?-1:Number(t[2]),patch:isNaN(Number(t[3]))?-1:Number(t[3])}}compareVersion(e,t,n){let r=r=>{if(e[r]==-1)return t[r]==-1?null:t;if(t[r]==-1)return e;if(e[r]==t[r])return null;{let r=Object.values(e).join(`.`),i=Object.values(t).join(`.`);return $.showErrorMessage(`Can't resolve version for dependency ${n} between ${r} and ${i}`),-1}};for(let e of[`major`,`minor`,`patch`]){let t=r(e);if(typeof t==`number`)return null;if(t)return t}return e}},uo=class{infos={};lastInfo=``;lastInfoToCompile=``;internalNames=[];build;storedInfo={};constructor(e){this.build=e}getInternalName(e){if(e=="default"&&(e=`_default`),!this.internalNames.includes(e))return this.internalNames.push(e),e;let t=0,n=e+`_`+t;for(;this.internalNames.includes(n);)t++,n=e+`_`+t;return this.internalNames.push(n),n}register(e,t,n){if(t.libName==`*`&&!t.alias)return[{range:n??m.Range.create(0,0,0,0),severity:m.DiagnosticSeverity.Error,source:T.TypeScript,message:`The lib ${t.uri} inside the file ${e} has no alias => impossible`}];this.storedInfo[e]||(this.storedInfo[e]=[]);let r=t.alias||t.libName,i=Object.values(this.storedInfo).flat(),a=[],o=new Set;for(let e of i){let i=e.alias||e.libName;e.uri===t.uri&&i==r&&e.libName!==t.libName&&!o.has(e.libName)&&(o.add(e.libName),a.push({range:n??m.Range.create(0,0,0,0),severity:m.DiagnosticSeverity.Error,source:T.TypeScript,message:`The npm alias ${r} for ${t.uri} is used by both ${e.libName} and ${t.libName}`}))}return this.storedInfo[e].push(t),this.rebuildInfo(),a}unregister(e){this.storedInfo[e]&&(delete this.storedInfo[e],this.rebuildInfo())}rebuildInfo(){if(this.build.isBuildAllowed){this.infos={},this.internalNames=[];for(let e in this.storedInfo)for(let t of this.storedInfo[e]){let n=t.uri;if(this.infos[n]||(this.infos[n]={md5:Os(n),part:{}}),t.libName==`*`){if(!t.alias)throw`The lib ${n} inside the file ${e} has no alias => impossible`;let r=this.infos[n].all;r||(r={externalAlias:[],internalAlias:this.getInternalName(`_default`)},this.infos[n].all=r),r.externalAlias.includes(t.alias)||r.externalAlias.push(t.alias)}else{let e=this.infos[n].part;e[t.libName]||(e[t.libName]={externalAlias:[],internalAlias:this.getInternalName(t.libName)});let r=t.alias?t.alias:t.libName;e[t.libName].externalAlias.includes(r)||e[t.libName].externalAlias.push(r)}}}}npmBuildTxt=``;npmDepBuildTxt={result:``,errors:[]};compiling;lastDependencies=``;getDependencies(){try{let e=JSON.parse((0,u.readFileSync)((0,f.join)((0,f.dirname)(this.build.nodeModulesDir),`package.json`),`utf8`)),t=(e={})=>Object.entries(e).sort(([e],[t])=>e.localeCompare(t));return JSON.stringify([t(e.dependencies),t(e.devDependencies)])}catch{return``}}async compile(){if(this.compiling)return await this.compiling,await this.compile();let e=this.compileCurrent();this.compiling=e;try{return await e}finally{this.compiling===e&&(this.compiling=void 0)}}async compileCurrent(){if(Object.keys(this.infos).length==0)return this.lastInfo=``,this.lastInfoToCompile=``,this.npmBuildTxt=``,this.lastDependencies=``,{result:``,errors:[]};let e=JSON.stringify(this.infos),t=this.getDependencies(),n=this.lastDependencies!==t;if(this.lastInfo!=e||n){this.lastInfo=e,this.lastDependencies=t;let r=this.writeFileToCompile();(this.lastInfoToCompile!=r.buildTxt||n)&&(Ni.part(`Compiling node modules`),this.lastInfoToCompile=r.buildTxt,this.npmDepBuildTxt=await this.esbuildBuild(this.lastInfoToCompile),this.npmDepBuildTxt.errors.length>0&&(this.lastInfo=``,this.lastInfoToCompile=``),Ni.part(`Compiling node modules done`)),this.npmBuildTxt=`var npmCompilation;
|
|
668
668
|
`,this.npmBuildTxt+=`(npmCompilation||(npmCompilation = {}));
|
package/out/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
let e=require("commander"),t=require("path"),n=require("vscode-languageserver"),r=require("child_process"),i=require("fs");var a=class{static realInteraction;static async load(e){let t=eval;this.realInteraction=(await t(`import("./RealInteraction.js")`)).default.RealInteraction,this.realInteraction._server=o,e&&(this.realInteraction.config=e)}static async init(){this.clear(),console.log(`Welcome inside Aventus CLI`)}static clear(){this.realInteraction.clear()}static async select(e,t){return this.realInteraction?.select(e,t)||null}static async selectMultiple(e,t){return this.realInteraction?.selectMultiple(e,t)||null}static async input(e,t,n){return this.realInteraction?.input(e,t,n)||null}static async password(e,t){return this.realInteraction?.password(e,t)||null}static async tree(e,t,n){return this.realInteraction?.tree(e,t,n)||null}static async log(){return this.realInteraction?.log()||null}},o=class{static realServer;static get notifications(){return this.realServer?.notifications}static async load(){let e=eval;this.realServer=(await e(`import("./RealServer.js")`)).default.RealServer,this.realServer._interaction=a}static subscribeErrors(e){return this.realServer?.subscribeErrors(e)}static unsubscribeErrors(e){return this.realServer?.unsubscribeErrors(e)}static executeCommand(e,...t){return this.realServer?.executeCommand(e,...t)}static getErrors(){return this.realServer?.getErrors()}static start(e){return this.realServer?.start(e)}static create(){return this.realServer?.create()}static getStatistics(){return this.realServer?.getStatistics()}static async Input(e){return this.realServer?.Input(e)}},s=class e{static actions={};argsNb=0;register(t){let n=this.name.trim().split(` `),r=``,i=t;for(let t of n)r+=t,e.actions[r]||(e.actions[r]=i.command(t)),i=e.actions[r],r+=` `;i=i.description(this.description),i=this._registerArgs(i),i=this._registerOptions(i),i.action(async(...e)=>{let t=[];for(let n=0;n<this.argsNb;n++)t.push(e[n]);let n=e[this.argsNb];await this.run(t,n),process.exit(0)})}_registerArgs(e){return this.registerArgs(t=>{let n=``;if(t.type){let e=`<`,r=`>`;t.typeIsRequired!==void 0&&!t.typeIsRequired&&(e=`[`,r=`]`),t.typeIsArray&&(r=`...`+r),n+=`${e}${t.type}${r}`}this.argsNb++,e=e.argument(n,t.description,t.defaultValue)}),e}_registerOptions(e){let t=new Set,n=[];return this.registerOptions(r=>{let i=r.name;e.on(`option:${i}`,()=>t.add(i));for(let e of r.conflicts?[].concat(r.conflicts):[])n.push([i,e]);let a=[];if(r.shortName){Array.isArray(r.shortName)||(r.shortName=[r.shortName]);for(let e of r.shortName)a.push(`-`+e)}a.push(`--`+r.name);let o=a.join(`, `);if(r.type){let e=`<`,t=`>`;r.typeIsRequired!==void 0&&!r.typeIsRequired&&(e=`[`,t=`]`),r.typeIsArray&&(t=`...`+t),o+=` ${e}${r.type}${t}`}e=r.required?e.requiredOption(o,r.description,r.defaultValue):e.option(o,r.description,r.defaultValue)}),e.hook(`preAction`,()=>{let r=n.find(([e,n])=>t.has(e)&&t.has(n));t.clear(),r&&e.error(`options '--${r[0]}' and '--${r[1]}' cannot be used together`,{code:`commander.conflictingOption`})}),e}},c=class{register(e){let t=this.name.trim().split(` `),n=``,r=e;for(let e of t)n+=e,s.actions[n]||(s.actions[n]=r.command(e)),r=s.actions[n],n+=` `;r=r.description(this.description)}};function l(e){return t.sep===`/`?decodeURIComponent(e.replace(`file://`,``)):decodeURIComponent(e.replace(`file:///`,``))}function u(e){if(e.startsWith(`file://`))return e;let n=e[0].toLowerCase()+e.substring(1);return n=d(encodeURI(n.replace(/\\/g,`/`))),t.sep===`/`?`file://`+n:`file:///`+n}function d(e){return e.replace(/:/g,`%3A`).replace(/@/g,`%40`)}function f(e){let t=1024,n=[`Bytes`,`KiB`,`MiB`,`GiB`,`TiB`,`PiB`,`EiB`,`ZiB`,`YiB`],r=e==0?0:Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/t**r).toFixed(2))} ${n[r]}`}const p={Error:n.DiagnosticSeverity.Error,Warning:n.DiagnosticSeverity.Warning,Information:n.DiagnosticSeverity.Information,Hint:n.DiagnosticSeverity.Hint};var m=class extends s{get name(){return`build`}get description(){return`Build an aventus project`}registerArgs(e){e({description:`aventus.conf.avt path`,type:`string`,typeIsRequired:!1})}registerOptions(e){e({name:`builds`,conflicts:`no-builds`,description:`Define the build name`,type:`string`,typeIsRequired:!0,typeIsArray:!0}),e({name:`no-builds`,description:`No builds`,type:`boolean`,typeIsRequired:!1}),e({name:`statics`,conflicts:`no-statics`,description:`Define the static files to export`,type:`string`,typeIsRequired:!0,typeIsArray:!0}),e({name:`no-statics`,description:`No statics`,type:`boolean`,typeIsRequired:!1}),e({name:`verbose`,conflicts:`silent`,shortName:`v`,description:`Debug your compilation`}),e({name:`silent`,shortName:`s`,description:`No output`}),e({name:`json`,type:`boolean`,typeIsRequired:!1,description:`Result as json`})}async run(e,n){let r=e[0];r&&=(0,t.resolve)(r),await o.load(),n.builds===!1&&(n.builds=[]),n.statics===!1&&(n.statics=[]),await o.start({configPath:r,loadFiles:!0,buildOnly:n[`no-statics`],noBuild:n[`no-builds`],builds:n.builds,statics:n.statics,logLevel:n.verbose?0:3,errorByBuild:!0,useStats:!n.silent}),n.json?this.handleResultJson(n):this.handleResult(n)}handleResult(e){let t=o.getStatistics(),n=e.silent?e=>{}:console.log;n(),n(`Loading all files : Done in `+t.loadFileTime+`ms`),n(),n(`----`),n();let r=o.getErrors(),i=!1;if(r[``])for(let t in r[``])for(let n of r[``][t])n.severity===p.Error&&(i=!0),e.silent||console.error(`${l(t)}:${n.range.start.line+1} : ${n.message}`);let a={},s={};for(let e in t.files){let n=t.files[e];if(n.type==`build`&&n.typeName){a[n.typeName]||(a[n.typeName]=[]);let e=` ${n.path} - ${f(n.size)}`;a[n.typeName].push(e)}else if(n.type==`static`&&n.typeName){s[n.typeName]||(s[n.typeName]=[]);let e=` ${n.path} - ${f(n.size)}`;s[n.typeName].push(e)}}let c=Object.keys(t.builds).length,u=Object.keys(t.statics).length,d=0;for(let o in t.builds){n(`Building `+o),n();let s=!1,f=r[o],m=t.builds[o],h=a[o];if(h){for(let e of h)n(e);n()}if(f){let t=!1;for(let n in f)for(let r of f[n]){let i=``,a;if(r.severity==p.Error)i=`\x1B[31m[error]\x1B[0m`,s=!0,a=console.error;else if(r.severity==p.Warning)i=`\x1B[33m[warning]\x1B[0m`,a=console.warn;else if(r.severity==p.Information)i=`\x1B[34m[info]\x1B[0m`,a=console.info;else if(r.severity==p.Hint){i=`\x1B[90m[hint]\x1B[0m`;continue}e.silent||(a(` ${i} ${l(n).replace(/\\/g,`/`)}:${r.range.start.line+1} : ${r.message}`),t=!0)}t&&n()}s?(n(` Build failed in `+m.buildTime+`ms`),i=!0):n(` Build success in `+m.buildTime+`ms`),d++,d==c&&u==0?n():(n(),n(`----`),n())}d=0;for(let e in t.statics){n(`Export static `+e),n();let r=t.statics[e],i=s[e];if(i){for(let e of i)n(e);n()}n(` Exported in `+r.buildTime+`ms`),d++,d==u?n():(n(),n(`----`),n())}i&&process.exit(1)}handleResultJson(e){let t=o.getStatistics(),n={success:!0,builds:{},statics:{}},r=o.getErrors(),i=!1;if(r[``])for(let e in r[``]){let t=l(e).replace(/\\/g,`/`);n.diagnostics||={},n.diagnostics[t]=[];for(let a of r[``][e])a.severity===p.Error&&(n.success=!1,i=!0),n.diagnostics[t].push({content:a.message,type:a.severity===p.Error?`error`:a.severity===p.Warning?`warning`:a.severity===p.Information?`info`:`hint`,start:`${a.range.start.line+1}:${a.range.start.character}`,end:`${a.range.end.line+1}:${a.range.end.character}`})}let a=e=>{n.builds[e]||(n.builds[e]={diagnostics:{},outputSize:{},success:!0})},s=e=>{n.statics[e]||(n.statics[e]={outputSize:{}})},c=e=>{let t=1024,n=[`Bytes`,`KiB`,`MiB`,`GiB`,`TiB`,`PiB`,`EiB`,`ZiB`,`YiB`],r=e==0?0:Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/t**r).toFixed(2))} ${n[r]}`};for(let e in t.files){let r=t.files[e];if(r.type==`build`&&r.typeName){let e=r.typeName,t=l(r.path).replace(/\\/g,`/`);a(e),n.builds[e].outputSize[t]=c(r.size)}else if(r.type==`static`&&r.typeName){let e=l(r.path).replace(/\\/g,`/`);s(r.typeName),n.statics[r.typeName].outputSize[e]=c(r.size)}}for(let e in t.builds){a(e);let t=r[e];if(t)for(let r in t){let a=l(r).replace(/\\/g,`/`),o=[];n.builds[e].diagnostics[a]=o;for(let a of t[r]){let t;a.severity==p.Error?(n.builds[e].success=!1,n.success=!1,i=!0,t=`error`):a.severity==p.Warning?t=`warning`:a.severity==p.Information?t=`info`:a.severity==p.Hint&&(t=`hint`),o.push({content:a.message,start:a.range.start.line+1+`:`+a.range.start.character,end:a.range.end.line+1+`:`+a.range.end.character,type:t})}}}console.log(JSON.stringify(n,void 0,4)),i&&process.exit(1)}},h=class extends s{get name(){return`dev`}get description(){return`Start an interactive cli to dev with your aventus project`}registerArgs(e){e({description:`aventus.conf.avt path`,type:`string`,typeIsRequired:!1})}registerOptions(e){}async run(e,t){await a.load({clear:!0,printLogo:!0}),await o.load(),console.clear(),await a.init(),await o.start({loadFiles:!0,watchFiles:!0,useCompilators:!0,useTemplates:!0});let n=[{value:`create`,name:`Create...`},{value:`log`,name:`Show logs`},{value:`quit`,name:`Quit`}];for(a.clear();;){let e=await a.select(`Which action shoud I perform?`,n);e==`create`?await o.create():e==`log`?await a.log():e==`quit`?process.exit(0):console.log(`WIP`),a.clear()}}},g=class extends s{get name(){return`check`}get description(){return`Check an aventus project`}registerArgs(e){e({description:`aventus.conf.avt path`,type:`string`,typeIsRequired:!1})}registerOptions(e){e({name:`builds`,description:`Define the build name`,type:`string`,typeIsRequired:!0,typeIsArray:!0}),e({name:`json`,type:`boolean`,typeIsRequired:!1,description:`Result as json`})}async run(e,n){let r=e[0];r&&=(0,t.resolve)(r),n.builds===!1&&(n.builds=[]),await o.load(),await o.start({noBuild:!0,loadFiles:!0,buildOnly:!0,configPath:r,builds:n.builds,statics:void 0,logLevel:3,errorByBuild:!0,useStats:!1}),n.json?this.handleResultJson(n):this.handleResult(n)}handleResult(e){let t=o.getStatistics(),n=console.log;n(),n(`Loading all files : Done in `+t.loadFileTime+`ms`),n(),n(`----`),n();let r=o.getErrors(),i=!1;for(let e in r){let t=!1,a=r[e];if(a){let e=!1;for(let n in a)for(let r of a[n]){let a=``,o;if(r.severity==p.Error)a=`\x1B[31m[error]\x1B[0m`,t=!0,i=!0,o=console.error;else if(r.severity==p.Warning)a=`\x1B[33m[warning]\x1B[0m`,o=console.warn;else if(r.severity==p.Information)a=`\x1B[34m[info]\x1B[0m`,o=console.info;else if(r.severity==p.Hint){a=`\x1B[90m[hint]\x1B[0m`;continue}o(` ${a} ${l(n).replace(/\\/g,`/`)}:${r.range.start.line+1} : ${r.message}`),e=!0}e&&n()}t||n(` Build has no error`)}i&&process.exit(1)}handleResultJson(e){let t={success:!0,builds:{}},n=o.getErrors(),r=!1,i=e=>{t.builds[e]||(t.builds[e]={diagnostics:{},success:!0})};for(let e in n){i(e);let a=n[e];if(a)for(let n in a){let i=l(n).replace(/\\/g,`/`),o=[];t.builds[e].diagnostics[i]=o;for(let i of a[n]){let n;i.severity==p.Error?(t.builds[e].success=!1,t.success=!1,r=!0,n=`error`):i.severity==p.Warning?n=`warning`:i.severity==p.Information?n=`info`:i.severity==p.Hint&&(n=`hint`),o.push({content:i.message,start:i.range.start.line+1+`:`+i.range.start.character,end:i.range.end.line+1+`:`+i.range.end.character,type:n})}}}console.log(JSON.stringify(t,void 0,4)),r&&process.exit(1)}},_=class extends s{get name(){return`format`}get description(){return`Format your project`}registerArgs(e){e({description:`aventus.conf.avt path`,type:`string`,typeIsRequired:!1})}registerOptions(e){}async run(e,n){let r=e[0];r&&=(0,t.resolve)(r),await o.load(),await o.start({noBuild:!0,configPath:r}),await o.executeCommand(`aventus.format`)}},v=class extends s{get name(){return`store login`}get description(){return`Login to the store`}registerArgs(e){}registerOptions(e){e({name:`username`,shortName:`u`,description:`Username for connection`,type:`string`,typeIsRequired:!0}),e({name:`password`,shortName:`p`,description:`Password for connection`,type:`string`,typeIsRequired:!0})}async run(e,t){try{await a.load(),await o.load(),await o.start({noStart:!0}),await o.executeCommand(`aventus.store.connect`,t.username,t.password)}catch(e){console.log(e),process.exit(1)}}},y=class extends s{get name(){return`store logout`}get description(){return`Logout from the store`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noStart:!0}),await o.executeCommand(`aventus.store.disconnect`)}catch(e){console.log(e),process.exit(1)}}},b=class extends s{get name(){return`store publish`}get description(){return`Publish to the store`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noStart:!0}),await o.executeCommand(`aventus.store.publish_package`)}catch(e){console.log(e),process.exit(1)}}},x=class extends s{get name(){return`create`}get description(){return`Create new project / files from a template`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noBuild:!0,useTemplates:!0,loadFiles:!0}),await o.executeCommand(`aventus.create`,u(process.cwd()))}catch(e){console.log(e)}}},S=class extends s{get name(){return`template install`}get description(){return`Import template to create aventus element`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noBuild:!0,useTemplates:!0}),await o.executeCommand(`aventus.template.import`)}catch(e){console.log(e),process.exit(1)}}},C=class extends s{get name(){return`project install`}get description(){return`Import project to init aventus`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noBuild:!0,useTemplates:!0}),await o.executeCommand(`aventus.template.import_project`)}catch(e){console.log(e),process.exit(1)}}},w=class{static cmd=`aventus/server/start`;static callbacks=[];static action(e){let t=[...this.callbacks];for(let n of t)n(e)}},T=class extends s{get name(){return`serve`}get description(){return`Start live server`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({loadFiles:!0,watchFiles:!0}),await o.executeCommand(`aventus.liveserver.start`),await this.waitStart(),await o.Input({title:`Press enter to stop server`})}catch(e){console.log(e)}}getAction(){return o.notifications.allNotifications[w.cmd]}waitStart(){return new Promise(e=>{let t=n=>{console.log(`Server started : `+n);let r=this.getAction().callbacks.indexOf(t);r!=-1&&this.getAction().callbacks.splice(r,1),e()};this.getAction().callbacks.push(t)})}},E=class extends s{get name(){return`dependencies help-llm`}get description(){return`Write dependencies to help llm`}registerArgs(e){}registerOptions(e){}async run(e,n){try{let n=e[0];n&&=(0,t.resolve)(n),await o.load(),await o.start({noBuild:!0,loadFiles:!1,configPath:n}),await o.executeCommand(`aventus.ai.dependencies`)}catch(e){console.log(e)}}},D=class extends s{get name(){return`project uninstall`}get description(){return`Uninstall project`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noBuild:!0,useTemplates:!0}),await o.executeCommand(`aventus.template.uninstall_project`)}catch(e){console.log(e),process.exit(1)}}},O=class extends s{get name(){return`template uninstall`}get description(){return`Uninstall project`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noBuild:!0,useTemplates:!0}),await o.executeCommand(`aventus.template.uninstall`)}catch(e){console.log(e),process.exit(1)}}},k=class extends c{get name(){return`project`}get description(){return`Manage project's templates`}},A=class extends c{get name(){return`template`}get description(){return`Manage templates`}},j=class extends c{get name(){return`dependencies`}get description(){return`Manage project's dependencies`}},M=class extends c{get name(){return`store`}get description(){return`Manage store`}},N=class extends s{get name(){return`watch`}get description(){return`Start the compiler in watch mode`}registerArgs(e){e({description:`aventus.conf.avt path`,type:`string`,typeIsRequired:!1})}registerOptions(e){e({name:`builds`,description:`Define the build name`,type:`string`,typeIsRequired:!0,typeIsArray:!0}),e({name:`json`,type:`boolean`,typeIsRequired:!1,description:`Result as json`})}async run(e,n){let r=e[0];r&&=(0,t.resolve)(r),n.builds===!1&&(n.builds=[]),await o.load(),console.clear(),await o.start({loadFiles:!0,watchFiles:!0,useCompilators:!0,useTemplates:!1,configPath:r,builds:n.builds,useStats:!1}),await this.sleep(2e3);let i=o.getErrors(),a=n.json?this.renderLogJson:this.renderLog;a(i);let s=(e,t)=>{i[t]=e,a(i)};o.subscribeErrors(s),await new Promise(e=>{process.once(`SIGINT`,e)}),o.unsubscribeErrors(s),process.exit(0)}sleep(e){return new Promise(t=>setTimeout(t,e))}renderLog(e){console.clear();let t=console.log;for(let n in e){let r=!1;t(`Build : `+(n??`default`));let i=e[n];if(i){let e=!1;for(let t in i)for(let n of i[t]){let i=``,a;if(n.severity==p.Error)i=`\x1B[31m[error]\x1B[0m`,r=!0,a=console.error;else if(n.severity==p.Warning)i=`\x1B[33m[warning]\x1B[0m`,a=console.warn;else if(n.severity==p.Information)i=`\x1B[34m[info]\x1B[0m`,a=console.info;else if(n.severity==p.Hint){i=`\x1B[90m[hint]\x1B[0m`;continue}a(` ${i} ${l(t).replace(/\\/g,`/`)}:${n.range.start.line+1} : ${n.message}`),e=!0}e&&t()}r||t(` No error detected`)}}renderLogJson(e){console.clear();let t={success:!0,builds:{}},n=e=>{t.builds[e]||(t.builds[e]={diagnostics:{},success:!0})};for(let r in e){let i=e[r];if(r=r==``?`default`:r,n(r),i)for(let e in i){let n=l(e).replace(/\\/g,`/`),a=[];t.builds[r].diagnostics[n]=a;for(let n of i[e]){let e;if(n.severity==p.Error)t.builds[r].success=!1,t.success=!1,e=`error`;else if(n.severity==p.Warning)e=`warning`;else if(n.severity==p.Information)e=`info`;else if(n.severity==p.Hint){e=`hint`;continue}a.push({content:n.message,start:n.range.start.line+1+`:`+n.range.start.character,end:n.range.end.line+1+`:`+n.range.end.character,type:e})}t.builds[r].diagnostics[n].length==0&&delete t.builds[r].diagnostics[n]}}console.log(JSON.stringify(t,void 0,4))}},P=class extends c{get name(){return`ai`}get description(){return`Manage ai helpers`}},F=class extends s{get name(){return`ai prepare`}get description(){return`Prepare file to help AI`}registerArgs(e){}registerOptions(e){}async run(e,n){try{let n=e[0];n&&=(0,t.resolve)(n),await o.load(),await o.start({noBuild:!0,loadFiles:!1,configPath:n}),await o.executeCommand(`aventus.ai.dependencies`),await o.executeCommand(`aventus.ai.rules`)}catch(e){console.log(e)}}},I=`0.0.44`;const L=`@aventusjs/cli`,R=[x,h,N,T,m,g,_,class extends s{get name(){return`update`}get description(){return`Update the cli`}registerArgs(e){}registerOptions(e){}async run(e,n){let r=(await this.runNpm([`view`,L,`version`])).trim();if(!r)throw Error(`npm did not return a version for ${L}.`);if(r===I){console.log(`${L} is already up to date (${I}).`);return}let a=(0,i.realpathSync)((await this.runNpm([`root`,`--global`])).trim()),o=(0,i.realpathSync)((0,t.resolve)(require.resolve(`../../package.json`),`..`)),s;try{s=(0,i.realpathSync)((0,t.resolve)(a,L))}catch{}let c=s===o?[`install`,`--global`,`${L}@${r}`]:[`install`,`--save-dev`,`${L}@${r}`];await this.runNpm(c,!0),console.log(`${L} was updated to ${r}.`)}runNpm(e,t=!1){return new Promise((n,i)=>{let a=process.platform===`win32`?{command:process.env.ComSpec||`cmd.exe`,args:[`/d`,`/s`,`/c`,`npm.cmd`,...e]}:{command:`npm`,args:e},o=(0,r.spawn)(a.command,a.args,{cwd:process.cwd(),stdio:t?`inherit`:[`ignore`,`pipe`,`pipe`]}),s=``,c=``;t||(o.stdout?.on(`data`,e=>s+=e.toString()),o.stderr?.on(`data`,e=>c+=e.toString())),o.on(`error`,i),o.on(`close`,t=>{if(t===0){n(s);return}let r=c.trim();i(Error(`npm ${e.join(` `)} failed with exit code ${t}${r?`: ${r}`:`.`}`))})})}},j,E,P,F,k,C,D,A,S,O,M,v,y,b];function z(e){for(let t of R)new t().register(e)}e.program.version(I).name(`aventus`).description(`Aventus CLI`),z(e.program),e.program.parse(process.argv);
|
|
2
|
+
let e=require("commander"),t=require("path"),n=require("vscode-languageserver"),r=require("child_process"),i=require("fs");var a=class{static realInteraction;static async load(e){let t=eval;this.realInteraction=(await t(`import("./RealInteraction.js")`)).default.RealInteraction,this.realInteraction._server=o,e&&(this.realInteraction.config=e)}static async init(){this.clear(),console.log(`Welcome inside Aventus CLI`)}static clear(){this.realInteraction.clear()}static async select(e,t){return this.realInteraction?.select(e,t)||null}static async selectMultiple(e,t){return this.realInteraction?.selectMultiple(e,t)||null}static async input(e,t,n){return this.realInteraction?.input(e,t,n)||null}static async password(e,t){return this.realInteraction?.password(e,t)||null}static async tree(e,t,n){return this.realInteraction?.tree(e,t,n)||null}static async log(){return this.realInteraction?.log()||null}},o=class{static realServer;static get notifications(){return this.realServer?.notifications}static async load(){let e=eval;this.realServer=(await e(`import("./RealServer.js")`)).default.RealServer,this.realServer._interaction=a}static subscribeErrors(e){return this.realServer?.subscribeErrors(e)}static unsubscribeErrors(e){return this.realServer?.unsubscribeErrors(e)}static executeCommand(e,...t){return this.realServer?.executeCommand(e,...t)}static getErrors(){return this.realServer?.getErrors()}static start(e){return this.realServer?.start(e)}static create(){return this.realServer?.create()}static getStatistics(){return this.realServer?.getStatistics()}static async Input(e){return this.realServer?.Input(e)}},s=class e{static actions={};argsNb=0;register(t){let n=this.name.trim().split(` `),r=``,i=t;for(let t of n)r+=t,e.actions[r]||(e.actions[r]=i.command(t)),i=e.actions[r],r+=` `;i=i.description(this.description),i=this._registerArgs(i),i=this._registerOptions(i),i.action(async(...e)=>{let t=[];for(let n=0;n<this.argsNb;n++)t.push(e[n]);let n=e[this.argsNb];await this.run(t,n),process.exit(0)})}_registerArgs(e){return this.registerArgs(t=>{let n=``;if(t.type){let e=`<`,r=`>`;t.typeIsRequired!==void 0&&!t.typeIsRequired&&(e=`[`,r=`]`),t.typeIsArray&&(r=`...`+r),n+=`${e}${t.type}${r}`}this.argsNb++,e=e.argument(n,t.description,t.defaultValue)}),e}_registerOptions(e){let t=new Set,n=[];return this.registerOptions(r=>{let i=r.name;e.on(`option:${i}`,()=>t.add(i));for(let e of r.conflicts?[].concat(r.conflicts):[])n.push([i,e]);let a=[];if(r.shortName){Array.isArray(r.shortName)||(r.shortName=[r.shortName]);for(let e of r.shortName)a.push(`-`+e)}a.push(`--`+r.name);let o=a.join(`, `);if(r.type){let e=`<`,t=`>`;r.typeIsRequired!==void 0&&!r.typeIsRequired&&(e=`[`,t=`]`),r.typeIsArray&&(t=`...`+t),o+=` ${e}${r.type}${t}`}e=r.required?e.requiredOption(o,r.description,r.defaultValue):e.option(o,r.description,r.defaultValue)}),e.hook(`preAction`,()=>{let r=n.find(([e,n])=>t.has(e)&&t.has(n));t.clear(),r&&e.error(`options '--${r[0]}' and '--${r[1]}' cannot be used together`,{code:`commander.conflictingOption`})}),e}},c=class{register(e){let t=this.name.trim().split(` `),n=``,r=e;for(let e of t)n+=e,s.actions[n]||(s.actions[n]=r.command(e)),r=s.actions[n],n+=` `;r=r.description(this.description)}};function l(e){return t.sep===`/`?decodeURIComponent(e.replace(`file://`,``)):decodeURIComponent(e.replace(`file:///`,``))}function u(e){if(e.startsWith(`file://`))return e;let n=e[0].toLowerCase()+e.substring(1);return n=d(encodeURI(n.replace(/\\/g,`/`))),t.sep===`/`?`file://`+n:`file:///`+n}function d(e){return e.replace(/:/g,`%3A`).replace(/@/g,`%40`)}function f(e){let t=1024,n=[`Bytes`,`KiB`,`MiB`,`GiB`,`TiB`,`PiB`,`EiB`,`ZiB`,`YiB`],r=e==0?0:Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/t**r).toFixed(2))} ${n[r]}`}const p={Error:n.DiagnosticSeverity.Error,Warning:n.DiagnosticSeverity.Warning,Information:n.DiagnosticSeverity.Information,Hint:n.DiagnosticSeverity.Hint};var m=class extends s{get name(){return`build`}get description(){return`Build an aventus project`}registerArgs(e){e({description:`aventus.conf.avt path`,type:`string`,typeIsRequired:!1})}registerOptions(e){e({name:`builds`,conflicts:`no-builds`,description:`Define the build name`,type:`string`,typeIsRequired:!0,typeIsArray:!0}),e({name:`no-builds`,description:`No builds`,type:`boolean`,typeIsRequired:!1}),e({name:`statics`,conflicts:`no-statics`,description:`Define the static files to export`,type:`string`,typeIsRequired:!0,typeIsArray:!0}),e({name:`no-statics`,description:`No statics`,type:`boolean`,typeIsRequired:!1}),e({name:`verbose`,conflicts:`silent`,shortName:`v`,description:`Debug your compilation`}),e({name:`silent`,shortName:`s`,description:`No output`}),e({name:`json`,type:`boolean`,typeIsRequired:!1,description:`Result as json`})}async run(e,n){let r=e[0];r&&=(0,t.resolve)(r),await o.load(),n.builds===!1&&(n.builds=[]),n.statics===!1&&(n.statics=[]),await o.start({configPath:r,loadFiles:!0,buildOnly:n[`no-statics`],noBuild:n[`no-builds`],builds:n.builds,statics:n.statics,logLevel:n.verbose?0:3,errorByBuild:!0,useStats:!n.silent}),n.json?this.handleResultJson(n):this.handleResult(n)}handleResult(e){let t=o.getStatistics(),n=e.silent?e=>{}:console.log;n(),n(`Loading all files : Done in `+t.loadFileTime+`ms`),n(),n(`----`),n();let r=o.getErrors(),i=!1;if(r[``])for(let t in r[``])for(let n of r[``][t])n.severity===p.Error&&(i=!0),e.silent||console.error(`${l(t)}:${n.range.start.line+1} : ${n.message}`);let a={},s={};for(let e in t.files){let n=t.files[e];if(n.type==`build`&&n.typeName){a[n.typeName]||(a[n.typeName]=[]);let e=` ${n.path} - ${f(n.size)}`;a[n.typeName].push(e)}else if(n.type==`static`&&n.typeName){s[n.typeName]||(s[n.typeName]=[]);let e=` ${n.path} - ${f(n.size)}`;s[n.typeName].push(e)}}let c=Object.keys(t.builds).length,u=Object.keys(t.statics).length,d=0;for(let o in t.builds){n(`Building `+o),n();let s=!1,f=r[o],m=t.builds[o],h=a[o];if(h){for(let e of h)n(e);n()}if(f){let t=!1;for(let n in f)for(let r of f[n]){let i=``,a;if(r.severity==p.Error)i=`\x1B[31m[error]\x1B[0m`,s=!0,a=console.error;else if(r.severity==p.Warning)i=`\x1B[33m[warning]\x1B[0m`,a=console.warn;else if(r.severity==p.Information)i=`\x1B[34m[info]\x1B[0m`,a=console.info;else if(r.severity==p.Hint){i=`\x1B[90m[hint]\x1B[0m`;continue}e.silent||(a(` ${i} ${l(n).replace(/\\/g,`/`)}:${r.range.start.line+1} : ${r.message}`),t=!0)}t&&n()}s?(n(` Build failed in `+m.buildTime+`ms`),i=!0):n(` Build success in `+m.buildTime+`ms`),d++,d==c&&u==0?n():(n(),n(`----`),n())}d=0;for(let e in t.statics){n(`Export static `+e),n();let r=t.statics[e],i=s[e];if(i){for(let e of i)n(e);n()}n(` Exported in `+r.buildTime+`ms`),d++,d==u?n():(n(),n(`----`),n())}i&&process.exit(1)}handleResultJson(e){let t=o.getStatistics(),n={success:!0,builds:{},statics:{}},r=o.getErrors(),i=!1;if(r[``])for(let e in r[``]){let t=l(e).replace(/\\/g,`/`);n.diagnostics||={},n.diagnostics[t]=[];for(let a of r[``][e])a.severity===p.Error&&(n.success=!1,i=!0),n.diagnostics[t].push({content:a.message,type:a.severity===p.Error?`error`:a.severity===p.Warning?`warning`:a.severity===p.Information?`info`:`hint`,start:`${a.range.start.line+1}:${a.range.start.character}`,end:`${a.range.end.line+1}:${a.range.end.character}`})}let a=e=>{n.builds[e]||(n.builds[e]={diagnostics:{},outputSize:{},success:!0})},s=e=>{n.statics[e]||(n.statics[e]={outputSize:{}})},c=e=>{let t=1024,n=[`Bytes`,`KiB`,`MiB`,`GiB`,`TiB`,`PiB`,`EiB`,`ZiB`,`YiB`],r=e==0?0:Math.floor(Math.log(e)/Math.log(t));return`${parseFloat((e/t**r).toFixed(2))} ${n[r]}`};for(let e in t.files){let r=t.files[e];if(r.type==`build`&&r.typeName){let e=r.typeName,t=l(r.path).replace(/\\/g,`/`);a(e),n.builds[e].outputSize[t]=c(r.size)}else if(r.type==`static`&&r.typeName){let e=l(r.path).replace(/\\/g,`/`);s(r.typeName),n.statics[r.typeName].outputSize[e]=c(r.size)}}for(let e in t.builds){a(e);let t=r[e];if(t)for(let r in t){let a=l(r).replace(/\\/g,`/`),o=[];n.builds[e].diagnostics[a]=o;for(let a of t[r]){let t;a.severity==p.Error?(n.builds[e].success=!1,n.success=!1,i=!0,t=`error`):a.severity==p.Warning?t=`warning`:a.severity==p.Information?t=`info`:a.severity==p.Hint&&(t=`hint`),o.push({content:a.message,start:a.range.start.line+1+`:`+a.range.start.character,end:a.range.end.line+1+`:`+a.range.end.character,type:t})}}}console.log(JSON.stringify(n,void 0,4)),i&&process.exit(1)}},h=class extends s{get name(){return`dev`}get description(){return`Start an interactive cli to dev with your aventus project`}registerArgs(e){e({description:`aventus.conf.avt path`,type:`string`,typeIsRequired:!1})}registerOptions(e){}async run(e,t){await a.load({clear:!0,printLogo:!0}),await o.load(),console.clear(),await a.init(),await o.start({loadFiles:!0,watchFiles:!0,useCompilators:!0,useTemplates:!0});let n=[{value:`create`,name:`Create...`},{value:`log`,name:`Show logs`},{value:`quit`,name:`Quit`}];for(a.clear();;){let e=await a.select(`Which action shoud I perform?`,n);e==`create`?await o.create():e==`log`?await a.log():e==`quit`?process.exit(0):console.log(`WIP`),a.clear()}}},g=class extends s{get name(){return`check`}get description(){return`Check an aventus project`}registerArgs(e){e({description:`aventus.conf.avt path`,type:`string`,typeIsRequired:!1})}registerOptions(e){e({name:`builds`,description:`Define the build name`,type:`string`,typeIsRequired:!0,typeIsArray:!0}),e({name:`json`,type:`boolean`,typeIsRequired:!1,description:`Result as json`})}async run(e,n){let r=e[0];r&&=(0,t.resolve)(r),n.builds===!1&&(n.builds=[]),await o.load(),await o.start({noBuild:!0,loadFiles:!0,buildOnly:!0,configPath:r,builds:n.builds,statics:void 0,logLevel:3,errorByBuild:!0,useStats:!1}),n.json?this.handleResultJson(n):this.handleResult(n)}handleResult(e){let t=o.getStatistics(),n=console.log;n(),n(`Loading all files : Done in `+t.loadFileTime+`ms`),n(),n(`----`),n();let r=o.getErrors(),i=!1;for(let e in r){let t=!1,a=r[e];if(a){let e=!1;for(let n in a)for(let r of a[n]){let a=``,o;if(r.severity==p.Error)a=`\x1B[31m[error]\x1B[0m`,t=!0,i=!0,o=console.error;else if(r.severity==p.Warning)a=`\x1B[33m[warning]\x1B[0m`,o=console.warn;else if(r.severity==p.Information)a=`\x1B[34m[info]\x1B[0m`,o=console.info;else if(r.severity==p.Hint){a=`\x1B[90m[hint]\x1B[0m`;continue}o(` ${a} ${l(n).replace(/\\/g,`/`)}:${r.range.start.line+1} : ${r.message}`),e=!0}e&&n()}t||n(` Build has no error`)}i&&process.exit(1)}handleResultJson(e){let t={success:!0,builds:{}},n=o.getErrors(),r=!1,i=e=>{t.builds[e]||(t.builds[e]={diagnostics:{},success:!0})};for(let e in n){i(e);let a=n[e];if(a)for(let n in a){let i=l(n).replace(/\\/g,`/`),o=[];t.builds[e].diagnostics[i]=o;for(let i of a[n]){let n;i.severity==p.Error?(t.builds[e].success=!1,t.success=!1,r=!0,n=`error`):i.severity==p.Warning?n=`warning`:i.severity==p.Information?n=`info`:i.severity==p.Hint&&(n=`hint`),o.push({content:i.message,start:i.range.start.line+1+`:`+i.range.start.character,end:i.range.end.line+1+`:`+i.range.end.character,type:n})}}}console.log(JSON.stringify(t,void 0,4)),r&&process.exit(1)}},_=class extends s{get name(){return`format`}get description(){return`Format your project`}registerArgs(e){e({description:`aventus.conf.avt path`,type:`string`,typeIsRequired:!1})}registerOptions(e){}async run(e,n){let r=e[0];r&&=(0,t.resolve)(r),await o.load(),await o.start({noBuild:!0,configPath:r}),await o.executeCommand(`aventus.format`)}},v=class extends s{get name(){return`store login`}get description(){return`Login to the store`}registerArgs(e){}registerOptions(e){e({name:`username`,shortName:`u`,description:`Username for connection`,type:`string`,typeIsRequired:!0}),e({name:`password`,shortName:`p`,description:`Password for connection`,type:`string`,typeIsRequired:!0})}async run(e,t){try{await a.load(),await o.load(),await o.start({noStart:!0}),await o.executeCommand(`aventus.store.connect`,t.username,t.password)}catch(e){console.log(e),process.exit(1)}}},y=class extends s{get name(){return`store logout`}get description(){return`Logout from the store`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noStart:!0}),await o.executeCommand(`aventus.store.disconnect`)}catch(e){console.log(e),process.exit(1)}}},b=class extends s{get name(){return`store publish`}get description(){return`Publish to the store`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noStart:!0}),await o.executeCommand(`aventus.store.publish_package`)}catch(e){console.log(e),process.exit(1)}}},x=class extends s{get name(){return`create`}get description(){return`Create new project / files from a template`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noBuild:!0,useTemplates:!0,loadFiles:!0}),await o.executeCommand(`aventus.create`,u(process.cwd()))}catch(e){console.log(e)}}},S=class extends s{get name(){return`template install`}get description(){return`Import template to create aventus element`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noBuild:!0,useTemplates:!0}),await o.executeCommand(`aventus.template.import`)}catch(e){console.log(e),process.exit(1)}}},C=class extends s{get name(){return`project install`}get description(){return`Import project to init aventus`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noBuild:!0,useTemplates:!0}),await o.executeCommand(`aventus.template.import_project`,e.length>0?e[0]:void 0)}catch(e){console.log(e),process.exit(1)}}},w=class{static cmd=`aventus/server/start`;static callbacks=[];static action(e){let t=[...this.callbacks];for(let n of t)n(e)}},T=class extends s{get name(){return`serve`}get description(){return`Start live server`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({loadFiles:!0,watchFiles:!0}),await o.executeCommand(`aventus.liveserver.start`),await this.waitStart(),await o.Input({title:`Press enter to stop server`})}catch(e){console.log(e)}}getAction(){return o.notifications.allNotifications[w.cmd]}waitStart(){return new Promise(e=>{let t=n=>{console.log(`Server started : `+n);let r=this.getAction().callbacks.indexOf(t);r!=-1&&this.getAction().callbacks.splice(r,1),e()};this.getAction().callbacks.push(t)})}},E=class extends s{get name(){return`dependencies help-llm`}get description(){return`Write dependencies to help llm`}registerArgs(e){}registerOptions(e){}async run(e,n){try{let n=e[0];n&&=(0,t.resolve)(n),await o.load(),await o.start({noBuild:!0,loadFiles:!1,configPath:n}),await o.executeCommand(`aventus.ai.dependencies`)}catch(e){console.log(e)}}},D=class extends s{get name(){return`project uninstall`}get description(){return`Uninstall project`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noBuild:!0,useTemplates:!0}),await o.executeCommand(`aventus.template.uninstall_project`)}catch(e){console.log(e),process.exit(1)}}},O=class extends s{get name(){return`template uninstall`}get description(){return`Uninstall project`}registerArgs(e){}registerOptions(e){}async run(e,t){try{await a.load(),await o.load(),await o.start({noBuild:!0,useTemplates:!0}),await o.executeCommand(`aventus.template.uninstall`)}catch(e){console.log(e),process.exit(1)}}},k=class extends c{get name(){return`project`}get description(){return`Manage project's templates`}},A=class extends c{get name(){return`template`}get description(){return`Manage templates`}},j=class extends c{get name(){return`dependencies`}get description(){return`Manage project's dependencies`}},M=class extends c{get name(){return`store`}get description(){return`Manage store`}},N=class extends s{get name(){return`watch`}get description(){return`Start the compiler in watch mode`}registerArgs(e){e({description:`aventus.conf.avt path`,type:`string`,typeIsRequired:!1})}registerOptions(e){e({name:`builds`,description:`Define the build name`,type:`string`,typeIsRequired:!0,typeIsArray:!0}),e({name:`json`,type:`boolean`,typeIsRequired:!1,description:`Result as json`})}async run(e,n){let r=e[0];r&&=(0,t.resolve)(r),n.builds===!1&&(n.builds=[]),await o.load(),console.clear(),await o.start({loadFiles:!0,watchFiles:!0,useCompilators:!0,useTemplates:!1,configPath:r,builds:n.builds,useStats:!1}),await this.sleep(2e3);let i=o.getErrors(),a=n.json?this.renderLogJson:this.renderLog;a(i);let s=(e,t)=>{i[t]=e,a(i)};o.subscribeErrors(s),await new Promise(e=>{process.once(`SIGINT`,e)}),o.unsubscribeErrors(s),process.exit(0)}sleep(e){return new Promise(t=>setTimeout(t,e))}renderLog(e){console.clear();let t=console.log;for(let n in e){let r=!1;t(`Build : `+(n??`default`));let i=e[n];if(i){let e=!1;for(let t in i)for(let n of i[t]){let i=``,a;if(n.severity==p.Error)i=`\x1B[31m[error]\x1B[0m`,r=!0,a=console.error;else if(n.severity==p.Warning)i=`\x1B[33m[warning]\x1B[0m`,a=console.warn;else if(n.severity==p.Information)i=`\x1B[34m[info]\x1B[0m`,a=console.info;else if(n.severity==p.Hint){i=`\x1B[90m[hint]\x1B[0m`;continue}a(` ${i} ${l(t).replace(/\\/g,`/`)}:${n.range.start.line+1} : ${n.message}`),e=!0}e&&t()}r||t(` No error detected`)}}renderLogJson(e){console.clear();let t={success:!0,builds:{}},n=e=>{t.builds[e]||(t.builds[e]={diagnostics:{},success:!0})};for(let r in e){let i=e[r];if(r=r==``?`default`:r,n(r),i)for(let e in i){let n=l(e).replace(/\\/g,`/`),a=[];t.builds[r].diagnostics[n]=a;for(let n of i[e]){let e;if(n.severity==p.Error)t.builds[r].success=!1,t.success=!1,e=`error`;else if(n.severity==p.Warning)e=`warning`;else if(n.severity==p.Information)e=`info`;else if(n.severity==p.Hint){e=`hint`;continue}a.push({content:n.message,start:n.range.start.line+1+`:`+n.range.start.character,end:n.range.end.line+1+`:`+n.range.end.character,type:e})}t.builds[r].diagnostics[n].length==0&&delete t.builds[r].diagnostics[n]}}console.log(JSON.stringify(t,void 0,4))}},P=class extends c{get name(){return`ai`}get description(){return`Manage ai helpers`}},F=class extends s{get name(){return`ai prepare`}get description(){return`Prepare file to help AI`}registerArgs(e){}registerOptions(e){}async run(e,n){try{let n=e[0];n&&=(0,t.resolve)(n),await o.load(),await o.start({noBuild:!0,loadFiles:!1,configPath:n}),await o.executeCommand(`aventus.ai.dependencies`),await o.executeCommand(`aventus.ai.rules`)}catch(e){console.log(e)}}},I=`0.0.46`;function L(){return(0,i.realpathSync)((0,t.resolve)(__dirname,`..`))}const R=`@aventusjs/cli`,z=[x,h,N,T,m,g,_,class extends s{get name(){return`update`}get description(){return`Update the cli`}registerArgs(e){}registerOptions(e){}async run(e,n){let r=(await this.runNpm([`view`,R,`version`])).trim();if(!r)throw Error(`npm did not return a version for ${R}.`);if(r===I){console.log(`${R} is already up to date (${I}).`);return}let a=(0,i.realpathSync)((await this.runNpm([`root`,`--global`])).trim()),o=L(),s;try{s=(0,i.realpathSync)((0,t.resolve)(a,R))}catch{}let c=s===o?[`install`,`--global`,`${R}@${r}`]:[`install`,`--save-dev`,`${R}@${r}`];await this.runNpm(c,!0),console.log(`${R} was updated to ${r}.`)}runNpm(e,t=!1){return new Promise((n,i)=>{let a=process.platform===`win32`?{command:process.env.ComSpec||`cmd.exe`,args:[`/d`,`/s`,`/c`,`npm.cmd`,...e]}:{command:`npm`,args:e},o=(0,r.spawn)(a.command,a.args,{cwd:process.cwd(),stdio:t?`inherit`:[`ignore`,`pipe`,`pipe`]}),s=``,c=``;t||(o.stdout?.on(`data`,e=>s+=e.toString()),o.stderr?.on(`data`,e=>c+=e.toString())),o.on(`error`,i),o.on(`close`,t=>{if(t===0){n(s);return}let r=c.trim();i(Error(`npm ${e.join(` `)} failed with exit code ${t}${r?`: ${r}`:`.`}`))})})}},j,E,P,F,k,C,D,A,S,O,M,v,y,b];function B(e){for(let t of z)new t().register(e)}e.program.version(I).name(`aventus`).description(`Aventus CLI`),B(e.program),e.program.parse(process.argv);
|
package/package.json
CHANGED