@arcgis/coding-components
Version:
Contains components for editing code in different languages. The currently supported languages are html, css, json, TypeScript, JavaScript, and Arcade.
19 lines (17 loc) • 19.1 kB
JavaScript
/*! All material copyright Esri, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/4.32/esri/copyright.txt for details.
v4.32.13 */
import{a as C,c as i,d as o,e as c}from"./S3BLTBJY.js";import{c as F}from"./42W5SSHX.js";import"./OSNFUWDR.js";import{a as y,v as T}from"./NXBT6LHX.js";import{Gl as P,Kl as k,Nl as g,Sl as f,kk as O}from"./O7MWLKAO.js";import"./7MJJ5QVF.js";O();var z={False:"false",Null:"null",True:"true"},$={Break:"break",Continue:"continue",Else:"else",For:"for",Function:"function",If:"if",Import:"import",Export:"export",In:"in",Return:"return",Var:"var",While:"while"};var j=["++","--"],V=["-","+","!","~"],W=["=","/=","*=","%=","+=","-="],R=["||","&&"],K=["|","&",">>","<<",">>>","^","==","!=","<","<=",">",">=","+","-","*","/","%"];var s={InvalidModuleUri:"InvalidModuleUri",ForInOfLoopInitializer:"ForInOfLoopInitializer",IdentifierExpected:"IdentifierExpected",InvalidEscapedReservedWord:"InvalidEscapedReservedWord",InvalidExpression:"InvalidExpression",InvalidFunctionIdentifier:"InvalidFunctionIdentifier",InvalidHexEscapeSequence:"InvalidHexEscapeSequence",InvalidLeftHandSideInAssignment:"InvalidLeftHandSideInAssignment",InvalidLeftHandSideInForIn:"InvalidLeftHandSideInForIn",InvalidTemplateHead:"InvalidTemplateHead",InvalidVariableAssignment:"InvalidVariableAssignment",KeyMustBeString:"KeyMustBeString",NoFunctionInsideBlock:"NoFunctionInsideBlock",NoFunctionInsideFunction:"NoFunctionInsideFunction",ModuleExportRootOnly:"ModuleExportRootOnly",ModuleImportRootOnly:"ModuleImportRootOnly",PunctuatorExpected:"PunctuatorExpected",TemplateOctalLiteral:"TemplateOctalLiteral",UnexpectedBoolean:"UnexpectedBoolean",UnexpectedEndOfScript:"UnexpectedEndOfScript",UnexpectedIdentifier:"UnexpectedIdentifier",UnexpectedKeyword:"UnexpectedKeyword",UnexpectedNull:"UnexpectedNull",UnexpectedNumber:"UnexpectedNumber",UnexpectedPunctuator:"UnexpectedPunctuator",UnexpectedString:"UnexpectedString",UnexpectedTemplate:"UnexpectedTemplate",UnexpectedToken:"UnexpectedToken"},H={[s.InvalidModuleUri]:"Module uri must be a text literal.",[s.ForInOfLoopInitializer]:"for-in loop variable declaration may not have an initializer.",[s.IdentifierExpected]:"'${value}' is an invalid identifier.",[s.InvalidEscapedReservedWord]:"Keyword cannot contain escaped characters.",[s.InvalidExpression]:"Invalid expression.",[s.InvalidFunctionIdentifier]:"'${value}' is an invalid function identifier.",[s.InvalidHexEscapeSequence]:"Invalid hexadecimal escape sequence.",[s.InvalidLeftHandSideInAssignment]:"Invalid left-hand side in assignment.",[s.InvalidLeftHandSideInForIn]:"Invalid left-hand side in for-in.",[s.InvalidTemplateHead]:"Invalid template structure.",[s.InvalidVariableAssignment]:"Invalid variable assignment.",[s.KeyMustBeString]:"Object property keys must be a word starting with a letter.",[s.NoFunctionInsideBlock]:"Functions cannot be declared inside of code blocks.",[s.NoFunctionInsideFunction]:"Functions cannot be declared inside another function.",[s.ModuleExportRootOnly]:"Module exports cannot be declared inside of code blocks.",[s.ModuleImportRootOnly]:"Module import cannot be declared inside of code blocks.",[s.PunctuatorExpected]:"'${value}' expected.",[s.TemplateOctalLiteral]:"Octal literals are not allowed in template literals.",[s.UnexpectedBoolean]:"Unexpected boolean literal.",[s.UnexpectedEndOfScript]:"Unexpected end of Arcade expression.",[s.UnexpectedIdentifier]:"Unexpected identifier.",[s.UnexpectedKeyword]:"Unexpected keyword.",[s.UnexpectedNull]:"Unexpected null literal.",[s.UnexpectedNumber]:"Unexpected number.",[s.UnexpectedPunctuator]:"Unexpected punctuator.",[s.UnexpectedString]:"Unexpected text literal.",[s.UnexpectedTemplate]:"Unexpected quasi '${value}'.",[s.UnexpectedToken]:"Unexpected token '${value}'."};var E=[[],[],[]];j.forEach(t=>E[t.length-1]?.push(t));V.forEach(t=>E[t.length-1]?.push(t));R.forEach(t=>E[t.length-1]?.push(t));W.forEach(t=>E[t.length-1]?.push(t));K.forEach(t=>E[t.length-1]?.push(t));var a={AlreadyDefined:"AlreadyDefined",ApiConflict:"ApiConflict",AssignedNeverUsed:"AssignedNeverUsed",DefinedNeverAssigned:"DefinedNeverAssigned",DefinedNeverUsed:"DefinedNeverUsed",EmptyBlockStatement:"EmptyBlockStatement",ExecutionError:"ExecutionError",InvalidApiFunctionUsage:"InvalidApiFunctionUsage",InvalidConstantIdentifier:"InvalidConstantIdentifier",InvalidPropertyIdentifier:"InvalidPropertyIdentifier",NoArgumentExpected:"NoArgumentExpected",NotADictionary:"NotADictionary",NotDefined:"NotDefined",NotEnoughArguments:"NotEnoughArguments",ProfileVariablesAreImmutable:"ProfileVariablesAreImmutable",ProfileVariablesConflict:"ProfileVariablesConflict",ReservedKeyword:"ReservedKeyword",TooManyArguments:"TooManyArguments",UnexpectedEmptyFunction:"UnexpectedEmptyFunction",UnexpectedPropertyIdentifier:"UnexpectedPropertyIdentifier",UnknownPropertyIdentifier:"UnknownPropertyIdentifier"},se={[a.AlreadyDefined]:"'${identifier}' is already defined.",[a.ApiConflict]:"'${identifier}' is already defined as an Arcade constant or function.",[a.AssignedNeverUsed]:"'${identifier}' is assigned but never used.",[a.DefinedNeverAssigned]:"'${identifier}' is defined but never assigned.",[a.DefinedNeverUsed]:"'${identifier}' is defined but never used.",[a.EmptyBlockStatement]:"Empty block statement.",[a.ExecutionError]:"Execution Error: '${stack}'",[a.InvalidApiFunctionUsage]:"Arcade function '${identifier}' not used in a call expression.",[a.InvalidConstantIdentifier]:"Invalid constant identifier, expecting ${list}.",[a.InvalidPropertyIdentifier]:"Invalid property identifier, expecting ${list}.",[a.NoArgumentExpected]:"Expecting no argument.",[a.NotADictionary]:"'${identifier}' doesn't have properties.",[a.NotDefined]:"'${identifier}' is not defined.",[a.NotEnoughArguments]:"Expecting at least ${min} argument(s).",[a.ProfileVariablesAreImmutable]:"Profile variables cannot be modified.",[a.ProfileVariablesConflict]:"'${identifier}' is already defined as a profile variable.",[a.ReservedKeyword]:"'${identifier}' is a reserved keyword.",[a.TooManyArguments]:"Too many arguments, expecting ${max}.",[a.UnexpectedEmptyFunction]:"Unexpected empty function '${identifier}'.",[a.UnexpectedPropertyIdentifier]:"Unexpected property identifier.",[a.UnknownPropertyIdentifier]:"Unknown property identifier '${identifier}'.",...H};var w=Object.values($),q=Object.values(z);var le=q.map(t=>({label:t,kind:i.Constant})),ce=w.map(t=>({label:t,kind:i.Keyword})),he=[{label:"exportfunction",kind:i.Snippet,detail:"Export Function Statement",insertText:`export function \${1:functionName} ($2) {
$0
}`,insertTextMode:c.adjustIndentation,insertTextFormat:o.Snippet},{label:"exportvar",kind:i.Snippet,detail:"Export Variable Statement",insertText:"export var ${0:variableName}\n",insertTextMode:c.adjustIndentation,insertTextFormat:o.Snippet},{label:"for",kind:i.Snippet,detail:"For Loop Statement",insertText:"for (var ${1:i} = 0; ${1:i} < ${2:array.length}; ${1:i}++) {\n $0\n}",insertTextMode:c.adjustIndentation,insertTextFormat:o.Snippet},{label:"forin",kind:i.Snippet,detail:"For-In Loop Statement",insertText:"for (var ${1:i} in ${2:arrayOrObject}) {\n $0\n}",insertTextMode:c.adjustIndentation,insertTextFormat:o.Snippet},{label:"forof",kind:i.Snippet,detail:"For-Of Loop Statement",insertText:"for (var ${1:i} of ${2:arrayOrObject}) {\n $0\n}",insertTextMode:c.adjustIndentation,insertTextFormat:o.Snippet},{label:"function",kind:i.Snippet,detail:"Function Statement",insertText:`function \${1:functionName} ($2) {
$0
}`,insertTextMode:c.adjustIndentation,insertTextFormat:o.Snippet},{label:"if",kind:i.Snippet,detail:"If Statement",insertText:`if (\${1:1==1}) {
$0
}`,insertTextMode:c.adjustIndentation,insertTextFormat:o.Snippet},{label:"ifelse",kind:i.Snippet,detail:"If-Else Statement",insertText:`if (\${1:1==1}) {
$0
} else {
}`,insertTextMode:c.adjustIndentation,insertTextFormat:o.Snippet},{label:"else",kind:i.Snippet,detail:"Else Statement",insertText:`else {
$0
}`,insertTextMode:c.adjustIndentation,insertTextFormat:o.Snippet},{label:"import",kind:i.Snippet,detail:"Import Statement",insertText:'import ${1:namespace} from "${0:uri}"',insertTextMode:c.adjustIndentation,insertTextFormat:o.Snippet},{label:"while",kind:i.Snippet,detail:"While Loop Statement",insertText:`while (\${1:false}) {
$0
}`,insertTextMode:c.adjustIndentation,insertTextFormat:o.Snippet}];var G=["<=",">=","==","!=","+","-","*","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","=","+=","-=","*=","**=","/=","%="],J={wordPattern:/(-?\d*\.\d\w*)|([^`~!#%\^&\*\(\)\-=\+\[\{\]\}\\\|;:'",\.<>\/\?\s]+)/gu,comments:{lineComment:"//",blockComment:["/*","*/"]},brackets:[["{","}"],["[","]"],["(",")"]],autoClosingPairs:[{open:"{",close:"}"},{open:"[",close:"]"},{open:"(",close:")"},{open:'"',close:'"',notIn:["string"]},{open:"'",close:"'",notIn:["string","comment"]},{open:"`",close:"`",notIn:["string","comment"]}],autoCloseBefore:";:.,=}])` \n ",folding:{markers:{start:/^\s*\/\/\s*#?region\b/u,end:/^\s*\/\/\s*#?endregion\b/u}},indentationRules:{decreaseIndentPattern:/^((?!.*?\/\*).*\*\/)?\s*[\}\]\)].*$/u,increaseIndentPattern:/^((?!\/\/).)*(\{[^}"'`]*|\([^)"'`]*|\[[^\]"'`]*)$/u}},Z={defaultToken:"invalid",tokenPostfix:".arcgis",ignoreCase:!0,keywords:w,operators:G,constants:["true","false","null"],symbols:/[=><!~?:&|+\-*\/\^%]+/u,escapes:/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/u,digits:/\d+(_+\d+)*/u,octaldigits:/[0-7]+(_+[0-7]+)*/u,binarydigits:/[0-1]+(_+[0-1]+)*/u,hexdigits:/[[0-9a-fA-F]+(_+[0-9a-fA-F]+)*/u,regexpctl:/[(){}\[\]\$\^|\-*+?\.]/u,regexpesc:/\\(?:[bBdDfnrstvwWn0\\\/]|@regexpctl|c[A-Z]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4})/u,tokenizer:{root:[[/[{}]/u,"delimiter.bracket"],{include:"common"}],common:[[/import(?=\s)/u,{token:"keyword",next:"@import"}],[/for(?=\s)/u,{token:"keyword",next:"@forLoopInit"}],[/[a-z_$][\w$]*/u,{cases:{"@constants":"constant","@keywords":"keyword","@default":"identifier"}}],{include:"@whitespace"},[/\/(?=([^\\\/]|\\.)+\/([gimsuy]*)(\s*)(\.|;|\/|,|\)|\]|\}|$))/u,{token:"regexp",bracket:"@open",next:"@regexp"}],[/[()\[\]]/u,"@brackets"],[/[<>](?!@symbols)/u,"@brackets"],[/@symbols/u,{cases:{"@operators":"delimiter","@default":""}}],[/(@digits)[eE]([\-+]?(@digits))?/u,"number"],[/(@digits)\.(@digits)([eE][\-+]?(@digits))?/u,"number"],[/0[xX](@hexdigits)/u,"number"],[/0[oO]?(@octaldigits)/u,"number"],[/0[bB](@binarydigits)/u,"number"],[/(@digits)/u,"number"],[/[;,.]/u,"delimiter"],[/"([^"\\]|\\.)*$/u,"string.invalid"],[/'([^'\\]|\\.)*$/u,"string.invalid"],[/"/u,"string","@string_double"],[/'/u,"string","@string_single"],[/`/u,"string","@string_backtick"]],import:[[/import(?=\s)/u,{token:"keyword"}],{include:"@whitespace"},[/[a-z_$][\w$]*/u,"identifier"],{include:"@whitespace"},[/from/u,{token:"keyword",next:"@popall"}]],forLoopInit:[{include:"@whitespace"},[/\(/u,{token:"@brackets",next:"@forLoopVar"}],[/.*/u,"","@pop"]],forLoopVar:[{include:"@whitespace"},[/var(?=\s)/u,"keyword","@forLoopVarName"],[/[a-z_$][\w$]*/u,"identifier","@forLoopCheckInOf"],[/\)/u,{token:"@brackets",next:"@popall"}]],forLoopVarName:[{include:"@whitespace"},[/[a-z_$][\w$]*/u,"identifier","@forLoopCheckInOf"],[/\)/u,{token:"@brackets",next:"@popall"}]],forLoopCheckInOf:[{include:"@whitespace"},[/in(?=\s)/u,"keyword","@popall"],[/of(?=\s)/u,"keyword","@popall"],[/[a-z_$][\w$]*/u,"identifier"],[/\)/u,{token:"@brackets",next:"@popall"}]],whitespace:[[/[ \t\r\n]+/u,""],[/\/\*/u,"comment","@comment"],[/\/\/.*$/u,"comment"]],comment:[[/[^\/*]+/u,"comment"],[/\*\//u,"comment","@pop"],[/[\/*]/u,"comment"]],regexp:[[/(\{)(\d+(?:,\d*)?)(\})/u,["regexp.escape.control","regexp.escape.control","regexp.escape.control"]],[/(\[)(\^?)(?=(?:[^\]\\\/]|\\.)+)/u,["regexp.escape.control",{token:"regexp.escape.control",next:"@regexrange"}]],[/(\()(\?:|\?=|\?!)/u,["regexp.escape.control","regexp.escape.control"]],[/[()]/u,"regexp.escape.control"],[/@regexpctl/u,"regexp.escape.control"],[/[^\\\/]/u,"regexp"],[/@regexpesc/u,"regexp.escape"],[/\\\./u,"regexp.invalid"],[/(\/)([gimsuy]*)/u,[{token:"regexp",bracket:"@close",next:"@pop"},"keyword.other"]]],regexrange:[[/-/u,"regexp.escape.control"],[/\^/u,"regexp.invalid"],[/@regexpesc/u,"regexp.escape"],[/[^\]]/u,"regexp"],[/\]/u,{token:"regexp.escape.control",next:"@pop",bracket:"@close"}]],string_double:[[/[^\\"]+/u,"string"],[/@escapes/u,"string.escape"],[/\\./u,"string.escape.invalid"],[/"/u,"string","@pop"]],string_single:[[/[^\\']+/u,"string"],[/@escapes/u,"string.escape"],[/\\./u,"string.escape.invalid"],[/'/u,"string","@pop"]],string_backtick:[[/\$\{/u,{token:"delimiter.bracket",next:"@bracketCounting"}],[/[^\\`$]+/u,"string"],[/@escapes/u,"string.escape"],[/\\./u,"string.escape.invalid"],[/`/u,"string","@pop"]],bracketCounting:[[/\{/u,"delimiter.bracket","@bracketCounting"],[/\}/u,"delimiter.bracket","@pop"],{include:"common"}]}},S=class{constructor(e,r,{defaults:h,diagnosticsService:D}){this._languageId=e,this._worker=r,this._disposables=[],this._modelListeners=new Map,this._diagnosticsService=D,this._defaults=h,F().then(d=>{let p=u=>{let n=u.getLanguageId();if(n!==this._languageId)return;let l=T(()=>{this._doValidate(u,n).catch(U=>{throw U})}),M=u.onDidChangeContent(l),_=u.onDidChangeAttached(l);this._modelListeners.set(u.uri.toString(),[M,_]),this._doValidate(u,n).catch(console.error)},m=u=>{let n=u.uri.toString();d.setModelMarkers(u,this._languageId,[]);let l=this._modelListeners.get(n);if(l){for(;l.length;)l.pop()?.dispose();this._modelListeners.delete(n)}};this._disposables.push(d.onDidCreateModel(p)),this._disposables.push(d.onWillDisposeModel(u=>{m(u)})),this._disposables.push(d.onDidChangeModelLanguage(u=>{m(u.model),p(u.model)})),this._disposables.push(h.onDidChange(()=>{d.getModels().forEach(u=>{u.getLanguageId()===this._languageId&&(m(u),p(u))})})),this._disposables.push(h.onModelContextDidChange(u=>{d.getModels().forEach(n=>{n.getLanguageId()===this._languageId&&n.uri.toString()===u&&this._doValidate(n,this._languageId).catch(console.error)})})),this._disposables.push({dispose:()=>{this._modelListeners.forEach(u=>u.forEach(n=>n.dispose())),this._modelListeners.clear()}}),d.getModels().forEach(p)})}dispose(){this._disposables.forEach(e=>e.dispose()),this._disposables=[]}async _doValidate(e,r){if(e.isAttachedToEditor())try{let h=await F(),D=await this._worker(e.uri),d=this._defaults.getApiContextForModel(e.uri),p=await D.doValidation(e.uri.toString(),d),m=p.map(u=>Y(e.uri,u));this._diagnosticsService.fireDiagnosticsChange(e.uri,p),h.setModelMarkers(e,r,m)}catch(h){console.error(h)}}};function X(t){switch(t){case C.Error:return g.Error;case C.Warning:return g.Warning;case C.Information:return g.Info;case C.Hint:return g.Hint;default:return g.Info}}function Y(t,e){return{severity:X(e.severity),startLineNumber:e.range.start.line+1,startColumn:e.range.start.character+1,endLineNumber:e.range.end.line+1,endColumn:e.range.end.character+1,message:e.message}}function Q(t){return{character:t.column-1,line:t.lineNumber-1}}function x(t){return new k(t.start.line+1,t.start.character+1,t.end.line+1,t.end.character+1)}function ee(t){return{range:x(t.range),text:t.newText}}function te(t){return typeof t.insert<"u"&&typeof t.replace<"u"}function ie(t){let e=f.CompletionItemKind;switch(t){case i.Text:return e.Text;case i.Method:return e.Method;case i.Function:return e.Function;case i.Constructor:return e.Constructor;case i.Field:return e.Field;case i.Variable:return e.Variable;case i.Class:return e.Class;case i.Interface:return e.Interface;case i.Module:return e.Module;case i.Property:return e.Property;case i.Unit:return e.Unit;case i.Value:return e.Value;case i.Enum:return e.Enum;case i.Keyword:return e.Keyword;case i.Snippet:return e.Snippet;case i.Color:return e.Color;case i.File:return e.File;case i.Reference:return e.Reference;case i.Folder:return e.Folder;case i.EnumMember:return e.EnumMember;case i.Constant:return e.Constant;case i.Struct:return e.Struct;case i.Event:return e.Event;case i.Operator:return e.Operator;case i.TypeParameter:return e.TypeParameter;default:return e.Property}}var b=class{constructor(e,r){this._worker=e,this._defaults=r,this.triggerCharacters=[".","("]}async provideCompletionItems(e,r){let h=await this._worker(e.uri),D=this._defaults.getApiContextForModel(e.uri),d=await h.doComplete(e.uri.toString(),Q(r),D),p=e.getWordUntilPosition(r),m=new k(r.lineNumber,p.startColumn,r.lineNumber,p.endColumn),u=d.items.map(n=>{let l={label:n.label,insertText:n.insertText||n.label,sortText:n.sortText,filterText:n.filterText,detail:n.detail,range:m,kind:ie(n.kind)};return n.textEdit&&(te(n.textEdit)?l.range={insert:x(n.textEdit.insert),replace:x(n.textEdit.replace)}:l.range=x(n.textEdit.range),l.insertText=n.textEdit.newText),n.additionalTextEdits&&(l.additionalTextEdits=n.additionalTextEdits.map(ee)),n.insertTextFormat===o.Snippet&&(l.insertTextRules=f.CompletionItemInsertTextRule.InsertAsSnippet),n.documentation&&(typeof n.documentation=="string"?l.documentation=n.documentation:l.documentation={supportThemeIcons:!1,value:n.documentation.value,supportHtml:!0}),l});return{incomplete:d.isIncomplete,suggestions:u}}},I=class{constructor(e,r){this._worker=e,this._defaults=r}async provideDocumentFormattingEdits(e){let r=await this._worker(e.uri),h=this._defaults.getApiContextForModel(e.uri.toString());return(await r.doFormat(e.uri.toString(),h)).map(D=>({range:x(D.range),text:D.newText}))}},B=new y,A=class{constructor(e){this._defaults=e,this._worker=null,this._client=null,this._configChangeListener=this._defaults.onDidChange(()=>this.stopWorker())}dispose(){this._configChangeListener.dispose(),this.stopWorker()}stopWorker(){this._worker&&(this._worker.dispose(),this._worker=null,B=new y),this._client=null}static async waitForWorker(){return await B.promise}async _getClientProxy(){let e=await F();if(!this._client){let{languageId:r}=this._defaults;this._worker=e.createWebWorker({moduleId:"ArcadeWorker",label:r,createData:{languageId:r},host:this._defaults.workerHost}),B.resolve(this._worker),this._client=this._worker.getProxy()}return await this._client}async getLanguageServiceWorker(...e){let r=await this._getClientProxy();return await this._worker?.withSyncedResources(e),r}},L;async function we(...t){return await A.waitForWorker(),await new Promise((e,r)=>{if(!L){r(new Error("Arcade not registered!"));return}e(L(...t))})}var v=class{constructor(){this._onDiagnosticsChange=new P}get onDiagnosticsChange(){return this._onDiagnosticsChange.event}fireDiagnosticsChange(e,r){this._onDiagnosticsChange.fire({uri:e,diagnostics:r})}},N=new v;function Be(){return N}function Se(t){let e=new A(t),r=async(...h)=>await e.getLanguageServiceWorker(...h);L=r,f.setMonarchTokensProvider(t.languageId,Z),f.setLanguageConfiguration(t.languageId,J),f.registerCompletionItemProvider(t.languageId,new b(r,t)),f.registerDocumentFormattingEditProvider(t.languageId,new I(r,t)),new S(t.languageId,r,{defaults:t,diagnosticsService:N})}export{Be as getArcadeDiagnosticService,we as getArcadeWorker,Se as setupMode};