vendor tsgo

This commit is contained in:
2026-07-09 16:50:43 -04:00
parent c06ea2e5a4
commit 98978e4930
5804 changed files with 1556156 additions and 101 deletions

View File

@@ -0,0 +1,514 @@
// Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package projecttestutil
import (
"context"
"sync"
"github.com/microsoft/typescript-go/internal/diagnostics"
"github.com/microsoft/typescript-go/internal/lsp/lsproto"
"github.com/microsoft/typescript-go/internal/project"
)
// Ensure, that ClientMock does implement project.Client.
// If this is not the case, regenerate this file with moq.
var _ project.Client = &ClientMock{}
// ClientMock is a mock implementation of project.Client.
//
// func TestSomethingThatUsesClient(t *testing.T) {
//
// // make and configure a mocked project.Client
// mockedClient := &ClientMock{
// IsActiveFunc: func() bool {
// panic("mock out the IsActive method")
// },
// ProgressFinishFunc: func(message *diagnostics.Message, args ...any) {
// panic("mock out the ProgressFinish method")
// },
// ProgressStartFunc: func(message *diagnostics.Message, args ...any) {
// panic("mock out the ProgressStart method")
// },
// PublishDiagnosticsFunc: func(ctx context.Context, params *lsproto.PublishDiagnosticsParams) error {
// panic("mock out the PublishDiagnostics method")
// },
// RefreshCodeLensFunc: func(ctx context.Context) error {
// panic("mock out the RefreshCodeLens method")
// },
// RefreshDiagnosticsFunc: func(ctx context.Context) error {
// panic("mock out the RefreshDiagnostics method")
// },
// RefreshInlayHintsFunc: func(ctx context.Context) error {
// panic("mock out the RefreshInlayHints method")
// },
// SendTelemetryFunc: func(ctx context.Context, telemetry lsproto.TelemetryEvent) error {
// panic("mock out the SendTelemetry method")
// },
// UnwatchFilesFunc: func(ctx context.Context, id project.WatcherID) error {
// panic("mock out the UnwatchFiles method")
// },
// WatchFilesFunc: func(ctx context.Context, id project.WatcherID, watchers []*lsproto.FileSystemWatcher) error {
// panic("mock out the WatchFiles method")
// },
// }
//
// // use mockedClient in code that requires project.Client
// // and then make assertions.
//
// }
type ClientMock struct {
// IsActiveFunc mocks the IsActive method.
IsActiveFunc func() bool
// ProgressFinishFunc mocks the ProgressFinish method.
ProgressFinishFunc func(message *diagnostics.Message, args ...any)
// ProgressStartFunc mocks the ProgressStart method.
ProgressStartFunc func(message *diagnostics.Message, args ...any)
// PublishDiagnosticsFunc mocks the PublishDiagnostics method.
PublishDiagnosticsFunc func(ctx context.Context, params *lsproto.PublishDiagnosticsParams) error
// RefreshCodeLensFunc mocks the RefreshCodeLens method.
RefreshCodeLensFunc func(ctx context.Context) error
// RefreshDiagnosticsFunc mocks the RefreshDiagnostics method.
RefreshDiagnosticsFunc func(ctx context.Context) error
// RefreshInlayHintsFunc mocks the RefreshInlayHints method.
RefreshInlayHintsFunc func(ctx context.Context) error
// SendTelemetryFunc mocks the SendTelemetry method.
SendTelemetryFunc func(ctx context.Context, telemetry lsproto.TelemetryEvent) error
// UnwatchFilesFunc mocks the UnwatchFiles method.
UnwatchFilesFunc func(ctx context.Context, id project.WatcherID) error
// WatchFilesFunc mocks the WatchFiles method.
WatchFilesFunc func(ctx context.Context, id project.WatcherID, watchers []*lsproto.FileSystemWatcher) error
// calls tracks calls to the methods.
calls struct {
// IsActive holds details about calls to the IsActive method.
IsActive []struct{}
// ProgressFinish holds details about calls to the ProgressFinish method.
ProgressFinish []struct {
// Message is the message argument value.
Message *diagnostics.Message
// Args is the args argument value.
Args []any
}
// ProgressStart holds details about calls to the ProgressStart method.
ProgressStart []struct {
// Message is the message argument value.
Message *diagnostics.Message
// Args is the args argument value.
Args []any
}
// PublishDiagnostics holds details about calls to the PublishDiagnostics method.
PublishDiagnostics []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Params is the params argument value.
Params *lsproto.PublishDiagnosticsParams
}
// RefreshCodeLens holds details about calls to the RefreshCodeLens method.
RefreshCodeLens []struct {
// Ctx is the ctx argument value.
Ctx context.Context
}
// RefreshDiagnostics holds details about calls to the RefreshDiagnostics method.
RefreshDiagnostics []struct {
// Ctx is the ctx argument value.
Ctx context.Context
}
// RefreshInlayHints holds details about calls to the RefreshInlayHints method.
RefreshInlayHints []struct {
// Ctx is the ctx argument value.
Ctx context.Context
}
// SendTelemetry holds details about calls to the SendTelemetry method.
SendTelemetry []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Telemetry is the telemetry argument value.
Telemetry lsproto.TelemetryEvent
}
// UnwatchFiles holds details about calls to the UnwatchFiles method.
UnwatchFiles []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// ID is the id argument value.
ID project.WatcherID
}
// WatchFiles holds details about calls to the WatchFiles method.
WatchFiles []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// ID is the id argument value.
ID project.WatcherID
// Watchers is the watchers argument value.
Watchers []*lsproto.FileSystemWatcher
}
}
lockIsActive sync.RWMutex
lockProgressFinish sync.RWMutex
lockProgressStart sync.RWMutex
lockPublishDiagnostics sync.RWMutex
lockRefreshCodeLens sync.RWMutex
lockRefreshDiagnostics sync.RWMutex
lockRefreshInlayHints sync.RWMutex
lockSendTelemetry sync.RWMutex
lockUnwatchFiles sync.RWMutex
lockWatchFiles sync.RWMutex
}
// IsActive calls IsActiveFunc.
func (mock *ClientMock) IsActive() bool {
callInfo := struct{}{}
mock.lockIsActive.Lock()
mock.calls.IsActive = append(mock.calls.IsActive, callInfo)
mock.lockIsActive.Unlock()
if mock.IsActiveFunc == nil {
var bOut bool
return bOut
}
return mock.IsActiveFunc()
}
// IsActiveCalls gets all the calls that were made to IsActive.
// Check the length with:
//
// len(mockedClient.IsActiveCalls())
func (mock *ClientMock) IsActiveCalls() []struct{} {
var calls []struct{}
mock.lockIsActive.RLock()
calls = mock.calls.IsActive
mock.lockIsActive.RUnlock()
return calls
}
// ProgressFinish calls ProgressFinishFunc.
func (mock *ClientMock) ProgressFinish(message *diagnostics.Message, args ...any) {
callInfo := struct {
Message *diagnostics.Message
Args []any
}{
Message: message,
Args: args,
}
mock.lockProgressFinish.Lock()
mock.calls.ProgressFinish = append(mock.calls.ProgressFinish, callInfo)
mock.lockProgressFinish.Unlock()
if mock.ProgressFinishFunc == nil {
return
}
mock.ProgressFinishFunc(message, args...)
}
// ProgressFinishCalls gets all the calls that were made to ProgressFinish.
// Check the length with:
//
// len(mockedClient.ProgressFinishCalls())
func (mock *ClientMock) ProgressFinishCalls() []struct {
Message *diagnostics.Message
Args []any
} {
var calls []struct {
Message *diagnostics.Message
Args []any
}
mock.lockProgressFinish.RLock()
calls = mock.calls.ProgressFinish
mock.lockProgressFinish.RUnlock()
return calls
}
// ProgressStart calls ProgressStartFunc.
func (mock *ClientMock) ProgressStart(message *diagnostics.Message, args ...any) {
callInfo := struct {
Message *diagnostics.Message
Args []any
}{
Message: message,
Args: args,
}
mock.lockProgressStart.Lock()
mock.calls.ProgressStart = append(mock.calls.ProgressStart, callInfo)
mock.lockProgressStart.Unlock()
if mock.ProgressStartFunc == nil {
return
}
mock.ProgressStartFunc(message, args...)
}
// ProgressStartCalls gets all the calls that were made to ProgressStart.
// Check the length with:
//
// len(mockedClient.ProgressStartCalls())
func (mock *ClientMock) ProgressStartCalls() []struct {
Message *diagnostics.Message
Args []any
} {
var calls []struct {
Message *diagnostics.Message
Args []any
}
mock.lockProgressStart.RLock()
calls = mock.calls.ProgressStart
mock.lockProgressStart.RUnlock()
return calls
}
// PublishDiagnostics calls PublishDiagnosticsFunc.
func (mock *ClientMock) PublishDiagnostics(ctx context.Context, params *lsproto.PublishDiagnosticsParams) error {
callInfo := struct {
Ctx context.Context
Params *lsproto.PublishDiagnosticsParams
}{
Ctx: ctx,
Params: params,
}
mock.lockPublishDiagnostics.Lock()
mock.calls.PublishDiagnostics = append(mock.calls.PublishDiagnostics, callInfo)
mock.lockPublishDiagnostics.Unlock()
if mock.PublishDiagnosticsFunc == nil {
var errOut error
return errOut
}
return mock.PublishDiagnosticsFunc(ctx, params)
}
// PublishDiagnosticsCalls gets all the calls that were made to PublishDiagnostics.
// Check the length with:
//
// len(mockedClient.PublishDiagnosticsCalls())
func (mock *ClientMock) PublishDiagnosticsCalls() []struct {
Ctx context.Context
Params *lsproto.PublishDiagnosticsParams
} {
var calls []struct {
Ctx context.Context
Params *lsproto.PublishDiagnosticsParams
}
mock.lockPublishDiagnostics.RLock()
calls = mock.calls.PublishDiagnostics
mock.lockPublishDiagnostics.RUnlock()
return calls
}
// RefreshCodeLens calls RefreshCodeLensFunc.
func (mock *ClientMock) RefreshCodeLens(ctx context.Context) error {
callInfo := struct {
Ctx context.Context
}{
Ctx: ctx,
}
mock.lockRefreshCodeLens.Lock()
mock.calls.RefreshCodeLens = append(mock.calls.RefreshCodeLens, callInfo)
mock.lockRefreshCodeLens.Unlock()
if mock.RefreshCodeLensFunc == nil {
var errOut error
return errOut
}
return mock.RefreshCodeLensFunc(ctx)
}
// RefreshCodeLensCalls gets all the calls that were made to RefreshCodeLens.
// Check the length with:
//
// len(mockedClient.RefreshCodeLensCalls())
func (mock *ClientMock) RefreshCodeLensCalls() []struct {
Ctx context.Context
} {
var calls []struct {
Ctx context.Context
}
mock.lockRefreshCodeLens.RLock()
calls = mock.calls.RefreshCodeLens
mock.lockRefreshCodeLens.RUnlock()
return calls
}
// RefreshDiagnostics calls RefreshDiagnosticsFunc.
func (mock *ClientMock) RefreshDiagnostics(ctx context.Context) error {
callInfo := struct {
Ctx context.Context
}{
Ctx: ctx,
}
mock.lockRefreshDiagnostics.Lock()
mock.calls.RefreshDiagnostics = append(mock.calls.RefreshDiagnostics, callInfo)
mock.lockRefreshDiagnostics.Unlock()
if mock.RefreshDiagnosticsFunc == nil {
var errOut error
return errOut
}
return mock.RefreshDiagnosticsFunc(ctx)
}
// RefreshDiagnosticsCalls gets all the calls that were made to RefreshDiagnostics.
// Check the length with:
//
// len(mockedClient.RefreshDiagnosticsCalls())
func (mock *ClientMock) RefreshDiagnosticsCalls() []struct {
Ctx context.Context
} {
var calls []struct {
Ctx context.Context
}
mock.lockRefreshDiagnostics.RLock()
calls = mock.calls.RefreshDiagnostics
mock.lockRefreshDiagnostics.RUnlock()
return calls
}
// RefreshInlayHints calls RefreshInlayHintsFunc.
func (mock *ClientMock) RefreshInlayHints(ctx context.Context) error {
callInfo := struct {
Ctx context.Context
}{
Ctx: ctx,
}
mock.lockRefreshInlayHints.Lock()
mock.calls.RefreshInlayHints = append(mock.calls.RefreshInlayHints, callInfo)
mock.lockRefreshInlayHints.Unlock()
if mock.RefreshInlayHintsFunc == nil {
var errOut error
return errOut
}
return mock.RefreshInlayHintsFunc(ctx)
}
// RefreshInlayHintsCalls gets all the calls that were made to RefreshInlayHints.
// Check the length with:
//
// len(mockedClient.RefreshInlayHintsCalls())
func (mock *ClientMock) RefreshInlayHintsCalls() []struct {
Ctx context.Context
} {
var calls []struct {
Ctx context.Context
}
mock.lockRefreshInlayHints.RLock()
calls = mock.calls.RefreshInlayHints
mock.lockRefreshInlayHints.RUnlock()
return calls
}
// SendTelemetry calls SendTelemetryFunc.
func (mock *ClientMock) SendTelemetry(ctx context.Context, telemetry lsproto.TelemetryEvent) error {
callInfo := struct {
Ctx context.Context
Telemetry lsproto.TelemetryEvent
}{
Ctx: ctx,
Telemetry: telemetry,
}
mock.lockSendTelemetry.Lock()
mock.calls.SendTelemetry = append(mock.calls.SendTelemetry, callInfo)
mock.lockSendTelemetry.Unlock()
if mock.SendTelemetryFunc == nil {
var errOut error
return errOut
}
return mock.SendTelemetryFunc(ctx, telemetry)
}
// SendTelemetryCalls gets all the calls that were made to SendTelemetry.
// Check the length with:
//
// len(mockedClient.SendTelemetryCalls())
func (mock *ClientMock) SendTelemetryCalls() []struct {
Ctx context.Context
Telemetry lsproto.TelemetryEvent
} {
var calls []struct {
Ctx context.Context
Telemetry lsproto.TelemetryEvent
}
mock.lockSendTelemetry.RLock()
calls = mock.calls.SendTelemetry
mock.lockSendTelemetry.RUnlock()
return calls
}
// UnwatchFiles calls UnwatchFilesFunc.
func (mock *ClientMock) UnwatchFiles(ctx context.Context, id project.WatcherID) error {
callInfo := struct {
Ctx context.Context
ID project.WatcherID
}{
Ctx: ctx,
ID: id,
}
mock.lockUnwatchFiles.Lock()
mock.calls.UnwatchFiles = append(mock.calls.UnwatchFiles, callInfo)
mock.lockUnwatchFiles.Unlock()
if mock.UnwatchFilesFunc == nil {
var errOut error
return errOut
}
return mock.UnwatchFilesFunc(ctx, id)
}
// UnwatchFilesCalls gets all the calls that were made to UnwatchFiles.
// Check the length with:
//
// len(mockedClient.UnwatchFilesCalls())
func (mock *ClientMock) UnwatchFilesCalls() []struct {
Ctx context.Context
ID project.WatcherID
} {
var calls []struct {
Ctx context.Context
ID project.WatcherID
}
mock.lockUnwatchFiles.RLock()
calls = mock.calls.UnwatchFiles
mock.lockUnwatchFiles.RUnlock()
return calls
}
// WatchFiles calls WatchFilesFunc.
func (mock *ClientMock) WatchFiles(ctx context.Context, id project.WatcherID, watchers []*lsproto.FileSystemWatcher) error {
callInfo := struct {
Ctx context.Context
ID project.WatcherID
Watchers []*lsproto.FileSystemWatcher
}{
Ctx: ctx,
ID: id,
Watchers: watchers,
}
mock.lockWatchFiles.Lock()
mock.calls.WatchFiles = append(mock.calls.WatchFiles, callInfo)
mock.lockWatchFiles.Unlock()
if mock.WatchFilesFunc == nil {
var errOut error
return errOut
}
return mock.WatchFilesFunc(ctx, id, watchers)
}
// WatchFilesCalls gets all the calls that were made to WatchFiles.
// Check the length with:
//
// len(mockedClient.WatchFilesCalls())
func (mock *ClientMock) WatchFilesCalls() []struct {
Ctx context.Context
ID project.WatcherID
Watchers []*lsproto.FileSystemWatcher
} {
var calls []struct {
Ctx context.Context
ID project.WatcherID
Watchers []*lsproto.FileSystemWatcher
}
mock.lockWatchFiles.RLock()
calls = mock.calls.WatchFiles
mock.lockWatchFiles.RUnlock()
return calls
}

View File

@@ -0,0 +1,86 @@
// Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package projecttestutil
import (
"sync"
"github.com/microsoft/typescript-go/internal/project/ata"
)
// Ensure, that NpmExecutorMock does implement ata.NpmExecutor.
// If this is not the case, regenerate this file with moq.
var _ ata.NpmExecutor = &NpmExecutorMock{}
// NpmExecutorMock is a mock implementation of ata.NpmExecutor.
//
// func TestSomethingThatUsesNpmExecutor(t *testing.T) {
//
// // make and configure a mocked ata.NpmExecutor
// mockedNpmExecutor := &NpmExecutorMock{
// NpmInstallFunc: func(cwd string, args []string) ([]byte, error) {
// panic("mock out the NpmInstall method")
// },
// }
//
// // use mockedNpmExecutor in code that requires ata.NpmExecutor
// // and then make assertions.
//
// }
type NpmExecutorMock struct {
// NpmInstallFunc mocks the NpmInstall method.
NpmInstallFunc func(cwd string, args []string) ([]byte, error)
// calls tracks calls to the methods.
calls struct {
// NpmInstall holds details about calls to the NpmInstall method.
NpmInstall []struct {
// Cwd is the cwd argument value.
Cwd string
// Args is the args argument value.
Args []string
}
}
lockNpmInstall sync.RWMutex
}
// NpmInstall calls NpmInstallFunc.
func (mock *NpmExecutorMock) NpmInstall(cwd string, args []string) ([]byte, error) {
callInfo := struct {
Cwd string
Args []string
}{
Cwd: cwd,
Args: args,
}
mock.lockNpmInstall.Lock()
mock.calls.NpmInstall = append(mock.calls.NpmInstall, callInfo)
mock.lockNpmInstall.Unlock()
if mock.NpmInstallFunc == nil {
var (
bytesOut []byte
errOut error
)
return bytesOut, errOut
}
return mock.NpmInstallFunc(cwd, args)
}
// NpmInstallCalls gets all the calls that were made to NpmInstall.
// Check the length with:
//
// len(mockedNpmExecutor.NpmInstallCalls())
func (mock *NpmExecutorMock) NpmInstallCalls() []struct {
Cwd string
Args []string
} {
var calls []struct {
Cwd string
Args []string
}
mock.lockNpmInstall.RLock()
calls = mock.calls.NpmInstall
mock.lockNpmInstall.RUnlock()
return calls
}

View File

@@ -0,0 +1,323 @@
package projecttestutil
import (
"context"
"fmt"
"os"
"slices"
"strings"
"sync"
"testing"
"github.com/microsoft/typescript-go/internal/bundled"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/glob"
"github.com/microsoft/typescript-go/internal/lsp/lsproto"
"github.com/microsoft/typescript-go/internal/project"
"github.com/microsoft/typescript-go/internal/project/logging"
"github.com/microsoft/typescript-go/internal/testutil/baseline"
"github.com/microsoft/typescript-go/internal/tspath"
"github.com/microsoft/typescript-go/internal/vfs"
"github.com/microsoft/typescript-go/internal/vfs/iovfs"
"github.com/microsoft/typescript-go/internal/vfs/osvfs"
"github.com/microsoft/typescript-go/internal/vfs/vfstest"
)
//go:generate go tool github.com/matryer/moq -stub -fmt goimports -pkg projecttestutil -out clientmock_generated.go ../../project Client
//go:generate npx dprint fmt clientmock_generated.go
//go:generate go tool github.com/matryer/moq -stub -fmt goimports -pkg projecttestutil -out npmexecutormock_generated.go ../../project/ata NpmExecutor
//go:generate npx dprint fmt npmexecutormock_generated.go
const (
TestTypingsLocation = "/home/src/Library/Caches/typescript"
)
type TypingsInstallerOptions struct {
TypesRegistry []string
PackageToFile map[string]string
}
type SessionUtils struct {
currentDirectory string
fsFromFileMap iovfs.FsWithSys
fs vfs.FS
client *ClientMock
npmExecutor *NpmExecutorMock
tiOptions *TypingsInstallerOptions
logger logging.LogCollector
}
func (h *SessionUtils) FsFromFileMap() iovfs.FsWithSys {
return h.fsFromFileMap
}
func (h *SessionUtils) Client() *ClientMock {
return h.client
}
func (h *SessionUtils) NpmExecutor() *NpmExecutorMock {
return h.npmExecutor
}
func (h *SessionUtils) SetupNpmExecutorForTypingsInstaller() {
if h.tiOptions == nil {
return
}
h.npmExecutor.NpmInstallFunc = func(cwd string, packageNames []string) ([]byte, error) {
// packageNames is actually npmInstallArgs due to interface misnaming
npmInstallArgs := packageNames
lenNpmInstallArgs := len(npmInstallArgs)
if lenNpmInstallArgs < 3 {
return nil, fmt.Errorf("unexpected npm install: %s %v", cwd, npmInstallArgs)
}
if lenNpmInstallArgs == 3 && npmInstallArgs[2] == "types-registry@latest" {
// Write typings file
err := h.fs.WriteFile(cwd+"/node_modules/types-registry/index.json", h.createTypesRegistryFileContent())
return nil, err
}
// Find the packages: they start at index 2 and continue until we hit a flag starting with --
packageEnd := lenNpmInstallArgs
for i := 2; i < lenNpmInstallArgs; i++ {
if strings.HasPrefix(npmInstallArgs[i], "--") {
packageEnd = i
break
}
}
for _, atTypesPackageTs := range npmInstallArgs[2:packageEnd] {
// @types/packageName@TsVersionToUse
atTypesPackage := atTypesPackageTs
// Remove version suffix
if versionIndex := strings.LastIndex(atTypesPackage, "@"); versionIndex > 6 { // "@types/".length is 7, so version @ must be after
atTypesPackage = atTypesPackage[:versionIndex]
}
// Extract package name from @types/packageName
packageBaseName := atTypesPackage[7:] // Remove "@types/" prefix
content, ok := h.tiOptions.PackageToFile[packageBaseName]
if !ok {
return nil, fmt.Errorf("content not provided for %s", packageBaseName)
}
err := h.fs.WriteFile(cwd+"/node_modules/@types/"+packageBaseName+"/index.d.ts", content)
if err != nil {
return nil, err
}
}
return nil, nil
}
}
func (h *SessionUtils) ToPath(fileName string) tspath.Path {
return tspath.ToPath(fileName, h.currentDirectory, h.fs.UseCaseSensitiveFileNames())
}
func (h *SessionUtils) FS() vfs.FS {
return h.fs
}
// WatchesFile reports whether any registered file watcher would match the given
// file path. It handles both absolute glob patterns and relative patterns with
// a base URI. On case-insensitive file systems the paths in glob patterns are
// lowercased, so callers should pass the lowercased path.
func (h *SessionUtils) WatchesFile(filePath string) bool {
for _, call := range h.client.WatchFilesCalls() {
for _, watcher := range call.Watchers {
if watcher.GlobPattern.Pattern != nil {
if g, err := glob.Parse(*watcher.GlobPattern.Pattern); err == nil && g.Match(filePath) {
return true
}
} else if watcher.GlobPattern.RelativePattern != nil {
rp := watcher.GlobPattern.RelativePattern
baseUri := string(*rp.BaseUri.URI)
// Convert base URI (e.g. "file:///home/projects") to a directory path
// with trailing separator for proper prefix matching on path boundaries.
baseDir := lsproto.DocumentUri(baseUri).FileName()
baseDir = tspath.EnsureTrailingDirectorySeparator(baseDir)
if strings.HasPrefix(filePath, baseDir) {
relativePath := filePath[len(baseDir):]
if g, err := glob.Parse(rp.Pattern); err == nil && g.Match(relativePath) {
return true
}
}
}
}
}
return false
}
func (h *SessionUtils) Logs() string {
return h.logger.String()
}
func (h *SessionUtils) BaselineLogs(t *testing.T) {
baseline.Run(t, t.Name()+".log", h.Logs(), baseline.Options{
Subfolder: "project",
})
}
var (
typesRegistryConfigTextOnce sync.Once
typesRegistryConfigText string
)
func TypesRegistryConfigText() string {
typesRegistryConfigTextOnce.Do(func() {
var result strings.Builder
for key, value := range TypesRegistryConfig() {
if result.Len() != 0 {
result.WriteString(",")
}
result.WriteString(fmt.Sprintf("\n \"%s\": \"%s\"", key, value))
}
typesRegistryConfigText = result.String()
})
return typesRegistryConfigText
}
var (
typesRegistryConfigOnce sync.Once
typesRegistryConfig map[string]string
)
func TypesRegistryConfig() map[string]string {
typesRegistryConfigOnce.Do(func() {
typesRegistryConfig = map[string]string{
"latest": "1.3.0",
"ts2.0": "1.0.0",
"ts2.1": "1.0.0",
"ts2.2": "1.2.0",
"ts2.3": "1.3.0",
"ts2.4": "1.3.0",
"ts2.5": "1.3.0",
"ts2.6": "1.3.0",
"ts2.7": "1.3.0",
}
})
return typesRegistryConfig
}
func (h *SessionUtils) createTypesRegistryFileContent() string {
var builder strings.Builder
builder.WriteString("{\n \"entries\": {")
for index, entry := range h.tiOptions.TypesRegistry {
h.appendTypesRegistryConfig(&builder, index, entry)
}
index := len(h.tiOptions.TypesRegistry)
for key := range h.tiOptions.PackageToFile {
if !slices.Contains(h.tiOptions.TypesRegistry, key) {
h.appendTypesRegistryConfig(&builder, index, key)
index++
}
}
builder.WriteString("\n }\n}")
return builder.String()
}
func (h *SessionUtils) appendTypesRegistryConfig(builder *strings.Builder, index int, entry string) {
if index > 0 {
builder.WriteString(",")
}
builder.WriteString(fmt.Sprintf("\n \"%s\": {%s\n }", entry, TypesRegistryConfigText()))
}
func Setup(files map[string]any) (*project.Session, *SessionUtils) {
return SetupWithTypingsInstaller(files, &TypingsInstallerOptions{})
}
func SetupWithRealFS() (*project.Session, *SessionUtils) {
fs := bundled.WrapFS(osvfs.FS())
clientMock := &ClientMock{}
npmExecutorMock := &NpmExecutorMock{}
wd, err := os.Getwd()
if err != nil {
panic(err)
}
sessionUtils := &SessionUtils{
currentDirectory: wd,
fs: fs,
client: clientMock,
npmExecutor: npmExecutorMock,
logger: logging.NewTestLogger(),
}
return project.NewSession(&project.SessionInit{
BackgroundCtx: context.Background(),
FS: fs,
Client: clientMock,
NpmExecutor: npmExecutorMock,
Logger: sessionUtils.logger,
Options: &project.SessionOptions{
CurrentDirectory: wd,
DefaultLibraryPath: bundled.LibPath(),
PositionEncoding: lsproto.PositionEncodingKindUTF8,
WatchEnabled: true,
LoggingEnabled: true,
PushDiagnosticsEnabled: true,
},
}), sessionUtils
}
func SetupWithOptions(files map[string]any, options *project.SessionOptions) (*project.Session, *SessionUtils) {
return SetupWithOptionsAndTypingsInstaller(files, options, &TypingsInstallerOptions{})
}
func SetupWithTypingsInstaller(files map[string]any, tiOptions *TypingsInstallerOptions) (*project.Session, *SessionUtils) {
return SetupWithOptionsAndTypingsInstaller(files, nil, tiOptions)
}
func SetupWithOptionsAndTypingsInstaller(files map[string]any, options *project.SessionOptions, tiOptions *TypingsInstallerOptions) (*project.Session, *SessionUtils) {
init, sessionUtils := GetSessionInitOptions(files, options, tiOptions)
session := project.NewSession(init)
return session, sessionUtils
}
func WithRequestID(ctx context.Context) context.Context {
return core.WithRequestID(ctx, "0")
}
func GetSessionInitOptions(files map[string]any, options *project.SessionOptions, tiOptions *TypingsInstallerOptions) (*project.SessionInit, *SessionUtils) {
fsFromFileMap := vfstest.FromMap(files, false /*useCaseSensitiveFileNames*/)
fs := bundled.WrapFS(fsFromFileMap)
clientMock := &ClientMock{}
npmExecutorMock := &NpmExecutorMock{}
sessionUtils := &SessionUtils{
currentDirectory: "/",
fsFromFileMap: fsFromFileMap.(iovfs.FsWithSys),
fs: fs,
client: clientMock,
npmExecutor: npmExecutorMock,
tiOptions: tiOptions,
logger: logging.NewTestLogger(),
}
// Configure the npm executor mock to handle typings installation
sessionUtils.SetupNpmExecutorForTypingsInstaller()
// Use provided options or create default ones
if options == nil {
options = &project.SessionOptions{
CurrentDirectory: "/",
DefaultLibraryPath: bundled.LibPath(),
TypingsLocation: TestTypingsLocation,
PositionEncoding: lsproto.PositionEncodingKindUTF8,
WatchEnabled: true,
LoggingEnabled: true,
PushDiagnosticsEnabled: true,
}
}
return &project.SessionInit{
BackgroundCtx: context.Background(),
Options: options,
FS: fs,
Client: clientMock,
NpmExecutor: npmExecutorMock,
Logger: sessionUtils.logger,
}, sessionUtils
}