Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
1 lines (1 loc) · 10.6 KB
/
Copy pathmain.js
File metadata and controls
1 lines (1 loc) · 10.6 KB
1
define(function(require,exports,module){const AppInit=brackets.getModule("utils/AppInit"),ProjectManager=brackets.getModule("project/ProjectManager"),EditorManager=brackets.getModule("editor/EditorManager"),PreferencesManager=brackets.getModule("preferences/PreferencesManager"),NodeConnector=brackets.getModule("NodeConnector"),Strings=brackets.getModule("strings"),ServerInstaller=require("./ServerInstaller"),SERVER_ID="php",SUPPORTED_LANGUAGES=["php"],PREF_LICENSE_KEY="php.licenseKey";PreferencesManager.definePreference(ServerInstaller.PREF_PHP_CODE_INTELLIGENCE,"boolean",!0,{description:Strings.DESCRIPTION_PHP_CODE_INTELLIGENCE}),PreferencesManager.definePreference(PREF_LICENSE_KEY,"string","",{description:Strings.DESCRIPTION_PHP_LICENSE_KEY});const INITIALIZATION_OPTIONS={};let lspClientPromise=null,registered=!1,_client=null,starting=!1,pendingRepoint=!1,initErrorReported=!1,_repairAttempted=!1;function canRun(){return Phoenix.isNativeApp&&NodeConnector.isNodeAvailable()}function loadLSPClient(){return lspClientPromise||(lspClientPromise=new Promise(function(resolve,reject){brackets.getModule(["languageTools/LSPClient"],resolve,function(){setTimeout(function(){brackets.getModule(["languageTools/LSPClient"],resolve,reject)},500)})})),lspClientPromise}function waitForNodeReady(timeout){return new Promise(function(resolve){const deadline=Date.now()+timeout;!function check(){NodeConnector.isNodeReady()?resolve(!0):Date.now()>deadline?resolve(!1):setTimeout(check,300)}()})}function _refreshInitializationOptions(clearCache){const licenseKey=(PreferencesManager.get(PREF_LICENSE_KEY)||"").trim();INITIALIZATION_OPTIONS.licenceKey=licenseKey||void 0,INITIALIZATION_OPTIONS.storagePath=ServerInstaller.getCachePlatformPath(),INITIALIZATION_OPTIONS.globalStoragePath=ServerInstaller.getCachePlatformPath(),INITIALIZATION_OPTIONS.clearCache=!!clearCache}async function _registerServer(entryPath,upgraded){if(registered)return;const LSPClient=await loadLSPClient();_refreshInitializationOptions(upgraded);const client=await LSPClient.registerLanguageServer({serverId:SERVER_ID,command:entryPath,args:["--stdio"],languages:SUPPORTED_LANGUAGES,languageIdMap:{php:"php"},initializationOptions:INITIALIZATION_OPTIONS});client&&(registered=!0,_client=client)}async function start(){if(registered||!canRun())return;const ready=await waitForNodeReady(3e4);if(!ready)return void console.error("[PHPSupport] Node not ready - PHP LSP disabled");const state=await ServerInstaller.installedState();state.installed&&state.pinMatches?(await _registerServer(ServerInstaller.getEntryPlatformPath(),!1),registered||_repairAttempted||Phoenix.isTestWindow||(_repairAttempted=!0,console.error("[PHPSupport] installed server failed to start - reinstalling"),await ServerInstaller.repairInstall())):await ServerInstaller.autoInstall()}function _isPhpDocumentActive(){const editor=EditorManager.getActiveEditor();return!(!editor||!editor.document)&&"php"===editor.document.getLanguage().getId()}function _ensureServerForActiveEditor(){if(canRun()&&_isPhpDocumentActive()&&!1!==PreferencesManager.get(ServerInstaller.PREF_PHP_CODE_INTELLIGENCE)){if(!registered){if(starting)return;return starting=!0,pendingRepoint=!1,void start().catch(function(err){initErrorReported||(initErrorReported=!0,window.logger&&window.logger.reportError(err,"[PHPSupport] PHP LSP init failed"))}).finally(function(){starting=!1})}pendingRepoint&&(pendingRepoint=!1,loadLSPClient().then(function(LSPClient){LSPClient.changeWorkspaceRoot(SERVER_ID)}))}}canRun()&&loadLSPClient(),AppInit.appReady(function(){canRun()&&(ServerInstaller.init({onInstalled:function(result){_registerServer(result.entryPath,result.upgraded).catch(function(err){window.logger&&window.logger.reportError(err,"[PHPSupport] start after install failed")})}}),EditorManager.on("activeEditorChange.phpSupport",function(){_ensureServerForActiveEditor()}),_ensureServerForActiveEditor(),ProjectManager.on(ProjectManager.EVENT_PROJECT_OPEN+".phpSupport",function(){pendingRepoint=!0,_ensureServerForActiveEditor()}),PreferencesManager.on("change",PREF_LICENSE_KEY,function(){registered&&(_refreshInitializationOptions(!1),loadLSPClient().then(function(LSPClient){LSPClient.restartLanguageServer(SERVER_ID)}))}),PreferencesManager.on("change",ServerInstaller.PREF_PHP_CODE_INTELLIGENCE,function(){!1!==PreferencesManager.get(ServerInstaller.PREF_PHP_CODE_INTELLIGENCE)&&_ensureServerForActiveEditor()}))}),exports._ensureServerForActiveEditor=_ensureServerForActiveEditor,exports.SERVER_ID=SERVER_ID,Phoenix.isTestWindow&&(exports._getClient=function(){return _client})}),define("ServerInstaller",function(require,exports,module){const NodeUtils=brackets.getModule("utils/NodeUtils"),NotificationUI=brackets.getModule("widgets/NotificationUI"),TaskManager=brackets.getModule("features/TaskManager"),PreferencesManager=brackets.getModule("preferences/PreferencesManager"),Metrics=brackets.getModule("utils/Metrics"),StringUtils=brackets.getModule("utils/StringUtils"),Strings=brackets.getModule("strings"),_PINS=brackets.config&&brackets.config.lsp_server_pins||{};_PINS.intelephense||window.alert("[PHPSupport] lsp_server_pins missing from AppConfig - stale build? Run npm run build.");const INTELEPHENSE_VERSION=_PINS.intelephense||"1.18.5",PREF_PHP_CODE_INTELLIGENCE="codeIntelligence.php";let _onInstalled=null,_inFlight=null,_cancelledThisSession=!1,_cancelRequested=!1,_activeNpmInstall=null,_onlineRetryArmed=!1;function _installDirVfs(){return Phoenix.VFS.getAppSupportDir()+"lspServers/intelephense/"}function _entryVfs(){return _installDirVfs()+"node_modules/intelephense/lib/intelephense.js"}function _packageJsonVfs(){return _installDirVfs()+"package.json"}function getEntryPlatformPath(){return Phoenix.fs.getTauriPlatformPath(_entryVfs())}function getCachePlatformPath(){return Phoenix.fs.getTauriPlatformPath(_installDirVfs()+"cache")}async function installedState(){const entryExists=await Phoenix.VFS.existsAsync(_entryVfs());if(!entryExists)return{installed:!1,pinMatches:!1};try{const pkgText=await Phoenix.VFS.readFileAsync(_packageJsonVfs(),"utf8"),pinned=JSON.parse(pkgText).dependencies.intelephense;return{installed:!0,pinMatches:pinned===INTELEPHENSE_VERSION}}catch(e){return{installed:!0,pinMatches:!1}}}async function _writePinnedPackageJson(){const pkg={name:"phcode-php-tooling",private:!0,description:"Locally installed PHP language server for Phoenix Code. Managed automatically.",dependencies:{}};pkg.dependencies.intelephense=INTELEPHENSE_VERSION,await Phoenix.VFS.writeFileAsync(_packageJsonVfs(),JSON.stringify(pkg,null,4),"utf8")}async function _wipeTree(){try{await Phoenix.VFS.unlinkAsync(_installDirVfs()+"node_modules")}catch(e){}try{await Phoenix.VFS.unlinkAsync(_installDirVfs()+"package-lock.json")}catch(e){}}const NETWORK_ERROR_RE=new RegExp("failed to fetch|fetch failed|load failed|ENOTFOUND|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENETUNREACH|getaddrinfo|network","i");function _isNetworkError(err){return NETWORK_ERROR_RE.test(err&&err.message||String(err))}function _armOnlineRetry(){_onlineRetryArmed||(_onlineRetryArmed=!0,window.addEventListener("online",function(){_onlineRetryArmed=!1,autoInstall()},{once:!0}))}function _showFailureToast(message){const $tpl=$("<div>").text(message);NotificationUI.createToastFromTemplate(Strings.PHP_INSTALL_TITLE,$tpl,{dismissOnClick:!0,toastStyle:NotificationUI.NOTIFICATION_STYLES_CSS_CLASS.SUBTLE,autoCloseTimeS:30,instantOpen:!0})}async function _doInstall(){const state=await installedState();if(state.installed&&state.pinMatches)return{entryPath:getEntryPlatformPath(),upgraded:!1};const upgrading=state.installed;_cancelRequested=!1;const task=TaskManager.addNewTask(Strings.PHP_INSTALL_TITLE,Strings.PHP_INSTALLING,"<i class='fa-brands fa-php'></i>",{progressPercent:5,onStopClick:function(){_cancelledThisSession=!0,_cancelRequested=!0,_activeNpmInstall&&_activeNpmInstall.cancel().catch(function(){})},onRetryClick:function(){task.close(),installNow()}});task.showStopIcon(Strings.PHP_INSTALL_STOP),task.show();try{if(await _wipeTree(),task.setProgressPercent(15),await Phoenix.VFS.ensureExistsDirAsync(_installDirVfs()),await Phoenix.VFS.ensureExistsDirAsync(_installDirVfs()+"cache/"),await _writePinnedPackageJson(),task.setProgressPercent(25),_cancelRequested){const cancelErr=new Error("install cancelled");throw cancelErr.cancelled=!0,cancelErr}const platformDir=Phoenix.fs.getTauriPlatformPath(_installDirVfs());_activeNpmInstall=NodeUtils._npmInstallInFolder(platformDir);try{await _activeNpmInstall}finally{_activeNpmInstall=null}task.setProgressPercent(90);const ok=await Phoenix.VFS.existsAsync(_entryVfs());if(!ok)throw new Error("intelephense entry missing after npm install");return task.setProgressPercent(100),task.setMessage(Strings.PHP_INSTALL_DONE),task.setSucceeded(),setTimeout(task.close,4e3),Metrics.countEvent("lsp","phpInst",upgrading?"upOk":"ok"),{entryPath:getEntryPlatformPath(),upgraded:upgrading}}catch(err){const message=err&&err.message||String(err);await _wipeTree();const cancelled=_cancelRequested||err&&err.cancelled||/cancelled/i.test(message);return cancelled?(Metrics.countEvent("lsp","phpInst","cancel"),task.close(),null):_isNetworkError(err)||!navigator.onLine?(Metrics.countEvent("lsp","phpInst","waitNet"),task.setMessage(Strings.PHP_INSTALL_WAITING_NETWORK),setTimeout(task.close,4e3),_armOnlineRetry(),null):(console.error("[PHPSupport] install failed",err),Metrics.countEvent("lsp","phpInst","fail"),window.logger&&window.logger.reportError(err,"[PHPSupport] LSP install failed"),task.setFailed(),task.setMessage(StringUtils.format(Strings.PHP_INSTALL_FAILED,message)),task.showRestartIcon(),task.show(),_showFailureToast(StringUtils.format(Strings.PHP_INSTALL_FAILED,message)),setTimeout(task.close,3e4),null)}finally{_activeNpmInstall=null}}function installNow(){return _inFlight||(_inFlight=_doInstall().then(function(result){return result&&_onInstalled&&_onInstalled(result),result}).finally(function(){_inFlight=null}))}function autoInstall(){return"undefined"!=typeof Phoenix&&Phoenix.isTestWindow?Promise.resolve(null):_cancelledThisSession||!1===PreferencesManager.get(PREF_PHP_CODE_INTELLIGENCE)?Promise.resolve(null):navigator.onLine?installNow():(_armOnlineRetry(),Promise.resolve(null))}async function repairInstall(){return await Phoenix.VFS.unlinkAsync(_installDirVfs()).catch(function(){}),installNow()}function init(options){_onInstalled=options&&options.onInstalled||null}exports.init=init,exports.installedState=installedState,exports.installNow=installNow,exports.autoInstall=autoInstall,exports.repairInstall=repairInstall,exports.getEntryPlatformPath=getEntryPlatformPath,exports.getCachePlatformPath=getCachePlatformPath,exports.INTELEPHENSE_VERSION=INTELEPHENSE_VERSION,exports.PREF_PHP_CODE_INTELLIGENCE=PREF_PHP_CODE_INTELLIGENCE});